Programs & Examples On #Snowflake schema

How to find lines containing a string in linux

Write the queue job information in long format to text file

qstat -f > queue.txt

Grep job names

grep 'Job_Name' queue.txt

How to unstage large number of files without deleting the content

If you want to unstage all the changes use below command,

git reset --soft HEAD

In the case you want to unstage changes and revert them from the working directory,

git reset --hard HEAD

Visual Studio 2010 shortcut to find classes and methods?

Left click on a method and press the F12 key to Go To Definition. Other Actions also available

Find the max of two or more columns with pandas

You can get the maximum like this:

>>> import pandas as pd
>>> df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
>>> df
   A  B
0  1 -2
1  2  8
2  3  1
>>> df[["A", "B"]]
   A  B
0  1 -2
1  2  8
2  3  1
>>> df[["A", "B"]].max(axis=1)
0    1
1    8
2    3

and so:

>>> df["C"] = df[["A", "B"]].max(axis=1)
>>> df
   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3

If you know that "A" and "B" are the only columns, you could even get away with

>>> df["C"] = df.max(axis=1)

And you could use .apply(max, axis=1) too, I guess.

What causes javac to issue the "uses unchecked or unsafe operations" warning

If you do what it suggests and recompile with the "-Xlint:unchecked" switch, it will give you more detailed information.

As well as the use of raw types (as described by the other answers), an unchecked cast can also cause the warning.

Once you've compiled with -Xlint, you should be able to rework your code to avoid the warning. This is not always possible, particularly if you are integrating with legacy code that cannot be changed. In this situation, you may decide to suppress the warning in places where you know that the code is correct:

@SuppressWarnings("unchecked")
public void myMethod()
{
    //...
}

How to load external scripts dynamically in Angular?

You can use following technique to dynamically load JS scripts and libraries on demand in your Angular project.

script.store.ts will contain the path of the script either locally or on a remote server and a name that will be used to load the script dynamically

 interface Scripts {
    name: string;
    src: string;
}  
export const ScriptStore: Scripts[] = [
    {name: 'filepicker', src: 'https://api.filestackapi.com/filestack.js'},
    {name: 'rangeSlider', src: '../../../assets/js/ion.rangeSlider.min.js'}
];

script.service.ts is an injectable service that will handle the loading of script, copy script.service.ts as it is

import {Injectable} from "@angular/core";
import {ScriptStore} from "./script.store";

declare var document: any;

@Injectable()
export class ScriptService {

private scripts: any = {};

constructor() {
    ScriptStore.forEach((script: any) => {
        this.scripts[script.name] = {
            loaded: false,
            src: script.src
        };
    });
}

load(...scripts: string[]) {
    var promises: any[] = [];
    scripts.forEach((script) => promises.push(this.loadScript(script)));
    return Promise.all(promises);
}

loadScript(name: string) {
    return new Promise((resolve, reject) => {
        //resolve if already loaded
        if (this.scripts[name].loaded) {
            resolve({script: name, loaded: true, status: 'Already Loaded'});
        }
        else {
            //load script
            let script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = this.scripts[name].src;
            if (script.readyState) {  //IE
                script.onreadystatechange = () => {
                    if (script.readyState === "loaded" || script.readyState === "complete") {
                        script.onreadystatechange = null;
                        this.scripts[name].loaded = true;
                        resolve({script: name, loaded: true, status: 'Loaded'});
                    }
                };
            } else {  //Others
                script.onload = () => {
                    this.scripts[name].loaded = true;
                    resolve({script: name, loaded: true, status: 'Loaded'});
                };
            }
            script.onerror = (error: any) => resolve({script: name, loaded: false, status: 'Loaded'});
            document.getElementsByTagName('head')[0].appendChild(script);
        }
    });
}

}

Inject this ScriptService wherever you need it and load js libs like this

this.script.load('filepicker', 'rangeSlider').then(data => {
    console.log('script loaded ', data);
}).catch(error => console.log(error));

How to compare two dates along with time in java

Use compareTo()

Return Values

0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.

Like

if(date1.compareTo(date2)>0) 

cannot resolve symbol javafx.application in IntelliJ Idea IDE

You might have a lower project language level than your JDK.

Check if: "Projeckt structure/project/Project-> language level" is lower than your JDK. I had the same problem with JDK 9 and the language level was per default set to 6.

I set the Project Language Level to 9 and everything worked fine after that.

You might have the same issue.

sh: 0: getcwd() failed: No such file or directory on cited drive

This error is usually caused by running a command from a directory that no longer exist.

Try changing your directory and re-run the command.

Oracle : how to subtract two dates and get minutes of the result

When you subtract two dates in Oracle, you get the number of days between the two values. So you just have to multiply to get the result in minutes instead:

SELECT (date2 - date1) * 24 * 60 AS minutesBetween
FROM ...

What is the equivalent of bigint in C#?

I just had a script that returned the primary key of an insert and used a

SELECT @@identity

on my bigint primary key, and I get a cast error using long - that was why I started this search. The correct answer, at least in my case, is that the type returned by that select is NUMERIC which equates to a decimal type. Using a long will cause a cast exception.

This is one reason to check your answers in more than one Google search (or even on Stack Overflow!).

To quote a database administrator who helped me out:

... BigInt is not the same as INT64 no matter how much they look alike. Part of the reason is that SQL will frequently convert Int/BigInt to Numeric as part of the normal processing. So when it goes to OLE or .NET the required conversion is NUMERIC to INT.

We don't often notice since the printed value looks the same.

How to install multiple python packages at once using pip

pip install -r requirements.txt

and in the requirements.txt file you put your modules in a list, with one item per line.

  • Django=1.3.1

  • South>=0.7

  • django-debug-toolbar

Find out where MySQL is installed on Mac OS X

for me it was installed in /usr/local/opt

The command I used for installation is brew install [email protected]

What is in your .vimrc?

set guifont=FreeMono\ 12

colorscheme default

set nocompatible
set backspace=indent,eol,start
set nobackup "do not keep a backup file, use versions instead
set history=10000 "keep 10000 lines of command line history
set ruler "show the cursor position all the time
set showcmd "display incomplete commands
set showmode
set showmatch
set nojoinspaces "do not insert a space, when joining lines
set whichwrap="" "do not jump to the next line when deleting
"set nowrap
filetype plugin indent on
syntax enable
set hlsearch
set incsearch "do incremental searching
set autoindent
set noexpandtab
set tabstop=4
set shiftwidth=4
set number
set laststatus=2
set visualbell "do not beep
set tabpagemax=100
set statusline=%F\ %h%m%r%=%l/%L\ \(%-03p%%\)\ %-03c\ 

"use listmode to make tabs visible and make them gray so they are not
"disctrating too much
set listchars=tab:»\ ,eol:¬,trail:.
highlight NonText ctermfg=gray guifg=gray
highlight SpecialKey ctermfg=gray guifg=gray
highlight clear MatchParen
highlight MatchParen cterm=bold
set list


match Todo /@todo/ "highlight doxygen todos


"different tabbing settings for different file types
if has("autocmd")
    autocmd FileType c setlocal tabstop=4 softtabstop=4 shiftwidth=4 expandtab
    autocmd FileType cpp setlocal tabstop=4 softtabstop=4 shiftwidth=4 expandtab
    autocmd FileType go setlocal tabstop=4 softtabstop=4 shiftwidth=4 noexpandtab
    autocmd FileType make setlocal tabstop=4 softtabstop=4 shiftwidth=4 noexpandtab
    autocmd FileType python setlocal tabstop=4 softtabstop=4 shiftwidth=4 noexpandtab

    " doesnt work properly -- revise me
    autocmd CursorMoved * call RonnyHighlightWordUnderCursor()
    autocmd CursorMovedI * call RonnyHighlightWordUnderCursor()

    "jump to the end of the file if it is a logfile
    autocmd BufReadPost *.log normal G

    autocmd BufRead,BufNewFile *.go set filetype=go
endif


highlight Search ctermfg=white ctermbg=gray
highlight IncSearch ctermfg=white ctermbg=gray
highlight RonnyWordUnderCursorHighlight cterm=bold


function! RonnyHighlightWordUnderCursor()
python << endpython
import vim

# get the character under the cursor
row, col = vim.current.window.cursor
characterUnderCursor = ''
try:
    characterUnderCursor = vim.current.buffer[row-1][col]
except:
    pass

# remove last search
vim.command("match RonnyWordUnderCursorHighlight //")

# if the cursor is currently located on a real word, move on and highlight it
if characterUnderCursor.isalpha() or characterUnderCursor.isdigit() or characterUnderCursor is '_':

    # expand cword to get the word under the cursor
    wordUnderCursor = vim.eval("expand(\'<cword>\')")
    if wordUnderCursor is None :
        wordUnderCursor = ""

    # escape the word
    wordUnderCursor = vim.eval("RonnyEscapeString(\"" + wordUnderCursor + "\")")
    wordUnderCursor = "\<" + wordUnderCursor + "\>"

    currentSearch = vim.eval("@/")

    if currentSearch != wordUnderCursor :
        # highlight it, if it is not the currently searched word
        vim.command("match RonnyWordUnderCursorHighlight /" + wordUnderCursor + "/")

endpython
endfunction


function! RonnyEscapeString(s)
python << endpython
import vim

s = vim.eval("a:s")

escapeMap = {
    '"'     : '\\"',
    "'"     : '\\''',
    "*"     : '\\*',
    "/"     : '\\/',
    #'' : ''
}

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

for before, after in escapeMap.items() :
    s = s.replace(before, after)

vim.command("return \'" + s + "\'")
endpython
endfunction

JavaScript equivalent of PHP's in_array()

With Dojo Toolkit, you would use dojo.indexOf(). See dojo.indexOf for the documentation, and Arrays Made Easy by Bryan Forbes for some examples.

Trigger to fire only if a condition is met in SQL Server

Your where clause should have worked. I am at a loss as to why it didn't. Let me show you how I would have figured out the problem with the where clause as it might help you for the future.

When I create triggers, I start at the query window by creating a temp table called #inserted (and or #deleted) with all the columns of the table. Then I popultae it with typical values (Always multiple records and I try to hit the test cases in the values)

Then I write my triggers logic and I can test without it actually being in a trigger. In a case like your where clause not doing what was expected, I could easily test by commenting out the insert to see what the select was returning. I would then probably be easily able to see what the problem was. I assure you that where clasues do work in triggers if they are written correctly.

Once I know that the code works properly for all the cases, I global replace #inserted with inserted and add the create trigger code around it and voila, a tested trigger.

AS I said in a comment, I have a concern that the solution you picked will not work properly in a multiple record insert or update. Triggers should always be written to account for that as you cannot predict if and when they will happen (and they do happen eventually to pretty much every table.)

how to use a like with a join in sql?

When writing queries with our server LIKE or INSTR (or CHARINDEX in T-SQL) takes too long, so we use LEFT like in the following structure:

select *
from little
left join big
on left( big.key, len(little.key) ) = little.key

I understand that might only work with varying endings to the query, unlike other suggestions with '%' + b + '%', but is enough and much faster if you only need b+'%'.

Another way to optimize it for speed (but not memory) is to create a column in "little" that is "len(little.key)" as "lenkey" and user that instead in the query above.

Bootstrap carousel multiple frames at once

Natively it is overly complicated and messy to achieve this just with Bootstrap 3.4 Carousel and Bootstrap 4.5 Carousel javascript component features.

OK so you do not want yet another jQuery plugin... I get that.

In my opinion if you're already forced to use jQuery in your project, you might as well have a decent jQuery carousel plugin with lots powerful options.

slick.js - the last carousel you'll ever need - Ken Wheeler

         _ _      _       _
     ___| (_) ___| | __  (_)___
    / __| | |/ __| |/ /  | / __|
    \__ \ | | (__|   < _ | \__ \
    |___/_|_|\___|_|\_(_)/ |___/
                       |__/

It truly is the last jQuery carousel plugin you will ever need.


Here are minified slick.js distribution sizes...


Some scenarios you may be faced with...

  • Unfortunately if you are just pulling distributed Bootstrap 3 or 4 js and css minified files from a CDN or where ever, then yeah it's another bulky jQuery plugin added to your website network requests.
  • If you are using NPM, Gulp, Bower or whatever you can just exclude the carousel.js and carousel.scss to reduce the final compiled sizes of your css and js. Excluding all unused Bootstrap js and scss vendors will help reduced your final compiled outputs anyway.

Added bonuses using slick.js...

  • Touch/swipe to scroll carousel on devices (you can drag on desktop too)
  • Define carousel options for each responsive breakpoint
  • Set mobileFirst: true or false to handle responsive breakpoint direction
  • Set how many slides (columns) you wish to show or scroll (define for each breakpoint)
  • Vertical and horizontal carousels
  • .on events for everything
  • Loads of options



Bootstrap 3 multi column slick carousel example

See codepen links below to test examples responsively...

_x000D_
_x000D_
// bootstrap 3 breakpoints 
const breakpoint = {
  // extra small screen / phone
  xs: 480,
  // small screen / tablet
  sm: 768,
  // medium screen / desktop
  md: 992,
  // large screen / large desktop
  lg: 1200
};

// bootstrap 3 responsive multi column slick carousel
$('#slick').slick({
  autoplay: true,
  autoplaySpeed: 2000,
  draggable: true,
  pauseOnHover: false,
  infinite: true,
  dots: false,
  arrows: false,
  speed: 1000,
  
  mobileFirst: true,
  
  slidesToShow: 1,
  slidesToScroll: 1,
  
  responsive: [{
      breakpoint: breakpoint.xs,
      settings: {
        slidesToShow: 2,
        slidesToScroll: 2
      }
    },
    {
      breakpoint: breakpoint.sm,
      settings: {
        slidesToShow: 3,
        slidesToScroll: 3
      }
    },
    {
      breakpoint: breakpoint.md,
      settings: {
        slidesToShow: 4,
        slidesToScroll: 4
      }
    },
    {
      breakpoint: breakpoint.lg,
      settings: {
        slidesToShow: 5,
        slidesToScroll: 5
      }
    }
  ]
});
_x000D_
/* .slick-list emulates .row */
#slick .slick-list {
  margin-left: -15px;
  margin-right: -15px;
}

/* .slick-slide emulates .col- */
#slick .slick-slide {
  padding-right: 15px;
  padding-left: 15px;
}

#slick .slick-slide:focus {
  outline: none;
}
_x000D_
<!-- jquery 3.3 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- bootstrap 3.4 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>

<!-- slick 1.9 -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.9.0/slick.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.9.0/slick.min.js"></script>

<!-- bootstrap 3 responsive multi column slick carousel example -->

<header>
  <nav class="navbar navbar-inverse navbar-static-top">
    <div class="navbar-header" style="float:left!important;">
      <a class="navbar-brand" href="#">Slick in Bootstrap 3</a>
    </div>
    <div class="navbar-text pull-right" style="margin:15px!important;">
      <a class="navbar-link" href="http://kenwheeler.github.io/slick/" target="_blank">Slick Github</a>
    </div>
  </nav>
</header>

