Programs & Examples On #Notation

Notation refers to a specific way of writing various concepts, functions, etc. Usually it is introduced to abbreviate complicated expressions and make common idioms more readable.

What do numbers using 0x notation mean?

In C and languages based on the C syntax, the prefix 0x means hexadecimal (base 16).

Thus, 0x400 = 4×(162) + 0×(161) + 0×(160) = 4×((24)2) = 22 × 28 = 210 = 1024, or one binary K.

And so 0x6400 = 0x4000 + 0x2400 = 0x19×0x400 = 25K

What exactly does big ? notation represent?

Big Theta notation:

Nothing to mess up buddy!!

If we have a positive valued functions f(n) and g(n) takes a positive valued argument n then ?(g(n)) defined as {f(n):there exist constants c1,c2 and n1 for all n>=n1}

where c1 g(n)<=f(n)<=c2 g(n)

Let's take an example:

let f(n)=

g(n)=

c1=5 and c2=8 and n1=1

Among all the notations ,? notation gives the best intuition about the rate of growth of function because it gives us a tight bound unlike big-oh and big -omega which gives the upper and lower bounds respectively.

? tells us that g(n) is as close as f(n),rate of growth of g(n) is as close to the rate of growth of f(n) as possible.

see the image to get a better intuition

What exactly does += do in python?

+= adds another value with the variable's value and assigns the new value to the variable.

>>> x = 3
>>> x += 2
>>> print x
5

-=, *=, /= does similar for subtraction, multiplication and division.

conversion from infix to prefix

Algorithm ConvertInfixtoPrefix

Purpose: Convert an infix expression into a prefix expression. Begin 
// Create operand and operator stacks as empty stacks. 
Create OperandStack
Create OperatorStack

// While input expression still remains, read and process the next token.

while( not an empty input expression ) read next token from the input expression

    // Test if token is an operand or operator 
    if ( token is an operand ) 
    // Push operand onto the operand stack. 
        OperandStack.Push (token)
    endif

    // If it is a left parentheses or operator of higher precedence than the last, or the stack is empty,
    else if ( token is '(' or OperatorStack.IsEmpty() or OperatorHierarchy(token) > OperatorHierarchy(OperatorStack.Top()) )
    // push it to the operator stack
        OperatorStack.Push ( token )
    endif

    else if( token is ')' ) 
    // Continue to pop operator and operand stacks, building 
    // prefix expressions until left parentheses is found. 
    // Each prefix expression is push back onto the operand 
    // stack as either a left or right operand for the next operator. 
        while( OperatorStack.Top() not equal '(' ) 
            OperatorStack.Pop(operator) 
            OperandStack.Pop(RightOperand) 
            OperandStack.Pop(LeftOperand) 
            operand = operator + LeftOperand + RightOperand 
            OperandStack.Push(operand) 
        endwhile

    // Pop the left parthenses from the operator stack. 
    OperatorStack.Pop(operator)
    endif

    else if( operator hierarchy of token is less than or equal to hierarchy of top of the operator stack )
    // Continue to pop operator and operand stack, building prefix 
    // expressions until the stack is empty or until an operator at 
    // the top of the operator stack has a lower hierarchy than that 
    // of the token. 
        while( !OperatorStack.IsEmpty() and OperatorHierarchy(token) lessThen Or Equal to OperatorHierarchy(OperatorStack.Top()) ) 
            OperatorStack.Pop(operator) 
            OperandStack.Pop(RightOperand) 
            OperandStack.Pop(LeftOperand) 
            operand = operator + LeftOperand + RightOperand 
            OperandStack.Push(operand)
        endwhile 
        // Push the lower precedence operator onto the stack 
        OperatorStack.Push(token)
    endif
endwhile 
// If the stack is not empty, continue to pop operator and operand stacks building 
// prefix expressions until the operator stack is empty. 
while( !OperatorStack.IsEmpty() ) OperatorStack.Pop(operator) 
    OperandStack.Pop(RightOperand) 
    OperandStack.Pop(LeftOperand) 
    operand = operator + LeftOperand + RightOperand

    OperandStack.Push(operand) 
endwhile

// Save the prefix expression at the top of the operand stack followed by popping // the operand stack.

print OperandStack.Top()

OperandStack.Pop()

End

What is the difference between T(n) and O(n)?

Using limits

Let's consider f(n) > 0 and g(n) > 0 for all n. It's ok to consider this, because the fastest real algorithm has at least one operation and completes its execution after the start. This will simplify the calculus, because we can use the value (f(n)) instead of the absolute value (|f(n)|).

  1. f(n) = O(g(n))

    General:

              f(n)     
    0 = lim -------- < 8
        n?8   g(n)
    

    For g(n) = n:

              f(n)     
    0 = lim -------- < 8
        n?8    n
    

    Examples:

        Expression               Value of the limit
    ------------------------------------------------
    n        = O(n)                      1
    1/2*n    = O(n)                     1/2
    2*n      = O(n)                      2
    n+log(n) = O(n)                      1
    n        = O(n*log(n))               0
    n        = O(n²)                     0
    n        = O(nn)                     0
    

    Counterexamples:

        Expression                Value of the limit
    -------------------------------------------------
    n        ? O(log(n))                 8
    1/2*n    ? O(sqrt(n))                8
    2*n      ? O(1)                      8
    n+log(n) ? O(log(n))                 8
    
  2. f(n) = T(g(n))

    General:

              f(n)     
    0 < lim -------- < 8
        n?8   g(n)
    

    For g(n) = n:

              f(n)     
    0 < lim -------- < 8
        n?8    n
    

    Examples:

        Expression               Value of the limit
    ------------------------------------------------
    n        = T(n)                      1
    1/2*n    = T(n)                     1/2
    2*n      = T(n)                      2
    n+log(n) = T(n)                      1
    

    Counterexamples:

        Expression                Value of the limit
    -------------------------------------------------
    n        ? T(log(n))                 8
    1/2*n    ? T(sqrt(n))                8
    2*n      ? T(1)                      8
    n+log(n) ? T(log(n))                 8
    n        ? T(n*log(n))               0
    n        ? T(n²)                     0
    n        ? T(nn)                     0
    

What does %w(array) mean?

I think of %w() as a "word array" - the elements are delimited by spaces and it returns an array of strings.

There are other % literals:

  • %r() is another way to write a regular expression.
  • %q() is another way to write a single-quoted string (and can be multi-line, which is useful)
  • %Q() gives a double-quoted string
  • %x() is a shell command
  • %i() gives an array of symbols (Ruby >= 2.0.0)
  • %s() turns foo into a symbol (:foo)

I don't know any others, but there may be some lurking around in there...

Python loop to run for certain amount of seconds

If I understand you, you can do it with a datetime.timedelta -

import datetime

endTime = datetime.datetime.now() + datetime.timedelta(minutes=15)
while True:
  if datetime.datetime.now() >= endTime:
    break
  # Blah
  # Blah

How to generate random colors in matplotlib?

elaborating @john-mee 's answer, if you have arbitrarily long data but don't need strictly unique colors:

for python 2:

from itertools import cycle
cycol = cycle('bgrcmk')

for X,Y in data:
    scatter(X, Y, c=cycol.next())

for python 3:

from itertools import cycle
cycol = cycle('bgrcmk')

for X,Y in data:
    scatter(X, Y, c=next(cycol))

this has the advantage that the colors are easy to control and that it's short.

How to click an element in Selenium WebDriver using JavaScript

Another easiest solution is to use Key.RETUEN

Click here for solution in detail

driver.findElement(By.name("q")).sendKeys("Selenium Tutorial", Key.RETURN);

Access multiple elements of list knowing their index

Kind of pythonic way:

c = [x for x in a if a.index(x) in b]

How can I pipe stderr, and not stdout?

This also works (and I find it a tiny bit easier to remember)

command 2> /dev/fd/1 | grep 'something'

More info about /dev/fd directory here

Git: Recover deleted (remote) branch

  1. find out commit id

    git reflog

  2. recover local branch you deleted by mistake

    git branch need-recover-branch-name commitId

  3. push need-recover-branch-name again if you deleted remote branch too before

    git push origin need-recover-branch-name

Convert float to double without losing precision

Use a BigDecimal instead of float/double. There are a lot of numbers which can't be represented as binary floating point (for example, 0.1). So you either must always round the result to a known precision or use BigDecimal.

See http://en.wikipedia.org/wiki/Floating_point for more information.

HTTP 1.0 vs 1.1

A key compatibility issue is support for persistent connections. I recently worked on a server that "supported" HTTP/1.1, yet failed to close the connection when a client sent an HTTP/1.0 request. When writing a server that supports HTTP/1.1, be sure it also works well with HTTP/1.0-only clients.

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

With Apache Commons 3, you want to call

StringUtils.join(myCollection, ",")

How to set space between listView Items in Android

In order to give spacing between views inside a listView please use padding on your inflate views.

You can use android:paddingBottom="(number)dp" && android:paddingTop="(number)dp" on your view or views you're inflate inside your listview.

The divider solution is just a fix, because some day, when you'll want to use a divider color (right now it's transparent) you will see that the divider line is been stretched.

jQuery Validation using the class instead of the name value

Since for me, some elements are created on page load, and some are dynamically added by the user; I used this to make sure everything stayed DRY.

On submit, find everything with class x, remove class x, add rule x.

$('#form').on('submit', function(e) {
    $('.alphanumeric_dash').each(function() {
        var $this = $(this);
        $this.removeClass('alphanumeric_dash');
        $(this).rules('add', {
            alphanumeric_dash: true
        });
    });
});

ASP.NET jQuery Ajax Calling Code-Behind Method

Firstly, you probably want to add a return false; to the bottom of your Submit() method in JavaScript (so it stops the submit, since you're handling it in AJAX).

You're connecting to the complete event, not the success event - there's a significant difference and that's why your debugging results aren't as expected. Also, I've never made the signature methods match yours, and I've always provided a contentType and dataType. For example:

$.ajax({
        type: "POST",
        url: "Default.aspx/OnSubmit",
        data: dataValue,                
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
        },
        success: function (result) {
            alert("We returned: " + result);
        }
    });

How to wrap text around an image using HTML/CSS

Addition to BeNdErR's answer:
The "other TEXT" element should have float:none, like:

_x000D_
_x000D_
    <div style="width:100%;">_x000D_
        <div style="float:left;width:30%; background:red;">...something something something  random text</div>_x000D_
        <div style="float:none; background:yellow;"> text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text  </div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

Removing NA observations with dplyr::filter()

From @Ben Bolker:

[T]his has nothing specifically to do with dplyr::filter()

From @Marat Talipov:

[A]ny comparison with NA, including NA==NA, will return NA

From a related answer by @farnsy:

The == operator does not treat NA's as you would expect it to.

Think of NA as meaning "I don't know what's there". The correct answer to 3 > NA is obviously NA because we don't know if the missing value is larger than 3 or not. Well, it's the same for NA == NA. They are both missing values but the true values could be quite different, so the correct answer is "I don't know."

R doesn't know what you are doing in your analysis, so instead of potentially introducing bugs that would later end up being published an embarrassing you, it doesn't allow comparison operators to think NA is a value.

Extracting extension from filename in Python

Although it is an old topic, but i wonder why there is none mentioning a very simple api of python called rpartition in this case:

to get extension of a given file absolute path, you can simply type:

filepath.rpartition('.')[-1]

example:

path = '/home/jersey/remote/data/test.csv'
print path.rpartition('.')[-1]

will give you: 'csv'

Posting array from form

When you post that data, it is stored as an array in $_POST.

You could optionally do something like:

<input name="arrayname[item1]">
<input name="arrayname[item2]">
<input name="arrayname[item3]">

Then:

$item1 = $_POST['arrayname']['item1'];
$item2 = $_POST['arrayname']['item2'];
$item3 = $_POST['arrayname']['item3'];

But I fail to see the point.

Message "Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout"

It should call the async/await when it is async from test.

describe("Profile Tab Exists and Clickable: /settings/user", () => {
    test(`Assert that you can click the profile tab`, async (done) => {
        await page.waitForSelector(PROFILE.TAB);
        await page.click(PROFILE.TAB);
        done();
    }, 30000);
});

How to decrypt the password generated by wordpress

You will not be able to retrieve a plain text password from wordpress.

Wordpress use a 1 way encryption to store the passwords using a variation of md5. There is no way to reverse this.

See this article for more info http://wordpress.org/support/topic/how-is-the-user-password-encrypted-wp_hash_password

What is a serialVersionUID and why should I use it?

Field data represents some information stored in the class. Class implements the Serializable interface, so eclipse automatically offered to declare the serialVersionUID field. Lets start with value 1 set there.

If you don't want that warning to come, use this:

@SuppressWarnings("serial")

How to convert java.lang.Object to ArrayList?

The conversion fails (java.lang.ClassCastException: java.lang.String cannot be cast to java.util.ArrayList) because you have surely some objects that are not ArrayList. verify the types of your different objects.

Bash script error [: !=: unary operator expected

Or for what seems like rampant overkill, but is actually simplistic ... Pretty much covers all of your cases, and no empty string or unary concerns.

In the case the first arg is '-v', then do your conditional ps -ef, else in all other cases throw the usage.

#!/bin/sh
case $1 in
  '-v') if [ "$1" = -v ]; then
         echo "`ps -ef | grep -v '\['`"
        else
         echo "`ps -ef | grep '\[' | grep root`"
        fi;;
     *) echo "usage: $0 [-v]"
        exit 1;; #It is good practice to throw a code, hence allowing $? check
esac

If one cares not where the '-v' arg is, then simply drop the case inside a loop. The would allow walking all the args and finding '-v' anywhere (provided it exists). This means command line argument order is not important. Be forewarned, as presented, the variable arg_match is set, thus it is merely a flag. It allows for multiple occurrences of the '-v' arg. One could ignore all other occurrences of '-v' easy enough.

#!/bin/sh

usage ()
 {
  echo "usage: $0 [-v]"
  exit 1
 }

unset arg_match

for arg in $*
 do
  case $arg in
    '-v') if [ "$arg" = -v ]; then
           echo "`ps -ef | grep -v '\['`"
          else
           echo "`ps -ef | grep '\[' | grep root`"
          fi
          arg_match=1;; # this is set, but could increment.
       *) ;;
  esac
done

if [ ! $arg_match ]
 then
  usage
fi

But, allow multiple occurrences of an argument is convenient to use in situations such as:

$ adduser -u:sam -s -f -u:bob -trace -verbose

We care not about the order of the arguments, and even allow multiple -u arguments. Yes, it is a simple matter to also allow:

$ adduser -u sam -s -f -u bob -trace -verbose

find all unchecked checkbox in jquery

$(".clscss-row").each(function () {
if ($(this).find(".po-checkbox").not(":checked")) {
               // enter your code here
            } });

Converting <br /> into a new line for use in a text area

Here is another approach.

class orbisius_custom_string {
    /**
     * The reverse of nl2br. Handles <br/> <br/> <br />
     * usage: orbisius_custom_string::br2nl('Your buffer goes here ...');
     * @param str $buff
     * @return str
     * @author Slavi Marinov | http://orbisius.com
     */
    public static function br2nl($buff = '') {
        $buff = preg_replace('#<br[/\s]*>#si', "\n", $buff);
        $buff = trim($buff);

        return $buff;
    }
}

