Programs & Examples On #Hxcpp

DataTables warning: Requested unknown parameter '0' from the data source for row '0'

I was having the same problem. Turns out in my case, I was missing the comma after the last column. 30 minutes of my life wasted, I will never get back!

enter image description here

Click in OK button inside an Alert (Selenium IDE)

To click the "ok" button in an alert box:


Convert array values from string to int?

Use this code with a closure (introduced in PHP 5.3), it's a bit faster than the accepted answer and for me, the intention to cast it to an integer, is clearer:

// if you have your values in the format '1,2,3,4', use this before:
// $stringArray = explode(',', '1,2,3,4');

$stringArray = ['1', '2', '3', '4'];

$intArray = array_map(
    function($value) { return (int)$value; },


Output will be:

array(4) {

How to change string into QString?

std::string s = "Sambuca";
QString q = s.c_str();

Warning: This won't work if the std::string contains \0s.

How to add jQuery to an HTML page?

Including the jQuery Library

That is jQuery code. You'll first need to make sure the jQuery library is loaded. If you don't host the library file yourself, you can hotlink one from the jQuery CDN:

<script src="//"></script>

You can do this within the <head> section, but it's fine as long as it's loaded before your jQuery code.

Further reading:

Placing Your Code in the Page

Place your code inside <script> tags. It can be inserted anywhere within either <head> or <body>. If you place it before the <input> and <tr> tags (as referenced in your code), you have to use $(document).ready() to make sure those elements are present before the code is run:

$(document).ready(function() {
    // put your jQuery code here.

If you want your page content to be loaded as soon as possible, you might want to place it as close as the </body> close tag as possible. But another common practice is to place all JavaScript code in the <head> section. This is your choice, based on your coding style and needs.

Suggestion: Instead of embedding JS/jQuery code directly into an HTML page, consider placing the code in a separate .js file. This will allow you to reuse the same code on other pages:

<script src="/path/to/your/code.js"></script>

Further reading:

How can I remove time from date with Moment.js?

Use format('LL')

Depending on what you're trying to do with it, format('LL') could do the trick. It produces something like this:

Moment().format('LL'); // => April 29, 2016

Clearing localStorage in javascript?

If you want to clear all item you stored in localStorage then


Use this for clear all stored key.

If you want to clear/remove only specific key/value then you can use removeItem(key).


Using Mysql in the command line in osx - command not found?

So there are few places where terminal looks for commands. This places are stored in your $PATH variable. Think of it as a global variable where terminal iterates over to look up for any command. This are usually binaries look how /bin folder is usually referenced.

/bin folder has lots of executable files inside it. Turns out this are command. This different folder locations are stored inside one Global variable i.e. $PATH separated by :

Now usually programs upon installation takes care of updating PATH & telling your terminal that hey i can be all commands inside my bin folder.

Turns out MySql doesn't do it upon install so we manually have to do it.

We do it by following command,

export PATH=$PATH:/usr/local/mysql/bin

If you break it down, export is self explanatory. Think of it as an assignment. So export a variable PATH with value old $PATH concat with new bin i.e. /usr/local/mysql/bin

This way after executing it all the commands inside /usr/local/mysql/bin are available to us.

There is a small catch here. Think of one terminal window as one instance of program and maybe something like $PATH is class variable ( maybe ). Note this is pure assumption. So upon close we lose the new assignment. And if we reopen terminal we won't have access to our command again because last when we exported, it was stored in primary memory which is volatile.

Now we need to have our mysql binaries exported every-time we use terminal. So we have to persist concat in our path.

You might be aware that our terminal using something called dotfiles to load configuration on terminal initialisation. I like to think of it's as sets of thing passed to constructer every-time a new instance of terminal is created ( Again an assumption but close to what it might be doing ). So yes by now you get the point what we are going todo.

.bash_profile is one of the primary known dotfile.

So in following command,

echo 'export PATH=$PATH:/usr/local/mysql/bin' >> ~/.bash_profile

What we are doing is saving result of echo i.e. output string to ~/.bash_profile

So now as we noted above every-time we open terminal or instance of terminal our dotfiles are loaded. So .bash_profile is loaded respectively and export that we appended above is run & thus a our global $PATH gets updated and we get all the commands inside /usr/local/mysql/bin.


if you are not running first command export directly but just running second in order to persist it? Than for current running instance of terminal you have to,

source ~/.bash_profile

This tells our terminal to reload that particular file.

Disable native datepicker in Google Chrome

The code above doesn't set the value of the input element nor does it fire a change event. The code below works in Chrome and Firefox (not tested in other browsers):

    onSelect: function(dateText){
        var d = new Date(dateText),
        dv = d.getFullYear().toString().pad(4)+'-'+(d.getMonth()+1).toString().pad(2)+'-'+d.getDate().toString().pad(2);

pad is a simple custom String method to pad strings with zeros (required)

Where is web.xml in Eclipse Dynamic Web Project

Might be your project is not JEE nature, to do this Right Click -> Properties -> Project Facets and click Convert to facet and check dynamic web module and ok. Now you will be able to see Java EE Tools.

How to upload a file from Windows machine to Linux machine using command lines via PuTTy?

Better and quicker approach without any software to download.

  • Open command prompt and follow steps mentioned below
  • cd path/from/where/file/istobe/copied
  • ftp (serverip or name)
  • It will ask for Server(AIX) User: (username)
  • It will ask for password : (password)
  • cd path/where/file/istobe/copied
  • pwd (to check current path)
  • mput (directory name which is to be copied)

This should work.

What is private bytes, virtual bytes, working set?

The short answer to this question is that none of these values are a reliable indicator of how much memory an executable is actually using, and none of them are really appropriate for debugging a memory leak.

Private Bytes refer to the amount of memory that the process executable has asked for - not necessarily the amount it is actually using. They are "private" because they (usually) exclude memory-mapped files (i.e. shared DLLs). But - here's the catch - they don't necessarily exclude memory allocated by those files. There is no way to tell whether a change in private bytes was due to the executable itself, or due to a linked library. Private bytes are also not exclusively physical memory; they can be paged to disk or in the standby page list (i.e. no longer in use, but not paged yet either).

Working Set refers to the total physical memory (RAM) used by the process. However, unlike private bytes, this also includes memory-mapped files and various other resources, so it's an even less accurate measurement than the private bytes. This is the same value that gets reported in Task Manager's "Mem Usage" and has been the source of endless amounts of confusion in recent years. Memory in the Working Set is "physical" in the sense that it can be addressed without a page fault; however, the standby page list is also still physically in memory but not reported in the Working Set, and this is why you might see the "Mem Usage" suddenly drop when you minimize an application.

Virtual Bytes are the total virtual address space occupied by the entire process. This is like the working set, in the sense that it includes memory-mapped files (shared DLLs), but it also includes data in the standby list and data that has already been paged out and is sitting in a pagefile on disk somewhere. The total virtual bytes used by every process on a system under heavy load will add up to significantly more memory than the machine actually has.

So the relationships are:

  • Private Bytes are what your app has actually allocated, but include pagefile usage;
  • Working Set is the non-paged Private Bytes plus memory-mapped files;
  • Virtual Bytes are the Working Set plus paged Private Bytes and standby list.

There's another problem here; just as shared libraries can allocate memory inside your application module, leading to potential false positives reported in your app's Private Bytes, your application may also end up allocating memory inside the shared modules, leading to false negatives. That means it's actually possible for your application to have a memory leak that never manifests itself in the Private Bytes at all. Unlikely, but possible.

Private Bytes are a reasonable approximation of the amount of memory your executable is using and can be used to help narrow down a list of potential candidates for a memory leak; if you see the number growing and growing constantly and endlessly, you would want to check that process for a leak. This cannot, however, prove that there is or is not a leak.

One of the most effective tools for detecting/correcting memory leaks in Windows is actually Visual Studio (link goes to page on using VS for memory leaks, not the product page). Rational Purify is another possibility. Microsoft also has a more general best practices document on this subject. There are more tools listed in this previous question.

I hope this clears a few things up! Tracking down memory leaks is one of the most difficult things to do in debugging. Good luck.

MySQL & Java - Get id of the last inserted value (JDBC)

Wouldn't you just change:

numero = stmt.executeUpdate(query);


numero = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);

Take a look at the documentation for the JDBC Statement interface.

Update: Apparently there is a lot of confusion about this answer, but my guess is that the people that are confused are not reading it in the context of the question that was asked. If you take the code that the OP provided in his question and replace the single line (line 6) that I am suggesting, everything will work. The numero variable is completely irrelevant and its value is never read after it is set.

Convert NSNumber to int in Objective-C

A less verbose approach:

int number = [dict[@"integer"] intValue];

How to save and load numpy.array() data properly?'data.npy', num_arr) # save
new_num_arr = np.load('data.npy') # load

Date difference in minutes in Python

The result depends on the timezone that corresponds to the input time strings.

The simplest case if both dates use the same utc offset:

#!/usr/bin/env python3
from datetime import datetime, timedelta

time_format = "%Y-%d-%m %H:%M:%S"
dt1 = datetime.strptime("2010-01-01 17:31:22", time_format)
dt2 = datetime.strptime("2010-01-03 17:31:22", time_format)
print((dt2 - dt1) // timedelta(minutes=1)) # minutes

If your Python version doesn't support td // timedelta; replace it with int(td.total_seconds() // 60).

If the input time is in the local timezone that might have different utc offset at different times e.g., it has daylight saving time then you should make dt1, dt2 into aware datetime objects before finding the difference, to take into account the possible changes in the utc offset.

The portable way to make an aware local datetime objects is to use pytz timezones:

#!/usr/bin/env python
from datetime import timedelta
import tzlocal # $ pip install tzlocal

local_tz = tzlocal.get_localzone() # get pytz timezone
aware_dt1, aware_dt2 = map(local_tz.localize, [dt1, dt2])
td  = aware_dt2 - aware_dt1 # elapsed time

If either dt1 or dt2 correspond to an ambiguous time then the default is_dst=False is used to disambiguate. You could set is_dst=None to raise an exception for ambiguous or non-existent local times instead.

If you can't install 3rd party modules then time.mktime() could be used from @Ken Cochrane's answer that can find the correct utc offset on some platforms for some dates in some timezones -- if you don't need a consistent (but perhaps wrong) result then it is much better than doing dt2 - dt1 with naive datetime objects that always fails if the corresponding utc offsets are different.

How to do IF NOT EXISTS in SQLite

How about this?


(Untested as I don't have SQLite... however this link is quite descriptive.)

Additionally, this should also work:

SELECT 'ANI Received'

How do I get the AM/PM value from a DateTime?

+ PC.GetHour(datetime) > 11 ? "pm" : "am"

For your example but there are better ways to format datetime.

Popup Message boxes

Use the following library: import javax.swing.JOptionPane;

Input at the top of the code-line. You must only add this, because the other things is done correctly!

JUnit assertEquals(double expected, double actual, double epsilon)

Epsilon is your "fuzz factor," since doubles may not be exactly equal. Epsilon lets you describe how close they have to be.

If you were expecting 3.14159 but would take anywhere from 3.14059 to 3.14259 (that is, within 0.001), then you should write something like

double myPi = 22.0d / 7.0d; //Don't use this in real life!
assertEquals(3.14159, myPi, 0.001);

(By the way, 22/7 comes out to 3.1428+, and would fail the assertion. This is a good thing.)

How do I create a branch?

If you're repo is available via https, you can use this command to branch ...

svn copy \ \
  -m "Creating a branch of project"

Run on server option not appearing in Eclipse

There is only 1 thing that fixed this for me. In the pom.xml, add the tag:


Then after saving that, when you right click on the project you should now see the "Run As... Run on Server" option showing up.

Stretch and scale CSS background

Use the background-size attribute in CSS3:

.class {
     background-image: url(bg.gif);
     background-size: 100%;

EDIT: Modernizr supports detection of background-size support. You can use a JavaScript workaround written to work however you need it and load it dynamically when there is no support. This will keep the code maintainable without resorting to intrusive CSS hacks for certain browsers.

Personally I use a script to deal with it using jQuery, its an adaption of imgsizer. As most designs I do now use width %'s for fluid layouts across devices there is a slight adaptation to one of the loops (accounting for sizes that aren't always 100%):

for (var i = 0; i < images.length; i++) {
    var image = images[i],
        width = String(image.currentStyle.width);

    if (width.indexOf('%') == -1) {

    image.origWidth = image.offsetWidth;
    image.origHeight = image.offsetHeight;

    c.ieAlpha(image); = width;

EDIT: You may also be interested in jQuery CSS3 Finaliz[s]e.

html text input onchange event

onChange doesn't fire until you lose focus later. If you want to be really strict with instantaneous changes of all sorts, use:

   type       = "text" 
   onchange   = "myHandler();"
   onkeypress = "this.onchange();"
   onpaste    = "this.onchange();"
   oninput    = "this.onchange();"

Classpath including JAR within a JAR

Well, there is a very easy way if you're using Eclipse.

Export your project as a "Runnable" Jar file (right-click project folder from within Eclipse, select "Export..."). When you configure the export settings, be sure to select "Extract required libraries into generated Jar." Keep in mind, select "Extract..." and not "Package required libraries...".

Additionally: You must select a run-configuration in your export settings. So, you could always create an empty main( ) in some class and use it for your run configuration.

Anyway, it isn't guaranteed to work 100% of the time - as you will notice a pop-up message telling you to make sure you check the licenses of the Jar files you're including and something about not copying signature files. However, I have been doing this for years and have never encountered a problem.

How do I format a number with commas in T-SQL?

  #            SQL Query Script                                            #
  #            ----------------                                            #
  # Funcion.:  dbo.fn_nDerecha ( Numero, Pos_Enteros, Pos_Decimales )      #
  #    Numero        : es el Numero o Valor a formatear                    #
  #    Pos_Enteros   : es la cantidad posiciones para Enteros              #
  #    Pos_Decimales : es la cantidad posiciones para Decimales            #
  #                                                                        #
  # OBJETIVO:  Formatear los Numeros con Coma y Justificado a la Derecha   #
  #  Por Ejemplo:                                                          #
  #   dbo.fn_nDerecha ( Numero, 9, 2 )         Resultado = ---,---,--9.99  #
  #               dado  Numero = 1234.56       Resultado =       1,234.56  #
  #               dado  Numero = -1.56         Resultado =          -1.56  #
  #               dado  Numero = -53783423.56  Resultado = -53,783,423.56  #
  #                                                                        #
  # Autor...:  Francisco Eugenio Cabrera Perez                             #
  # Fecha...:  Noviembre 25, 2015                                          #
  # Pais....:  Republica Dominicana                                        #

CREATE FUNCTION [dbo].[fn_nDerecha]
    -- Agregue Argumentos, para personalizar la funcion a su conveniencia
    @Numero_str    varchar(max)
   ,@Pos_Enteros   int
   ,@Pos_Decimales int
RETURNS varchar(max)
  --  Declare la variable del RETURN aqui, en este caso es RESULT
  declare @RESULTADO varchar(max)
  set     @RESULTADO = '****'

  -----------------------------------------------  --
  declare @Numero_num numeric(28,12)
  set     @Numero_num =
  case when isnumeric(@Numero_str) = 0 
       then 0
       else round (convert( numeric(28,12), @Numero_str), @Pos_Decimales)
  --  -----------------------------------------------  --
  --  Aumenta @Pos_Enteros de @RESULTADO,
  --      si las posiciones de Enteros del dato @Numero_str es Mayor...
  declare   @Num_Pos_Ent int
  set       @Num_Pos_Ent = len ( convert( varchar, convert(int, abs(@Numero_num) ) ) )
  declare   @Pos_Ent_Mas int
  set       @Pos_Ent_Mas =
  case when @Num_Pos_Ent > @Pos_Enteros
       then @Num_Pos_Ent - @Pos_Enteros
       else 0
  set       @Pos_Enteros = @Pos_Enteros + @Pos_Ent_Mas
  --  -----------------------------------------------  --
  declare @p_Signo_ctd       int
  set     @p_Signo_ctd       = (case when @Numero_num < 1 then 1 else 0 end)
  declare @p_Comas_ctd       int
  set     @p_Comas_ctd       = ( @Pos_Enteros - 1 ) / 3
  declare @p_Punto_ctd       int
  set     @p_Punto_ctd       = (case when @Pos_Decimales > 0 then 1 else 0 end)
  declare @p_input_Longitud  int
  set     @p_input_Longitud  = ( @p_Signo_ctd + @Pos_Enteros ) +
                                 @p_Punto_ctd + @Pos_Decimales
  declare @p_output_Longitud int
  set     @p_output_Longitud = ( @p_Signo_ctd + @Pos_Enteros   + @p_Comas_ctd )
                             + ( @p_Punto_ctd + @Pos_Decimales )
  --  ===================================================================  --

  declare @Valor_str varchar(max)
  set     @Valor_str = str(@Numero_num, @p_input_Longitud, @Pos_Decimales)

  declare @V_Ent_str varchar(max)
  set     @V_Ent_str = 
  (case when @Pos_Decimales > 0 
        then substring( @Valor_str, 0, charindex('.', @Valor_str, 0) )
        else            @Valor_str end)
  declare @V_Dec_str varchar(max)
  set     @V_Dec_str = 
  (case when @Pos_Decimales > 0 
        then '.' + right(@Valor_str, @Pos_Decimales)
        else '' end)
  set @V_Ent_str = convert(VARCHAR, convert(money, @V_Ent_str), 1) 
  set @V_Ent_str = substring( @V_Ent_str, 0, charindex('.', @V_Ent_str, 0) )

  set @RESULTADO    = @V_Ent_str + @V_Dec_str 
  set @RESULTADO = ( replicate( ' ', @p_output_Longitud - len(@RESULTADO) ) + @RESULTADO )

  --  ===================================================================  -

-- =================================================================== -


  --  ===================================================================  --

/* This function needs 3 arguments: the First argument is the @Numero_str which the Number as data input, and the other 2 arguments specify how the information will be formatted for the output, those arguments are @Pos_Enteros and @Pos_Decimales which specify how many Integers and Decimal places you want to show for the Number you pass as input argument. */

makefile execute another target

If you removed the make all line from your "fresh" target:

fresh :
    rm -f *.o $(EXEC)

You could simply run the command make fresh all, which will execute as make fresh; make all.

Some might consider this as a second instance of make, but it's certainly not a sub-instance of make (a make inside of a make), which is what your attempt seemed to result in.

How to prevent gcc optimizing some statements in C?

Turning off optimization fixes the problem, but it is unnecessary. A safer alternative is to make it illegal for the compiler to optimize out the store by using the volatile type qualifier.

// Assuming pageptr is unsigned char * already...
unsigned char *pageptr = ...;
((unsigned char volatile *)pageptr)[0] = pageptr[0];

The volatile type qualifier instructs the compiler to be strict about memory stores and loads. One purpose of volatile is to let the compiler know that the memory access has side effects, and therefore must be preserved. In this case, the store has the side effect of causing a page fault, and you want the compiler to preserve the page fault.

This way, the surrounding code can still be optimized, and your code is portable to other compilers which don't understand GCC's #pragma or __attribute__ syntax.

how to bold words within a paragraph in HTML/CSS?

Although your answer has many solutions I think this is a great way to save lines of code. Try using spans which is great for situations like yours.

  1. Create a class for making any item bold. So for paragraph text it would be
span.bold(This name can be anything do not include parenthesis) {
   font-weight: bold;
  1. In your html you can access that class like by using the span tags and adding a class of bold or whatever name you have chosen

Terminating a Java Program

What does return; mean?

return; really means it returns nothing void. That's it.

why return; or other codes can write below the statement of System.exit(0);

It is allowed since compiler doesn't know calling System.exit(0) will terminate the JVM. The compiler will just give a warning - unnecessary return statement

groovy: safely find a key in a map and return its value

The reason you get a Null Pointer Exception is because there is no key likesZZZ in your second example. Try:

def mymap = [name:"Gromit", likes:"cheese", id:1234]
def x = mymap.find{ it.key == "likes" }.value
    println "x value: ${x}"

Stratified Train/Test-split in scikit-learn

Here's an example for continuous/regression data (until this issue on GitHub is resolved).

min = np.amin(y)
max = np.amax(y)

# 5 bins may be too few for larger datasets.
bins     = np.linspace(start=min, stop=max, num=5)
y_binned = np.digitize(y, bins, right=True)

X_train, X_test, y_train, y_test = train_test_split(
  • Where start is min and stop is max of your continuous target.
  • If you don't set right=True then it will more or less make your max value a separate bin and your split will always fail because too few samples will be in that extra bin.

Powershell Active Directory - Limiting my get-aduser search to a specific OU [and sub OUs]

If I understand you correctly, you need to use -SearchBase:

Get-ADUser -SearchBase "OU=Accounts,OU=RootOU,DC=ChildDomain,DC=RootDomain,DC=com" -Filter *

Note that Get-ADUser defaults to using

 -SearchScope Subtree

so you don't need to specify it. It's this that gives you all sub-OUs (and sub-sub-OUs, etc.).

How to run or debug php on Visual Studio Code (VSCode)

To debug php with vscode,you need these things:

  1. vscode with php debuge plugin(XDebug) installed;
  2. php with downloaded and configured;
  3. a web server,such as apache/nginx or just nothing(use the php built-in server)

you can gently walk through step 1 and 2,by following the vscode official guide.It is fully recommended to use XDebug installation wizard to verify your XDebug configuration.

If you want to debug without a standalone web server,the php built-in maybe a choice.Start the built-in server by php -S localhost:port -t path/to/your/project command,setting your project dir as document root.You can refer to this post for more details.

Global Events in Angular

I'm using a message service that wraps an rxjs Subject (TypeScript)

Plunker example: Message Service

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/operator/filter'
import 'rxjs/add/operator/map'

interface Message {
  type: string;
  payload: any;

type MessageCallback = (payload: any) => void;

export class MessageService {
  private handler = new Subject<Message>();

  broadcast(type: string, payload: any) {{ type, payload });

  subscribe(type: string, callback: MessageCallback): Subscription {
    return this.handler
      .filter(message => message.type === type)
      .map(message => message.payload)

Components can subscribe and broadcast events (sender):

import { Component, OnDestroy } from '@angular/core'
import { MessageService } from './message.service'
import { Subscription } from 'rxjs/Subscription'

  selector: 'sender',
  template: ...
export class SenderComponent implements OnDestroy {
  private subscription: Subscription;
  private messages = [];
  private messageNum = 0;
  private name = 'sender'

  constructor(private messageService: MessageService) {
    this.subscription = messageService.subscribe(, (payload) => {

  send() {
    let payload = {
      text: `Message ${++this.messageNum}`,
    this.messageService.broadcast('receiver', payload);

  clear() {
    this.messages = [];

  ngOnDestroy() {


import { Component, OnDestroy } from '@angular/core'
import { MessageService } from './message.service'
import { Subscription } from 'rxjs/Subscription'

  selector: 'receiver',
  template: ...
export class ReceiverComponent implements OnDestroy {
  private subscription: Subscription;
  private messages = [];

  constructor(private messageService: MessageService) {
    this.subscription = messageService.subscribe('receiver', (payload) => {

  send(message: {text: string, respondEvent: string}) {
    this.messageService.broadcast(message.respondEvent, message.text);

  clear() {
    this.messages = [];

  ngOnDestroy() {

The subscribe method of MessageService returns an rxjs Subscription object, which can be unsubscribed from like so:

import { Subscription } from 'rxjs/Subscription';
export class SomeListener {
  subscription: Subscription;

  constructor(private messageService: MessageService) {
    this.subscription = messageService.subscribe('someMessage', (payload) => {

Also see this answer:

Plunker example: Message Service

How to select the first, second, or third element with a given class name?

Use CSS nth-child with the prefix class name

div.myclass:nth-child(1) {
  color: #000;

div.myclass:nth-child(2) {
  color: #FFF;

div.myclass:nth-child(3) {
  color: #006;

How do I get the key at a specific index from a Dictionary in Swift?

In Swift 3 try to use this code to get Key-Value Pair (tuple) at given index:

extension Dictionary {
    subscript(i:Int) -> (key:Key,value:Value) {
        get {
            return self[index(startIndex, offsetBy: i)];

Google Maps: How to create a custom InfoWindow?

I found InfoBox perfect for advanced styling.

An InfoBox behaves like a google.maps.InfoWindow, but it supports several additional properties for advanced styling. An InfoBox can also be used as a map label. An InfoBox also fires the same events as a google.maps.InfoWindow.

Include in your page

What key shortcuts are to comment and uncomment code?

From your screenshot it appears you have ReSharper installed.

Depending on the key binding options you chose when you installed it, some of your standard shortcuts may now be redirected to ReSharper commands. It's worth checking, for example Ctrl+E, C is used by R# for the code cleanup dialog.

How to set ID using javascript?

Do you mean like this?

var hello1 = document.getElementById('hello1'); = btoa(;

To further the example, say you wanted to get all elements with the class 'abc'. We can use querySelectorAll() to accomplish this:


<div class="abc"></div>
<div class="abc"></div>


var abcElements = document.querySelectorAll('.abc');

// Set their ids
for (var i = 0; i < abcElements.length; i++)
    abcElements[i].id = 'abc-' + i;

This will assign the ID 'abc-<index number>' to each element. So it would come out like this:

<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>

To create an element and assign an id we can use document.createElement() and then appendChild().

var div = document.createElement('div'); = 'hello1';

var body = document.querySelector('body');


You can set the id on your element like this if your script is in your HTML file.

<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">

<script type="text/javascript">
    var s = document.getElementsByClassName('assign-me')[0]; = btoa({{str(produit["avt"]["fto"])}});

Your requirements still aren't 100% clear though.

MVC 4 Razor adding input type date

You will get it by tag type="date"...then it will render beautiful calendar and all...

@Html.TextBoxFor(model => model.EndTime, new { type = "date" })

How to select distinct query using symfony2 doctrine query builder?

This works:

$category = $catrep->createQueryBuilder('cc')
        ->where('cc.contenttype = :type')
        ->setParameter('type', 'blogarticle')

$categories = $category->getResult();

Edit for Symfony 3 & 4.

You should use ->groupBy('cc.categoryid') instead of ->distinct()

How to find the size of integer array

If array is static allocated:

size_t size = sizeof(arr) / sizeof(int);

if array is dynamic allocated(heap):

int *arr = malloc(sizeof(int) * size);

where variable size is a dimension of the arr.

How can I match a string with a regex in Bash?

A Function To Do This

extract () {
  if [ -f $1 ] ; then
      case $1 in
          *.tar.bz2)   tar xvjf $1    ;;
          *.tar.gz)    tar xvzf $1    ;;
          *.bz2)       bunzip2 $1     ;;
          *.rar)       rar x $1       ;;
          *.gz)        gunzip $1      ;;
          *.tar)       tar xvf $1     ;;
          *.tbz2)      tar xvjf $1    ;;
          *.tgz)       tar xvzf $1    ;;
          *.zip)       unzip $1       ;;
          *.Z)         uncompress $1  ;;
          *.7z)        7z x $1        ;;
          *)           echo "don't know '$1'..." ;;
      echo "'$1' is not a valid file!"

Other Note

In response to Aquarius Power in the comment above, We need to store the regex on a var

The variable BASH_REMATCH is set after you match the expression, and ${BASH_REMATCH[n]} will match the nth group wrapped in parentheses ie in the following ${BASH_REMATCH[1]} = "compressed" and ${BASH_REMATCH[2]} = ".gz"

if [[ "compressed.gz" =~ ^(.*)(\.[a-z]{1,5})$ ]]; 
  echo ${BASH_REMATCH[2]} ; 
  echo "Not proper format"; 

(The regex above isn't meant to be a valid one for file naming and extensions, but it works for the example)

PHP Session data not being saved

Another few things I had to do (I had same problem: no sesson retention after PHP upgrade to 5.4). You many not need these, depending on what your server's php.ini contains (check phpinfio());

session.use_trans_sid=0 ; Do not add session id to URI (osc does this)
session.use_cookies=0;  ; ensure cookies are not used
session.use_only_cookies=0 ; ensure sessions are OK to use IMPORTANT
session.save_path=~/tmp/osc; ; Set to same as admin setting
session.auto_start = off; Tell PHP not to start sessions, osc code will do this

Basically, your php.ini should be set to no cookies, and session parameters must be consistent with what osc wants.

You may also need to change a few session code snippets in application_top.php - creating objects where none exist in the tep_session_is_registered(...) calls (e eg. navigation object), set $HTTP_ variables to the newer $_SERVER ones and a few other isset tests for empty objects (google for info). I ended up being able to use the original sessions.php files (includes/classes and includes/functions) with a slightly modified application_top.php to get things going again. The php.ini settings were the main problem, but this of course depends on what your server company has installed as the defaults.

Can we use JSch for SSH key-based communication?

It is possible. Have a look at JSch.addIdentity(...)

This allows you to use key either as byte array or to read it from file.

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class UserAuthPubKey {
    public static void main(String[] arg) {
        try {
            JSch jsch = new JSch();

            String user = "tjill";
            String host = "";
            int port = 10022;
            String privateKey = ".ssh/id_rsa";

            System.out.println("identity added ");

            Session session = jsch.getSession(user, host, port);
            System.out.println("session created.");

            // disabling StrictHostKeyChecking may help to make connection but makes it insecure
            // see
            // java.util.Properties config = new java.util.Properties();
            // config.put("StrictHostKeyChecking", "no");
            // session.setConfig(config);

            System.out.println("session connected.....");

            Channel channel = session.openChannel("sftp");
            System.out.println("shell channel connected....");

            ChannelSftp c = (ChannelSftp) channel;

            String fileName = "test.txt";
            c.put(fileName, "./in/");

        } catch (Exception e) {

How can you print a variable name in python?

Rather than ask for details to a specific solution, I recommend describing the problem you face; I think you'll get better answers. I say this since there's almost certainly a better way to do whatever it is you're trying to do. Accessing variable names in this way is not commonly needed to solve problems in any language.

That said, all of your variable names are already in dictionaries which are accessible through the built-in functions locals and globals. Use the correct one for the scope you are inspecting.

One of the few common idioms for inspecting these dictionaries is for easy string interpolation:

>>> first = 'John'
>>> last = 'Doe'
>>> print '%(first)s %(last)s' % globals()
John Doe

This sort of thing tends to be a bit more readable than the alternatives even though it requires inspecting variables by name.

Using scanner.nextLine()

I think your problem is that

int selection = scanner.nextInt();

reads just the number, not the end of line or anything after the number. When you declare

String sentence = scanner.nextLine();

This reads the remainder of the line with the number on it (with nothing after the number I suspect)

Try placing a scanner.nextLine(); after each nextInt() if you intend to ignore the rest of the line.

Fling gesture detection on grid layout

There's a built-in interface that you can use directly for all gestures:
Here is an explanation for a basic level user: enter image description here There is 2 imports be careful in choosing that both are diferent enter image description here enter image description here

Play/pause HTML 5 video using JQuery

Your solution shows the issue here -- play is not a jQuery function but a function of the DOM element. You therefore need to call it upon the DOM element. You give an example of how to do this with the native DOM functions. The jQuery equivalent -- if you wanted to do this to fit in with an existing jQuery selection -- would be $('#videoId').get(0).play(). (get gets the native DOM element from the jQuery selection.)

How to call function on child component on parent events

The below example is self explainatory. where refs and events can be used to call function from and to parent and child.

    <button @click="callChild">Call Method in child</button>

export default {
  methods: {
    callChild() {
      this.$refs.childRef.childMethod('Hi from parent');
    childCallBack(message) {
      console.log('message from child', message);

    <button @click="callParent">Call Parent</button>

export default {
  methods: {
    callParent() {
      this.$emit('onChange', 'hi from child');
    childMethod(message) {
      console.log('message from parent', message);

Not class selector in jQuery

You can use the :not filter selector:


Or not() method:


More Info:

MySQL order by before group by

Just to recap, the standard solution uses an uncorrelated subquery and looks like this:

  FROM my_table x
  JOIN (SELECT grouping_criteria,MAX(ranking_criterion) max_n FROM my_table GROUP BY grouping_criteria) y
    ON y.grouping_criteria = x.grouping_criteria
   AND y.max_n = x.ranking_criterion;

If you're using an ancient version of MySQL, or a fairly small data set, then you can use the following method:

  FROM my_table x
  JOIN my_table y
    ON y.joining_criteria = x.joining_criteria
   AND y.ranking_criteria < x.ranking_criteria
 WHERE y.some_non_null_column IS NULL;  

How to view transaction logs in SQL Server 2008

You can't read the transaction log file easily because that's not properly documented. There are basically two ways to do this. Using undocumented or semi-documented database functions or using third-party tools.

Note: This only makes sense if your database is in full recovery mode.

SQL Functions:

DBCC LOG and fn_dblog - more details here and here.

Third-party tools:

Toad for SQL Server and ApexSQL Log.

You can also check out several other topics where this was discussed:

How to print instances of a class using print()?

A generic way that can be applied to any class without specific formatting could be done as follows:

class Element:
    def __init__(self, name, symbol, number): = name
        self.symbol = symbol
        self.number = number

    def __str__(self):
        return str(self.__class__) + ": " + str(self.__dict__)

And then,

elem = Element('my_name', 'some_symbol', 3)


__main__.Element: {'symbol': 'some_symbol', 'name': 'my_name', 'number': 3}

html5 <input type="file" accept="image/*" capture="camera"> display as image rather than "choose file" button

You have to use Javascript Filereader for this. (Introduction into filereader-api:

Once the user have choose a image you can read the file-path of the chosen image and place it into your html.


<form id="form1" runat="server">
    <input type='file' id="imgInp" />
    <img id="blah" src="#" alt="your image" />


function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {



Drop-down box dependent on the option selected in another drop-down box

Try something like this... jsfiddle demo


<!-- Source: -->
<select id="source" name="source">

<!-- Status: -->
<select id="status" name="status">


$(document).ready(function () {

    $("#source").change(function () {
        var el = $(this);
        if (el.val() === "ONLINE") {
        } else if (el.val() === "MANUAL") {
            $("#status option:last-child").remove();


Go to particular revision

You can get a graphical view of the project history with tools like gitk. Just run:

gitk --all

If you want to checkout a specific branch:

git checkout <branch name>

For a specific commit, use the SHA1 hash instead of the branch name. (See Treeishes in the Git Community Book, which is a good read, to see other options for navigating your tree.)

git log has a whole set of options to display detailed or summary history too.

I don't know of an easy way to move forward in a commit history. Projects with a linear history are probably not all that common. The idea of a "revision" like you'd have with SVN or CVS doesn't map all that well in Git.

how to open a jar file in Eclipse

Since the jar file 'executes' then it contains compiled java files known as .class files. You cannot import it to eclipse and modify the code. You should ask the supplier of the "demo" for the "source code". (or check the page you got the demo from for the source code)

Unless, you want to decompile the .class files and import to Eclipse. That may not be the case for starters.

Youtube API Limitations

Version 3 of the YouTube Data API has concrete quota numbers listed in the Google API Console where you register for your API Key. You can use 10,000 units per day. Projects that had enabled the YouTube Data API before April 20, 2016, have a default quota of 50M/day.

You can read about what a unit is here:

  • A simple read operation that only retrieves the ID of each returned resource has a cost of approximately 1 unit.
  • A write operation has a cost of approximately 50 units.
  • A video upload has a cost of approximately 1600 units.

If you hit the limits, Google will stop returning results until your quota is reset. You can apply for more than 1M requests per day, but you will have to pay for those extra requests.

Also, you can read about why Google has deferred support to StackOverflow on their YouTube blog here:

There are a number of active members on the YouTube Developer Relations team here including Jeff Posnick, Jarek Wilkiewicz, and Ibrahim Ulukaya who all have knowledge of Youtube internals...

UPDATE: Increased the quota numbers to reflect current limits on December 10, 2013.

UPDATE: Decreased the quota numbers from 50M to 1M per day to reflect current limits on May 13, 2016.

UPDATE: Decreased the quota numbers from 1M to 10K per day as of January 11, 2019.

How to use GROUP_CONCAT in a CONCAT in MySQL

IF OBJECT_ID('master..test') is not null Drop table test

INSERT INTO test VALUES (1, 'A', 4);
INSERT INTO test VALUES (1, 'A', 5);
INSERT INTO test VALUES (1, 'B', 8);
INSERT INTO test VALUES (2, 'C', 9);

select distinct NAME , LIST = Replace(Replace(Stuff((select ',', +Value from test where name = for xml path('')), 1,1,''),'<Value>', ''),'</Value>','') from test _a order by 1 desc

My table name is test , and for concatination I use the For XML Path('') syntax. The stuff function inserts a string into another string. It deletes a specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.

STUFF functions looks like this : STUFF (character_expression , start , length ,character_expression )

character_expression Is an expression of character data. character_expression can be a constant, variable, or column of either character or binary data.

start Is an integer value that specifies the location to start deletion and insertion. If start or length is negative, a null string is returned. If start is longer than the first character_expression, a null string is returned. start can be of type bigint.

length Is an integer that specifies the number of characters to delete. If length is longer than the first character_expression, deletion occurs up to the last character in the last character_expression. length can be of type bigint.

How to tell bash that the line continues on the next line

In general, you can use a backslash at the end of a line in order for the command to continue on to the next line. However, there are cases where commands are implicitly continued, namely when the line ends with a token than cannot legally terminate a command. In that case, the shell knows that more is coming, and the backslash can be omitted. Some examples:

# In general
$ echo "foo" \
> "bar"
foo bar

# Pipes
$ echo foo |
> cat

# && and ||
$ echo foo &&
> echo bar
$ false ||
> echo bar

Different, but related, is the implicit continuation inside quotes. In this case, without a backslash, you are simply adding a newline to the string.

$ x="foo
> bar"
$ echo "$x"

With a backslash, you are again splitting the logical line into multiple logical lines.

$ x="foo\
> bar"
$ echo "$x"

How to show all of columns name on pandas dataframe?

In the interactive console, it's easy to do:


Or this within a script:


Flask Error: "Method Not Allowed The method is not allowed for the requested URL"

What is happening here is that database route does not accept any url methods.

I would try putting the url methods in the app route just like you have in the entry_page function:

@app.route('/entry', methods=['GET', 'POST'])
def entry_page():
    if request.method == 'POST':
        date = request.form['date']
        title = request.form['blog_title']
        post = request.form['blog_main']
        post_entry = models.BlogPost(date = date, title = title, post = post)
        return redirect(url_for('database'))
        return render_template('entry.html')

@app.route('/database', methods=['GET', 'POST'])        
def database():
    query = []
    for i in session.query(models.BlogPost):
    return render_template('database.html', query = query)

How can I check if PostgreSQL is installed or not via Linux script?

If it is debian based.

aptitude show postgresql | grep State

But I guess you can just try to launch it with some flag like --version, that simply prints some info and exits.

Updated using "service postgres status". Try:

service postgres status
if [ "$?" -gt "0" ]; then
  echo "Not installed".
  echo "Intalled"

Oracle - How to generate script from sql developer

If you want to see DDL for the objects, you can use

select dbms_metadata.get_ddl('OBJECT_TYPE','OBJECT_NAME','OBJECT_OWNER') 
  from dual

For example this will give you the DDL script for emp table.

select dbms_metadata.get_ddl('TABLE','EMP','HR') 
  from dual

You may need to set the long type format to big number. For packages, you need to access dba_source, user_source, all_source tables. You can query for object name and type to see what code is stored.

Error: macro names must be identifiers using #ifdef 0

Use the following to evaluate an expression (constant 0 evaluates to false).

#if 0

Postgres integer arrays as parameters?

You can always use a properly formatted string. The trick is the formatting.

command.Parameters.Add("@array_parameter", string.Format("{{{0}}}", string.Join(",", array));

Note that if your array is an array of strings, then you'll need to use array.Select(value => string.Format("\"{0}\", value)) or the equivalent. I use this style for an array of an enumerated type in PostgreSQL, because there's no automatic conversion from the array.

In my case, my enumerated type has some values like 'value1', 'value2', 'value3', and my C# enumeration has matching values. In my case, the final SQL query ends up looking something like (E'{"value1","value2"}'), and this works.

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

If you want to bypass that restriction when fetching the contents with fetch API or XMLHttpRequest in javascript, you can use a proxy server so that it sets the header Access-Control-Allow-Origin to *.

const express = require('express');
const request = require('request');

const app = express();

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');

app.get('/fetch', (req, res) => {
    { url: req.query.url },
    (error, response, body) => {
      if (error || response.statusCode !== 200) {
        return res.status(500).send('error');

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`listening on ${PORT}`));

Above is a sample code( node Js required ) which can act as a proxy server. For eg: If I want to fetch normally a CORS error is thrown, but now since the request is sent through the proxy server hosted locally at port 3000, the proxy server adds the Access-Control-Allow-Origin header in the response and there wont be any issue.

Send a GET request to http://localhost:3000/fetch?url=Your URL here , instead of directly sending the request to the URl you want to fetch.

Your URL here stands for the URL you wish to fetch eg:

How to make RatingBar to show five stars


Configure the number of Stars in the XML file... No need to provide it in Styles or Activity/Fragment .... IMPORTANT: Make sure you Put the WIDTH as Wrap content and weights are not enabled

System.Collections.Generic.IEnumerable' does not contain any definition for 'ToList'

In my case, I had copied some code from another project that was using Automapper - took me ages to work that one out. Just had to add automapper nuget package to project.

how to change text box value with jQuery?

Try this out:

  $(document).ready(function() {
    $("#button-id").click(function() {

How to display table data more clearly in oracle sqlplus

You can set the line size as per the width of the window and set wrap off using the following command.

set linesize 160;
set wrap off;

I have used 160 as per my preference you can set it to somewhere between 100 - 200 and setting wrap will not your data and it will display the data properly.

Launch Failed. Binary not found. CDT on Eclipse Helios

My problem was the same as one commenter above. I had to change the binary parser to the correct one (PE for windows, ELF for Linux, mach for mac)

Remove empty array elements

I think array_walk is much more suitable here

$linksArray = array('name', '        ', '  342', '0', 0.0, null, '', false);

array_walk($linksArray, function(&$v, $k) use (&$linksArray){
    $v = trim($v);
    if ($v == '')


    [0] => name
    [2] => 342
    [3] => 0
    [4] => 0
  • We made sure that empty values are removed even if the user adds more than one space

  • We also trimmed empty spaces from the valid values

  • Finally, only (null), (Boolean False) and ('') will be considered empty strings

As for False it's ok to remove it, because AFAIK the user can't submit boolean values.

PHP - warning - Undefined property: stdClass - fix?

Depending on whether you're looking for a member or method, you can use either of these two functions to see if a member/method exists in a particular object:

More generally if you want all of them:

How can I solve Exception in thread "main" java.lang.NullPointerException error

This is the problem

double a[] = null;

Since a is null, NullPointerException will arise every time you use it until you initialize it. So this:

a[i] = var;

will fail.

A possible solution would be initialize it when declaring it:

double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7

IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.


This exception means there's a variable with null value being used. How to solve? Just make sure the variable is not null before being used.

at twoten.TwoTenB.(

This line has two parts:

  • First, shows the class and method where the error was thrown. In this case, it was at <init> method in class TwoTenB declared in package twoten. When you encounter an error message with SomeClassName.<init>, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).
  • Secondly, shows the file and line number location where the error is thrown, which is between parenthesis. This way is easier to spot where the error arose. So you have to look into file, line number 29. This seems to be a[i] = var;.

From this line, other lines will be similar to tell you where the error arose. So when reading this:

at javapractice.JavaPractice.main(

It means that you were trying to instantiate a TwoTenB object reference inside the main method of your class JavaPractice declared in javapractice package.

How to automatically close cmd window after batch file execution?

You normally end a batch file with a line that just says exit. If you want to make sure the file has run and the DOS window closes after 2 seconds, you can add the lines:

timeout 2 >nul

But the exit command will not work if your batch file opens another window, because while ever the second window is open the old DOS window will also be displayed.

SOLUTION: For example there's a great little free program called BgInfo which will display all the info about your computer. Assuming it's in a directory called C:\BgInfo, to run it from a batch file with the /popup switch and to close the DOS window while it still runs, use:

start "" "C:\BgInfo\BgInfo.exe" /popup

HTML inside Twitter Bootstrap popover

I really hate to put long HTML inside of the attribute, here is my solution, clear and simple (replace ? with whatever you want):

<a class="btn-lg popover-dismiss" data-placement="bottom" data-toggle="popover" title="Help">
    <h2>Some title</h2>
    Some text


var help = $('.popover-dismiss');
help.attr('data-content', help.html()).text(' ? ').popover({trigger: 'hover', html: true});

HTML Input="file" Accept Attribute File Type (CSV)

After my test, on ?macOS 10.15.7 Catalina?, the answer of ?Dom / Rikin Patel? cannot recognize the [.xlsx] file normally.

I personally summarized the practice of most of the existing answers and passed personal tests. Sum up the following answers:

accept=".csv, .xls, .xlsx, text/csv, application/csv,
text/comma-separated-values, application/csv, application/excel,
application/vnd.msexcel, text/anytext, application/vnd. ms-excel,

URL for public Amazon S3 bucket

The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.

Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.

If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either or

The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].

S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.

If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.

However... the two endpoints do not offer the same functionality.

Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.

Choose the correct type of endpoint (REST or web site) for your application:

¹ has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2 had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1 so s3-external-2 appears to have no purpose except backwards-compatibility.

How to get the latest file in a folder?

I lack the reputation to comment but ctime from Marlon Abeykoons response did not give the correct result for me. Using mtime does the trick though. (key=os.path.getmtime))

import glob
import os

list_of_files = glob.glob('/path/to/folder/*') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getmtime)
print latest_file

I found two answers for that problem:

python os.path.getctime max does not return latest Difference between python - getmtime() and getctime() in unix system

Deploying just HTML, CSS webpage to Tomcat

Here's my step in Ubuntu 16.04 and Tomcat 8.

  1. Copy folder /var/lib/tomcat8/webapps/ROOT to your folder.

    cp -r /var/lib/tomcat8/webapps/ROOT /var/lib/tomcat8/webapps/{yourfolder}

  2. Add your html, css, js, to your folder.

  3. Open "http://localhost:8080/{yourfolder}" in browser


  1. If you using chrome web browser and did wrong folder before, then clean web browser's cache(or change another name) otherwise (sometimes) it always 404.

  2. The folder META-INF with context.xml is needed.

Receiving "fatal: Not a git repository" when attempting to remote add a Git repo

in my case, i had the same problem while i try any git -- commands (eg git status) using windows cmd. so what i do is after installing git for window in the environmental variables, add the class path of the git on the "PATH" varaiable. usually the git will installed on C:/user/"username"/appdata/local/git/bin add this on the PATH in the environmental variable

and one more thing on the cmd go to your git repository or cd to where your clone are on your window usually they will be stored on the documents under github cd Document/Github/yourproject after that you can have any git commands

thank you

How to extract HTTP response body from a Python requests call?

import requests

site_request = requests.get("")

site_response = str(site_request.content)


You can do it either way.

Could not load file or assembly 'System.Web.Mvc'

In addition to the Haack post, Hanselman also has a similar post. BIN Delploying ASP.NET MVC 3 with Razor to a Windows Server without MVC installed

For me, the "Copy Local = true" solution was insufficient because my Website's project references did not include all the dlls that were missing. As Scott mentions in his post, I also needed to get additional dlls from the following folder on my development box: C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies. The error message informed me which dll was missing (System.Web.Infrastructure, System.Web.Razor, etc.) I continued to add each missing dll, one by one, until it worked.

Pythonic way to combine FOR loop and IF statement

Use intersection or intersection_update

  • intersection :

    a = [2,3,4,5,6,7,8,9,0]
    xyz = [0,12,4,6,242,7,9]
    ans = sorted(set(a).intersection(set(xyz)))
  • intersection_update:

    a = [2,3,4,5,6,7,8,9,0]
    xyz = [0,12,4,6,242,7,9]
    b = set(a)

    then b is your answer

sql query to return differences between two tables

Presenting the Cadillac of Diffs as an SP. See within for the basic template that was based on answer by @erikkallen. It supports

  • Duplicate row sensing (most other answers here do not)
  • Sort results by argument
  • Limit to specific columns
  • Ignore columns (e.g. ModifiedUtc)
  • Cross database tables names
  • Temp tables (use as workaround to diff views)


exec Common.usp_DiffTableRows '#t1', '#t2';

exec Common.usp_DiffTableRows 
    @pTable0          = 'ydb.ysh.table1',
    @pTable1          = 'xdb.xsh.table2',
    @pOrderByCsvOpt   = null,  -- Order the results
    @pOnlyCsvOpt      = null,  -- Only compare these columns
    @pIgnoreCsvOpt    = null;  -- Ignore these columns (ignored if @pOnlyCsvOpt is specified)


alter proc [Common].[usp_DiffTableRows]    
    @pTable0          varchar(300),
    @pTable1          varchar(300),
    @pOrderByCsvOpt   nvarchar(1000) = null,  -- Order the Results
    @pOnlyCsvOpt      nvarchar(4000) = null,  -- Only compare these columns
    @pIgnoreCsvOpt    nvarchar(4000) = null,  -- Ignore these columns (ignored if @pOnlyCsvOpt is specified)
    @pDebug           bit = 0
    Purpose:  Compare rows between two tables.

      Usage:  exec Common.usp_DiffTableRows '#a', '#b';

    Modified    By          Description
    ----------  ----------  -------------------------------------------------------------------------------------------
    2015.10.06  crokusek    Initial Version
    2019.03.13  crokusek    Added @pOrderByCsvOpt
    2019.06.26  crokusek    Support for @pIgnoreCsvOpt, @pOnlyCsvOpt.    
    2019.09.04  crokusek    Minor debugging improvement
    2020.03.12  crokusek    Detect duplicate rows in either source table
begin try

    if (substring(@pTable0, 1, 1) = '#')
        set @pTable0 = 'tempdb..' + @pTable0; -- object_id test below needs full names for temp tables

    if (substring(@pTable1, 1, 1) = '#')
        set @pTable1 = 'tempdb..' + @pTable1; -- object_id test below needs full names for temp tables

    if (object_id(@pTable0) is null)
        raiserror('Table name is not recognized: ''%s''', 16, 1, @pTable0);

    if (object_id(@pTable1) is null)
        raiserror('Table name is not recognized: ''%s''', 16, 1, @pTable1);

    create table #ColumnGathering
        Name nvarchar(300) not null,
        Sequence int not null,
        TableArg tinyint not null

        @usp          varchar(100) = object_name(@@procid),    
        @sql          nvarchar(4000),
        @sqlTemplate  nvarchar(4000) = 
            use $database$;

            insert into #ColumnGathering
            select Name, column_id as Sequence, $TableArg$ as TableArg
              from sys.columns c
             where object_id = object_id(''$table$'', ''U'')

    set @sql = replace(replace(replace(@sqlTemplate,
        '$TableArg$', 0),
        '$database$', (select DatabaseName from Common.ufn_SplitDbIdentifier(@pTable0))),
        '$table$', @pTable0);

    if (@pDebug = 1)
        print 'Sql #CG 0: ' + @sql;

    exec sp_executesql @sql;

    set @sql = replace(replace(replace(@sqlTemplate,
        '$TableArg$', 1),
        '$database$', (select DatabaseName from Common.ufn_SplitDbIdentifier(@pTable1))),
        '$table$', @pTable1);

    if (@pDebug = 1)
        print 'Sql #CG 1: ' + @sql;

    exec sp_executesql @sql;

    if (@pDebug = 1)
        select * from #ColumnGathering;

    select Name, 
           min(Sequence) as Sequence, 
           convert(bit, iif(min(TableArg) = 0, 1, 0)) as InTable0,
           convert(bit, iif(max(TableArg) = 1, 1, 0)) as InTable1
      into #Columns
      from #ColumnGathering
     group by Name
    having (     @pOnlyCsvOpt is not null 
             and Name in (select Value from Common.ufn_UsvToNVarcharKeyTable(@pOnlyCsvOpt, default)))
           (     @pOnlyCsvOpt is null
             and @pIgnoreCsvOpt is not null 
             and Name not in (select Value from Common.ufn_UsvToNVarcharKeyTable(@pIgnoreCsvOpt, default)))
           (     @pOnlyCsvOpt is null
             and @pIgnoreCsvOpt is null)

    if (exists (select 1 from #Columns where InTable0 = 0 or InTable1 = 0))
        select 1; -- without this the debugging info doesn't stream sometimes
        select * from #Columns order by Sequence;        
        waitfor delay '00:00:02';  -- give results chance to stream before raising exception
        raiserror('Columns are not equal between tables, consider using args @pIgnoreCsvOpt, @pOnlyCsvOpt.  See Result Sets for details.', 16, 1);    

    if (@pDebug = 1)
        select * from #Columns order by Sequence;

        @columns nvarchar(4000) = --iif(@pOnlyCsvOpt is null and @pIgnoreCsvOpt is null,
           -- '*',     
              select substring((select ',' +
                from #Columns ac
               order by Sequence
                 for xml path('')),2,200000) as csv

    if (@pDebug = 1)
        print 'Columns: ' + @columns;
        waitfor delay '00:00:02';  -- give results chance to stream before possibly raising exception

    -- Based on
    --     - Added sensing for duplicate rows
    --     - Added reporting of source table location
    set @sqlTemplate = '
               a as (select ~, Row_Number() over (partition by ~ order by (select null)) -1 as Duplicates from $a$), 
               b as (select ~, Row_Number() over (partition by ~ order by (select null)) -1 as Duplicates from $b$)
            select 0 as SourceTable, ~
                   select * from a
                   select * from b
                 )  anb
              union all
             select 1 as SourceTable, ~
                   select * from b
                   select * from a
                 )  bna
             order by $orderBy$

     set @sql = replace(replace(replace(replace(@sqlTemplate, 
            '$a$', @pTable0), 
            '$b$', @pTable1),
            '~', @columns),
            '$orderBy$', coalesce(@pOrderByCsvOpt, @columns + ', SourceTable')

     if (@pDebug = 1)
        print 'Sql: ' + @sql;

     exec sp_executesql @sql;

end try
begin catch
        @CatchingUsp  varchar(100) = object_name(@@procid);    

    if (xact_state() = -1)

    -- Disabled for S.O. post

    --exec Common.usp_Log
        --@pMethod = @CatchingUsp;

    --exec Common.usp_RethrowError        
        --@pCatchingMethod = @CatchingUsp;

end catch

create function Common.Trim
    @pOriginalString nvarchar(max), 
    @pCharsToTrim nvarchar(50) = null -- specify null or 'default' for whitespae 
returns table
with schemabinding
    Purpose:   Trim the specified characters from a string.

    Modified    By              Description
    ----------  --------------  --------------------------------------------------------------------
    2012.09.25  S.Rutszy/crok   Modified from    
with cte AS
  select patindex(N'%[^' + EffCharsToTrim + N']%', @pOriginalString) AS [FirstChar],
         patindex(N'%[^' + EffCharsToTrim + N']%', reverse(@pOriginalString)) AS [LastChar],
         len(@pOriginalString + N'~') - 1 AS [ActualLength]
         select EffCharsToTrim = coalesce(@pCharsToTrim, nchar(0x09) + nchar(0x20) + nchar(0x0d) + nchar(0x0a))
   ) c
select substring(@pOriginalString, [FirstChar],
                 ((cte.[ActualLength] - [LastChar]) - [FirstChar] + 2)
       ) AS [TrimmedString]
       --((cte.[ActualLength] - [LastChar]) + 1) AS [LastChar]              
from cte;

create function [Common].[ufn_UsvToNVarcharKeyTable] (
    @pCsvList     nvarchar(MAX),
    @pSeparator   nvarchar(1) = ','       -- can pass keyword 'default' when calling using ()'s
    -- SQL Server 2012 distinguishes nvarchar keys up to maximum of 450 in length (900 bytes)
    returns @tbl table (Value nvarchar(450) not null primary key(Value)) as
    Purpose:  Converts a comma separated list of strings into a sql NVarchar table.  From


              This may be called from RunSelectQuery:

                  GRANT SELECT ON Common.ufn_UsvToNVarcharTable TO MachCloudDynamicSql;

    Modified    By              Description
    ----------  --------------  -------------------------------------------------------------------
    2011.07.13  internet        Initial version
    2011.11.22  crokusek        Support nvarchar strings and a custom separator.
    2017.12.06  crokusek        Trim leading and trailing whitespace from each element.
    2019.01.26  crokusek        Remove newlines
        @pos      int,
        @textpos  int,
        @chunklen smallint,
        @str      nvarchar(4000),
        @tmpstr   nvarchar(4000),
        @leftover nvarchar(4000),
        @csvList nvarchar(max) = iif(@pSeparator not in (char(13), char(10), char(13) + char(10)),
            replace(replace(@pCsvList, char(13), ''), char(10), ''),
            @pCsvList); -- remove newlines

    set @textpos = 1
    set @leftover = ''  
    while @textpos <= len(@csvList)
        set @chunklen = 4000 - len(@leftover)
        set @tmpstr = ltrim(@leftover + substring(@csvList, @textpos, @chunklen))
        set @textpos = @textpos + @chunklen

        set @pos = charindex(@pSeparator, @tmpstr)
        while @pos > 0
            set @str = substring(@tmpstr, 1, @pos - 1)
            set @str = (select TrimmedString from Common.Trim(@str, default));
            insert @tbl (value) values(@str);
            set @tmpstr = ltrim(substring(@tmpstr, @pos + 1, len(@tmpstr)))
            set @pos = charindex(@pSeparator, @tmpstr)

        set @leftover = @tmpstr

    -- Handle @leftover

    set @str = (select TrimmedString from Common.Trim(@leftover, default));

    if @str <> ''
       insert @tbl (value) values(@str);


create function Common.ufn_SplitDbIdentifier(@pIdentifier nvarchar(300))
returns @table table 
    InstanceName          nvarchar(300) not null,
    DatabaseName          nvarchar(300) not null,
    SchemaName            nvarchar(300),
    BaseName              nvarchar(300) not null,
    FullTempDbBaseName    nvarchar(300),            -- non-null for tempdb (e.g. #Abc____...)
    InstanceWasSpecified  bit not null,
    DatabaseWasSpecified  bit not null,
    SchemaWasSpecified    bit not null,
    IsCurrentInstance     bit not null,
    IsCurrentDatabase     bit not null,
    IsTempDb              bit not null,
    OrgIdentifier         nvarchar(300) not null
) as
    Purpose:  Split a Sql Server Identifier into its parts, providing appropriate default values and
              handling temp table (tempdb) references.

    Example:  select * from Common.ufn_SplitDbIdentifier('t')
              union all
              select * from Common.ufn_SplitDbIdentifier('s.t')
              union all
              select * from Common.ufn_SplitDbIdentifier('d.s.t')
              union all
              select * from Common.ufn_SplitDbIdentifier('i.d.s.t')
              union all
              select * from Common.ufn_SplitDbIdentifier('#d')
              union all
              select * from Common.ufn_SplitDbIdentifier('tempdb..#d'); 

              -- Empty
              select * from Common.ufn_SplitDbIdentifier('illegal name'); 

    Modified    By              Description
    ----------  --------------  -----------------------------------------------------------------------------
    2013.09.27  crokusek        Initial version.  
        @name nvarchar(300) = ltrim(rtrim(@pIdentifier));

    -- Return an empty table as a "throw"
    --Removed for SO post
    --if (Common.ufn_IsSpacelessLiteralIdentifier(@name) = 0)
      --  return;

    -- Find dots starting from the right by reversing first.

        @revName nvarchar(300) = reverse(@name);

        @firstDot int = charindex('.', @revName);

        @secondDot  int = iif(@firstDot = 0,  0, charindex('.', @revName, @firstDot + 1));

        @thirdDot   int = iif(@secondDot = 0, 0, charindex('.', @revName, @secondDot + 1));

        @fourthDot  int = iif(@thirdDot = 0, 0, charindex('.', @revName, @thirdDot + 1));

    --select @firstDot, @secondDot, @thirdDot, @fourthDot, len(@name);

    -- Undo the reverse() (first dot is first from the right).
    set @firstDot = iif(@firstDot = 0, 0, len(@name) - @firstDot + 1);
    set @secondDot = iif(@secondDot = 0, 0, len(@name) - @secondDot + 1);
    set @thirdDot = iif(@thirdDot = 0, 0, len(@name) - @thirdDot + 1);
    set @fourthDot = iif(@fourthDot = 0, 0, len(@name) - @fourthDot + 1);

    --select @firstDot, @secondDot, @thirdDot, @fourthDot, len(@name);

        @baseName   nvarchar(300)  = substring(@name, @firstDot + 1, len(@name) - @firstdot);

        @schemaName nvarchar(300) = iif(@firstDot - @secondDot - 1 <= 0, 
                                        substring(@name, @secondDot + 1, @firstDot - @secondDot - 1));
        @dbName     nvarchar(300) = iif(@secondDot - @thirdDot - 1 <= 0, 
                                        substring(@name, @thirdDot + 1, @secondDot - @thirdDot - 1));
        @instName   nvarchar(300) = iif(@thirdDot - @fourthDot - 1 <= 0, 
                                        substring(@name, @fourthDot + 1, @thirdDot - @fourthDot - 1));

    with input as (
           coalesce(@instName, '[' + @@servername + ']') as InstanceName,
           coalesce(@dbName,     iif(left(@baseName, 1) = '#', 'tempdb', db_name())) as DatabaseName,
           coalesce(@schemaName, iif(left(@baseName, 1) = '#', 'dbo', schema_name())) as SchemaName,
           @baseName as BaseName,
           iif(left(@baseName, 1) = '#',
                  select [name] from tempdb.sys.objects
                  where object_id = object_id('tempdb..' + @baseName)
               null) as FullTempDbBaseName,                
           iif(@instName is null, 0, 1) InstanceWasSpecified,       
           iif(@dbName is null, 0, 1) DatabaseWasSpecified,
           iif(@schemaName is null, 0, 1) SchemaWasSpecified    
     insert into @table           
     select i.InstanceName, i.DatabaseName, i.SchemaName, i.BaseName, i.FullTempDbBaseName,
            i.InstanceWasSpecified, i.DatabaseWasSpecified, i.SchemaWasSpecified,
            iif(i.InstanceName = '[' + @@servername + ']', 1, 0) as IsCurrentInstance,
            iif(i.DatabaseName = db_name(), 1, 0) as IsCurrentDatabase,
            iif(left(@baseName, 1) = '#', 1, 0) as IsTempDb,
            @name as OrgIdentifier
       from input i;


document.getElementById().value doesn't set the value

Try using ,


How to insert programmatically a new line in an Excel cell in C#?

Internally Excel uses U+000D U+000A (CR+LF, \r\n) for a line break, at least in its XML representation. I also couldn't find the value directly in a cell. It was migrated to another XML file containing shared strings. Maybe cells that contain line breaks are handled differently by the file format and your library doesn't know about this.

How do I generate a random integer between min and max in Java?

Construct a Random object at application startup:

Random random = new Random();

Then use Random.nextInt(int):

int randomNumber = random.nextInt(max + 1 - min) + min;

Note that the both lower and upper limits are inclusive.

Difference between .dll and .exe?

? .exe and dll are the compiled version of c# code which are also called as assemblies.

? .exe is a stand alone executable file, which means it can executed directly.

? .dll is a reusable component which cannot be executed directly and it requires other programs to execute it.

Detect if HTML5 Video element is playing

Here is what we are using at to keep people from accidentally leaving the page while a video is playing or paused.

$(document).ready(function() {

    var video = $("video#webcast_video");
    if (video.length <= 0) {

    window.onbeforeunload = function () {
        var htmlVideo = video[0];
        if (htmlVideo.currentTime < 0.01 || htmlVideo.ended) {
            return null;

        return "Leaving this page will stop your video.";

How does += (plus equal) work?

NO 1+=2!=2 it means you are going to add 1+2. But this will give you a syntax error. Assume if a variable is int type int a=1; then a+=2; means a=1+2; and increase the value of a from 1 to 3.

How to Correctly Use Lists in R?

You say:

For another, lists can be returned from functions even though you never passed in a List when you called the function, and even though the function doesn't contain a List constructor, e.g.,

x = strsplit(LETTERS[1:10], "") # passing in an object of type 'character'
# => 'list'

And I guess you suggest that this is a problem(?). I'm here to tell you why it's not a problem :-). Your example is a bit simple, in that when you do the string-split, you have a list with elements that are 1 element long, so you know that x[[1]] is the same as unlist(x)[1]. But what if the result of strsplit returned results of different length in each bin. Simply returning a vector (vs. a list) won't do at all.

For instance:

stuff <- c("You, me, and dupree",  "You me, and dupree",
           "He ran away, but not very far, and not very fast")
x <- strsplit(stuff, ",")
xx <- unlist(strsplit(stuff, ","))

In the first case (x : which returns a list), you can tell what the 2nd "part" of the 3rd string was, eg: x[[3]][2]. How could you do the same using xx now that the results have been "unraveled" (unlist-ed)?

How to present UIAlertController when not in a view controller?

There 2 approaches that you can use:

-Use UIAlertView or 'UIActionSheet' instead (not recommended, cause it deprecated in iOS 8 but it works now)

-Somehow remember the last view controller which is presented. Here is example.

@interface UIViewController (TopController)
+ (UIViewController *)topViewController;

// implementation

#import "UIViewController+TopController.h"
#import <objc/runtime.h>

static __weak UIViewController *_topViewController = nil;

@implementation UIViewController (TopController)

+ (UIViewController *)topViewController {
    UIViewController *vc = _topViewController;
    while (vc.parentViewController) {
        vc = vc.parentViewController;
    return vc;

+ (void)load {
    [super load];
    [self swizzleSelector:@selector(viewDidAppear:) withSelector:@selector(myViewDidAppear:)];
    [self swizzleSelector:@selector(viewWillDisappear:) withSelector:@selector(myViewWillDisappear:)];

- (void)myViewDidAppear:(BOOL)animated {
    if (_topViewController == nil) {
        _topViewController = self;

    [self myViewDidAppear:animated];

- (void)myViewWillDisappear:(BOOL)animated {
    if (_topViewController == self) {
        _topViewController = nil;

    [self myViewWillDisappear:animated];

+ (void)swizzleSelector:(SEL)sel1 withSelector:(SEL)sel2
    Class class = [self class];

    Method originalMethod = class_getInstanceMethod(class, sel1);
    Method swizzledMethod = class_getInstanceMethod(class, sel2);

    BOOL didAddMethod = class_addMethod(class,

    if (didAddMethod) {
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);



[[UIViewController topViewController] presentViewController:alertController ...];

How can you get the Manifest Version number from the App's (Layout) XML variables?

I use BuildConfig.VERSION_NAME.toString();. What's the difference between that and getting it from the packageManager?

No XML based solutions have worked for me, sorry.

How to determine whether an object has a given property in JavaScript

Why not simply:

if (typeof myObject.myProperty == "undefined") alert("myProperty is not defined!");

Or if you expect a specific type:

if (typeof myObject.myProperty != "string") alert("myProperty has wrong type or does not exist!");

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

First you need to Fetch the remote (the specific branch), then you can create a local br and track it with that remote branch using your command (i.e. checkout with -b and --track).

How can the default node version be set using NVM?

The current answers did not solve the problem for me, because I had node installed in /usr/bin/node and /usr/local/bin/node - so the system always resolved these first, and ignored the nvm version.

I solved the issue by moving the existing versions to /usr/bin/node-system and /usr/local/bin/node-system

Then I had no node command anymore, until I used nvm use :(

I solved this issue by creating a symlink to the version that would be installed by nvm.

sudo mv /usr/local/bin/node /usr/local/bin/node-system    
sudo mv /usr/bin/node /usr/bin/node-system 
nvm use node
  Now using node v12.20.1 (npm v6.14.10)
which node
sudo ln -s /home/paul/.nvm/versions/node/v12.20.1/bin/node /usr/bin/node

Then open a new shell

node -v

jQuery attr('onclick')

As @Richard pointed out above, the onClick needs to have a capital 'C'.

$('#stop').click(function() {

Getting PEAR to work on XAMPP (Apache/MySQL stack on Windows)

I fixed

avast deletes your server.php in your directory so disable the antivirus

check the (server.php) file on your laravel folder


 * Laravel - A PHP Framework For Web Artisans_x000D_
 * @package  Laravel_x000D_
 * @author   Taylor Otwell <[email protected]>_x000D_
$uri = urldecode(_x000D_
    parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)_x000D_
// This file allows us to emulate Apache's "mod_rewrite" functionality from the_x000D_
// built-in PHP web server. This provides a convenient way to test a Laravel_x000D_
// application without having installed a "real" web server software here._x000D_
if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {_x000D_
    return false;_x000D_
require_once __DIR__.'/public/index.php';

How to get the fields in an Object via reflection?

You can use Class#getDeclaredFields() to get all declared fields of the class. You can use Field#get() to get the value.

In short:

Object someObject = getItSomehow();
for (Field field : someObject.getClass().getDeclaredFields()) {
    field.setAccessible(true); // You might want to set modifier to public first.
    Object value = field.get(someObject); 
    if (value != null) {
        System.out.println(field.getName() + "=" + value);

To learn more about reflection, check the Sun tutorial on the subject.

That said, the fields does not necessarily all represent properties of a VO. You would rather like to determine the public methods starting with get or is and then invoke it to grab the real property values.

for (Method method : someObject.getClass().getDeclaredMethods()) {
    if (Modifier.isPublic(method.getModifiers())
        && method.getParameterTypes().length == 0
        && method.getReturnType() != void.class
        && (method.getName().startsWith("get") || method.getName().startsWith("is"))
    ) {
        Object value = method.invoke(someObject);
        if (value != null) {
            System.out.println(method.getName() + "=" + value);

That in turn said, there may be more elegant ways to solve your actual problem. If you elaborate a bit more about the functional requirement for which you think that this is the right solution, then we may be able to suggest the right solution. There are many, many tools available to massage javabeans.

Relative imports for the billionth time

Script vs. Module

Here's an explanation. The short version is that there is a big difference between directly running a Python file, and importing that file from somewhere else. Just knowing what directory a file is in does not determine what package Python thinks it is in. That depends, additionally, on how you load the file into Python (by running or by importing).

There are two ways to load a Python file: as the top-level script, or as a module. A file is loaded as the top-level script if you execute it directly, for instance by typing python on the command line. It is loaded as a module if you do python -m myfile, or if it is loaded when an import statement is encountered inside some other file. There can only be one top-level script at a time; the top-level script is the Python file you ran to start things off.


When a file is loaded, it is given a name (which is stored in its __name__ attribute). If it was loaded as the top-level script, its name is __main__. If it was loaded as a module, its name is the filename, preceded by the names of any packages/subpackages of which it is a part, separated by dots.

So for instance in your example:


if you imported moduleX (note: imported, not directly executed), its name would be package.subpackage1.moduleX. If you imported moduleA, its name would be package.moduleA. However, if you directly run moduleX from the command line, its name will instead be __main__, and if you directly run moduleA from the command line, its name will be __main__. When a module is run as the top-level script, it loses its normal name and its name is instead __main__.

Accessing a module NOT through its containing package

There is an additional wrinkle: the module's name depends on whether it was imported "directly" from the directory it is in, or imported via a package. This only makes a difference if you run Python in a directory, and try to import a file in that same directory (or a subdirectory of it). For instance, if you start the Python interpreter in the directory package/subpackage1 and then do import moduleX, the name of moduleX will just be moduleX, and not package.subpackage1.moduleX. This is because Python adds the current directory to its search path on startup; if it finds the to-be-imported module in the current directory, it will not know that that directory is part of a package, and the package information will not become part of the module's name.

A special case is if you run the interpreter interactively (e.g., just type python and start entering Python code on the fly). In this case the name of that interactive session is __main__.

Now here is the crucial thing for your error message: if a module's name has no dots, it is not considered to be part of a package. It doesn't matter where the file actually is on disk. All that matters is what its name is, and its name depends on how you loaded it.

Now look at the quote you included in your question:

Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

Relative imports...

Relative imports use the module's name to determine where it is in a package. When you use a relative import like from .. import foo, the dots indicate to step up some number of levels in the package hierarchy. For instance, if your current module's name is package.subpackage1.moduleX, then ..moduleA would mean package.moduleA. For a from .. import to work, the module's name must have at least as many dots as there are in the import statement.

... are only relative in a package

However, if your module's name is __main__, it is not considered to be in a package. Its name has no dots, and therefore you cannot use from .. import statements inside it. If you try to do so, you will get the "relative-import in non-package" error.

Scripts can't import relative

What you probably did is you tried to run moduleX or the like from the command line. When you did this, its name was set to __main__, which means that relative imports within it will fail, because its name does not reveal that it is in a package. Note that this will also happen if you run Python from the same directory where a module is, and then try to import that module, because, as described above, Python will find the module in the current directory "too early" without realizing it is part of a package.

Also remember that when you run the interactive interpreter, the "name" of that interactive session is always __main__. Thus you cannot do relative imports directly from an interactive session. Relative imports are only for use within module files.

Two solutions:

  1. If you really do want to run moduleX directly, but you still want it to be considered part of a package, you can do python -m package.subpackage1.moduleX. The -m tells Python to load it as a module, not as the top-level script.

  2. Or perhaps you don't actually want to run moduleX, you just want to run some other script, say, that uses functions inside moduleX. If that is the case, put somewhere elsenot inside the package directory – and run it. If inside you do things like from package.moduleA import spam, it will work fine.


  • For either of these solutions, the package directory (package in your example) must be accessible from the Python module search path (sys.path). If it is not, you will not be able to use anything in the package reliably at all.

  • Since Python 2.6, the module's "name" for package-resolution purposes is determined not just by its __name__ attributes but also by the __package__ attribute. That's why I'm avoiding using the explicit symbol __name__ to refer to the module's "name". Since Python 2.6 a module's "name" is effectively __package__ + '.' + __name__, or just __name__ if __package__ is None.)

Display tooltip on Label's hover?

You can use the "title attribute" for label tag.

<label title="Hello This Will Have Some Value">Hello...</label>

If you need more control over the looks,

1 . try as shown below. But you will need to include bootstrap.

<button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="left" title="Hello This Will Have Some Value">Hello...</button>

2 . try But you will need to include jQueryUI.

<script type="text/javascript">

calling Jquery function from javascript

Yes you can (this is how I understand the original question). Here is how I did it. Just tie it into outside context. For example:


my_function = null;

 $(function() { 

        function my_fun(){ 
               /.. some operations ../ 
        my_function = my_fun;

 //just js 
 function js_fun () {  
       my_function(); //== call jquery function - just Reference is globally defined not function itself

I encountered this same problem when trying to access methods of the object, that was instantiated on DOM object ready only. Works. My example:

MyControl.prototype = {
   init:   function { 
        // init something
   update: function () {
           // something useful, like updating the list items of control or etc.         

MyCtrl = null;

// create jquery plug-in
$.fn.aControl = function () {
    var control = new MyControl(this);
    MyCtrl = control; // here is the trick
    return control;

now you can use something simple like:

function() = {
   MyCtrl.update(); // yes!

Date Format in Swift

For Swift 4.2, 5

Pass date and format as whatever way you want. To choose format you can visit, NSDATEFORMATTER website:

static func dateFormatter(date: Date,dateFormat:String) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = dateFormat
    return dateFormatter.string(from: date)

How to select an element inside "this" in jQuery?

I use this to get the Parent, similarly for child

$( this ).children( '' ).css("border", "3px double red");

Good Luck

What is the iPad user agent?

Mine says:

Mozilla/5.0 (iPad; U; CPU OS 4_3 like Mac OS X; da-dk) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8F190 Safari/6533.18.5


From the manual: The SELECT ... INTO OUTFILE statement is intended primarily to let you very quickly dump a table to a text file on the server machine. If you want to create the resulting file on some client host other than the server host, you cannot use SELECT ... INTO OUTFILE. In that case, you should instead use a command such as mysql -e "SELECT ..." > file_name to generate the file on the client host."

An example:

mysql -h -u usrname--password=pass db_name -e 'SELECT foo FROM bar' > /tmp/myfile.txt

Get output parameter value in ADO.NET

The other response shows this, but essentially you just need to create a SqlParameter, set the Direction to Output, and add it to the SqlCommand's Parameters collection. Then execute the stored procedure and get the value of the parameter.

Using your code sample:

// SqlConnection and SqlCommand are IDisposable, so stack a couple using()'s
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand("sproc", conn))
   // Create parameter with Direction as Output (and correct name and type)
   SqlParameter outputIdParam = new SqlParameter("@ID", SqlDbType.Int)
      Direction = ParameterDirection.Output 

   cmd.CommandType = CommandType.StoredProcedure;


   // Some various ways to grab the output depending on how you would like to
   // handle a null value returned from the query (shown in comment for each).

   // Note: You can use either the SqlParameter variable declared
   // above or access it through the Parameters collection by name:
   //   outputIdParam.Value == cmd.Parameters["@ID"].Value

   // Throws FormatException
   int idFromString = int.Parse(outputIdParam.Value.ToString());

   // Throws InvalidCastException
   int idFromCast = (int)outputIdParam.Value; 

   // idAsNullableInt remains null
   int? idAsNullableInt = outputIdParam.Value as int?; 

   // idOrDefaultValue is 0 (or any other value specified to the ?? operator)
   int idOrDefaultValue = outputIdParam.Value as int? ?? default(int); 


Be careful when getting the Parameters[].Value, since the type needs to be cast from object to what you're declaring it as. And the SqlDbType used when you create the SqlParameter needs to match the type in the database. If you're going to just output it to the console, you may just be using Parameters["@Param"].Value.ToString() (either explictly or implicitly via a Console.Write() or String.Format() call).

EDIT: Over 3.5 years and almost 20k views and nobody had bothered to mention that it didn't even compile for the reason specified in my "be careful" comment in the original post. Nice. Fixed it based on good comments from @Walter Stabosz and @Stephen Kennedy and to match the update code edit in the question from @abatishchev.

jQuery javascript regex Replace <br> with \n

var str = document.getElementById('mydiv').innerHTML;
document.getElementById('mytextarea').innerHTML = str.replace(/<br\s*[\/]?>/gi, "\n");

or using jQuery:

var str = $("#mydiv").html();
var regex = /<br\s*[\/]?>/gi;
$("#mydiv").html(str.replace(regex, "\n"));


edit: added i flag

edit2: you can use /<br[^>]*>/gi which will match anything between the br and slash if you have for example <br class="clear" />

How to get thread id of a pthread in linux c program?

There is also another way of getting thread id. While creating threads with

int pthread_create(pthread_t * thread, const pthread_attr_t * attr, void * (*start_routine)(void *), void *arg);

function call; the first parameter pthread_t * thread is actually a thread id (that is an unsigned long int defined in bits/pthreadtypes.h). Also, the last argument void *arg is the argument that is passed to void * (*start_routine) function to be threaded.

You can create a structure to pass multiple arguments and send a pointer to a structure.

typedef struct thread_info {
    pthread_t thread;
} thread_info;
tinfo = malloc(sizeof(thread_info) * NUMBER_OF_THREADS);
pthread_create (&tinfo[i].thread, NULL, handler, (void*)&tinfo[i]);
void *handler(void *targs) {
    thread_info *tinfo = targs;
    // here you get the thread id with tinfo->thread

How to check if a double value has no decimal part

Use number formatter to format the value, as required. Please check this.

C++ where to initialize static const

In a translation unit within the same namespace, usually at the top:

// foo.h
struct foo
    static const std::string s;

// foo.cpp
const std::string foo::s = "thingadongdong"; // this is where it lives

// bar.h
namespace baz
    struct bar
        static const float f;

// bar.cpp
namespace baz
    const float bar::f = 3.1415926535;

Get the last three chars from any string - Java

If you want the String composed of the last three characters, you can use substring(int):

String new_word = word.substring(word.length() - 3);

If you actually want them as a character array, you should write

char[] buffer = new char[3];
int length = word.length();
word.getChars(length - 3, length, buffer, 0);

The first two arguments to getChars denote the portion of the string you want to extract. The third argument is the array into which that portion will be put. And the last argument gives the position in the buffer where the operation starts.

If the string has less than three characters, you'll get an exception in either of the above cases, so you might want to check for that.

Differences between unique_ptr and shared_ptr

Both of these classes are smart pointers, which means that they automatically (in most cases) will deallocate the object that they point at when that object can no longer be referenced. The difference between the two is how many different pointers of each type can refer to a resource.

When using unique_ptr, there can be at most one unique_ptr pointing at any one resource. When that unique_ptr is destroyed, the resource is automatically reclaimed. Because there can only be one unique_ptr to any resource, any attempt to make a copy of a unique_ptr will cause a compile-time error. For example, this code is illegal:

unique_ptr<T> myPtr(new T);       // Okay
unique_ptr<T> myOtherPtr = myPtr; // Error: Can't copy unique_ptr

However, unique_ptr can be moved using the new move semantics:

unique_ptr<T> myPtr(new T);                  // Okay
unique_ptr<T> myOtherPtr = std::move(myPtr); // Okay, resource now stored in myOtherPtr

Similarly, you can do something like this:

unique_ptr<T> MyFunction() {
    unique_ptr<T> myPtr(/* ... */);

    /* ... */

    return myPtr;

This idiom means "I'm returning a managed resource to you. If you don't explicitly capture the return value, then the resource will be cleaned up. If you do, then you now have exclusive ownership of that resource." In this way, you can think of unique_ptr as a safer, better replacement for auto_ptr.

shared_ptr, on the other hand, allows for multiple pointers to point at a given resource. When the very last shared_ptr to a resource is destroyed, the resource will be deallocated. For example, this code is perfectly legal:

shared_ptr<T> myPtr(new T);       // Okay
shared_ptr<T> myOtherPtr = myPtr; // Sure!  Now have two pointers to the resource.

Internally, shared_ptr uses reference counting to track how many pointers refer to a resource, so you need to be careful not to introduce any reference cycles.

In short:

  1. Use unique_ptr when you want a single pointer to an object that will be reclaimed when that single pointer is destroyed.
  2. Use shared_ptr when you want multiple pointers to the same resource.

Hope this helps!

Sort table rows In Bootstrap

These examples are minified because StackOverflow has a maximum character limit and links to external code are discouraged since links can break.

There are multiple plugins if you look: Bootstrap Sortable, Bootstrap Table or DataTables.

Bootstrap 3 with DataTables Example: Bootstrap Docs & DataTables Docs

$(document).ready(function() {
<link href= rel=stylesheet><link href= rel=stylesheet><div class=container><h1>Bootstrap 3 DataTables</h1><table cellspacing=0 class="table table-bordered table-hover table-striped"id=example width=100%><thead><tr><th>Name<th>Position<th>Office<th>Salary<tbody><tr><td>Tiger Nixon<td>System Architect<td>Edinburgh<td>$320,800<tr><td>Garrett Winters<td>Accountant<td>Tokyo<td>$170,750<tr><td>Ashton Cox<td>Junior Technical Author<td>San Francisco<td>$86,000<tr><td>Cedric Kelly<td>Senior Javascript Developer<td>Edinburgh<td>$433,060<tr><td>Airi Satou<td>Accountant<td>Tokyo<td>$162,700<tr><td>Brielle Williamson<td>Integration Specialist<td>New York<td>$372,000<tr><td>Herrod Chandler<td>Sales Assistant<td>San Francisco<td>$137,500<tr><td>Rhona Davidson<td>Integration Specialist<td>Tokyo<td>$327,900<tr><td>Colleen Hurst<td>Javascript Developer<td>San Francisco<td>$205,500<tr><td>Sonya Frost<td>Software Engineer<td>Edinburgh<td>$103,600<tr><td>Jena Gaines<td>Office Manager<td>London<td>$90,560<tr><td>Quinn Flynn<td>Support Lead<td>Edinburgh<td>$342,000<tr><td>Charde Marshall<td>Regional Director<td>San Francisco<td>$470,600<tr><td>Haley Kennedy<td>Senior Marketing Designer<td>London<td>$313,500<tr><td>Tatyana Fitzpatrick<td>Regional Director<td>London<td>$385,750<tr><td>Michael Silva<td>Marketing Designer<td>London<td>$198,500<tr><td>Paul Byrd<td>Chief Financial Officer (CFO)<td>New York<td>$725,000<tr><td>Gloria Little<td>Systems Administrator<td>New York<td>$237,500<tr><td>Bradley Greer<td>Software Engineer<td>London<td>$132,000<tr><td>Dai Rios<td>Personnel Lead<td>Edinburgh<td>$217,500<tr><td>Jenette Caldwell<td>Development Lead<td>New York<td>$345,000<tr><td>Yuri Berry<td>Chief Marketing Officer (CMO)<td>New York<td>$675,000<tr><td>Caesar Vance<td>Pre-Sales Support<td>New York<td>$106,450<tr><td>Doris Wilder<td>Sales Assistant<td>Sidney<td>$85,600<tr><td>Angelica Ramos<td>Chief Executive Officer (CEO)<td>London<td>$1,200,000<tr><td>Gavin Joyce<td>Developer<td>Edinburgh<td>$92,575<tr><td>Jennifer Chang<td>Regional Director<td>Singapore<td>$357,650<tr><td>Brenden Wagner<td>Software Engineer<td>San Francisco<td>$206,850<tr><td>Fiona Green<td>Chief Operating Officer (COO)<td>San Francisco<td>$850,000<tr><td>Shou Itou<td>Regional Marketing<td>Tokyo<td>$163,000<tr><td>Michelle House<td>Integration Specialist<td>Sidney<td>$95,400<tr><td>Suki Burks<td>Developer<td>London<td>$114,500<tr><td>Prescott Bartlett<td>Technical Author<td>London<td>$145,000<tr><td>Gavin Cortez<td>Team Leader<td>San Francisco<td>$235,500<tr><td>Martena Mccray<td>Post-Sales support<td>Edinburgh<td>$324,050<tr><td>Unity Butler<td>Marketing Designer<td>San Francisco<td>$85,675<tr><td>Howard Hatfield<td>Office Manager<td>San Francisco<td>$164,500<tr><td>Hope Fuentes<td>Secretary<td>San Francisco<td>$109,850<tr><td>Vivian Harrell<td>Financial Controller<td>San Francisco<td>$452,500<tr><td>Timothy Mooney<td>Office Manager<td>London<td>$136,200<tr><td>Jackson Bradshaw<td>Director<td>New York<td>$645,750<tr><td>Olivia Liang<td>Support Engineer<td>Singapore<td>$234,500<tr><td>Bruno Nash<td>Software Engineer<td>London<td>$163,500<tr><td>Sakura Yamamoto<td>Support Engineer<td>Tokyo<td>$139,575<tr><td>Thor Walton<td>Developer<td>New York<td>$98,540<tr><td>Finn Camacho<td>Support Engineer<td>San Francisco<td>$87,500<tr><td>Serge Baldwin<td>Data Coordinator<td>Singapore<td>$138,575<tr><td>Zenaida Frank<td>Software Engineer<td>New York<td>$125,250<tr><td>Zorita Serrano<td>Software Engineer<td>San Francisco<td>$115,000<tr><td>Jennifer Acosta<td>Junior Javascript Developer<td>Edinburgh<td>$75,650<tr><td>Cara Stevens<td>Sales Assistant<td>New York<td>$145,600<tr><td>Hermione Butler<td>Regional Director<td>London<td>$356,250<tr><td>Lael Greer<td>Systems Administrator<td>London<td>$103,500<tr><td>Jonas Alexander<td>Developer<td>San Francisco<td>$86,500<tr><td>Shad Decker<td>Regional Director<td>Edinburgh<td>$183,000<tr><td>Michael Bruce<td>Javascript Developer<td>Singapore<td>$183,000<tr><td>Donna Snider<td>Customer Support<td>New York<td>$112,000</table></div><script src=></script><script src=></script><script src=></script>

Bootstrap 4 with DataTables Example: Bootstrap Docs & DataTables Docs

$(document).ready(function() {
<link href= rel=stylesheet><link href= rel=stylesheet><div class=container><h1>Bootstrap 4 DataTables</h1><table cellspacing=0 class="table table-bordered table-hover table-inverse table-striped"id=example width=100%><thead><tr><th>Name<th>Position<th>Office<th>Age<th>Start date<th>Salary<tfoot><tr><th>Name<th>Position<th>Office<th>Age<th>Start date<th>Salary<tbody><tr><td>Tiger Nixon<td>System Architect<td>Edinburgh<td>61<td>2011/04/25<td>$320,800<tr><td>Garrett Winters<td>Accountant<td>Tokyo<td>63<td>2011/07/25<td>$170,750<tr><td>Ashton Cox<td>Junior Technical Author<td>San Francisco<td>66<td>2009/01/12<td>$86,000<tr><td>Cedric Kelly<td>Senior Javascript Developer<td>Edinburgh<td>22<td>2012/03/29<td>$433,060<tr><td>Airi Satou<td>Accountant<td>Tokyo<td>33<td>2008/11/28<td>$162,700<tr><td>Brielle Williamson<td>Integration Specialist<td>New York<td>61<td>2012/12/02<td>$372,000<tr><td>Herrod Chandler<td>Sales Assistant<td>San Francisco<td>59<td>2012/08/06<td>$137,500<tr><td>Rhona Davidson<td>Integration Specialist<td>Tokyo<td>55<td>2010/10/14<td>$327,900<tr><td>Colleen Hurst<td>Javascript Developer<td>San Francisco<td>39<td>2009/09/15<td>$205,500<tr><td>Sonya Frost<td>Software Engineer<td>Edinburgh<td>23<td>2008/12/13<td>$103,600<tr><td>Jena Gaines<td>Office Manager<td>London<td>30<td>2008/12/19<td>$90,560<tr><td>Quinn Flynn<td>Support Lead<td>Edinburgh<td>22<td>2013/03/03<td>$342,000<tr><td>Charde Marshall<td>Regional Director<td>San Francisco<td>36<td>2008/10/16<td>$470,600<tr><td>Haley Kennedy<td>Senior Marketing Designer<td>London<td>43<td>2012/12/18<td>$313,500<tr><td>Tatyana Fitzpatrick<td>Regional Director<td>London<td>19<td>2010/03/17<td>$385,750<tr><td>Michael Silva<td>Marketing Designer<td>London<td>66<td>2012/11/27<td>$198,500<tr><td>Paul Byrd<td>Chief Financial Officer (CFO)<td>New York<td>64<td>2010/06/09<td>$725,000<tr><td>Gloria Little<td>Systems Administrator<td>New York<td>59<td>2009/04/10<td>$237,500<tr><td>Bradley Greer<td>Software Engineer<td>London<td>41<td>2012/10/13<td>$132,000<tr><td>Dai Rios<td>Personnel Lead<td>Edinburgh<td>35<td>2012/09/26<td>$217,500<tr><td>Jenette Caldwell<td>Development Lead<td>New York<td>30<td>2011/09/03<td>$345,000<tr><td>Yuri Berry<td>Chief Marketing Officer (CMO)<td>New York<td>40<td>2009/06/25<td>$675,000<tr><td>Caesar Vance<td>Pre-Sales Support<td>New York<td>21<td>2011/12/12<td>$106,450<tr><td>Doris Wilder<td>Sales Assistant<td>Sidney<td>23<td>2010/09/20<td>$85,600<tr><td>Angelica Ramos<td>Chief Executive Officer (CEO)<td>London<td>47<td>2009/10/09<td>$1,200,000<tr><td>Gavin Joyce<td>Developer<td>Edinburgh<td>42<td>2010/12/22<td>$92,575<tr><td>Jennifer Chang<td>Regional Director<td>Singapore<td>28<td>2010/11/14<td>$357,650<tr><td>Brenden Wagner<td>Software Engineer<td>San Francisco<td>28<td>2011/06/07<td>$206,850<tr><td>Fiona Green<td>Chief Operating Officer (COO)<td>San Francisco<td>48<td>2010/03/11<td>$850,000<tr><td>Shou Itou<td>Regional Marketing<td>Tokyo<td>20<td>2011/08/14<td>$163,000<tr><td>Michelle House<td>Integration Specialist<td>Sidney<td>37<td>2011/06/02<td>$95,400<tr><td>Suki Burks<td>Developer<td>London<td>53<td>2009/10/22<td>$114,500<tr><td>Prescott Bartlett<td>Technical Author<td>London<td>27<td>2011/05/07<td>$145,000<tr><td>Gavin Cortez<td>Team Leader<td>San Francisco<td>22<td>2008/10/26<td>$235,500<tr><td>Martena Mccray<td>Post-Sales support<td>Edinburgh<td>46<td>2011/03/09<td>$324,050<tr><td>Unity Butler<td>Marketing Designer<td>San Francisco<td>47<td>2009/12/09<td>$85,675<tr><td>Howard Hatfield<td>Office Manager<td>San Francisco<td>51<td>2008/12/16<td>$164,500<tr><td>Hope Fuentes<td>Secretary<td>San Francisco<td>41<td>2010/02/12<td>$109,850<tr><td>Vivian Harrell<td>Financial Controller<td>San Francisco<td>62<td>2009/02/14<td>$452,500<tr><td>Timothy Mooney<td>Office Manager<td>London<td>37<td>2008/12/11<td>$136,200<tr><td>Jackson Bradshaw<td>Director<td>New York<td>65<td>2008/09/26<td>$645,750<tr><td>Olivia Liang<td>Support Engineer<td>Singapore<td>64<td>2011/02/03<td>$234,500<tr><td>Bruno Nash<td>Software Engineer<td>London<td>38<td>2011/05/03<td>$163,500<tr><td>Sakura Yamamoto<td>Support Engineer<td>Tokyo<td>37<td>2009/08/19<td>$139,575<tr><td>Thor Walton<td>Developer<td>New York<td>61<td>2013/08/11<td>$98,540<tr><td>Finn Camacho<td>Support Engineer<td>San Francisco<td>47<td>2009/07/07<td>$87,500<tr><td>Serge Baldwin<td>Data Coordinator<td>Singapore<td>64<td>2012/04/09<td>$138,575<tr><td>Zenaida Frank<td>Software Engineer<td>New York<td>63<td>2010/01/04<td>$125,250<tr><td>Zorita Serrano<td>Software Engineer<td>San Francisco<td>56<td>2012/06/01<td>$115,000<tr><td>Jennifer Acosta<td>Junior Javascript Developer<td>Edinburgh<td>43<td>2013/02/01<td>$75,650<tr><td>Cara Stevens<td>Sales Assistant<td>New York<td>46<td>2011/12/06<td>$145,600<tr><td>Hermione Butler<td>Regional Director<td>London<td>47<td>2011/03/21<td>$356,250<tr><td>Lael Greer<td>Systems Administrator<td>London<td>21<td>2009/02/27<td>$103,500<tr><td>Jonas Alexander<td>Developer<td>San Francisco<td>30<td>2010/07/14<td>$86,500<tr><td>Shad Decker<td>Regional Director<td>Edinburgh<td>51<td>2008/11/13<td>$183,000<tr><td>Michael Bruce<td>Javascript Developer<td>Singapore<td>29<td>2011/06/27<td>$183,000<tr><td>Donna Snider<td>Customer Support<td>New York<td>27<td>2011/01/25<td>$112,000</table></div><script src=></script><script src=></script><script src=></script>

Bootstrap 3 with Bootstrap Table Example: Bootstrap Docs & Bootstrap Table Docs

<link href= rel=stylesheet><link href= rel=stylesheet><table data-sort-name=stargazers_count data-sort-order=desc data-toggle=table data-url=""><thead><tr><th data-field=name data-sortable=true>Name<th data-field=stargazers_count data-sortable=true>Stars<th data-field=forks_count data-sortable=true>Forks<th data-field=description data-sortable=true>Description</thead></table><script src=></script><script src=></script>

Bootstrap 3 with Bootstrap Sortable Example: Bootstrap Docs & Bootstrap Sortable Docs

function randomDate(t,e){return new Date(t.getTime()+Math.random()*(e.getTime()-t.getTime()))}function randomName(){return["Jack","Peter","Frank","Steven"][Math.floor(4*Math.random())]+" "+["White","Jackson","Sinatra","Spielberg"][Math.floor(4*Math.random())]}function newTableRow(){var t=moment(randomDate(new Date(2e3,0,1),new Date)).format("D.M.YYYY"),e=Math.round(Math.random()*Math.random()*100*100)/100,a=Math.round(Math.random()*Math.random()*100*100)/100,r=Math.round(Math.random()*Math.random()*100*100)/100;return"<tr><td>"+randomName()+"</td><td>"+e+"</td><td>"+a+"</td><td>"+r+"</td><td>"+Math.round(100*(e+a+r))/100+"</td><td data-dateformat='D-M-YYYY'>"+t+"</td></tr>"}function customSort(){alert("Custom sort.")}!function(t,e){"use strict";"function"==typeof define&&define.amd?define("tinysort",function(){return e}):t.tinysort=e}(this,function(){"use strict";function t(t,e){for(var a,r=t.length,o=r;o--;)e(t[a=r-o-1],a)}function e(t,e,a){for(var o in e)(a||t[o]===r)&&(t[o]=e[o]);return t}function a(t,e,a){u.push({prepare:t,sort:e,sortBy:a})}var r,o=!1,n=null,s=window,d=s.document,i=parseFloat,l=/(-?\d+\.?\d*)\s*$/g,c=/(\d+\.?\d*)\s*$/g,u=[],f=0,h=0,p=String.fromCharCode(4095),m={selector:n,order:"asc",attr:n,data:n,useVal:o,place:"org",returns:o,cases:o,natural:o,forceStrings:o,ignoreDashes:o,sortFunction:n,useFlex:o,emptyEnd:o};return s.Element&&function(t){t.matchesSelector=t.matchesSelector||t.mozMatchesSelector||t.msMatchesSelector||t.oMatchesSelector||t.webkitMatchesSelector||function(t){for(var e=this,a=(e.parentNode||e.document).querySelectorAll(t),r=-1;a[++r]&&a[r]!=e;);return!!a[r]}}(Element.prototype),e(a,{loop:t}),e(function(a,s){function v(t){var a=!!t.selector,r=a&&":"===t.selector[0],o=e(t||{},m);E.push(e({hasSelector:a,hasAttr:!(o.attr===n||""===o.attr),!==n,hasFilter:r,sortReturnNumber:"asc"===o.order?1:-1},o))}function b(t,e,a){for(var r=a(t.toString()),o=a(e.toString()),n=0;r[n]&&o[n];n++)if(r[n]!==o[n]){var s=Number(r[n]),d=Number(o[n]);return s==r[n]&&d==o[n]?s-d:r[n]>o[n]?1:-1}return r.length-o.length}function g(t){for(var e,a,r=[],o=0,n=-1,s=0;e=(a=t.charAt(o++)).charCodeAt(0);){var d=46==e||e>=48&&57>=e;d!==s&&(r[++n]="",s=d),r[n]+=a}return r}function w(){return Y.forEach(function(t){F.appendChild(t.elm)}),F}function S(t){var e=t.elm,a=d.createElement("div");return t.ghost=a,e.parentNode.insertBefore(a,e),t}function y(t,e){var a=t.ghost,r=a.parentNode;r.insertBefore(e,a),r.removeChild(a),delete t.ghost}function C(t,e){var a,r=t.elm;return e.selector&&(e.hasFilter?r.matchesSelector(e.selector)||(r=n):r=r.querySelector(e.selector)),e.hasAttr?a=r.getAttribute(e.attr):e.useVal?a=r.value||r.getAttribute("value"):e.hasData?a=r.getAttribute("data-",M(a)&&(e.cases||(a=a.toLowerCase()),a=a.replace(/\s+/g," ")),null===a&&(a=p),a}function M(t){return"string"==typeof t}M(a)&&(a=d.querySelectorAll(a)),0===a.length&&console.warn("No elements to sort");var x,N,F=d.createDocumentFragment(),D=[],Y=[],$=[],E=[],k=!0,A=a.length&&a[0].parentNode,T=A.rootNode!==document,R=a.length&&(s===r||!1!==s.useFlex)&&!T&&-1!==getComputedStyle(A,null).display.indexOf("flex");return function(){0===arguments.length?v({}):t(arguments,function(t){v(M(t)?{selector:t}:t)}),f=E.length}.apply(n,,1)),t(a,function(t,e){N?N!==t.parentNode&&(k=!1):N=t.parentNode;var a=E[0],r=a.hasFilter,o=a.selector,n=!o||r&&t.matchesSelector(o)||o&&t.querySelector(o)?Y:$,s={elm:t,pos:e,posn:n.length};D.push(s),n.push(s)}),x=Y.slice(0),Y.sort(function(e,a){var n=0;for(0!==h&&(h=0);0===n&&f>h;){var s=E[h],d=s.ignoreDashes?c:l;if(t(u,function(t){var e=t.prepare;e&&e(s)}),s.sortFunction)n=s.sortFunction(e,a);else if("rand"==s.order)n=Math.random()<.5?1:-1;else{var p=o,m=C(e,s),v=C(a,s),w=""===m||m===r,S=""===v||v===r;if(m===v)n=0;else if(s.emptyEnd&&(w||S))n=w&&S?0:w?1:-1;else{if(!s.forceStrings){var y=M(m)?m&&m.match(d):o,x=M(v)?v&&v.match(d):o;y&&x&&m.substr(0,m.length-y[0].length)==v.substr(0,v.length-x[0].length)&&(p=!o,m=i(y[0]),v=i(x[0]))}n=m===r||v===r?0:s.natural&&(isNaN(m)||isNaN(v))?b(m,v,g):v>m?-1:m>v?1:0}}t(u,function(t){var e=t.sort;e&&(n=e(s,p,m,v,n))}),0==(n*=s.sortReturnNumber)&&h++}return 0===n&&(n=e.pos>a.pos?1:-1),n}),function(){var t=Y.length===D.length;if(k&&t)R?Y.forEach(function(t,e){}):N?N.appendChild(w()):console.warn("parentNode has been removed");else{var e=E[0].place,a="start"===e,r="end"===e,o="first"===e,n="last"===e;if("org"===e)Y.forEach(S),Y.forEach(function(t,e){y(x[e],t.elm)});else if(a||r){var s=x[a?0:x.length-1],d=s&&s.elm.parentNode,i=d&&(a&&d.firstChild||d.lastChild);i&&(i!==s.elm&&(s={elm:i}),S(s),r&&d.appendChild(s.ghost),y(s,w()))}else(o||n)&&y(S(x[o?0:x.length-1]),w())}}(),{return t.elm})},{plugin:a,defaults:m})}()),function(t,e){"function"==typeof define&&define.amd?define(["jquery","tinysort","moment"],e):e(t.jQuery,t.tinysort,t.moment||void 0)}(this,function(t,e,a){var r,o,n,s=t(document);function d(e){var s=void 0!==a;r=e.sign?e.sign:"arrow","default"==e.customSort&&(e.customSort=c),o=e.customSort||o||c,n=e.emptyEnd,t("table.sortable").each(function(){var r=t(this),o=!0===e.applyLast;r.find("span.sign").remove(),r.find("> thead [colspan]").each(function(){for(var e=parseFloat(t(this).attr("colspan")),a=1;a<e;a++)t(this).after('<th class="colspan-compensate">')}),r.find("> thead [rowspan]").each(function(){for(var e=t(this),a=parseFloat(e.attr("rowspan")),r=1;r<a;r++){var o=e.parent("tr"),"tr"),s=o.children().index(e);n.children().eq(s).before('<th class="rowspan-compensate">')}}),r.find("> thead tr").each(function(e){t(this).find("th").each(function(a){var r=t(this);r.addClass("nosort").removeClass("up down"),r.attr("data-sortcolumn",a),r.attr("data-sortkey",a+"-"+e)})}),r.find("> thead .rowspan-compensate, .colspan-compensate").remove(),r.find("th").each(function(){var e=t(this);if(void 0!==e.attr("data-dateformat")&&s){var o=parseFloat(e.attr("data-sortcolumn"));r.find("td:nth-child("+(o+1)+")").each(function(){var r=t(this);r.attr("data-value",a(r.text(),e.attr("data-dateformat")).format("YYYY/MM/DD/HH/mm/ss"))})}else if(void 0!==e.attr("data-valueprovider")){o=parseFloat(e.attr("data-sortcolumn"));r.find("td:nth-child("+(o+1)+")").each(function(){var a=t(this);a.attr("data-value",new RegExp(e.attr("data-valueprovider")).exec(a.text())[0])})}}),r.find("td").each(function(){var e=t(this);void 0!==e.attr("data-dateformat")&&s?e.attr("data-value",a(e.text(),e.attr("data-dateformat")).format("YYYY/MM/DD/HH/mm/ss")):void 0!==e.attr("data-valueprovider")?e.attr("data-value",new RegExp(e.attr("data-valueprovider")).exec(e.text())[0]):void 0===e.attr("data-value")&&e.attr("data-value",e.text())});var n=l(r),d=n.bsSort;r.find('> thead th[data-defaultsort!="disabled"]').each(function(e){var a=t(this),r=a.closest("table.sortable");"sortTable",r);var s=a.attr("data-sortkey"),i=o?n.lastSort:-1;d[s]=o?d[s]:a.attr("data-defaultsort"),void 0!==d[s]&&o===(s===i)&&(d[s]="asc"===d[s]?"desc":"asc",u(a,r))})})}function i(e){var a=t(e),"sortTable")||a.closest("table.sortable");u(a,r)}function l(e){var"bootstrap-sortable-context");return void 0===a&&(a={bsSort:[],lastSort:void 0},e.find('> thead th[data-defaultsort!="disabled"]').each(function(e){var r=t(this),o=r.attr("data-sortkey");a.bsSort[o]=r.attr("data-defaultsort"),void 0!==a.bsSort[o]&&(a.lastSort=o)}),"bootstrap-sortable-context",a)),a}function c(t,a){e(t,a)}function u(e,a){a.trigger("before-sort");var s=parseFloat(e.attr("data-sortcolumn")),d=l(a),i=d.bsSort;if(e.attr("colspan")){var c=parseFloat("mainsort"))||0,f=parseFloat("sortkey").split("-").pop());if(a.find("> thead tr").length-1>f)return void u(a.find('[data-sortkey="'+(s+c)+"-"+(f+1)+'"]'),a);s+=c}var h=e.attr("data-defaultsign")||r;if(a.find("> thead th").each(function(){t(this).removeClass("up").removeClass("down").addClass("nosort")}),t.browser.mozilla){var p=a.find("> thead div.mozilla");void 0!==p&&(p.find(".sign").remove(),p.parent().html(p.html())),e.wrapInner('<div class="mozilla"></div>'),e.children().eq(0).append('<span class="sign '+h+'"></span>')}else a.find("> thead span.sign").remove(),e.append('<span class="sign '+h+'"></span>');var m=e.attr("data-sortkey"),v="desc"!==e.attr("data-firstsort")?"desc":"asc",b=i[m]||v;d.lastSort!==m&&void 0!==i[m]||(b="asc"===b?"desc":"asc"),i[m]=b,d.lastSort=m,"desc"===i[m]?(e.find("span.sign").addClass("up"),e.addClass("up").removeClass("down nosort")):e.addClass("down").removeClass("up nosort");var g=a.children("tbody").children("tr"),w=[];t(g.filter('[data-disablesort="true"]').get().reverse()).each(function(e,a){var r=t(a);w.push({index:g.index(r),row:r}),r.remove()});var S=g.not('[data-disablesort="true"]');if(0!=S.length){var y="asc"===i[m]&&n;o(S,{emptyEnd:y,selector:"td:nth-child("+(s+1)+")",order:i[m],data:"value"})}t(w.reverse()).each(function(t,e){0===e.index?a.children("tbody").prepend(e.row):a.children("tbody").children("tr").eq(e.index-1).after(e.row)}),a.find("> tbody > tr > td.sorted,> thead th.sorted").removeClass("sorted"),S.find("td:eq("+s+")").addClass("sorted"),e.addClass("sorted"),a.trigger("sorted")}if(t.bootstrapSortable=function(t){null==t?d({}):t.constructor===Boolean?d({applyLast:t}):void 0!==t.sortingHeader?i(t.sortingHeader):d(t)},s.on("click",'table.sortable>thead th[data-defaultsort!="disabled"]',function(t){i(this)}),!t.browser){t.browser={chrome:!1,mozilla:!1,opera:!1,msie:!1,safari:!1};var f=navigator.userAgent;t.each(t.browser,function(e){t.browser[e]=!!new RegExp(e,"i").test(f),t.browser.mozilla&&"mozilla"===e&&(t.browser.mozilla=!!new RegExp("firefox","i").test(f)),"safari"===e&&(t.browser.safari=!1)})}t(t.bootstrapSortable)}),function(){var t=$("table");t.append(newTableRow()),t.append(newTableRow()),$("button.add-row").on("click",function(){var e=$(this);t.append(newTableRow()),"sort")?$.bootstrapSortable(!0):$.bootstrapSortable(!1)}),$("button.change-sort").on("click",function(){$(this).data("custom")?$.bootstrapSortable(!0,void 0,customSort):$.bootstrapSortable(!0,void 0,"default")}),t.on("sorted",function(){alert("Table was sorted.")}),$("#event").on("change",function(){$(this).is(":checked")?t.on("sorted",function(){alert("Table was sorted.")})"sorted")}),$("input[name=sign]:radio").change(function(){$.bootstrapSortable(!0,$(this).val())})}();
table.sortable span.sign { display: block; position: absolute; top: 50%; right: 5px; font-size: 12px; margin-top: -10px; color: #bfbfc1; } table.sortable th:after { display: block; position: absolute; top: 50%; right: 5px; font-size: 12px; margin-top: -10px; color: #bfbfc1; } table.sortable th.arrow:after { content: ''; } table.sortable span.arrow, span.reversed, th.arrow.down:after, th.reversedarrow.down:after, th.arrow.up:after, th.reversedarrow.up:after { border-style: solid; border-width: 5px; font-size: 0; border-color: #ccc transparent transparent transparent; line-height: 0; height: 0; width: 0; margin-top: -2px; } table.sortable span.arrow.up, th.arrow.up:after { border-color: transparent transparent #ccc transparent; margin-top: -7px; } table.sortable span.reversed, th.reversedarrow.down:after { border-color: transparent transparent #ccc transparent; margin-top: -7px; } table.sortable span.reversed.up, th.reversedarrow.up:after { border-color: #ccc transparent transparent transparent; margin-top: -2px; } table.sortable, { content: "a .. z"; } table.sortable, { content: "z .. a"; } table.sortable, th.AZ.nosort:after, th._19.nosort:after, th.month.nosort:after { content: ".."; } table.sortable span.AZ:before, th.AZ.down:after { content: "A .. Z"; } table.sortable span.AZ.up:before, th.AZ.up:after { content: "Z .. A"; } table.sortable span._19:before, th._19.down:after { content: "1 .. 9"; } table.sortable span._19.up:before, th._19.up:after { content: "9 .. 1"; } table.sortable span.month:before, th.month.down:after { content: "jan .. dec"; } table.sortable span.month.up:before, th.month.up:after { content: "dec .. jan"; } table.sortable thead th:not([data-defaultsort=disabled]) { cursor: pointer; position: relative; top: 0; left: 0; } table.sortable thead th:hover:not([data-defaultsort=disabled]) { background: #efefef; } table.sortable thead th div.mozilla { position: relative; }
<link href= rel=stylesheet><link href= rel=stylesheet><div class=container><div class=hero-unit><h1>Bootstrap Sortable</h1></div><table class="sortable table table-bordered table-striped"><thead><tr><th style=width:20%;vertical-align:middle data-defaultsign=nospan class=az data-defaultsort=asc rowspan=2><i class="fa fa-fw fa-map-marker"></i>Name<th style=text-align:center colspan=4 data-mainsort=3>Results<th data-defaultsort=disabled><tr><th style=width:20% colspan=2 data-mainsort=1 data-firstsort=desc>Round 1<th style=width:20%>Round 2<th style=width:20%>Total<t

How to calculate 1st and 3rd quartiles?

If you want to use raw python rather than numpy or panda, you can use the python stats module to find the median of the upper and lower half of the list:

    >>> import statistics as stat
    >>> def quartile(data):
            half_list = int(len(data)//2)
            upper_quartile = stat.median(data[-half_list]
            lower_quartile = stat.median(data[:half_list])
            print("Lower Quartile: "+str(lower_quartile))
            print("Upper Quartile: "+str(upper_quartile))
            print("Interquartile Range: "+str(upper_quartile-lower_quartile)

    >>> quartile(df.time_diff)

Line 1: import the statistics module under the alias "stat"

Line 2: define the quartile function

Line 3: sort the data into ascending order

Line 4: get the length of half of the list

Line 5: get the median of the lower half of the list

Line 6: get the median of the upper half of the list

Line 7: print the lower quartile

Line 8: print the upper quartile

Line 9: print the interquartile range

Line 10: run the quartile function for the time_diff column of the DataFrame

How do I install a custom font on an HTML site

For the best possible browser support, your CSS code should look like this :

@font-face {
  font-family: 'MyWebFont';
  src: url('webfont.eot'); /* IE9 Compat Modes */
  src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
       url('webfont.woff2') format('woff2'), /* Super Modern Browsers */
       url('webfont.woff') format('woff'), /* Pretty Modern Browsers */
       url('webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
       url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */

body {
  font-family: 'MyWebFont', Fallback, sans-serif;

For more info, see the article Using @font-face at

How do you replace double quotes with a blank space in Java?

Use String#replace().

To replace them with spaces (as per your question title):

System.out.println("I don't like these \"double\" quotes".replace("\"", " "));

The above can also be done with characters:

System.out.println("I don't like these \"double\" quotes".replace('"', ' '));

To remove them (as per your example):

System.out.println("I don't like these \"double\" quotes".replace("\"", ""));

JavaScript: undefined !== undefined?

var a;

typeof a === 'undefined'; // true
a === undefined; // true
typeof a === typeof undefined; // true
typeof a === typeof sdfuwehflj; // true

phpMyAdmin allow remote users

The other answers so far seem to advocate the complete replacement of the <Directory/> block, this is not needed and may remove extra settings like the 'AddDefaultCharset UTF-8' now included.

To allow remote access you need to add 1 line to the 2.4 config block or change 2 lines in the 2.2 (depending on your apache version):

<Directory /usr/share/phpMyAdmin/>
   AddDefaultCharset UTF-8

   <IfModule mod_authz_core.c>
     # Apache 2.4
       #ADD following line:
       Require all granted
       Require ip
       Require ip ::1
   <IfModule !mod_authz_core.c>
     # Apache 2.2
     #CHANGE following 2 lines:
     Order Allow,Deny
     Allow from All
     Allow from
     Allow from ::1

In SQL Server, how to create while loop in select

You Could do something like this .....
Your Table




My Suggestion

CREATE TABLE #DestinationTable
    SELECT * INTO #Temp FROM TestTable


        SELECT TOP 1 @Data =  DATA, @ID = ID FROM  #Temp

          WHILE LEN(@Data) > 0
                SET @String = LEFT(@Data, 2)

                INSERT INTO #DestinationTable (ID, Data)
                VALUES (@ID, @String)

                SET @Data = RIGHT(@Data, LEN(@Data) -2)
        DELETE FROM #Temp WHERE ID = @ID

SELECT * FROM #DestinationTable

Result Set

ID  Data
1   AA
1   BB
1   CC
2   FF
2   DD
3   TT
3   HH
3   JJ
3   KK
3   LL

DROP Temp Tables

DROP TABLE #DestinationTable

Importing CSV data using PHP/MySQL

letsay $infile = a.csv //file needs to be imported.

class blah
 static public function readJobsFromFile($file)
    if (($handle = fopen($file, "r")) === FALSE) 
        echo "readJobsFromFile: Failed to open file [$file]\n";

    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) 
        // ignore header
        if ($header == true)
            $header = false;

        if ($data[0] == '' && $data[1] == '' ) //u have oly 2 fields
            echo "readJobsFromFile: No more input entries\n";

        $a      = trim($data[0]);
        $b   = trim($data[1]);                 

        if (check_if_exists("SELECT count(*) FROM Db_table WHERE a='$a' AND b='$b'") === true)


        $sql = "INSERT INTO DB_table SET a='$a' , b='$b' ";
        @mysql_query($sql) or die("readJobsFromFile: " . mysql_error());            

    return $index; //no. of fields in database.
$result = mysql_query($sql) or die("$sql --" . mysql_error());
if (!$result) {
    $message  = 'check_if_exists::Invalid query: ' . mysql_error() . "\n";
    $message .= 'Query: ' . $sql;

$row = mysql_fetch_assoc ($result);
$count = $row['count(*)'];
if ($count > 0)
    return true;
return false;


hope this helps.

405 method not allowed Web API

check in your project .csproj file and change


to your website url like this


Formatting MM/DD/YYYY dates in textbox in VBA

While I agree with what's mentioned in the answers below, suggesting that this is a very bad design for a Userform unless copious amounts of error checks are included...

to accomplish what you need to do, with minimal changes to your code, there are two approaches.

  1. Use KeyUp() event instead of Change event for the textbox. Here is an example:

    Private Sub TextBox2_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
        Dim TextStr As String
        TextStr = TextBox2.Text
        If KeyCode <> 8 Then ' i.e. not a backspace
            If (Len(TextStr) = 2 Or Len(TextStr) = 5) Then
                TextStr = TextStr & "/"
            End If
        End If
        TextBox2.Text = TextStr
    End Sub
  2. Alternately, if you need to use the Change() event, use the following code. This alters the behavior so the user keeps entering the numbers, as


while the result as he's typing appears as


But the '/' character appears only once the first character of the DD i.e. 0 of 07 is entered. Not ideal, but will still handle backspaces.

    Private Sub TextBox1_Change()
        Dim TextStr As String

        TextStr = TextBox1.Text

        If (Len(TextStr) = 3 And Mid(TextStr, 3, 1) <> "/") Then
            TextStr = Left(TextStr, 2) & "/" & Right(TextStr, 1)
        ElseIf (Len(TextStr) = 6 And Mid(TextStr, 6, 1) <> "/") Then
            TextStr = Left(TextStr, 5) & "/" & Right(TextStr, 1)
        End If

        TextBox1.Text = TextStr
    End Sub

How can I add new array elements at the beginning of an array in Javascript?

you can reverse your array and push the data , at the end again reverse it:

var arr=[2,3,4,5,6];
var arr2=1;

Excel - Shading entire row based on change of value

A simpler version of one of the above answers. Column A is the key.
Yes, it needs a helper column.  That's column K.
1) Set first cell in table to TRUE (K8)
2) On second row at K9, and to end of table (K99), paste: =IF(A8=A9,K8,NOT(K8))
This gives a pattern of TRUE...TRUE, FALSE...FALSE,...
3) Select key column A1:A99, or whole table A1:K99
4) Set Home/Conditional/New Rule/Formula  =K8
5) Format as you wish for the TRUE cells
6) Select the range from (3) and Right-click Format White (or whatever
background color you want) for the FALSE cells

Note that this solution (and the others) have a major flaw, in that this
highlighting doesn't work properly when you have filters active in your
table.  I want that fix :)

how to make a div to wrap two float divs inside?

It's a common problem when you have two floats inside a block. The best way of fixing it is using clear:both after the second div.

<div style="display: block; clear: both;"></div>

It should force the container to be the correct height.

SimpleDateFormat and locale based format string

This will display the date according to user's current locale:

To return date and time:

import java.text.DateFormat;    
import java.util.Date;

Date date = new Date();
DateFormat df = DateFormat.getDateTimeInstance();
String myDate = df.format(date);

Dec 31, 1969 7:00:02 PM

To return date only, use:


Dec 31, 1969

How to find if a native DLL file is compiled as x64 or x86?

For an unmanaged DLL file, you need to first check if it is a 16-bit DLL file (hopefully not). Then check the IMAGE\_FILE_HEADER.Machine field.

Someone else took the time to work this out already, so I will just repeat here:

To distinguish between a 32-bit and 64-bit PE file, you should check IMAGE_FILE_HEADER.Machine field. Based on the Microsoft PE and COFF specification below, I have listed out all the possible values for this field:

IMAGE_FILE_MACHINE_UNKNOWN 0x0 The contents of this field are assumed to be applicable to any machine type

IMAGE_FILE_MACHINE_AM33 0x1d3 Matsushita AM33


IMAGE_FILE_MACHINE_ARM 0x1c0 ARM little endian


IMAGE_FILE_MACHINE_I386 0x14c Intel 386 or later processors and compatible processors

IMAGE_FILE_MACHINE_IA64 0x200 Intel Itanium processor family

IMAGE_FILE_MACHINE_M32R 0x9041 Mitsubishi M32R little endian




IMAGE_FILE_MACHINE_POWERPC 0x1f0 Power PC little endian

IMAGE_FILE_MACHINE_POWERPCFP 0x1f1 Power PC with floating point support

IMAGE_FILE_MACHINE_R4000 0x166 MIPS little endian







Yes, you may check IMAGE_FILE_MACHINE_AMD64|IMAGE_FILE_MACHINE_IA64 for 64bit and IMAGE_FILE_MACHINE_I386 for 32bit.

Random string generation with upper case letters and digits

I have gone though almost all of the answers but none of them looks easier. I would suggest you to try the passgen library which is generally used to create random passwords.

You can generate random strings of your choice of length, punctuation, digits, letters and case.

Here's the code for your case:

from passgen import passgen
string_length = int(input())
random_string = passgen(length=string_length, punctuation=False, digits=True, letters=True, case='upper')

How to calculate difference in hours (decimal) between two dates in SQL Server?

Using Postgres I had issues with DATEDIFF, but had success with this:

  DATE_PART('day',(delivery_time)::timestamp - (placed_time)::timestamp) * 24 + 
  DATE_PART('hour',(delivery_time)::timestamp - (placed_time)::timestamp) +
  DATE_PART('minute',(delivery_time)::timestamp - (placed_time)::timestamp) / 60

which gave me an output like "14.3"

How to use JNDI DataSource provided by Tomcat in Spring?

Another feature: instead of of server.xml, you can add "Resource" tag in
your_application/META-INF/Context.xml (according to tomcat docs) like this:

<Resource name="jdbc/DatabaseName" auth="Container" type="javax.sql.DataSource"
  username="dbUsername" password="dbPasswd"
  initialSize="5" maxWait="5000"
  maxActive="120" maxIdle="5"
  validationQuery="select 1"

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

If you are using TypeScript and don't want to account for "values those are false" then this is the solution for you:

First: import { isNullOrUndefined } from 'util';

Then: isNullOrUndefined(this.yourVariableName)

Please Note: As mentioned below this is now deprecated, use value === undefined || value === null instead. ref.

Close Bootstrap Modal

to close bootstrap modal you can pass 'hide' as option to modal method as follow


Please take a look at working fiddle here

bootstrap also provide events that you can hook into modal functionality, like if you want to fire a event when the modal has finished being hidden from the user you can use event you can read more about modal methods and events here in Documentation

If none of the above method work, give a id to your close button and trigger click on close button.

How to convert .pem into .key?

openssl rsa -in privkey.pem -out private.key does the job.

Open a link in browser with java button?

Use the Desktop#browse(URI) method. It opens a URI in the user's default browser.

public static boolean openWebpage(URI uri) {
    Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
    if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
        try {
            return true;
        } catch (Exception e) {
    return false;

public static boolean openWebpage(URL url) {
    try {
        return openWebpage(url.toURI());
    } catch (URISyntaxException e) {
    return false;

"The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine" Error in importing process of xlsx to a sql server

Currently, Microsoft don't provide download option for '2007 Office System Driver: Data Connectivity Components' and click on first answer for '2007 Office System Driver: Data Connectivity Components' redirect to Cnet where getting download link creates confusion.

That's why who use SQL Server 2014 and latest version of SQL Server in Windows 10 click on below link for download this component which resolve your problem : - Microsoft Access Database Engine 2010

Happy Coding!

What is the proper use of an EventEmitter?


No, don't subscribe manually to them, don't use them in services. Use them as is shown in the documentation only to emit events in components. Don't defeat angular's abstraction.


No, you should not subscribe manually to it.

EventEmitter is an angular2 abstraction and its only purpose is to emit events in components. Quoting a comment from Rob Wormald

[...] EventEmitter is really an Angular abstraction, and should be used pretty much only for emitting custom Events in components. Otherwise, just use Rx as if it was any other library.

This is stated really clear in EventEmitter's documentation.

Use by directives and components to emit custom Events.

What's wrong about using it?

Angular2 will never guarantee us that EventEmitter will continue being an Observable. So that means refactoring our code if it changes. The only API we must access is its emit() method. We should never subscribe manually to an EventEmitter.

All the stated above is more clear in this Ward Bell's comment (recommended to read the article, and the answer to that comment). Quoting for reference

Do NOT count on EventEmitter continuing to be an Observable!

Do NOT count on those Observable operators being there in the future!

These will be deprecated soon and probably removed before release.

Use EventEmitter only for event binding between a child and parent component. Do not subscribe to it. Do not call any of those methods. Only call eve.emit()

His comment is in line with Rob's comment long time ago.

So, how to use it properly?

Simply use it to emit events from your component. Take a look a the following example.

    selector : 'child',
    template : `
        <button (click)="sendNotification()">Notify my parent!</button>
class Child {
    @Output() notifyParent: EventEmitter<any> = new EventEmitter();
    sendNotification() {
        this.notifyParent.emit('Some value to send to the parent');

    selector : 'parent',
    template : `
        <child (notifyParent)="getNotification($event)"></child>
class Parent {
    getNotification(evt) {
        // Do something with the notification (evt) sent by the child!

How not to use it?

class MyService {
    @Output() myServiceEvent : EventEmitter<any> = new EventEmitter();

Stop right there... you're already wrong...

Hopefully these two simple examples will clarify EventEmitter's proper usage.

How to use if-else logic in Java 8 stream forEach

I think it's possible in Java 9:

                        pair -> Optional.ofNullable(pair.getValue())
                                .ifPresentOrElse(v -> myMap.put(pair.getKey(), v), v -> myList.add(pair.getKey())))

Need the ifPresentOrElse for it to work though. (I think a for loop looks better.) Connection reset

Whenever I have had odd issues like this, I usually sit down with a tool like WireShark and look at the raw data being passed back and forth. You might be surprised where things are being disconnected, and you are only being notified when you try and read.

Redirect with CodeIgniter

Here is .htacess file that hide index file

#RewriteEngine on
#RewriteCond $1 !^(index\.php|images|robots\.txt)
#RewriteRule ^(.*)$ /index.php/$1 [L]

<IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteBase /

        # Removes index.php from ExpressionEngine URLs
        RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
        RewriteCond %{REQUEST_URI} !/system/.* [NC]
        RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]

        # Directs all EE web requests through the site index file
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ index.php/$1 [L]

How to use struct timeval to get the execution time?

You have two typing errors in your code:

 struct timeval,

should be

 struct timeval

and after the printf() parenthesis you need a semicolon.

Also, depending on the compiler, so simple a cycle might just be optimized out, giving you a time of 0 microseconds whatever you do.

Finally, the time calculation is wrong. You only take into accounts the seconds, ignoring the microseconds. You need to get the difference between seconds, multiply by one million, then add "after" tv_usec and subtract "before" tv_usec. You gain nothing by casting an integer number of seconds to a float.

I'd suggest checking out the man page for struct timeval.

This is the code:

#include <stdio.h>
#include <sys/time.h>

int main (int argc, char** argv) {
    struct timeval tvalBefore, tvalAfter;  // removed comma

    gettimeofday (&tvalBefore, NULL);
    int i =0;
    while ( i < 10000) {
        i ++;

    gettimeofday (&tvalAfter, NULL);

    // Changed format to long int (%ld), changed time calculation

    printf("Time in microseconds: %ld microseconds\n",
            ((tvalAfter.tv_sec - tvalBefore.tv_sec)*1000000L
           +tvalAfter.tv_usec) - tvalBefore.tv_usec
          ); // Added semicolon
    return 0;

How to detect incoming calls, in an Android device?

Please use the below code. It will help you to get the incoming number with other call details.


<RelativeLayout xmlns:android=""
tools:context=".MainActivity" >

    android:text="@string/hello_world" />


public class MainActivity extends Activity {

private static final int MISSED_CALL_TYPE = 0;
private TextView txtcall;

    protected void onCreate(Bundle savedInstanceState) {

    txtcall = (TextView) findViewById(;

    StringBuffer sb = new StringBuffer();
    Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null,
            null, null, null);
    int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
    int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
    int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
    int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
    sb.append("Call Details :");
    while (managedCursor.moveToNext()) {
        String phNumber = managedCursor.getString(number);
        String callType = managedCursor.getString(type);
        String callDate = managedCursor.getString(date);
        Date callDayTime = new Date(Long.valueOf(callDate));
        String callDuration = managedCursor.getString(duration);
        String dir = null;
        int dircode = Integer.parseInt(callType);
        switch (dircode) {

        case CallLog.Calls.OUTGOING_TYPE:
            dir = "OUTGOING";

        case CallLog.Calls.INCOMING_TYPE:
            dir = "INCOMING";

        case CallLog.Calls.MISSED_TYPE:
            dir = "MISSED";
        sb.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- "
                + dir + " \nCall Date:--- " + callDayTime
                + " \nCall duration in sec :--- " + callDuration);

public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(, menu);
    return true;


and in your manifest request for following permissions:

<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.READ_LOGS"/>

How to style a div to have a background color for the entire width of the content, and not just for the width of the display?

It is because you set the width:100% which by definition only spans the width of the screen. You want to set the min-width:100% which sets it to the width of the screen... with the ability to grow beyond that.

Also make sure you set min-width:100% for body and html.

How to work with string fields in a C struct?

On strings and memory allocation:

A string in C is just a sequence of chars, so you can use char * or a char array wherever you want to use a string data type:

typedef struct     {
  int number;
  char *name;
  char *address;
  char *birthdate;
  char gender;
} patient;

Then you need to allocate memory for the structure itself, and for each of the strings:

patient *createPatient(int number, char *name, 
  char *addr, char *bd, char sex) {

  // Allocate memory for the pointers themselves and other elements
  // in the struct.
  patient *p = malloc(sizeof(struct patient));

  p->number = number; // Scalars (int, char, etc) can simply be copied

  // Must allocate memory for contents of pointers.  Here, strdup()
  // creates a new copy of name.  Another option:
  // p->name = malloc(strlen(name)+1);
  // strcpy(p->name, name);
  p->name = strdup(name);
  p->address = strdup(addr);
  p->birthdate = strdup(bd);
  p->gender = sex;
  return p;

If you'll only need a few patients, you can avoid the memory management at the expense of allocating more memory than you really need:

typedef struct     {
  int number;
  char name[50];       // Declaring an array will allocate the specified
  char address[200];   // amount of memory when the struct is created,
  char birthdate[50];  // but pre-determines the max length and may
  char gender;         // allocate more than you need.
} patient;

On linked lists:

In general, the purpose of a linked list is to prove quick access to an ordered collection of elements. If your llist contains an element called num (which presumably contains the patient number), you need an additional data structure to hold the actual patients themselves, and you'll need to look up the patient number every time.

Instead, if you declare

typedef struct llist
  patient *p;
  struct llist *next;
} list;

then each element contains a direct pointer to a patient structure, and you can access the data like this:

patient *getPatient(list *patients, int num) {
  list *l = patients;
  while (l != NULL) {
    if (l->p->num == num) {
      return l->p;
    l = l->next;
  return NULL;

Format a JavaScript string using placeholders and an object of substitutions?

As with modern browser, placeholder is supported by new version of Chrome / Firefox, similar as the C style function printf().


  • %s String.
  • %d,%i Integer number.
  • %f Floating point number.
  • %o Object hyperlink.


console.log("generation 0:\t%f, %f, %f", a1a1, a1a2, a2a2);

BTW, to see the output:

  • In Chrome, use shortcut Ctrl + Shift + J or F12 to open developer tool.
  • In Firefox, use shortcut Ctrl + Shift + K or F12 to open developer tool.

@Update - nodejs support

Seems nodejs don't support %f, instead, could use %d in nodejs. With %d number will be printed as floating number, not just integer.

How do I remove repeated elements from ArrayList?

If you want to preserve your Order then it is best to use LinkedHashSet. Because if you want to pass this List to an Insert Query by Iterating it, the order would be preserved.

Try this

LinkedHashSet link=new LinkedHashSet();
List listOfValues=new ArrayList();

This conversion will be very helpful when you want to return a List but not a Set.

Search for a string in all tables, rows and columns of a DB

I’d suggest you find yourself a 3rd party tool for this such as ApexSQL Search (there are probably others out there too but I use this one because it’s free).

If you really want to go the SQL way you can try using stored procedure created by Sorna Kumar Muthuraj – copied code is below. Just execute this stored procedure for all tables in your schema (easy with dynamics SQL)

 @Tablenames VARCHAR(500) 
,@SearchStr NVARCHAR(60) 
,@GenerateSQLOnly Bit = 0 

    Parameters and usage 

    @Tablenames        -- Provide a single table name or multiple table name with comma seperated.  
                        If left blank , it will check for all the tables in the database 
    @SearchStr        -- Provide the search string. Use the '%' to coin the search.  
                        EX : X%--- will give data staring with X 
                             %X--- will give data ending with X 
                             %X%--- will give data containig  X 
    @GenerateSQLOnly -- Provide 1 if you only want to generate the SQL statements without seraching the database.  
                        By default it is 0 and it will search. 

    Samples : 

    1. To search data in a table 

        EXEC SearchTables @Tablenames = 'T1' 
                         ,@SearchStr  = '%TEST%' 

        The above sample searches in table T1 with string containing TEST. 

    2. To search in a multiple table 

        EXEC SearchTables @Tablenames = 'T2' 
                         ,@SearchStr  = '%TEST%' 

        The above sample searches in tables T1 & T2 with string containing TEST. 

    3. To search in a all table 

        EXEC SearchTables @Tablenames = '%' 
                         ,@SearchStr  = '%TEST%' 

        The above sample searches in all table with string containing TEST. 

    4. Generate the SQL for the Select statements 

        EXEC SearchTables @Tablenames        = 'T1' 
                         ,@SearchStr        = '%TEST%' 
                         ,@GenerateSQLOnly    = 1 



    DECLARE @CheckTableNames Table 
    Tablename sysname 

     Tablename        SYSNAME 
    ,WHEREClause    VARCHAR(MAX) 
    ,SQLStatement   VARCHAR(MAX) 
    ,Execstatus        BIT  

    DECLARE @tmpTblname sysname 

    IF LTRIM(RTRIM(@Tablenames)) IN ('' ,'%') 

        INSERT INTO @CheckTableNames 
        SELECT Name 
          FROM sys.tables 

        SELECT @sql = 'SELECT ''' + REPLACE(@Tablenames,',',''' UNION SELECT ''') + '''' 

        INSERT INTO @CheckTableNames 


    ( Tablename,WHEREClause) 
    SELECT + '.' + ST.NAME, 
                SELECT '[' + + ']' + ' LIKE ''' + @SearchStr + ''' OR ' + CHAR(10) 
                  FROM SYS.columns SC 
                  JOIN SYS.types STy 
                    ON STy.system_type_id = SC.system_type_id 
                   AND STy.user_type_id =SC.user_type_id 
                 WHERE in ('varchar','char','nvarchar','nchar') 
                   AND SC.object_id = ST.object_id 
                 ORDER BY 
                FOR XML PATH('') 
      FROM  SYS.tables ST 
      JOIN @CheckTableNames chktbls 
                ON chktbls.Tablename =  
      JOIN SYS.schemas SCh 
        ON ST.schema_id = SCh.schema_id 
     WHERE <> 'SearchTMP' 
      GROUP BY ST.object_id, + '.' + ST.NAME ; 

      UPDATE @SQLTbl 
         SET SQLStatement = 'SELECT * INTO SearchTMP FROM ' + Tablename + ' WHERE ' + substring(WHEREClause,1,len(WHEREClause)-5) 



        SELECT TOP 1 @tmpTblname = Tablename , @sql = SQLStatement 
          FROM @SQLTbl  
         WHERE ISNULL(Execstatus ,0) = 0 

         IF @GenerateSQLOnly = 0 

            IF OBJECT_ID('SearchTMP','U') IS NOT NULL 
                DROP TABLE SearchTMP 
            EXEC (@SQL) 

            IF EXISTS(SELECT 1 FROM SearchTMP) 
                SELECT Tablename=@tmpTblname,* FROM SearchTMP 

             PRINT REPLICATE('-',100) 
             PRINT @tmpTblname 
             PRINT REPLICATE('-',100) 
             PRINT replace(@sql,'INTO SearchTMP','') 

         UPDATE @SQLTbl 
            SET Execstatus = 1 
          WHERE Tablename = @tmpTblname 




How do I copy a range of formula values and paste them to a specific range in another sheet?

How about if you're copying each column in a sheet to different sheets? Example: row B of mysheet to row B of sheet1, row C of mysheet to row B of sheet 2...

htaccess <Directory> deny from all

You cannot use the Directory directive in .htaccess. However if you create a .htaccess file in the /system directory and place the following in it, you will get the same result

#place this in /system/.htaccess as you had before
deny from all

Change a Rails application to production

rails s -e production

This will run the server with RAILS_ENV = 'production'.

Apart from this you have to set the assets path in production.rb

config.serve_static_assets = true

Without this your assets will not be loaded.

HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK


Curl: SSL certificate problem, verify that the CA cert is OK

07 April 2006

When opening a secure url with Curl you may get the following error:

SSL certificate problem, verify that the CA cert is OK

I will explain why the error and what you should do about it.

The easiest way of getting rid of the error would be adding the following two lines to your script . This solution poses a security risk tho.

//WARNING: this would prevent curl from detecting a 'man in the middle' attack
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0); 

Let see what this two parameters do. Quoting the manual.

CURLOPT_SSL_VERIFYHOST: 1 to check the existence of a common name in the SSL peer certificate. 2 to check the existence of a common name and also verify that it matches the hostname provided.

CURLOPT_SSL_VERIFYPEER: FALSE to stop CURL from verifying the peer's certificate. Alternate certificates to verify against can be specified with the CURLOPT_CAINFO option or a certificate directory can be specified with the CURLOPT_CAPATH option. CURLOPT_SSL_VERIFYHOST may also need to be TRUE or FALSE if CURLOPT_SSL_VERIFYPEER is disabled (it defaults to 2). Setting CURLOPT_SSL_VERIFYHOST to 2 (This is the default value) will garantee that the certificate being presented to you have a 'common name' matching the URN you are using to access the remote resource. This is a healthy check but it doesn't guarantee your program is not being decieved.

Enter the 'man in the middle'

Your program could be misleaded into talking to another server instead. This can be achieved through several mechanisms, like dns or arp poisoning ( This is a story for another day). The intruder can also self-sign a certificate with the same 'comon name' your program is expecting. The communication would still be encrypted but you would be giving away your secrets to an impostor. This kind of attack is called 'man in the middle'

Defeating the 'man in the middle'

Well, we need to to verify the certificate being presented to us is good for real. We do this by comparing it against a certificate we reasonable* trust.

If the remote resource is protected by a certificate issued by one of the main CA's like Verisign, GeoTrust et al, you can safely compare against Mozilla's CA certificate bundle which you can get from

Save the file cacert.pem somewhere in your server and set the following options in your script.

curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, TRUE); 
curl_setopt ($ch, CURLOPT_CAINFO, "pathto/cacert.pem");

for All above Info Credit Goes to :

Cannot find the object because it does not exist or you do not have permissions. Error in SQL Server

Does the user you're executing this script under even see that table??

select top 1 * from products

Do you get any output for this??

If yes: does this user have the permission to modify the table, i.e. execute DDL scripts like ALTER TABLE etc.? Typically, regular users don't have this elevated permissions.

Is it possible to clone html element objects in JavaScript / JQuery?

You can use clone() method to create a copy..

$('#foo1').html( $('#foo2 > div').clone())?;


jQuery Cross Domain Ajax

Unfortunately it seems that this web service returns JSON which contains another JSON - parsing contents of the inner JSON is successful. The solution is ugly but works for me. JSON.parse(...) tries to convert the entire string and fails. Assuming that you always get the answer starting with {"AuthenticateUserResult": and interesting data is after this, try:

    type: 'GET',
    dataType: "text",
    crossDomain: true,
    url: "",
    success: function (responseData, textStatus, jqXHR) {
        var authResult = JSON.parse(
                '{"AuthenticateUserResult":"', ''
            ).replace('}"}', '}')
    error: function (responseData, textStatus, errorThrown) {
        alert('POST failed.');

It is very important that dataType must be text to prevent auto-parsing of malformed JSON you are receiving from web service.

Basically, I'm wiping out the outer JSON by removing topmost braces and key AuthenticateUserResult along with leading and trailing quotation marks. The result is a well formed JSON, ready for parsing.

How do I make an Event in the Usercontrol and have it handled in the Main Form?

For those looking to do this in VB, here's how I got mine to work with a checkbox.

Background: I was trying to make my own checkbox that is a slider/switch control. I've only included the relevant code for this question.

In User control MyCheckbox.ascx

<asp:CheckBox ID="checkbox" runat="server" AutoPostBack="true" />

In User control MyCheckbox.ascx.vb

Create an EventHandler (OnCheckChanged). When an event fires on the control (ID="checkbox") inside your usercontrol (MyCheckBox.ascx), then fire your EventHandler (OnCheckChanged).

Public Event OnCheckChanged As EventHandler

Private Sub checkbox_CheckedChanged(sender As Object, e As EventArgs) Handles checkbox.CheckedChanged
    RaiseEvent OnCheckChanged(Me, e)
End Sub

In Page MyPage.aspx

<uc:MyCheckbox runat="server" ID="myCheck" OnCheckChanged="myCheck_CheckChanged" />

Note: myCheck_CheckChanged didn't fire until I added the Handles clause below

In Page MyPage.aspx.vb

Protected Sub myCheck_CheckChanged (sender As Object, e As EventArgs) Handles scTransparentVoting.OnCheckChanged
    'Do some page logic here
End Sub

Angularjs dynamic ng-pattern validation

You can use site for building your own specific pattern for some country:

For example, Poland:

-pattern = xxxxxxxxx OR xxx-xxx-xxx OR xxx xxx xxx 
-regexp ="^\d{9}|^\d{3}-\d{3}-\d{3}|^\d{3}\s\d{3}\s\d{3}"

VBA copy cells value and format

Found this on OzGrid courtesy of Mr. Aaron Blood - simple direct and works.

Cells(1, 3).Copy Cells(1, 1)
Cells(1, 1).Value = Cells(1, 3).Value

However, I kinda suspect you were just providing us with an oversimplified example to ask the question. If you just want to copy formats from one range to another it looks like this...

Cells(1, 3).Copy
    Cells(1, 1).PasteSpecial (xlPasteFormats)
    Application.CutCopyMode = False

No module named pkg_resources

If you are using Python 3, you should use pip3 instead of pip. The command looks like $ pip3 install requirements.txt

Is it possible to have empty RequestParam values use the defaultValue?

This was considered a bug in 2013:

and was fixed with version 3.2.2. Problem shouldn't occur in any versions after that and your code should work just fine.

How to convert a Hibernate proxy to a real entity object

Here's a method I'm using.

public static <T> T initializeAndUnproxy(T entity) {
    if (entity == null) {
        throw new 
           NullPointerException("Entity passed for initialization is null");

    if (entity instanceof HibernateProxy) {
        entity = (T) ((HibernateProxy) entity).getHibernateLazyInitializer()
    return entity;

c# how to add byte to byte array

As many people here have pointed out, arrays in C#, as well as in most other common languages, are statically sized. If you're looking for something more like PHP's arrays, which I'm just going to guess you are, since it's a popular language with dynamically sized (and typed!) arrays, you should use an ArrayList:

var mahByteArray = new ArrayList<byte>();

If you have a byte array from elsewhere, you can use the AddRange function.


Then you can use Add() and Insert() to add elements.

mahByteArray.Add(0x00); // Adds 0x00 to the end.
mahByteArray.Insert(0, 0xCA) // Adds 0xCA to the beginning.

Need it back in an array? .ToArray() has you covered!

mahOldByteArray = mahByteArray.ToArray();

Java8: sum values from specific field of the objects in a list


int sum = -> o.field > 10).mapToInt(o -> o.field).sum();

What is the equivalent to getLastInsertId() in Cakephp?

In Cake, the last insert id is automatically saved in the id property of the model. So if you just inserted a user via the User model, the last insert id could be accessed via $User->id

id - Value of the primary key ID of the record that this model is currently pointing to. Automatically set after database insertions.

Read more about model properties in the CakePHP API Docs:

Edit: I just realized that Model::getLastInsertID() is essentially the same thing as Model->id

After looking at your code more closely, it's hard to tell exactly what you're doing with the different functions and where they exist in the grand scheme of things. This may actually be more of a scope issue. Are you trying to access the last insert id in two different requests?

Can you explain the flow of your application and how it relates to your problem?

PostgreSQL naming conventions

Regarding tables names, case, etc, the prevalent convention is:

  • SQL keywords: UPPER CASE
  • names (identifiers): lower_case_with_underscores

For example:

UPDATE my_table SET name = 5;

This is not written in stone, but the bit about identifiers in lower case is highly recommended, IMO. Postgresql treats identifiers case insensitively when not quoted (it actually folds them to lowercase internally), and case sensitively when quoted; many people are not aware of this idiosyncrasy. Using always lowercase you are safe. Anyway, it's acceptable to use camelCase or PascalCase (or UPPER_CASE), as long as you are consistent: either quote identifiers always or never (and this includes the schema creation!).

I am not aware of many more conventions or style guides. Surrogate keys are normally made from a sequence (usually with the serial macro), it would be convenient to stick to that naming for those sequences if you create them by hand (tablename_colname_seq).

See also some discussion here, here and (for general SQL) here, all with several related links.

Note: Postgresql 10 introduced identity columns as an SQL-compliant replacement for serial.

How to add spacing between UITableViewCell

I solved it like this way in Swift 4.

I create a extension of UITableViewCell and include this code:

override open var frame: CGRect {
    get {
        return super.frame
    set (newFrame) {
        var frame =  newFrame
        frame.origin.y += 10
        frame.origin.x += 10
        frame.size.height -= 15
        frame.size.width -= 2 * 10
        super.frame = frame

override open func awakeFromNib() {
    layer.cornerRadius = 15
    layer.masksToBounds = false

I hope it helps you.

How to change int into int64?

This is called type conversion :

i := 23
var i64 int64
i64 = int64(i)

Combating AngularJS executing controller twice

I had the same problem, in a simple app (with no routing and a simple ng-controller reference) and my controller's constructor did run twice. Finally, I found out that my problem was the following declaration to auto-bootstrap my AngularJS application in my Razor view

<html ng-app="mTest1">

I have also manually bootstrapped it using angular.bootstrap i.e.

angular.bootstrap(document, []);

so removing one of them, it worked for me.

Table Naming Dilemma: Singular vs. Plural Names

Guidelines are really there as just that. It's not "set in stone" that's why you have the option of being able to ignore them.

I would say that it's more logically intuitive to have pluralized table names. A table is a collection of entity after all. In addition to other alternatives mentioned I commonly see prefixes on table names...

  • tblUser
  • tblThis
  • tblThat
  • tblTheOther

I'm not suggesting this is the way to go, I also see spaces used a LOT in table names which I abhor. I've even come across field names with idiotic characters like ? as if to say this field answers a question.

How is OAuth 2 different from OAuth 1?

OAuth 2 is apparently a waste of time (from the mouth of someone that was heavily involved in it):

He says (edited for brevity and bolded for emphasis):

...I can no longer be associated with the OAuth 2.0 standard. I resigned my role as lead author and editor, withdraw my name from the specification, and left the working group. Removing my name from a document I have painstakingly labored over for three years and over two dozen drafts was not easy. Deciding to move on from an effort I have led for over five years was agonizing.

...At the end, I reached the conclusion that OAuth 2.0 is a bad protocol. WS-* bad. It is bad enough that I no longer want to be associated with it. ...When compared with OAuth 1.0, the 2.0 specification is more complex, less interoperable, less useful, more incomplete, and most importantly, less secure.

To be clear, OAuth 2.0 at the hand of a developer with deep understanding of web security will likely result is a secure implementation. However, at the hands of most developers – as has been the experience from the past two years – 2.0 is likely to produce insecure implementations.

Login failed for user 'DOMAIN\MACHINENAME$'

A colleague had the same error and it was due to a little configuration error in IIS.
The wrong Application Pool was assigned for the web application.

Indeed we use a custom Application Pool with a specific Identity to meet our needs.

In his local IIS Manager -> Sites -> Default Web Site -> Our Web App Name -> Basic Settings... The Application Pool was "DefaultAppPool" instead of our custom Application Pool.

Setting the correct application pool solved the problem.

What are the differences between "=" and "<-" assignment operators in R?

Google's R style guide simplifies the issue by prohibiting the "=" for assignment. Not a bad choice.

The R manual goes into nice detail on all 5 assignment operators.

VBA Excel sort range by specific column

Try this code:

Dim lastrow As Long
lastrow = Cells(Rows.Count, 2).End(xlUp).Row
Range("A3:D" & lastrow).Sort key1:=Range("B3:B" & lastrow), _
   order1:=xlAscending, Header:=xlNo

Waiting for HOME ('android.process.acore') to be launched

Following steps worked for me: 1. Goto Project -> Clean. 2. Delete your previous AVD and create a new one.

How Do I Insert a Byte[] Into an SQL Server VARBINARY Column

You can do something like this, very simple and efficient solution: What i did was actually use a parameter instead of basic placeholder, created a SqlParameter object and used another existing execution method. For e.g in your scenario:

string sql = "INSERT INTO mssqltable (varbinarycolumn) VALUES (@img)";
SqlParameter param = new SqlParameter("img", arraytoinsert); //where img is your parameter name in the query
ExecuteStoreCommand(sql, param);

This should work like a charm, provided you have an open sql connection established.

Comparing user-inputted characters in C

answer shouldn't be a pointer, the intent is obviously to hold a character. scanf takes the address of this character, so it should be called as

char answer;
scanf(" %c", &answer);

Next, your "or" statement is formed incorrectly.

if (answer == 'Y' || answer == 'y')

What you wrote originally asks to compare answer with the result of 'Y' || 'y', which I'm guessing isn't quite what you wanted to do.

Count length of array and return 1 if it only contains one element

declare you array as:

$car = array("bmw")


now with powershell syntax:)

$car = [array]"bmw"

HTML span align center not working?

span.login-text {
    font-size: 22px;
    margin-left: auto;
    margin-right: auto;

<span class="login-text">Welcome To .....CMP</span>

For me it worked very well. try this also

Angular.js directive dynamic templateURL

You don't need custom directive here. Just use ng-include src attribute. It's compiled so you can put code inside. See plunker with solution for your issue.

<div ng-repeat="week in [1,2]">
  <div ng-repeat="day in ['monday', 'tuesday']">
    <ng-include src="'content/before-'+ week + '-' + day + '.html'"></ng-include>

Comparing Arrays of Objects in JavaScript

I have worked a bit on a simple algorithm to compare contents of two objects and return an intelligible list of difference. Thought I would share. It borrows some ideas for jQuery, namely the map function implementation and the object and array type checking.

It returns a list of "diff objects", which are arrays with the diff info. It's very simple.

Here it is:

// compare contents of two objects and return a list of differences
// returns an array where each element is also an array in the form:
// [accessor, diffType, leftValue, rightValue ]
// diffType is one of the following:
//   value: when primitive values at that index are different
//   undefined: when values in that index exist in one object but don't in 
//              another; one of the values is always undefined
//   null: when a value in that index is null or undefined; values are
//         expressed as boolean values, indicated wheter they were nulls
//   type: when values in that index are of different types; values are 
//         expressed as types
//   length: when arrays in that index are of different length; values are
//           the lengths of the arrays

function DiffObjects(o1, o2) {
    // choose a map() impl.
    // you may use $.map from jQuery if you wish
    var map =
        function(a) { return,, 1)); } :
        function(a, f) { 
            var ret = new Array(a.length), value;
            for ( var i = 0, length = a.length; i < length; i++ ) 
                ret[i] = f(a[i], i);
            return ret.concat();

    // shorthand for push impl.
    var push = Array.prototype.push;

    // check for null/undefined values
    if ((o1 == null) || (o2 == null)) {
        if (o1 != o2)
            return [["", "null", o1!=null, o2!=null]];

        return undefined; // both null
    // compare types
    if ((o1.constructor != o2.constructor) ||
        (typeof o1 != typeof o2)) {
        return [["", "type",, ]]; // different type


    // compare arrays
    if ( == "[object Array]") {
        if (o1.length != o2.length) { 
            return [["", "length", o1.length, o2.length]]; // different length
        var diff =[];
        for (var i=0; i<o1.length; i++) {
            // per element nested diff
            var innerDiff = DiffObjects(o1[i], o2[i]);
            if (innerDiff) { // o1[i] != o2[i]
                // merge diff array into parent's while including parent object name ([i])
                push.apply(diff, map(innerDiff, function(o, j) { o[0]="[" + i + "]" + o[0]; return o; }));
        // if any differences were found, return them
        if (diff.length)
            return diff;
        // return nothing if arrays equal
        return undefined;

    // compare object trees
    if ( == "[object Object]") {
        var diff =[];
        // check all props in o1
        for (var prop in o1) {
            // the double check in o1 is because in V8 objects remember keys set to undefined 
            if ((typeof o2[prop] == "undefined") && (typeof o1[prop] != "undefined")) {
                // prop exists in o1 but not in o2
                diff.push(["[" + prop + "]", "undefined", o1[prop], undefined]); // prop exists in o1 but not in o2

            else {
                // per element nested diff
                var innerDiff = DiffObjects(o1[prop], o2[prop]);
                if (innerDiff) { // o1[prop] != o2[prop]
                    // merge diff array into parent's while including parent object name ([prop])
                    push.apply(diff, map(innerDiff, function(o, j) { o[0]="[" + prop + "]" + o[0]; return o; }));

        for (var prop in o2) {
            // the double check in o2 is because in V8 objects remember keys set to undefined 
            if ((typeof o1[prop] == "undefined") && (typeof o2[prop] != "undefined")) {
                // prop exists in o2 but not in o1
                diff.push(["[" + prop + "]", "undefined", undefined, o2[prop]]); // prop exists in o2 but not in o1

        // if any differences were found, return them
        if (diff.length)
            return diff;
        // return nothing if objects equal
        return undefined;
    // if same type and not null or objects or arrays
    // perform primitive value comparison
    if (o1 != o2)
        return [["", "value", o1, o2]];

    // return nothing if values are equal
    return undefined;

Laravel 5 Application Key

You can generate a key by the following command:

php artisan key:generate 

The key will be written automatically in your .env file.


If you want to see your key after generation use --show option

php artisan key:generate --show

Note: The .env is a hidden file in your project folder.

enter image description here

Smooth GPS data

What you are looking for is called a Kalman Filter. It's frequently used to smooth navigational data. It is not necessarily trivial, and there is a lot of tuning you can do, but it is a very standard approach and works well. There is a KFilter library available which is a C++ implementation.

My next fallback would be least squares fit. A Kalman filter will smooth the data taking velocities into account, whereas a least squares fit approach will just use positional information. Still, it is definitely simpler to implement and understand. It looks like the GNU Scientific Library may have an implementation of this.

How do I escape double quotes in attributes in an XML String in T-SQL?

Wouldn't that be &quot; in xml? i.e.

"hi &quot;mom&quot; lol" 

**edit: ** tested; works fine:

declare @xml xml

 set @xml = '<transaction><item value="hi &quot;mom&quot; lol" 
    ItemId="106"  ItemType="2"  instanceId="215923801"  dataSetId="1" /></transaction>'

select @xml.value('(//item/@value)[1]','varchar(50)')

How to forcefully set IE's Compatibility Mode off from the server-side?

Update: More useful information What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

Maybe this url can help you: Activating Browser Modes with Doctype

Edit: Today we were able to override the compatibility view with: <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />

Vue component event after render

updated might be what you're looking for.

Increasing the Command Timeout for SQL command

it takes this command about 2 mins to return the data as there is a lot of data

Probably, Bad Design. Consider using paging here.

default connection time is 30 secs, how do I increase this

As you are facing a timeout on your command, therefore you need to increase the timeout of your sql command. You can specify it in your command like this

// Setting command timeout to 2 minutes
scGetruntotals.CommandTimeout = 120;

How can I get stock quotes using Google Finance API?

In order to find chart data using the financial data API of Google, one must simply go to Google as if looking for a search term, type finance into the search engine, and a link to Google finance will appear. Once at the Google finance search engine, type the ticker name into the financial data API engine and the result will be displayed. However, it should be noted that all Google finance charts are delayed by 15 minutes, and at most can be used for a better understanding of the ticker's past history, rather than current price.

A solution to the delayed chart information is to obtain a real-time financial data API. An example of one would be the barchartondemand interface that has real-time quote information, along with other detailed features that make it simpler to find the exact chart you're looking for. With fully customizable features, and specific programming tools for the precise trading information you need, barchartondemand's tools outdo Google finance by a wide margin.

SPA best practices for authentication and session management

This question has been addressed, in a slightly different form, at length, here:

RESTful Authentication

But this addresses it from the server-side. Let's look at this from the client-side. Before we do that, though, there's an important prelude:

Javascript Crypto is Hopeless

Matasano's article on this is famous, but the lessons contained therein are pretty important:

To summarize:

  • A man-in-the-middle attack can trivially replace your crypto code with <script> function hash_algorithm(password){ lol_nope_send_it_to_me_instead(password); }</script>
  • A man-in-the-middle attack is trivial against a page that serves any resource over a non-SSL connection.
  • Once you have SSL, you're using real crypto anyways.

And to add a corollary of my own:

  • A successful XSS attack can result in an attacker executing code on your client's browser, even if you're using SSL - so even if you've got every hatch battened down, your browser crypto can still fail if your attacker finds a way to execute any javascript code on someone else's browser.

This renders a lot of RESTful authentication schemes impossible or silly if you're intending to use a JavaScript client. Let's look!

HTTP Basic Auth

First and foremost, HTTP Basic Auth. The simplest of schemes: simply pass a name and password with every request.

This, of course, absolutely requires SSL, because you're passing a Base64 (reversibly) encoded name and password with every request. Anybody listening on the line could extract username and password trivially. Most of the "Basic Auth is insecure" arguments come from a place of "Basic Auth over HTTP" which is an awful idea.

The browser provides baked-in HTTP Basic Auth support, but it is ugly as sin and you probably shouldn't use it for your app. The alternative, though, is to stash username and password in JavaScript.

This is the most RESTful solution. The server requires no knowledge of state whatsoever and authenticates every individual interaction with the user. Some REST enthusiasts (mostly strawmen) insist that maintaining any sort of state is heresy and will froth at the mouth if you think of any other authentication method. There are theoretical benefits to this sort of standards-compliance - it's supported by Apache out of the box - you could store your objects as files in folders protected by .htaccess files if your heart desired!

The problem? You are caching on the client-side a username and password. This gives a better crack at it - even the most basic of XSS vulnerabilities could result in the client beaming his username and password to an evil server. You could try to alleviate this risk by hashing and salting the password, but remember: JavaScript Crypto is Hopeless. You could alleviate this risk by leaving it up to the Browser's Basic Auth support, but.. ugly as sin, as mentioned earlier.

HTTP Digest Auth

Is Digest authentication possible with jQuery?

A more "secure" auth, this is a request/response hash challenge. Except JavaScript Crypto is Hopeless, so it only works over SSL and you still have to cache the username and password on the client side, making it more complicated than HTTP Basic Auth but no more secure.

Query Authentication with Additional Signature Parameters.

Another more "secure" auth, where you encrypt your parameters with nonce and timing data (to protect against repeat and timing attacks) and send the. One of the best examples of this is the OAuth 1.0 protocol, which is, as far as I know, a pretty stonking way to implement authentication on a REST server.

Oh, but there aren't any OAuth 1.0 clients for JavaScript. Why?

JavaScript Crypto is Hopeless, remember. JavaScript can't participate in OAuth 1.0 without SSL, and you still have to store the client's username and password locally - which puts this in the same category as Digest Auth - it's more complicated than HTTP Basic Auth but it's no more secure.


The user sends a username and password, and in exchange gets a token that can be used to authenticate requests.

This is marginally more secure than HTTP Basic Auth, because as soon as the username/password transaction is complete you can discard the sensitive data. It's also less RESTful, as tokens constitute "state" and make the server implementation more complicated.

SSL Still

The rub though, is that you still have to send that initial username and password to get a token. Sensitive information still touches your compromisable JavaScript.

To protect your user's credentials, you still need to keep attackers out of your JavaScript, and you still need to send a username and password over the wire. SSL Required.

Token Expiry

It's common to enforce token policies like "hey, when this token has been around too long, discard it and make the user authenticate again." or "I'm pretty sure that the only IP address allowed to use this token is XXX.XXX.XXX.XXX". Many of these policies are pretty good ideas.


However, using a token Without SSL is still vulnerable to an attack called 'sidejacking':

The attacker doesn't get your user's credentials, but they can still pretend to be your user, which can be pretty bad.

tl;dr: Sending unencrypted tokens over the wire means that attackers can easily nab those tokens and pretend to be your user. FireSheep is a program that makes this very easy.

A Separate, More Secure Zone

The larger the application that you're running, the harder it is to absolutely ensure that they won't be able to inject some code that changes how you process sensitive data. Do you absolutely trust your CDN? Your advertisers? Your own code base?

Common for credit card details and less common for username and password - some implementers keep 'sensitive data entry' on a separate page from the rest of their application, a page that can be tightly controlled and locked down as best as possible, preferably one that is difficult to phish users with.

Cookie (just means Token)

It is possible (and common) to put the authentication token in a cookie. This doesn't change any of the properties of auth with the token, it's more of a convenience thing. All of the previous arguments still apply.

Session (still just means Token)

Session Auth is just Token authentication, but with a few differences that make it seem like a slightly different thing:

  • Users start with an unauthenticated token.
  • The backend maintains a 'state' object that is tied to a user's token.
  • The token is provided in a cookie.
  • The application environment abstracts the details away from you.

Aside from that, though, it's no different from Token Auth, really.

This wanders even further from a RESTful implementation - with state objects you're going further and further down the path of plain ol' RPC on a stateful server.

OAuth 2.0

OAuth 2.0 looks at the problem of "How does Software A give Software B access to User X's data without Software B having access to User X's login credentials."

The implementation is very much just a standard way for a user to get a token, and then for a third party service to go "yep, this user and this token match, and you can get some of their data from us now."

Fundamentally, though, OAuth 2.0 is just a token protocol. It exhibits the same properties as other token protocols - you still need SSL to protect those tokens - it just changes up how those tokens are generated.

There are two ways that OAuth 2.0 can help you:

  • Providing Authentication/Information to Others
  • Getting Authentication/Information from Others

But when it comes down to it, you're just... using tokens.

Back to your question

So, the question that you're asking is "should I store my token in a cookie and have my environment's automatic session management take care of the details, or should I store my token in Javascript and handle those details myself?"

And the answer is: do whatever makes you happy.

The thing about automatic session management, though, is that there's a lot of magic happening behind the scenes for you. Often it's nicer to be in control of those details yourself.

I am 21 so SSL is yes

The other answer is: Use https for everything or brigands will steal your users' passwords and tokens.

pandas get rows which are NOT in other dataframe

Here is another way of solving this:

df1[~df1.index.isin(df1.merge(df2, how='inner', on=['col1', 'col2']).index)]


df1.loc[df1.index.difference(df1.merge(df2, how='inner', on=['col1', 'col2']).index)]

Redirect using AngularJS

Assuming you're not using html5 routing, try $location.path("route"). This will redirect your browser to #/route which might be what you want.

Video 100% width and height

use this css for height

height: calc(100vh) !important;

This will make the video to have 100% vertical height available.

Align image to left of text on same line - Twitter Bootstrap3

I would use Bootstrap's grid to achieve the desired result. The class="img-responsive" works nicely. Something like:

    <div class="container-fluid">
        <div class="row">
            <div class="col-md-3"><img src="./pictures/placeholder.jpg" class="img-responsive" alt="Some picture" width="410" height="307"></div>
            <div class="col-md-9"><h1>Heading</h1><p>Your Information.</p></div>