<main>
  <div class="container">
    <div id="slick">

      <div class="slide">
        <div class="panel panel-default">
          <img src="https://via.placeholder.com/1600x900" class="img-responsive" />
          <div class="panel-body">
            <h3 style="margin-top:0;">Article title</h3>
            <p>Ut sed ligula vel felis vulputate lobortis id eget mauris. Nullam sollicitudin arcu ac diam ornare, eget iaculis nisl accumsan.</p>
            <button class="btn btn-primary">View article</button>
          </div>
        </div>
      </div>

      <div class="slide">
        <div class="panel panel-default">
          <img src="https://via.placeholder.com/1600x900" class="img-responsive" />
          <div class="panel-body">
            <h3 style="margin-top:0;">Article title</h3>
            <p>Ut sed ligula vel felis vulputate lobortis id eget mauris. Nullam sollicitudin arcu ac diam ornare, eget iaculis nisl accumsan.</p>
            <button class="btn btn-primary">View article</button>
          </div>
        </div>
      </div>

      <div class="slide">
        <div class="panel panel-default">
          <img src="https://via.placeholder.com/1600x900" class="img-responsive" />
          <div class="panel-body">
            <h3 style="margin-top:0;">Article title</h3>
            <p>Ut sed ligula vel felis vulputate lobortis id eget mauris. Nullam sollicitudin arcu ac diam ornare, eget iaculis nisl accumsan.</p>
            <button class="btn btn-primary">View article</button>
          </div>
        </div>
      </div>

      <div class="slide">
        <div class="panel panel-default">
          <img src="https://via.placeholder.com/1600x900" class="img-responsive" />
          <div class="panel-body">
            <h3 style="margin-top:0;">Article title</h3>
            <p>Ut sed ligula vel felis vulputate lobortis id eget mauris. Nullam sollicitudin arcu ac diam ornare, eget iaculis nisl accumsan.</p>
            <button class="btn btn-primary">View article</button>
          </div>
        </div>
      </div>

      <div class="slide">
        <div class="panel panel-default">
          <img src="https://via.placeholder.com/1600x900" class="img-responsive" />
          <div class="panel-body">
            <h3 style="margin-top:0;">Article title</h3>
            <p>Ut sed ligula vel felis vulputate lobortis id eget mauris. Nullam sollicitudin arcu ac diam ornare, eget iaculis nisl accumsan.</p>
            <button class="btn btn-primary">View article</button>
          </div>
        </div>
      </div>

      <div class="slide">
        <div class="panel panel-default">
          <img src="https://via.placeholder.com/1600x900" class="img-responsive" />
          <div class="panel-body">
            <h3 style="margin-top:0;">Article title</h3>
            <p>Ut sed ligula vel felis vulputate lobortis id eget mauris. Nullam sollicitudin arcu ac diam ornare, eget iaculis nisl accumsan.</p>
            <button class="btn btn-primary">View article</button>
          </div>
        </div>
      </div>
      
      <div class="slide">
        <div class="panel panel-default">
          <img src="https://via.placeholder.com/1600x900" class="img-responsive" />
          <div class="panel-body">
            <h3 style="margin-top:0;">Article title</h3>
            <p>Ut sed ligula vel felis vulputate lobortis id eget mauris. Nullam sollicitudin arcu ac diam ornare, eget iaculis nisl accumsan.</p>
            <button class="btn btn-primary">View article</button>
          </div>
        </div>
      </div>

      <div class="slide">
        <div class="panel panel-default">
          <img src="https://via.placeholder.com/1600x900" class="img-responsive" />
          <div class="panel-body">
            <h3 style="margin-top:0;">Article title</h3>
            <p>Ut sed ligula vel felis vulputate lobortis id eget mauris. Nullam sollicitudin arcu ac diam ornare, eget iaculis nisl accumsan.</p>
            <button class="btn btn-primary">View article</button>
          </div>
        </div>
      </div>

      <div class="slide">
        <div class="panel panel-default">
          <img src="https://via.placeholder.com/1600x900" class="img-responsive" />
          <div class="panel-body">
            <h3 style="margin-top:0;">Article title</h3>
            <p>Ut sed ligula vel felis vulputate lobortis id eget mauris. Nullam sollicitudin arcu ac diam ornare, eget iaculis nisl accumsan.</p>
            <button class="btn btn-primary">View article</button>
          </div>
        </div>
      </div>

      <div class="slide">
        <div class="panel panel-default">
          <img src="https://via.placeholder.com/1600x900" class="img-responsive" />
          <div class="panel-body">
            <h3 style="margin-top:0;">Article title</h3>
            <p>Ut sed ligula vel felis vulputate lobortis id eget mauris. Nullam sollicitudin arcu ac diam ornare, eget iaculis nisl accumsan.</p>
            <button class="btn btn-primary">View article</button>
          </div>
        </div>
      </div>

    </div>
  </div>
</main>
_x000D_
_x000D_
_x000D_


Bootstrap 4 multi column slick carousel example

See codepen links below to test example responsively...

_x000D_
_x000D_
// bootstrap 4 breakpoints
const breakpoint = {
  // small screen / phone
  sm: 576,
  // medium screen / tablet
  md: 768,
  // large screen / desktop
  lg: 992,
  // extra large screen / wide desktop
  xl: 1200
};

// bootstrap 4 responsive multi column slick carousel
$('#slick').slick({
  autoplay: true,
  autoplaySpeed: 2000,
  draggable: true,
  pauseOnHover: false,
  infinite: true,
  dots: false,
  arrows: false,
  speed: 1000,
  
  mobileFirst: true,
  
  slidesToShow: 1,
  slidesToScroll: 1,
  
  responsive: [{
      breakpoint: breakpoint.sm,
      settings: {
        slidesToShow: 2,
        slidesToScroll: 2
      }
    },
    {
      breakpoint: breakpoint.md,
      settings: {
        slidesToShow: 3,
        slidesToScroll: 3
      }
    },
    {
      breakpoint: breakpoint.lg,
      settings: {
        slidesToShow: 4,
        slidesToScroll: 4
      }
    },
    {
      breakpoint: breakpoint.xl,
      settings: {
        slidesToShow: 5,
        slidesToScroll: 5
      }
    }
  ]
});
_x000D_
/* .slick-list emulates .row */
#slick .slick-list {
  margin-left: -15px;
  margin-right: -15px;
}

/* .slick-slide emulates .col- */
#slick .slick-slide {
  padding-right: 15px;
  padding-left: 15px;
}

#slick .slick-slide:focus {
  outline: none;
}
_x000D_
<!-- jquery 3.5 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<!-- bootstrap 4.5 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>

<!-- slick 1.9 -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.9.0/slick.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.9.0/slick.min.js"></script>

<!-- bootstrap 4 responsive multi column slick carousel example -->
    
<header>
  <nav class="navbar navbar-expand-md navbar-dark bg-dark">
    <a class="navbar-brand mr-auto" href="#">Slick in Bootstrap 4</a>
    <a class="nav-link d-none d-sm-inline" href="http://kenwheeler.github.io/slick/" target="_blank">Slick Github</a>
  </nav>
</header>

<main class="py-4">
  <div class="container">
    <div id="slick">

      <div class="slide">
        <div class="card">
          <img src="https://via.placeholder.com/1600x900" class="card-img-top" />
          <div class="card-body">
            <h5 class="card-title">Article title</h5>
            <p class="card-text">Ut sed ligula vel felis vulputate lobortis id eget mauris. Nullam sollicitudin arcu ac diam ornare, eget iaculis nisl accumsan.</p>
            <button class="btn btn-primary">View article</button>
          </div>
        </div>
      </div>

      <div class="slide">
        <div class="card">
          <img src="https://via.placeholder.com/1600x900" class="card-img-top" />
          <div class="card-body">
            <h5 class="card-title">Article title</h5>
            <p class="card-text">Ut sed ligula vel felis vulputate lobortis id eget mauris. Nullam sollicitudin arcu ac diam ornare, eget iaculis nisl accumsan.</p>
            <button class="btn btn-primary">View article</button>
          </div>
        </div>
      </div>

      <div class="slide">
        <div class="card">
          <img src="https://via.placeholder.com/1600x900" class="card-img-top" />
          <div class="card-body">
            <h5 class="card-title">Article title</h5>
            <p class="card-text">Ut sed ligula vel felis vulputate lobortis id eget mauris. Nullam sollicitudin arcu ac diam ornare, eget iaculis nisl accumsan.</p>
            <button class="btn btn-primary">View article</button>
          </div>
        </div>
      </div>

      <div class="slide">
        <div class="card">
          <img src="https://via.placeholder.com/1600x900" class="card-img-top" />
          <div class="card-body">
            <h5 class="card-title">Article title</h5>
            <p class="card-text">Ut sed ligula vel felis vulputate lobortis id eget mauris. Nullam sollicitudin arcu ac diam ornare, eget iaculis nisl accumsan.</p>
            <button class="btn btn-primary">View article</button>
          </div>
        </div>
      </div>

      <div class="slide">
        <div class="card">
          <img src="https://via.placeholder.com/1600x900" class="card-img-top" />
          <div class="card-body">
            <h5 class="card-title">Article title</h5>
            <p class="card-text">Ut sed ligula vel felis vulputate lobortis id eget mauris. Nullam sollicitudin arcu ac diam ornare, eget iaculis nisl accumsan.</p>
            <button class="btn btn-primary">View article</button>
          </div>
        </div>
      </div>

      <div class="slide">
        <div class="card">
          <img src="https://via.placeholder.com/1600x900" class="card-img-top" />
          <div class="card-body">
            <h5 class="card-title">Article title</h5>
            <p class="card-text">Ut sed ligula vel felis vulputate lobortis id eget mauris. Nullam sollicitudin arcu ac diam ornare, eget iaculis nisl accumsan.</p>
            <button class="btn btn-primary">View article</button>
          </div>
        </div>
      </div>
      
      <div class="slide">
        <div class="card">
          <img src="https://via.placeholder.com/1600x900" class="card-img-top" />
          <div class="card-body">
            <h5 class="card-title">Article title</h5>
            <p class="card-text">Ut sed ligula vel felis vulputate lobortis id eget mauris. Nullam sollicitudin arcu ac diam ornare, eget iaculis nisl accumsan.</p>
            <button class="btn btn-primary">View article</button>
          </div>
        </div>
      </div>

      <div class="slide">
        <div class="card">
          <img src="https://via.placeholder.com/1600x900" class="card-img-top" />
          <div class="card-body">
            <h5 class="card-title">Article title</h5>
            <p class="card-text">Ut sed ligula vel felis vulputate lobortis id eget mauris. Nullam sollicitudin arcu ac diam ornare, eget iaculis nisl accumsan.</p>
            <button class="btn btn-primary">View article</button>
          </div>
        </div>
      </div>

      <div class="slide">
        <div class="card">
          <img src="https://via.placeholder.com/1600x900" class="card-img-top" />
          <div class="card-body">
            <h5 class="card-title">Article title</h5>
            <p class="card-text">Ut sed ligula vel felis vulputate lobortis id eget mauris. Nullam sollicitudin arcu ac diam ornare, eget iaculis nisl accumsan.</p>
            <button class="btn btn-primary">View article</button>
          </div>
        </div>
      </div>

      <div class="slide">
        <div class="card">
          <img src="https://via.placeholder.com/1600x900" class="card-img-top" />
          <div class="card-body">
            <h5 class="card-title">Article title</h5>
            <p class="card-text">Ut sed ligula vel felis vulputate lobortis id eget mauris. Nullam sollicitudin arcu ac diam ornare, eget iaculis nisl accumsan.</p>
            <button class="btn btn-primary">View article</button>
          </div>
        </div>
      </div>

    </div>
  </div>
</main>
_x000D_
_x000D_
_x000D_

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

cast (field1 as decimal(53,8)
) field 1

The default is: decimal(18,0)

How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?

In my situation, the Visual Studio loads the DLLs in Global Assembly Cache (GAC), not the DLL in my project list. I deleted the DLLs in GAC and now I can see the break point working.

How to set "value" to input web element using selenium?

Use findElement instead of findElements