Convert a SQL Server datetime to a shorter date format

The shortest date format of mm/dd/yy can be obtained with:

Select Convert(varchar(8),getdate(),1)

customize Android Facebook Login button

<FrameLayout
    android:id="@+id/FrameLayout1"
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:layout_marginStart="132dp"
    android:layout_marginTop="12dp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/logbu">


    <ImageView
        android:id="@+id/fb"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/fb"
        android:onClick="onClickFacebookButton"
        android:textAllCaps="false"
        android:textColor="#ffffff"
        android:textSize="22sp" />

    <com.facebook.login.widget.LoginButton

        android:alpha="0"  <!--***SOLUTION***-->
        android:id="@+id/buttonFacebookLogin"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingTop="45sp"
        android:visibility="visible"
        app:com_facebook_login_text="Log in with Facebook" />

</FrameLayout>

The easiest way to customize the integrated facebook button for both java and kotlin

Automatic vertical scroll bar in WPF TextBlock?

You can use

ScrollViewer.HorizontalScrollBarVisibility="Visible"
ScrollViewer.VerticalScrollBarVisibility="Visible"

These are attached property of wpf. For more information

http://wpfbugs.blogspot.in/2014/02/wpf-layout-controls-scrollviewer.html

Why am I getting this error Premature end of file?

Use inputstream once don't use it multiple times and Do inputstream.close()

How to install MySQLdb package? (ImportError: No module named setuptools)

well installing C compiler or GCC didn't work but I found a way to successfully install mysqldb package

kindly follow Mike schrieb's (Thanks to him) instructions here . In my case, I used setuptools-0.6c11-py2.7.egg and setuptools-0.6c11 . Then download the executable file here then install that file. hope it helps :)

Setting up Vim for Python

Re: the dead "Turning Vim Into A Modern Python IDE" link, back in 2013 I saved a copy, that I converted to a HTML page as well as a PDF copy:

http://persagen.com/files/misc/Turning_vim_into_a_modern_Python_IDE.html

http://persagen.com/files/misc/Turning_vim_into_a_modern_Python_IDE.pdf

Edit (Sep 08, 2017) updated URLs.

Selenium WebDriver How to Resolve Stale Element Reference Exception?

After deep investigation of the problem I found that error occurs selecting DIV elements that were added for Bootstrap only. Chrome browser removes such DIVS and the error occurs. It is enough to step down and select real element for fixing an error. For example, my modal dialog has structure:

<div class="modal-content" uib-modal-transclude="">
    <div class="modal-header">
        ...
    </div>
    <div class="modal-body">
        <form class="form-horizontal ...">
            ...
        </form>
    <div>
<div>

Selecting div class="modal-body" generates an error, selecting form ... works as it would.

How can I rename a single column in a table at select?

us the AS keyword

select a.Price as PriceOne, b.price as PriceTwo 
from tablea a, tableb b

How to see if an object is an array without using reflection?

You can use instanceof.

JLS 15.20.2 Type Comparison Operator instanceof

 RelationalExpression:
    RelationalExpression instanceof ReferenceType

At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

That means you can do something like this:

Object o = new int[] { 1,2 };
System.out.println(o instanceof int[]); // prints "true"        

You'd have to check if the object is an instanceof boolean[], byte[], short[], char[], int[], long[], float[], double[], or Object[], if you want to detect all array types.

Also, an int[][] is an instanceof Object[], so depending on how you want to handle nested arrays, it can get complicated.

For the toString, java.util.Arrays has a toString(int[]) and other overloads you can use. It also has deepToString(Object[]) for nested arrays.

public String toString(Object arr) {
   if (arr instanceof int[]) {
      return Arrays.toString((int[]) arr);
   } else //...
}

It's going to be very repetitive (but even java.util.Arrays is very repetitive), but that's the way it is in Java with arrays.

See also

forEach is not a function error with JavaScript array

That's because parent.children is a NodeList, and it doesn't support the .forEach method (as NodeList is an array like structure but not an array), so try to call it by first converting it to array using

var children = [].slice.call(parent.children);
children.forEach(yourFunc);

How do I make background-size work in IE?

Thanks to this post, my full css for cross browser happiness is:

<style>
    .backgroundpic {
        background-image: url('img/home.jpg');
        background-size: cover;
        filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(
        src='img/home.jpg',
        sizingMethod='scale');
    }
</style>

It's been so long since I've worked on this piece of code, but I'd like to add for more browser compatibility I've appended this to my CSS for more browser compatibility:

-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;

How to use boolean 'and' in Python

As pointed out, "&" in python performs a bitwise and operation, just as it does in C#. and is the appropriate equivalent to the && operator.

Since we're dealing with booleans (i == 5 is True and ii == 10 is also True), you may wonder why this didn't either work anyway (True being treated as an integer quantity should still mean True & True is a True value), or throw an exception (eg. by forbidding bitwise operations on boolean types)

The reason is operator precedence. The "and" operator binds more loosely than ==, so the expression: "i==5 and ii==10" is equivalent to: "(i==5) and (ii==10)"

