Programs & Examples On #N73

ORA-01653: unable to extend table by in tablespace ORA-06512

You could also turn on autoextend for the whole database using this command:

ALTER DATABASE DATAFILE 'C:\ORACLEXE\APP\ORACLE\ORADATA\XE\SYSTEM.DBF'
AUTOEXTEND ON NEXT 1M MAXSIZE 1024M;

Just change the filepath to point to your system.dbf file.

Credit Here

json: cannot unmarshal object into Go value of type

Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:

json: cannot unmarshal object into Go struct field Comment.author of type string

Get Substring - everything before certain char

Things have moved on a bit since this thread started.

Now, you could use

string.Concat(s.TakeWhile((c) => c != '-'));

javascript unexpected identifier

In such cases, you are better off re-adding the whitespace which makes the syntax error immediate apparent:

function(){
  if(xmlhttp.readyState==4&&xmlhttp.status==200){
    document.getElementById("content").innerHTML=xmlhttp.responseText;
  }
}
xmlhttp.open("GET","data/"+id+".html",true);xmlhttp.send();
}

There's a } too many. Also, after the closing } of the function, you should add a ; before the xmlhttp.open()

And finally, I don't see what that anonymous function does up there. It's never executed or referenced. Are you sure you pasted the correct code?

What is for Python what 'explode' is for PHP?

The alternative for explode in php is split.

The first parameter is the delimiter, the second parameter the maximum number splits. The parts are returned without the delimiter present (except possibly the last part). When the delimiter is None, all whitespace is matched. This is the default.

>>> "Rajasekar SP".split()
['Rajasekar', 'SP']

>>> "Rajasekar SP".split('a',2)
['R','j','sekar SP']

How to view the assembly behind the code using Visual C++?

Additional note: there is big difference between Debug assembler output and Release one. The first one is good to learn how compiler produces assembler code from C++. The second one is good to learn how compiler optimizes various C++ constructs. In this case some C++-to-asm transformations are not obvious.

Angular JS: What is the need of the directive’s link function when we already had directive’s controller with scope?

After my initial struggle with the link and controller functions and reading quite a lot about them, I think now I have the answer.

First lets understand,

How do angular directives work in a nutshell:

  • We begin with a template (as a string or loaded to a string)

    var templateString = '<div my-directive>{{5 + 10}}</div>';

  • Now, this templateString is wrapped as an angular element

    var el = angular.element(templateString);

  • With el, now we compile it with $compile to get back the link function.

    var l = $compile(el)

    Here is what happens,

    • $compile walks through the whole template and collects all the directives that it recognizes.
    • All the directives that are discovered are compiled recursively and their link functions are collected.
    • Then, all the link functions are wrapped in a new link function and returned as l.
  • Finally, we provide scope function to this l (link) function which further executes the wrapped link functions with this scope and their corresponding elements.

    l(scope)

  • This adds the template as a new node to the DOM and invokes controller which adds its watches to the scope which is shared with the template in DOM.

enter image description here

Comparing compile vs link vs controller :

  • Every directive is compiled only once and link function is retained for re-use. Therefore, if there's something applicable to all instances of a directive should be performed inside directive's compile function.

  • Now, after compilation we have link function which is executed while attaching the template to the DOM. So, therefore we perform everything that is specific to every instance of the directive. For eg: attaching events, mutating the template based on scope, etc.

  • Finally, the controller is meant to be available to be live and reactive while the directive works on the DOM (after getting attached). Therefore:

    (1) After setting up the view[V] (i.e. template) with link. $scope is our [M] and $controller is our [C] in M V C

    (2) Take advantage the 2-way binding with $scope by setting up watches.

    (3) $scope watches are expected to be added in the controller since this is what is watching the template during run-time.

    (4) Finally, controller is also used to be able to communicate among related directives. (Like myTabs example in https://docs.angularjs.org/guide/directive)

    (5) It's true that we could've done all this in the link function as well but its about separation of concerns.

Therefore, finally we have the following which fits all the pieces perfectly :

enter image description here

jQuery & CSS - Remove/Add display:none

To hide the div

$('.news').hide();

or

$('.news').css('display','none');

and to show the div:

$('.news').show();

or

$('.news').css('display','block');

Tomcat Server Error - Port 8080 already in use

You can stop the running tomcat server by doing the following steps:

Step 1: go to your tomcat installation path (/bin) in your Windows system

Step 2: open cmd for that bin directory (you can easily do this by typing "cmd" at that directory )

Step 3: Run "Tomcat7.exe stop"

This will stop all running instances of tomcat server and now you can start server from your eclipse IDE.

Change New Google Recaptcha (v2) Width

I have found following best ways to resize google recaptchas

Option 1: You can resize google ReCaptcha by using inline style.

A very first way for resizing google recapture by using inline style. Inline styles are CSS styles that are applied to one element, directly in the page's HTML, using the style attribute. Here is the example that shows you how you to style Google reCAPTCHA by using inline style.

<div class="g-recaptcha" style="transform: scale(0.77); -webkit-transform: scale(0.77); transform-origin: 0 0; -webkit-transform-origin: 0 0;" data-theme="light" data-sitekey="XXXXXXXXXXXXX"></div>

Option 2: By putting the following style in your page (Internal Style Sheet).

Secondly, you can put style for ReCaptcha into the page between and . An internal style sheet is a section on an HTML page that contains style definitions. Internal style sheets are defined by using the tag within the area of the document. Here is the example that shows you how you to style Google reCAPTCHA by using an external style sheet.

<style type="text/css">
.g-recaptcha{
transform:scale(0.77);
-webkit-transform:scale(0.77);
transform-origin:0 0;
-webkit-transform-origin:0 0;
}
</style>

Option 3: Resize google ReCaptcha by using an external stylesheet.

Create a separate file and give a name like style.css and add this file link in between your an element in your page. For ex. .

<style type="text/css">
.g-recaptcha{
transform:scale(0.77);
-webkit-transform:scale(0.77);
transform-origin:0 0;
-webkit-transform-origin:0 0;
}
</style>

Reference from the blog: https://www.scratchcode.io/how-to-resize-the-google-recaptcha/

Syntax for creating a two-dimensional array in Java

int [][] twoDim = new int [5][5];

int a = (twoDim.length);//5
int b = (twoDim[0].length);//5

for(int i = 0; i < a; i++){ // 1 2 3 4 5
    for(int j = 0; j <b; j++) { // 1 2 3 4 5
        int x = (i+1)*(j+1);
        twoDim[i][j] = x;
        if (x<10) {
            System.out.print(" " + x + " ");
        } else {
            System.out.print(x + " ");
        }
    }//end of for J
    System.out.println();
}//end of for i

Finding all possible permutations of a given string in python

Here's a really simple generator version:

def find_all_permutations(s, curr=[]):
    if len(s) == 0:
        yield curr
    else:
        for i, c in enumerate(s):
            for combo in find_all_permutations(s[:i]+s[i+1:], curr + [c]):
                yield "".join(combo)

I think it's not so bad!

Batch script loop

DOS doesn't offer very elegant mechanisms for this, but I think you can still code a loop for 100 or 200 iterations with reasonable effort. While there's not a numeric for loop, you can use a character string as a "loop variable."

Code the loop using GOTO, and for each iteration use SET X=%X%@ to add yet another @ sign to an environment variable X; and to exit the loop, compare the value of X with a string of 100 (or 200) @ signs.

I never said this was elegant, but it should work!

python save image from url

Python code snippet to download a file from an url and save with its name

import requests

url = 'http://google.com/favicon.ico'
filename = url.split('/')[-1]
r = requests.get(url, allow_redirects=True)
open(filename, 'wb').write(r.content)

Row count on the Filtered data

Rowz = Application.WorksheetFunction.Subtotal(2, Range("A2:A" & Rows(Rows.Count).End(xlUp).Row))

Password must have at least one non-alpha character

Run it through a fairly simple regex: [^a-zA-Z]

And then check it's length separately:

if(string.Length > 7)

Regular expression to match DNS hostname or IP Address?

how about this?

([0-9]{1,3}\.){3}[0-9]{1,3}

CSS background-image not working

<span class="btn-pTool">
         <a class="btn-pToolName" href="#"></a>
     </span>

Try to add display:block to .btn-pTool, and give it a width and height.

Also in your code both tbn-pTool and btn-pToolName have no text content, so that may result in them not being displayed at all.

You can try to force come content in them this way

.btn-pTool, .btn-pToolName {
    content: " ";
}

Modulo operation with negative numbers

According to C99 standard, section 6.5.5 Multiplicative operators, the following is required:

(a / b) * b + a % b = a

Conclusion

The sign of the result of a remainder operation, according to C99, is the same as the dividend's one.

Let's see some examples (dividend / divisor):

When only dividend is negative

(-3 / 2) * 2  +  -3 % 2 = -3

(-3 / 2) * 2 = -2

(-3 % 2) must be -1

When only divisor is negative

(3 / -2) * -2  +  3 % -2 = 3

(3 / -2) * -2 = 2

(3 % -2) must be 1

When both divisor and dividend are negative

(-3 / -2) * -2  +  -3 % -2 = -3

(-3 / -2) * -2 = -2

(-3 % -2) must be -1

6.5.5 Multiplicative operators

Syntax

  1. multiplicative-expression:
    • cast-expression
    • multiplicative-expression * cast-expression
    • multiplicative-expression / cast-expression
    • multiplicative-expression % cast-expression

Constraints

  1. Each of the operands shall have arithmetic type. The operands of the % operator shall have integer type.

Semantics

  1. The usual arithmetic conversions are performed on the operands.

  2. The result of the binary * operator is the product of the operands.

  3. The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.

  4. When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded [1]. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.

[1]: This is often called "truncation toward zero".

What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs?

In the case of a non blocking socket that has no data available, recv will throw the socket.error exception and the value of the exception will have the errno of either EAGAIN or EWOULDBLOCK. Example:

import sys
import socket
import fcntl, os
import errno
from time import sleep

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',9999))
fcntl.fcntl(s, fcntl.F_SETFL, os.O_NONBLOCK)

while True:
    try:
        msg = s.recv(4096)
    except socket.error, e:
        err = e.args[0]
        if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
            sleep(1)
            print 'No data available'
            continue
        else:
            # a "real" error occurred
            print e
            sys.exit(1)
    else:
        # got a message, do something :)

The situation is a little different in the case where you've enabled non-blocking behavior via a time out with socket.settimeout(n) or socket.setblocking(False). In this case a socket.error is stil raised, but in the case of a time out, the accompanying value of the exception is always a string set to 'timed out'. So, to handle this case you can do:

import sys
import socket
from time import sleep

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',9999))
s.settimeout(2)

while True:
    try:
        msg = s.recv(4096)
    except socket.timeout, e:
        err = e.args[0]
        # this next if/else is a bit redundant, but illustrates how the
        # timeout exception is setup
        if err == 'timed out':
            sleep(1)
            print 'recv timed out, retry later'
            continue
        else:
            print e
            sys.exit(1)
    except socket.error, e:
        # Something else happened, handle error, exit, etc.
        print e
        sys.exit(1)
    else:
        if len(msg) == 0:
            print 'orderly shutdown on server end'
            sys.exit(0)
        else:
            # got a message do something :)

As indicated in the comments, this is also a more portable solution since it doesn't depend on OS specific functionality to put the socket into non-blockng mode.

See recv(2) and python socket for more details.

Best approach to remove time part of datetime in SQL Server

Of-course this is an old thread but to make it complete.

From SQL 2008 you can use DATE datatype so you can simply do:

SELECT CONVERT(DATE,GETDATE())

Git push/clone to new server

There are many ways to move repositories around, git bundle is a nice way if you have insufficient network availability. Since a Git repository is really just a directory full of files, you can "clone" a repository by making a copy of the .git directory in whatever way suits you best.

The most efficient way is to use an external repository somewhere (use GitHub or set up Gitosis), and then git push.

What is %timeit in python?

This is known as a line magic in iPython. They are unique in that their arguments only extend to the end of the current line, and magics themselves are really structured for command line development. timeit is used to time the execution of code.

If you wanted to see all of the magics you can use, you could simply type:

%lsmagic

to get a list of both line magics and cell magics.

Some further magic information from documentation here:

IPython has a system of commands we call magics that provide effectively a mini command language that is orthogonal to the syntax of Python and is extensible by the user with new commands. Magics are meant to be typed interactively, so they use command-line conventions, such as using whitespace for separating arguments, dashes for options and other conventions typical of a command-line environment.

Depending on whether you are in line or cell mode, there are two different ways to use %timeit. Your question illustrates the first way:

In [1]: %timeit range(100)

vs.

In [1]: %%timeit 
      : x = range(100)
      :

Detecting a long press with Android

setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {

                int action = MotionEventCompat.getActionMasked(event);


                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        longClick = false;
                        x1 = event.getX();
                        break;

                    case MotionEvent.ACTION_MOVE:
                        if (event.getEventTime() - event.getDownTime() > 500 && Math.abs(event.getX() - x1) < MIN_DISTANCE) {
                            longClick = true;
                        }
                        break;

                    case MotionEvent.ACTION_UP:
                                if (longClick) {
                                    Toast.makeText(activity, "Long preess", Toast.LENGTH_SHORT).show();
                                } 
                }
                return true;
            }
        });

How to start http-server locally

When you're running npm install in the project's root, it installs all of the npm dependencies into the project's node_modules directory.

If you take a look at the project's node_modules directory, you should see a directory called http-server, which holds the http-server package, and a .bin folder, which holds the executable binaries from the installed dependencies. The .bin directory should have the http-server binary (or a link to it).

So in your case, you should be able to start the http-server by running the following from your project's root directory (instead of npm start):

./node_modules/.bin/http-server -a localhost -p 8000 -c-1

This should have the same effect as running npm start.

If you're running a Bash shell, you can simplify this by adding the ./node_modules/.bin folder to your $PATH environment variable:

export PATH=./node_modules/.bin:$PATH

This will put this folder on your path, and you should be able to simply run

http-server -a localhost -p 8000 -c-1

Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

This will work, Try this -

<input id="textField1" onfocus="this.select()" onmouseup="return false" /> 

Works in Safari/IE 9 and Chrome, I did not get a chance to test in Firefox though.

Check whether a path is valid

private bool IsValidPath(string path)
{
    Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");

    if (string.IsNullOrWhiteSpace(path) || path.Length < 3)
    {
        return false;
    }

    if (!driveCheck.IsMatch(path.Substring(0, 3)))
    {
        return false;
    }

    var x1 = (path.Substring(3, path.Length - 3));
    string strTheseAreInvalidFileNameChars = new string(Path.GetInvalidPathChars());
    strTheseAreInvalidFileNameChars += @":?*";
    Regex containsABadCharacter = new Regex("[" + Regex.Escape(strTheseAreInvalidFileNameChars) + "]");

    if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
    {
        return false;
    }

    var driveLetterWithColonAndSlash = Path.GetPathRoot(path);

    if (!DriveInfo.GetDrives().Any(x => x.Name == driveLetterWithColonAndSlash))
    {
        return false;
    }

    return true;
}

Get PostGIS version

Did you try using SELECT PostGIS_version();

assigning column names to a pandas series

You can also use the .to_frame() method.

If it is a Series, I assume 'Gene' is already the index, and will remain the index after converting it to a DataFrame. The name argument of .to_frame() will name the column.

x = x.to_frame('count')

If you want them both as columns, you can reset the index:

x = x.to_frame('count').reset_index()

What is the bower (and npm) version syntax?

If there is no patch number, ~ is equivalent to appending .x to the non-tilde version. If there is a patch number, ~ allows all patch numbers >= the specified one.

~1     := 1.x
~1.2   := 1.2.x
~1.2.3 := (>=1.2.3 <1.3.0)

I don't have enough points to comment on the accepted answer, but some of the tilde information is at odds with the linked semver documentation: "angular": "~1.2" will not match 1.3, 1.4, 1.4.9. Also "angular": "~1" and "angular": "~1.0" are not equivalent. This can be verified with the npm semver calculator.

How may I align text to the left and text to the right in the same line?

An answer using css flex layout and justify-content

_x000D_
_x000D_
p {
  display: flex;
  justify-content: space-between;
}
_x000D_
<p>
  <span>This text is left aligned</span>
  <span>This text is right aligned</span>
</p>
_x000D_
_x000D_
_x000D_

what is Ljava.lang.String;@

I also met this problem when I've made ListView for android app:

Map<String, Object> m;

for(int i=0; i < dates.length; i++){
    m = new HashMap<String, Object>();
    m.put(ATTR_DATES, dates[i]);
    m.put(ATTR_SQUATS, squats[i]);
    m.put(ATTR_BP, benchpress[i]);
    m.put(ATTR_ROW, row[i]);
    data.add(m);
}

The problem was that I've forgotten to use the [i] index inside the loop

What's the best way to break from nested loops in JavaScript?

Already mentioned previously by swilliams, but with an example below (Javascript):