driver.findElement(By.xpath("//input[@id='invoice_supplier_id'])).sendKeys("your value");

OR

driver.findElement(By.id("invoice_supplier_id")).sendKeys("value", "your value");

OR using JavascriptExecutor

WebElement element = driver.findElement(By.xpath("enter the xpath here")); // you can use any locator
 JavascriptExecutor jse = (JavascriptExecutor)driver;
 jse.executeScript("arguments[0].value='enter the value here';", element);

OR

(JavascriptExecutor) driver.executeScript("document.evaluate(xpathExpresion, document, null, 9, null).singleNodeValue.innerHTML="+ DesiredText);

OR (in javascript)

driver.findElement(By.xpath("//input[@id='invoice_supplier_id'])).setAttribute("value", "your value")

Hope it will help you :)

How to convert number to words in java

I've developed a Java component to convert given number into words. All you've to do is - just copy the whole class from Java program to convert numbers to words and paste it in your project.

Just invoke it like below

Words w = Words.getInstance(1234567);
System.out.println(w.getNumberInWords());

My program supports up to 10 million. If you want, you can still extend this. Just below the example output

2345223 = Twenty Three Lakh Fourty Five Thousand Two Hundred Twenty Three
9999999 = Ninety Nine Lakh Ninety Nine Thousand Nine Hundred Ninety Nine
199 = One Hundred Ninety Nine
10 = Ten

Thanks

Santhosh

libz.so.1: cannot open shared object file

for centos, just zlib didn't solve the problem.I did sudo yum install zlib-devel.i686

Register DLL file on Windows Server 2008 R2

You need the full path to the regsvr32 so %windir$\system32\regsvr32 <*.dll>

What's the difference between SCSS and Sass?

The Sass .sass file is visually different from .scss file, e.g.

Example.sass - sass is the older syntax

$color: red

=my-border($color)
  border: 1px solid $color

body
  background: $color
  +my-border(green)

Example.scss - sassy css is the new syntax as of Sass 3

$color: red;

@mixin my-border($color) {
  border: 1px solid $color;
}

body {
  background: $color;
  @include my-border(green);
}

Any valid CSS document can be converted to Sassy CSS (SCSS) simply by changing the extension from .css to .scss.

GCC -fPIC option

Adding further...

Every process has same virtual address space (If randomization of virtual address is stopped by using a flag in linux OS) (For more details Disable and re-enable address space layout randomization only for myself)

So if its one exe with no shared linking (Hypothetical scenario), then we can always give same virtual address to same asm instruction without any harm.

But when we want to link shared object to the exe, then we are not sure of the start address assigned to shared object as it will depend upon the order the shared objects were linked.That being said, asm instruction inside .so will always have different virtual address depending upon the process its linking to.

So one process can give start address to .so as 0x45678910 in its own virtual space and other process at the same time can give start address of 0x12131415 and if they do not use relative addressing, .so will not work at all.

So they always have to use the relative addressing mode and hence fpic option.

SQL SELECT from multiple tables

SELECT `product`.*, `customer1`.`name1`, `customer2`.`name2`
FROM `product`
LEFT JOIN `customer1` ON `product`.`cid` = `customer1`.`cid`
LEFT JOIN `customer2` ON `product`.`cid` = `customer2`.`cid`

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block

You are catching the error but then you are re throwing it. You should try and handle it more gracefully, otherwise your user is going to see 500, internal server, errors.

You may want to send back a response telling the user what went wrong as well as logging the error on your server.

I am not sure exactly what errors the request might return, you may want to return something like.

router.get("/emailfetch", authCheck, async (req, res) => {
  try {
    let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
      emailFetch = emailFetch.data
      res.send(emailFetch)
   } catch(error) {
      res.status(error.response.status)
      return res.send(error.message);
    })

})

This code will need to be adapted to match the errors that you get from the axios call.

I have also converted the code to use the try and catch syntax since you are already using async.

How/when to generate Gradle wrapper files?

As gradle built-in tasks is deprecated in 4.8, try below

wrapper {
   gradleVersion = '2.0' //version required
}

and run

gradle wrapper

How do I initialize the base (super) class?

As of python 3.5.2, you can use:

class C(B):
def method(self, arg):
    super().method(arg)    # This does the same thing as:
                           # super(C, self).method(arg)

https://docs.python.org/3/library/functions.html#super

What are .tpl files? PHP, web design

Other possibilities for .tpl: HTML::SimpleTemplate, example:

Hello $name

, and Template Toolkit, example:

Hello [% world %]!

Bubble Sort Homework

Here is a different variation of bubble sort without for loop. Basically you are considering the lastIndex of the array and slowly decrementing it until it first index of the array.

The algorithm will continue to move through the array like this until an entire pass is made without any swaps occurring.

The bubble is sort is basically Quadratic Time: O(n²) when it comes to performance.

class BubbleSort: 
  def __init__(self, arr):
    self.arr = arr;

  def bubbleSort(self):
    count = 0;
    lastIndex = len(self.arr) - 1;
    
    while(count < lastIndex):
      if(self.arr[count] > self.arr[count + 1]):
        self.swap(count)  
      count = count + 1;

      if(count == lastIndex):
        count = 0;
        lastIndex = lastIndex - 1;   

  def swap(self, count):
    temp = self.arr[count];
    self.arr[count] = self.arr[count + 1];
    self.arr[count + 1] = temp;
    
arr = [9, 1, 5, 3, 8, 2]
p1 = BubbleSort(arr)

print(p1.bubbleSort())

Daylight saving time and time zone best practices

In dealing with databases (in particular MySQL, but this applies to most databases), I found it hard to store UTC.

  • Databases usually work with server datetime by default (that is, CURRENT_TIMESTAMP).
  • You may not be able to change the server timezone.
  • Even if you are able to change the timezone, you may have third-party code that expects server timezone to be local.

I found it easier to just store server datetime in the database, then let the database convert the stored datetime back to UTC (that is, UNIX_TIMESTAMP()) in the SQL statements. After that you can use the datetime as UTC in your code.

If you have 100% control over the server and all code, it's probably better to change server timezone to UTC.

Jackson Vs. Gson

I did this research the last week and I ended up with the same 2 libraries. As I'm using Spring 3 (that adopts Jackson in its default Json view 'JacksonJsonView') it was more natural for me to do the same. The 2 lib are pretty much the same... at the end they simply map to a json file! :)

Anyway as you said Jackson has a + in performance and that's very important for me. The project is also quite active as you can see from their web page and that's a very good sign as well.

How to gzip all files in all sub-directories into one compressed file in bash

tar -zcvf compressFileName.tar.gz folderToCompress

everything in folderToCompress will go to compressFileName

Edit: After review and comments I realized that people may get confused with compressFileName without an extension. If you want you can use .tar.gz extension(as suggested) with the compressFileName

How to delete a folder with files using Java

My basic recursive version, working with older versions of JDK:

public static void deleteFile(File element) {
    if (element.isDirectory()) {
        for (File sub : element.listFiles()) {
            deleteFile(sub);
        }
    }
    element.delete();
}

Show image using file_get_contents

Small edit to @seengee answer: In order to work, you need curly braces around the variable, otherwise you'll get an error.

header("Content-type: {$imginfo['mime']}");

Get table column names in MySQL?

I made a PDO function which returns all the column names in an simple array.

public function getColumnNames($table){
    $sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = :table";
    try {
        $core = Core::getInstance();
        $stmt = $core->dbh->prepare($sql);
        $stmt->bindValue(':table', $table, PDO::PARAM_STR);
        $stmt->execute();
        $output = array();
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            $output[] = $row['COLUMN_NAME'];                
        }
        return $output; 
    }

    catch(PDOException $pe) {
        trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
    }
}

The output will be an array:

Array (
[0] => id
[1] => name
[2] => email
[3] => shoe_size
[4] => likes
... )

Sorry for the necro but I like my function ;)

P.S. I have not included the class Core but you can use your own class.. D.S.

How to open a new form from another form

ok so I used this:

public partial class Form1 : Form
{
    private void Button_Click(object sender, EventArgs e)
    {
        Form2 myForm = new Form2();
        this.Hide();
        myForm.ShowDialog();
        this.Close();
    }
}

This seems to be working fine but the first form is just hidden and it can still generate events. the "this.Close()" is needed to close the first form but if you still want your form to run (and not act like a launcher) you MUST replace it with

this.Show();

Best of luck!

How to enable authentication on MongoDB through Docker?

use this images to fix:

With docker-compose.yml

services:
  db:
    image: aashreys/mongo-auth:latest
    environment:
      - AUTH=yes
      - MONGODB_ADMIN_USER=admin
      - MONGODB_ADMIN_PASS=admin123
      - MONGODB_APPLICATION_DATABASE=sample
      - MONGODB_APPLICATION_USER=aashrey
      - MONGODB_APPLICATION_PASS=admin123
    ports:
      - "27017:27017"
     // more configuration

How to get images in Bootstrap's card to be the same height/width?

I solved with these:

.card-img-top {
    max-height: 20vh; /*not want to take all vertical space*/
    object-fit: contain;/*show all image, autosized, no cut, in available space*/
}

How to compare two JSON have the same properties without order?

This code will verify the json independently of param object order.

_x000D_
_x000D_
var isEqualsJson = (obj1,obj2)=>{
    keys1 = Object.keys(obj1);
    keys2 = Object.keys(obj2);

    //return true when the two json has same length and all the properties has same value key by key
    return keys1.length === keys2.length && Object.keys(obj1).every(key=>obj1[key]==obj2[key]);
}

var obj1 = {a:1,b:2,c:3};
var obj2 = {a:1,b:2,c:3}; 

console.log("json is equals: "+ isEqualsJson(obj1,obj2));
alert("json is equals: "+ isEqualsJson(obj1,obj2));
_x000D_
_x000D_
_x000D_

Replace all non-alphanumeric characters in a string

Regex to the rescue!

import re

s = re.sub('[^0-9a-zA-Z]+', '*', s)

Example:

>>> re.sub('[^0-9a-zA-Z]+', '*', 'h^&ell`.,|o w]{+orld')
'h*ell*o*w*orld'

How to switch from POST to GET in PHP CURL

Add this before calling curl_exec($curl_handle)

curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'GET');

Error handling with try and catch in Laravel

You are inside a namespace so you should use \Exception to specify the global namespace:

try {

  $this->buildXMLHeader();

} catch (\Exception $e) {

    return $e->getMessage();
}

In your code you've used catch (Exception $e) so Exception is being searched in/as:

App\Services\PayUService\Exception

Since there is no Exception class inside App\Services\PayUService so it's not being triggered. Alternatively, you can use a use statement at the top of your class like use Exception; and then you can use catch (Exception $e).

Working with a List of Lists in Java

Here's an example that reads a list of CSV strings into a list of lists and then loops through that list of lists and prints the CSV strings back out to the console.

import java.util.ArrayList;
import java.util.List;

public class ListExample
{
    public static void main(final String[] args)
    {
        //sample CSV strings...pretend they came from a file
        String[] csvStrings = new String[] {
                "abc,def,ghi,jkl,mno",
                "pqr,stu,vwx,yz",
                "123,345,678,90"
        };

        List<List<String>> csvList = new ArrayList<List<String>>();

        //pretend you're looping through lines in a file here
        for(String line : csvStrings)
        {
            String[] linePieces = line.split(",");
            List<String> csvPieces = new ArrayList<String>(linePieces.length);
            for(String piece : linePieces)
            {
                csvPieces.add(piece);
            }
            csvList.add(csvPieces);
        }

        //write the CSV back out to the console
        for(List<String> csv : csvList)
        {
            //dumb logic to place the commas correctly
            if(!csv.isEmpty())
            {
                System.out.print(csv.get(0));
                for(int i=1; i < csv.size(); i++)
                {
                    System.out.print("," + csv.get(i));
                }
            }
            System.out.print("\n");
        }
    }
}

Pretty straightforward I think. Just a couple points to notice:

  1. I recommend using "List" instead of "ArrayList" on the left side when creating list objects. It's better to pass around the interface "List" because then if later you need to change to using something like Vector (e.g. you now need synchronized lists), you only need to change the line with the "new" statement. No matter what implementation of list you use, e.g. Vector or ArrayList, you still always just pass around List<String>.

  2. In the ArrayList constructor, you can leave the list empty and it will default to a certain size and then grow dynamically as needed. But if you know how big your list might be, you can sometimes save some performance. For instance, if you knew there were always going to be 500 lines in your file, then you could do:

List<List<String>> csvList = new ArrayList<List<String>>(500);

That way you would never waste processing time waiting for your list to grow dynamically grow. This is why I pass "linePieces.length" to the constructor. Not usually a big deal, but helpful sometimes.

Hope that helps!

Encode/Decode URLs in C++

Had to do it in a project without Boost. So, ended up writing my own. I will just put it on GitHub: https://github.com/corporateshark/LUrlParser

clParseURL URL = clParseURL::ParseURL( "https://name:[email protected]:80/path/res" );

if ( URL.IsValid() )
{
    cout << "Scheme    : " << URL.m_Scheme << endl;
    cout << "Host      : " << URL.m_Host << endl;
    cout << "Port      : " << URL.m_Port << endl;
    cout << "Path      : " << URL.m_Path << endl;
    cout << "Query     : " << URL.m_Query << endl;
    cout << "Fragment  : " << URL.m_Fragment << endl;
    cout << "User name : " << URL.m_UserName << endl;
    cout << "Password  : " << URL.m_Password << endl;
}

Better way to revert to a previous SVN revision of a file?

If you use the Eclipse IDE with the SVN plugin you can do as follows:

  1. Right-click the files that you want to revert (or the folder they were contained in, if you deleted them by mistake and you want to add them back)
  2. Select "Team > Switch"
  3. Choose the "Revision" radion button, and enter the revision number you'd like to revert to. Click OK
  4. Go to the Synchronize perspective
  5. Select all the files you want to revert
  6. Right-click on the selection and do "Override and Commit..."

This will revert the files to the revision that you want. Just keep in mind that SVN will see the changes as a new commit. That is, the change gets a new revision number, and there is no link between the old revision and the new one. You should specify in the commit comments that you are reverting those files to a specific revision.

Select <a> which href ends with some string

   $('a[href$="ABC"]')...

Selector documentation can be found at http://docs.jquery.com/Selectors

For attributes:

= is exactly equal
!= is not equal
^= is starts with
$= is ends with
*= is contains
~= is contains word
|= is starts with prefix (i.e., |= "prefix" matches "prefix-...")

How to install xgboost in Anaconda Python (Windows platform)?

GUYS ITS NOT THAT EASY:- PLEASE FOLLOW BELOW STEP TO GET TO MARK

So here's what I did to finish a 64-bit build on Windows:

Download and install MinGW-64: sourceforge.net /projects/mingw-w64/

On the first screen of the install prompt make sure you set the Architecture to x86_64 and the Threads to win32 I installed to C:\mingw64 (to avoid spaces in the file path) so I added this to my PATH environment variable: C:\ mingw64 \ mingw64 \ bin(Please remove spaces)

I also noticed that the make utility that is included in bin\mingw64 is called mingw32-make so to simplify things I just renamed this to make

Open a Windows command prompt and type gcc. You should see something like "fatal error: no input file"

Next type make. You should see something like "No targets specified and no makefile found"

Type git. If you don't have git, install it and add it to your PATH. These should be all the tools you need to build the xgboost project. To get the source code run these lines:

  • cd c:\
  • git clone --recursive https://github.com/dmlc/xgboost
  • cd xgboost
  • git submodule init
  • git submodule update
  • cp make/mingw64.mk config.mk
  • make -j4 Note that I ran this part from a Cygwin shell. If you are using the Windows command prompt you should be able to change cp to copy and arrive at the same result. However, if the build fails on you for any reason I would recommend trying again using cygwin.

If the build finishes successfully, you should have a file called xgboost.exe located in the project root. To install the Python package, do the following:

  • cd python-package
  • python setup.py install Now you should be good to go. Open up Python, and you can import the package with:

  • import xgboost as xgb To test the installation, I went ahead and ran the basic_walkthrough.py file that was included in the demo/guide-python folder of the project and didn't get any errors.

How can I display two div in one line via css inline property

use inline-block instead of inline. Read more information here about the difference between inline and inline-block.

.inline { 
display: inline-block; 
border: 1px solid red; 
margin:10px;
}

DEMO

Allow click on twitter bootstrap dropdown toggle link?

Here's a little hack that switched from data-hover to data-toggle depending the screen width:

/**
 * Bootstrap nav menu hack
 */
$(window).on('load', function () {
    // On page load
    if ($(window).width() < 768) {
        $('.navbar-nav > li > .dropdown-toggle').removeAttr('data-hover').attr('data-toggle', 'dropdown');
    }

    // On window resize
    $(window).resize(function () {
        if ($(window).width() < 768) {
            $('.navbar-nav > li > .dropdown-toggle').removeAttr('data-hover').attr('data-toggle', 'dropdown');
        } else {
            $('.navbar-nav > li > .dropdown-toggle').removeAttr('data-toggle').attr('data-hover', 'dropdown');
        }
    });
});

How do I resolve "Run-time error '429': ActiveX component can't create object"?

I got the same error but I solved by using regsvr32.exe in C:\Windows\SysWOW64. Because we use x64 system. So if your machine is also x64, the ocx/dll must registered also with regsvr32 x64 version

How to check if a column exists in Pandas

To check if one or more columns all exist, you can use set.issubset, as in:

if set(['A','C']).issubset(df.columns):
   df['sum'] = df['A'] + df['C']                

As @brianpck points out in a comment, set([]) can alternatively be constructed with curly braces,

if {'A', 'C'}.issubset(df.columns):

See this question for a discussion of the curly-braces syntax.

Or, you can use a list comprehension, as in:

if all([item in df.columns for item in ['A','C']]):

In Unix, how do you remove everything in the current directory and below it?

Practice safe computing. Simply go up one level in the hierarchy and don't use a wildcard expression:

cd ..; rm -rf -- <dir-to-remove>

The two dashes -- tell rm that <dir-to-remove> is not a command-line option, even when it begins with a dash.

UIButton: set image for selected-highlighted state

If you have a good reason to do that, this will do the trick

add these targets:

[button addTarget:self action:@selector(buttonTouchDown:) forControlEvents:UIControlEventTouchDown];
[button addTarget:self action:@selector(buttonTouchUp:) forControlEvents:UIControlEventTouchUpInside];