However, bitwise & has a higher precedence than "==" (since you wouldn't want expressions like "a & 0xff == ch" to mean "a & (0xff == ch)"), so the expression would actually be interpreted as:

if i == (5 & ii) == 10:

Which is using python's operator chaining to mean: does the valuee of ii anded with 5 equal both i and 10. Obviously this will never be true.

You would actually get (seemingly) the right answer if you had included brackets to force the precedence, so:

if (i==5) & (ii=10)

would cause the statement to be printed. It's the wrong thing to do, however - "&" has many different semantics to "and" - (precedence, short-cirtuiting, behaviour with integer arguments etc), so it's fortunate that you caught this here rather than being fooled till it produced less obvious bugs.

Firebase TIMESTAMP to date and Time

Working with Firebase Firestone 18.0.1 (com.google.firebase.Timestamp)

val timestamp = (document.data["timestamp"] as Timestamp).toDate()

Difference between require, include, require_once and include_once?

My suggestion is to just use require_once 99.9% of the time.

Using require or include instead implies that your code is not reusable elsewhere, i.e. that the scripts you're pulling in actually execute code instead of making available a class or some function libraries.

If you are require/including code that executes on the spot, that's procedural code, and you need to get to know a new paradigm. Like object oriented programming, function-based programming, or functional programming.

If you're already doing OO or functional programming, using include_once is mostly going to be delaying where in the stack you find bugs/errors. Do you want to know that the function do_cool_stuff() is not available when you go to call for it later, or the moment that you expect it to be available by requiring the library? Generally, it's best to know immediately if something you need and expect isn't available, so just use require_once.

Alternatively, in modern OOP, just autoload your classes upon use.

Simplest/cleanest way to implement a singleton in JavaScript

var singleton = (function () {

    var singleton = function(){
        // Do stuff
    }
    var instance = new singleton();
    return function(){
        return instance;
    }
})();

A solution without the getInstance method.

How do you get the process ID of a program in Unix or Linux using Python?

The task can be solved using the following piece of code, [0:28] being interval where the name is being held, while [29:34] contains the actual pid.

import os

program_pid = 0
program_name = "notepad.exe"

task_manager_lines = os.popen("tasklist").readlines()
for line in task_manager_lines:
    try:
        if str(line[0:28]) == program_name + (28 - len(program_name) * ' ': #so it includes the whitespaces
            program_pid = int(line[29:34])
            break
    except:
        pass

print(program_pid)

How do I tell what type of value is in a Perl variable?

A scalar always holds a single element. Whatever is in a scalar variable is always a scalar. A reference is a scalar value.

If you want to know if it is a reference, you can use ref. If you want to know the reference type, you can use the reftype routine from Scalar::Util.

If you want to know if it is an object, you can use the blessed routine from Scalar::Util. You should never care what the blessed package is, though. UNIVERSAL has some methods to tell you about an object: if you want to check that it has the method you want to call, use can; if you want to see that it inherits from something, use isa; and if you want to see it the object handles a role, use DOES.

If you want to know if that scalar is actually just acting like a scalar but tied to a class, try tied. If you get an object, continue your checks.

If you want to know if it looks like a number, you can use looks_like_number from Scalar::Util. If it doesn't look like a number and it's not a reference, it's a string. However, all simple values can be strings.

If you need to do something more fancy, you can use a module such as Params::Validate.

SQL SELECT everything after a certain character

For SQL Management studio I used a variation of BWS' answer. This gets the data to the right of '=', or NULL if the symbol doesn't exist:

   CASE WHEN (RIGHT(supplier_reference, CASE WHEN (CHARINDEX('=',supplier_reference,0)) = 0 THEN
    0 ELSE CHARINDEX('=', supplier_reference) -1 END)) <> '' THEN (RIGHT(supplier_reference, CASE WHEN (CHARINDEX('=',supplier_reference,0)) = 0 THEN
    0 ELSE CHARINDEX('=', supplier_reference) -1 END)) ELSE NULL END

What is the reason behind "non-static method cannot be referenced from a static context"?

A non-static method is dependent on the object. It is recognized by the program once the object is created.

Static methods can be called even before the creation of an object. Static methods are great for doing comparisons or operations that aren't dependent on the actual objects you plan to work with.

Why do we need the "finally" clause in Python?

Perfect example is as below:

try:
    #x = Hello + 20
    x = 10 + 20 
except:
    print 'I am in except block'
    x = 20 + 30
else:
    print 'I am in else block'
    x += 1
finally:
    print 'Finally x = %s' %(x)

How to convert JSON to a Ruby hash

Have you tried: http://flori.github.com/json/?

Failing that, you could just parse it out? If it's only arrays you're interested in, something to split the above out will be quite simple.

Cannot insert explicit value for identity column in table 'table' when IDENTITY_INSERT is set to OFF

In my case I was having set another property as key in context for my modelBuilder.

modelBuilder.Entity<MyTable>().HasKey(t => t.OtherProp);

I had to set the proper id

 modelBuilder.Entity<MyTable>().HasKey(t => t.Id);

How can I share Jupyter notebooks with non-programmers?

Michael's suggestion of running your own nbviewer instance is a good one I used in the past with an Enterprise Github server.

Another lightweight alternative is to have a cell at the end of your notebook that does a shell call to nbconvert so that it's automatically refreshed after running the whole thing:

!ipython nbconvert <notebook name>.ipynb --to html

EDIT: With Jupyter/IPython's Big Split, you'll probably want to change this to !jupyter nbconvert <notebook name>.ipynb --to html now.

Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.`

Add Serializable() before the type you expose

Serializable()
Public Class YourType

Put Serializable into <>

library not found for -lPods

I tried EVERY answer in this thread to no avail. Finally resolved my issue by matching the "Pre-Configuration Build Products Path" in my target project with the value in the Pods project. Turns out they were building to two different output locations. None of the other suggestions in this thread were relevant for me. Would be great if XCode gave a useful error description (like WHY it can't use the lib - File Not Found, No matching architecture found, etc.).

How to write into a file in PHP?

$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase');
fwrite($fp, 'mice');
fclose($fp);

http://php.net/manual/en/function.fwrite.php

Default values for Vue component props & how to check if a user did not set the prop?

This is an old question, but regarding the second part of the question - how can you check if the user set/didn't set a prop?

Inspecting this within the component, we have this.$options.propsData. If the prop is present here, the user has explicitly set it; default values aren't shown.

This is useful in cases where you can't really compare your value to its default, e.g. if the prop is a function.

Is it possible to make desktop GUI application in .NET Core?

You could use Electron and wire it up with Edge.js resp. electron-edge. Edge.js allows Electron (Node.js) to call .NET DLL files and vice versa.

This way you can write the GUI with HTML, CSS and JavaScript and the backend with .NET Core. Electron itself is also cross platform and based on the Chromium browser.

How to change text color and console color in code::blocks?

Functions like textcolor worked in old compilers like turbo C and Dev C. In today's compilers these functions would not work. I am going to give two function SetColor and ChangeConsoleToColors. You copy paste these functions code in your program and do the following steps.The code I am giving will not work in some compilers.

The code of SetColor is -

 void SetColor(int ForgC)
 {
     WORD wColor;

      HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
      CONSOLE_SCREEN_BUFFER_INFO csbi;

                       //We use csbi for the wAttributes word.
     if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
     {
                 //Mask out all but the background attribute, and add in the forgournd     color
          wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
          SetConsoleTextAttribute(hStdOut, wColor);
     }
     return;
 }

To use this function you need to call it from your program. For example I am taking your sample program -

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <dos.h>
#include <dir.h>

int main(void)
{
  SetColor(4);
  printf("\n \n \t This text is written in Red Color \n ");
  getch();
  return 0;
}

void SetColor(int ForgC)
 {
 WORD wColor;

  HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
  CONSOLE_SCREEN_BUFFER_INFO csbi;

                       //We use csbi for the wAttributes word.
 if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
 {
                 //Mask out all but the background attribute, and add in the forgournd color
      wColor = (csbi.wAttributes & 0xF0) + (ForgC & 0x0F);
      SetConsoleTextAttribute(hStdOut, wColor);
 }
 return;
}

When you run the program you will get the text color in RED. Now I am going to give you the code of each color -

Name         | Value
             |
Black        |   0
Blue         |   1
Green        |   2
Cyan         |   3
Red          |   4
Magenta      |   5
Brown        |   6
Light Gray   |   7
Dark Gray    |   8
Light Blue   |   9
Light Green  |   10
Light Cyan   |   11
Light Red    |   12
Light Magenta|   13
Yellow       |   14
White        |   15

Now I am going to give the code of ChangeConsoleToColors. The code is -

void ClearConsoleToColors(int ForgC, int BackC)
 {
 WORD wColor = ((BackC & 0x0F) << 4) + (ForgC & 0x0F);
               //Get the handle to the current output buffer...
 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
                     //This is used to reset the carat/cursor to the top left.
 COORD coord = {0, 0};
                  //A return value... indicating how many chars were written
                    //   not used but we need to capture this since it will be
                      //   written anyway (passing NULL causes an access violation).
  DWORD count;

                               //This is a structure containing all of the console info
                      // it is used here to find the size of the console.
 CONSOLE_SCREEN_BUFFER_INFO csbi;
                 //Here we will set the current color
 SetConsoleTextAttribute(hStdOut, wColor);
 if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
 {
                          //This fills the buffer with a given character (in this case 32=space).
      FillConsoleOutputCharacter(hStdOut, (TCHAR) 32, csbi.dwSize.X * csbi.dwSize.Y, coord, &count);

      FillConsoleOutputAttribute(hStdOut, csbi.wAttributes, csbi.dwSize.X * csbi.dwSize.Y, coord, &count );
                          //This will set our cursor position for the next print statement.
      SetConsoleCursorPosition(hStdOut, coord);
 }
 return;
}

In this function you pass two numbers. If you want normal colors just put the first number as zero and the second number as the color. My example is -

#include <windows.h>          //header file for windows
#include <stdio.h>

void ClearConsoleToColors(int ForgC, int BackC);

int main()
{
ClearConsoleToColors(0,15);
Sleep(1000);
return 0;
}
void ClearConsoleToColors(int ForgC, int BackC)
{
 WORD wColor = ((BackC & 0x0F) << 4) + (ForgC & 0x0F);
               //Get the handle to the current output buffer...
 HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
                     //This is used to reset the carat/cursor to the top left.
 COORD coord = {0, 0};
                  //A return value... indicating how many chars were written
                    //   not used but we need to capture this since it will be
                      //   written anyway (passing NULL causes an access violation).
 DWORD count;

                               //This is a structure containing all of the console info
                      // it is used here to find the size of the console.
 CONSOLE_SCREEN_BUFFER_INFO csbi;
                 //Here we will set the current color
 SetConsoleTextAttribute(hStdOut, wColor);
 if(GetConsoleScreenBufferInfo(hStdOut, &csbi))
 {
                          //This fills the buffer with a given character (in this case 32=space).
      FillConsoleOutputCharacter(hStdOut, (TCHAR) 32, csbi.dwSize.X * csbi.dwSize.Y, coord, &count);

      FillConsoleOutputAttribute(hStdOut, csbi.wAttributes, csbi.dwSize.X * csbi.dwSize.Y, coord, &count );
                          //This will set our cursor position for the next print statement.
      SetConsoleCursorPosition(hStdOut, coord);
 }
 return;
} 

In this case I have put the first number as zero and the second number as 15 so the console color will be white as the code for white is 15. This is working for me in code::blocks. Hope it works for you too.

How to run vbs as administrator from vbs?

Nice article for elevation options - http://www.novell.com/support/kb/doc.php?id=7010269

Configuring Applications to Always Request Elevated Rights:

Programs can be configured to always request elevation on the user level via registry settings under HKCU. These registry settings are effective on the fly, so they can be set immediately prior to launching a particular application and even removed as soon as the application is launched, if so desired. Simply create a "String Value" under "HKCU\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers" for the full path to an executable with a value of "RUN AS ADMIN". Below is an example for CMD.

Windows Registry Editor Version 5.00
[HKEY_Current_User\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers]
"c:\\windows\\system32\\cmd.exe"="RUNASADMIN"

Object of class DateTime could not be converted to string

Check to make sure there is a film release date; if the date is missing you will not be able to format on a non-object.

if ($info['Film_Release']){ //check if the date exists
   $dateFromDB = $info['Film_Release'];
   $newDate = DateTime::createFromFormat("l dS F Y", $dateFromDB);
   $newDate = $newDate->format('d/m/Y'); 
} else {
   $newDate = "none"; 
}

or

 $newDate = ($info['Film_Release']) ? DateTime::createFromFormat("l dS F Y", $info['Film_Release'])->format('d/m/Y'): "none" 

Your project contains error(s), please fix it before running it

Try changing your workspace. I am not sure this is the exact solution . I did face the same issue for sometime untill i changed my workspace.

Convert String value format of YYYYMMDDHHMMSS to C# DateTime

You have to use a custom parsing string. I also suggest to include the invariant culture to identify that this format does not relate to any culture. Plus, it will prevent a warning in some code analysis tools.

var date = DateTime.ParseExact(value, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);

Why I'm getting 'Non-static method should not be called statically' when invoking a method in a Eloquent model?

You defined your method as non-static and you are trying to invoke it as static. That said...

1.if you want to invoke a static method, you should use the :: and define your method as static.

// Defining a static method in a Foo class.
public static function getAll() { /* code */ }

// Invoking that static method
Foo::getAll();

2.otherwise, if you want to invoke an instance method you should instance your class, use ->.

// Defining a non-static method in a Foo class.
public function getAll() { /* code */ }

// Invoking that non-static method.
$foo = new Foo();
$foo->getAll();

Note: In Laravel, almost all Eloquent methods return an instance of your model, allowing you to chain methods as shown below:

$foos = Foo::all()->take(10)->get();

In that code we are statically calling the all method via Facade. After that, all other methods are being called as instance methods.

Java parsing XML document gives "Content not allowed in prolog." error

Please check the xml file whether it has any junk character like this ?.If exists,please use the following syntax to remove that.

String XString = writer.toString();
XString = XString.replaceAll("[^\\x20-\\x7e]", "");

How do I print the content of httprequest request?

In case someone also want to dump response like me. i avoided to dump response body. following code just dump the StatusCode and Headers.

static private String dumpResponse(HttpServletResponse resp){
    StringBuilder sb = new StringBuilder();

    sb.append("Response Status = [" + resp.getStatus() + "], ");
    String headers = resp.getHeaderNames().stream()
                    .map(headerName -> headerName + " : " + resp.getHeaders(headerName) )
                    .collect(Collectors.joining(", "));

    if (headers.isEmpty()) {
        sb.append("Response headers: NONE,");
    } else {
        sb.append("Response headers: "+headers+",");
    }

    return sb.toString();
}

Woocommerce, get current product id

Since WooCommerce 2.2 you are able to simply use the wc_get_product Method. As an argument you can pass the ID or simply leave it empty if you're already in the loop.

wc_get_product()->get_id();

OR with 2 lines

$product = wc_get_product();
$id = $product->get_id();

Android M - check runtime permission - how to determine if the user checked "Never ask again"?

The method shouldShowRequestPermissionRationale() can be used to check whether the user selected the 'never asked again' option and denied the permission. There's plenty of code examples, so I would rather explain how to use it for such a purpose, because I think its name and its implementation makes this more complicated that it actually is.

As explained in Requesting Permissions at Run Time, that method returns true if the option 'never ask again' is visible, false otherwise; so it returns false the very first time a dialog is shown, then from the second time on it returns true, and only if the user deny the permission selecting the option, at that point it returns false again.

To detect such a case, either you can detect the sequence false-true-false, or (more simple) you can have a flag which keeps track of the initial time the dialog is shown. After that, that method returns either true or false, where the false will allow you to detect when the option is selected.

How can I get a list of all open named pipes in Windows?

You can view these with Process Explorer from sysinternals. Use the "Find -> Find Handle or DLL..." option and enter the pattern "\Device\NamedPipe\". It will show you which processes have which pipes open.

Is it bad to have my virtualenv directory inside my git repository?

I use what is basically David Sickmiller's answer with a little more automation. I create a (non-executable) file at the top level of my project named activate with the following contents:

[ -n "$BASH_SOURCE" ] \
    || { echo 1>&2 "source (.) this with Bash."; exit 2; }
(
    cd "$(dirname "$BASH_SOURCE")"
    [ -d .build/virtualenv ] || {
        virtualenv .build/virtualenv
        . .build/virtualenv/bin/activate
        pip install -r requirements.txt
    }
)
. "$(dirname "$BASH_SOURCE")/.build/virtualenv/bin/activate"

(As per David's answer, this assumes you're doing a pip freeze > requirements.txt to keep your list of requirements up to date.)

The above gives the general idea; the actual activate script (documentation) that I normally use is a bit more sophisticated, offering a -q (quiet) option, using python when python3 isn't available, etc.

This can then be sourced from any current working directory and will properly activate, first setting up the virtual environment if necessary. My top-level test script usually has code along these lines so that it can be run without the developer having to activate first:

cd "$(dirname "$0")"
[[ $VIRTUAL_ENV = $(pwd -P) ]] || . ./activate

Sourcing ./activate, not activate, is important here because the latter will find any other activate in your path before it will find the one in the current directory.

How to convert FormData (HTML5 object) to JSON

If you have multiple entries with the same name, for example if you use <SELECT multiple> or have multiple <INPUT type="checkbox"> with the same name, you need to take care of that and make an array of the value. Otherwise you only get the last selected value.

Here is the modern ES6-variant:

function formToJSON( elem ) {
  let output = {};
  new FormData( elem ).forEach(
    ( value, key ) => {
      // Check if property already exist
      if ( Object.prototype.hasOwnProperty.call( output, key ) ) {
        let current = output[ key ];
        if ( !Array.isArray( current ) ) {
          // If it's not an array, convert it to an array.
          current = output[ key ] = [ current ];
        }
        current.push( value ); // Add the new value to the array.
      } else {
        output[ key ] = value;
      }
    }
  );
  return JSON.stringify( output );
}

Slightly older code (but still not supported by IE11, since it doesn't support ForEach or entries on FormData)

function formToJSON( elem ) {
  var current, entries, item, key, output, value;
  output = {};
  entries = new FormData( elem ).entries();
  // Iterate over values, and assign to item.
  while ( item = entries.next().value )
    {
      // assign to variables to make the code more readable.
      key = item[0];
      value = item[1];
      // Check if key already exist
      if (Object.prototype.hasOwnProperty.call( output, key)) {
        current = output[ key ];
        if ( !Array.isArray( current ) ) {
          // If it's not an array, convert it to an array.
          current = output[ key ] = [ current ];
        }
        current.push( value ); // Add the new value to the array.
      } else {
        output[ key ] = value;
      }
    }
    return JSON.stringify( output );
  }

Creating a DateTime in a specific Time Zone in c#

Jon's answer talks about TimeZone, but I'd suggest using TimeZoneInfo instead.

Personally I like keeping things in UTC where possible (at least for the past; storing UTC for the future has potential issues), so I'd suggest a structure like this:

public struct DateTimeWithZone
{
    private readonly DateTime utcDateTime;
    private readonly TimeZoneInfo timeZone;

    public DateTimeWithZone(DateTime dateTime, TimeZoneInfo timeZone)
    {
        var dateTimeUnspec = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified);
        utcDateTime = TimeZoneInfo.ConvertTimeToUtc(dateTimeUnspec, timeZone); 
        this.timeZone = timeZone;
    }

    public DateTime UniversalTime { get { return utcDateTime; } }

    public TimeZoneInfo TimeZone { get { return timeZone; } }

    public DateTime LocalTime
    { 
        get 
        { 
            return TimeZoneInfo.ConvertTime(utcDateTime, timeZone); 
        }
    }        
}

You may wish to change the "TimeZone" names to "TimeZoneInfo" to make things clearer - I prefer the briefer names myself.

Creating an Array from a Range in VBA

Using Value2 gives a performance benefit. As per Charles Williams blog

Range.Value2 works the same way as Range.Value, except that it does not check the cell format and convert to Date or Currency. And thats probably why its faster than .Value when retrieving numbers.

So

DirArray = [a1:a5].Value2

Bonus Reading

  • Range.Value: Returns or sets a Variant value that represents the value of the specified range.
  • Range.Value2: The only difference between this property and the Value property is that the Value2 property doesn't use the Currency and Date data types.

Get environment value in controller

It's a better idea to put your configuration variables in a configuration file.

In your case, I would suggest putting your variables in config/mail.php like:

'imap_hostname' => env('IMAP_HOSTNAME_TEST', 'imap.gmail.com')

And refer to them by

config('mail.imap_hostname')

It first tries to get the configuration variable value in the .env file and if it couldn't find the variable value in the .env file, it will get the variable value from file config/mail.php.

Terminating a Java Program

  1. System.exit() is a method that causes JVM to exit.
  2. return just returns the control to calling function.
  3. return 8 will return control and value 8 to calling method.

You are trying to add a non-nullable field 'new_field' to userprofile without a default

In case anyone is setting a ForeignKey, you can just allow nullable fields without setting a default:

new_field = models.ForeignKey(model, null=True)

If you already have data stored within the database, you can also set a default value:

new_field = models.ForeignKey(model, default=<existing model id here>)

How to use Java property files?

There are many ways to create and read properties files:

  1. Store the file in the same package.
  2. Recommend .properties extension however you can choose your own.
  3. Use theses classes located at java.util package => Properties, ListResourceBundle, ResourceBundle classes.
  4. To read properties, use iterator or enumerator or direct methods of Properties or java.lang.System class.

ResourceBundle class:

 ResourceBundle rb = ResourceBundle.getBundle("prop"); // prop.properties
 System.out.println(rb.getString("key"));

Properties class:

Properties ps = new Properties();
ps.Load(new java.io.FileInputStream("my.properties"));

What does hash do in python?

The Python docs for hash() state:

Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup.

Python dictionaries are implemented as hash tables. So any time you use a dictionary, hash() is called on the keys that you pass in for assignment, or look-up.

Additionally, the docs for the dict type state:

Values that are not hashable, that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys.

byte array to pdf

Usually this happens if something is wrong with the byte array.

File.WriteAllBytes("filename.PDF", Byte[]);

This creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.

Asynchronous implementation of this is also available.

public static System.Threading.Tasks.Task WriteAllBytesAsync 
(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = null);

Child with max-height: 100% overflows parent

Containers will already generally wrap their content nicely. It often doesn't work as well the other way around: children don't fill their ancestors nicely. So, set your width/height values on the inner-most element rather than the outer-most element, and let the outer elements wrap their contents.

.container {
    background: blue;
    padding: 10px;
}

img {
    display: block;
    max-height: 200px;
    max-width: 200px;
}

Remove "Using default security password" on Spring Boot

If you are declaring your configs in a separate package, make sure you add component scan like this :

@SpringBootApplication
@ComponentScan("com.mycompany.MY_OTHER_PACKAGE.account.config")

    public class MyApplication {

        public static void main(String[] args) {
            SpringApplication.run(MyApplication.class, args);
        }



    }

You may also need to add @component annotation in the config class like so :

  @Component
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()

.....
  1. Also clear browser cache and run spring boot app in incognito mode

ToggleClass animate jQuery?

You can simply use CSS transitions, see this fiddle

.on {
color:#fff;
transition:all 1s;
}

.off{
color:#000;
transition:all 1s;
}

Wireshark vs Firebug vs Fiddler - pros and cons?

I use both Charles Proxy and Fiddler for my HTTP/HTTPS level debugging.

Pros of Charles Proxy:

  1. Handles HTTPS better (you get a Charles Certificate which you'd put in 'Trusted Authorities' list)
  2. Has more features like Load/Save Session (esp. useful when debugging multiple pages), Mirror a website (useful in caching assets and hence faster debugging), etc.
  3. As mentioned by jburgess, handles AMF.
  4. Displays JSON, XML and other kind of responses in a tree structure, making it easier to read. Displays images in image responses instead of binary data.

Cons of Charles Proxy:

  1. Cost :-)

How can I check if an ip is in a network in Python?

This code is working for me on Linux x86. I haven't really given any thought to endianess issues, but I have tested it against the "ipaddr" module using over 200K IP addresses tested against 8 different network strings, and the results of ipaddr are the same as this code.

def addressInNetwork(ip, net):
   import socket,struct
   ipaddr = int(''.join([ '%02x' % int(x) for x in ip.split('.') ]), 16)
   netstr, bits = net.split('/')
   netaddr = int(''.join([ '%02x' % int(x) for x in netstr.split('.') ]), 16)
   mask = (0xffffffff << (32 - int(bits))) & 0xffffffff
   return (ipaddr & mask) == (netaddr & mask)

Example:

>>> print addressInNetwork('10.9.8.7', '10.9.1.0/16')
True
>>> print addressInNetwork('10.9.8.7', '10.9.1.0/24')
False

Reading a JSP variable from JavaScript

The cleanest way, as far as I know:

  1. add your JSP variable to an HTML element's data-* attribute
  2. then read this value via Javascript when required

My opinion regarding the current solutions on this SO page: reading "directly" JSP values using java scriplet inside actual javascript code is probably the most disgusting thing you could do. Makes me wanna puke. haha. Seriously, try to not do it.

The HTML part without JSP:

<body data-customvalueone="1st Interpreted Jsp Value" data-customvaluetwo="another Interpreted Jsp Value">
    Here is your regular page main content
</body>

The HTML part when using JSP:

<body data-customvalueone="${beanName.attrName}" data-customvaluetwo="${beanName.scndAttrName}">
    Here is your regular page main content
</body>

The javascript part (using jQuery for simplicity):

<script type="text/JavaScript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script type="text/javascript">
    jQuery(function(){
        var valuePassedFromJSP = $("body").attr("data-customvalueone");
        var anotherValuePassedFromJSP = $("body").attr("data-customvaluetwo");

        alert(valuePassedFromJSP + " and " + anotherValuePassedFromJSP + " are the values passed from your JSP page");
});
</script>

And here is the jsFiddle to see this in action http://jsfiddle.net/6wEYw/2/

Resources:

How to set Spinner default value to null?

Merge this:

private long previousItemId = 0;

@Override
public long getItemId(int position) {
    long nextItemId = random.nextInt(Integer.MAX_VALUE);
    while(previousItemId == nextItemId) {
        nextItemId = random.nextInt(Integer.MAX_VALUE);
    }
    previousItemId = nextItemId;
    return nextItemId;
}

With this answer:

public class SpinnerInteractionListener
        implements AdapterView.OnItemSelectedListener, View.OnTouchListener {

    private AdapterView.OnItemSelectedListener onItemSelectedListener;

    public SpinnerInteractionListener(AdapterView.OnItemSelectedListener selectedListener) {
        this.onItemSelectedListener = selectedListener;
    }

    boolean userSelect = false;

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        userSelect = true;
        return false;
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        if(userSelect) {
            onItemSelectedListener.onItemSelected(parent, view, pos, id);
            userSelect = false;
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        if(userSelect) {
            onItemSelectedListener.onNothingSelected(parent);
            userSelect = false;
        }
    }
}

Gradle store on local file system

I just stumbled onto this while searching for this answer. If you are using intellij, you can navigate to the file location, but opening the external lib folder in the project explorer, right clicking on the jar, and select Open Library Settings. enter image description here

Parse (split) a string in C++ using string delimiter (standard C++)

std::vector<std::string> split(const std::string& s, char c) {
  std::vector<std::string> v;
  unsigned int ii = 0;
  unsigned int j = s.find(c);
  while (j < s.length()) {
    v.push_back(s.substr(i, j - i));
    i = ++j;
    j = s.find(c, j);
    if (j >= s.length()) {
      v.push_back(s.substr(i, s,length()));
      break;
    }
  }
  return v;
}

C++ Boost: undefined reference to boost::system::generic_category()

try

g++ -c main.cpp && g++ main.o /usr/lib/x86_64-linux-gnu/libboost_system.so && ./a.out 

/usr/lib/x86_64-linux-gnu/ is the location of the boost library

use find /usr/ -name '*boost*.so' to find the boost library location

What do the return values of Comparable.compareTo mean in Java?

I use this mnemonic :

a.compareTo(b) < 0 // a < b

a.compareTo(b) > 0 // a > b

a.compareTo(b) == 0 // a == b

You keep the signs and always compare the result of compareTo() to 0

Change the size of a JTextField inside a JBorderLayout

Try to play with

setMinSize()
setMaxSize()
setPreferredSize()

These method are used by layout when it decide what should be the size of current element. The layout manager calls setSize() and actually overrides your values.

Can't import org.apache.http.HttpResponse in Android Studio

Use This:-

compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'

Java Does Not Equal (!=) Not Working?

Sure, you can use equals if you want to go along with the crowd, but if you really want to amaze your fellow programmers check for inequality like this:

if ("success" != statusCheck.intern())

intern method is part of standard Java String API.

LINQ .Any VS .Exists - What's the difference?

As a continuation on Matas' answer on benchmarking.

TL/DR: Exists() and Any() are equally fast.

First off: Benchmarking using Stopwatch is not precise (see series0ne's answer on a different, but similiar, topic), but it is far more precise than DateTime.

The way to get really precise readings is by using Performance Profiling. But one way to get a sense of how the two methods' performance measure up to each other is by executing both methods loads of times and then comparing the fastest execution time of each. That way, it really doesn't matter that JITing and other noise gives us bad readings (and it does), because both executions are "equally misguiding" in a sense.

static void Main(string[] args)
    {
        Console.WriteLine("Generating list...");
        List<string> list = GenerateTestList(1000000);
        var s = string.Empty;

        Stopwatch sw;
        Stopwatch sw2;
        List<long> existsTimes = new List<long>();
        List<long> anyTimes = new List<long>();

        Console.WriteLine("Executing...");
        for (int j = 0; j < 1000; j++)
        {
            sw = Stopwatch.StartNew();
            if (!list.Exists(o => o == "0123456789012"))
            {
                sw.Stop();
                existsTimes.Add(sw.ElapsedTicks);
            }
        }

        for (int j = 0; j < 1000; j++)
        {
            sw2 = Stopwatch.StartNew();
            if (!list.Exists(o => o == "0123456789012"))
            {
                sw2.Stop();
                anyTimes.Add(sw2.ElapsedTicks);
            }
        }

        long existsFastest = existsTimes.Min();
        long anyFastest = anyTimes.Min();

        Console.WriteLine(string.Format("Fastest Exists() execution: {0} ticks\nFastest Any() execution: {1} ticks", existsFastest.ToString(), anyFastest.ToString()));
        Console.WriteLine("Benchmark finished. Press any key.");
        Console.ReadKey();
    }

    public static List<string> GenerateTestList(int count)
    {
        var list = new List<string>();
        for (int i = 0; i < count; i++)
        {
            Random r = new Random();
            int it = r.Next(0, 100);
            list.Add(new string('s', it));
        }
        return list;
    }

After executing the above code 4 times (which in turn do 1 000 Exists() and Any() on a list with 1 000 000 elements), it's not hard to see that the methods are pretty much equally fast.

Fastest Exists() execution: 57881 ticks
Fastest Any() execution: 58272 ticks

Fastest Exists() execution: 58133 ticks
Fastest Any() execution: 58063 ticks

Fastest Exists() execution: 58482 ticks
Fastest Any() execution: 58982 ticks

Fastest Exists() execution: 57121 ticks
Fastest Any() execution: 57317 ticks

There is a slight difference, but it's too small a difference to not be explained by background noise. My guess would be that if one would do 10 000 or 100 000 Exists() and Any() instead, that slight difference would disappear more or less.

Exposing a port on a live Docker container

Here are some solutions:

https://forums.docker.com/t/how-to-expose-port-on-running-container/3252/12

The solution to mapping port while running the container.

docker run -d --net=host myvnc

that will expose and map the port automatically to your host

What is the size of column of int(11) in mysql in bytes?

INT(x) will make difference only in term of display, that is to show the number in x digits, and not restricted to 11. You pair it using ZEROFILL, which will prepend the zeros until it matches your length.

So, for any number of x in INT(x)

  • if the stored value has less digits than x, ZEROFILL will prepend zeros.

INT(5) ZEROFILL with the stored value of 32 will show 00032
INT(5) with the stored value of 32 will show 32
INT with the stored value of 32 will show 32

  • if the stored value has more digits than x, it will be shown as it is.

INT(3) ZEROFILL with the stored value of 250000 will show 250000
INT(3) with the stored value of 250000 will show 250000
INT with the stored value of 250000 will show 250000

The actual value stored in database is not affected, the size is still the same, and any calculation will behave normally.

This also applies to BIGINT, MEDIUMINT, SMALLINT, and TINYINT.

How to multiply individual elements of a list with a number?

Here is a functional approach using map, itertools.repeat and operator.mul:

import operator
from itertools import repeat


def scalar_multiplication(vector, scalar):
    yield from map(operator.mul, vector, repeat(scalar))

Example of usage:

>>> v = [1, 2, 3, 4]
>>> c = 3
>>> list(scalar_multiplication(v, c))
[3, 6, 9, 12]

Java: Check the date format of current string is according to required format or not

Disclaimer

Parsing a string back to date/time value in an unknown format is inherently impossible (let's face it, what does 3/3/3 actually mean?!), all we can do is "best effort"

Important

This solution doesn't throw an Exception, it returns a boolean, this is by design. Any Exceptions are used purely as a guard mechanism.

2018

Since it's now 2018 and Java 8+ has the date/time API (and the rest have the ThreeTen backport). The solution remains basically the same, but becomes slightly more complicated, as we need to perform checks for:

  • date and time
  • date only
  • time only

This makes it look something like...

public static boolean isValidFormat(String format, String value, Locale locale) {
    LocalDateTime ldt = null;
    DateTimeFormatter fomatter = DateTimeFormatter.ofPattern(format, locale);

    try {
        ldt = LocalDateTime.parse(value, fomatter);
        String result = ldt.format(fomatter);
        return result.equals(value);
    } catch (DateTimeParseException e) {
        try {
            LocalDate ld = LocalDate.parse(value, fomatter);
            String result = ld.format(fomatter);
            return result.equals(value);
        } catch (DateTimeParseException exp) {
            try {
                LocalTime lt = LocalTime.parse(value, fomatter);
                String result = lt.format(fomatter);
                return result.equals(value);
            } catch (DateTimeParseException e2) {
                // Debugging purposes
                //e2.printStackTrace();
            }
        }
    }

    return false;
}

This makes the following...

System.out.println("isValid - dd/MM/yyyy with 20130925 = " + isValidFormat("dd/MM/yyyy", "20130925", Locale.ENGLISH));
System.out.println("isValid - dd/MM/yyyy with 25/09/2013 = " + isValidFormat("dd/MM/yyyy", "25/09/2013", Locale.ENGLISH));
System.out.println("isValid - dd/MM/yyyy with 25/09/2013 12:13:50 = " + isValidFormat("dd/MM/yyyy", "25/09/2013  12:13:50", Locale.ENGLISH));
System.out.println("isValid - yyyy-MM-dd with 2017-18--15 = " + isValidFormat("yyyy-MM-dd", "2017-18--15", Locale.ENGLISH));

output...

isValid - dd/MM/yyyy with 20130925 = false
isValid - dd/MM/yyyy with 25/09/2013 = true
isValid - dd/MM/yyyy with 25/09/2013 12:13:50 = false
isValid - yyyy-MM-dd with 2017-18--15 = false

Original Answer

Simple try and parse the String to the required Date using something like SimpleDateFormat

Date date = null;
try {
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    date = sdf.parse(value);
    if (!value.equals(sdf.format(date))) {
        date = null;
    }
} catch (ParseException ex) {
    ex.printStackTrace();
}
if (date == null) {
    // Invalid date format
} else {
    // Valid date format
}

You could then simply write a simple method that performed this action and returned true when ever Date was not null...

As a suggestion...

Updated with running example

I'm not sure what you are doing, but, the following example...

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TestDateParser {

    public static void main(String[] args) {
        System.out.println("isValid - dd/MM/yyyy with 20130925 = " + isValidFormat("dd/MM/yyyy", "20130925"));
        System.out.println("isValid - dd/MM/yyyy with 25/09/2013 = " + isValidFormat("dd/MM/yyyy", "25/09/2013"));
        System.out.println("isValid - dd/MM/yyyy with 25/09/2013 12:13:50 = " + isValidFormat("dd/MM/yyyy", "25/09/2013  12:13:50"));
    }

    public static boolean isValidFormat(String format, String value) {
        Date date = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            date = sdf.parse(value);
            if (!value.equals(sdf.format(date))) {
                date = null;
            }
        } catch (ParseException ex) {
            ex.printStackTrace();
        }
        return date != null;
    }

}

Outputs (something like)...

java.text.ParseException: Unparseable date: "20130925"
isValid - dd/MM/yyyy with 20130925 = false
isValid - dd/MM/yyyy with 25/09/2013 = true
isValid - dd/MM/yyyy with 25/09/2013 12:13:50 = false
    at java.text.DateFormat.parse(DateFormat.java:366)
    at javaapplication373.JavaApplication373.isValidFormat(JavaApplication373.java:28)
    at javaapplication373.JavaApplication373.main(JavaApplication373.java:19)

Not correct. For isValidFormat("yyyy-MM-dd", "2017-18--15"); not throw any Exception.

isValid - yyyy-MM-dd", "2017-18--15 = false

Seems to work as expected for me - the method doesn't rely on (nor does it throw) the exception alone to perform it's operation

*ngIf else if in template

you don't need to use *ngIf if you use ng-container

<ng-container [ngTemplateOutlet]="myTemplate === 'first' ? first : myTemplate === 
   'second' ? second : third"></ng-container>

  <ng-template #first>first</ng-template>
  <ng-template #second>second</ng-template>
  <ng-template #third>third</ng-template>

Way to go from recursion to iteration

A rough description of how a system takes any recursive function and executes it using a stack:

This intended to show the idea without details. Consider this function that would print out nodes of a graph:

function show(node)
0. if isleaf(node):
1.  print node.name
2. else:
3.  show(node.left)
4.  show(node)
5.  show(node.right)

For example graph: A->B A->C show(A) would print B, A, C

Function calls mean save the local state and the continuation point so you can come back, and then jump the the function you want to call.

For example, suppose show(A) begins to run. The function call on line 3. show(B) means - Add item to the stack meaning "you'll need to continue at line 2 with local variable state node=A" - Goto line 0 with node=B.

To execute code, the system runs through the instructions. When a function call is encountered, the system pushes information it needs to come back to where it was, runs the function code, and when the function completes, pops the information about where it needs to go to continue.

Comparing two byte arrays in .NET

User gil suggested unsafe code which spawned this solution:

// Copyright (c) 2008-2013 Hafthor Stefansson
// Distributed under the MIT/X11 software license
// Ref: http://www.opensource.org/licenses/mit-license.php.
static unsafe bool UnsafeCompare(byte[] a1, byte[] a2) {
  if(a1==a2) return true;
  if(a1==null || a2==null || a1.Length!=a2.Length)
    return false;
  fixed (byte* p1=a1, p2=a2) {
    byte* x1=p1, x2=p2;
    int l = a1.Length;
    for (int i=0; i < l/8; i++, x1+=8, x2+=8)
      if (*((long*)x1) != *((long*)x2)) return false;
    if ((l & 4)!=0) { if (*((int*)x1)!=*((int*)x2)) return false; x1+=4; x2+=4; }
    if ((l & 2)!=0) { if (*((short*)x1)!=*((short*)x2)) return false; x1+=2; x2+=2; }
    if ((l & 1)!=0) if (*((byte*)x1) != *((byte*)x2)) return false;
    return true;
  }
}

which does 64-bit based comparison for as much of the array as possible. This kind of counts on the fact that the arrays start qword aligned. It'll work if not qword aligned, just not as fast as if it were.

It performs about seven timers faster than the simple for loop. Using the J# library performed equivalently to the original for loop. Using .SequenceEqual runs around seven times slower; I think just because it is using IEnumerator.MoveNext. I imagine LINQ-based solutions being at least that slow or worse.

process.env.NODE_ENV is undefined

We ran into this problem when working with node on Windows.

Rather than requiring anyone who attempts to run the app to set these variables, we provided a fallback within the application.

var environment = process.env.NODE_ENV || 'development';

In a production environment, we would define it per the usual methods (SET/export).

How to know/change current directory in Python shell?

>>> import os
>>> os.system('cd c:\mydir')

In fact, os.system() can execute any command that windows command prompt can execute, not just change dir.

Installing TensorFlow on Windows (Python 3.6.x)

On 2/22/18, when I tried the official recommendation:

pip3 install --upgrade tensorflow

I got this error

Could not find a version that satisfies the requirement tensorflow

But instead using

pip install --upgrade tensorflow

installed it ok. (I ran it from the ps command prompt.)

I have 64-bit windows 10, 64-bit python 3.6.3, and pip3 version 9.0.1.

jQuery.getJSON - Access-Control-Allow-Origin Issue

You may well want to use JSON-P instead (see below). First a quick explanation.

The header you've mentioned is from the Cross Origin Resource Sharing standard. Beware that it is not supported by some browsers people actually use, and on other browsers (Microsoft's, sigh) it requires using a special object (XDomainRequest) rather than the standard XMLHttpRequest that jQuery uses. It also requires that you change server-side resources to explicitly allow the other origin (www.xxxx.com).

To get the JSON data you're requesting, you basically have three options:

  1. If possible, you can be maximally-compatible by correcting the location of the files you're loading so they have the same origin as the document you're loading them into. (I assume you must be loading them via Ajax, hence the Same Origin Policy issue showing up.)

  2. Use JSON-P, which isn't subject to the SOP. jQuery has built-in support for it in its ajax call (just set dataType to "jsonp" and jQuery will do all the client-side work). This requires server side changes, but not very big ones; basically whatever you have that's generating the JSON response just looks for a query string parameter called "callback" and wraps the JSON in JavaScript code that would call that function. E.g., if your current JSON response is:

    {"weather": "Dreary start but soon brightening into a fine summer day."}
    

    Your script would look for the "callback" query string parameter (let's say that the parameter's value is "jsop123") and wraps that JSON in the syntax for a JavaScript function call:

    jsonp123({"weather": "Dreary start but soon brightening into a fine summer day."});
    

    That's it. JSON-P is very broadly compatible (because it works via JavaScript script tags). JSON-P is only for GET, though, not POST (again because it works via script tags).

  3. Use CORS (the mechanism related to the header you quoted). Details in the specification linked above, but basically:

    A. The browser will send your server a "preflight" message using the OPTIONS HTTP verb (method). It will contain the various headers it would send with the GET or POST as well as the headers "Origin", "Access-Control-Request-Method" (e.g., GET or POST), and "Access-Control-Request-Headers" (the headers it wants to send).

    B. Your PHP decides, based on that information, whether the request is okay and if so responds with the "Access-Control-Allow-Origin", "Access-Control-Allow-Methods", and "Access-Control-Allow-Headers" headers with the values it will allow. You don't send any body (page) with that response.

    C. The browser will look at your response and see whether it's allowed to send you the actual GET or POST. If so, it will send that request, again with the "Origin" and various "Access-Control-Request-xyz" headers.

    D. Your PHP examines those headers again to make sure they're still okay, and if so responds to the request.

    In pseudo-code (I haven't done much PHP, so I'm not trying to do PHP syntax here):

    // Find out what the request is asking for
    corsOrigin = get_request_header("Origin")
    corsMethod = get_request_header("Access-Control-Request-Method")
    corsHeaders = get_request_header("Access-Control-Request-Headers")
    if corsOrigin is null or "null" {
        // Requests from a `file://` path seem to come through without an
        // origin or with "null" (literally) as the origin.
        // In my case, for testing, I wanted to allow those and so I output
        // "*", but you may want to go another way.
        corsOrigin = "*"
    }
    
    // Decide whether to accept that request with those headers
    // If so:
    
    // Respond with headers saying what's allowed (here we're just echoing what they
    // asked for, except we may be using "*" [all] instead of the actual origin for
    // the "Access-Control-Allow-Origin" one)
    set_response_header("Access-Control-Allow-Origin", corsOrigin)
    set_response_header("Access-Control-Allow-Methods", corsMethod)
    set_response_header("Access-Control-Allow-Headers", corsHeaders)
    if the HTTP request method is "OPTIONS" {
        // Done, no body in response to OPTIONS
        stop
    }
    // Process the GET or POST here; output the body of the response
    

    Again stressing that this is pseudo-code.

jQuery hasClass() - check for more than one class

How about:

element.is('.class1, .class2')

Get the date (a day before current time) in Bash

#!/bin/bash
OFFSET=1;
eval `date "+day=%d; month=%m; year=%Y"`
# Subtract offset from day, if it goes below one use 'cal'
# to determine the number of days in the previous month.
day=`expr $day - $OFFSET`
if [ $day -le 0 ] ;then
month=`expr $month - 1`
if [ $month -eq 0 ] ;then
year=`expr $year - 1`
month=12
fi
set `cal $month $year`
xday=${$#}
day=`expr $xday + $day`
fi
echo $year-$month-$day

How to randomize Excel rows

Here's a macro that allows you to shuffle selected cells in a column:

Option Explicit

Sub ShuffleSelectedCells()
  'Do nothing if selecting only one cell
  If Selection.Cells.Count = 1 Then Exit Sub
  'Save selected cells to array
  Dim CellData() As Variant
  CellData = Selection.Value
  'Shuffle the array
  ShuffleArrayInPlace CellData
  'Output array to spreadsheet
  Selection.Value = CellData
End Sub

Sub ShuffleArrayInPlace(InArray() As Variant)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' ShuffleArrayInPlace
' This shuffles InArray to random order, randomized in place.
' Source: http://www.cpearson.com/excel/ShuffleArray.aspx
' Modified by Tom Doan to work with Selection.Value two-dimensional arrays.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
  Dim J As Long, _
    N As Long, _
    Temp As Variant
  'Randomize
  For N = LBound(InArray) To UBound(InArray)
    J = CLng(((UBound(InArray) - N) * Rnd) + N)
    If J <> N Then
      Temp = InArray(N, 1)
      InArray(N, 1) = InArray(J, 1)
      InArray(J, 1) = Temp
    End If
  Next N
End Sub

You can read the comments to see what the macro is doing. Here's how to install the macro:

  1. Open the VBA editor (Alt + F11).
  2. Right-click on "ThisWorkbook" under your currently open spreadsheet (listed in parentheses after "VBAProject") and select Insert / Module.
  3. Paste the code above and save the spreadsheet.

Now you can assign the "ShuffleSelectedCells" macro to an icon or hotkey to quickly randomize your selected rows (keep in mind that you can only select one column of rows).

How do you delete a column by name in data.table?

For a data.table, assigning the column to NULL removes it:

DT[,c("col1", "col1", "col2", "col2")] <- NULL
^
|---- Notice the extra comma if DT is a data.table

... which is the equivalent of:

DT$col1 <- NULL
DT$col2 <- NULL
DT$col3 <- NULL
DT$col4 <- NULL

The equivalent for a data.frame is:

DF[c("col1", "col1", "col2", "col2")] <- NULL
      ^
      |---- Notice the missing comma if DF is a data.frame

Q. Why is there a comma in the version for data.table, and no comma in the version for data.frame?

A. As data.frames are stored as a list of columns, you can skip the comma. You could also add it in, however then you will need to assign them to a list of NULLs, DF[, c("col1", "col2", "col3")] <- list(NULL).

How to flush output of print function?

Running python -h, I see a command line option:

-u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x see man page for details on internal buffering relating to '-u'

Here is the relevant doc.

Android RecyclerView addition & removal of items

I have done something similar. In your MyAdapter:

public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
    public CardView mCardView;
    public TextView mTextViewTitle;
    public TextView mTextViewContent;
    public ImageView mImageViewContentPic;

    public ImageView imgViewRemoveIcon;
    public ViewHolder(View v) {
        super(v);
        mCardView = (CardView) v.findViewById(R.id.card_view);
        mTextViewTitle = (TextView) v.findViewById(R.id.item_title);
        mTextViewContent = (TextView) v.findViewById(R.id.item_content);
        mImageViewContentPic = (ImageView) v.findViewById(R.id.item_content_pic);
        //......
        imgViewRemoveIcon = (ImageView) v.findViewById(R.id.remove_icon);

        mTextViewContent.setOnClickListener(this);
        imgViewRemoveIcon.setOnClickListener(this);
        v.setOnClickListener(this);
        mTextViewContent.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                if (mItemClickListener != null) {
                    mItemClickListener.onItemClick(view, getPosition());
                }
                return false;
            }
        });
    }


    @Override
    public void onClick(View v) {
        //Log.d("View: ", v.toString());
        //Toast.makeText(v.getContext(), mTextViewTitle.getText() + " position = " + getPosition(), Toast.LENGTH_SHORT).show();
        if(v.equals(imgViewRemoveIcon)){
            removeAt(getPosition());
        }else if (mItemClickListener != null) {
            mItemClickListener.onItemClick(v, getPosition());
        }
    }
}