// Function wrapping inner for loop
function CriteriaMatch(record, criteria) {
  for (var k in criteria) {
    if (!(k in record))
      return false;

    if (record[k] != criteria[k])
      return false;
  }

  return true;
}

// Outer for loop implementing continue if inner for loop returns false
var result = [];

for (var i = 0; i < _table.length; i++) {
  var r = _table[i];

  if (!CriteriaMatch(r[i], criteria))
    continue;

  result.add(r);
}

Usage of $broadcast(), $emit() And $on() in AngularJS

  • Broadcast: We can pass the value from parent to child (i.e parent -> child controller.)
  • Emit: we can pass the value from child to parent (i.e.child ->parent controller.)
  • On: catch the event dispatched by $broadcast or $emit.

Writing numerical values on the plot with Matplotlib

You can use the annotate command to place text annotations at any x and y values you want. To place them exactly at the data points you could do this

import numpy
from matplotlib import pyplot

x = numpy.arange(10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])

fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.set_ylim(0,10)
pyplot.plot(x,y)
for i,j in zip(x,y):
    ax.annotate(str(j),xy=(i,j))

pyplot.show()

If you want the annotations offset a little, you could change the annotate line to something like

ax.annotate(str(j),xy=(i,j+0.5))

Calling ASP.NET MVC Action Methods from JavaScript

You are calling the addToCart method and passing the product id. Now you may use jQuery ajax to pass that data to your server side action method.d

jQuery post is the short version of jQuery ajax.

function addToCart(id)
{
  $.post('@Url.Action("Add","Cart")',{id:id } function(data) {
    //do whatever with the result.
  });
}

If you want more options like success callbacks and error handling, use jQuery ajax,

function addToCart(id)
{
  $.ajax({
  url: '@Url.Action("Add","Cart")',
  data: { id: id },
  success: function(data){
    //call is successfully completed and we got result in data
  },
  error:function (xhr, ajaxOptions, thrownError){
                  //some errror, some show err msg to user and log the error  
                  alert(xhr.responseText);

                }    
  });
}

When making ajax calls, I strongly recommend using the Html helper method such as Url.Action to generate the path to your action methods.

This will work if your code is in a razor view because Url.Action will be executed by razor at server side and that c# expression will be replaced with the correct relative path. But if you are using your jQuery code in your external js file, You may consider the approach mentioned in this answer.

Switch firefox to use a different DNS than what is in the windows.host file

What about having different names for your dev and prod servers? That should avoid any confusions and you'd not have to edit the hosts file every time.

Why use #ifndef CLASS_H and #define CLASS_H in .h file but not in .cpp?

First, to address your first inquiry:

When you see this in .h file:

#ifndef FILE_H
#define FILE_H

/* ... Declarations etc here ... */

#endif

This is a preprocessor technique of preventing a header file from being included multiple times, which can be problematic for various reasons. During compilation of your project, each .cpp file (usually) is compiled. In simple terms, this means the compiler will take your .cpp file, open any files #included by it, concatenate them all into one massive text file, and then perform syntax analysis and finally it will convert it to some intermediate code, optimize/perform other tasks, and finally generate the assembly output for the target architecture. Because of this, if a file is #included multiple times under one .cpp file, the compiler will append its file contents twice, so if there are definitions within that file, you will get a compiler error telling you that you redefined a variable. When the file is processed by the preprocessor step in the compilation process, the first time its contents are reached the first two lines will check if FILE_H has been defined for the preprocessor. If not, it will define FILE_H and continue processing the code between it and the #endif directive. The next time that file's contents are seen by the preprocessor, the check against FILE_H will be false, so it will immediately scan down to the #endif and continue after it. This prevents redefinition errors.

And to address your second concern:

In C++ programming as a general practice we separate development into two file types. One is with an extension of .h and we call this a "header file." They usually provide a declaration of functions, classes, structs, global variables, typedefs, preprocessing macros and definitions, etc. Basically, they just provide you with information about your code. Then we have the .cpp extension which we call a "code file." This will provide definitions for those functions, class members, any struct members that need definitions, global variables, etc. So the .h file declares code, and the .cpp file implements that declaration. For this reason, we generally during compilation compile each .cpp file into an object and then link those objects (because you almost never see one .cpp file include another .cpp file).

How these externals are resolved is a job for the linker. When your compiler processes main.cpp, it gets declarations for the code in class.cpp by including class.h. It only needs to know what these functions or variables look like (which is what a declaration gives you). So it compiles your main.cpp file into some object file (call it main.obj). Similarly, class.cpp is compiled into a class.obj file. To produce the final executable, a linker is invoked to link those two object files together. For any unresolved external variables or functions, the compiler will place a stub where the access happens. The linker will then take this stub and look for the code or variable in another listed object file, and if it's found, it combines the code from the two object files into an output file and replaces the stub with the final location of the function or variable. This way, your code in main.cpp can call functions and use variables in class.cpp IF AND ONLY IF THEY ARE DECLARED IN class.h.

I hope this was helpful.

How can a divider line be added in an Android RecyclerView?

To make N J's answer a little simpler you can do:

public class DividerColorItemDecoration extends DividerItemDecoration {

    public DividerColorItemDecoration(Context context, int orientation) {
        super(context, orientation);
        setDrawable(ContextCompat.getDrawable(context, R.drawable.line_divider));
    }
}

How to find largest objects in a SQL Server database?

In SQL Server 2008, you can also just run the standard report Disk Usage by Top Tables. This can be found by right clicking the DB, selecting Reports->Standard Reports and selecting the report you want.

How do I setup the dotenv file in Node.js?

If you are facing this problem it could be that the environment variable(s) is added/loaded after the file that requires the specific variable

const express = require('express');

const app = express();
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const morgan = require('morgan');

const passport = require('passport'); //you want to use process.env.JWT_SECRET (you will get undefined)

dotenv.config();

in the above case, you will get undefined for the process.env.JWT_SECRET

So the solution is that you put dotenv.config() before const passport = require('passport');

const express = require('express');

const app = express();
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const morgan = require('morgan');
dotenv.config();   
const passport = require('passport'); //you want to use process.env.JWT_SECRET (you will get the value for the enviroment variable)

Where is SQLite database stored on disk?

SQLite is created in your python directory where you installed the python.

Upgrading PHP on CentOS 6.5 (Final)

Steps for upgrading to PHP7 on CentOS 6 system. Taken from install-php-7-in-centos-6

To install latest PHP 7, you need to add EPEL and Remi repository to your CentOS 6 system

yum install https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm
yum install http://rpms.remirepo.net/enterprise/remi-release-6.rpm

Now install yum-utils, a group of useful tools that enhance yum’s default package management features

yum install yum-utils

In this step, you need to enable Remi repository using yum-config-manager utility, as the default repository for installing PHP.

yum-config-manager --enable remi-php70

If you want to install PHP 7.1 or PHP 7.2 on CentOS 6, just enable it as shown.

yum-config-manager --enable remi-php71 
yum-config-manager --enable remi-php72

Then finally install PHP 7 on CentOS 6 with all necessary PHP modules using the following command.

yum install php php-mcrypt php-cli php-gd php-curl php-mysql php-ldap php-zip php-fileinfo

Double check the installed version of PHP on your system as follows.

php -V 

What's the difference between Instant and LocalDateTime?

Table of all date-time types in Java, both modern and legacy

tl;dr

Instant and LocalDateTime are two entirely different animals: One represents a moment, the other does not.

  • Instant represents a moment, a specific point in the timeline.
  • LocalDateTime represents a date and a time-of-day. But lacking a time zone or offset-from-UTC, this class cannot represent a moment. It represents potential moments along a range of about 26 to 27 hours, the range of all time zones around the globe. A LocalDateTime value is inherently ambiguous.

Incorrect Presumption

LocalDateTime is rather date/clock representation including time-zones for humans.

Your statement is incorrect: A LocalDateTime has no time zone. Having no time zone is the entire point of that class.

To quote that class’ doc:

This class does not store or represent a time-zone. Instead, it is a description of the date, as used for birthdays, combined with the local time as seen on a wall clock. It cannot represent an instant on the time-line without additional information such as an offset or time-zone.

So Local… means “not zoned, no offset”.

Instant

enter image description here

An Instant is a moment on the timeline in UTC, a count of nanoseconds since the epoch of the first moment of 1970 UTC (basically, see class doc for nitty-gritty details). Since most of your business logic, data storage, and data exchange should be in UTC, this is a handy class to be used often.

Instant instant = Instant.now() ;  // Capture the current moment in UTC.

OffsetDateTime

enter image description here

The class OffsetDateTime class represents a moment as a date and time with a context of some number of hours-minutes-seconds ahead of, or behind, UTC. The amount of offset, the number of hours-minutes-seconds, is represented by the ZoneOffset class.

If the number of hours-minutes-seconds is zero, an OffsetDateTime represents a moment in UTC the same as an Instant.

ZoneOffset

enter image description here

The ZoneOffset class represents an offset-from-UTC, a number of hours-minutes-seconds ahead of UTC or behind UTC.

A ZoneOffset is merely a number of hours-minutes-seconds, nothing more. A zone is much more, having a name and a history of changes to offset. So using a zone is always preferable to using a mere offset.

ZoneId

enter image description here

A time zone is represented by the ZoneId class.

A new day dawns earlier in Paris than in Montréal, for example. So we need to move the clock’s hands to better reflect noon (when the Sun is directly overhead) for a given region. The further away eastward/westward from the UTC line in west Europe/Africa the larger the offset.

A time zone is a set of rules for handling adjustments and anomalies as practiced by a local community or region. The most common anomaly is the all-too-popular lunacy known as Daylight Saving Time (DST).

A time zone has the history of past rules, present rules, and rules confirmed for the near future.

These rules change more often than you might expect. Be sure to keep your date-time library's rules, usually a copy of the 'tz' database, up to date. Keeping up-to-date is easier than ever now in Java 8 with Oracle releasing a Timezone Updater Tool.

Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

Time Zone = Offset + Rules of Adjustments

ZoneId z = ZoneId.of( “Africa/Tunis” ) ; 

ZonedDateTime

enter image description here

Think of ZonedDateTime conceptually as an Instant with an assigned ZoneId.

ZonedDateTime = ( Instant + ZoneId )

To capture the current moment as seen in the wall-clock time used by the people of a particular region (a time zone):

ZonedDateTime zdt = ZonedDateTime.now( z ) ;  // Pass a `ZoneId` object such as `ZoneId.of( "Europe/Paris" )`. 

Nearly all of your backend, database, business logic, data persistence, data exchange should all be in UTC. But for presentation to users you need to adjust into a time zone expected by the user. This is the purpose of the ZonedDateTime class and the formatter classes used to generate String representations of those date-time values.

ZonedDateTime zdt = instant.atZone( z ) ;
String output = zdt.toString() ;                 // Standard ISO 8601 format.

You can generate text in localized format using DateTimeFormatter.

DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( Locale.CANADA_FRENCH ) ; 
String outputFormatted = zdt.format( f ) ;

mardi 30 avril 2019 à 23 h 22 min 55 s heure de l’Inde

LocalDate, LocalTime, LocalDateTime

Diagram showing only a calendar for a LocalDate.

Diagram showing only a clock for a LocalTime.

Diagram showing a calendar plus clock for a LocalDateTime.

The "local" date time classes, LocalDateTime, LocalDate, LocalTime, are a different kind of critter. The are not tied to any one locality or time zone. They are not tied to the timeline. They have no real meaning until you apply them to a locality to find a point on the timeline.

The word “Local” in these class names may be counter-intuitive to the uninitiated. The word means any locality, or every locality, but not a particular locality.

So for business apps, the "Local" types are not often used as they represent just the general idea of a possible date or time not a specific moment on the timeline. Business apps tend to care about the exact moment an invoice arrived, a product shipped for transport, an employee was hired, or the taxi left the garage. So business app developers use Instant and ZonedDateTime classes most commonly.

So when would we use LocalDateTime? In three situations:

  • We want to apply a certain date and time-of-day across multiple locations.
  • We are booking appointments.
  • We have an intended yet undetermined time zone.

Notice that none of these three cases involve a single certain specific point on the timeline, none of these are a moment.

One time-of-day, multiple moments

Sometimes we want to represent a certain time-of-day on a certain date, but want to apply that into multiple localities across time zones.

For example, "Christmas starts at midnight on the 25th of December 2015" is a LocalDateTime. Midnight strikes at different moments in Paris than in Montréal, and different again in Seattle and in Auckland.

LocalDate ld = LocalDate.of( 2018 , Month.DECEMBER , 25 ) ;
LocalTime lt = LocalTime.MIN ;   // 00:00:00
LocalDateTime ldt = LocalDateTime.of( ld , lt ) ;  // Christmas morning anywhere. 

Another example, "Acme Company has a policy that lunchtime starts at 12:30 PM at each of its factories worldwide" is a LocalTime. To have real meaning you need to apply it to the timeline to figure the moment of 12:30 at the Stuttgart factory or 12:30 at the Rabat factory or 12:30 at the Sydney factory.

Booking appointments

Another situation to use LocalDateTime is for booking future events (ex: Dentist appointments). These appointments may be far enough out in the future that you risk politicians redefining the time zone. Politicians often give little forewarning, or even no warning at all. If you mean "3 PM next January 23rd" regardless of how the politicians may play with the clock, then you cannot record a moment – that would see 3 PM turn into 2 PM or 4 PM if that region adopted or dropped Daylight Saving Time, for example.

For appointments, store a LocalDateTime and a ZoneId, kept separately. Later, when generating a schedule, on-the-fly determine a moment by calling LocalDateTime::atZone( ZoneId ) to generate a ZonedDateTime object.

ZonedDateTime zdt = ldt.atZone( z ) ;  // Given a date, a time-of-day, and a time zone, determine a moment, a point on the timeline.

If needed, you can adjust to UTC. Extract an Instant from the ZonedDateTime.

Instant instant = zdt.toInstant() ;  // Adjust from some zone to UTC. Same moment, same point on the timeline, different wall-clock time.

Unknown zone

Some people might use LocalDateTime in a situation where the time zone or offset is unknown.

I consider this case inappropriate and unwise. If a zone or offset is intended but undetermined, you have bad data. That would be like storing a price of a product without knowing the intended currency (dollars, pounds, euros, etc.). Not a good idea.

All date-time types

For completeness, here is a table of all the possible date-time types, both modern and legacy in Java, as well as those defined by the SQL standard. This might help to place the Instant & LocalDateTime classes in a larger context.

Table of all date-time types in Java (both modern & legacy) as well as SQL standard.

Notice the odd choices made by the Java team in designing JDBC 4.2. They chose to support all the java.time times… except for the two most commonly used classes: Instant & ZonedDateTime.

But not to worry. We can easily convert back and forth.

Converting Instant.

// Storing
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
myPreparedStatement.setObject( … , odt ) ;

// Retrieving
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
Instant instant = odt.toInstant() ;

Converting ZonedDateTime.

// Storing
OffsetDateTime odt = zdt.toOffsetDateTime() ;
myPreparedStatement.setObject( … , odt ) ;

// Retrieving
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = odt.atZone( z ) ; 

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to debug in Django, the good way?

There are a bunch of ways to do it, but the most straightforward is to simply use the Python debugger. Just add following line in to a Django view function:

import pdb; pdb.set_trace()

or

breakpoint()  #from Python3.7

If you try to load that page in your browser, the browser will hang and you get a prompt to carry on debugging on actual executing code.

However there are other options (I am not recommending them):

* return HttpResponse({variable to inspect})

* print {variable to inspect}

* raise Exception({variable to inspect})

But the Python Debugger (pdb) is highly recommended for all types of Python code. If you are already into pdb, you'd also want to have a look at IPDB that uses ipython for debugging.

Some more useful extension to pdb are

pdb++, suggested by Antash.

pudb, suggested by PatDuJour.

Using the Python debugger in Django, suggested by Seafangs.

How to run python script in webpage

In order for your code to show, you need several things:

Firstly, there needs to be a server that handles HTTP requests. At the moment you are just opening a file with Firefox on your local hard drive. A server like Apache or something similar is required.

Secondly, presuming that you now have a server that serves the files, you will also need something that interprets the code as Python code for the server. For Python users the go to solution is nowadays mod_wsgi. But for simpler cases you could stick with CGI (more info here), but if you want to produce web pages easily, you should go with a existing Python web framework like Django.

Setting this up can be quite the hassle, so be prepared.

Interfaces vs. abstract classes

The real question is: whether to use interfaces or base classes. This has been covered before.

In C#, an abstract class (one marked with the keyword "abstract") is simply a class from which you cannot instantiate objects. This serves a different purpose than simply making the distinction between base classes and interfaces.

How to get image width and height in OpenCV?

Also for openCV in python you can do:

img = cv2.imread('myImage.jpg')
height, width, channels = img.shape 

T-SQL CASE Clause: How to specify WHEN NULL