-(void)buttonTouchDown:(id)sender{
    UIButton *button=(UIButton *)sender;
    if(button.selected){
        [button setImage:[UIImage imageNamed:@"pressed.png"] forState:UIControlStateNormal];
    }
}

-(void)buttonTouchUp:(id)sender{
    UIButton *button=(UIButton *)sender;
    [button setImage:[UIImage imageNamed:@"normal.png"] forState:UIControlStateNormal];
}

How to make div same height as parent (displayed as table-cell)

You have to set the height for the parents (container and child) explicitly, here is another work-around (if you don't want to set that height explicitly):

.child {
  width: 30px;
  background-color: red;
  display: table-cell;
  vertical-align: top;
  position:relative;
}

.content {
  position:absolute;
  top:0;
  bottom:0;
  width:100%;
  background-color: blue;
}

Fiddle

What is $@ in Bash?

Yes. Please see the man page of bash ( the first thing you go to ) under Special Parameters

Special Parameters

The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed.

* Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equivalent to "$1c$2c...", where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.

@ Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" ... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).

How to get row count in an Excel file using POI library?

If you do a check

if
(getLastRowNum()<1){
 res="Sheet Cannot be empty";
return
}

This will make sure you have at least one row with data except header. Below is my program which works fine. Excel file has three columns ie. ID, NAME , LASTNAME

XSSFWorkbook workbook = new XSSFWorkbook(inputstream);
        XSSFSheet sheet = workbook.getSheetAt(0);
        Row header = sheet.getRow(0);
        int n = header.getLastCellNum();
        String header1 = header.getCell(0).getStringCellValue();
        String header2 = header.getCell(1).getStringCellValue();
        String header3 = header.getCell(2).getStringCellValue();
        if (header1.equals("ID") && header2.equals("NAME")
                && header3.equals("LASTNAME")) {
            if(sheet.getLastRowNum()<1){
                System.out.println("Sheet empty");
                         return;
            }   
                        iterate over sheet to get cell values
        }else{
                          SOP("invalid format");
                          return;
                          }

how to change the dist-folder path in angular-cli after 'ng build'

Another option would be to set the webroot path to the angular cli dist folder. In your Program.cs when configuring the WebHostBuilder just say

.UseWebRoot(Directory.GetCurrentDirectory() + "\\Frontend\\dist")

or whatever the path to your dist dir is.

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.6 or one of its dependencies could not be resolved

I had a similar problem in spring tool suite(sts). THE .m2 repository was not completely downloaded in the local system which is the reason why I was getting this error. So I reinstalled sts and deleted the old .m2 repository from the system and created a new maven project in sts which downloaded the complete .m2 repository. It worked for me.

How to drop columns by name in a data frame

You should use either indexing or the subset function. For example :

R> df <- data.frame(x=1:5, y=2:6, z=3:7, u=4:8)
R> df
  x y z u
1 1 2 3 4
2 2 3 4 5
3 3 4 5 6
4 4 5 6 7
5 5 6 7 8

Then you can use the which function and the - operator in column indexation :

R> df[ , -which(names(df) %in% c("z","u"))]
  x y
1 1 2
2 2 3
3 3 4
4 4 5
5 5 6

Or, much simpler, use the select argument of the subset function : you can then use the - operator directly on a vector of column names, and you can even omit the quotes around the names !

R> subset(df, select=-c(z,u))
  x y
1 1 2
2 2 3
3 3 4
4 4 5
5 5 6

Note that you can also select the columns you want instead of dropping the others :

R> df[ , c("x","y")]
  x y
1 1 2
2 2 3
3 3 4
4 4 5
5 5 6

R> subset(df, select=c(x,y))
  x y
1 1 2
2 2 3
3 3 4
4 4 5
5 5 6

OnClickListener in Android Studio

Button button= (Button) findViewById(R.id.standingsButton);
button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        startActivity(new Intent(MainActivity.this,StandingsActivity.class));
    }
});

This code is not in any method. If you want to use it, it must be within a method like OnCreate()

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button button= (Button) findViewById(R.id.standingsButton);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this,StandingsActivity.class));
        }
    });
}

Changing default shell in Linux

Try linux command chsh.

The detailed command is chsh -s /bin/bash. It will prompt you to enter your password. Your default login shell is /bin/bash now. You must log out and log back in to see this change.

The following is quoted from man page:

The chsh command changes the user login shell. This determines the name of the users initial login command. A normal user may only change the login shell for her own account, the superuser may change the login shell for any account

This command will change the default login shell permanently.

Note: If your user account is remote such as on Kerberos authentication (e.g. Enterprise RHEL) then you will not be able to use chsh.

Can't change table design in SQL Server 2008

Just go to the SQL Server Management Studio -> Tools -> Options -> Designer; and Uncheck the option "prevent saving changes that require table re-creation".

Android Notification Sound

// set notification audio (Tested upto android 10)

builder.setDefaults(Notification.DEFAULT_VIBRATE);
//OR 
builder.setDefaults(Notification.DEFAULT_SOUND);

How to restart Postgresql

This should work:

sudo systemctl stop postgresql

sudo systemctl start postgresql

FutureWarning: elementwise comparison failed; returning scalar, but in the future will perform elementwise comparison

I had this code which was causing the error:

for t in dfObj['time']:
  if type(t) == str:
    the_date = dateutil.parser.parse(t)
    loc_dt_int = int(the_date.timestamp())
    dfObj.loc[t == dfObj.time, 'time'] = loc_dt_int

I changed it to this:

for t in dfObj['time']:
  try:
    the_date = dateutil.parser.parse(t)
    loc_dt_int = int(the_date.timestamp())
    dfObj.loc[t == dfObj.time, 'time'] = loc_dt_int
  except Exception as e:
    print(e)
    continue

to avoid the comparison, which is throwing the warning - as stated above. I only had to avoid the exception because of dfObj.loc in the for loop, maybe there is a way to tell it not to check the rows it has already changed.

How to convert char to integer in C?

In the old days, when we could assume that most computers used ASCII, we would just do

int i = c[0] - '0';

But in these days of Unicode, it's not a good idea. It was never a good idea if your code had to run on a non-ASCII computer.

Edit: Although it looks hackish, evidently it is guaranteed by the standard to work. Thanks @Earwicker.

Serializing to JSON in jQuery

If you don't want to use external libraries there is .toSource() native JavaScript method, but it's not perfectly cross-browser.

Undo a git stash

git stash list to list your stashed changes.

git stash show to see what n is in the below commands.

git stash apply to apply the most recent stash.

git stash apply stash@{n} to apply an older stash.

https://git-scm.com/book/en/v2/Git-Tools-Stashing-and-Cleaning

How to install package from github repo in Yarn

For ssh style urls just add ssh before the url:

yarn add ssh://<whatever>@<xxx>#<branch,tag,commit>

Count number of occurences for each unique value

You can try also a tidyverse

library(tidyverse) 
dummyData %>% 
    as.tibble() %>% 
    count(value)
# A tibble: 2 x 2
  value     n
  <dbl> <int>
1     1    25
2     2    75

Trigger back-button functionality on button click in Android

If you are inside the fragment then you write the following line of code inside your on click listener, getActivity().onBackPressed(); this works perfectly for me.

Create a BufferedImage from file and make it TYPE_INT_ARGB

Create a BufferedImage from file and make it TYPE_INT_RGB

import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
public class Main{
    public static void main(String args[]){
        try{
            BufferedImage img = new BufferedImage( 
                500, 500, BufferedImage.TYPE_INT_RGB );
            File f = new File("MyFile.png");
            int r = 5;
            int g = 25; 
            int b = 255;
            int col = (r << 16) | (g << 8) | b;
            for(int x = 0; x < 500; x++){
                for(int y = 20; y < 300; y++){
                    img.setRGB(x, y, col);
                }
            }
            ImageIO.write(img, "PNG", f); 
        }
        catch(Exception e){ 
            e.printStackTrace();
        }
    }
}

This paints a big blue streak across the top.

If you want it ARGB, do it like this:

    try{
        BufferedImage img = new BufferedImage( 
            500, 500, BufferedImage.TYPE_INT_ARGB );
        File f = new File("MyFile.png");
        int r = 255;
        int g = 10;
        int b = 57;
        int alpha = 255;
        int col = (alpha << 24) | (r << 16) | (g << 8) | b;
        for(int x = 0; x < 500; x++){
            for(int y = 20; y < 30; y++){
                img.setRGB(x, y, col);
            }
        }
        ImageIO.write(img, "PNG", f);
    }
    catch(Exception e){
        e.printStackTrace();
    }

Open up MyFile.png, it has a red streak across the top.

Event on a disabled input

We had today a problem like this, but we didn't wanted to change the HTML. So we used mouseenter event to achieve that

var doThingsOnClick = function() {
    // your click function here
};

$(document).on({
    'mouseenter': function () {
        $(this).removeAttr('disabled').bind('click', doThingsOnClick);
    },
    'mouseleave': function () {
        $(this).unbind('click', doThingsOnClick).attr('disabled', 'disabled');
    },
}, 'input.disabled');

java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.encodeBase64String() in Java EE application

@Adam Augusta is right, One more thing

Apache-HTTP client jars also comes in same category as some google-apis.

org.apache.httpcomponents.httpclient_4.2.jar and commons-codec-1.4.jar both on classpath, This is very possible that you will get this problem.

This prove to all jars which are using early version of common-codec internally and at the same time someone using common-codec explicitly on classpath too.

RestTemplate: How to send URL and query parameters together

String url = "http://test.com/Services/rest/{id}/Identifier";
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1234");
URI uri = UriComponentsBuilder.fromUriString(url)
        .buildAndExpand(params)
        .toUri();
uri = UriComponentsBuilder
        .fromUri(uri)
        .queryParam("name", "myName")
        .build()
        .toUri();
restTemplate.exchange(uri , HttpMethod.PUT, requestEntity, class_p);

The safe way is to expand the path variables first, and then add the query parameters:

For me this resulted in duplicated encoding, e.g. a space was decoded to %2520 (space -> %20 -> %25).

I solved it by:

String url = "http://test.com/Services/rest/{id}/Identifier";
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1234");
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(url);
uriComponentsBuilder.uriVariables(params);
Uri uri = uriComponentsBuilder.queryParam("name", "myName");
        .build()
        .toUri();
restTemplate.exchange(uri , HttpMethod.PUT, requestEntity, class_p);

Essentially I am using uriComponentsBuilder.uriVariables(params); to add path parameters. The documentation says:

... In contrast to UriComponents.expand(Map) or buildAndExpand(Map), this method is useful when you need to supply URI variables without building the UriComponents instance just yet, or perhaps pre-expand some shared default values such as host and port. ...

Source: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/util/UriComponentsBuilder.html#uriVariables-java.util.Map-

Get Selected Item Using Checkbox in Listview

I had similar problem. Provided xml sample is put as single ListViewItem, and i couldn't click on Item itself, but checkbox was workng.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="50dp"
    android:id="@+id/source_container"
    >
    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:id="@+id/menu_source_icon"
        android:background="@drawable/bla"
        android:layout_margin="5dp"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/menu_source_name"
        android:text="Test"
        android:textScaleX="1.5"
        android:textSize="20dp"
        android:padding="8dp"
        android:layout_weight="1"
        android:layout_gravity="center_vertical"
        android:textColor="@color/source_text_color"/>
    <CheckBox
        android:layout_width="40dp"
        android:layout_height="match_parent"
        android:id="@+id/menu_source_check_box"/>

</LinearLayout>

Solution: add attribute

android:focusable="false"

to CheckBox control.

Difference between application/x-javascript and text/javascript content types

Use type="application/javascript"

In case of HTML5, the type attribute is obsolete, you may remove it. Note: that it defaults to "text/javascript" according to w3.org, so I would suggest to add the "application/javascript" instead of removing it.

http://www.w3.org/TR/html5/scripting-1.html#attr-script-type
The type attribute gives the language of the script or format of the data. If the attribute is present, its value must be a valid MIME type. The charset parameter must not be specified. The default, which is used if the attribute is absent, is "text/javascript".

Use "application/javascript", because "text/javascript" is obsolete:

RFC 4329: http://www.rfc-editor.org/rfc/rfc4329.txt

  1. Deployed Scripting Media Types and Compatibility

    Various unregistered media types have been used in an ad-hoc fashion to label and exchange programs written in ECMAScript and JavaScript. These include:

    +-----------------------------------------------------+ | text/javascript | text/ecmascript | | text/javascript1.0 | text/javascript1.1 | | text/javascript1.2 | text/javascript1.3 | | text/javascript1.4 | text/javascript1.5 | | text/jscript | text/livescript | | text/x-javascript | text/x-ecmascript | | application/x-javascript | application/x-ecmascript | | application/javascript | application/ecmascript | +-----------------------------------------------------+

Use of the "text" top-level type for this kind of content is known to be problematic. This document thus defines text/javascript and text/
ecmascript but marks them as "obsolete". Use of experimental and
unregistered media types, as listed in part above, is discouraged.
The media types,

  * application/javascript
  * application/ecmascript

which are also defined in this document, are intended for common use and should be used instead.

This document defines equivalent processing requirements for the
types text/javascript, text/ecmascript, and application/javascript.
Use of and support for the media type application/ecmascript is
considerably less widespread than for other media types defined in
this document. Using that to its advantage, this document defines
stricter processing rules for this type to foster more interoperable
processing.

x-javascript is experimental, don't use it.

Java check if boolean is null

A boolean cannot be null in java.

A Boolean, however, can be null.

If a boolean is not assigned a value (say a member of a class) then it will be false by default.

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

When to favor ng-if vs. ng-show/ng-hide?

ng-if on ng-include and on ng-controller will have a big impact matter on ng-include it will not load the required partial and does not process unless flag is true on ng-controller it will not load the controller unless flag is true but the problem is when a flag gets false in ng-if it will remove from DOM when flag gets true back it will reload the DOM in this case ng-show is better, for one time show ng-if is better

How to group by month from Date field using sql

I used the FORMAT function to accomplish this:

select
 FORMAT(Closing_Date, 'yyyy_MM') AS Closing_Month
 , count(*) cc 
FROM
 MyTable
WHERE
 Defect_Status1 IS NOT NULL
 AND Closing_Date >= '2011-12-01'
 AND Closing_Date < '2016-07-01' 
GROUP BY FORMAT(Closing_Date, 'yyyy_MM')
ORDER BY Closing_Month

How to stop a thread created by implementing runnable interface?

If you use ThreadPoolExecutor, and you use submit() method, it will give you a Future back. You can call cancel() on the returned Future to stop your Runnable task.

How can I get all a form's values that would be submitted without submitting

In straight Javascript you could do something similar to the following:

var kvpairs = [];
var form = // get the form somehow
for ( var i = 0; i < form.elements.length; i++ ) {
   var e = form.elements[i];
   kvpairs.push(encodeURIComponent(e.name) + "=" + encodeURIComponent(e.value));
}
var queryString = kvpairs.join("&");

In short, this creates a list of key-value pairs (name=value) which is then joined together using "&" as a delimiter.

What are XAND and XOR

XOR is short for exclusive or. It is a logical, binary operator that requires that one of the two operands be true but not both.