public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
    this.mItemClickListener = mItemClickListener;
}
public void removeAt(int position) {
    mDataset.remove(position);
    notifyItemRemoved(position);
    notifyItemRangeChanged(position, mDataSet.size());
}

Hope this helps.

Edit:

getPosition() is deprecated now, use getAdapterPosition() instead.

Easier way to create circle div than using an image?

You can use radius but it will not work on IE: border-radius: 5px 5px;.

Node.js Error: connect ECONNREFUSED

People run into this error when the Node.js process is still running and they are attempting to start the server again. Try this:

ps aux | grep node

This will print something along the lines of:

user    7668  4.3  1.0  42060 10708 pts/1    Sl+  20:36   0:00 node server
user    7749  0.0  0.0   4384   832 pts/8    S+   20:37   0:00 grep --color=auto node

In this case, the process will be the one with the pid 7668. To kill it and restart the server, run kill -9 7668.

Returning value from called function in a shell script

You are working way too hard. Your entire script should be:

if mkdir "$lockdir" 2> /dev/null; then 
  echo lock acquired
else
  echo could not acquire lock >&2
fi

but even that is probably too verbose. I would code it:

mkdir "$lockdir" || exit 1

but the resulting error message is a bit obscure.

CSS Circular Cropping of Rectangle Image