CASE  
    WHEN last_name IS null THEN '' 
    ELSE ' ' + last_name 
END

jQuery rotate/transform

t = setTimeout(function() { rotate(++degree); },65);

and clearTimeout to stop

clearTimeout(t);

I use this with AJAX

success:function(){ clearTimeout(t); }

Find index of last occurrence of a sub-string using T-SQL

This worked very well for me.

REVERSE(SUBSTRING(REVERSE([field]), CHARINDEX(REVERSE('[expr]'), REVERSE([field])) + DATALENGTH('[expr]'), DATALENGTH([field])))

How to read a single char from the console in Java (as the user types it)?

You need to knock your console into raw mode. There is no built-in platform-independent way of getting there. jCurses might be interesting, though.

On a Unix system, this might work:

String[] cmd = {"/bin/sh", "-c", "stty raw </dev/tty"};
Runtime.getRuntime().exec(cmd).waitFor();

For example, if you want to take into account the time between keystrokes, here's sample code to get there.

Purpose of __repr__ method?

__repr__ is used by the standalone Python interpreter to display a class in printable format. Example:

~> python3.5
Python 3.5.1 (v3.5.1:37a07cee5969, Dec  5 2015, 21:12:44) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class StackOverflowDemo:
...     def __init__(self):
...         pass
...     def __repr__(self):
...         return '<StackOverflow demo object __repr__>'
... 
>>> demo = StackOverflowDemo()
>>> demo
<StackOverflow demo object __repr__>

In cases where a __str__ method is not defined in the class, it will call the __repr__ function in an attempt to create a printable representation.

>>> str(demo)
'<StackOverflow demo object __repr__>'

Additionally, print()ing the class will call __str__ by default.


Documentation, if you please

How to select into a variable in PL/SQL when the result might be null?

I use this syntax for flexibility and speed -

    begin
    --
    with KLUJ as
    ( select 0 ROES from dual
       union 
      select count(*) from MY_TABLE where rownum = 1
    ) select max(ROES) into has_rows from KLUJ;
    --
    end;

Dual returns 1 row, rownum adds 0 or 1 rows, and max() groups to exactly 1. This gives 0 for no rows in a table and 1 for any other number of rows.

I extend the where clause to count rows by condition, remove rownum to count rows meeting a condition, and increase rownum to count rows meeting the condition up to a limit.

Setting Java heap space under Maven 2 on Windows

It worked - To change in Eclipse, go to Window -> Preferences -> Java -> Installed JREs. Select the checked JRE/JDK and click edit.

Default VM Arguments = -Xms128m -Xmx1024m

How to check postgres user and password?

You will not be able to find out the password he chose. However, you may create a new user or set a new password to the existing user.

Usually, you can login as the postgres user:

Open a Terminal and do sudo su postgres. Now, after entering your admin password, you are able to launch psql and do

CREATE USER yourname WITH SUPERUSER PASSWORD 'yourpassword';

This creates a new admin user. If you want to list the existing users, you could also do

\du

to list all users and then

ALTER USER yourusername WITH PASSWORD 'yournewpass';

Lock screen orientation (Android)

In the Manifest, you can set the screenOrientation to landscape. It would look something like this in the XML:

<activity android:name="MyActivity"
android:screenOrientation="landscape"
android:configChanges="keyboardHidden|orientation|screenSize">
...
</activity>

Where MyActivity is the one you want to stay in landscape.

The android:configChanges=... line prevents onResume(), onPause() from being called when the screen is rotated. Without this line, the rotation will stay as you requested but the calls will still be made.

Note: keyboardHidden and orientation are required for < Android 3.2 (API level 13), and all three options are required 3.2 or above, not just orientation.

Android : How to read file in bytes?

You can also do it this way:

byte[] getBytes (File file)
{
    FileInputStream input = null;
    if (file.exists()) try
    {
        input = new FileInputStream (file);
        int len = (int) file.length();
        byte[] data = new byte[len];
        int count, total = 0;
        while ((count = input.read (data, total, len - total)) > 0) total += count;
        return data;
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
    finally
    {
        if (input != null) try
        {
            input.close();
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
    return null;
}

How to set up file permissions for Laravel?

First of your answer is.

sudo chmod -R 777/775 /path/project_folder

Now You need to understand permissions and options in ubuntu.

  • chmod - You can set permissions.
  • chown - You can set the ownership of files and directories.
  • 777 - read/write/execute.
  • 775 - read/execute.

GET parameters in the URL with CodeIgniter

GET parameters are cached by the web browser, POST is not. So with a POST you don't have to worry about caching, so that is why it is usually prefered.

How to delete all data from solr and hbase

Use the "match all docs" query in a delete by query command: :

You must also commit after running the delete so, to empty the index, run the following two commands:

curl http://localhost:8983/solr/update --data '<delete><query>*:*</query></delete>' -H 'Content-type:text/xml; charset=utf-8'

curl http://localhost:8983/solr/update --data '<commit/>' -H 'Content-type:text/xml; charset=utf-8'

"Full screen" <iframe>

Try adding the following attribute:

scrolling="no"

JSON find in JavaScript

(You're not searching through "JSON", you're searching through an array -- the JSON string has already been deserialized into an object graph, in this case an array.)

Some options:

Use an Object Instead of an Array

If you're in control of the generation of this thing, does it have to be an array? Because if not, there's a much simpler way.

Say this is your original data:

[
    {"id": "one",   "pId": "foo1", "cId": "bar1"},
    {"id": "two",   "pId": "foo2", "cId": "bar2"},
    {"id": "three", "pId": "foo3", "cId": "bar3"}
]

Could you do the following instead?

{
    "one":   {"pId": "foo1", "cId": "bar1"},
    "two":   {"pId": "foo2", "cId": "bar2"},
    "three": {"pId": "foo3", "cId": "bar3"}
}

Then finding the relevant entry by ID is trivial:

id = "one"; // Or whatever
var entry = objJsonResp[id];

...as is updating it:

objJsonResp[id] = /* New value */;

...and removing it:

delete objJsonResp[id];

This takes advantage of the fact that in JavaScript, you can index into an object using a property name as a string -- and that string can be a literal, or it can come from a variable as with id above.

Putting in an ID-to-Index Map

(Dumb idea, predates the above. Kept for historical reasons.)

It looks like you need this to be an array, in which case there isn't really a better way than searching through the array unless you want to put a map on it, which you could do if you have control of the generation of the object. E.g., say you have this originally:

[
    {"id": "one",   "pId": "foo1", "cId": "bar1"},
    {"id": "two",   "pId": "foo2", "cId": "bar2"},
    {"id": "three", "pId": "foo3", "cId": "bar3"}
]

The generating code could provide an id-to-index map:

{
    "index": {
        "one": 0, "two": 1, "three": 2
    },
    "data": [
        {"id": "one",   "pId": "foo1", "cId": "bar1"},
        {"id": "two",   "pId": "foo2", "cId": "bar2"},
        {"id": "three", "pId": "foo3", "cId": "bar3"}
    ]
}

Then getting an entry for the id in the variable id is trivial:

var index = objJsonResp.index[id];
var obj = objJsonResp.data[index];

This takes advantage of the fact you can index into objects using property names.

Of course, if you do that, you have to update the map when you modify the array, which could become a maintenance problem.

But if you're not in control of the generation of the object, or updating the map of ids-to-indexes is too much code and/ora maintenance issue, then you'll have to do a brute force search.

Brute Force Search (corrected)

Somewhat OT (although you did ask if there was a better way :-) ), but your code for looping through an array is incorrect. Details here, but you can't use for..in to loop through array indexes (or rather, if you do, you have to take special pains to do so); for..in loops through the properties of an object, not the indexes of an array. Your best bet with a non-sparse array (and yours is non-sparse) is a standard old-fashioned loop:

var k;
for (k = 0; k < someArray.length; ++k) { /* ... */ }

or

var k;
for (k = someArray.length - 1; k >= 0; --k) { /* ... */ }

Whichever you prefer (the latter is not always faster in all implementations, which is counter-intuitive to me, but there we are). (With a sparse array, you might use for..in but again taking special pains to avoid pitfalls; more in the article linked above.)

Using for..in on an array seems to work in simple cases because arrays have properties for each of their indexes, and their only other default properties (length and their methods) are marked as non-enumerable. But it breaks as soon as you set (or a framework sets) any other properties on the array object (which is perfectly valid; arrays are just objects with a bit of special handling around the length property).

java : non-static variable cannot be referenced from a static context Error

Your main() method is static, but it is referencing two non-static members: con2 and getConnectionUrl2(). You need to do one of three things:

1) Make con2 and getConnectionUrl2() static.

2) Inside main(), create an instance of class testconnect and access con2 and getConnectionUrl2() off of that.

3) Break out a different class to hold con2 and getConnectionUrl2() so that testconnect only has main in it. It will still need to instantiate the different class and call the methods off that.

Option #3 is the best option. #1 is the worst.

But, you cannot access non-static members from within a static method.

How to increase space between dotted border dots

AFAIK there isn't a way to do this. You could use a dashed border or perhaps increase the width of the border a bit, but just getting more spaced out dots is impossible with CSS.

How to save a list to a file and read it as a list type?

Although the accepted answer works, you should really be using python's json module:

import json

score=[1,2,3,4,5]

with open("file.json", 'w') as f:
    # indent=2 is not needed but makes the file human-readable
    json.dump(score, f, indent=2) 

with open("file.json", 'r') as f:
    score = json.load(f)

print(score)

Advantages:

  1. json is a widely adopted and standardized data format, so non-python programs can easily read and understand the json files
  2. json files are human-readable
  3. Any nested or non-nested list/dictionary structure can be saved to a json file (as long as all the contents are serializable).

Disadvantages:

  1. The data is stored in plain-text (ie it's uncompressed), which makes it a slow and bloated option for large amounts of data (ie probably a bad option for storing large numpy arrays, that's what hdf5 is for).
  2. The contents of a list/dictionary need to be serializable before you can save it as a json, so while you can save things like strings, ints, and floats, you'll need to write custom serialization and deserialization code to save objects, classes, and functions

When to use json vs pickle:

  • If you want to store something you know you're only ever going to use in the context of a python program, use pickle
  • If you need to save data that isn't serializable by default (ie objects), save yourself the trouble and use pickle.
  • If you need a platform agnostic solution, use json
  • If you need to be able to inspect and edit the data directly, use json

Common use cases:

  • Configuration files (for example, node.js uses a package.json file to track project details, dependencies, scripts, etc ...)
  • Most REST APIs use json to transmit and receive data
  • Data that requires a nested list/dictionary structure, or requires variable length lists/dicts
  • Can be an alternative to csv, xml or yaml files

PackagesNotFoundError: The following packages are not available from current channels:

Even i was facing the same problem ,but solved it by

conda install -c conda-forge pysoundfile

while importing it

import soundfile 

Open youtube video in Fancybox jquery

If you wanna add autoplay function to it. Simply replace

this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'), 

with

this.href = this.href.replace(new RegExp("watch\\?v=", "i"), 'v/') + '&autoplay=1',

also you can do the same with vimeo

this.href.replace(new RegExp("([0-9])","i"),'moogaloop.swf?clip_id=$1'),

with

this.href = this.href.replace(new RegExp("([0-9])","i"),'moogaloop.swf?clip_id=$1') + '&autoplay=1',

Determine if string is in list in JavaScript

EcmaScript 6 and up

If you're using ES6 or higher, the cleanest way is to construct an array of the items and use Array.includes:

['a', 'b', 'c'].includes('b')

This has some inherent benefits over indexOf because it can properly test for the presence of NaN in the list, and can match missing array elements such as the middle one in [1, , 2] to undefined. includes also works on JavaScript typed arrays such as Uint8Array.

If you're concerned about browser support (such as for IE or Edge), you can check Array.includes at CanIUse.Com, and if you want to target a browser or browser version that's missing includes, I recommend polyfill.io for polyfilling.

Without An Array

You could add a new isInList property to strings as follows:

if (!String.prototype.isInList) {
  Object.defineProperty(String.prototype, 'isInList', {
    get: () => function(...args) {
      let value = this.valueOf();
      for (let i = 0, l = args.length; i < l; i += 1) {
        if (arguments[i] === value) return true;
      }
      return false;
    }
  });
}

Then use it like so:

'fox'.isInList('weasel', 'fox', 'stoat') // true
'fox'.isInList('weasel', 'stoat') // false

You can do the same thing for Number.prototype.

Note that Object.defineProperty cannot be used in IE8 and earlier, or very old versions of other browsers. However, it is a far superior solution to String.prototype.isInList = function() { ... } because using simple assignment like that will create an enumerable property on String.prototype, which is more likely to break code.

Array.indexOf

If you are using a modern browser, indexOf always works. However, for IE8 and earlier you'll need a polyfill.

If indexOf returns -1, the item is not in the list. Be mindful though, that this method will not properly check for NaN, and while it can match an explicit undefined, it can’t match a missing element to undefined as in the array [1, , 2].

Polyfill for indexOf or includes in IE, or any other browser/version lacking support

If you don't want to use a service like polyfill.io as mentioned above, you can always include in your own source code standards-compliant custom polyfills. For example, Mozilla Developer Network has one for indexOf.

In this situation where I had to make a solution for Internet Explorer 7, I "rolled my own" simpler version of the indexOf() function that is not standards-compliant:

if (!Array.prototype.indexOf) {
   Array.prototype.indexOf = function(item) {
      var i = this.length;
      while (i--) {
         if (this[i] === item) return i;
      }
      return -1;
   }
}

However, I don't think modifying Array.prototype is the best answer in the long term. Modifying Object and Array prototypes in JavaScript can lead to serious bugs. You need to decide whether doing so is safe in your own environment. Of primary note is that iterating an array (when Array.prototype has added properties) with for ... in will return the new function name as one of the keys:

Array.prototype.blah = function() { console.log('blah'); };
let arr = [1, 2, 3];
for (let x in arr) { console.log(x); }
// Result:
0
1
2
blah // Extra member iterated over!

Your code may work now, but the moment someone in the future adds a third-party JavaScript library or plugin that isn't zealously guarding against inherited keys, everything can break.

The old way to avoid that breakage is, during enumeration, to check each value to see if the object actually has it as a non-inherited property with if (arr.hasOwnProperty(x)) and only then work with that x.

The new ES6 ways to avoid this extra-key problem are:

  1. Use of instead of in, for (let x of arr). However, unless you can guarantee that all of your code and third-party libraries strictly stick to this method, then for the purposes of this question you'll probably just want to use includes as stated above.

  2. Define your new properties on the prototype using Object.defineProperty(), as this will make the property (by default) non-enumerable. This only truly solves the problem if all the JavaScript libraries or modules you use also do this.

How to keep one variable constant with other one changing with row in excel

There are two kinds of cell reference, and it's really valuable to understand them well.

One is relative reference, which is what you get when you just type the cell: A5. This reference will be adjusted when you paste or fill the formula into other cells.

The other is absolute reference, and you get this by adding dollar signs to the cell reference: $A$5. This cell reference will not change when pasted or filled.

A cool but rarely used feature is that row and column within a single cell reference may be independent: $A5 and A$5. This comes in handy for producing things like multiplication tables from a single formula.

How do I get the result of a command in a variable in windows?

I would like to add a remark to the above solutions:

All these syntaxes work perfectly well IF YOUR COMMAND IS FOUND WITHIN THE PATH or IF THE COMMAND IS A cmdpath WITHOUT SPACES OR SPECIAL CHARACTERS.