So these statements are true:

TRUE XOR FALSE
FALSE XOR TRUE

And these statements are false:

FALSE XOR FALSE
TRUE XOR TRUE

There really isn't such a thing as an"exclusive and" (or XAND) since in theory it would have the same exact requirements as XOR. There also isn't an XNOT since NOT is a unary operator that negates its single operand (basically it just flips a boolean value to its opposite) and as such it cannot support any notion of exclusivity.

System.IO.FileNotFoundException: Could not load file or assembly 'X' or one of its dependencies when deploying the application

I had the same issue. For me it helped to remove the .vs directory in the project folder.

bitwise XOR of hex numbers in python

here's a better function

def strxor(a, b):     # xor two strings of different lengths
    if len(a) > len(b):
        return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)])
    else:
        return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b[:len(a)])])

Python - IOError: [Errno 13] Permission denied:

Check if you are implementing the code inside a could drive like box, dropbox etc. If you copy the files you are trying to implement to a local folder on your machine you should be able to get rid of the error.

How to request a random row in SQL?

A simple and efficient way from http://akinas.com/pages/en/blog/mysql_random_row/

SET @i = (SELECT FLOOR(RAND() * COUNT(*)) FROM table); PREPARE get_stmt FROM 'SELECT * FROM table LIMIT ?, 1'; EXECUTE get_stmt USING @i;

What are the JavaScript KeyCodes?

I needed something like this for a game's control configuration UI, so I compiled a list for the standard US keyboard layout keycodes and mapped them to their respective key names.

Here's a fiddle that contains a map for code -> name and visi versa: http://jsfiddle.net/vWx8V/

If you want to support other key layouts you'll need to modify these maps to accommodate for them separately.

That is unless you were looking for a list of keycode values that included the control characters and other special values that are not (or are rarely) possible to input using a keyboard and may be outside of the scope of the keydown/keypress/keyup events of Javascript. Many of them are control characters or special characters like null (\0) and you most likely won't need them.

Notice that the number of keys on a full keyboard is less than many of the keycode values.

Unnamed/anonymous namespaces vs. static functions

Having learned of this feature only just now while reading your question, I can only speculate. This seems to provide several advantages over a file-level static variable:

  • Anonymous namespaces can be nested within one another, providing multiple levels of protection from which symbols can not escape.
  • Several anonymous namespaces could be placed in the same source file, creating in effect different static-level scopes within the same file.

I'd be interested in learning if anyone has used anonymous namespaces in real code.

jQuery: more than one handler for same event

Made it work successfully using the 2 methods: Stephan202's encapsulation and multiple event listeners. I have 3 search tabs, let's define their input text id's in an Array:

var ids = new Array("searchtab1", "searchtab2", "searchtab3");

When the content of searchtab1 changes, I want to update searchtab2 and searchtab3. Did it this way for encapsulation:

for (var i in ids) {
    $("#" + ids[i]).change(function() {
        for (var j in ids) {
            if (this != ids[j]) {
                $("#" + ids[j]).val($(this).val());
            }
        }
    });
}

Multiple event listeners:

for (var i in ids) {
    for (var j in ids) {
        if (ids[i] != ids[j]) {
            $("#" + ids[i]).change(function() {
                $("#" + ids[j]).val($(this).val());
            });
        }
    }
}

I like both methods, but the programmer chose encapsulation, however multiple event listeners worked also. We used Chrome to test it.

What's the difference between a temp table and table variable in SQL Server?

It surprises me that no one mentioned the key difference between these two is that the temp table supports parallel insert while the table variable doesn't. You should be able to see the difference from the execution plan. And here is the video from SQL Workshops on Channel 9.

This also explains why you should use a table variable for smaller tables, otherwise use a temp table, as SQLMenace answered before.

Is it a bad practice to use break in a for loop?

You can find all sorts of professional code with 'break' statements in them. It perfectly make sense to use this whenever necessary. In your case this option is better than creating a separate variable just for the purpose of coming out of the loop.

rsync: how can I configure it to create target directory on server?

this worked for me:

 rsync /dev/null node:existing-dir/new-dir/

I do get this message :

skipping non-regular file "null"

but I don't have to worry about having an empty directory hanging around.

SELECT INTO a table variable in T-SQL

First create a temp table :

Step 1:

create table #tblOm_Temp (

    Name varchar(100),
    Age Int ,
    RollNumber bigint
)

**Step 2: ** Insert Some value in Temp table .

insert into #tblom_temp values('Om Pandey',102,1347)

Step 3: Declare a table Variable to hold temp table data.

declare   @tblOm_Variable table(

    Name Varchar(100),
    Age int,
    RollNumber bigint
)

Step 4: select value from temp table and insert into table variable.

insert into @tblOm_Variable select * from #tblom_temp

Finally value is inserted from a temp table to Table variable

Step 5: Can Check inserted value in table variable.

select * from @tblOm_Variable

Manage toolbar's navigation and back button from fragment in android

The easiest solution I found was to simply put that in your fragment :

androidx.appcompat.widget.Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            NavController navController = Navigation.findNavController(getActivity(), 
R.id.nav_host_fragment);
            navController.navigate(R.id.action_position_to_destination);
        }
    });

Personnaly I wanted to go to another page but of course you can replace the 2 lines in the onClick method by the action you want to perform.

Script for rebuilding and reindexing the fragmented index?

To rebuild use:

ALTER INDEX __NAME_OF_INDEX__ ON __NAME_OF_TABLE__ REBUILD

or to reorganize use:

ALTER INDEX __NAME_OF_INDEX__ ON __NAME_OF_TABLE__ REORGANIZE

Reorganizing should be used at lower (<30%) fragmentations but only rebuilding (which is heavier to the database) cuts the fragmentation down to 0%.
For further information see https://msdn.microsoft.com/en-us/library/ms189858.aspx

SQL Count for each date

CREATE PROCEDURE [dbo].[sp_Myforeach_Date]
    -- Add the parameters for the stored procedure here
    @SatrtDate as DateTime,
    @EndDate as dateTime,
    @DatePart as varchar(2),
    @OutPutFormat as int 
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    Declare @DateList Table
    (Date varchar(50))

    WHILE @SatrtDate<= @EndDate
    BEGIN
    INSERT @DateList (Date) values(Convert(varchar,@SatrtDate,@OutPutFormat))
    IF Upper(@DatePart)='DD'
    SET @SatrtDate= DateAdd(dd,1,@SatrtDate)
    IF Upper(@DatePart)='MM'
    SET @SatrtDate= DateAdd(mm,1,@SatrtDate)
    IF Upper(@DatePart)='YY'
    SET @SatrtDate= DateAdd(yy,1,@SatrtDate)
    END 
    SELECT * FROM @DateList
END

Just put this Code and call the SP in This way

exec sp_Myforeach_Date @SatrtDate='03 Jan 2010',@EndDate='03 Mar 2010',@DatePart='dd',@OutPutFormat=106

Thanks Suvabrata Roy ICRA Online Ltd. Kolkata

Align nav-items to right side in bootstrap-4

In Bootstrap 4 alpha-6 version, As navbar is using flex model, you can use justify-content-end in parent's div and remove mr-auto.

<div class="collapse navbar-collapse justify-content-end" id="navbarText">
  <ul class="navbar-nav">
    <li class="nav-item active">
      <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#">Link</a>
    </li>
    <li class="nav-item">
      <a class="nav-link disabled" href="#">Disabled</a>
    </li>
  </ul>
</div>

This works like a charm :)

What is %2C in a URL?

Simple & Easy answer,

The %2C means , comma in URL. when you add the String "abc,defg" in the url as parameter then that comma in the string which is abc , defg is changed to abc%2Cdefg .There is no need to worry about it.

Open Windows Explorer and select a file

Check out this snippet:

Private Sub openDialog()
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      ' Set the title of the dialog box.
      .Title = "Please select the file."

      ' Clear out the current filters, and add our own.
      .Filters.Clear
      .Filters.Add "Excel 2003", "*.xls"
      .Filters.Add "All Files", "*.*"

      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
      If .Show = True Then
        txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox

      End If
   End With
End Sub

I think this is what you are asking for.

Plugin with id 'com.google.gms.google-services' not found

Had the same problem.

adding this to my dependency didn't solve

classpath 'com.google.gms:google-services:3.0.0'

Adding this solved for me

classpath 'com.google.gms:google-services:+'

to the root build.gradle.

Text vertical alignment in WPF TextBlock

If you can do without the text wrapping, I think that replacing the TextBlock with a Label is the most succinct way to do this. Otherwise follow one of the other valid answers.

<Label Content="Some Text" VerticalAlignment="Center"/>

Print ArrayList

From what I understand you are trying to print an ArrayList of arrays and one way to display that would be

System.out.println(Arrays.deepToString(list.toArray()));

SQL: Alias Column Name for Use in CASE Statement

Not in MySQL. I tried it and I get the following error:

ERROR 1054 (42S22): Unknown column 'a' in 'field list'

WPF Binding to parent DataContext

Because of things like this, as a general rule of thumb, I try to avoid as much XAML "trickery" as possible and keep the XAML as dumb and simple as possible and do the rest in the ViewModel (or attached properties or IValueConverters etc. if really necessary).

If possible I would give the ViewModel of the current DataContext a reference (i.e. property) to the relevant parent ViewModel

public class ThisViewModel : ViewModelBase
{
    TypeOfAncestorViewModel Parent { get; set; }
}

and bind against that directly instead.

<TextBox Text="{Binding Parent}" />

Unable to establish SSL connection upon wget on Ubuntu 14.04 LTS

Although this is almost certainly not the OPs issue, you can also get Unable to establish SSL connection from wget if you're behind a proxy and don't have HTTP_PROXY and HTTPS_PROXY environment variables set correctly. Make sure to set HTTP_PROXY and HTTPS_PROXY to point to your proxy.

This is a common situation if you work for a large corporation.

How to extract table as text from the PDF using Python?

  • I would suggest you to extract the table using tabula.
  • Pass your pdf as an argument to the tabula api and it will return you the table in the form of dataframe.
  • Each table in your pdf is returned as one dataframe.
  • The table will be returned in a list of dataframea, for working with dataframe you need pandas.

This is my code for extracting pdf.

import pandas as pd
import tabula
file = "filename.pdf"
path = 'enter your directory path here'  + file
df = tabula.read_pdf(path, pages = '1', multiple_tables = True)
print(df)

Please refer to this repo of mine for more details.

Vue equivalent of setTimeout?

please use setInterval like below:

    setInterval(()=>{this.checkOrder()},2000);

fstream won't create a file

You need to add some arguments. Also, instancing and opening can be put in one line:

fstream file("test.txt", fstream::in | fstream::out | fstream::trunc);

"for loop" with two variables?

For your use case, it may be easier to utilize a while loop.

t1 = [137, 42]
t2 = ["Hello", "world"]

i = 0
j = 0
while i < len(t1) and j < len(t2):
    print t1[i], t2[j]
    i += 1
    j += 1

# 137 Hello
# 42 world

As a caveat, this approach will truncate to the length of your shortest list.

How to display with n decimal places in Matlab

You can convert a number to a string with n decimal places using the SPRINTF command:

>> x = 1.23;
>> sprintf('%0.6f', x)

ans =

1.230000

>> x = 1.23456789;
>> sprintf('%0.6f', x)

ans =

1.234568

Maven plugin not using Eclipse's proxy settings

Eclipse by default does not know about your external Maven installation and uses the embedded one. Therefore in order for Eclipse to use your global settings you need to set it in menu Settings ? Maven ? Installations.

Not Able To Debug App In Android Studio

I did clean build using below command.. Surprisingly worked.

sh gradlew clean build

Hopefully someone get help!

How to pass a form input value into a JavaScript function

Give your inputs names it will make it easier

<form>
<input type="text" id="formValueId" name="valueId"/>
<input type="button" onclick="foo(this.form.valueId.value)"/>
</form>

UPDATE:

If you give your button an id things can be even easier:

<form>
<input type="text" id="formValueId" name="valueId"/>
<input type="button" id="theButton"/>
</form>

Javascript:

var button = document.getElementById("theButton"),
value =  button.form.valueId.value;
button.onclick = function() {
    foo(value);
}

error: expected declaration or statement at end of input in c

For me this problem was caused by a missing ) at the end of an if statement in a function called by the function the error was reported as from. Try scrolling up in the output to find the first error reported by the compiler. Fixing that error may fix this error.

What are advantages of Artificial Neural Networks over Support Vector Machines?

One obvious advantage of artificial neural networks over support vector machines is that artificial neural networks may have any number of outputs, while support vector machines have only one. The most direct way to create an n-ary classifier with support vector machines is to create n support vector machines and train each of them one by one. On the other hand, an n-ary classifier with neural networks can be trained in one go. Additionally, the neural network will make more sense because it is one whole, whereas the support vector machines are isolated systems. This is especially useful if the outputs are inter-related.

For example, if the goal was to classify hand-written digits, ten support vector machines would do. Each support vector machine would recognize exactly one digit, and fail to recognize all others. Since each handwritten digit cannot be meant to hold more information than just its class, it makes no sense to try to solve this with an artificial neural network.

However, suppose the goal was to model a person's hormone balance (for several hormones) as a function of easily measured physiological factors such as time since last meal, heart rate, etc ... Since these factors are all inter-related, artificial neural network regression makes more sense than support vector machine regression.

How to display count of notifications in app launcher icon

This is sample and best way for showing badge on notification launcher icon.

Add This Class in your application

public class BadgeUtils {

    public static void setBadge(Context context, int count) {
        setBadgeSamsung(context, count);
        setBadgeSony(context, count);
    }

    public static void clearBadge(Context context) {
        setBadgeSamsung(context, 0);
        clearBadgeSony(context);
    }


    private static void setBadgeSamsung(Context context, int count) {
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null) {
            return;
        }
        Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
        intent.putExtra("badge_count", count);
        intent.putExtra("badge_count_package_name", context.getPackageName());
        intent.putExtra("badge_count_class_name", launcherClassName);
        context.sendBroadcast(intent);
    }

    private static void setBadgeSony(Context context, int count) {
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null) {
            return;
        }

        Intent intent = new Intent();
        intent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", launcherClassName);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", true);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", String.valueOf(count));
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", context.getPackageName());

        context.sendBroadcast(intent);
    }


    private static void clearBadgeSony(Context context) {
        String launcherClassName = getLauncherClassName(context);
        if (launcherClassName == null) {
            return;
        }

        Intent intent = new Intent();
        intent.setAction("com.sonyericsson.home.action.UPDATE_BADGE");
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.ACTIVITY_NAME", launcherClassName);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.SHOW_MESSAGE", false);
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.MESSAGE", String.valueOf(0));
        intent.putExtra("com.sonyericsson.home.intent.extra.badge.PACKAGE_NAME", context.getPackageName());

        context.sendBroadcast(intent);
    }

    private static String getLauncherClassName(Context context) {

        PackageManager pm = context.getPackageManager();

        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);

        List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
        for (ResolveInfo resolveInfo : resolveInfos) {
            String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
            if (pkgName.equalsIgnoreCase(context.getPackageName())) {
                String className = resolveInfo.activityInfo.name;
                return className;
            }
        }
        return null;
    }


}