insert the image and then backhand all you need is:

<style>
img {
  border-radius: 50%;
}
</style>

** the image code will be here automatically**

How to create dynamic href in react render function?

Use string concatenation:

href={'/posts/' + post.id}

The JSX syntax allows either to use strings or expressions ({...}) as values. You cannot mix both. Inside an expression you can, as the name suggests, use any JavaScript expression to compute the value.

How do I set the colour of a label (coloured text) in Java?

For single color foreground color

label.setForeground(Color.RED)

For multiple foreground colors in the same label:

(I would probably put two labels next to each other using a GridLayout or something, but here goes...)

You could use html in your label text as follows:

frame.add(new JLabel("<html>Text color: <font color='red'>red</font></html>"));

which produces:

enter image description here

Set an environment variable in git bash

A normal variable is set by simply assigning it a value; note that no whitespace is allowed around the =:

HOME=c

An environment variable is a regular variable that has been marked for export to the environment.

export HOME
HOME=c

You can combine the assignment with the export statement.

export HOME=c

Determine if 2 lists have the same elements, regardless of order?

As mentioned in comments above, the general case is a pain. It is fairly easy if all items are hashable or all items are sortable. However I have recently had to try solve the general case. Here is my solution. I realised after posting that this is a duplicate to a solution above that I missed on the first pass. Anyway, if you use slices rather than list.remove() you can compare immutable sequences.

def sequences_contain_same_items(a, b):
    for item in a:
        try:
            i = b.index(item)
        except ValueError:
            return False
        b = b[:i] + b[i+1:]
    return not b

Assign width to half available screen width declaratively

If your widget is a Button:

<LinearLayout android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:weightSum="2"
    android:orientation="horizontal">
    <Button android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="somebutton"/>

    <TextView android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
</LinearLayout>

I'm assuming you want your widget to take up one half, and another widget to take up the other half. The trick is using a LinearLayout, setting layout_width="fill_parent" on both widgets, and setting layout_weight to the same value on both widgets as well. If there are two widgets, both with the same weight, the LinearLayout will split the width between the two widgets.

Using Html.ActionLink to call action on different controller

With that parameters you're triggering the wrong overloaded function/method.

What worked for me:

<%= Html.ActionLink("Details", "Details", "Product", new { id=item.ID }, null) %>

It fires HtmlHelper.ActionLink(string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes)

I'm using MVC 4.

Cheerio!

WCF vs ASP.NET Web API

The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).

WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.


For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:

enter image description here


ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.

Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.


In the scenarios listed below you should go for WCF:

  1. If you need to send data on protocols like TCP, MSMQ or MIME
  2. If the consuming client just knows how to consume SOAP messages

WEB API is a framework for developing RESTful/HTTP services.

There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.

HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.

Creating a left-arrow button (like UINavigationBar's "back" style) on a UIToolbar

Here's what I ended up doing after searching through all these solutions and others. It uses a stretchable png's extracted from the UIKit stock images. This way you can set the text to whatever you liek

// Generate the background images
UIImage *stretchableBackButton = [[UIImage imageNamed:@"UINavigationBarDefaultBack.png"] stretchableImageWithLeftCapWidth:14 topCapHeight:0];
UIImage *stretchableBackButtonPressed = [[UIImage imageNamed:@"UINavigationBarDefaultBackPressed.png"] stretchableImageWithLeftCapWidth:13 topCapHeight:0];
// Setup the UIButton
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
[backButton setBackgroundImage:stretchableBackButton forState:UIControlStateNormal];
[backButton setBackgroundImage:stretchableBackButtonPressed forState:UIControlStateSelected];
NSString *buttonTitle = NSLocalizedString(@"Back", @"Back");
[backButton setTitle:buttonTitle forState:UIControlStateNormal];
[backButton setTitle:buttonTitle forState:UIControlStateSelected];
backButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 2, 1); // Tweak the text position
NSInteger width = ([backButton.titleLabel.text sizeWithFont:backButton.titleLabel.font].width + backButton.titleEdgeInsets.right +backButton.titleEdgeInsets.left);
[backButton setFrame:CGRectMake(0, 0, width, 29)];
backButton.titleLabel.font = [UIFont boldSystemFontOfSize:13.0f];
[backButton addTarget:self action:@selector(yourSelector:) forControlEvents:UIControlEventTouchDown];
// Now add the button as a custom UIBarButtonItem
UIBarButtonItem *backButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:backButton] autorelease];
self.navigationItem.leftBarButtonItem = backButtonItem;

How to import/include a CSS file using PHP code and not HTML code?

You could do this

<?php include("Includes/styles.inc"); ?>

And then in this include file, have a link to the your css file(s).