But if you try to use an executable command located in a folder which path contains special characters then you would need to enclose your command path into double quotes (") and then the FOR /F syntax does not work.

Examples:

$ for /f "tokens=* USEBACKQ" %f in (
    `""F:\GLW7\Distrib\System\Shells and scripting\f2ko.de\folderbrowse.exe"" Hello '"F:\GLW7\Distrib\System\Shells and scripting"'`
) do echo %f
The filename, directory name, or volume label syntax is incorrect.

or

$ for /f "tokens=* USEBACKQ" %f in (
      `"F:\GLW7\Distrib\System\Shells and scripting\f2ko.de\folderbrowse.exe" "Hello World" "F:\GLW7\Distrib\System\Shells and scripting"`
) do echo %f
'F:\GLW7\Distrib\System\Shells' is not recognized as an internal or external command, operable program or batch file.

or

`$ for /f "tokens=* USEBACKQ" %f in (
     `""F:\GLW7\Distrib\System\Shells and scripting\f2ko.de\folderbrowse.exe"" "Hello World" "F:\GLW7\Distrib\System\Shells and scripting"`
) do echo %f
'"F:\GLW7\Distrib\System\Shells and scripting\f2ko.de\folderbrowse.exe"" "Hello' is not recognized as an internal or external command, operable program or batch file.

In that case, the only solution I found to use a command and store its result in a variable is to set (temporarily) the default directory to the one of command itself :

pushd "%~d0%~p0"
FOR /F "tokens=* USEBACKQ" %%F IN (
    `FOLDERBROWSE "Hello world!" "F:\GLW7\Distrib\System\Layouts (print,display...)"`
) DO (SET MyFolder=%%F)
popd
echo My selected folder: %MyFolder%

The result is then correct:

My selected folder: F:\GLW7\Distrib\System\OS install, recovery, VM\
Press any key to continue . . .

Of course in the above example, I assume that my batch script is located in the same folder as the one of my executable command so that I can use the "%~d0%~p0" syntax. If this is not your case, then you have to find a way to locate your command path and change the default directory to its path.

NB: For those who wonder, the sample command used here (to select a folder) is FOLDERBROWSE.EXE. I found it on the web site f2ko.de (http://f2ko.de/en/cmd.php).

If anyone has a better solution for that kind of commands accessible through a complex path, I will be very glad to hear of it.

Gilles

Jquery to open Bootstrap v3 modal of remote url

If using @worldofjr answer in jQuery you are getting error:

e.relatedTarget.data is not a function

you should use:

$('#myModal').on('show.bs.modal', function (e) {
    var loadurl = $(e.relatedTarget).data('load-url');
    $(this).find('.modal-body').load(loadurl);
});

Not that e.relatedTarget if wrapped by $(..)

I was getting the error in latest Bootstrap 3 and after using this method it's working without any problem.

Querying Windows Active Directory server using ldapsearch from command line

You could query an LDAP server from the command line with ldap-utils: ldapsearch, ldapadd, ldapmodify

Finding blocking/locking queries in MS SQL (mssql)

I found this query which helped me find my locked table and query causing the issue.

SELECT  L.request_session_id AS SPID, 
        DB_NAME(L.resource_database_id) AS DatabaseName,
        O.Name AS LockedObjectName, 
        P.object_id AS LockedObjectId, 
        L.resource_type AS LockedResource, 
        L.request_mode AS LockType,
        ST.text AS SqlStatementText,        
        ES.login_name AS LoginName,
        ES.host_name AS HostName,
        TST.is_user_transaction as IsUserTransaction,
        AT.name as TransactionName,
        CN.auth_scheme as AuthenticationMethod
FROM    sys.dm_tran_locks L
        JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
        JOIN sys.objects O ON O.object_id = P.object_id
        JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
        JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
        JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
        JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
        CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE   resource_database_id = db_id()
ORDER BY L.request_session_id

Is it necessary to use # for creating temp tables in SQL server?

Yes. You need to prefix the table name with "#" (hash) to create temporary tables.

If you do NOT need the table later, go ahead & create it. Temporary Tables are very much like normal tables. However, it gets created in tempdb. Also, it is only accessible via the current session i.e. For EG: if another user tries to access the temp table created by you, he'll not be able to do so.

"##" (double-hash creates "Global" temp table that can be accessed by other sessions as well.

Refer the below link for the Basics of Temporary Tables: http://www.codeproject.com/Articles/42553/Quick-Overview-Temporary-Tables-in-SQL-Server-2005

If the content of your table is less than 5000 rows & does NOT contain data types such as nvarchar(MAX), varbinary(MAX), consider using Table Variables.

They are the fastest as they are just like any other variables which are stored in the RAM. They are stored in tempdb as well, not in RAM.

DECLARE @ItemBack1 TABLE
(
 column1 int,
 column2 int,
 someInt int,
 someVarChar nvarchar(50)
);

INSERT INTO @ItemBack1
SELECT column1, 
       column2, 
       someInt, 
       someVarChar 
  FROM table2
 WHERE table2.ID = 7;

More Info on Table Variables: http://odetocode.com/articles/365.aspx

jQuery click anywhere in the page except on 1 div

You can apply click on body of document and cancel click processing if the click event is generated by div with id menu_content, This will bind event to single element and saving binding of click with every element except menu_content

$('body').click(function(evt){    
       if(evt.target.id == "menu_content")
          return;
       //For descendants of menu_content being clicked, remove this check if you do not want to put constraint on descendants.
       if($(evt.target).closest('#menu_content').length)
          return;             

      //Do processing of click event here for every element except with id menu_content

});

Accessing last x characters of a string in Bash

You can use tail:

$ foo="1234567890"
$ echo -n $foo | tail -c 3
890

A somewhat roundabout way to get the last three characters would be to say:

echo $foo | rev | cut -c1-3 | rev

How does one Display a Hyperlink in React Native App?

If you want to do links and other types of rich text, a more comprehensive solution is to use React Native HTMLView.

Frame Buster Buster ... buster code needed

We have used the following approach in one of our websites from http://seclab.stanford.edu/websec/framebusting/framebust.pdf

<style>
 body { 
 display : none   
}
</style>
<script>
if(self == top) {
document.getElementsByTagName("body")[0].style.display = 'block';
}
else{
top.location = self.location;
}
</script>

How to reset the use/password of jenkins on windows?

1 ) Copy the initialAdminPassword in Specified path.

2 ) Login with following Credentials

User Name : admin

Password : <da12906084fd405090a9fabfd66342f0> 

enter image description here

3 ) Once you login into the jenkins application you can click on admin profile and reset the password.

enter image description here

How can I run a html file from terminal?

we could open html file from linux/unix by using firefox .html

How to Handle Button Click Events in jQuery?

 $("#btnSubmit").click(function(){
        alert("button");
    });    

SQL Server Linked Server Example Query

The format should probably be:

<server>.<database>.<schema>.<table>

For example: DatabaseServer1.db1.dbo.table1


Update: I know this is an old question and the answer I have is correct; however, I think any one else stumbling upon this should know a few things.

Namely, when querying against a linked server in a join situation the ENTIRE table from the linked server will likely be downloaded to the server the query is executing from in order to do the join operation. In the OP's case, both table1 from DB1 and table1 from DB2 will be transferred in their entirety to the server executing the query, presumably named DB3.

If you have large tables, this may result in an operation that takes a long time to execute. After all it is now constrained by network traffic speeds which is orders of magnitude slower than memory or even disk transfer speeds.

If possible, perform a single query against the remote server, without joining to a local table, to pull the data you need into a temp table. Then query off of that.

If that's not possible then you need to look at the various things that would cause SQL server to have to load the entire table locally. For example using GETDATE() or even certain joins. Others performance killers include not giving appropriate rights.

See http://thomaslarock.com/2013/05/top-3-performance-killers-for-linked-server-queries/ for some more info.

How to customize the background/border colors of a grouped table view cell?

First of all thanks for this code. I have made some drawing changes in this function to remove corner problem of drawing.

-(void)drawRect:(CGRect)rect 
{
    // Drawing code

    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(c, [fillColor CGColor]);
    CGContextSetStrokeColorWithColor(c, [borderColor CGColor]);
    CGContextSetLineWidth(c, 2);

    if (position == CustomCellBackgroundViewPositionTop) {

        CGFloat minx = CGRectGetMinX(rect) , midx = CGRectGetMidX(rect), maxx = CGRectGetMaxX(rect) ;
        CGFloat miny = CGRectGetMinY(rect) , maxy = CGRectGetMaxY(rect) ;
        minx = minx + 1;
        miny = miny + 1;

        maxx = maxx - 1;
        maxy = maxy ;

        CGContextMoveToPoint(c, minx, maxy);
        CGContextAddArcToPoint(c, minx, miny, midx, miny, ROUND_SIZE);
        CGContextAddArcToPoint(c, maxx, miny, maxx, maxy, ROUND_SIZE);
        CGContextAddLineToPoint(c, maxx, maxy);

        // Close the path
        CGContextClosePath(c);
        // Fill & stroke the path
        CGContextDrawPath(c, kCGPathFillStroke);        
        return;
    } else if (position == CustomCellBackgroundViewPositionBottom) {

        CGFloat minx = CGRectGetMinX(rect) , midx = CGRectGetMidX(rect), maxx = CGRectGetMaxX(rect) ;
        CGFloat miny = CGRectGetMinY(rect) , maxy = CGRectGetMaxY(rect) ;
        minx = minx + 1;
        miny = miny ;

        maxx = maxx - 1;
        maxy = maxy - 1;

        CGContextMoveToPoint(c, minx, miny);
        CGContextAddArcToPoint(c, minx, maxy, midx, maxy, ROUND_SIZE);
        CGContextAddArcToPoint(c, maxx, maxy, maxx, miny, ROUND_SIZE);
        CGContextAddLineToPoint(c, maxx, miny);
        // Close the path
        CGContextClosePath(c);
        // Fill & stroke the path
        CGContextDrawPath(c, kCGPathFillStroke);    
        return;
    } else if (position == CustomCellBackgroundViewPositionMiddle) {
        CGFloat minx = CGRectGetMinX(rect) , maxx = CGRectGetMaxX(rect) ;
        CGFloat miny = CGRectGetMinY(rect) , maxy = CGRectGetMaxY(rect) ;
        minx = minx + 1;
        miny = miny ;

        maxx = maxx - 1;
        maxy = maxy ;

        CGContextMoveToPoint(c, minx, miny);
        CGContextAddLineToPoint(c, maxx, miny);
        CGContextAddLineToPoint(c, maxx, maxy);
        CGContextAddLineToPoint(c, minx, maxy);

        CGContextClosePath(c);
        // Fill & stroke the path
        CGContextDrawPath(c, kCGPathFillStroke);    
        return;
    }
}

How to avoid mysql 'Deadlock found when trying to get lock; try restarting transaction'

You might try having that delete job operate by first inserting the key of each row to be deleted into a temp table like this pseudocode

create temporary table deletetemp (userid int);

insert into deletetemp (userid)
  select userid from onlineusers where datetime <= now - interval 900 second;

delete from onlineusers where userid in (select userid from deletetemp);

Breaking it up like this is less efficient but it avoids the need to hold a key-range lock during the delete.

Also, modify your select queries to add a where clause excluding rows older than 900 seconds. This avoids the dependency on the cron job and allows you to reschedule it to run less often.

Theory about the deadlocks: I don't have a lot of background in MySQL but here goes... The delete is going to hold a key-range lock for datetime, to prevent rows matching its where clause from being added in the middle of the transaction, and as it finds rows to delete it will attempt to acquire a lock on each page it is modifying. The insert is going to acquire a lock on the page it is inserting into, and then attempt to acquire the key lock. Normally the insert will wait patiently for that key lock to open up but this will deadlock if the delete tries to lock the same page the insert is using because thedelete needs that page lock and the insert needs that key lock. This doesn't seem right for inserts though, the delete and insert are using datetime ranges that don't overlap so maybe something else is going on.

http://dev.mysql.com/doc/refman/5.1/en/innodb-next-key-locking.html

Converting an int into a 4 byte char array (C)

You can try:

void CopyInt(int value, char* buffer) {
  memcpy(buffer, (void*)value, sizeof(int));
}

How can I count the occurrences of a list item?

l2=[1,"feto",["feto",1,["feto"]],['feto',[1,2,3,['feto']]]]
count=0
 def Test(l):   
        global count 
        if len(l)==0:
             return count
        count=l.count("feto")
        for i in l:
             if type(i) is list:
                count+=Test(i)
        return count   
    print(Test(l2))

this will recursive count or search for the item in the list even if it in list of lists

logger configuration to log to file and print to stdout

Here is a complete, nicely wrapped solution based on Waterboy's answer and various other sources. It supports logging to both console and log file, allows for different log level settings, provides colorized output and is easily configurable (also available as Gist):

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# -------------------------------------------------------------------------------
#                                                                               -
#  Python dual-logging setup (console and log file),                            -
#  supporting different log levels and colorized output                         -
#                                                                               -
#  Created by Fonic <https://github.com/fonic>                                  -
#  Date: 04/05/20                                                               -
#                                                                               -
#  Based on:                                                                    -
#  https://stackoverflow.com/a/13733863/1976617                                 -
#  https://uran198.github.io/en/python/2016/07/12/colorful-python-logging.html  -
#  https://en.wikipedia.org/wiki/ANSI_escape_code#Colors                        -
#                                                                               -
# -------------------------------------------------------------------------------

# Imports
import os
import sys
import logging

# Logging formatter supporting colored output
class LogFormatter(logging.Formatter):

    COLOR_CODES = {
        logging.CRITICAL: "\033[1;35m", # bright/bold magenta
        logging.ERROR:    "\033[1;31m", # bright/bold red
        logging.WARNING:  "\033[1;33m", # bright/bold yellow
        logging.INFO:     "\033[0;37m", # white / light gray
        logging.DEBUG:    "\033[1;30m"  # bright/bold black / dark gray
    }

    RESET_CODE = "\033[0m"

    def __init__(self, color, *args, **kwargs):
        super(LogFormatter, self).__init__(*args, **kwargs)
        self.color = color

    def format(self, record, *args, **kwargs):
        if (self.color == True and record.levelno in self.COLOR_CODES):
            record.color_on  = self.COLOR_CODES[record.levelno]
            record.color_off = self.RESET_CODE
        else:
            record.color_on  = ""
            record.color_off = ""
        return super(LogFormatter, self).format(record, *args, **kwargs)

# Setup logging
def setup_logging(console_log_output, console_log_level, console_log_color, logfile_file, logfile_log_level, logfile_log_color, log_line_template):

    # Create logger
    # For simplicity, we use the root logger, i.e. call 'logging.getLogger()'
    # without name argument. This way we can simply use module methods for
    # for logging throughout the script. An alternative would be exporting
    # the logger, i.e. 'global logger; logger = logging.getLogger("<name>")'
    logger = logging.getLogger()

    # Set global log level to 'debug' (required for handler levels to work)
    logger.setLevel(logging.DEBUG)

    # Create console handler
    console_log_output = console_log_output.lower()
    if (console_log_output == "stdout"):
        console_log_output = sys.stdout
    elif (console_log_output == "stderr"):
        console_log_output = sys.stderr
    else:
        print("Failed to set console output: invalid output: '%s'" % console_log_output)
        return False
    console_handler = logging.StreamHandler(console_log_output)

    # Set console log level
    try:
        console_handler.setLevel(console_log_level.upper()) # only accepts uppercase level names
    except:
        print("Failed to set console log level: invalid level: '%s'" % console_log_level)
        return False

    # Create and set formatter, add console handler to logger
    console_formatter = LogFormatter(fmt=log_line_template, color=console_log_color)
    console_handler.setFormatter(console_formatter)
    logger.addHandler(console_handler)

    # Create log file handler
    try:
        logfile_handler = logging.FileHandler(logfile_file)
    except Exception as exception:
        print("Failed to set up log file: %s" % str(exception))
        return False

    # Set log file log level
    try:
        logfile_handler.setLevel(logfile_log_level.upper()) # only accepts uppercase level names
    except:
        print("Failed to set log file log level: invalid level: '%s'" % logfile_log_level)
        return False

    # Create and set formatter, add log file handler to logger
    logfile_formatter = LogFormatter(fmt=log_line_template, color=logfile_log_color)
    logfile_handler.setFormatter(logfile_formatter)
    logger.addHandler(logfile_handler)

    # Success
    return True

# Main function
def main():

    # Setup logging
    script_name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
    if (not setup_logging(console_log_output="stdout", console_log_level="warning", console_log_color=True,
                        logfile_file=script_name + ".log", logfile_log_level="debug", logfile_log_color=False,
                        log_line_template="%(color_on)s[%(created)d] [%(threadName)s] [%(levelname)-8s] %(message)s%(color_off)s")):
        print("Failed to setup logging, aborting.")
        return 1

    # Log some messages
    logging.debug("Debug message")
    logging.info("Info message")
    logging.warning("Warning message")
    logging.error("Error message")
    logging.critical("Critical message")

# Call main function
if (__name__ == "__main__"):
    sys.exit(main())

NOTE regarding Microsoft Windows 10:
For colors to actually appear on Microsoft Windows 10, ANSI terminal mode has to be enabled first. Here is a function to do just that:

# Enable ANSI terminal on Microsoft Windows 10
# https://stackoverflow.com/a/36760881/1976617
# https://docs.microsoft.com/en-us/windows/console/setconsolemode
def windows_enable_ansi_terminal():
    if (sys.platform != "win32"):
        return None
    try:
        import ctypes
        kernel32 = ctypes.windll.kernel32
        result = kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)
        if (result == 0): raise Exception
        return True
    except:
        return False

How to detect if javascript files are loaded?

I don't have a reference for it handy, but script tags are processed in order, and so if you put your $(document).ready(function1) in a script tag after the script tags that define function1, etc., you should be good to go.

<script type='text/javascript' src='...'></script>
<script type='text/javascript' src='...'></script>
<script type='text/javascript'>
$(document).ready(function1);
</script>

Of course, another approach would be to ensure that you're using only one script tag, in total, by combining files as part of your build process. (Unless you're loading the other ones from a CDN somewhere.) That will also help improve the perceived speed of your page.

EDIT: Just realized that I didn't actually answer your question: I don't think there's a cross-browser event that's fired, no. There is if you work hard enough, see below. You can test for symbols and use setTimeout to reschedule:

<script type='text/javascript'>
function fireWhenReady() {
    if (typeof function1 != 'undefined') {
        function1();
    }
    else {
        setTimeout(fireWhenReady, 100);
    }
}
$(document).ready(fireWhenReady);
</script>

...but you shouldn't have to do that if you get your script tag order correct.


Update: You can get load notifications for script elements you add to the page dynamically if you like. To get broad browser support, you have to do two different things, but as a combined technique this works:

function loadScript(path, callback) {

    var done = false;
    var scr = document.createElement('script');

    scr.onload = handleLoad;
    scr.onreadystatechange = handleReadyStateChange;
    scr.onerror = handleError;
    scr.src = path;
    document.body.appendChild(scr);

    function handleLoad() {
        if (!done) {
            done = true;
            callback(path, "ok");
        }
    }

    function handleReadyStateChange() {
        var state;

        if (!done) {
            state = scr.readyState;
            if (state === "complete") {
                handleLoad();
            }
        }
    }
    function handleError() {
        if (!done) {
            done = true;
            callback(path, "error");
        }
    }
}

In my experience, error notification (onerror) is not 100% cross-browser reliable. Also note that some browsers will do both mechanisms, hence the done variable to avoid duplicate notifications.

Difference between $(this) and event.target?

Within an event handler function or object method, one way to access the properties of "the containing element" is to use the special this keyword. The this keyword represents the owner of the function or method currently being processed. So:

  • For a global function, this represents the window.

  • For an object method, this represents the object instance.

  • And in an event handler, this represents the element that received the event.

For example:

<!DOCTYPE html>
<html>
    <head>
        <script>
        function mouseDown() {
            alert(this);
        }
        </script>
    </head>
    <body>
        <p onmouseup="mouseDown();alert(this);">Hi</p>
    </body>
</html>

The content of alert windows after rendering this html respectively are:

object Window
object HTMLParagraphElement

An Event object is associated with all events. It has properties that provide information "about the event", such as the location of a mouse click in the web page.

For example:

<!DOCTYPE html>
<html>
    <head>
        <script>
        function mouseDown(event) {
            var theEvent = event ? event : window.event;
            var locString = "X = " + theEvent.screenX + " Y = " + theEvent.screenY;
            alert(event);
                    alert(locString);
        }
        </script>
    </head>
    <body>
        <p onmouseup="mouseDown(event);">Hi</p>
    </body>
</html>

The content of alert windows after rendering this html respectively are:

object MouseEvent
X = 982 Y = 329

SQL ORDER BY multiple columns

Sorting in an ORDER BY is done by the first column, and then by each additional column in the specified statement.

For instance, consider the following data:

Column1    Column2
=======    =======
1          Smith
2          Jones
1          Anderson
3          Andrews

The query

SELECT Column1, Column2 FROM thedata ORDER BY Column1, Column2

would first sort by all of the values in Column1

and then sort the columns by Column2 to produce this:

Column1    Column2
=======    =======
1          Anderson
1          Smith
2          Jones
3          Andrews

In other words, the data is first sorted in Column1 order, and then each subset (Column1 rows that have 1 as their value) are sorted in order of the second column.

The difference between the two statements you posted is that the rows in the first one would be sorted first by prod_price (price order, from lowest to highest), and then by order of name (meaning that if two items have the same price, the one with the lower alpha value for name would be listed first), while the second would sort in name order only (meaning that prices would appear in order based on the prod_name without regard for price).

problem with php mail 'From' header

headers were not working for me on my shared hosting, reason was i was using my hotmail email address in header. i created a email on my cpanel and i set that same email in the header yeah it worked like a charm!

 $header = 'From: ShopFive <[email protected]>' . "\r\n";

What's the best way to identify hidden characters in the result of a query in SQL Server (Query Analyzer)?

They way I did it was by selecting all of the data

select * from myTable and then right-clicking on the result set and chose "Save results as..." a csv file.

Opening the csv file in Notepad++ I saw the LF characters not visible in SQL Server result set.

Why is visible="false" not working for a plain html table?

The reason that visible="false" does not work is because HTML is defined as a standard by a consortium group. The standard for the Table element does not have a visibility property defined.

You can see all the valid properties for a table by going to the standards web page for tables.

That page can be a bit hard to read, so here is a link to another page that makes it easier to read.

What is the difference between method overloading and overriding?

Method overloading deals with the notion of having two or more methods in the same class with the same name but different arguments.

void foo(int a)
void foo(int a, float b)

Method overriding means having two methods with the same arguments, but different implementations. One of them would exist in the parent class, while another will be in the derived, or child class. The @Override annotation, while not required, can be helpful to enforce proper overriding of a method at compile time.

class Parent {
    void foo(double d) {
        // do something
    }
}

class Child extends Parent {

    @Override
    void foo(double d){
        // this method is overridden.  
    }
}

How to test that a registered variable is not empty?

(ansible 2.9.6 ansible-lint 4.2.0)

See ansible-lint default rules. The condition below causes E602 Don’t compare to empty string

    when: test_myscript.stderr != ""

Correct syntax and also "Ansible Galaxy Warning-Free" option is

    when: test_myscript.stderr | length > 0

Quoting from source code

"Use when: var|length > 0 rather than when: var != "" (or ' 'conversely when: var|length == 0 rather than when: var == "")"


Notes

  1. Test empty bare variable e.g.
    - debug:
        msg: "Empty string '{{ var }}' evaluates to False"
      when: not var
      vars:
        var: ''

    - debug:
        msg: "Empty list {{ var }} evaluates to False"
      when: not var
      vars:
        var: []

give

    "msg": "Empty string '' evaluates to False"
    "msg": "Empty list [] evaluates to False"
  1. But, testing non-empty bare variable string depends on CONDITIONAL_BARE_VARS. Setting ANSIBLE_CONDITIONAL_BARE_VARS=false the condition works fine but setting ANSIBLE_CONDITIONAL_BARE_VARS=true the condition will fail
    - debug:
        msg: "String '{{ var }}' evaluates to True"
      when: var
      vars:
        var: 'abc'

gives

fatal: [localhost]: FAILED! => 
  msg: |-
    The conditional check 'var' failed. The error was: error while 
    evaluating conditional (var): 'abc' is undefined

Explicit cast to Boolean prevents the error but evaluates to False i.e. will be always skipped (unless var='True'). When the filter bool is used the options ANSIBLE_CONDITIONAL_BARE_VARS=true and ANSIBLE_CONDITIONAL_BARE_VARS=false have no effect

    - debug:
        msg: "String '{{ var }}' evaluates to True"
      when: var|bool
      vars:
        var: 'abc'

gives

skipping: [localhost]
  1. Quoting from Porting guide 2.8 Bare variables in conditionals
  - include_tasks: teardown.yml
    when: teardown

  - include_tasks: provision.yml
    when: not teardown

" based on a variable you define as a string (with quotation marks around it):"

  • In Ansible 2.7 and earlier, the two conditions above evaluated as True and False respectively if teardown: 'true'

  • In Ansible 2.7 and earlier, both conditions evaluated as False if teardown: 'false'

  • In Ansible 2.8 and later, you have the option of disabling conditional bare variables, so when: teardown always evaluates as True and when: not teardown always evaluates as False when teardown is a non-empty string (including 'true' or 'false')

  1. Quoting from CONDITIONAL_BARE_VARS

"Expect that this setting eventually will be deprecated after 2.12"

How to set width and height dynamically using jQuery

Try this:

<div id="mainTable" style="width:100px; height:200px;"></div> 

$(document).ready(function() {
  $("#mainTable").width(100).height(200);
}) ;

What is the best way to ensure only one instance of a Bash script is running?

first test example

[[ $(lsof -t $0| wc -l) > 1 ]] && echo "At least one of $0 is running"

second test example

currsh=$0
currpid=$$
runpid=$(lsof -t $currsh| paste -s -d " ")
if [[ $runpid == $currpid ]]
then
  sleep 11111111111111111
else
  echo -e "\nPID($runpid)($currpid) ::: At least one of \"$currsh\" is running !!!\n"
  false
  exit 1
fi

explanation

"lsof -t" to list all pids of current running scripts named "$0".

Command "lsof" will do two advantages.

  1. Ignore pids which is editing by editor such as vim, because vim edit its mapping file such as ".file.swp".
  2. Ignore pids forked by current running shell scripts, which most "grep" derivative command can't achieve it. Use "pstree -pH pidnum" command to see details about current process forking status.

How to align a <div> to the middle (horizontally/width) of the page

If you have some regular content, and not only one line of text, the only possible reason I know is to calculate margin.

Here is an example:

HTML

<div id="supercontainer">
  <div id="middlecontainer">
    <div class="common" id="first">first</div>
    <div id="container">
      <div class="common" id="second">second</div>
      <div class="common" id="third">third</div>
    </div>
  </div>
</div>

CSS

body {
  margin: 0;
  padding: 0;
}

.common {
  border: 1px solid black;
}

#supercontainer {
  width: 1200px;
  background: aqua;
  float: left;
}

#middlecontainer {
  float: left;
  width: 104px;
  margin: 0 549px;
}

#container {
  float: left;
}

#first {
  background: red;
  height: 102px;
  width: 50px;
  float: left;
}

#second {
  background: green;
  height: 50px;
  width: 50px;
}

#third {
  background: yellow;
  height: 50px;
  width: 50px;
}

So, #supercontainer is your "whole page" and its width is 1200px.

#middlecontainer is div with content of your site; it's width 102px. In case the width of content is known, you need to divide the page's size to 2, and subtract half of content's width from the result: 1200 / 2 - (102 / 2) = 549;

Yes, I'm also seeing that this is der grosse fail of CSS.

Which is fastest? SELECT SQL_CALC_FOUND_ROWS FROM `table`, or SELECT COUNT(*)

It depends. See the MySQL Performance Blog post on this subject: To SQL_CALC_FOUND_ROWS or not to SQL_CALC_FOUND_ROWS?

Just a quick summary: Peter says that it depends on your indexes and other factors. Many of the comments to the post seem to say that SQL_CALC_FOUND_ROWS is almost always slower - sometimes up to 10x slower - than running two queries.

scp with port number specified

I'm using different ports then standard and copy files between files like this:

scp -P 1234 user@[ip address or host name]:/var/www/mywebsite/dumps/* /var/www/myNewPathOnCurrentLocalMachine

This is only for occasional use, if it repeats itself based on a schedule you should use rsync and cron job to do it.

How do the likely/unlikely macros in the Linux kernel work and what is their benefit?

In many linux release, you can find complier.h in /usr/linux/ , you can include it for use simply. And another opinion, unlikely() is more useful rather than likely(), because

if ( likely( ... ) ) {
     doSomething();
}

it can be optimized as well in many compiler.

And by the way, if you want to observe the detail behavior of the code, you can do simply as follow:

gcc -c test.c objdump -d test.o > obj.s

Then, open obj.s, you can find the answer.

How to install package from github repo in Yarn

For GitHub (or similar) private repository:

yarn add 'ssh://[email protected]:myproject.git#<branch,tag,commit>'
npm install 'ssh://[email protected]:myproject.git#<branch,tag,commit>'

Spring Security redirect to previous page after successful login

You can use a Custom SuccessHandler extending SimpleUrlAuthenticationSuccessHandler for redirecting users to different URLs when login according to their assigned roles.

CustomSuccessHandler class provides custom redirect functionality:

package com.mycompany.uomrmsweb.configuration;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

@Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler{

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        String targetUrl = determineTargetUrl(authentication);

        if (response.isCommitted()) {
            System.out.println("Can't redirect");
            return;
        }

        redirectStrategy.sendRedirect(request, response, targetUrl);
    }

    protected String determineTargetUrl(Authentication authentication) {
        String url="";

        Collection<? extends GrantedAuthority> authorities =  authentication.getAuthorities();

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

        for (GrantedAuthority a : authorities) {
            roles.add(a.getAuthority());
        }

        if (isStaff(roles)) {
            url = "/staff";
        } else if (isAdmin(roles)) {
            url = "/admin";
        } else if (isStudent(roles)) {
            url = "/student";
        }else if (isUser(roles)) {
            url = "/home";
        } else {
            url="/Access_Denied";
        }

        return url;
    }

    public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
        this.redirectStrategy = redirectStrategy;
    }
    protected RedirectStrategy getRedirectStrategy() {
        return redirectStrategy;
    }

    private boolean isUser(List<String> roles) {
        if (roles.contains("ROLE_USER")) {
            return true;
        }
        return false;
    }

    private boolean isStudent(List<String> roles) {
        if (roles.contains("ROLE_Student")) {
            return true;
        }
        return false;
    }

    private boolean isAdmin(List<String> roles) {
        if (roles.contains("ROLE_SystemAdmin") || roles.contains("ROLE_ExaminationsStaff")) {
            return true;
        }
        return false;
    }

    private boolean isStaff(List<String> roles) {
        if (roles.contains("ROLE_AcademicStaff") || roles.contains("ROLE_UniversityAdmin")) {
            return true;
        }
        return false;
    }
}

Extending Spring SimpleUrlAuthenticationSuccessHandler class and overriding handle() method which simply invokes a redirect using configured RedirectStrategy [default in this case] with the URL returned by the user defined determineTargetUrl() method. This method extracts the Roles of currently logged in user from Authentication object and then construct appropriate URL based on there roles. Finally RedirectStrategy , which is responsible for all redirections within Spring Security framework , redirects the request to specified URL.

Registering CustomSuccessHandler using SecurityConfiguration class:

package com.mycompany.uomrmsweb.configuration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("customUserDetailsService")
    UserDetailsService userDetailsService;

    @Autowired
    CustomSuccessHandler customSuccessHandler;

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        .antMatchers("/", "/home").access("hasRole('USER')")
        .antMatchers("/admin/**").access("hasRole('SystemAdmin') or hasRole('ExaminationsStaff')")
        .antMatchers("/staff/**").access("hasRole('AcademicStaff') or hasRole('UniversityAdmin')")
        .antMatchers("/student/**").access("hasRole('Student')")  
                    .and().formLogin().loginPage("/login").successHandler(customSuccessHandler)
        .usernameParameter("username").passwordParameter("password")
        .and().csrf()
        .and().exceptionHandling().accessDeniedPage("/Access_Denied");
    }
}

successHandler is the class responsible for eventual redirection based on any custom logic, which in this case will be to redirect the user [to student/admin/staff ] based on his role [USER/Student/SystemAdmin/UniversityAdmin/ExaminationsStaff/AcademicStaff].

how to do file upload using jquery serialization

A file cannot be uploaded using AJAX because you cannot access the contents of a file stored on the client computer and send it in the request using javascript. One of the techniques to achieve this is to use hidden iframes. There's a nice jquery form plugin which allows you to AJAXify your forms and it supports file uploads as well. So using this plugin your code will simply look like this:

$(function() {
    $('#ifoftheform').ajaxForm(function(result) {
        alert('the form was successfully processed');
    });
});

The plugin automatically takes care of subscribing to the submit event of the form, canceling the default submission, serializing the values, using the proper method and handle file upload fields, ...

What is a singleton in C#?

A Singleton (and this isn't tied to C#, it's an OO design pattern) is when you want to allow only ONE instance of a class to be created throughout your application. Useages would typically include global resources, although I will say from personal experience, they're very often the source of great pain.

The simplest way to resize an UIImage?

A more compact version for Swift 4 and iOS 10+:

extension UIImage {
    func resized(to size: CGSize) -> UIImage {
        return UIGraphicsImageRenderer(size: size).image { _ in
            draw(in: CGRect(origin: .zero, size: size))
        }
    }
}

Usage:

let resizedImage = image.resized(to: CGSize(width: 50, height: 50))

rename the columns name after cbind the data

You can also name columns directly in the cbind call, e.g.

cbind(date=c(0,1), high=c(2,3))

Output:

     date high
[1,]    0    2
[2,]    1    3

What is Robocopy's "restartable" option?

Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.

That option could be useful when copying very large files over a potentially unstable connection.

Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.

How to update fields in a model without creating a new record in django?

Django has some documentation about that on their website, see: Saving changes to objects. To summarize:

.. to save changes to an object that's already in the database, use save().

best way to get the key of a key/value javascript object

// iterate through key-value gracefully
const obj = { a: 5, b: 7, c: 9 };
for (const [key, value] of Object.entries(obj)) {
  console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
}

Refer MDN

Regex to match a 2-digit number (to validate Credit/Debit Card Issue number)

You need to use anchors to match the beginning of the string ^ and the end of the string $

^[0-9]{2}$

How to convert HTML file to word?

Other Alternatives from just renaming the file to .doc.....

http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word(office.11).aspx

Here is a good place to start. You can also try using this Office Open XML.

http://www.ecma-international.org/publications/standards/Ecma-376.htm

Pass form data to another page with php

The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

index.php

<html>
<body>

<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>

</body>
</html> 

site2.php

 <html>
 <body>

 Hello <?php echo $_POST["name"]; ?>!<br>
 Your mail is <?php echo $_POST["mail"]; ?>.

 </body>
 </html> 

output

Hello "name" !

Your email is "[email protected]" .

How to use WPF Background Worker

using System;  
using System.ComponentModel;   
using System.Threading;    
namespace BackGroundWorkerExample  
{   
    class Program  
    {  
        private static BackgroundWorker backgroundWorker;  

        static void Main(string[] args)  
        {  
            backgroundWorker = new BackgroundWorker  
            {  
                WorkerReportsProgress = true,  
                WorkerSupportsCancellation = true  
            };  

            backgroundWorker.DoWork += backgroundWorker_DoWork;  
            //For the display of operation progress to UI.    
            backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;  
            //After the completation of operation.    
            backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;  
            backgroundWorker.RunWorkerAsync("Press Enter in the next 5 seconds to Cancel operation:");  

            Console.ReadLine();  

            if (backgroundWorker.IsBusy)  
            { 
                backgroundWorker.CancelAsync();  
                Console.ReadLine();  
            }  
        }  

        static void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)  
        {  
            for (int i = 0; i < 200; i++)  
            {  
                if (backgroundWorker.CancellationPending)  
                {  
                    e.Cancel = true;  
                    return;  
                }  

                backgroundWorker.ReportProgress(i);  
                Thread.Sleep(1000);  
                e.Result = 1000;  
            }  
        }  

        static void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)  
        {  
            Console.WriteLine("Completed" + e.ProgressPercentage + "%");  
        }  

        static void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)  
        {  

            if (e.Cancelled)  
            {  
                Console.WriteLine("Operation Cancelled");  
            }  
            else if (e.Error != null)  
            {  
                Console.WriteLine("Error in Process :" + e.Error);  
            }  
            else  
            {  
                Console.WriteLine("Operation Completed :" + e.Result);  
            }  
        }  
    }  
} 

Also, referr the below link you will understand the concepts of Background:

http://www.c-sharpcorner.com/UploadFile/1c8574/threads-in-wpf/

How can I extract a number from a string in JavaScript?

You should try the following:

var txt = "#div-name-1234-characteristic:561613213213";
var numb = txt.match(/\d/g);
numb = numb.join("");
alert (numb);?

result

1234561613213213

How can I delete all cookies with JavaScript?

There is no 100% solution to delete browser cookies.

The problem is that cookies are uniquely identified by not just by their key "name" but also their "domain" and "path".

Without knowing the "domain" and "path" of a cookie, you cannot reliably delete it. This information is not available through JavaScript's document.cookie. It's not available through the HTTP Cookie header either!

However, if you know the name, path and domain of a cookie, then you can clear it by setting an empty cookie with an expiry date in the past, for example:

function clearCookie(name, domain, path){
    var domain = domain || document.domain;
    var path = path || "/";
    document.cookie = name + "=; expires=" + +new Date + "; domain=" + domain + "; path=" + path;
};

error LNK2005, already defined?

Why this error?

You broke the one definition rule and hence the linking error.

Suggested Solutions:


If you need the same named variable in the two cpp files then You need to use Nameless namespace(Anonymous Namespace) to avoid the error.

namespace 
{
    int k;
}

If you need to share the same variable across multiple files then you need to use extern.

A.h

extern int k;

A.cpp

#include "A.h"
int k = 0;

B.cpp

#include "A.h"

//Use `k` anywhere in the file 

Reset textbox value in javascript

In Javascript :

document.getElementById('searchField').value = '';

In jQuery :

$('#searchField').val('');

That should do it

How to align linearlayout to vertical center?

Use layout_gravity instead of gravity. layout_gravity tells the parent where it should be positioned, and gravity tells its child where they should be positioned.

<LinearLayout
    android:id="@+id/groupNumbers"
    android:orientation="horizontal"
    android:layout_gravity="center_vertical"
    android:layout_weight="0.7"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

How to give a user only select permission on a database

create LOGIN guest WITH PASSWORD='guest@123', CHECK_POLICY = OFF;

Be sure when you want to exceute the following

DENY VIEW ANY DATABASE TO guest;

ALTER AUTHORIZATION ON DATABASE::BiddingSystemDB TO guest

Selected Database should be Master

How to change the window title of a MATLAB plotting figure?

You need to set figure properties.

At the very beginning of the script, call

figure('name','something else')

Calling figure is a good thing, anyway, because without it, you always plot into the same window, and sometimes you may want to compare two windows side-by-side.

Alternatively, you can store the figure's handle by calling

figH = figure;

so that you can later change the figure properties to your liking (the 'numberTitle' property setting eliminates the "figure X" text)

set(figH,'Name','something else','NumberTitle','off')

Have a look at the figure properties in the MATLAB documentation to see what else you can change if you want.

position fixed is not working

We'll never convince people to leave IE6 if we keep striving to deliver quality websites to those users.

Only IE7+ understood "position: fixed".

https://developer.mozilla.org/en-US/docs/Web/CSS/position

So you're out of luck for IE6. To get the footer semi-sticky try this:

.main {
  min-height: 100%;
  margin-bottom: -60px;
}
.footer {
  height: 60px;
}

You could also use an iFrame maybe.

This will keep the footer from 'lifting off' from the bottom of the page. If you have more than one page of content then it will push down out of site.

On a philosophical note, I'd rather point IE6 users to http://browsehappy.com/ and spend the time I save hacking for IE6 on something else.

creating json object with variables

Try this to see how you can create a object from strings.

var firstName = "xx";
var lastName  = "xy";
var phone     = "xz";
var adress    = "x1";
var obj = {"firstName":firstName, "lastName":lastName, "phone":phone, "address":adress};
console.log(obj);

How to do a Jquery Callback after form submit?

I could not get the number one upvoted solution to work reliably, but have found this works. Not sure if it's required or not, but I do not have an action or method attribute on the tag, which ensures the POST is handled by the $.ajax function and gives you the callback option.

<form id="form">
...
<button type="submit"></button>
</form>

<script>
$(document).ready(function() {
  $("#form_selector").submit(function() {

    $.ajax({
     type: "POST",
      url: "form_handler.php",
      data: $(this).serialize(),
      success: function() {
        // callback code here
       }
    })

  })
})
</script>

Standardize data columns in R

'Caret' package provides methods for preprocessing data (e.g. centering and scaling). You could also use the following code:

library(caret)
# Assuming goal class is column 10
preObj <- preProcess(data[, -10], method=c("center", "scale"))
newData <- predict(preObj, data[, -10])

More details: http://www.inside-r.org/node/86978

LaTeX: Prevent line break in a span of text

Also, if you have two subsequent words in regular text and you want to avoid a line break between them, you can use the ~ character.

For example:

As we can see in Fig.~\ref{BlaBla}, there is nothing interesting to see. A~better place..

This can ensure that you don't have a line starting with a figure number (without the Fig. part) or with an uppercase A.

How to display scroll bar onto a html table

I resolved this problem by separating my content into two tables.

One table is the header row.

The seconds is also <table> tag, but wrapped by <div> with static height and overflow scroll.

Keep-alive header clarification

Where is this info kept ("this connection is between computer A and server F")?

A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.

HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.

This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.

When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection

No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.

which is only for my session ?

Does it mean that no one else can use that connection

That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.

If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?

Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:

  • Lower CPU and memory usage (because fewer connections are open simultaneously).
  • Enables HTTP pipelining of requests and responses.
  • Reduced network congestion (fewer TCP connections).
  • Reduced latency in subsequent requests (no handshaking).

if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)

An typical keep-alive response looks like this:

Keep-Alive: timeout=15, max=100

See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):

  • A host sets the value of the timeout parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.

  • The max parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.

However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.

Why write <script type="text/javascript"> when the mime type is set by the server?

Boris Zbarsky (Mozilla), who probably knows more about the innards of Gecko than anyone else, provided at http://lists.w3.org/Archives/Public/public-html/2009Apr/0195.html the pseudocode repeated below to describe what Gecko based browsers do:

if (@type not set or empty) {
   if (@language not set or empty) {
     // Treat as default script language; what this is depends on the
     // content-script-type HTTP header or equivalent META tag
   } else {
     if (@language is one of "javascript", "livescript", "mocha",
                             "javascript1.0", "javascript1.1",
                             "javascript1.2", "javascript1.3",
                             "javascript1.4", "javascript1.5",
                             "javascript1.6", "javascript1.7",
                             "javascript1.8") {
       // Treat as javascript
     } else {
       // Treat as unknown script language; do not execute
     }
   }
} else {
   if (@type is one of "text/javascript", "text/ecmascript",
                       "application/javascript",
                       "application/ecmascript",
                       "application/x-javascript") {
     // Treat as javascript
   } else {
     // Treat as specified (e.g. if pyxpcom is installed and
     // python script is allowed in this context and the type
     // is one that the python runtime claims to handle, use that).
     // If we don't have a runtime for this type, do not execute.
   }
}

Excel CSV - Number cell format

The Text Import Wizard method does NOT work when the CSV file being imported has line breaks within a cell. This method handles this scenario(at least with tab delimited data):

  1. Create new Excel file
  2. Ctrl+A to select all cells
  3. In Number Format combobox, select Text
  4. Open tab delimited file in text editor
  5. Select all, copy and paste into Excel

Install specific branch from github using Npm

Another approach would be to add the following line to package.json dependencies:

"package-name": "user/repo#branch"

For example:

"dependencies": {
    ... other dependencies ...

    "react-native": "facebook/react-native#master"
}

And then do npm install or yarn install

Unable to install pyodbc on Linux

Adding one more answer on this question. For Linux Debian Stretch release you would need to install the following dependencies:

apt-get update
apt-get install g++
apt-get install unixodbc-dev
pip install pyodbc

How do I create a round cornered UILabel on the iPhone?

For devices with iOS 7.1 or later, you need to add:

yourUILabel.layer.masksToBounds = YES;
yourUILabel.layer.cornerRadius = 8.0;

How to get progress from XMLHttpRequest

The only way to do that with pure javascript is to implement some kind of polling mechanism. You will need to send ajax requests at fixed intervals (each 5 seconds for example) to get the number of bytes received by the server.

A more efficient way would be to use flash. The flex component FileReference dispatchs periodically a 'progress' event holding the number of bytes already uploaded. If you need to stick with javascript, bridges are available between actionscript and javascript. The good news is that this work has been already done for you :)

swfupload

This library allows to register a javascript handler on the flash progress event.

This solution has the hudge advantage of not requiring aditionnal resources on the server side.

How to get a list of user accounts using the command line in MySQL?

The mysql.db table is possibly more important in determining user rights. I think an entry in it is created if you mention a table in the GRANT command. In my case the mysql.users table showed no permissions for a user when it obviously was able to connect and select, etc.

mysql> select * from mysql.db;
mysql> select * from db;
+---------------+-----------------+--------+-------------+-------------+-------------+--------
| Host          | Db              | User   | Select_priv | Insert_priv | Update_priv | Del...

Check play state of AVPlayer

For Swift:

AVPlayer:

let player = AVPlayer(URL: NSURL(string: "http://www.sample.com/movie.mov"))
if (player.rate != 0 && player.error == nil) {
   println("playing")
}

Update:
player.rate > 0 condition changed to player.rate != 0 because if video is playing in reverse it can be negative thanks to Julian for pointing out.
Note: This might look same as above(Maz's) answer but in Swift '!player.error' was giving me a compiler error so you have to check for error using 'player.error == nil' in Swift.(because error property is not of 'Bool' type)

AVAudioPlayer:

if let theAudioPlayer =  appDelegate.audioPlayer {
   if (theAudioPlayer.playing) {
       // playing
   }
}

AVQueuePlayer:

if let theAudioQueuePlayer =  appDelegate.audioPlayerQueue {
   if (theAudioQueuePlayer.rate != 0 && theAudioQueuePlayer.error == nil) {
       // playing
   }
}

Print current call stack from a method in Python code

for those who need to print the call stack while using pdb, just do

(Pdb) where

Detect if the app was launched/opened from a push notification

Xcode 10 Swift 4.2

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {

    let state : UIApplicationState = application.applicationState
    if (state == .Inactive || state == .Background) {
        // coming from background
    } else {
        // App is running in foreground
    }
}

how can select from drop down menu and call javascript function

<select name="aa" onchange="report(this.value)"> 
  <option value="">Please select</option>
  <option value="daily">daily</option>
  <option value="monthly">monthly</option>
</select>

using

function report(period) {
  if (period=="") return; // please select - possibly you want something else here

  const report = "script/"+((period == "daily")?"d":"m")+"_report.php";
  loadXMLDoc(report,'responseTag');
  document.getElementById('responseTag').style.visibility='visible';
  document.getElementById('list_report').style.visibility='hidden';
  document.getElementById('formTag').style.visibility='hidden'; 
} 

Unobtrusive version:

<select id="aa" name="aa"> 
  <option value="">Please select</option>
  <option value="daily">daily</option>
  <option value="monthly">monthly</option>
</select>

using

window.addEventListener("load",function() {
  document.getElementById("aa").addEventListener("change",function() {
    const period = this.value;
    if (period=="") return; // please select - possibly you want something else here

    const report = "script/"+((period == "daily")?"d":"m")+"_report.php";
    loadXMLDoc(report,'responseTag');
    document.getElementById('responseTag').style.visibility='visible';
    document.getElementById('list_report').style.visibility='hidden';
    document.getElementById('formTag').style.visibility='hidden'; 
  }); 
});

jQuery version - same select with ID

$(function() {
  $("#aa").on("change",function() {
    const period = this.value;
    if (period=="") return; // please select - possibly you want something else here

    var report = "script/"+((period == "daily")?"d":"m")+"_report.php";
    loadXMLDoc(report,'responseTag');
    $('#responseTag').show();
    $('#list_report').hide();
    $('#formTag').hide(); 
  }); 
});

Only allow specific characters in textbox

For your validation event IMO the easiest method would be to use a character array to validate textbox characters against. True - iterating and validating isn't particularly efficient, but it is straightforward.

Alternately, use a regular expression of your whitelist characters against the input string. Your events are availalbe at MSDN here: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.lostfocus.aspx

How to suppress scientific notation when printing float values?

Using the newer version ''.format (also remember to specify how many digit after the . you wish to display, this depends on how small is the floating number). See this example:

>>> a = -7.1855143557448603e-17
>>> '{:f}'.format(a)
'-0.000000'

as shown above, default is 6 digits! This is not helpful for our case example, so instead we could use something like this:

>>> '{:.20f}'.format(a)
'-0.00000000000000007186'

Update

Starting in Python 3.6, this can be simplified with the new formatted string literal, as follows:

>>> f'{a:.20f}'
'-0.00000000000000007186'

What is the use of rt.jar file in java?

Your question is already answered here :

Basically, rt.jar contains all of the compiled class files for the base Java Runtime ("rt") Environment. Normally, javac should know the path to this file

Also, a good link on what happens if we try to include our class file in rt.jar.

Reverse ip, find domain names on ip address

This worked for me to get domain in intranet

https://gist.github.com/jrothmanshore/2656003

It's a powershell script. Run it in PowerShell

.\ip_lookup.ps1 <ip>

Can't import database through phpmyadmin file size too large

  1. Set the below values in php.ini file (C:\xampp\php\)

    • max_execution_time = 0
    • max_input_time=259200
    • memory_limit = 1000M
    • upload_max_filesize = 750M
    • post_max_size = 750M
  2. Open config.default file(C:\xampp\phpMyAdmin\libraries\config.default) and set the value as below:

    • $cfg['ExecTimeLimit'] = 0;
  3. Then open the config.inc file(C:\xampp\phpMyAdmin\config.inc). and paste below line:

    • $cfg['UploadDir'] = 'upload';
  4. Go to phpMyAdmin(C:\xampp\phpMyAdmin) folder and create folder called upload and paste your database to newly created upload folder (don't need to zip)

  5. Lastly, go to phpMyAdmin and upload your db (Please select your database in drop-down)

upload image

  1. That's all baby ! :)

*It takes lot of time.In my db(266mb) takes 50min to upload. So be patient ! *

Table Naming Dilemma: Singular vs. Plural Names

Others have given pretty good answers as far as "standards" go, but I just wanted to add this... Is it possible that "User" (or "Users") is not actually a full description of the data held in the table? Not that you should get too crazy with table names and specificity, but perhaps something like "Widget_Users" (where "Widget" is the name of your application or website) would be more appropriate.

What is the difference between C# and .NET?

C# is a programming language, .NET is a blanket term that tends to cover both the .NET Framework (an application framework library) and the Common Language Runtime which is the runtime in which .NET assemblies are run.

Microsoft's implementation of C# is heavily integrated with the .NET Framework so it is understandable that the two concepts would be confused. However it is important to understand that they are two very different things.

Here is a class written in C#:

class Example { }

Here is a class written in C# that explicitly uses a .NET framework assembly, type, and method:

class Example
{
    static void Main()
    {
        // Here we call into the .NET framework to 
        // write to the output console
        System.Console.Write("hello, world");
    }
}

As I mentioned before, it is very difficult to use Microsoft's implementation of C# without using the .NET framework as well. My first Example implementation above even uses the .NET framework (implicitly, yes, but it does use it nonetheless) because Example inherits from System.Object.

Also, the reason I use the phrase Microsoft's implementation of C# is because there are other implementations of C# available.

How do I export (and then import) a Subversion repository?

You can also use svnsync. This only requires read-only access on the source repository

more at svnbook

Android camera android.hardware.Camera deprecated

Now we have to use android.hardware.camera2 as android.hardware.Camera is deprecated which will only work on API >23 FlashLight

   public class MainActivity extends AppCompatActivity {

     Button button;

     Boolean light=true;

     CameraDevice cameraDevice;

     private CameraManager cameraManager;

     private CameraCharacteristics cameraCharacteristics;

     String cameraId;

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button=(Button)findViewById(R.id.button);
        cameraManager = (CameraManager) 
        getSystemService(Context.CAMERA_SERVICE);
        try {
          cameraId = cameraManager.getCameraIdList()[0];
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(light){
                    try {

                        cameraManager.setTorchMode(cameraId,true);
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }

                    light=false;}
                    else {

                    try {

                      cameraManager.setTorchMode(cameraId,false);
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }


                    light=true;
                    }


            }
        });
    }
}

Datatable date sorting dd/mm/yyyy issue

If you don't want to use momentum.js or any other date formating, you can prepend a date format in milliseconds in the date value so that the sort will read according to it's millisecond. And hide the milliseconds date format.

Sample code:

var date = new Date();
var millisecond = Date.parse(date);

HTML

<td>'<span style="display: none;">' + millisecond + "</span>" + date + </td>

That's it.

Generating an MD5 checksum of a file

I'm clearly not adding anything fundamentally new, but added this answer before I was up to commenting status, plus the code regions make things more clear -- anyway, specifically to answer @Nemo's question from Omnifarious's answer:

I happened to be thinking about checksums a bit (came here looking for suggestions on block sizes, specifically), and have found that this method may be faster than you'd expect. Taking the fastest (but pretty typical) timeit.timeit or /usr/bin/time result from each of several methods of checksumming a file of approx. 11MB:

$ ./sum_methods.py
crc32_mmap(filename) 0.0241742134094
crc32_read(filename) 0.0219960212708
subprocess.check_output(['cksum', filename]) 0.0553209781647
md5sum_mmap(filename) 0.0286180973053
md5sum_read(filename) 0.0311000347137
subprocess.check_output(['md5sum', filename]) 0.0332629680634
$ time md5sum /tmp/test.data.300k
d3fe3d5d4c2460b5daacc30c6efbc77f  /tmp/test.data.300k

real    0m0.043s
user    0m0.032s
sys     0m0.010s
$ stat -c '%s' /tmp/test.data.300k
11890400

So, looks like both Python and /usr/bin/md5sum take about 30ms for an 11MB file. The relevant md5sum function (md5sum_read in the above listing) is pretty similar to Omnifarious's:

import hashlib
def md5sum(filename, blocksize=65536):
    hash = hashlib.md5()
    with open(filename, "rb") as f:
        for block in iter(lambda: f.read(blocksize), b""):
            hash.update(block)
    return hash.hexdigest()

Granted, these are from single runs (the mmap ones are always a smidge faster when at least a few dozen runs are made), and mine's usually got an extra f.read(blocksize) after the buffer is exhausted, but it's reasonably repeatable and shows that md5sum on the command line is not necessarily faster than a Python implementation...

EDIT: Sorry for the long delay, haven't looked at this in some time, but to answer @EdRandall's question, I'll write down an Adler32 implementation. However, I haven't run the benchmarks for it. It's basically the same as the CRC32 would have been: instead of the init, update, and digest calls, everything is a zlib.adler32() call:

import zlib
def adler32sum(filename, blocksize=65536):
    checksum = zlib.adler32("")
    with open(filename, "rb") as f:
        for block in iter(lambda: f.read(blocksize), b""):
            checksum = zlib.adler32(block, checksum)
    return checksum & 0xffffffff

Note that this must start off with the empty string, as Adler sums do indeed differ when starting from zero versus their sum for "", which is 1 -- CRC can start with 0 instead. The AND-ing is needed to make it a 32-bit unsigned integer, which ensures it returns the same value across Python versions.

Why an interface can not implement another interface?

Interface is the class that contains an abstract method that cannot create any object.Since Interface cannot create the object and its not a pure class, Its no worth implementing it.

Static methods in Python?

You don't really need to use the @staticmethod decorator. Just declaring a method (that doesn't expect the self parameter) and call it from the class. The decorator is only there in case you want to be able to call it from an instance as well (which was not what you wanted to do)

Mostly, you just use functions though...

Is there a method to generate a UUID with go language

This library is our standard for uuid generation and parsing:

https://github.com/pborman/uuid

Accessing the last entry in a Map

To answer your question in one sentence:

Per default, Maps don't have a last entry, it's not part of their contract.


And a side note: it's good practice to code against interfaces, not the implementation classes (see Effective Java by Joshua Bloch, Chapter 8, Item 52: Refer to objects by their interfaces).

So your declaration should read:

Map<String,Integer> map = new HashMap<String,Integer>();

(All maps share a common contract, so the client need not know what kind of map it is, unless he specifies a sub interface with an extended contract).


Possible Solutions

Sorted Maps:

There is a sub interface SortedMap that extends the map interface with order-based lookup methods and it has a sub interface NavigableMap that extends it even further. The standard implementation of this interface, TreeMap, allows you to sort entries either by natural ordering (if they implement the Comparable interface) or by a supplied Comparator.

You can access the last entry through the lastEntry method:

NavigableMap<String,Integer> map = new TreeMap<String, Integer>();
// add some entries
Entry<String, Integer> lastEntry = map.lastEntry();

Linked maps:

There is also the special case of LinkedHashMap, a HashMap implementation that stores the order in which keys are inserted. There is however no interface to back up this functionality, nor is there a direct way to access the last key. You can only do it through tricks such as using a List in between:

Map<String,String> map = new LinkedHashMap<String, Integer>();
// add some entries
List<Entry<String,Integer>> entryList =
    new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
Entry<String, Integer> lastEntry =
    entryList.get(entryList.size()-1);

Proper Solution:

Since you don't control the insertion order, you should go with the NavigableMap interface, i.e. you would write a comparator that positions the Not-Specified entry last.

Here is an example:

final NavigableMap<String,Integer> map = 
        new TreeMap<String, Integer>(new Comparator<String>() {
    public int compare(final String o1, final String o2) {
        int result;
        if("Not-Specified".equals(o1)) {
            result=1;
        } else if("Not-Specified".equals(o2)) {
            result=-1;
        } else {
            result =o1.compareTo(o2);
        }
        return result;
    }

});
map.put("test", Integer.valueOf(2));
map.put("Not-Specified", Integer.valueOf(1));
map.put("testtest", Integer.valueOf(3));
final Entry<String, Integer> lastEntry = map.lastEntry();
System.out.println("Last key: "+lastEntry.getKey()
         + ", last value: "+lastEntry.getValue());

Output:

Last key: Not-Specified, last value: 1

Solution using HashMap:

If you must rely on HashMaps, there is still a solution, using a) a modified version of the above comparator, b) a List initialized with the Map's entrySet and c) the Collections.sort() helper method:

    final Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("test", Integer.valueOf(2));
    map.put("Not-Specified", Integer.valueOf(1));
    map.put("testtest", Integer.valueOf(3));

    final List<Entry<String, Integer>> entries =
        new ArrayList<Entry<String, Integer>>(map.entrySet());
    Collections.sort(entries, new Comparator<Entry<String, Integer>>(){

        public int compareKeys(final String o1, final String o2){
            int result;
            if("Not-Specified".equals(o1)){
                result = 1;
            } else if("Not-Specified".equals(o2)){
                result = -1;
            } else{
                result = o1.compareTo(o2);
            }
            return result;
        }

        @Override
        public int compare(final Entry<String, Integer> o1,
            final Entry<String, Integer> o2){
            return this.compareKeys(o1.getKey(), o2.getKey());
        }

    });

    final Entry<String, Integer> lastEntry =
        entries.get(entries.size() - 1);
    System.out.println("Last key: " + lastEntry.getKey() + ", last value: "
        + lastEntry.getValue());

}

Output:

Last key: Not-Specified, last value: 1

Changing CSS style from ASP.NET code

C#, because I don't want to typo the VB syntax.

Markup:

<div runat="server" id="divControl">...</div>

Class of the Page:

protected System.Web.UI.HtmlControls.HtmlGenericControl divControl;

OnLoad/Other function:

divControl.Style.Add("height", number / anotherNumer);

Regular expression for a string that does not start with a sequence

You could use a negative look-ahead assertion:

^(?!tbd_).+

Or a negative look-behind assertion:

(^.{1,3}$|^.{4}(?<!tbd_).*)

Or just plain old character sets and alternations:

^([^t]|t($|[^b]|b($|[^d]|d($|[^_])))).*

Letsencrypt add domain to existing certificate

You need to specify all of the names, including those already registered.

I used the following command originally to register some certificates:

/opt/certbot/certbot-auto certonly --webroot --agree-tos -w /srv/www/letsencrypt/ \
--email [email protected] \
--expand -d example.com,www.example.com

... and just now I successfully used the following command to expand my registration to include a new subdomain as a SAN:

/opt/certbot/certbot-auto certonly --webroot --agree-tos -w /srv/www/letsencrypt/ \
--expand -d example.com,www.example.com,click.example.com

From the documentation:

--expand "If an existing cert covers some subset of the requested names, always expand and replace it with the additional names."

Don't forget to restart the server to load the new certificates if you are running nginx.

Javascript Equivalent to C# LINQ Select

Take a peek at underscore.js which provides many linq like functions. In the example you give you would use the map function.

Centering floating divs within another div

First, remove the float attribute on the inner divs. Then, put text-align: center on the main outer div. And for the inner divs, use display: inline-block. Might also be wise to give them explicit widths too.


<div style="margin: auto 1.5em; display: inline-block;">
  <img title="Nadia Bjorlin" alt="Nadia Bjorlin" src="headshot.nadia.png"/>
  <br/>
  Nadia Bjorlin
</div>

JavaScript moving element in the DOM

.before and .after

Use modern vanilla JS! Way better/cleaner than previously. No need to reference a parent.

const div1 = document.getElementById("div1");
const div2 = document.getElementById("div2");
const div3 = document.getElementById("div3");

div2.after(div1);
div2.before(div3);

Browser Support - 95% Global as of Oct '20

How to convert a char array back to a string?

Try this

Arrays.toString(array)

How do I use setsockopt(SO_REUSEADDR)?

Depending on the libc release it could be needed to set both SO_REUSEADDR and SO_REUSEPORT socket options as explained in socket(7) documentation :

   SO_REUSEPORT (since Linux 3.9)
          Permits multiple AF_INET or AF_INET6 sockets to be bound to an
          identical socket address.  This option must be set on each
          socket (including the first socket) prior to calling bind(2)
          on the socket.  To prevent port hijacking, all of the
          processes binding to the same address must have the same
          effective UID.  This option can be employed with both TCP and
          UDP sockets.

As this socket option appears with kernel 3.9 and raspberry use 3.12.x, it will be needed to set SO_REUSEPORT.

You can set theses two options before calling bind like this :

    int reuse = 1;
    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)) < 0)
        perror("setsockopt(SO_REUSEADDR) failed");

#ifdef SO_REUSEPORT
    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, (const char*)&reuse, sizeof(reuse)) < 0) 
        perror("setsockopt(SO_REUSEPORT) failed");
#endif

Hide Button After Click (With Existing Form on Page)

CSS code:

.hide{
display:none;
}

.show{
display:block;
}

Html code:

<button onclick="block_none()">Check Availability</button>

Javascript Code:

function block_none(){
 document.getElementById('hidden-div').classList.add('show');
document.getElementById('button-id').classList.add('hide');
}

IE11 prevents ActiveX from running

We started finding some machines with IE 11 not playing video (via flash) after we set the emulation mode of our app (web browser control) to 110001. Adding the meta tag to our htm files worked for us.

Path of currently executing powershell script

For PowerShell 3.0 users - following works for both modules and script files:

function Get-ScriptDirectory {
    Split-Path -parent $PSCommandPath
}

Define a struct inside a class in C++

Yes you can. In c++, class and struct are kind of similar. We can define not only structure inside a class, but also a class inside one. It is called inner class.

As an example I am adding a simple Trie class.

class Trie {
private:
    struct node{
        node* alp[26];
        bool isend;
    };
    node* root;
    node* createNode(){
        node* newnode=new node();
        for(int i=0; i<26; i++){
            newnode->alp[i]=nullptr;
        }
        newnode->isend=false;
        return newnode;
    }
public:
    /** Initialize your data structure here. */
    Trie() {
        root=createNode();
    }

    /** Inserts a word into the trie. */
    void insert(string word) {
        node* head=root;
        for(int i=0; i<word.length(); i++){
            if(head->alp[int(word[i]-'a')]==nullptr){
                node* newnode=createNode();
                head->alp[int(word[i]-'a')]=newnode;
            }
            head=head->alp[int(word[i]-'a')];
        }
        head->isend=true;
    }

    /** Returns if the word is in the trie. */
    bool search(string word) {
        node* head=root;
        for(int i=0; i<word.length(); i++){
            if(head->alp[int(word[i]-'a')]==nullptr){
                return false;
            }
            head=head->alp[int(word[i]-'a')];
        }
        if(head->isend){return true;}
        return false;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        node* head=root;
        for(int i=0; i<prefix.length(); i++){
            if(head->alp[int(prefix[i]-'a')]==nullptr){
                return false;
            }
            head=head->alp[int(prefix[i]-'a')];
        }
        return true;
    }
};

/**
 * Your Trie object will be instantiated and called as such:
 * Trie* obj = new Trie();
 * obj->insert(word);
 * bool param_2 = obj->search(word);
 * bool param_3 = obj->startsWith(prefix);
 */

Error Code 1292 - Truncated incorrect DOUBLE value - Mysql

Had this issue with ES6 and TypeORM while trying to pass .where("order.id IN (:orders)", { orders }), where orders was a comma separated string of numbers. When I converted to a template literal, the problem was resolved.

.where(`order.id IN (${orders})`);

Add custom message to thrown exception while maintaining stack trace in Java

you can use super while extending Exception

if (pass.length() < minPassLength)
    throw new InvalidPassException("The password provided is too short");
 } catch (NullPointerException e) {
    throw new InvalidPassException("No password provided", e);
 }


// A custom business exception
class InvalidPassException extends Exception {

InvalidPassException() {

}

InvalidPassException(String message) {
    super(message);
}
InvalidPassException(String message, Throwable cause) {
   super(message, cause);
}

}

}

source

"Active Directory Users and Computers" MMC snap-in for Windows 7?

As "me1" has mentioned you can do this assuming that your version of Windows 7 is either Professional or Ultimate, the PC is on the domain and you have preinstall the Remote Server Administration Tools (Windows6.1-KB958830-x64-RefreshPkg.msu or newer) then you'll be able to do the following:

Step 1. Select "Start", select "Control Panel", select "Programs" and click on "Turn Windows features on or off".

Step 2. Check the following 5 features:

"remote server administration tools>feature administration tools>group policy management tools"

"remote server administration tools>feature administration tools>smtp server tools"

"remote server administration tools>role administration tools>ad ds and ad lds tools>active directory module for windows powershell"

"remote server administration tools>role administration tools>ad ds and ad lds tools>ad ds tools>active directory administrative center"

"remote server administration tools>role administration tools>ad ds and ad lds tools>ad ds tools>ad ds snap-ins and command-line tools"

Step 3. Click "OK".

How to implement endless list with RecyclerView?

Here my solution using AsyncListUtil, in the web says: Note that this class uses a single thread to load the data, so it suitable to load data from secondary storage such as disk, but not from network. but i am using odata to read the data and work fine. I miss in my example data entities and network methods. I include only the example adapter.

public class AsyncPlatoAdapter extends RecyclerView.Adapter {

    private final AsyncPlatoListUtil mAsyncListUtil;
    private final MainActivity mActivity;
    private final RecyclerView mRecyclerView;
    private final String mFilter;
    private final String mOrderby;
    private final String mExpand;

    public AsyncPlatoAdapter(String filter, String orderby, String expand, RecyclerView recyclerView, MainActivity activity) {
        mFilter = filter;
        mOrderby = orderby;
        mExpand = expand;
        mRecyclerView = recyclerView;
        mActivity = activity;
        mAsyncListUtil = new AsyncPlatoListUtil();

    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).
                inflate(R.layout.plato_cardview, parent, false);

        // Create a ViewHolder to find and hold these view references, and
        // register OnClick with the view holder:
        return new PlatoViewHolderAsync(itemView, this);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        final Plato item = mAsyncListUtil.getItem(position);
        PlatoViewHolderAsync vh = (PlatoViewHolderAsync) holder;
        if (item != null) {
            Integer imagen_id = item.Imagen_Id.get();
            vh.getBinding().setVariable(BR.plato, item);
            vh.getBinding().executePendingBindings();
            vh.getImage().setVisibility(View.VISIBLE);
            vh.getProgress().setVisibility(View.GONE);
            String cacheName = null;
            String urlString = null;
            if (imagen_id != null) {
                cacheName = String.format("imagenes/imagen/%d", imagen_id);
                urlString = String.format("%s/menusapi/%s", MainActivity.ROOTPATH, cacheName);
            }
            ImageHelper.downloadBitmap(mActivity, vh.getImage(), vh.getProgress(), urlString, cacheName, position);
        } else {
            vh.getBinding().setVariable(BR.plato, item);
            vh.getBinding().executePendingBindings();
            //show progress while loading.
            vh.getImage().setVisibility(View.GONE);
            vh.getProgress().setVisibility(View.VISIBLE);
        }
    }

    @Override
    public int getItemCount() {
        return mAsyncListUtil.getItemCount();
    }

    public class AsyncPlatoListUtil extends AsyncListUtil<Plato> {
        /**
         * Creates an AsyncListUtil.
         */
        public AsyncPlatoListUtil() {
            super(Plato.class, //my data class
                    10, //page size
                    new DataCallback<Plato>() {
                        @Override
                        public int refreshData() {
                            //get count calling ../$count ... odata endpoint
                            return countPlatos(mFilter, mOrderby, mExpand, mActivity);
                        }

                        @Override
                        public void fillData(Plato[] data, int startPosition, int itemCount) {
                            //get items from odata endpoint using $skip and $top
                            Platos p = loadPlatos(mFilter, mOrderby, mExpand, startPosition, itemCount, mActivity);
                            for (int i = 0; i < Math.min(itemCount, p.value.size()); i++) {
                                data[i] = p.value.get(i);
                            }

                        }
                    }, new ViewCallback() {
                        @Override
                        public void getItemRangeInto(int[] outRange) {
                            //i use LinearLayoutManager in the RecyclerView
                            LinearLayoutManager layoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
                            outRange[0] = layoutManager.findFirstVisibleItemPosition();
                            outRange[1] = layoutManager.findLastVisibleItemPosition();
                        }

                        @Override
                        public void onDataRefresh() {
                            mRecyclerView.getAdapter().notifyDataSetChanged();
                        }

                        @Override
                        public void onItemLoaded(int position) {
                            mRecyclerView.getAdapter().notifyItemChanged(position);
                        }
                    });
            mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    onRangeChanged();
                }
            });
        }
    }
}

Copying files from one directory to another in Java

import static java.nio.file.StandardCopyOption.*;
...
Files.copy(source, target, REPLACE_EXISTING);

Source: https://docs.oracle.com/javase/tutorial/essential/io/copy.html

Center image in table td in CSS

Center a div inside td using margin, the trick is to make the div width same as image width.

<td>
    <div style="margin: 0 auto; width: 130px">
          <img src="me.jpg" alt="me" style="width: 130px" />
    </div>
</td>

How to force cp to overwrite without confirmation

It is not cp -i. If you do not want to be asked for confirmation, it is cp -n; for example:

cp -n src dest

Or in case of directories/folders is:

cp -nr src_dir dest_dir

Checking if date is weekend PHP

If you have PHP >= 5.1:

function isWeekend($date) {
    return (date('N', strtotime($date)) >= 6);
}

otherwise:

function isWeekend($date) {
    $weekDay = date('w', strtotime($date));
    return ($weekDay == 0 || $weekDay == 6);
}

How can I edit a view using phpMyAdmin 3.2.4?

In your database table list it should show View in Type column. To edit View:

  1. Click on your View in table list
  2. Click on Structure tab
  3. Click on Edit View under Check All

enter image description here

Hope this help

update: in PHPMyAdmin 4.x, it doesn't show View in Type, but you can still recognize it:

  1. In Row column: It had zero Row
  2. In Action column: It had greyed empty button

Of course it may be just an empty table, but when you open the structure, you will know whether it's a table or a view.

echo key and value of an array without and with loop

How to echo key and value of an array without and with loop

$keys = array_keys($page);
implode(',',$keys);
echo $keys[0].' is at '.$page['Home'];

How do I loop through items in a list box and then remove those item?

How about:

foreach(var s in listBox1.Items.ToArray())
{
    MessageBox.Show(s);
    //do stuff with (s);
    listBox1.Items.Remove(s);
}

The ToArray makes a copy of the list, so you don't need to worry about it changing the list while you are processing it.

python - checking odd/even numbers and changing outputs on number size

The modulo 2 solutions with %2 is good, but that requires a division and a subtraction. Because computers use binary arithmetic, a much more efficient solution is:

# This first solution does not produce a Boolean value. 
is_odd_if_zero = value & 1

# or

is_odd = (value & 1) == 1

# or

is_even = (value & 1) == 0

How to give color to each class in scatter plot in R?

One way is to use the lattice package and xyplot():

R> DF <- data.frame(x=1:10, y=rnorm(10)+5, 
+>                  z=sample(letters[1:3], 10, replace=TRUE))
R> DF
    x       y z
1   1 3.91191 c
2   2 4.57506 a
3   3 3.16771 b
4   4 5.37539 c
5   5 4.99113 c
6   6 5.41421 a
7   7 6.68071 b
8   8 5.58991 c
9   9 5.03851 a
10 10 4.59293 b
R> with(DF, xyplot(y ~ x, group=z))

By giving explicit grouping information via variable z, you obtain different colors. You can specify colors etc, see the lattice documentation.

Because z here is a factor variable for which we obtain the levels (== numeric indices), you can also do

R> with(DF, plot(x, y, col=z))

but that is less transparent (to me, at least :) then xyplot() et al.

How to convert std::string to lower case?

On microsoft platforms you can use the strlwr family of functions: http://msdn.microsoft.com/en-us/library/hkxwh33z.aspx

// crt_strlwr.c
// compile with: /W3
// This program uses _strlwr and _strupr to create
// uppercase and lowercase copies of a mixed-case string.
#include <string.h>
#include <stdio.h>

int main( void )
{
   char string[100] = "The String to End All Strings!";
   char * copy1 = _strdup( string ); // make two copies
   char * copy2 = _strdup( string );

   _strlwr( copy1 ); // C4996
   _strupr( copy2 ); // C4996

   printf( "Mixed: %s\n", string );
   printf( "Lower: %s\n", copy1 );
   printf( "Upper: %s\n", copy2 );

   free( copy1 );
   free( copy2 );
}

how to get the attribute value of an xml node using java

try something like this :

    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document dDoc = builder.parse("d://utf8test.xml");

    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList) xPath.evaluate("//xml/ep/source/@type", dDoc, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        System.out.println(node.getTextContent());
    }

please note the changes :

  • we ask for a nodeset (XPathConstants.NODESET) and not only for a single node.
  • the xpath is now //xml/ep/source/@type and not //xml/source/@type/text()

PS: can you add the tag java to your question ? thanks.

Android translate animation - permanently move View to new position using AnimationListener

I usually prefer to work with deltas in translate animation, since it avoids a lot of confusion.

Try this out, see if it works for you:

TranslateAnimation anim = new TranslateAnimation(0, amountToMoveRight, 0, amountToMoveDown);
anim.setDuration(1000);

anim.setAnimationListener(new TranslateAnimation.AnimationListener() {

    @Override
    public void onAnimationStart(Animation animation) { }

    @Override
    public void onAnimationRepeat(Animation animation) { }

    @Override
    public void onAnimationEnd(Animation animation) 
    {
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)view.getLayoutParams();
        params.topMargin += amountToMoveDown;
        params.leftMargin += amountToMoveRight;
        view.setLayoutParams(params);
    }
});

view.startAnimation(anim);

Make sure to make amountToMoveRight / amountToMoveDown final

Hope this helps :)

Measuring code execution time

Stopwatch is designed for this purpose and is one of the best way to measure execution time in .NET.

var watch = System.Diagnostics.Stopwatch.StartNew();
/* the code that you want to measure comes here */
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;

Do not use DateTimes to measure execution time in .NET.

How do I pass multiple parameters in Objective-C?

(int) add: (int) numberOne plus: (int) numberTwo ;
(returnType) functionPrimaryName : (returnTypeOfArgumentOne) argumentName functionSecondaryNa

me:

(returnTypeOfSecontArgument) secondArgumentName ;

as in other languages we use following syntax void add(int one, int second) but way of assigning arguments in OBJ_c is different as described above

Check if element exists in jQuery

Try to check the length of the selector, if it returns you something then the element must exists else not.

 if( $('#selector').length )         // use this if you are using id to check
{
     // it exists
}


 if( $('.selector').length )         // use this if you are using class to check
{
     // it exists
}

How do I add a foreign key to an existing SQLite table?

In case somebody else needs info on SQLiteStudio, you can easily do it form it's GUI.

Double-click on the column and double-click foreign key row, then tick foreign key and click configure. You can add the reference column, then click OK in every window.

Finally click on the green tick to commit changes in the structure.

BE AWARE THAT THESE STEPS CREATE SQL SCRIPTS THAT DELETES THE TABLE AND RECREATES IT!!

Backup your data from the database.

setting content between div tags using javascript

If the number of your messages is limited then the following may help. I used jQuery for the following example, but it works with plain js too.

The innerHtml property did not work for me. So I experimented with ...

    <div id=successAndErrorMessages-1>100% OK</div>
    <div id=successAndErrorMessages-2>This is an error mssg!</div>

and toggled one of the two on/off ...

 $("#successAndErrorMessages-1").css('display', 'none')
 $("#successAndErrorMessages-2").css('display', '')

For some reason I had to fiddle around with the ordering before it worked in all types of browsers.

Getting a timestamp for today at midnight?

$timestamp = strtotime('today midnight');

is the same as

$timestamp = strtotime('today');

and it's a little less work on your server.

Persistent invalid graphics state error when using ggplot2

You likely don't need to reinstall ggplot2

Solution: go back to plot that didn't work previously. Take the below console output for example. The figure margins (the window that displays your plots) were too small to display the pairs(MinusInner) plot. Then when I tried to make the next qplot, R was still hung up on previous error.

pairs(MinusInner) Error in plot.new() : figure margins too large qplot(Sample.Type, BAE,data=MinusInner, geom="boxplot") Error in .Call.graphics(C_palette2, .Call(C_palette2, NULL)) : invalid graphics state

I fixed the first error by expanding the plot window and rerunning the pairs(MinusInner) plot. Then blam, it worked.

pairs(MinusInner) qplot(Sample.Type, BAE,data=MinusInner, geom="boxplot")

How should I load files into my Java application?

I haven't had a problem just using Unix-style path separators, even on Windows (though it is good practice to check File.separatorChar).

The technique of using ClassLoader.getResource() is best for read-only resources that are going to be loaded from JAR files. Sometimes, you can programmatically determine the application directory, which is useful for admin-configurable files or server applications. (Of course, user-editable files should be stored somewhere in the System.getProperty("user.home") directory.)

show distinct column values in pyspark dataframe: python

you could do

distinct_column = 'somecol' 

distinct_column_vals = df.select(distinct_column).distinct().collect()
distinct_column_vals = [v[distinct_column] for v in distinct_column_vals]

URL encoding the space character: + or %20?

This confusion is because URLs are still 'broken' to this day.

Take "http://www.google.com" for instance. This is a URL. A URL is a Uniform Resource Locator and is really a pointer to a web page (in most cases). URLs actually have a very well-defined structure since the first specification in 1994.

We can extract detailed information about the "http://www.google.com" URL:

+---------------+-------------------+
|      Part     |      Data         |
+---------------+-------------------+
|  Scheme       | http              |
|  Host         | www.google.com    |
+---------------+-------------------+

If we look at a more complex URL such as:

"https://bob:[email protected]:8080/file;p=1?q=2#third"

we can extract the following information:

+-------------------+---------------------+
|        Part       |       Data          |
+-------------------+---------------------+
|  Scheme           | https               |
|  User             | bob                 |
|  Password         | bobby               |
|  Host             | www.lunatech.com    |
|  Port             | 8080                |
|  Path             | /file;p=1           |
|  Path parameter   | p=1                 |
|  Query            | q=2                 |
|  Fragment         | third               |
+-------------------+---------------------+

https://bob:[email protected]:8080/file;p=1?q=2#third
\___/   \_/ \___/ \______________/ \__/\_______/ \_/ \___/
  |      |    |          |          |      | \_/  |    |
Scheme User Password    Host       Port  Path |   | Fragment
        \_____________________________/       | Query
                       |               Path parameter
                   Authority

The reserved characters are different for each part.

For HTTP URLs, a space in a path fragment part has to be encoded to "%20" (not, absolutely not "+"), while the "+" character in the path fragment part can be left unencoded.

Now in the query part, spaces may be encoded to either "+" (for backwards compatibility: do not try to search for it in the URI standard) or "%20" while the "+" character (as a result of this ambiguity) has to be escaped to "%2B".

This means that the "blue+light blue" string has to be encoded differently in the path and query parts:

"http://example.com/blue+light%20blue?blue%2Blight+blue".

From there you can deduce that encoding a fully constructed URL is impossible without a syntactical awareness of the URL structure.

This boils down to:

You should have %20 before the ? and + after.

Source

Override back button to act like home button

Working example..

Make sure don't call super.onBackPressed();

@Override
public void onBackPressed() {
   Log.d("CDA", "onBackPressed Called");
   Intent setIntent = new Intent(Intent.ACTION_MAIN);
   setIntent.addCategory(Intent.CATEGORY_HOME);
   setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   startActivity(setIntent);
}

In this way your Back Button act like Home button . It doesn't finishes your activity but take it to background

Second way is to call moveTaskToBack(true); in onBackPressed and be sure to remove super.onBackPressed

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

When none of the if test in number_translator() evaluate to true, the function returns None. The error message is the consequence of that.

Whenever you see an error that include 'NoneType' that means that you have an operand or an object that is None when you were expecting something else.

Uncaught TypeError: Cannot read property 'msie' of undefined

$.browser was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.

OpenCV get pixel channel value from Mat image

Assuming the type is CV_8UC3 you would do this:

for(int i = 0; i < foo.rows; i++)
{
    for(int j = 0; j < foo.cols; j++)
    {
        Vec3b bgrPixel = foo.at<Vec3b>(i, j);

        // do something with BGR values...
    }
}

Here is the documentation for Vec3b. Hope that helps! Also, don't forget OpenCV stores things internally as BGR not RGB.

EDIT :
For performance reasons, you may want to use direct access to the data buffer in order to process the pixel values:

Here is how you might go about this:

uint8_t* pixelPtr = (uint8_t*)foo.data;
int cn = foo.channels();
Scalar_<uint8_t> bgrPixel;

for(int i = 0; i < foo.rows; i++)
{
    for(int j = 0; j < foo.cols; j++)
    {
        bgrPixel.val[0] = pixelPtr[i*foo.cols*cn + j*cn + 0]; // B
        bgrPixel.val[1] = pixelPtr[i*foo.cols*cn + j*cn + 1]; // G
        bgrPixel.val[2] = pixelPtr[i*foo.cols*cn + j*cn + 2]; // R

        // do something with BGR values...
    }
}

Or alternatively:

int cn = foo.channels();
Scalar_<uint8_t> bgrPixel;

for(int i = 0; i < foo.rows; i++)
{
    uint8_t* rowPtr = foo.row(i);
    for(int j = 0; j < foo.cols; j++)
    {
        bgrPixel.val[0] = rowPtr[j*cn + 0]; // B
        bgrPixel.val[1] = rowPtr[j*cn + 1]; // G
        bgrPixel.val[2] = rowPtr[j*cn + 2]; // R

        // do something with BGR values...
    }
}

length and length() in Java

Consider:

int[] myArray = new int[10];
String myString = "hello world!";
List<int> myList = new ArrayList<int>();

myArray.length    // Gives the length of the array
myString.length() // Gives the length of the string
myList.size()     // Gives the length of the list

It's very likely that strings and arrays were designed at different times and hence ended up using different conventions. One justification is that since Strings use arrays internally, a method, length(), was used to avoid duplication of the same information. Another is that using a method length() helps emphasize the immutability of strings, even though the size of an array is also unchangeable.

Ultimately this is just an inconsistency that evolved that would definitely be fixed if the language were ever redesigned from the ground up. As far as I know no other languages (C#, Python, Scala, etc.) do the same thing, so this is likely just a slight flaw that ended up as part of the language.

You'll get an error if you use the wrong one anyway.