==> MyGcmListenerService.java Use BadgeUtils class when notification comes.

public class MyGcmListenerService extends GcmListenerService { 

    private static final String TAG = "MyGcmListenerService"; 
    @Override
    public void onMessageReceived(String from, Bundle data) {

            String message = data.getString("Msg");
            String Type = data.getString("Type"); 
            Intent intent = new Intent(this, SplashActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                    PendingIntent.FLAG_ONE_SHOT);

            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            NotificationCompat.BigTextStyle bigTextStyle= new NotificationCompat.BigTextStyle();

            bigTextStyle .setBigContentTitle(getString(R.string.app_name))
                    .bigText(message);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(getNotificationIcon())
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText(message)
                    .setStyle(bigTextStyle) 
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);

            int color = getResources().getColor(R.color.appColor);
            notificationBuilder.setColor(color);
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


            int unOpenCount=AppUtill.getPreferenceInt("NOTICOUNT",this);
            unOpenCount=unOpenCount+1;

            AppUtill.savePreferenceLong("NOTICOUNT",unOpenCount,this);  
            notificationManager.notify(unOpenCount /* ID of notification */, notificationBuilder.build()); 

// This is for bladge on home icon          
        BadgeUtils.setBadge(MyGcmListenerService.this,(int)unOpenCount);

    }


    private int getNotificationIcon() {
        boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);
        return useWhiteIcon ? R.drawable.notification_small_icon : R.drawable.icon_launcher;
    }
}

And clear notification from preference and also with badge count

 public class SplashActivity extends AppCompatActivity { 
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_splash);

                    AppUtill.savePreferenceLong("NOTICOUNT",0,this);
                    BadgeUtils.clearBadge(this);
            }
    }
<uses-permission android:name="com.sonyericsson.home.permission.BROADCAST_BADGE" />

What is the difference between a generative and a discriminative algorithm?

A generative algorithm model will learn completely from the training data and will predict the response.

A discriminative algorithm job is just to classify or differentiate between the 2 outcomes.

Running npm command within Visual Studio Code

  1. Edit user setting file settings.json.
    • Settings > Search for settings.json > Edit in settings.json
    or
    • Run > type %APPDATA%\Code\User\settings.json
  2. Copy this code
    { "terminal.integrated.shell.windows": "C:\\Windows\\System32\\cmd.exe", "terminal.integrated.shellArgs.windows": ["/k nodevars.bat"] }
  3. Restart VS Code

Program does not contain a static 'Main' method suitable for an entry point

Project Properties \ Output file -> Select Class Library :)

Image vs Bitmap class

The Bitmap class is an implementation of the Image class. The Image class is an abstract class;

The Bitmap class contains 12 constructors that construct the Bitmap object from different parameters. It can construct the Bitmap from another bitmap, and the string address of the image.

See more in this comprehensive sample.

What is the difference between association, aggregation and composition?

I'd like to illustrate how the three terms are implemented in Rails. ActiveRecord calls any type of relationship between two models an association. One would not find very often the terms composition and aggregation, when reading documentation or articles, related to ActiveRecord. An association is created by adding one of the association class macros to the body of the class. Some of these macros are belongs_to, has_one, has_many etc..

If we want to set up a composition or aggregation, we need to add belongs_to to the owned model (also called child) and has_one or has_many to the owning model (also called parent). Wether we set up composition or aggregation depends on the options we pass to the belongs_to call in the child model. Prior to Rails 5, setting up belongs_to without any options created an aggregation, the child could exist without a parent. If we wanted a composition, we needed to explicitly declare this by adding the option required: true:

class Room < ActiveRecord::Base
  belongs_to :house, required: true
end

In Rails 5 this was changed. Now, declaring a belongs_to association creates a composition by default, the child cannot exist without a parent. So the above example can be re-written as:

class Room < ApplicationRecord
  belongs_to :house
end

If we want to allow the child object to exist without a parent, we need to declare this explicitly via the option optional

class Product < ApplicationRecord
  belongs_to :category, optional: true
end

How to prevent form from being submitted?

Unlike the other answers, return false is only part of the answer. Consider the scenario in which a JS error occurs prior to the return statement...

html

<form onsubmit="return mySubmitFunction(event)">
  ...
</form>

script

function mySubmitFunction()
{
  someBug()
  return false;
}

returning false here won't be executed and the form will be submitted either way. You should also call preventDefault to prevent the default form action for Ajax form submissions.

function mySubmitFunction(e) {
  e.preventDefault();
  someBug();
  return false;
}

In this case, even with the bug the form won't submit!

Alternatively, a try...catch block could be used.

function mySubmit(e) { 
  e.preventDefault(); 
  try {
   someBug();
  } catch (e) {
   throw new Error(e.message);
  }
  return false;
}

How to kill a while loop with a keystroke?

There is always sys.exit().

The system library in Python's core library has an exit function which is super handy when prototyping. The code would be along the lines of:

import sys

while True:
    selection = raw_input("U: Create User\nQ: Quit")
    if selection is "Q" or selection is "q":
        print("Quitting")
        sys.exit()
    if selection is "U" or selection is "u":
        print("User")
        #do_something()

How do I prevent and/or handle a StackOverflowException?

By the looks of it, apart from starting another process, there doesn't seem to be any way of handling a StackOverflowException. Before anyone else asks, I tried using AppDomain, but that didn't work:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;

namespace StackOverflowExceptionAppDomainTest
{
    class Program
    {
        static void recrusiveAlgorithm()
        {
            recrusiveAlgorithm();
        }
        static void Main(string[] args)
        {
            if(args.Length>0&&args[0]=="--child")
            {
                recrusiveAlgorithm();
            }
            else
            {
                var domain = AppDomain.CreateDomain("Child domain to test StackOverflowException in.");
                domain.ExecuteAssembly(Assembly.GetEntryAssembly().CodeBase, new[] { "--child" });
                domain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) =>
                {
                    Console.WriteLine("Detected unhandled exception: " + e.ExceptionObject.ToString());
                };
                while (true)
                {
                    Console.WriteLine("*");
                    Thread.Sleep(1000);
                }
            }
        }
    }
}

If you do end up using the separate-process solution, however, I would recommend using Process.Exited and Process.StandardOutput and handle the errors yourself, to give your users a better experience.

how to get 2 digits after decimal point in tsql?

DECLARE @i AS FLOAT = 2 SELECT @i / 3 SELECT cast(@i / cast(3 AS DECIMAL(18,2))as decimal (18,2))

Both factor and result requires casting to be considered as decimals.

Application Installation Failed in Android Studio

Your APK file is missing . So , Clean Project >> Build APK >> Run the project .

What is "String args[]"? parameter in main method Java

When you finish your code, you will turn it into a file with the extension .java, which can be run by double clicking it, but also throughout a console (terminal on a mac, cmd.exe on windows) which lets the user do many things. One thing is they can see console messages (System.out.print or System.out.println) which they can't see if they double click. Another thing they can do is specify parameters, so normally you would use the line

java -jar MyCode.jar

after navigating to the folder of the program with

cd C:My/Code/Location

on windows or

cd My/Code/Location

on Mac (notice that mac is less clunky) to run code, but to specify parameters you would use

java -jar MyCode.jar parameter1 parameter2

These parameters stored in the args array, which you can use in your program is you want to allow the user to control special parameters such as what file to use or how much memory the program can have. If you want to know how to use an array, you could probably find a topic on this site or just google it. Note that any number of parameters can be used.

'^M' character at end of lines

In vi, do a :%s/^M//g

To get the ^M hold the CTRL key, press V then M (Both while holding the control key) and the ^M will appear. This will find all occurrences and replace them with nothing.

How to turn off the Eclipse code formatter for certain sections of Java code?

You have to turn on the ability to add the formatter tags. In the menubar go to:

Windows Preferences Java Code Style Formatter

Press the Edit button. Choose the last tab. Notice the On/Off box and enable them with a checkbox.

Calling a javascript function recursively

Here's one very simple example:

var counter = 0;

function getSlug(tokens) {
    var slug = '';

    if (!!tokens.length) {
        slug = tokens.shift();
        slug = slug.toLowerCase();
        slug += getSlug(tokens);

        counter += 1;
        console.log('THE SLUG ELEMENT IS: %s, counter is: %s', slug, counter);
    }

    return slug;
}

var mySlug = getSlug(['This', 'Is', 'My', 'Slug']);
console.log('THE SLUG IS: %s', mySlug);

Notice that the counter counts "backwards" in regards to what slug's value is. This is because of the position at which we are logging these values, as the function recurs before logging -- so, we essentially keep nesting deeper and deeper into the call-stack before logging takes place.

Once the recursion meets the final call-stack item, it trampolines "out" of the function calls, whereas, the first increment of counter occurs inside of the last nested call.

I know this is not a "fix" on the Questioner's code, but given the title I thought I'd generically exemplify Recursion for a better understanding of recursion, outright.

How do you run a command for each line of a file?

Read a file line by line and execute commands: 4 answers

This is because there is not only 1 answer...

  1. shell command line expansion
  2. xargs dedicated tool
  3. while read with some remarks
  4. while read -u using dedicated fd, for interactive processing (sample)

Regarding the OP request: running chmod on all targets listed in file, xargs is the indicated tool. But for some other applications, small amount of files, etc...

  1. Read entire file as command line argument.

    If your file is not too big and all files are well named (without spaces or other special chars like quotes), you could use shell command line expansion. Simply:

    chmod 755 $(<file.txt)
    

    For small amount of files (lines), this command is the lighter one.

  2. xargs is the right tool

    For bigger amount of files, or almost any number of lines in your input file...

    For many binutils tools, like chown, chmod, rm, cp -t ...

    xargs chmod 755 <file.txt
    

    If you have special chars and/or a lot of lines in file.txt.

    xargs -0 chmod 755 < <(tr \\n \\0 <file.txt)
    

    if your command need to be run exactly 1 time by entry:

    xargs -0 -n 1 chmod 755 < <(tr \\n \\0 <file.txt)
    

    This is not needed for this sample, as chmod accept multiple files as argument, but this match the title of question.

    For some special case, you could even define location of file argument in commands generateds by xargs:

    xargs -0 -I '{}' -n 1 myWrapper -arg1 -file='{}' wrapCmd < <(tr \\n \\0 <file.txt)
    

    Test with seq 1 5 as input

    Try this:

    xargs -n 1 -I{} echo Blah {} blabla {}.. < <(seq 1 5)
    Blah 1 blabla 1..
    Blah 2 blabla 2..
    Blah 3 blabla 3..
    Blah 4 blabla 4..
    Blah 5 blabla 5..
    

    Where commande is done once per line.

  3. while read and variants.

    As OP suggest cat file.txt | while read in; do chmod 755 "$in"; done will work, but there is 2 issues:

    • cat | is an useless fork, and

    • | while ... ;done will become a subshell where environment will disapear after ;done.

    So this could be better written:

    while read in; do chmod 755 "$in"; done < file.txt
    

    But,

    • You may be warned about $IFS and read flags:

      help read
      
      read: read [-r] ... [-d delim] ... [name ...]
          ...
          Reads a single line from the standard input... The line is split
          into fields as with word splitting, and the first word is assigned
          to the first NAME, the second word to the second NAME, and so on...
          Only the characters found in $IFS are recognized as word delimiters.
          ...
          Options:
            ...
            -d delim   continue until the first character of DELIM is read, 
                       rather than newline
            ...
            -r do not allow backslashes to escape any characters
          ...
          Exit Status:
          The return code is zero, unless end-of-file is encountered...
      

      In some case, you may need to use

      while IFS= read -r in;do chmod 755 "$in";done <file.txt
      

      For avoiding problems with stranges filenames. And maybe if you encouter problems with UTF-8:

      while LANG=C IFS= read -r in ; do chmod 755 "$in";done <file.txt
      
    • While you use STDIN for reading file.txt, your script could not be interactive (you cannot use STDIN anymore).

  4. while read -u, using dedicated fd.

    Syntax: while read ...;done <file.txt will redirect STDIN to file.txt. That mean, you won't be able to deal with process, until they finish.

    If you plan to create interactive tool, you have to avoid use of STDIN and use some alternative file descriptor.

    Constants file descriptors are: 0 for STDIN, 1 for STDOUT and 2 for STDERR. You could see them by:

    ls -l /dev/fd/
    

    or

    ls -l /proc/self/fd/
    

    From there, you have to choose unused number, between 0 and 63 (more, in fact, depending on sysctl superuser tool) as file descriptor:

    For this demo, I will use fd 7:

    exec 7<file.txt      # Without spaces between `7` and `<`!
    ls -l /dev/fd/
    

    Then you could use read -u 7 this way:

    while read -u 7 filename;do
        ans=;while [ -z "$ans" ];do
            read -p "Process file '$filename' (y/n)? " -sn1 foo
            [ "$foo" ]&& [ -z "${foo/[yn]}" ]&& ans=$foo || echo '??'
        done
        if [ "$ans" = "y" ] ;then
            echo Yes
            echo "Processing '$filename'."
        else
            echo No
        fi
    done 7<file.txt
    

    done
    

    To close fd/7:

    exec 7<&-            # This will close file descriptor 7.
    ls -l /dev/fd/
    

    Nota: I let striked version because this syntax could be usefull, when doing many I/O with parallels process:

    mkfifo sshfifo
    exec 7> >(ssh -t user@host sh >sshfifo)
    exec 6<sshfifo
    

Button Listener for button in fragment in android

This works for me.

private OnClickListener mDisconnectListener;
mDisconnectListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

        }
    };

...

... onCreateView(...){

mButtonDisconnect = (Button) rootView.findViewById(R.id.button_disconnect);
mButtonDisconnect.setOnClickListener(mDisconnectListener);
...
}

'npm' is not recognized as internal or external command, operable program or batch file

Just Download and Install Node.js from here https://nodejs.org/en/

If you run the downloaded file and install it, they will automatically configure for your system

You don't need any other configurations anymore, now you can use the npm command anywhere


If the Nodejs is successfully installed and still displays the message like this:

'npm' is not recognized as an internal or external command, operable program or batch file.

Follow the steps below for Windows users:

  1. Go to My Computer Properties
  2. Click Advanced System Setting from the Left bar of a window.
  3. Now you have a System Properties window. Click Advanced
  4. Then, Click Environment Variable button
  5. Now you have Environment variable window: From System Variable, Select Path
  6. Click Edit
  7. At the end of the Variable value, add ;C:\Program Files\nodejs\

    Note: If you have installed nodejs on other drives then please act accordingly.

  8. Click Ok all the open dialogue box

Very important Note: "Close your Command Prompt And Restart Again" (It's very important because if you didn't restart your command prompt then changes will not be reflected.)

Now you can use the npm command anywhere

Fixed footer in Bootstrap

Add this:

<div class="footer navbar-fixed-bottom">

https://stackoverflow.com/a/21604189

EDIT: class navbar-fixed-bottom has been changed to fixed-bottom as of Bootstrap v4-alpha.6.

http://v4-alpha.getbootstrap.com/components/navbar/#placement

Difference between virtual and abstract methods

First of all you should know the difference between a virtual and abstract method.