Align inline-block DIVs to top of container element

<style type="text/css">
        div {
  text-align: center;
         }

         .img1{
            width: 150px;
            height: 150px;
            border-radius: 50%;
         }

         span{
            display: block;
         }
    </style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type='password' class='secondInput mt-4 mr-1' placeholder="Password">
  <span class='dif'></span>
  <br>
  <button>ADD</button>
</div>

<script type="text/javascript">

$('button').click(function() {
  $('.dif').html("<img/>");

})

What is a correct MIME type for .docx, .pptx, etc.?

Alternatively, if you're working in .NET v4.5 or above, try using System.Web.MimeMapping.GetMimeMapping(yourFileName) to get MIME types. It is much better than hard-coding strings.

How do I handle newlines in JSON?

As I understand you question, it is not about parsing JSON because you can copy-paste your JSON into your code directly - so if this is the case then just copy your JSON direct to dataObj variable without wrapping it with single quotes (tip: eval==evil)

_x000D_
_x000D_
var dataObj = {"count" : 1, "stack" : "sometext\n\n"};_x000D_
_x000D_
console.log(dataObj);
_x000D_
_x000D_
_x000D_

Can't perform a React state update on an unmounted component

Inspired by @ford04 answer I use this hook, which also takes callbacks for success, errors, finally and an abortFn:

export const useAsync = (
        asyncFn, 
        onSuccess = false, 
        onError = false, 
        onFinally = false, 
        abortFn = false
    ) => {

    useEffect(() => {
        let isMounted = true;
        const run = async () => {
            try{
                let data = await asyncFn()
                if (isMounted && onSuccess) onSuccess(data)
            } catch(error) {
                if (isMounted && onError) onSuccess(error)
            } finally {
                if (isMounted && onFinally) onFinally()
            }
        }
        run()
        return () => {
            if(abortFn) abortFn()
            isMounted = false
        };
    }, [asyncFn, onSuccess])
}

If the asyncFn is doing some kind of fetch from back-end it often makes sense to abort it when the component is unmounted (not always though, sometimes if ie. you're loading some data into a store you might as well just want to finish it even if component is unmounted)

How to copy a char array in C?

None of the above was working for me.. this works perfectly name here is char *name which is passed via the function

  1. get length of char *name using strlen(name)
  2. storing it in a const variable is important
  3. create same length size char array
  4. copy name 's content to temp using strcpy(temp, name);

use however you want, if you want original content back. strcpy(name, temp); copy temp back to name and voila works perfectly

    const int size = strlen(name);
    char temp[size];
    cout << size << endl;
    strcpy(temp, name);

ASP.NET Button to redirect to another page

You can use PostBackUrl="~/Confirm.aspx"

For example:

In your .aspx file

<asp:Button ID="btnConfirm" runat="server" Text="Confirm" PostBackUrl="~/Confirm.aspx" />

or in your .cs file

btnConfirm.PostBackUrl="~/Confirm.aspx"

Disable browser's back button

I also had the same problem, use this Java script function on head tag or in , its 100% working fine, would not let you go back.

 <script type = "text/javascript" >
      function preventBack(){window.history.forward();}
        setTimeout("preventBack()", 0);
        window.onunload=function(){null};
    </script>

Why use a ReentrantLock if one can use synchronized(this)?

Lets assume this code is running in a thread:

private static ReentrantLock lock = new ReentrantLock();

void accessResource() {
    lock.lock();
    if( checkSomeCondition() ) {
        accessResource();
    }
    lock.unlock();
}

Because the thread owns the lock it will allow multiple calls to lock(), so it re-enter the lock. This can be achieved with a reference count so it doesn't has to acquire lock again.

Eclipse CDT: no rule to make target all

In C/C++ Build -> Builder Settings, select Internal builder (instead of External builder).

It works for me.

Is there a "standard" format for command line/shell help text?

The GNU Coding Standard is a good reference for things like this. This section deals with the output of --help. In this case it is not very specific. You probably can't go wrong with printing a table showing the short and long options and a succinct description. Try to get the spacing between all arguments right for readability. You probably want to provide a man page (and possibly an info manual) for your tool to provide a more elaborate explanation.

How to detect internet speed in JavaScript?

I needed something similar, so I wrote https://github.com/beradrian/jsbandwidth. This is a rewrite of https://code.google.com/p/jsbandwidth/.

The idea is to make two calls through Ajax, one to download and the other to upload through POST.

It should work with both jQuery.ajax or Angular $http.

Node.js console.log() not logging anything

This can be confusing for anyone using nodejs for the first time. It is actually possible to pipe your node console output to the browser console. Take a look at connect-browser-logger on github

UPDATE: As pointed out by Yan, connect-browser-logger appears to be defunct. I would recommend NodeMonkey as detailed here : Output to Chrome console from Node.js

Force SSL/https using .htaccess and mod_rewrite

This code works for me

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP:X-HTTPS} !1
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

Find out the history of SQL queries

For recent SQL:

select * from v$sql

For history:

select * from dba_hist_sqltext

How to list all AWS S3 objects in a bucket using Java

Try this one out

public void getObjectList(){
        System.out.println("Listing objects");
        ObjectListing objectListing = s3.listObjects(new ListObjectsRequest()
                .withBucketName(bucketName)
                .withPrefix("ads"));
        for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
            System.out.println(" - " + objectSummary.getKey() + "  " +
                               "(size = " + objectSummary.getSize() + ")");
        }
    }

You can all the objects within the bucket with specific prefix.

ImportError: No Module named simplejson

@noskio is correct... it just means that simplejson isn't found on your system and you need to install it for Python older than 2.6. one way is to use the setuptools easy_install tool. with it, you can install it as easily as: easy_install simplejson

UPDATE (Feb 2014): this is probably old news to many of you, but pip is a more modern tool that works in a similar way (i.e., pip install simplejson), only it can also uninstall apps.

MySql Table Insert if not exist otherwise update

Jai is correct that you should use INSERT ... ON DUPLICATE KEY UPDATE.

Note that you do not need to include datenum in the update clause since it's the unique key, so it should not change. You do need to include all of the other columns from your table. You can use the VALUES() function to make sure the proper values are used when updating the other columns.

Here is your update re-written using the proper INSERT ... ON DUPLICATE KEY UPDATE syntax for MySQL:

INSERT INTO AggregatedData (datenum,Timestamp)
VALUES ("734152.979166667","2010-01-14 23:30:00.000")
ON DUPLICATE KEY UPDATE 
  Timestamp=VALUES(Timestamp)

Oracle's default date format is YYYY-MM-DD, WHY?

It's never wise to rely on defaults being set to a particular value, IMHO, whether it's for date formats, currency formats, optimiser modes or whatever. You should always set the value of date format that you need, in the server, the client, or the application.

In particular, never rely on defaults when converting date or numeric data types for display purposes, because a single change to the database can break your application. Always use an explicit conversion format. For years I worked on Oracle systems where the out of the box default date display format was MM/DD/RR, which drove me nuts but at least forced me to always use an explicit conversion.

ASP.NET - How to write some html in the page? With Response.Write?

You should really use the Literal ASP.NET control for that.

How to refresh or show immediately in datagridview after inserting?

this.donorsTableAdapter.Fill(this.sbmsDataSet.donors);

Perform curl request in javascript?

curl is a command in linux (and a library in php). Curl typically makes an HTTP request.

What you really want to do is make an HTTP (or XHR) request from javascript.

Using this vocab you'll find a bunch of examples, for starters: Sending authorization headers with jquery and ajax

Essentially you will want to call $.ajax with a few options for the header, etc.

$.ajax({
        url: 'https://api.wit.ai/message?v=20140826&q=',
        beforeSend: function(xhr) {
             xhr.setRequestHeader("Authorization", "Bearer 6QXNMEMFHNY4FJ5ELNFMP5KRW52WFXN5")
        }, success: function(data){
            alert(data);
            //process the JSON data etc
        }
})

Conditionally displaying JSF components

Yes, use the rendered attribute.

<h:form rendered="#{some boolean condition}">

You usually tie it to the model rather than letting the model grab the component and manipulate it.

E.g.

<h:form rendered="#{bean.booleanValue}" />
<h:form rendered="#{bean.intValue gt 10}" />
<h:form rendered="#{bean.objectValue eq null}" />
<h:form rendered="#{bean.stringValue ne 'someValue'}" />
<h:form rendered="#{not empty bean.collectionValue}" />
<h:form rendered="#{not bean.booleanValue and bean.intValue ne 0}" />
<h:form rendered="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

Note the importance of keyword based EL operators such as gt, ge, le and lt instead of >, >=, <= and < as angle brackets < and > are reserved characters in XML. See also this related Q&A: Error parsing XHTML: The content of elements must consist of well-formed character data or markup.

As to your specific use case, let's assume that the link is passing a parameter like below:

<a href="page.xhtml?form=1">link</a>

You can then show the form as below:

<h:form rendered="#{param.form eq '1'}">

(the #{param} is an implicit EL object referring to a Map representing the request parameters)

See also:

PHP combine two associative arrays into one array

There is also array_replace, where an original array is modified by other arrays preserving the key => value association without creating duplicate keys.

  • Same keys on other arrays will cause values to overwrite the original array
  • New keys on other arrays will be created on the original array

jQuery: how to trigger anchor link's click event

There's a difference in invoking the click event (does not do the redirect), and navigating to the href location.

Navigate:

 window.location = $('#myanchor').attr('href');

Open in new tab or window:

 window.open($('#myanchor').attr('href'));

invoke click event (call the javascript):

 $('#myanchor').click();

Import error: No module name urllib2

Simplest of all solutions:

In Python 3.x:

import urllib.request
url = "https://api.github.com/users?since=100"
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
data_content = response.read()
print(data_content)

Get month name from Date

The natural format this days is to use Moment.js.

The way to get the month in a string format , is very simple in Moment.js no need to hard code the month names in your code: To get the current month and year in month name format and full year (May 2015) :

  moment(new Date).format("MMMM YYYY");

C# Collection was modified; enumeration operation may not execute

The problem is where you are executing:

rankings[kvp.Key] = rankings[kvp.Key] + 4;

You cannot modify the collection you are iterating through in a foreach loop. A foreach loop requires the loop to be immutable during iteration.

Instead, use a standard 'for' loop or create a new loop that is a copy and iterate through that while updating your original.

How do I upgrade PHP in Mac OS X?

You may want to check out Marc Liyanage's PHP package. It comes in a nice Mac OS X installer package that you can double-click. He keeps it pretty up to date.

http://php-osx.liip.ch/

Also, although upgrading to Snow Leopard won't help you do PHP updates in the future, it will probably give you a newer version of PHP. I'm running OS X 10.6.2 and it has PHP 5.3.0.

Are arrays passed by value or passed by reference in Java?

Arrays are in fact objects, so a reference is passed (the reference itself is passed by value, confused yet?). Quick example:

// assuming you allocated the list
public void addItem(Integer[] list, int item) {
    list[1] = item;
}

You will see the changes to the list from the calling code. However you can't change the reference itself, since it's passed by value:

// assuming you allocated the list
public void changeArray(Integer[] list) {
    list = null;
}

If you pass a non-null list, it won't be null by the time the method returns.

React.js: onChange event for contentEditable

Here is a component that incorporates much of this by lovasoa: https://github.com/lovasoa/react-contenteditable/blob/master/index.js

He shims the event in the emitChange

emitChange: function(evt){
    var html = this.getDOMNode().innerHTML;
    if (this.props.onChange && html !== this.lastHtml) {
        evt.target = { value: html };
        this.props.onChange(evt);
    }
    this.lastHtml = html;
}

I'm using a similar approach successfully

How to assign the output of a command to a Makefile variable

With GNU Make, you can use shell and eval to store, run, and assign output from arbitrary command line invocations. The difference between the example below and those which use := is the := assignment happens once (when it is encountered) and for all. Recursively expanded variables set with = are a bit more "lazy"; references to other variables remain until the variable itself is referenced, and the subsequent recursive expansion takes place each time the variable is referenced, which is desirable for making "consistent, callable, snippets". See the manual on setting variables for more info.

# Generate a random number.
# This is not run initially.
GENERATE_ID = $(shell od -vAn -N2 -tu2 < /dev/urandom)

# Generate a random number, and assign it to MY_ID
# This is not run initially.
SET_ID = $(eval MY_ID=$(GENERATE_ID))

# You can use .PHONY to tell make that we aren't building a target output file
.PHONY: mytarget
mytarget:
# This is empty when we begin
    @echo $(MY_ID)
# This recursively expands SET_ID, which calls the shell command and sets MY_ID
    $(SET_ID)
# This will now be a random number
    @echo $(MY_ID)
# Recursively expand SET_ID again, which calls the shell command (again) and sets MY_ID (again)
    $(SET_ID)
# This will now be a different random number
    @echo $(MY_ID)

SQLDataReader Row Count

SQLDataReaders are forward-only. You're essentially doing this:

count++;  // initially 1
.DataBind(); //consuming all the records

//next iteration on
.Read()
//we've now come to end of resultset, thanks to the DataBind()
//count is still 1 

You could do this instead:

if (reader.HasRows)
{
    rep.DataSource = reader;
    rep.DataBind();
}
int count = rep.Items.Count; //somehow count the num rows/items `rep` has.

How to trim whitespace from a Bash variable?

Use this simple Bash parameter expansion:

$ x=" a z     e r ty "
$ echo "START[${x// /}]END"
START[azerty]END

AngularJS - Any way for $http.post to send request parameters instead of JSON?

   .controller('pieChartController', ['$scope', '$http', '$httpParamSerializerJQLike', function($scope, $http, $httpParamSerializerJQLike) {
        var data = {
                TimeStamp : "2016-04-25 12:50:00"
        };
        $http({
            method: 'POST',
            url: 'serverutilizationreport',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            data: $httpParamSerializerJQLike(data),
        }).success(function () {});
    }
  ]);

How to Query an NTP Server using C#?

A modified version to compensate network times and calculate with DateTime-Ticks (more precise than milliseconds)

public static DateTime GetNetworkTime()
{
  const string NtpServer = "pool.ntp.org";

  const int DaysTo1900 = 1900 * 365 + 95; // 95 = offset for leap-years etc.
  const long TicksPerSecond = 10000000L;
  const long TicksPerDay = 24 * 60 * 60 * TicksPerSecond;
  const long TicksTo1900 = DaysTo1900 * TicksPerDay;

  var ntpData = new byte[48];
  ntpData[0] = 0x1B; // LeapIndicator = 0 (no warning), VersionNum = 3 (IPv4 only), Mode = 3 (Client Mode)

  var addresses = Dns.GetHostEntry(NtpServer).AddressList;
  var ipEndPoint = new IPEndPoint(addresses[0], 123);
  long pingDuration = Stopwatch.GetTimestamp(); // temp access (JIT-Compiler need some time at first call)
  using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
  {
    socket.Connect(ipEndPoint);
    socket.ReceiveTimeout = 5000;
    socket.Send(ntpData);
    pingDuration = Stopwatch.GetTimestamp(); // after Send-Method to reduce WinSocket API-Call time

    socket.Receive(ntpData);
    pingDuration = Stopwatch.GetTimestamp() - pingDuration;
  }

  long pingTicks = pingDuration * TicksPerSecond / Stopwatch.Frequency;

  // optional: display response-time
  // Console.WriteLine("{0:N2} ms", new TimeSpan(pingTicks).TotalMilliseconds);

  long intPart = (long)ntpData[40] << 24 | (long)ntpData[41] << 16 | (long)ntpData[42] << 8 | ntpData[43];
  long fractPart = (long)ntpData[44] << 24 | (long)ntpData[45] << 16 | (long)ntpData[46] << 8 | ntpData[47];
  long netTicks = intPart * TicksPerSecond + (fractPart * TicksPerSecond >> 32);

  var networkDateTime = new DateTime(TicksTo1900 + netTicks + pingTicks / 2);

  return networkDateTime.ToLocalTime(); // without ToLocalTime() = faster
}

How to build & install GLFW 3 and use it in a Linux project

2020 Updated Answer

It is 2020 (7 years later) and I have learned more about Linux during this time. Specifically that it might not be a good idea to run sudo make install when installing libraries, as these may interfere with the package management system. (In this case apt as I am using Debian 10.)

If this is not correct, please correct me in the comments.

Alternative proposed solution

This information is taken from the GLFW docs, however I have expanded/streamlined the information which is relevant to Linux users.

  • Go to home directory and clone glfw repository from github
cd ~
git clone https://github.com/glfw/glfw.git
cd glfw
  • You can at this point create a build directory and follow the instructions here (glfw build instructions), however I chose not to do that. The following command still seems to work in 2020 however it is not explicitly stated by the glfw online instructions.
cmake -G "Unix Makefiles"
  • You may need to run sudo apt-get build-dep glfw3 before (?). I ran both this command and sudo apt install xorg-dev as per the instructions.

  • Finally run make

  • Now in your project directory, do the following. (Go to your project which uses the glfw libs)

  • Create a CMakeLists.txt, mine looks like this

CMAKE_MINIMUM_REQUIRED(VERSION 3.7)
PROJECT(project)

SET(CMAKE_CXX_STANDARD 14)
SET(CMAKE_BUILD_TYPE DEBUG)

set(GLFW_BUILD_DOCS OFF CACHE BOOL "" FORCE)
set(GLFW_BUILD_TESTS OFF CACHE BOOL "" FORCE)
set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)

add_subdirectory(/home/<user>/glfw /home/<user>/glfw/src)


FIND_PACKAGE(OpenGL REQUIRED)

SET(SOURCE_FILES main.cpp)

ADD_EXECUTABLE(project ${SOURCE_FILES})
TARGET_LINK_LIBRARIES(project glfw)
TARGET_LINK_LIBRARIES(project OpenGL::GL)
  • If you don't like CMake then I appologize but in my opinion it is the easiest way to get your project working quickly. I would recommend learning to use it, at least to a basic level. Regretably I do not know of any good CMake tutorial

  • Then do cmake . and make, your project should be built and linked against glfw3 shared lib

  • There is some way of creating a dynamic linked lib. I believe I have used the static method here. Please comment / add a section in this answer below if you know more than I do

  • This should work on other systems, if not let me know and I will help if I am able to

What is SuppressWarnings ("unchecked") in Java?

The SuppressWarning annotation is used to suppress compiler warnings for the annotated element. Specifically, the unchecked category allows suppression of compiler warnings generated as a result of unchecked type casts.

Celery Received unregistered task of type (run example)

What worked for me, was to add explicit name to celery task decorator. I changed my task declaration from @app.tasks to @app.tasks(name='module.submodule.task')

Here is an example

# test_task.py
@celery.task
def test_task():
    print("Celery Task  !!!!")

# test_task.py
@celery.task(name='tasks.test.test_task')
def test_task():
    print("Celery Task  !!!!")

JWT (Json Web Token) Audience "aud" versus Client_Id - What's the difference?

If you came here searching OpenID Connect (OIDC): OAuth 2.0 != OIDC

I recognize that this is tagged for oauth 2.0 and NOT OIDC, however there is frequently a conflation between the 2 standards since both standards can use JWTs and the aud claim. And one (OIDC) is basically an extension of the other (OAUTH 2.0). (I stumbled across this question looking for OIDC myself.)

OAuth 2.0 Access Tokens##

For OAuth 2.0 Access tokens, existing answers pretty well cover it. Additionally here is one relevant section from OAuth 2.0 Framework (RFC 6749)

For public clients using implicit flows, this specification does not provide any method for the client to determine what client an access token was issued to.
...
Authenticating resource owners to clients is out of scope for this specification. Any specification that uses the authorization process as a form of delegated end-user authentication to the client (e.g., third-party sign-in service) MUST NOT use the implicit flow without additional security mechanisms that would enable the client to determine if the access token was issued for its use (e.g., audience- restricting the access token).

OIDC ID Tokens##

OIDC has ID Tokens in addition to Access tokens. The OIDC spec is explicit on the use of the aud claim in ID Tokens. (openid-connect-core-1.0)

aud
REQUIRED. Audience(s) that this ID Token is intended for. It MUST contain the OAuth 2.0 client_id of the Relying Party as an audience value. It MAY also contain identifiers for other audiences. In the general case, the aud value is an array of case sensitive strings. In the common special case when there is one audience, the aud value MAY be a single case sensitive string.

furthermore OIDC specifies the azp claim that is used in conjunction with aud when aud has more than one value.

azp
OPTIONAL. Authorized party - the party to which the ID Token was issued. If present, it MUST contain the OAuth 2.0 Client ID of this party. This Claim is only needed when the ID Token has a single audience value and that audience is different than the authorized party. It MAY be included even when the authorized party is the same as the sole audience. The azp value is a case sensitive string containing a StringOrURI value.

Eclipse JUnit - possible causes of seeing "initializationError" in Eclipse window

I had naively added junit-4.12.jar from poi.apache.org to my Build Path in Eclipse. I deleted it (Project, Properties, Java Build Path, Libraries, junit-4.12.jar, Remove) then in my test class allowed Eclipse to "Fix Project Setup" after pressing Ctrl-1. No more problems! :-)

How to select last two characters of a string

If it's an integer you need a part of....

var result = number.toString().slice(-2);

Compiling a C++ program with gcc

gcc can actually compile c++ code just fine. The errors you received are linker errors, not compiler errors.

Odds are that if you change the compilation line to be this:

gcc info.C -lstdc++

which makes it link to the standard c++ library, then it will work just fine.

However, you should just make your life easier and use g++.


EDIT:

Rup says it best in his comment to another answer:

[...] gcc will select the correct back-end compiler based on file extension (i.e. will compile a .c as C and a .cc as C++) and links binaries against just the standard C and GCC helper libraries by default regardless of input languages; g++ will also select the correct back-end based on extension except that I think it compiles all C source as C++ instead (i.e. it compiles both .c and .cc as C++) and it includes libstdc++ in its link step regardless of input languages.

Sum all values in every column of a data.frame in R

We can use dplyr to select only numeric columns and purr to get sum for all columns. (can be used to get what ever value for all columns, such as mean, min, max, etc. )

library("dplyr")
library("purrr")

people %>%
    select_if(is.numeric) %>%
    map_dbl(sum)

Or another easy way by only using dplyr

library("dplyr")
people %>%
    summarize_if(is.numeric, sum, na.rm=TRUE)

Multiple GitHub Accounts & SSH Config

I recently had to do this and had to sift through all these answers and their comments to eventually piece the information together, so I'll put it all here, in one post, for your convenience:


Step 1: ssh keys
Create any keypairs you'll need. In this example I've named me default/original 'id_rsa' (which is the default) and my new one 'id_rsa-work':

ssh-keygen -t rsa -C "[email protected]"


Step 2: ssh config
Set up multiple ssh profiles by creating/modifying ~/.ssh/config. Note the slightly differing 'Host' values:

# Default GitHub
Host github.com
    HostName github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa

# Work GitHub
Host work.github.com
    HostName github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa_work


Step 3: ssh-add
You may or may not have to do this. To check, list identity fingerprints by running:

$ ssh-add -l
2048 1f:1a:b8:69:cd:e3:ee:68:e1:c4:da:d8:96:7c:d0:6f stefano (RSA)
2048 6d:65:b9:3b:ff:9c:5a:54:1c:2f:6a:f7:44:03:84:3f [email protected] (RSA)

If your entries aren't there then run:

ssh-add ~/.ssh/id_rsa_work


Step 4: test
To test you've done this all correctly, I suggest the following quick check:

$ ssh -T [email protected]
Hi stefano! You've successfully authenticated, but GitHub does not provide shell access.

$ ssh -T [email protected]
Hi stefano! You've successfully authenticated, but GitHub does not provide shell access.

Note that you'll have to change the hostname (github / work.github) depending on what key/identity you'd like to use. But now you should be good to go! :)

How to create a .NET DateTime from ISO 8601 format

This solution makes use of the DateTimeStyles enumeration, and it also works with Z.

DateTime d2 = DateTime.Parse("2010-08-20T15:00:00Z", null, System.Globalization.DateTimeStyles.RoundtripKind);

This prints the solution perfectly.

Programmatically register a broadcast receiver

It sounds like you want to control whether components published in your manifest are active, not dynamically register a receiver (via Context.registerReceiver()) while running.

If so, you can use PackageManager.setComponentEnabledSetting() to control whether these components are active:

http://developer.android.com/reference/android/content/pm/PackageManager.html#setComponentEnabledSetting(android.content.ComponentName, int, int)

Note if you are only interested in receiving a broadcast while you are running, it is better to use registerReceiver(). A receiver component is primarily useful for when you need to make sure your app is launched every time the broadcast is sent.

AttributeError("'str' object has no attribute 'read'")

Ok, this is an old thread but. I had a same issue, my problem was I used json.load instead of json.loads

This way, json has no problem with loading any kind of dictionary.

Official documentation

json.load - Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to a Python object using this conversion table.

json.loads - Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table.

jQuery - on change input text

Seems to me like you are updating the value of the text field in javascript. onchange event will be triggered only when you key-in data and tab out of the text field.

One workaround is to trigger the textbox change event when modifying the textbox value from the script. See below,

$("#kat").change(function(){ 
    alert("Hello");
});


$('<tab_cell>').click (function () {
   $('#kat')
      .val($(this).text()) //updating the value of the textbox 
      .change();           //trigger change event.
});

Rails: Adding an index after adding column

You can use this, just think Job is the name of the model to which you are adding index cader_id:

class AddCaderIdToJob < ActiveRecord::Migration[5.2]
  def change
    change_table :jobs do |t|
      t.integer :cader_id
      t.index :cader_id
    end
  end
end

How can I clear an HTML file input with JavaScript?

I tried most of solutions but did not seem anyone to work. However I found a walk around for it below.

The structure of the form is: form => label, input and submit button. After we choose a file, the filename will be shown by the label by doing so manually in JavaScript.

So my strategy is: initially the submit button is disabled, after a file is chosen, the submit button disabled attribute will be removed such that I can submit file. After I submit, I clear the label which makes it look like I clear the file input but actually not. Then I will disable the submit button again to prevent from submitting the form.

By setting the submit button disable or not, I stop the file from submitted many times unless I choose another file.

"Cannot send session cache limiter - headers already sent"

"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.

Check that you don't send ANY content before calling session_start. Better yet, just make session_start the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).

PHP CURL CURLOPT_SSL_VERIFYPEER ignored

According to documentation: to verify host or peer certificate you need to specify alternate certificates with the CURLOPT_CAINFO option or a certificate directory can be specified with the CURLOPT_CAPATH option.

Also look at CURLOPT_SSL_VERIFYHOST:

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

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

How to find patterns across multiple lines using grep?

The filepattern *.sh is important to prevent directories to be inspected. Of course some test could prevent that too.

for f in *.sh
do
  a=$( grep -n -m1 abc $f )
  test -n "${a}" && z=$( grep -n efg $f | tail -n 1) || continue 
  (( ((${z/:*/}-${a/:*/})) > 0 )) && echo $f
done

The

grep -n -m1 abc $f 

searches maximum 1 matching and returns (-n) the linenumber. If a match was found (test -n ...) find the last match of efg (find all and take the last with tail -n 1).

z=$( grep -n efg $f | tail -n 1)

else continue.

Since the result is something like 18:foofile.sh String alf="abc"; we need to cut away from ":" till end of line.

((${z/:*/}-${a/:*/}))

Should return a positive result if the last match of the 2nd expression is past the first match of the first.

Then we report the filename echo $f.

Which is the preferred way to concatenate a string in Python?

As @jdi mentions Python documentation suggests to use str.join or io.StringIO for string concatenation. And says that a developer should expect quadratic time from += in a loop, even though there's an optimisation since Python 2.4. As this answer says:

If Python detects that the left argument has no other references, it calls realloc to attempt to avoid a copy by resizing the string in place. This is not something you should ever rely on, because it's an implementation detail and because if realloc ends up needing to move the string frequently, performance degrades to O(n^2) anyway.

I will show an example of real-world code that naively relied on += this optimisation, but it didn't apply. The code below converts an iterable of short strings into bigger chunks to be used in a bulk API.

def test_concat_chunk(seq, split_by):
    result = ['']
    for item in seq:
        if len(result[-1]) + len(item) > split_by: 
            result.append('')
        result[-1] += item
    return result

This code can literary run for hours because of quadratic time complexity. Below are alternatives with suggested data structures:

import io

def test_stringio_chunk(seq, split_by):
    def chunk():
        buf = io.StringIO()
        size = 0
        for item in seq:
            if size + len(item) <= split_by:
                size += buf.write(item)
            else:
                yield buf.getvalue()
                buf = io.StringIO()
                size = buf.write(item)
        if size:
            yield buf.getvalue()

    return list(chunk())

def test_join_chunk(seq, split_by):
    def chunk():
        buf = []
        size = 0
        for item in seq:
            if size + len(item) <= split_by:
                buf.append(item)
                size += len(item)
            else:
                yield ''.join(buf)                
                buf.clear()
                buf.append(item)
                size = len(item)
        if size:
            yield ''.join(buf)

    return list(chunk())

And a micro-benchmark:

import timeit
import random
import string
import matplotlib.pyplot as plt

line = ''.join(random.choices(
    string.ascii_uppercase + string.digits, k=512)) + '\n'
x = []
y_concat = []
y_stringio = []
y_join = []
n = 5
for i in range(1, 11):
    x.append(i)
    seq = [line] * (20 * 2 ** 20 // len(line))
    chunk_size = i * 2 ** 20
    y_concat.append(
        timeit.timeit(lambda: test_concat_chunk(seq, chunk_size), number=n) / n)
    y_stringio.append(
        timeit.timeit(lambda: test_stringio_chunk(seq, chunk_size), number=n) / n)
    y_join.append(
        timeit.timeit(lambda: test_join_chunk(seq, chunk_size), number=n) / n)
plt.plot(x, y_concat)
plt.plot(x, y_stringio)
plt.plot(x, y_join)
plt.legend(['concat', 'stringio', 'join'], loc='upper left')
plt.show()

micro-benchmark

What exactly does a jar file contain?

Just check if the aopalliance.jar file has .java files instead of .class files. if so, just extract the jar file, import it in eclipse & create a jar though eclipse. It worked for me.

ggplot2, change title size

+ theme(plot.title = element_text(size=22))

Here is the full set of things you can change in element_text:

element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
  hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
  color = NULL)