Abstract Method

  • Abstract Method resides in abstract class and it has no body.
  • Abstract Method must be overridden in non-abstract child class.

Virtual Method

  • Virtual Method can reside in abstract and non-abstract class.
  • It is not necessary to override virtual method in derived but it can be.
  • Virtual method must have body ....can be overridden by "override keyword".....

Compare dates in MySQL

I got the answer.

Here is the code:

SELECT * FROM table
WHERE STR_TO_DATE(column, '%d/%m/%Y')
  BETWEEN STR_TO_DATE('29/01/15', '%d/%m/%Y')
    AND STR_TO_DATE('07/10/15', '%d/%m/%Y')

How to pass argument to Makefile from command line?

You probably shouldn't do this; you're breaking the basic pattern of how Make works. But here it is:

action:
        @echo action $(filter-out $@,$(MAKECMDGOALS))

%:      # thanks to chakrit
    @:    # thanks to William Pursell

EDIT:
To explain the first command,

$(MAKECMDGOALS) is the list of "targets" spelled out on the command line, e.g. "action value1 value2".

$@ is an automatic variable for the name of the target of the rule, in this case "action".

filter-out is a function that removes some elements from a list. So $(filter-out bar, foo bar baz) returns foo baz (it can be more subtle, but we don't need subtlety here).

Put these together and $(filter-out $@,$(MAKECMDGOALS)) returns the list of targets specified on the command line other than "action", which might be "value1 value2".

Can't start Tomcat as Windows Service

Go to Start > Configure Tomcat >

  • Startup > Mode = Java
  • Shutdown > Mode = Java

This worked for me!

Finding rows that don't contain numeric data in Oracle

To get an indicator:

DECODE( TRANSLATE(your_number,' 0123456789',' ')

e.g.

SQL> select DECODE( TRANSLATE('12345zzz_not_numberee',' 0123456789',' '), NULL, 'number','contains char')
 2 from dual
 3 /

"contains char"

and

SQL> select DECODE( TRANSLATE('12345',' 0123456789',' '), NULL, 'number','contains char')
 2 from dual
 3 /

"number"

and

SQL> select DECODE( TRANSLATE('123405',' 0123456789',' '), NULL, 'number','contains char')
 2 from dual
 3 /

"number"

Oracle 11g has regular expressions so you could use this to get the actual number:

SQL> SELECT colA
  2  FROM t1
  3  WHERE REGEXP_LIKE(colA, '[[:digit:]]');

COL1
----------
47845
48543
12
...

If there is a non-numeric value like '23g' it will just be ignored.

pip: no module named _internal

For me

python -m pip uninstall pip

solved the issue. Reference

$http.get(...).success is not a function

The .success syntax was correct up to Angular v1.4.3.

For versions up to Angular v.1.6, you have to use then method. The then() method takes two arguments: a success and an error callback which will be called with a response object.

Using the then() method, attach a callback function to the returned promise.

Something like this:

app.controller('MainCtrl', function ($scope, $http){
   $http({
      method: 'GET',
      url: 'api/url-api'
   }).then(function (response){

   },function (error){

   });
}

See reference here.

Shortcut methods are also available.

$http.get('api/url-api').then(successCallback, errorCallback);

function successCallback(response){
    //success code
}
function errorCallback(error){
    //error code
}

The data you get from the response is expected to be in JSON format. JSON is a great way of transporting data, and it is easy to use within AngularJS

The major difference between the 2 is that .then() call returns a promise (resolved with a value returned from a callback) while .success() is more traditional way of registering callbacks and doesn't return a promise.

Add multiple items to a list

Code check:

This is offtopic here but the people over at CodeReview are more than happy to help you.

I strongly suggest you to do so, there are several things that need attention in your code. Likewise I suggest that you do start reading tutorials since there is really no good reason not to do so.

Lists:

As you said yourself: you need a list of items. The way it is now you only store a reference to one item. Lucky there is exactly that to hold a group of related objects: a List.

Lists are very straightforward to use but take a look at the related documentation anyway.

A very simple example to keep multiple bikes in a list:

List<Motorbike> bikes = new List<Motorbike>();

bikes.add(new Bike { make = "Honda", color = "brown" });
bikes.add(new Bike { make = "Vroom", color = "red" });

And to iterate over the list you can use the foreach statement:

foreach(var bike in bikes) {
     Console.WriteLine(bike.make);
}

Checkout old commit and make it a new commit

The other answers so far create new commits that undo what is in older commits. It is possible to go back and "change history" as it were, but this can be a bit dangerous. You should only do this if the commit you're changing has not been pushed to other repositories.

The command you're looking for is git rebase --interactive

If you want to change HEAD~3, the command you want to issue is git rebase --interactive HEAD~4. This will open a text editor and allow you to specify which commits you want to change.

Practice on a different repository before you try this with something important. The man pages should give you all the rest of the information you need.

How do I clone a subdirectory only of a Git repository?

Git 1.7.0 has “sparse checkouts”. See “core.sparseCheckout” in the git config manpage, “Sparse checkout” in the git read-tree manpage, and “Skip-worktree bit” in the git update-index manpage.

The interface is not as convenient as SVN’s (e.g. there is no way to make a sparse checkout at the time of an initial clone), but the base functionality upon which simpler interfaces could be built is now available.

Creating a "logical exclusive or" operator in Java

Here is a var arg XOR method for java...

public static boolean XOR(boolean... args) {
  boolean r = false;
  for (boolean b : args) {
    r = r ^ b;
  }
  return r;
}

Enjoy

Set value of textbox using JQuery

$(document).ready(function() {
 $('#main_search').val('hi');
});

Does Visual Studio Code have box select/multi-line edit?

On Windows it's holding down Alt while box selecting. Once you have your selection then attempt your edit.

Can I have multiple background images using CSS?

If you want multiple background images but don't want them to overlap, you can use this CSS:

body {
  font-size: 13px;
  font-family:Century Gothic, Helvetica, sans-serif;
  color: #333;
  text-align: center;
  margin:0px;
  padding: 25px;
}

#topshadow {
  height: 62px
  width:1030px;
  margin: -62px
  background-image: url(images/top-shadow.png);
}

#pageborders {
width:1030px;
min-height:100%;
margin:auto;        
    background:url(images/mid-shadow.png);
}

#bottomshadow {
    margin:0px;
height:66px;
width:1030px;
background:url(images/bottom-shadow.png);
}

#page {
  text-align: left;
  margin:62px, 0px, 20px;
  background-color: white;
  margin:auto;
  padding:0px;
  width:1000px;
}

with this HTML structure:

<body 

<?php body_class(); ?>>

  <div id="topshadow">
  </div>

  <div id="pageborders">

    <div id="page">
    </div>
  </div>
</body>

how to change directory using Windows command line

Another alternative is pushd, which will automatically switch drives as needed. It also allows you to return to the previous directory via popd:

C:\Temp>pushd D:\some\folder
D:\some\folder>popd
C:\Temp>_

Concatenate two JSON objects

var baseArrayOfJsonObjects = [{},{}];
for (var i=0; i<arrayOfJsonObjectsFromAjax.length; i++) {
    baseArrayOfJsonObjects.push(arrayOfJsonObjectsFromAjax[i]);
}

php.ini & SMTP= - how do you pass username & password

  1. Install the latest hMailServer. "Run hMailServer Administrator" in the last step.
  2. Connect to "localhost".
  3. "Add domain..."
  4. Set "127.0.0.1." as the "Domain", click "Save".
  5. "Settings" > "Protocols" > "SMTP" > "Delivery of e-mail"
  6. Set "localhost" as the "Local host name", provide your data in the "SMTP Relayer" section, click "Save".
  7. "Settings" > "Advanced" > "IP Ranges" > "My Computer"
  8. Disable the "External to external e-mail addresses" checkbox in the "Require SMTP authentication" group.
  9. If you have modified php.ini, rewrite these 3 values:

"SMTP = localhost",

"smtp_port = 25",

"; sendmail_path = ".

Credit: How to configure WAMP (localhost) to send email using Gmail?

How to use Scanner to accept only valid int as input

What you could do is also to take the next token as a String, converts this string to a char array and test that each character in the array is a digit.

I think that's correct, if you don't want to deal with the exceptions.

Check that an email address is valid on iOS

to validate the email string you will need to write a regular expression to check it is in the correct form. there are plenty out on the web but be carefull as some can exclude what are actually legal addresses.

essentially it will look something like this

^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*"\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$

Actually checking if the email exists and doesn't bounce would mean sending an email and seeing what the result was. i.e. it bounced or it didn't. However it might not bounce for several hours or not at all and still not be a "real" email address. There are a number of services out there which purport to do this for you and would probably be paid for by you and quite frankly why bother to see if it is real?

It is good to check the user has not misspelt their email else they could enter it incorrectly, not realise it and then get hacked of with you for not replying. However if someone wants to add a bum email address there would be nothing to stop them creating it on hotmail or yahoo (or many other places) to gain the same end.

So do the regular expression and validate the structure but forget about validating against a service.

How to hide 'Back' button on navigation bar on iPhone?

try this one - self.navigationController?.navigationItem.hidesBackButton = true

Styling input radio with css

You should use some background image to your radio buttons and flip it with another image on change

.radio {
    background: url(customButton.png) no-repeat;
}

Function in JavaScript that can be called only once

try this

var fun = (function() {
  var called = false;
  return function() {
    if (!called) {
      console.log("I  called");
      called = true;
    }
  }
})()

MVC - Set selected value of SelectList

Doug answered my question... But I'll explain what my problem was exactly, and how Doug helped me solve my problem which you could be encountering.

I call jquery $.post and am replacing my div with my partial view, like so.

function AddNewAddress (paramvalue) {
    $.post(url, { param: paramvalue}, function(d) {
        $('#myDiv').replaceWith(d);
    });
}

When doing so, for some reason when stepping into my model my selected value affiliated property was never set, only until I stepped into the view it came into scope.

So, What I had before

@Html.DropDownListUnobtrusiveFor(model => model.CustomerAddresses[i].YearsAtAddress, Model.CustomerAddresses[i].YearsAtAddressSelectList, new {onchange = "return Address.AddNewAddress(this,'" + @Url.Action("AddNewAddress", "Address") + "'," + i + ")"})

however even though Model.CustomerAddresses[i].YearsAtAddressSelectList, was set... it didn't set the selected value.

So after....

 @Html.DropDownListUnobtrusiveFor(model => model.CustomerAddresses[i].YearsAtAddress, new SelectList(Model.CustomerAddresses[i].YearsAtAddressSelectList, "Value", "Text", Model.CustomerAddresses[i].YearsAtAddress), new { onchange = "return Address.AddNewAddress(this,'" + @Url.Action("AddNewAddress", "Address") + "'," + i + ")" })

and it worked!

I decided not to use DropDownListFor as it has problem when using unobtrusive validation, which is why i reference the following if your curious in a class classed

HtmlExtensions.cs




[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]

public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList)
{
    return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, null /* optionLabel */, null /* htmlAttributes */);

}


[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]

public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, object htmlAttributes)
{
    return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, null /* optionLabel */, new RouteValueDictionary(htmlAttributes));

}


[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]

public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, IDictionary<string, object> htmlAttributes)
{
    return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, null /* optionLabel */, htmlAttributes);

}


[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]

public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel)
{
    return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, optionLabel, null /* htmlAttributes */);

}


[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]

public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, object htmlAttributes)
{
    return DropDownListUnobtrusiveFor(htmlHelper, expression, selectList, optionLabel, new RouteValueDictionary(htmlAttributes));

}


[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Users cannot use anonymous methods with the LambdaExpression type")]

[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]

public static MvcHtmlString DropDownListUnobtrusiveFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes)
{
    if (expression == null)
    {
        throw new ArgumentNullException("expression");
    }


    ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);



    IDictionary<string, object> validationAttributes = htmlHelper
        .GetUnobtrusiveValidationAttributes(ExpressionHelper.GetExpressionText(expression), metadata);



    if (htmlAttributes == null)
        htmlAttributes = validationAttributes;
    else
        htmlAttributes = htmlAttributes.Concat(validationAttributes).ToDictionary(k => k.Key, v => v.Value);



    return SelectExtensions.DropDownListFor(htmlHelper, expression, selectList, optionLabel, htmlAttributes);

}

How to spyOn a value property (rather than a method) with Jasmine

I'm using a kendo grid and therefore can't change the implementation to a getter method but I want to test around this (mocking the grid) and not test the grid itself. I was using a spy object but this doesn't support property mocking so I do this:

    this.$scope.ticketsGrid = { 
        showColumn: jasmine.createSpy('showColumn'),
        hideColumn: jasmine.createSpy('hideColumn'),
        select: jasmine.createSpy('select'),
        dataItem: jasmine.createSpy('dataItem'),
        _data: []
    } 

It's a bit long winded but it works a treat

Android studio Gradle icon error, Manifest Merger

GOT THE SOLUTION AFTER ALOT OF TIME GOOGLING

just get your ic_launcher and paste it in your drawables folder,

Go to your manifest and change android:icon="@drawable/ic_launcher"

Clean your project and rebuild

Hope it helps you

How good is Java's UUID.randomUUID?

We have been using the Java's random UUID in our application for more than one year and that to very extensively. But we never come across of having collision.

Number input type that takes only integers?

This is not only for html5 all browser is working fine . try this

onkeyup="this.value=this.value.replace(/[^0-9]/g,'');"

Sorting Directory.GetFiles()

A more succinct VB.Net version...is very nice. Thank you. To traverse the list in reverse order, add the reverse method...

For Each fi As IO.FileInfo In filePaths.reverse
  ' Do whatever you wish here
Next

How to programmatically determine the current checked out Git branch

The correct solution is to take a peek at contrib/completions/git-completion.bash does that for bash prompt in __git_ps1. Removing all extras like selecting how to describe detached HEAD situation, i.e. when we are on unnamed branch, it is:

branch_name="$(git symbolic-ref HEAD 2>/dev/null)" ||
branch_name="(unnamed branch)"     # detached HEAD