If/else else if in Jquery for a condition

See this answer. val() is comparing a string, not a numeric value.

What's the difference between SHA and AES encryption?

SHA doesn't require anything but an input to be applied, while AES requires at least 3 things - what you're encrypting/decrypting, an encryption key, and the initialization vector.

Number to String in a formula field

CSTR({number_field}, 0, '')

The second placeholder is for decimals.

The last placeholder is for thousands separator.

Can a java file have more than one class?

There can only be one public class top level class in a file. The class name of that public class should be the name of the file. It can have many public inner classes.

You can have many classes in a single file. The limits for various levels of class visibility in a file are as follows:

Top level classes:
1 public class
0 private class
any number of default/protected classes

Inner classes:
any number of inner classes with any visibility (default, private, protected, public)

Please correct me if I am wrong.

Run an exe from C# code

using System.Diagnostics;

class Program
{
    static void Main()
    {
        Process.Start("C:\\");
    }
}

If your application needs cmd arguments, use something like this:

using System.Diagnostics;

class Program
{
    static void Main()
    {
        LaunchCommandLineApp();
    }

    /// <summary>
    /// Launch the application with some options set.
    /// </summary>
    static void LaunchCommandLineApp()
    {
        // For the example
        const string ex1 = "C:\\";
        const string ex2 = "C:\\Dir";

        // Use ProcessStartInfo class
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.CreateNoWindow = false;
        startInfo.UseShellExecute = false;
        startInfo.FileName = "dcm2jpg.exe";
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.Arguments = "-f j -o \"" + ex1 + "\" -z 1.0 -s y " + ex2;

        try
        {
            // Start the process with the info we specified.
            // Call WaitForExit and then the using statement will close.
            using (Process exeProcess = Process.Start(startInfo))
            {
                exeProcess.WaitForExit();
            }
        }
        catch
        {
             // Log error.
        }
    }
}

The conversion of the varchar value overflowed an int column

Just make rdg2.nPhoneNumber varchar everywhere instead of int !

unique combinations of values in selected columns in pandas data frame and count

Slightly related, I was looking for the unique combinations and I came up with this method:

def unique_columns(df,columns):

    result = pd.Series(index = df.index)

    groups = meta_data_csv.groupby(by = columns)
    for name,group in groups:
       is_unique = len(group) == 1
       result.loc[group.index] = is_unique

    assert not result.isnull().any()

    return result

And if you only want to assert that all combinations are unique:

df1.set_index(['A','B']).index.is_unique

How to check cordova android version of a cordova/phonegap project?

just type cordova platform ls

This will list all the platforms installed along with its version and available for installation plus :)

How to enable DataGridView sorting when user clicks on the column header?

put this line in your windows form (on load or better in a public method like "binddata" ):

//
// bind the data and make the grid sortable 
//
this.datagridview1.MakeSortable( myenumerablecollection ); 

Put this code in a file called DataGridViewExtensions.cs (or similar)

// MakeSortable extension. 
// this will make any enumerable collection sortable on a datagrid view.  

//
// BEGIN MAKESORTABLE - Mark A. Lloyd
//
// Enables sort on all cols of a DatagridView 

//



    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using System.Windows.Forms;

    public static class DataGridViewExtensions
    {
    public static void MakeSortable<T>(
        this DataGridView dataGridView, 
        IEnumerable<T> dataSource,
        SortOrder defaultSort = SortOrder.Ascending, 
        SortOrder initialSort = SortOrder.None)
    {
        var sortProviderDictionary = new Dictionary<int, Func<SortOrder, IEnumerable<T>>>();
        var previousSortOrderDictionary = new Dictionary<int, SortOrder>();
        var itemType = typeof(T);
        dataGridView.DataSource = dataSource;
        foreach (DataGridViewColumn c in dataGridView.Columns)
        {
            object Provider(T info) => itemType.GetProperty(c.Name)?.GetValue(info);
            sortProviderDictionary[c.Index] = so => so != defaultSort ? 
                dataSource.OrderByDescending<T, object>(Provider) : 
                dataSource.OrderBy<T,object>(Provider);
            previousSortOrderDictionary[c.Index] = initialSort;
        }

        async Task DoSort(int index)
        {

            switch (previousSortOrderDictionary[index])
            {
                case SortOrder.Ascending:
                    previousSortOrderDictionary[index] = SortOrder.Descending;
                    break;
                case SortOrder.None:
                case SortOrder.Descending:
                    previousSortOrderDictionary[index] = SortOrder.Ascending;
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            IEnumerable<T> sorted = null;
            dataGridView.Cursor = Cursors.WaitCursor;
            dataGridView.Enabled = false;
            await Task.Run(() => sorted = sortProviderDictionary[index](previousSortOrderDictionary[index]).ToList());
            dataGridView.DataSource = sorted;
            dataGridView.Enabled = true;
            dataGridView.Cursor = Cursors.Default;

        }

        dataGridView.ColumnHeaderMouseClick+= (object sender, DataGridViewCellMouseEventArgs e) => DoSort(index: e.ColumnIndex);
    }
}

difference between css height : 100% vs height : auto

height:100% works if the parent container has a specified height property else, it won't work

How to change a string into uppercase

>>> s = 'sdsd'
>>> s.upper()
'SDSD'

See String Methods.

regex to match a single character that is anything but a space

The following should suffice:

[^ ]

If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):

[^\s]

or

\S  # Note this is a CAPITAL 'S'!

Multiple REPLACE function in Oracle

I have created a general multi replace string Oracle function by a table of varchar2 as parameter. The varchar will be replaced for the position rownum value of table.

For example:

Text: Hello {0}, this is a {2} for {1}
Parameters: TABLE('world','all','message')

Returns:

Hello world, this is a message for all.

You must create a type:

CREATE OR REPLACE TYPE "TBL_VARCHAR2" IS TABLE OF VARCHAR2(250);

The funcion is:

CREATE OR REPLACE FUNCTION FN_REPLACETEXT(
    pText IN VARCHAR2, 
    pPar IN TBL_VARCHAR2
) RETURN VARCHAR2
IS
    vText VARCHAR2(32767);
    vPos INT;
    vValue VARCHAR2(250);

    CURSOR cuParameter(POS INT) IS
    SELECT VAL
        FROM
            (
            SELECT VAL, ROWNUM AS RN 
            FROM (
                  SELECT COLUMN_VALUE VAL
                  FROM TABLE(pPar)
                  )
            )
        WHERE RN=POS+1;
BEGIN
    vText := pText;
    FOR i IN 1..REGEXP_COUNT(pText, '[{][0-9]+[}]') LOOP
        vPos := TO_NUMBER(SUBSTR(REGEXP_SUBSTR(pText, '[{][0-9]+[}]',1,i),2, LENGTH(REGEXP_SUBSTR(pText, '[{][0-9]+[}]',1,i)) - 2));

        OPEN cuParameter(vPos);
        FETCH cuParameter INTO vValue;
        IF cuParameter%FOUND THEN
            vText := REPLACE(vText, REGEXP_SUBSTR(pText, '[{][0-9]+[}]',1,i), vValue);
        END IF;
        CLOSE cuParameter;
    END LOOP;

    RETURN vText;

EXCEPTION
      WHEN OTHERS
      THEN
         RETURN pText;
END FN_REPLACETEXT;
/

Usage:

TEXT_RETURNED := FN_REPLACETEXT('Hello {0}, this is a {2} for {1}', TBL_VARCHAR2('world','all','message'));

How to get ip address of a server on Centos 7 in bash

I believe that the most reliable way to get the external server ip address would be to use an external service.

ipaddr=$(curl -s http://whatismyip.akamai.com/)

Reading integers from binary file in Python

As you are reading the binary file, you need to unpack it into a integer, so use struct module for that

import struct
fin = open("hi.bmp", "rb")
firm = fin.read(2)  
file_size, = struct.unpack("i",fin.read(4))

moment.js - UTC gives wrong date

By default, MomentJS parses in local time. If only a date string (with no time) is provided, the time defaults to midnight.

In your code, you create a local date and then convert it to the UTC timezone (in fact, it makes the moment instance switch to UTC mode), so when it is formatted, it is shifted (depending on your local time) forward or backwards.

If the local timezone is UTC+N (N being a positive number), and you parse a date-only string, you will get the previous date.

Here are some examples to illustrate it (my local time offset is UTC+3 during DST):

>>> moment('07-18-2013', 'MM-DD-YYYY').utc().format("YYYY-MM-DD HH:mm")
"2013-07-17 21:00"
>>> moment('07-18-2013 12:00', 'MM-DD-YYYY HH:mm').utc().format("YYYY-MM-DD HH:mm")
"2013-07-18 09:00"
>>> Date()
"Thu Jul 25 2013 14:28:45 GMT+0300 (Jerusalem Daylight Time)"

If you want the date-time string interpreted as UTC, you should be explicit about it:

>>> moment(new Date('07-18-2013 UTC')).utc().format("YYYY-MM-DD HH:mm")
"2013-07-18 00:00"

or, as Matt Johnson mentions in his answer, you can (and probably should) parse it as a UTC date in the first place using moment.utc() and include the format string as a second argument to prevent ambiguity.

>>> moment.utc('07-18-2013', 'MM-DD-YYYY').format("YYYY-MM-DD HH:mm")
"2013-07-18 00:00"

To go the other way around and convert a UTC date to a local date, you can use the local() method, as follows:

>>> moment.utc('07-18-2013', 'MM-DD-YYYY').local().format("YYYY-MM-DD HH:mm")
"2013-07-18 03:00"

How to specify maven's distributionManagement organisation wide?

There's no need for a parent POM.

You can omit the distributionManagement part entirely in your poms and set it either on your build server or in settings.xml.

To do it on the build server, just pass to the mvn command:

-DaltSnapshotDeploymentRepository=snapshots::default::https://YOUR_NEXUS_URL/snapshots
-DaltReleaseDeploymentRepository=releases::default::https://YOUR_NEXUS_URL/releases

See https://maven.apache.org/plugins/maven-deploy-plugin/deploy-mojo.html for details which options can be set.

It's also possible to set this in your settings.xml.

Just create a profile there which is enabled and contains the property.

Example settings.xml:

<settings>
[...]
  <profiles>
    <profile>
      <id>nexus</id>
      <properties>
        <altSnapshotDeploymentRepository>snapshots::default::https://YOUR_NEXUS_URL/snapshots</altSnapshotDeploymentRepository>
        <altReleaseDeploymentRepository>releases::default::https://YOUR_NEXUS_URL/releases</altReleaseDeploymentRepository>
      </properties>
    </profile>
  </profiles>

  <activeProfiles>
    <activeProfile>nexus</activeProfile>
  </activeProfiles>

</settings>

Make sure that credentials for "snapshots" and "releases" are in the <servers> section of your settings.xml

The properties altSnapshotDeploymentRepository and altReleaseDeploymentRepository are introduced with maven-deploy-plugin version 2.8. Older versions will fail with the error message

Deployment failed: repository element was not specified in the POM inside distributionManagement element or in -DaltDeploymentRepository=id::layout::url parameter

To fix this, you can enforce a newer version of the plug-in:

        <build>
          <pluginManagement>
            <plugins>
              <plugin>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>2.8</version>
              </plugin>
            </plugins>
          </pluginManagement>
        </build>

Center image in table td in CSS

Set a fixed with of your image in your css and add an auto-margin/padding on the image to...

div.image img {
    width: 100px;
    margin: auto;
}

Or set the text-align to center...

td {
    text-align: center;
}

Regex to get string between curly braces

If your string will always be of that format, a regex is overkill:

>>> var g='{getThis}';
>>> g.substring(1,g.length-1)
"getThis"

substring(1 means to start one character in (just past the first {) and ,g.length-1) means to take characters until (but not including) the character at the string length minus one. This works because the position is zero-based, i.e. g.length-1 is the last position.

For readers other than the original poster: If it has to be a regex, use /{([^}]*)}/ if you want to allow empty strings, or /{([^}]+)}/ if you want to only match when there is at least one character between the curly braces. Breakdown:

  • /: start the regex pattern
    • {: a literal curly brace
      • (: start capturing
        • [: start defining a class of characters to capture
          • ^}: "anything other than }"
        • ]: OK, that's our whole class definition
        • *: any number of characters matching that class we just defined
      • ): done capturing
    • }: a literal curly brace must immediately follow what we captured
  • /: end the regex pattern

Validate IPv4 address in Java

There is also an undocumented utility class sun.net.util.IPAddressUtil, which you should not actually use, although it might be useful in a quick one-off, throw-away utility:

boolean isIP = IPAddressUtil.isIPv4LiteralAddress(ipAddressString);

Internally, this is the utility class InetAddress uses to parse IP addresses.

Note that this will return true for strings like "123", which, technically are valid IPv4 addresses, just not in dot-decimal notation.

How to move a file?

After Python 3.4, you can also use pathlib's class Path to move file.

from pathlib import Path

Path("path/to/current/file.foo").rename("path/to/new/destination/for/file.foo")

https://docs.python.org/3.4/library/pathlib.html#pathlib.Path.rename

Can't push image to Amazon ECR - fails with "no basic auth credentials"

For Mac OSX

TL;DR Make sure your "auths" key matches your credential store key exactly

  • Check your docker config:

cat ~/.docker/config.json

Sample Result:

{
    "auths": {
        "https://55511155511.dkr.ecr.us-east-1.amazonaws.com": {}
    },
    "HttpHeaders": {
        "User-Agent": "Docker-Client/19.03.5 (darwin)"
    },
    "credsStore": "osxkeychain"
}

Notice that the "auths" value is an empty object and docker is using a credential store "osxkeychain".

  • Open Mac's "Keychain Access" app and find the name "Docker Credentials"

enter image description here

Notice the Where: field

  • Make sure the auths key in ~/.docker/config.json matches the Where: field in Keychain Access.

If the auths key in ~/.docker/config.json does NOT match they Where: field in the keychain, you may get a Login Succeeded from docker login... but still get ERROR: Service 'web' failed to build: Get https://55511155511.dkr.ecr.us-east-1.amazonaws.com/v2/path/to/image/latest: no basic auth credentials when you try to pull.

In my case, I needed to add https://

Original

    "auths": {
        "55511155511.dkr.ecr.us-east-1.amazonaws.com": {}
    },

Fixed

    "auths": {
        "https://55511155511.dkr.ecr.us-east-1.amazonaws.com": {}
    },

Store a closure as a variable in Swift

Depends on your needs there is an addition to accepted answer. You may also implement it like this:

var parseCompletion: (() ->Void)!

and later in some func assign to it

func someHavyFunc(completion: @escaping () -> Void){
    self.parseCompletion = completion
}

and in some second function use it

func someSecondFunc(){
    if let completion = self.parseCompletion {
        completion()
    }
}

note that @escaping parameter is a mandatory here