branch_name=${branch_name##refs/heads/}

git symbolic-ref is used to extract fully qualified branch name from symbolic reference; we use it for HEAD, which is currently checked out branch.

Alternate solution could be:

branch_name=$(git symbolic-ref -q HEAD)
branch_name=${branch_name##refs/heads/}
branch_name=${branch_name:-HEAD}

where in last line we deal with the detached HEAD situation, using simply "HEAD" to denote such situation.


Added 11-06-2013

Junio C. Hamano (git maintainer) blog post, Checking the current branch programatically, from June 10, 2013 explains whys (and hows) in more detail.

How to Convert unsigned char* to std::string in C++?

You just needed to cast the unsigned char into a char as the string class doesn't have a constructor that accepts unsigned char:

unsigned char* uc;
std::string s( reinterpret_cast< char const* >(uc) ) ;

However, you will need to use the length argument in the constructor if your byte array contains nulls, as if you don't, only part of the array will end up in the string (the array up to the first null)

size_t len;
unsigned char* uc;
std::string s( reinterpret_cast<char const*>(uc), len ) ;

pandas get rows which are NOT in other dataframe

a bit late, but it might be worth checking the "indicator" parameter of pd.merge.

See this other question for an example: Compare PandaS DataFrames and return rows that are missing from the first one

How to make the corners of a button round?

You can also use the card layout like below

  <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="60dp"
        app:cardCornerRadius="30dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"

            >

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:text="Template"

                />

        </LinearLayout>

    </androidx.cardview.widget.CardView>

How to change the locale in chrome browser

Based from this thread, you need to bookmark chrome://settings/languages and then Drag and Drop the language to make it default. You have to click on the Display Google Chrome in this Language button and completely restart Chrome.

MySQL: Selecting multiple fields into multiple variables in a stored procedure

==========Advise==========

@martin clayton Answer is correct, But this is an advise only.

Please avoid the use of ambiguous variable in the stored procedure.

Example :

SELECT Id, dateCreated
INTO id, datecreated
FROM products
WHERE pName = iName

The above example will cause an error (null value error)

Example give below is correct. I hope this make sense.

Example :

SELECT Id, dateCreated
INTO val_id, val_datecreated
FROM products
WHERE pName = iName

You can also make them unambiguous by referencing the table, like:

[ Credit : maganap ]

SELECT p.Id, p.dateCreated INTO id, datecreated FROM products p 
WHERE pName = iName

How to concatenate string and int in C?

Use sprintf (or snprintf if like me you can't count) with format string "pre_%d_suff".

For what it's worth, with itoa/strcat you could do:

char dst[12] = "pre_";
itoa(i, dst+4, 10);
strcat(dst, "_suff");

Java 8 Stream API to find Unique Object matching a property value

Instead of using a collector try using findFirst or findAny.

Optional<Person> matchingObject = objects.stream().
    filter(p -> p.email().equals("testemail")).
    findFirst();

This returns an Optional since the list might not contain that object.

If you're sure that the list always contains that person you can call:

Person person = matchingObject.get();

Be careful though! get throws NoSuchElementException if no value is present. Therefore it is strongly advised that you first ensure that the value is present (either with isPresent or better, use ifPresent, map, orElse or any of the other alternatives found in the Optional class).

If you're okay with a null reference if there is no such person, then:

Person person = matchingObject.orElse(null);

If possible, I would try to avoid going with the null reference route though. Other alternatives methods in the Optional class (ifPresent, map etc) can solve many use cases. Where I have found myself using orElse(null) is only when I have existing code that was designed to accept null references in some cases.


Optionals have other useful methods as well. Take a look at Optional javadoc.

How can I print a circular structure in a JSON-like format?

I know this question is old and has lots of great answers but I post this answer because of it's new flavor (es5+)

_x000D_
_x000D_
Object.defineProperties(JSON, {_x000D_
  refStringify: {_x000D_
    value: function(obj) {_x000D_
_x000D_
      let objMap = new Map();_x000D_
      let stringified = JSON.stringify(obj,_x000D_
        function(key, value) {_x000D_
_x000D_
          // only for objects_x000D_
          if (typeof value == 'object') {_x000D_
            // If has the value then return a reference to it_x000D_
            if (objMap.has(value))_x000D_
              return objMap.get(value);_x000D_
_x000D_
            objMap.set(value, `ref${objMap.size + 1}`);_x000D_
          }_x000D_
          return value;_x000D_
        });_x000D_
      return stringified;_x000D_
    }_x000D_
  },_x000D_
  refParse: {_x000D_
    value: function(str) {_x000D_
_x000D_
      let parsed = JSON.parse(str);_x000D_
      let objMap = _createObjectMap(parsed);_x000D_
      objMap.forEach((value, key) => _replaceKeyWithObject(value, key));_x000D_
      return parsed;_x000D_
    }_x000D_
  },_x000D_
});_x000D_
_x000D_
// *************************** Example_x000D_
let a = {_x000D_
  b: 32,_x000D_
  c: {_x000D_
    get a() {_x000D_
        return a;_x000D_
      },_x000D_
      get c() {_x000D_
        return a.c;_x000D_
      }_x000D_
  }_x000D_
};_x000D_
let stringified = JSON.refStringify(a);_x000D_
let parsed = JSON.refParse(stringified, 2);_x000D_
console.log(parsed, JSON.refStringify(parsed));_x000D_
// *************************** /Example_x000D_
_x000D_
// *************************** Helper_x000D_
function _createObjectMap(obj) {_x000D_
_x000D_
  let objMap = new Map();_x000D_
  JSON.stringify(obj, (key, value) => {_x000D_
    if (typeof value == 'object') {_x000D_
      if (objMap.has(value))_x000D_
        return objMap.get(value);_x000D_
      objMap.set(value, `ref${objMap.size + 1}`);_x000D_
_x000D_
    }_x000D_
    return value;_x000D_
  });_x000D_
  return objMap;_x000D_
}_x000D_
_x000D_
function _replaceKeyWithObject(key, obj, replaceWithObject = obj) {_x000D_
_x000D_
  Object.keys(obj).forEach(k => {_x000D_
_x000D_
    let val = obj[k];_x000D_
    if (val == key)_x000D_
      return (obj[k] = replaceWithObject);_x000D_
    if (typeof val == 'object' && val != replaceWithObject)_x000D_
      _replaceKeyWithObject(key, val, replaceWithObject);_x000D_
  });_x000D_
}
_x000D_
_x000D_
_x000D_

Export table to file with column headers (column names) using the bcp utility and SQL Server 2008

I got a version based on what I saw previously. It helped me a lot to create export files as CSV or TXT. I'm storing a table into a ## Temp Table:

    IF OBJECT_ID('tempdb..##TmpExportFile') IS NOT NULL
DROP TABLE ##TmpExportFile;


DECLARE @columnHeader VARCHAR(8000)
DECLARE @raw_sql nvarchar(3000)

SELECT
              * INTO ##TmpExportFile
              ------ FROM THE TABLE RESULTS YOU WANT TO GET
              ------ COULD BE A TABLE OR A TEMP TABLE BASED ON INNER JOINS
              ------ ,ETC.

FROM TableName -- optional WHERE ....


DECLARE @table_name  VARCHAR(50) = '##TmpExportFile'
SELECT
              @columnHeader = COALESCE(@columnHeader + ',', '') + '''[' + c.name + ']''' + ' as ' + '' + c.name + ''
FROM tempdb.sys.columns c
INNER JOIN tempdb.sys.tables t
              ON c.object_id = t.object_id
WHERE t.NAME = @table_name

print @columnheader

                DECLARE @ColumnList VARCHAR(max)
SELECT
              @ColumnList = COALESCE(@ColumnList + ',', '') + 'CAST([' + c.name + '] AS CHAR(' + LTRIM(STR(max_length)) + '))'
FROM tempdb.sys.columns c
INNER JOIN tempdb.sys.tables t
              ON c.object_id = t.object_id
WHERE t.name = @table_name
print @ColumnList

--- CSV FORMAT                                       
SELECT
              @raw_sql = 'bcp "SELECT ' + @columnHeader + ' UNION all SELECT ' + @ColumnList + ' FROM ' + @table_name + ' " queryout \\networkdrive\networkfolder\datafile.csv -c -t, /S' + ' SQLserverName /T'
--PRINT @raw_sql
EXEC xp_cmdshell @raw_sql

  --- TXT FORMAT
       SET @raw_sql = 'bcp "SELECT ' + @columnHeader + ' UNION all SELECT ' + @ColumnList + ' FROM ' + @table_name + ' " queryout \\networkdrive\networkfolder\MISD\datafile.txt /c /S'+ ' SQLserverName /T'
       EXEC xp_cmdshell @raw_sql



DROP TABLE ##TmpExportFile

How to recognize vehicle license / number plate (ANPR) from an image?

It maybe work looking at Character recoqnition software as there are many libraries out there that perform the same thing. I reading an image and storing it. Micrsoft office is able to read tiff files and return alphanumerics

Node.js: How to send headers with form data using request module?

I think it's just because you have forgot HTTP METHOD. The default HTTP method of request is GET.

You should add method: 'POST' and your code will work if your backend receive the post method.

var req = require('request');

req.post({
   url: 'someUrl',
   form: { username: 'user', password: '', opaque: 'someValue', logintype: '1'},
   headers: { 
      'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36',
      'Content-Type' : 'application/x-www-form-urlencoded' 
   },
   method: 'POST'
  },

  function (e, r, body) {
      console.log(body);
  });

Node.js ES6 classes with require

In class file you can either use:

module.exports = class ClassNameHere {
 print() {
  console.log('In print function');
 }
}

or you can use this syntax

class ClassNameHere{
 print(){
  console.log('In print function');
 }
}

module.exports = ClassNameHere;

On the other hand to use this class in any other file you need to do these steps. First require that file using this syntax: const anyVariableNameHere = require('filePathHere');

Then create an object const classObject = new anyVariableNameHere();

After this you can use classObject to access the actual class variables

Java: Most efficient method to iterate over all elements in a org.w3c.dom.Document?

I also stumbled over this problem recently. Here is my solution. I wanted to avoid recursion, so I used a while loop.

Because of the adds and removes in arbitrary places on the list, I went with the LinkedList implementation.

/* traverses tree starting with given node */
  private static List<Node> traverse(Node n)
  {
    return traverse(Arrays.asList(n));
  }

  /* traverses tree starting with given nodes */
  private static List<Node> traverse(List<Node> nodes)
  {
    List<Node> open = new LinkedList<Node>(nodes);
    List<Node> visited = new LinkedList<Node>();

    ListIterator<Node> it = open.listIterator();
    while (it.hasNext() || it.hasPrevious())
    {
      Node unvisited;
      if (it.hasNext())
        unvisited = it.next();
      else
        unvisited = it.previous();

      it.remove();

      List<Node> children = getChildren(unvisited);
      for (Node child : children)
        it.add(child);

      visited.add(unvisited);
    }

    return visited;
  }

  private static List<Node> getChildren(Node n)
  {
    List<Node> children = asList(n.getChildNodes());
    Iterator<Node> it = children.iterator();
    while (it.hasNext())
      if (it.next().getNodeType() != Node.ELEMENT_NODE)
        it.remove();
    return children;
  }

  private static List<Node> asList(NodeList nodes)
  {
    List<Node> list = new ArrayList<Node>(nodes.getLength());
    for (int i = 0, l = nodes.getLength(); i < l; i++)
      list.add(nodes.item(i));
    return list;
  }

Update TextView Every Second

It would be better if you just used an AsyncTask running using a Timer something like this

 Timer LAIATT = new Timer();
    TimerTask LAIATTT = new TimerTask()
    {
        @Override
        public void run()
        {
            LoadAccountInformationAsyncTask LAIAT = new LoadAccountInformationAsyncTask();
            LAIAT.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
    };
    LAIATT.schedule(LAIATTT, 0, 1000);

Use URI builder in Android or create URL with variables

Using appendEncodePath() could save you multiple lines than appendPath(), the following code snippet builds up this url: http://api.openweathermap.org/data/2.5/forecast/daily?zip=94043

Uri.Builder urlBuilder = new Uri.Builder();
urlBuilder.scheme("http");
urlBuilder.authority("api.openweathermap.org");
urlBuilder.appendEncodedPath("data/2.5/forecast/daily");
urlBuilder.appendQueryParameter("zip", "94043,us");
URL url = new URL(urlBuilder.build().toString());

How to write both h1 and h2 in the same line?

In answer the question heading (found by a google search) and not the re-question To stop the line breaking when you have different heading tags e.g.

<h5 style="display:inline;"> What the... </h5><h1 style="display:inline;"> heck is going on? </h1>

Will give you:

What the...heck is going on?

and not

What the... 
heck is going on?

Regular expression to extract text between square brackets

Just in case, you might have had unbalanced brackets, you can likely design some expression with recursion similar to,

\[(([^\]\[]+)|(?R))*+\]

which of course, it would relate to the language or RegEx engine that you might be using.

RegEx Demo 1


Other than that,

\[([^\]\[\r\n]*)\]

RegEx Demo 2

or,

(?<=\[)[^\]\[\r\n]*(?=\])

RegEx Demo 3

are good options to explore.


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Test

_x000D_
_x000D_
const regex = /\[([^\]\[\r\n]*)\]/gm;_x000D_
const str = `This is a [sample] string with [some] special words. [another one]_x000D_
This is a [sample string with [some special words. [another one_x000D_
This is a [sample[sample]] string with [[some][some]] special words. [[another one]]`;_x000D_
let m;_x000D_
_x000D_
while ((m = regex.exec(str)) !== null) {_x000D_
    // This is necessary to avoid infinite loops with zero-width matches_x000D_
    if (m.index === regex.lastIndex) {_x000D_
        regex.lastIndex++;_x000D_
    }_x000D_
    _x000D_
    // The result can be accessed through the `m`-variable._x000D_
    m.forEach((match, groupIndex) => {_x000D_
        console.log(`Found match, group ${groupIndex}: ${match}`);_x000D_
    });_x000D_
}
_x000D_
_x000D_
_x000D_

Source

Regular expression to match balanced parentheses

How to make python Requests work via socks proxy

The modern way:

pip install -U requests[socks]

then

import requests

resp = requests.get('http://go.to', 
                    proxies=dict(http='socks5://user:pass@host:port',
                                 https='socks5://user:pass@host:port'))

Android Studio Stuck at Gradle Download on create new project

Yes, You can install Gradle manually before Android Studio, first install gradle in any location then add de gladle location to path variable (in Environment Variables Window).

Substring in VBA

Test for ':' first, then take test string up to ':' or end, depending on if it was found

Dim strResult As String

' Position of :
intPos = InStr(1, strTest, ":")
If intPos > 0 Then
    ' : found, so take up to :
    strResult = Left(strTest, intPos - 1)
Else
    ' : not found, so take whole string
    strResult = strTest
End If

When to use Common Table Expression (CTE)

I use them to break up complex queries, especially complex joins and sub-queries. I find I'm using them more and more as 'pseudo-views' to help me get my head around the intent of the query.

My only complaint about them is they cannot be re-used. For example, I may have a stored proc with two update statements that could use the same CTE. But the 'scope' of the CTE is the first query only.

Trouble is, 'simple examples' probably don't really need CTE's!

Still, very handy.

CSS: Creating textured backgrounds

with latest CSS3 technology, it is possible to create textured background. Check this out: http://lea.verou.me/css3patterns/#

but it still limited on so many aspect. And browser support is also not so ready.

your best bet is using small texture image and make repeat to that background. you could get some nice ready to use texture image here:

http://subtlepatterns.com

Generate an integer sequence in MySQL

There is no sequence number generator (CREATE SEQUENCE) in MySQL. Closest thing is AUTO_INCREMENT, which can help you construct the table.

Invoking JavaScript code in an iframe from the parent page

       $("#myframe").load(function() {
            alert("loaded");
        });

Create tap-able "links" in the NSAttributedString of a UILabel?

I'd strongly recommend using a library that automatically detects URLs in text and converts them to links. Try:

Both are under MIT license.

How to take character input in java

use :

char ch=**scanner.nextChar**()

Calculate date/time difference in java

long diffSeconds = (diff / 1000)%60;
try this and let me know if it works correctly...

How to get rows count of internal table in abap?

The functional module EM_GET_NUMBER_OF_ENTRIES will also provide the row count. It takes 1 parameter - the table name.