Programs & Examples On #Trim

Trimming refers to the manipulation of a text string to remove leading and/or trailing whitespace (and/or ASCII control characters).

Trim characters in Java

I don't think there is any built in function to trim based on a passed in string. Here is a small example of how to do this. This is not likely the most efficient solution, but it is probably fast enough for most situations, evaluate and adapt to your needs. I recommend testing performance and optimizing as needed for any code snippet that will be used regularly. Below, I've included some timing information as an example.

public String trim( String stringToTrim, String stringToRemove )
{
    String answer = stringToTrim;

    while( answer.startsWith( stringToRemove ) )
    {
        answer = answer.substring( stringToRemove.length() );
    }

    while( answer.endsWith( stringToRemove ) )
    {
        answer = answer.substring( 0, answer.length() - stringToRemove.length() );
    }

    return answer;
}

This answer assumes that the characters to be trimmed are a string. For example, passing in "abc" will trim out "abc" but not "bbc" or "cba", etc.

Some performance times for running each of the following 10 million times.

" mile ".trim(); runs in 248 ms included as a reference implementation for performance comparisons.

trim( "smiles", "s" ); runs in 547 ms - approximately 2 times as long as java's String.trim() method.

"smiles".replaceAll("s$|^s",""); runs in 12,306 ms - approximately 48 times as long as java's String.trim() method.

And using a compiled regex pattern Pattern pattern = Pattern.compile("s$|^s"); pattern.matcher("smiles").replaceAll(""); runs in 7,804 ms - approximately 31 times as long as java's String.trim() method.

Trim specific character from a string

"|Howdy".replace(new RegExp("^\\|"),"");

(note the double escaping. \\ needed, to have an actually single slash in the string, that then leads to escaping of | in the regExp).

Only few characters need regExp-Escaping., among them the pipe operator.

Remove '\' char from string c#

Try using

String sOld = ...;
String sNew =     sOld.Replace("\\", String.Empty);

How can I trim leading and trailing white space?

Another option is to use the stri_trim function from the stringi package which defaults to removing leading and trailing whitespace:

> x <- c("  leading space","trailing space   ")
> stri_trim(x)
[1] "leading space"  "trailing space"

For only removing leading whitespace, use stri_trim_left. For only removing trailing whitespace, use stri_trim_right. When you want to remove other leading or trailing characters, you have to specify that with pattern =.

See also ?stri_trim for more info.

How to use a TRIM function in SQL Server

TRIM all SPACE's TAB's and ENTER's:

DECLARE @Str VARCHAR(MAX) = '      
          [         Foo    ]       
          '

DECLARE @NewStr VARCHAR(MAX) = ''
DECLARE @WhiteChars VARCHAR(4) =
      CHAR(13) + CHAR(10) -- ENTER
    + CHAR(9) -- TAB
    + ' ' -- SPACE

;WITH Split(Chr, Pos) AS (
    SELECT
          SUBSTRING(@Str, 1, 1) AS Chr
        , 1 AS Pos
    UNION ALL
    SELECT
          SUBSTRING(@Str, Pos, 1) AS Chr
        , Pos + 1 AS Pos
    FROM Split
    WHERE Pos <= LEN(@Str)
)
SELECT @NewStr = @NewStr + Chr
FROM Split
WHERE
    Pos >= (
        SELECT MIN(Pos)
        FROM Split
        WHERE CHARINDEX(Chr, @WhiteChars) = 0
    )
    AND Pos <= (
        SELECT MAX(Pos)
        FROM Split
        WHERE CHARINDEX(Chr, @WhiteChars) = 0
    )

SELECT '"' + @NewStr + '"'

As Function

CREATE FUNCTION StrTrim(@Str VARCHAR(MAX)) RETURNS VARCHAR(MAX) BEGIN
    DECLARE @NewStr VARCHAR(MAX) = NULL

    IF (@Str IS NOT NULL) BEGIN
        SET @NewStr = ''

        DECLARE @WhiteChars VARCHAR(4) =
              CHAR(13) + CHAR(10) -- ENTER
            + CHAR(9) -- TAB
            + ' ' -- SPACE

        IF (@Str LIKE ('%[' + @WhiteChars + ']%')) BEGIN

            ;WITH Split(Chr, Pos) AS (
                SELECT
                      SUBSTRING(@Str, 1, 1) AS Chr
                    , 1 AS Pos
                UNION ALL
                SELECT
                      SUBSTRING(@Str, Pos, 1) AS Chr
                    , Pos + 1 AS Pos
                FROM Split
                WHERE Pos <= LEN(@Str)
            )
            SELECT @NewStr = @NewStr + Chr
            FROM Split
            WHERE
                Pos >= (
                    SELECT MIN(Pos)
                    FROM Split
                    WHERE CHARINDEX(Chr, @WhiteChars) = 0
                )
                AND Pos <= (
                    SELECT MAX(Pos)
                    FROM Split
                    WHERE CHARINDEX(Chr, @WhiteChars) = 0
                )
        END
    END

    RETURN @NewStr
END

Example

-- Test
DECLARE @Str VARCHAR(MAX) = '      
          [         Foo    ]       
              '

SELECT 'Str', '"' + dbo.StrTrim(@Str) + '"'
UNION SELECT 'EMPTY', '"' + dbo.StrTrim('') + '"'
UNION SELECT 'EMTPY', '"' + dbo.StrTrim('      ') + '"'
UNION SELECT 'NULL', '"' + dbo.StrTrim(NULL) + '"'

Result

+-------+----------------+
| Test  | Result         |
+-------+----------------+
| EMPTY | ""             |
| EMTPY | ""             |
| NULL  | NULL           |
| Str   | "[   Foo    ]" |
+-------+----------------+

How do I trim whitespace?

If you want to trim the whitespace off just the beginning and end of the string, you can do something like this:

some_string = "    Hello,    world!\n    "
new_string = some_string.strip()
# new_string is now "Hello,    world!"

This works a lot like Qt's QString::trimmed() method, in that it removes leading and trailing whitespace, while leaving internal whitespace alone.

But if you'd like something like Qt's QString::simplified() method which not only removes leading and trailing whitespace, but also "squishes" all consecutive internal whitespace to one space character, you can use a combination of .split() and " ".join, like this:

some_string = "\t    Hello,  \n\t  world!\n    "
new_string = " ".join(some_string.split())
# new_string is now "Hello, world!"

In this last example, each sequence of internal whitespace replaced with a single space, while still trimming the whitespace off the start and end of the string.

How to remove new line characters from data rows in mysql?

Removes trailing returns when importing from Excel. When you execute this, you may receive an error that there is no WHERE; ignore and execute.

UPDATE table_name SET col_name = TRIM(TRAILING '\r' FROM col_name)

.trim() in JavaScript not working in IE

jQuery:

$.trim( $("#mycomment").val() );

Someone uses $("#mycomment").val().trim(); but this will not work on IE.

How many spaces will Java String.trim() remove?

From java docs(String class source),

/**
 * Returns a copy of the string, with leading and trailing whitespace
 * omitted.
 * <p>
 * If this <code>String</code> object represents an empty character
 * sequence, or the first and last characters of character sequence
 * represented by this <code>String</code> object both have codes
 * greater than <code>'&#92;u0020'</code> (the space character), then a
 * reference to this <code>String</code> object is returned.
 * <p>
 * Otherwise, if there is no character with a code greater than
 * <code>'&#92;u0020'</code> in the string, then a new
 * <code>String</code> object representing an empty string is created
 * and returned.
 * <p>
 * Otherwise, let <i>k</i> be the index of the first character in the
 * string whose code is greater than <code>'&#92;u0020'</code>, and let
 * <i>m</i> be the index of the last character in the string whose code
 * is greater than <code>'&#92;u0020'</code>. A new <code>String</code>
 * object is created, representing the substring of this string that
 * begins with the character at index <i>k</i> and ends with the
 * character at index <i>m</i>-that is, the result of
 * <code>this.substring(<i>k</i>,&nbsp;<i>m</i>+1)</code>.
 * <p>
 * This method may be used to trim whitespace (as defined above) from
 * the beginning and end of a string.
 *
 * @return  A copy of this string with leading and trailing white
 *          space removed, or this string if it has no leading or
 *          trailing white space.
 */
public String trim() {
int len = count;
int st = 0;
int off = offset;      /* avoid getfield opcode */
char[] val = value;    /* avoid getfield opcode */

while ((st < len) && (val[off + st] <= ' ')) {
    st++;
}
while ((st < len) && (val[off + len - 1] <= ' ')) {
    len--;
}
return ((st > 0) || (len < count)) ? substring(st, len) : this;
}

Note that after getting start and length it calls the substring method of String class.

How to trim a string in SQL Server before 2017?

SELECT LTRIM(RTRIM(Names)) AS Names FROM Customer

Trim spaces from end of a NSString

NSString* NSStringWithoutSpace(NSString* string)
{
    return [string stringByReplacingOccurrencesOfString:@" " withString:@""];
}

How to remove whitespace from a string in typescript?

Problem

The trim() method removes whitespace from both sides of a string.

Source

Solution

You can use a Javascript replace method to remove white space like

"hello world".replace(/\s/g, "");

Example

_x000D_
_x000D_
var out = "hello world".replace(/\s/g, "");_x000D_
console.log(out);
_x000D_
_x000D_
_x000D_

Replace multiple whitespaces with single whitespace in JavaScript string

How about this one?

"my test string \t\t with crazy stuff is cool ".replace(/\s{2,9999}|\t/g, ' ')

outputs "my test string with crazy stuff is cool "

This one gets rid of any tabs as well

How to Select a substring in Oracle SQL up to a specific character?

To find any sub-string from large string:

string_value:=('This is String,Please search string 'Ple');

Then to find the string 'Ple' from String_value we can do as:

select substr(string_value,instr(string_value,'Ple'),length('Ple')) from dual;

You will find result: Ple

Fastest way to remove first char in a String

You could profile it, if you really cared. Write a loop of many iterations and see what happens. Chances are, however, that this is not the bottleneck in your application, and TrimStart seems the most semantically correct. Strive to write code readably before optimizing.

Best way to verify string is empty or null

If you have to test more than one string in the same validation, you can do something like this:

import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Stream;

public class StringHelper {

  public static Boolean hasBlank(String ... strings) {

    Predicate<String> isBlank = s -> s == null || s.trim().isEmpty();

    return Optional
      .ofNullable(strings)
      .map(Stream::of)
      .map(stream -> stream.anyMatch(isBlank))
      .orElse(false);
  }

}

So, you can use this like StringHelper.hasBlank("Hello", null, "", " ") or StringHelper.hasBlank("Hello") in a generic form.

How to delete specific characters from a string in Ruby?

If you just want to remove the first two characters and the last two, then you can use negative indexes on the string:

s = "((String1))"
s = s[2...-2]
p s # => "String1"

If you want to remove all parentheses from the string you can use the delete method on the string class:

s = "((String1))"
s.delete! '()'
p s #  => "String1"

How do I trim whitespace from a string?

This can also be done with a regular expression

import re

input  = " Hello "
output = re.sub(r'^\s+|\s+$', '', input)
# output = 'Hello'

Removing spaces from string

When I am reading numbers from contact book, then it doesn't worked I used

number=number.replaceAll("\\s+", "");

It worked and for url you may use

url=url.replaceAll(" ", "%20");

JavaScript: Parsing a string Boolean value?

You can try the following:

function parseBool(val)
{
    if ((typeof val === 'string' && (val.toLowerCase() === 'true' || val.toLowerCase() === 'yes')) || val === 1)
        return true;
    else if ((typeof val === 'string' && (val.toLowerCase() === 'false' || val.toLowerCase() === 'no')) || val === 0)
        return false;

    return null;
}

If it's a valid value, it returns the equivalent bool value otherwise it returns null.

Strip / trim all strings of a dataframe

def trim(x):
    if x.dtype == object:
        x = x.str.split(' ').str[0]
    return(x)

df = df.apply(trim)

Remove all whitespace in a string

To remove only spaces use str.replace:

sentence = sentence.replace(' ', '')

To remove all whitespace characters (space, tab, newline, and so on) you can use split then join:

sentence = ''.join(sentence.split())

or a regular expression:

import re
pattern = re.compile(r'\s+')
sentence = re.sub(pattern, '', sentence)

If you want to only remove whitespace from the beginning and end you can use strip:

sentence = sentence.strip()

You can also use lstrip to remove whitespace only from the beginning of the string, and rstrip to remove whitespace from the end of the string.

Remove all spaces from a string in SQL Server

I had this issue today and replace / trim did the trick..see below.

update table_foo 
set column_bar  = REPLACE(LTRIM(RTRIM(column_bar)), '  ', '')

before and after :

old-bad:  column_bar    |   New-fixed:   column_bar
       '  xyz  '        |                'xyz'   
       '  xyz  '        |                'xyz' 
       '  xyz  '        |                'xyz' 
       '  xyz  '        |                'xyz' 
       '  xyz  '        |                'xyz' 
       '  xyz  '        |                'xyz' 

Replace all whitespace characters

Try this:

str.replace(/\s/g, "X")

Remove whitespaces inside a string in javascript

Probably because you forgot to implement the solution in the accepted answer. That's the code that makes trim() work.

update

This answer only applies to older browsers. Newer browsers apparently support trim() natively.

How to trim a string to N chars in Javascript?

I suggest to use an extension for code neatness. Note that extending an internal object prototype could potentially mess with libraries that depend on them.

String.prototype.trimEllip = function (length) {
  return this.length > length ? this.substring(0, length) + "..." : this;
}

And use it like:

var stringObject= 'this is a verrrryyyyyyyyyyyyyyyyyyyyyyyyyyyyylllooooooooooooonggggggggggggsssssssssssssttttttttttrrrrrrrrriiiiiiiiiiinnnnnnnnnnnnggggggggg';
stringObject.trimEllip(25)

What's the best way to trim std::string?

Ok this maight not be the fastest but it's... simple.

str = "   aaa    ";
int len = str.length();
// rtrim
while(str[len-1] == ' ') { str.erase(--len,1); }
// ltrim
while(str[0] == ' ') { str.erase(0,1); }

How to remove trailing and leading whitespace for user-provided input in a batch file?

I'd like to present a compact solution using a call by reference (yes, "batch" has pointers too!) to a function, and a "subfunction":

  @ECHO OFF
  SETLOCAL ENABLEDELAYEDEXPANSION

  SET /p NAME=- NAME ? 
  ECHO "%NAME%"
  CALL :TRIM NAME
  ECHO "%NAME%"
  GOTO :EOF

  :TRIM
  SetLocal EnableDelayedExpansion
  Call :TRIMSUB %%%1%%
  EndLocal & set %1=%tempvar%
  GOTO :EOF

  :TRIMSUB
  set tempvar=%*
  GOTO :EOF

Trim to remove white space

No need for jQuery

JavaScript does have a native .trim() method.

var name = "    John Smith  ";
name = name.trim();

console.log(name); // "John Smith"

Example Here

String.prototype.trim()

The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).

Does swift have a trim method on String?

**Swift 5**

extension String {

    func trimAllSpace() -> String {
         return components(separatedBy: .whitespacesAndNewlines).joined()
    }
    
    func trimSpace() -> String {
        return self.trimmingCharacters(in: .whitespacesAndNewlines)
    }
}

**Use:**
let result = " abc ".trimAllSpace()
// result == "abc"
let ex = " abc cd  ".trimSpace()
// ex == "abc cd"

Trim string in JavaScript?

For IE9+ and other browsers

function trim(text) {
    return (text == null) ? '' : ''.trim.call(text);
}

How to Remove the last char of String in C#?

newString = yourString.Substring(0, yourString.length -1);

Adding whitespace in Java

Use the StringUtils class, it also includes null check

StringUtils.leftPad(String str, int size)
StringUtils.rightPad(String str, int size)

Trim Whitespaces (New Line and Tab space) in a String in Oracle

If you have Oracle 10g, REGEXP_REPLACE is pretty flexible.

Using the following string as a test:

chr(9) || 'Q   qwer' || chr(9) || chr(10) ||
chr(13) || 'qwerqwer     qwerty' || chr(9) || 
chr(10) || chr(13)

The [[:space:]] will remove all whitespace, and the ([[:cntrl:]])|(^\t) regexp will remove non-printing characters and tabs.

select
    tester,
    regexp_replace(tester, '(^[[:space:]]+)|([[:space:]]+$)',null)
            regexp_tester_1,
    regexp_replace(tester, '(^[[:cntrl:]^\t]+)|([[:cntrl:]^\t]+$)',null) 
            regexp_tester_2
from
    (
    select
        chr(9) || 'Q   qwer' || chr(9) || chr(10) ||
                chr(13) || 'qwerqwer     qwerty' || chr(9) || 
                chr(10) || chr(13) tester 
    from 
        dual
    )

Returning:

  • REGEXP_TESTER_1: "Qqwerqwerqwerqwerty"
  • REGEXP_TESTER_2: "Q qwerqwerqwer qwerty"

Hope this is of some use.

How can I trim beginning and ending double quotes from a string?

Scala

s.stripPrefix("\"").stripSuffix("\"")

This works regardless of whether the string has or does not have quotes at the start and / or end.

Edit: Sorry, Scala only

Remove last specific character in a string c#

Or you can convert it into Char Array first by:

string Something = "1,5,12,34,";
char[] SomeGoodThing=Something.ToCharArray[];

Now you have each character indexed:

SomeGoodThing[0] -> '1'
SomeGoodThing[1] -> ','

Play around it

How to remove all white space from the beginning or end of a string?

string a = "   Hello   ";
string trimmed = a.Trim();

trimmed is now "Hello"

How to trim whitespace from a Bash variable?

This will remove all the whitespaces from your String,

 VAR2="${VAR2//[[:space:]]/}"

/ replaces the first occurrence and // all occurrences of whitespaces in the string. I.e. all white spaces get replaced by – nothing

String strip() for JavaScript?

Use this:

if(typeof(String.prototype.trim) === "undefined")
{
    String.prototype.trim = function() 
    {
        return String(this).replace(/^\s+|\s+$/g, '');
    };
}

The trim function will now be available as a first-class function on your strings. For example:

" dog".trim() === "dog" //true

EDIT: Took J-P's suggestion to combine the regex patterns into one. Also added the global modifier per Christoph's suggestion.

Took Matthew Crumley's idea about sniffing on the trim function prior to recreating it. This is done in case the version of JavaScript used on the client is more recent and therefore has its own, native trim function.

How do I remove leading whitespace in Python?

The function strip will remove whitespace from the beginning and end of a string.

my_str = "   text "
my_str = my_str.strip()

will set my_str to "text".

Trim whitespace from a String

I think that substr() throws an exception if str only contains the whitespace.

I would modify it to the following code:

string trim(string& str)
{
    size_t first = str.find_first_not_of(' ');
    if (first == std::string::npos)
        return "";
    size_t last = str.find_last_not_of(' ');
    return str.substr(first, (last-first+1));
}

How do I trim leading/trailing whitespace in a standard way?

Here is what I disclosed regarding the question in Linux kernel code:

/**
 * skip_spaces - Removes leading whitespace from @s.
 * @s: The string to be stripped.
 *
 * Returns a pointer to the first non-whitespace character in @s.
 */
char *skip_spaces(const char *str)
{
    while (isspace(*str))
            ++str;
    return (char *)str;
}

/**
 * strim - Removes leading and trailing whitespace from @s.
 * @s: The string to be stripped.
 *
 * Note that the first trailing whitespace is replaced with a %NUL-terminator
 * in the given string @s. Returns a pointer to the first non-whitespace
 * character in @s.
 */
char *strim(char *s)
{
    size_t size;
    char *end;

    size = strlen(s);

    if (!size)
            return s;

    end = s + size - 1;
    while (end >= s && isspace(*end))
            end--;
    *(end + 1) = '\0';

    return skip_spaces(s);
}

It is supposed to be bug free due to the origin ;-)

Mine one piece is closer to KISS principle I guess:

/**
 * trim spaces
 **/
char * trim_inplace(char * s, int len)
{
    // trim leading
    while (len && isspace(s[0]))
    {
        s++; len--;
    }

    // trim trailing
    while (len && isspace(s[len - 1]))
    {
        s[len - 1] = 0; len--;
    }

    return s;
}

Saving and loading objects and using pickle

As for your second problem:

 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "C:\Python31\lib\pickle.py", line
 1365, in load encoding=encoding,
 errors=errors).load() EOFError

After you have read the contents of the file, the file pointer will be at the end of the file - there will be no further data to read. You have to rewind the file so that it will be read from the beginning again:

file.seek(0)

What you usually want to do though, is to use a context manager to open the file and read data from it. This way, the file will be automatically closed after the block finishes executing, which will also help you organize your file operations into meaningful chunks.

Finally, cPickle is a faster implementation of the pickle module in C. So:

In [1]: import _pickle as cPickle

In [2]: d = {"a": 1, "b": 2}

In [4]: with open(r"someobject.pickle", "wb") as output_file:
   ...:     cPickle.dump(d, output_file)
   ...:

# pickle_file will be closed at this point, preventing your from accessing it any further

In [5]: with open(r"someobject.pickle", "rb") as input_file:
   ...:     e = cPickle.load(input_file)
   ...:

In [7]: print e
------> print(e)
{'a': 1, 'b': 2}

How can I create a carriage return in my C# string

You can put \r\n in your string.

Collectors.toMap() keyMapper -- more succinct expression?

List<Person> roster = ...;

Map<String, Person> map = 
    roster
        .stream()
        .collect(
            Collectors.toMap(p -> p.getLast(), p -> p)
        );

that would be the translation, but i havent run this or used the API. most likely you can substitute p -> p, for Function.identity(). and statically import toMap(...)

How to send email by using javascript or jquery

You can do it server-side with nodejs.

Check out the popular Nodemailer package. There are plenty of transports and plugins for integrating with services like AWS SES and SendGrid!

The following example uses SES transport (Amazon SES):

let nodemailer = require("nodemailer");
let aws = require("aws-sdk");
let transporter = nodemailer.createTransport({
  SES: new aws.SES({ apiVersion: "2010-12-01" })
});

Oracle PL/SQL : remove "space characters" from a string

I'd go for regexp_replace, although I'm not 100% sure this is usable in PL/SQL

my_value := regexp_replace(my_value, '[[:space:]]*',''); 

Excel VBA Check if directory exists error

Use the FolderExists method of the Scripting object.

Public Function dirExists(s_directory As String) As Boolean
    Dim oFSO As Object
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    dirExists = oFSO.FolderExists(s_directory)
End Function

How to display Toast in Android?

The Getting Started Way

Toast.makeText(this, "Hello World", Toast.LENGTH_SHORT).show();

How do I abort the execution of a Python script?

To exit a script you can use,

import sys
sys.exit()

You can also provide an exit status value, usually an integer.

import sys
sys.exit(0)

Exits with zero, which is generally interpreted as success. Non-zero codes are usually treated as errors. The default is to exit with zero.

import sys
sys.exit("aa! errors!")

Prints "aa! errors!" and exits with a status code of 1.

There is also an _exit() function in the os module. The sys.exit() function raises a SystemExit exception to exit the program, so try statements and cleanup code can execute. The os._exit() version doesn't do this. It just ends the program without doing any cleanup or flushing output buffers, so it shouldn't normally be used.

The Python docs indicate that os._exit() is the normal way to end a child process created with a call to os.fork(), so it does have a use in certain circumstances.

Another git process seems to be running in this repository

For me the solution was as simple as closing my IDE and then checking out. A teammate of mine had accepted my PR and merged the code via TFS. Removing the .lock files did not work.

Vertically align an image inside a div with responsive height

Here's a technique that allows you to center ANY content both vertically and horizontally!

Basically, you just need a two containers and make sure your elements meet the following criteria.

The outher container :

  • should have display: table;

The inner container :

  • should have display: table-cell;
  • should have vertical-align: middle;
  • should have text-align: center;

The content box :

  • should have display: inline-block;

If you use this technique, just add your image (along with any other content you want to go with it) to the content box.

Demo :

_x000D_
_x000D_
body {_x000D_
    margin : 0;_x000D_
}_x000D_
_x000D_
.outer-container {_x000D_
    position : absolute;_x000D_
    display: table;_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    background: #ccc;_x000D_
}_x000D_
_x000D_
.inner-container {_x000D_
    display: table-cell;_x000D_
    vertical-align: middle;_x000D_
    text-align: center;_x000D_
}_x000D_
_x000D_
.centered-content {_x000D_
    display: inline-block;_x000D_
    background: #fff;_x000D_
    padding : 12px;_x000D_
    border : 1px solid #000;_x000D_
}_x000D_
_x000D_
img {_x000D_
   max-width : 120px;_x000D_
}
_x000D_
<div class="outer-container">_x000D_
   <div class="inner-container">_x000D_
     <div class="centered-content">_x000D_
        <img src="https://i.stack.imgur.com/mRsBv.png" />_x000D_
     </div>_x000D_
   </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

See also this Fiddle!

PHP Function with Optional Parameters

To accomplish what you want, use an array Like Rabbot said (though this can become a pain to document/maintain if used excessively). Or just use the traditional optional args.

//My function with tons of optional params
function my_func($req_a, $req_b, $opt_a = NULL, $opt_b = NULL, $opt_c = NULL)
{
  //Do stuff
}
my_func('Hi', 'World', null, null, 'Red');

However, I usually find that when I start writing a function/method with that many arguments - more often than not it is a code smell, and can be re-factored/abstracted into something much cleaner.

//Specialization of my_func - assuming my_func itself cannot be refactored
function my_color_func($reg_a, $reg_b, $opt = 'Red')
{
  return my_func($reg_a, $reg_b, null, null, $opt);
}
my_color_func('Hi', 'World');
my_color_func('Hello', 'Universe', 'Green');

How to deal with "java.lang.OutOfMemoryError: Java heap space" error?

I read somewhere else that you can try - catch java.lang.OutOfMemoryError and on the catch block, you can free all resources that you know might use a lot of memory, close connections and so forth, then do a System.gc() then re-try whatever you were going to do.

Another way is this although, i don't know whether this would work, but I am currently testing whether it will work on my application.

The Idea is to do Garbage collection by calling System.gc() which is known to increase free memory. You can keep checking this after a memory gobbling code executes.

//Mimimum acceptable free memory you think your app needs
long minRunningMemory = (1024*1024);

Runtime runtime = Runtime.getRuntime();

if(runtime.freeMemory()<minRunningMemory)
 System.gc();

How to install node.js as windows service?

Late to the party, but node-windows will do the trick too.

enter image description here

It also has system logging built in.

enter image description here

There is an API to create scripts from code, i.e.

var Service = require('node-windows').Service;

// Create a new service object
var svc = new Service({
  name:'Hello World',
  description: 'The nodejs.org example web server.',
  script: 'C:\\path\\to\\helloworld.js'
});

// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install',function(){
  svc.start();
});

svc.install();

FD: I'm the author of this module.

How to connect to remote Redis server?

One thing that confused me a little bit with this command is that if redis-cli fails to connect using the passed connection string it will still put you in the redis-cli shell, i.e:

redis-cli
Could not connect to Redis at 127.0.0.1:6379: Connection refused
not connected> 

You'll then need to exit to get yourself out of the shell. I wasn't paying much attention here and kept passing in new redis-cli commands wondering why the command wasn't using my passed connection string.

Garbage collector in Android

My app manage a lot of images and it died with a OutOfMemoryError. This helped me. In the Manifest.xml Add

<application
....
   android:largeHeap="true"> 

Add timestamp column with default NOW() for new rows only

For example, I will create a table called users as below and give a column named date a default value NOW()

create table users_parent (
    user_id     varchar(50),
    full_name   varchar(240),
    login_id_1  varchar(50),
    date        timestamp NOT NULL DEFAULT NOW()
);

Thanks

How to exclude 0 from MIN formula Excel

Not entirely sure what you want here, but if you want to discount blank cells in the range and pass over zeros then this would do it; if a little contrived:

=MIN(IF(A1:E1=0,MAX(A1:E1),A1:E1))

With Ctrl+Shift+Enter as an array.

What I'm doing here is replacing zeros with the maximum value in the list.

jQuery select box validation

simplify the whole thing a bit, fix some issues with commas which will blow up some browsers:

  $(document).ready(function () {
       $("#register").validate({
           debug: true,
           rules: {
               year: {
                   required: function () {
                       return ($("#year option:selected").val() == "0");
                   }
               }
           },
           messages: {
               year: "Year Required"
           }
       });
   });

Jumping to an assumption, should your select not have this attribute validate="required:true"?

How do I run .sh or .bat files from Terminal?

This is because the script is not in your $PATH. Use

./scriptname

You can also copy this to one of the folders in your $PATH or alter the $PATH variable so you can always use just the script name. Take care, however, there is a reason why your current folder is not in $PATH. It might be a security risk.

If you still have problems executing the script, you might want to check its permissions - you must have execute permissions to execute it, obviously. Use

chmod u+x scriptname

A .sh file is a Unix shell script. A .bat file is a Windows batch file.

linux script to kill java process

If you just want to kill any/all java processes, then all you need is;

killall java

If, however, you want to kill the wskInterface process in particular, then you're most of the way there, you just need to strip out the process id;

PID=`ps -ef | grep wskInterface | awk '{ print $2 }'`
kill -9 $PID

Should do it, there is probably an easier way though...

What does "if (rs.next())" mean?

Look at the picture, it's a result set of a query select * from employee

enter image description here

and the next() method of ResultSet class help to move the cursor to the next row of a returned result set which is rs in your example.

:)

What's the best way to get the current URL in Spring MVC?

Instead of using RequestContextHolder directly, you can also use ServletUriComponentsBuilder and its static methods:

  • ServletUriComponentsBuilder.fromCurrentContextPath()
  • ServletUriComponentsBuilder.fromCurrentServletMapping()
  • ServletUriComponentsBuilder.fromCurrentRequestUri()
  • ServletUriComponentsBuilder.fromCurrentRequest()

They use RequestContextHolder under the hood, but provide additional flexibility to build new URLs using the capabilities of UriComponentsBuilder.

Example:

ServletUriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentRequestUri();
builder.scheme("https");
builder.replaceQueryParam("someBoolean", false);
URI newUri = builder.build().toUri();

HTML text input allow only numeric input

This is the extended version of geowa4's solution. Supports min and max attributes. If the number is out of range, the previous value will be shown.

You can test it here.

Usage: <input type=text class='number' maxlength=3 min=1 max=500>

function number(e) {
var theEvent = e || window.event;
var key = theEvent.keyCode || theEvent.which;
if(key!=13&&key!=9){//allow enter and tab
  key = String.fromCharCode( key );
  var regex = /[0-9]|\./;
  if( !regex.test(key)) {
    theEvent.returnValue = false;
    if(theEvent.preventDefault) theEvent.preventDefault();
    }   
  }
}

$(document).ready(function(){
    $("input[type=text]").filter(".number,.NUMBER").on({
        "focus":function(e){
         $(e.target).data('oldValue',$(e.target).val());
            },
        "keypress":function(e){
                e.target.oldvalue = e.target.value;
                number(e);
            },
        "change":function(e){
            var t = e.target;
            var min = $(t).attr("min");
            var max = $(t).attr("max");
            var val = parseInt($(t).val(),10);          
            if( val<min || max<val)
                {
                    alert("Error!");
                    $(t).val($(t).data('oldValue'));
                }

            }       
    });     
});

If the inputs are dynamic use this:

$(document).ready(function(){
    $("body").on("focus","input[type=text].number,.NUMBER",function(e){
        $(e.target).data('oldValue',$(e.target).val());
    }); 
    $("body").on("keypress","input[type=text].number,.NUMBER",function(e){
        e.target.oldvalue = e.target.value;
        number(e);
    }); 
    $("body").on("change","input[type=text].number,.NUMBER",function(e){
        var t = e.target
        var min = $(t).attr("min");
        var max = $(t).attr("max");
        var val = parseInt($(t).val());         
        if( val<min || max<val)
            {
                alert("Error!");
                $(t).val($(t).data('oldValue'));
            }
    }); 
});

How do I get column datatype in Oracle with PL-SQL with low privileges?

Quick and dirty way (e.g. to see how data is stored in oracle)

SQL> select dump(dummy) dump_dummy, dummy
     , dump(10) dump_ten
from dual

DUMP_DUMMY       DUMMY DUMP_TEN            
---------------- ----- --------------------
Typ=1 Len=1: 88  X     Typ=2 Len=2: 193,11 
1 row selected.

will show that dummy column in table sys.dual has typ=1 (varchar2), while 10 is Typ=2 (number).

Pinging servers in Python

My version of a ping function:

  • Works on Python 3.5 and later, on Windows and Linux (should work on Mac, but can't test it).
  • On Windows, returns False if the ping command fails with "Destination Host Unreachable".
  • And does not show any output, either as a pop-up window or in command line.
import platform, subprocess

def ping(host_or_ip, packets=1, timeout=1000):
    ''' Calls system "ping" command, returns True if ping succeeds.
    Required parameter: host_or_ip (str, address of host to ping)
    Optional parameters: packets (int, number of retries), timeout (int, ms to wait for response)
    Does not show any output, either as popup window or in command line.
    Python 3.5+, Windows and Linux compatible (Mac not tested, should work)
    '''
    # The ping command is the same for Windows and Linux, except for the "number of packets" flag.
    if platform.system().lower() == 'windows':
        command = ['ping', '-n', str(packets), '-w', str(timeout), host_or_ip]
        # run parameters: capture output, discard error messages, do not show window
        result = subprocess.run(command, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, creationflags=0x08000000)
        # 0x0800000 is a windows-only Popen flag to specify that a new process will not create a window.
        # On Python 3.7+, you can use a subprocess constant:
        #   result = subprocess.run(command, capture_output=True, creationflags=subprocess.CREATE_NO_WINDOW)
        # On windows 7+, ping returns 0 (ok) when host is not reachable; to be sure host is responding,
        # we search the text "TTL=" on the command output. If it's there, the ping really had a response.
        return result.returncode == 0 and b'TTL=' in result.stdout
    else:
        command = ['ping', '-c', str(packets), '-w', str(timeout), host_or_ip]
        # run parameters: discard output and error messages
        result = subprocess.run(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        return result.returncode == 0

Feel free to use it as you will.

How to get list of all installed packages along with version in composer?

The behaviour of this command as been modified so you don't have to pass the -i option:

[10:19:05] coil@coil:~/workspace/api$ composer show -i
You are using the deprecated option "installed". 
Only installed packages are shown by default now. 
The --all option can be used to show all packages.

css background image in a different folder from css

For mac OS you should use this :

body {
 background: url(../../img/bg.png);
}

MySQL, create a simple function

this is a mysql function example. I hope it helps. (I have not tested it yet, but should work)

DROP FUNCTION IF EXISTS F_TEST //
CREATE FUNCTION F_TEST(PID INT) RETURNS VARCHAR
BEGIN
/*DECLARE VALUES YOU MAY NEED, EXAMPLE:
  DECLARE NOM_VAR1 DATATYPE [DEFAULT] VALUE;
  */
  DECLARE NAME_FOUND VARCHAR DEFAULT "";

    SELECT EMPLOYEE_NAME INTO NAME_FOUND FROM TABLE_NAME WHERE ID = PID;
  RETURN NAME_FOUND;
END;//

How can I get a list of users from active directory?

Certainly the credit goes to @Harvey Kwok here, but I just wanted to add this example because in my case I wanted to get an actual List of UserPrincipals. It's probably more efficient to filter this query upfront, but in my small environment, it's just easier to pull everything and then filter as needed later from my list.

Depending on what you need, you may not need to cast to DirectoryEntry, but some properties are not available from UserPrincipal.

using (var searcher = new PrincipalSearcher(new UserPrincipal(new PrincipalContext(ContextType.Domain, Environment.UserDomainName))))
{
    List<UserPrincipal> users = searcher.FindAll().Select(u => (UserPrincipal)u).ToList();
    foreach(var u in users)
        {
            DirectoryEntry d = (DirectoryEntry)u.GetUnderlyingObject();
            Console.WriteLine(d.Properties["GivenName"]?.Value?.ToString() + d.Properties["sn"]?.Value?.ToString());
        }
}

Express: How to pass app-instance to routes from a different file?

Or just do that:

var app = req.app

inside the Middleware you are using for these routes. Like that:

router.use( (req,res,next) => {
    app = req.app;
    next();
});

Error 1920 service failed to start. Verify that you have sufficient privileges to start system services

In my case I had to delete the services in my installshield project and start from square one. My original service components were added manually and I couldn't get them working, the only error I was getting was the same "Error 1920 service failed to start. Verify that you have sufficient privileges to start system services." that you were getting. After deleting my components, I re-added them using the component wizard.
enter image description here

Component Wizard looks like this

I actually had to create two new components. One was of type "Install Service".

Service Component type shown here

enter image description here

The other component I had to add was of "Control Service" type.

enter image description here

I had to choose the service that I had setup when I added the Install Service component.enter image description here

After that it worked, even though nothing looked differently from the components I had added manually. Installshield must do something behind the scenes when it wires up the service components with the component wizard.

All of this was with Install Shield 2016.

How to concatenate items in a list to a single string?

Edit from the future: Please don't use this, this function was removed in Python 3 and Python 2 is dead. Even if you are still using Python 2 you should write Python 3 ready code to make the inevitable upgrade easier.

Although @Burhan Khalid's answer is good, I think it's more understandable like this:

from str import join

sentence = ['this','is','a','sentence']

join(sentence, "-") 

The second argument to join() is optional and defaults to " ".

How to detect tableView cell touched or clicked in swift

 # Check delegate? first must be connected owner of view controller

    # Simple implementation of the didSelectRowAt function.

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
         print("row selection: \(indexPath.row)")
    }

Is there a php echo/print equivalent in javascript

From w3school's page on JavaScript output,

JavaScript can "display" data in different ways:

Writing into an alert box, using window.alert().

Writing into the HTML output using document.write().

Writing into an HTML element, using innerHTML.

Writing into the browser console, using console.log().

What exactly do "u" and "r" string flags do, and what are raw string literals?

A "u" prefix denotes the value has type unicode rather than str.

Raw string literals, with an "r" prefix, escape any escape sequences within them, so len(r"\n") is 2. Because they escape escape sequences, you cannot end a string literal with a single backslash: that's not a valid escape sequence (e.g. r"\").

"Raw" is not part of the type, it's merely one way to represent the value. For example, "\\n" and r"\n" are identical values, just like 32, 0x20, and 0b100000 are identical.

You can have unicode raw string literals:

>>> u = ur"\n"
>>> print type(u), len(u)
<type 'unicode'> 2

The source file encoding just determines how to interpret the source file, it doesn't affect expressions or types otherwise. However, it's recommended to avoid code where an encoding other than ASCII would change the meaning:

Files using ASCII (or UTF-8, for Python 3.0) should not have a coding cookie. Latin-1 (or UTF-8) should only be used when a comment or docstring needs to mention an author name that requires Latin-1; otherwise, using \x, \u or \U escapes is the preferred way to include non-ASCII data in string literals.

Reading and displaying data from a .txt file

In Java 8, you can read a whole file, simply with:

public String read(String file) throws IOException {
  return new String(Files.readAllBytes(Paths.get(file)));
}

or if its a Resource:

public String read(String file) throws IOException {
  URL url = Resources.getResource(file);
  return Resources.toString(url, Charsets.UTF_8);
}

window.location.href not working

Try this

`var url = "http://stackoverflow.com";    
$(location).attr('href',url);`

Or you can do something like this

// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");

// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";

and add a return false at the end of your function call

What are the time complexities of various data structures?

Arrays

  • Set, Check element at a particular index: O(1)
  • Searching: O(n) if array is unsorted and O(log n) if array is sorted and something like a binary search is used,
  • As pointed out by Aivean, there is no Delete operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirements
  • Similarly, Insert for arrays is basically Set as mentioned in the beginning

ArrayList:

  • Add: Amortized O(1)
  • Remove: O(n)
  • Contains: O(n)
  • Size: O(1)

Linked List:

  • Inserting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Doubly-Linked List:

  • Inserting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Stack:

  • Push: O(1)
  • Pop: O(1)
  • Top: O(1)
  • Search (Something like lookup, as a special operation): O(n) (I guess so)

Queue/Deque/Circular Queue:

  • Insert: O(1)
  • Remove: O(1)
  • Size: O(1)

Binary Search Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(n)

Red-Black Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(log n)

Heap/PriorityQueue (min/max):

  • Find Min/Find Max: O(1)
  • Insert: O(log n)
  • Delete Min/Delete Max: O(log n)
  • Extract Min/Extract Max: O(log n)
  • Lookup, Delete (if at all provided): O(n), we will have to scan all the elements as they are not ordered like BST

HashMap/Hashtable/HashSet:

  • Insert/Delete: O(1) amortized
  • Re-size/hash: O(n)
  • Contains: O(1)

matplotlib savefig() plots different from show()

Old question, but apparently Google likes it so I thought I put an answer down here after some research about this problem.

If you create a figure from scratch you can give it a size option while creation:

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(3, 6))

plt.plot(range(10)) #plot example
plt.show() #for control

fig.savefig('temp.png', dpi=fig.dpi)

figsize(width,height) adjusts the absolute dimension of your plot and helps to make sure both plots look the same.

As stated in another answer the dpi option affects the relative size of the text and width of the stroke on lines, etc. Using the option dpi=fig.dpi makes sure the relative size of those are the same both for show() and savefig().

Alternatively the figure size can be changed after creation with:

fig.set_size_inches(3, 6, forward=True)

forward allows to change the size on the fly.

If you have trouble with too large borders in the created image you can adjust those either with:

plt.tight_layout()
#or:
plt.tight_layout(pad=2)

or:

fig.savefig('temp.png', dpi=fig.dpi, bbox_inches='tight')
#or:
fig.savefig('temp.png', dpi=fig.dpi, bbox_inches='tight', pad_inches=0.5)

The first option just minimizes the layout and borders and the second option allows to manually adjust the borders a bit. These tips helped at least me to solve my problem of different savefig() and show() images.

Casting a number to a string in TypeScript

One can also use the following syntax in typescript. Note the backtick " ` "

window.location.hash = `${page_number}`

How to unpack and pack pkg file?

Packages are just .xar archives with a different extension and a specified file hierarchy. Unfortunately, part of that file hierarchy is a cpio.gz archive of the actual installables, and usually that's what you want to edit. And there's also a Bom file that includes information on the files inside that cpio archive, and a PackageInfo file that includes summary information.

If you really do just need to edit one of the info files, that's simple:

mkdir Foo
cd Foo
xar -xf ../Foo.pkg
# edit stuff
xar -cf ../Foo-new.pkg *

But if you need to edit the installable files:

mkdir Foo
cd Foo
xar -xf ../Foo.pkg
cd foo.pkg
cat Payload | gunzip -dc |cpio -i
# edit Foo.app/*
rm Payload
find ./Foo.app | cpio -o | gzip -c > Payload
mkbom Foo.app Bom # or edit Bom
# edit PackageInfo
rm -rf Foo.app
cd ..
xar -cf ../Foo-new.pkg

I believe you can get mkbom (and lsbom) for most linux distros. (If you can get ditto, that makes things even easier, but I'm not sure if that's nearly as ubiquitously available.)

Trying to use fetch and pass in mode: no-cors

So if you're like me and developing a website on localhost where you're trying to fetch data from Laravel API and use it in your Vue front-end, and you see this problem, here is how I solved it:

  1. In your Laravel project, run command php artisan make:middleware Cors. This will create app/Http/Middleware/Cors.php for you.
  2. Add the following code inside the handles function in Cors.php:

    return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    
  3. In app/Http/kernel.php, add the following entry in $routeMiddleware array:

    ‘cors’ => \App\Http\Middleware\Cors::class
    

    (There would be other entries in the array like auth, guest etc. Also make sure you're doing this in app/Http/kernel.php because there is another kernel.php too in Laravel)

  4. Add this middleware on route registration for all the routes where you want to allow access, like this:

    Route::group(['middleware' => 'cors'], function () {
        Route::get('getData', 'v1\MyController@getData');
        Route::get('getData2', 'v1\MyController@getData2');
    });
    
  5. In Vue front-end, make sure you call this API in mounted() function and not in data(). Also make sure you use http:// or https:// with the URL in your fetch() call.

Full credits to Pete Houston's blog article.

MySQL - Selecting data from multiple tables all with same structure but different data

The union statement cause a deal time in huge data. It is good to perform the select in 2 steps:

  1. select the id
  2. then select the main table with it

Retrieve a Fragment from a ViewPager

Another simple solution:

    public class MyPagerAdapter extends FragmentPagerAdapter {
        private Fragment mCurrentFragment;

        public Fragment getCurrentFragment() {
            return mCurrentFragment;
        }
//...    
        @Override
        public void setPrimaryItem(ViewGroup container, int position, Object object) {
            if (getCurrentFragment() != object) {
                mCurrentFragment = ((Fragment) object);
            }
            super.setPrimaryItem(container, position, object);
        }
    }

What does T&& (double ampersand) mean in C++11?

The term for T&& when used with type deduction (such as for perfect forwarding) is known colloquially as a forwarding reference. The term "universal reference" was coined by Scott Meyers in this article, but was later changed.

That is because it may be either r-value or l-value.

Examples are:

// template
template<class T> foo(T&& t) { ... }

// auto
auto&& t = ...;

// typedef
typedef ... T;
T&& t = ...;

// decltype
decltype(...)&& t = ...;

More discussion can be found in the answer for: Syntax for universal references

Remove excess whitespace from within a string

If you want to replace only multiple spaces in a string, for Example: "this string have lots of space . " And you expect the answer to be "this string have lots of space", you can use the following solution:

$strng = "this string                        have lots of                        space  .   ";

$strng = trim(preg_replace('/\s+/',' ', $strng));

echo $strng;

Javascript : get <img> src and set as variable?

Use JQuery, its easy.

Include the JQuery library into your html file in the head as such:

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

(Make sure that this script tag goes before your other script tags in your html file)

Target your id in your JavaScript file as such:

<script>
var youtubeimcsrc = $('#youtubeimg').attr('src');

//your var will be the src string that you're looking for

</script>

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use

Don't quote the column filename

mysql> INSERT INTO risks (status, subject, reference_id, location, category, team,    technology, owner, manager, assessment, notes,filename) 
VALUES ('san', 'ss', 1, 1, 1, 1, 2, 1, 1, 'sment', 'notes','santu');

parsing a tab-separated file in Python

You can use the csv module to parse tab seperated value files easily.

import csv

with open("tab-separated-values") as tsv:
    for line in csv.reader(tsv, dialect="excel-tab"): #You can also use delimiter="\t" rather than giving a dialect.
        ... 

Where line is a list of the values on the current row for each iteration.

Edit: As suggested below, if you want to read by column, and not by row, then the best thing to do is use the zip() builtin:

with open("tab-separated-values") as tsv:
    for column in zip(*[line for line in csv.reader(tsv, dialect="excel-tab")]):
        ...

Create unique constraint with null columns

Create two partial indexes:

CREATE UNIQUE INDEX favo_3col_uni_idx ON favorites (user_id, menu_id, recipe_id)
WHERE menu_id IS NOT NULL;

CREATE UNIQUE INDEX favo_2col_uni_idx ON favorites (user_id, recipe_id)
WHERE menu_id IS NULL;

This way, there can only be one combination of (user_id, recipe_id) where menu_id IS NULL, effectively implementing the desired constraint.

Possible drawbacks: you cannot have a foreign key referencing (user_id, menu_id, recipe_id), you cannot base CLUSTER on a partial index, and queries without a matching WHERE condition cannot use the partial index. (It seems unlikely you'd want a FK reference three columns wide - use the PK column instead).

If you need a complete index, you can alternatively drop the WHERE condition from favo_3col_uni_idx and your requirements are still enforced.
The index, now comprising the whole table, overlaps with the other one and gets bigger. Depending on typical queries and the percentage of NULL values, this may or may not be useful. In extreme situations it might even help to maintain all three indexes (the two partial ones and a total on top).

Aside: I advise not to use mixed case identifiers in PostgreSQL.

Single-threaded apartment - cannot instantiate ActiveX control

Go ahead and add [STAThread] to the main entry of your application, this indicates the COM threading model is single-threaded apartment (STA)

example:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new WebBrowser());
    }
}

How do I uniquely identify computers visiting my web site?

Because i want the solution to work on all machines and all browsers (within reason) I am trying to create a solution using javascript.

Isn't that a really good reason not to use javascript?

As others have said - cookies are probably your best option - just be aware of the limitations.

Copy file remotely with PowerShell

From PowerShell version 5 onwards (included in Windows Server 2016, downloadable as part of WMF 5 for earlier versions), this is possible with remoting. The benefit of this is that it works even if, for whatever reason, you can't access shares.

For this to work, the local session where copying is initiated must have PowerShell 5 or higher installed. The remote session does not need to have PowerShell 5 installed -- it works with PowerShell versions as low as 2, and Windows Server versions as low as 2008 R2.[1]

From server A, create a session to server B:

$b = New-PSSession B

And then, still from A:

Copy-Item -FromSession $b C:\Programs\temp\test.txt -Destination C:\Programs\temp\test.txt

Copying items to B is done with -ToSession. Note that local paths are used in both cases; you have to keep track of what server you're on.


[1]: when copying from or to a remote server that only has PowerShell 2, beware of this bug in PowerShell 5.1, which at the time of writing means recursive file copying doesn't work with -ToSession, an apparently copying doesn't work at all with -FromSession.

Opencv - Grayscale mode Vs gray color conversion

Note: This is not a duplicate, because the OP is aware that the image from cv2.imread is in BGR format (unlike the suggested duplicate question that assumed it was RGB hence the provided answers only address that issue)

To illustrate, I've opened up this same color JPEG image:

enter image description here

once using the conversion

img = cv2.imread(path)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

and another by loading it in gray scale mode

img_gray_mode = cv2.imread(path, cv2.IMREAD_GRAYSCALE)

Like you've documented, the diff between the two images is not perfectly 0, I can see diff pixels in towards the left and the bottom

enter image description here

I've summed up the diff too to see

import numpy as np
np.sum(diff)
# I got 6143, on a 494 x 750 image

I tried all cv2.imread() modes

Among all the IMREAD_ modes for cv2.imread(), only IMREAD_COLOR and IMREAD_ANYCOLOR can be converted using COLOR_BGR2GRAY, and both of them gave me the same diff against the image opened in IMREAD_GRAYSCALE

The difference doesn't seem that big. My guess is comes from the differences in the numeric calculations in the two methods (loading grayscale vs conversion to grayscale)

Naturally what you want to avoid is fine tuning your code on a particular version of the image just to find out it was suboptimal for images coming from a different source.

In brief, let's not mix the versions and types in the processing pipeline.

So I'd keep the image sources homogenous, e.g. if you have capturing the image from a video camera in BGR, then I'd use BGR as the source, and do the BGR to grayscale conversion cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

Vice versa if my ultimate source is grayscale then I'd open the files and the video capture in gray scale cv2.imread(path, cv2.IMREAD_GRAYSCALE)

Copying formula to the next row when inserting a new row

Private Sub Worksheet_Change(ByVal Target As Range)

'data starts on row 3 which has the formulas
'the sheet is protected - input cells not locked - formula cells locked
'this routine is triggered on change of any cell on the worksheet so first check if
' it's a cell that we're interested in - and the row doesn't already have formulas
If Target.Column = 3 And Target.Row > 3 _
And Range("M" & Target.Row).Formula = "" Then

    On Error GoTo ERROR_OCCURRED

    'unprotect the sheet - otherwise can't copy and paste
    ActiveSheet.Unprotect
    'disable events - this prevents this routine from triggering again when
    'copy and paste below changes the cell values
    Application.EnableEvents = False

    'copy col D (with validation list) from row above to new row (not locked)
    Range("D" & Target.Row - 1).Copy
    Range("D" & Target.Row).PasteSpecial

    'copy col M to P (with formulas) from row above to new row
    Range("M" & Target.Row - 1 & ":P" & Target.Row - 1).Copy
    Range("M" & Target.Row).PasteSpecial

'make sure if an error occurs (or not) events are re-enabled and sheet re-protected

ERROR_OCCURRED:

    If Err.Number <> 0 Then
        MsgBox "An error occurred. Formulas may not have been copied." & vbCrLf & vbCrLf & _
            Err.Number & " - " & Err.Description
    End If

    're-enable events
    Application.EnableEvents = True
    're-protect the sheet
    ActiveSheet.Protect

    'put focus back on the next cell after routine was triggered
    Range("D" & Target.Row).Select

End If

End Sub

Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?

Another way to wait for maximum of certain amount say 10 seconds of time for the element to be displayed as below:

(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver d) {
                return d.findElement(By.id("<name>")).isDisplayed();

            }
        });

PHP function use variable from outside

Do not forget that you also can pass these use variables by reference.

The use cases are when you need to change the use'd variable from inside of your callback (e.g. produce the new array of different objects from some source array of objects).

$sourcearray = [ (object) ['a' => 1], (object) ['a' => 2]];
$newarray = [];
array_walk($sourcearray, function ($item) use (&$newarray) {
    $newarray[] = (object) ['times2' => $item->a * 2];
});
var_dump($newarray);

Now $newarray will comprise (pseudocode here for brevity) [{times2:2},{times2:4}].

On the contrary, using $newarray with no & modifier would make outer $newarray variable be read-only accessible from within the closure scope. But $newarray within closure scope would be a completelly different newly created variable living only within the closure scope.

Despite both variables' names are the same these would be two different variables. The outer $newarray variable would comprise [] in this case after the code has finishes.

Java 8 Filter Array Using Lambda

Yes, you can do this by creating a DoubleStream from the array, filtering out the negatives, and converting the stream back to an array. Here is an example:

double[] d = {8, 7, -6, 5, -4};
d = Arrays.stream(d).filter(x -> x > 0).toArray();
//d => [8, 7, 5]

If you want to filter a reference array that is not an Object[] you will need to use the toArray method which takes an IntFunction to get an array of the original type as the result:

String[] a = { "s", "", "1", "", "" };
a = Arrays.stream(a).filter(s -> !s.isEmpty()).toArray(String[]::new);

Scala: join an iterable of strings

How about mkString ?

theStrings.mkString(",")

A variant exists in which you can specify a prefix and suffix too.

See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.

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.

Eclipse: How to build an executable jar with external jar?

Try the fat-jar extension. It will include all external jars inside the jar.

Calculate age given the birth date in the format YYYYMMDD

Here's my solution, just pass in a parseable date:

function getAge(birth) {
  ageMS = Date.parse(Date()) - Date.parse(birth);
  age = new Date();
  age.setTime(ageMS);
  ageYear = age.getFullYear() - 1970;

  return ageYear;

  // ageMonth = age.getMonth(); // Accurate calculation of the month part of the age
  // ageDay = age.getDate();    // Approximate calculation of the day part of the age
}

How to use ESLint with Jest

To complete Zachary's answer, here is a workaround for the "extend in overrides" limitation of eslint config :

overrides: [
  Object.assign(
    {
      files: [ '**/*.test.js' ],
      env: { jest: true },
      plugins: [ 'jest' ],
    },
    require('eslint-plugin-jest').configs.recommended
  )
]

From https://github.com/eslint/eslint/issues/8813#issuecomment-320448724

Apk location in New Android Studio

Hello all above all answers are right you can find the apk through the path in android studio but there is exceptions you can't find the build/output folder some times if you can't see it just go to

app--> app.iml file and find below line in it :-

  <excludeFolder url="file://$MODULE_DIR$/build/outputs" />

--> after removing this line you can see the output folder its just the adding more information to above answers as per my experience :)

THANKS!~!

How can I get the current contents of an element in webdriver

I believe prestomanifesto was on the right track. It depends on what kind of element it is. You would need to use element.get_attribute('value') for input elements and element.text to return the text node of an element.

You could check the WebElement object with element.tag_name to find out what kind of element it is and return the appropriate value.

This should help you figure out:

driver = webdriver.Firefox()
driver.get('http://www.w3c.org')
element = driver.find_element_by_name('q')
element.send_keys('hi mom')

element_text = element.text
element_attribute_value = element.get_attribute('value')

print element
print 'element.text: {0}'.format(element_text)
print 'element.get_attribute(\'value\'): {0}'.format(element_attribute_value)
driver.quit()

Change color inside strings.xml

Just add your text between the font tags:

for blue color

<string name="hello_world"><font color='blue'>Hello world!</font></string>

or for red color

<string name="hello_world"><font color='red'>Hello world!</font></string>

How can I plot a histogram such that the heights of the bars sum to 1 in matplotlib?

It would be more helpful if you posed a more complete working (or in this case non-working) example.

I tried the following:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.randn(1000)

fig = plt.figure()
ax = fig.add_subplot(111)
n, bins, rectangles = ax.hist(x, 50, density=True)
fig.canvas.draw()
plt.show()

This will indeed produce a bar-chart histogram with a y-axis that goes from [0,1].

Further, as per the hist documentation (i.e. ax.hist? from ipython), I think the sum is fine too:

*normed*:
If *True*, the first element of the return tuple will
be the counts normalized to form a probability density, i.e.,
``n/(len(x)*dbin)``.  In a probability density, the integral of
the histogram should be 1; you can verify that with a
trapezoidal integration of the probability density function::

    pdf, bins, patches = ax.hist(...)
    print np.sum(pdf * np.diff(bins))

Giving this a try after the commands above:

np.sum(n * np.diff(bins))

I get a return value of 1.0 as expected. Remember that normed=True doesn't mean that the sum of the value at each bar will be unity, but rather than the integral over the bars is unity. In my case np.sum(n) returned approx 7.2767.

How can I show figures separately in matplotlib?

As of November 2020, in order to show one figure at a time, the following works:

import matplotlib.pyplot as plt

f1, ax1 = plt.subplots()
ax1.plot(range(0,10))
f1.show()
input("Close the figure and press a key to continue")
f2, ax2 = plt.subplots()
ax2.plot(range(10,20))
f2.show()
input("Close the figure and press a key to continue")

The call to input() prevents the figure from opening and closing immediately.

The project type is not supported by this installation

I had similar issue with c#, first I found that each project may have a few different types. i.e. in .csproject file locate ProjectTypeGuids, it should be a few guids, i.e.

<ProjectTypeGuids>{F85E285D-A4E0-4152-9332-AB1D724D3325};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>

they will point on component you are missing. In my case it was ASP.NET MVC 2. Some guys get it worked by installing MVC 2 destribution.

My case was worse, because installation didn't work, but it turned out that it was because I had Express 2008 and 2010. I fixed it by uninstalling both 2008 & 2010 and installing only 2010 versions. For c# you need both Visual C# Express and Visual Web Developer express

Submit a form using jQuery

Use it to submit your form using jquery. Here is the link http://api.jquery.com/submit/

<form id="form" method="post" action="#">
    <input type="text" id="input">
    <input type="button" id="button" value="Submit">
</form>

<script type="text/javascript">
$(document).ready(function () {
    $( "#button" ).click(function() {
        $( "#form" ).submit();
    });
});
</script>

Download data url file

_x000D_
_x000D_
function download(dataurl, filename) {_x000D_
  var a = document.createElement("a");_x000D_
  a.href = dataurl;_x000D_
  a.setAttribute("download", filename);_x000D_
  a.click();_x000D_
}_x000D_
_x000D_
download("data:text/html,HelloWorld!", "helloWorld.txt");
_x000D_
_x000D_
_x000D_

or:

_x000D_
_x000D_
function download(url, filename) {_x000D_
fetch(url).then(function(t) {_x000D_
    return t.blob().then((b)=>{_x000D_
        var a = document.createElement("a");_x000D_
        a.href = URL.createObjectURL(b);_x000D_
        a.setAttribute("download", filename);_x000D_
        a.click();_x000D_
    }_x000D_
    );_x000D_
});_x000D_
}_x000D_
_x000D_
download("https://get.geojs.io/v1/ip/geo.json","geoip.json")_x000D_
download("data:text/html,HelloWorld!", "helloWorld.txt");
_x000D_
_x000D_
_x000D_

PHP removing a character in a string

$splitPos = strpos($url, "?/");
if ($splitPos !== false) {
    $url = substr($url, 0, $splitPos) . "?" . substr($url, $splitPos + 2);
}

Make an image width 100% of parent div, but not bigger than its own width

Just specify max-width: 100% alone, that should do it.

Most efficient T-SQL way to pad a varchar on the left to a certain length?

I liked vnRocks solution, here it is in the form of a udf

create function PadLeft(
      @String varchar(8000)
     ,@NumChars int
     ,@PadChar char(1) = ' ')
returns varchar(8000)
as
begin
    return stuff(@String, 1, 0, replicate(@PadChar, @NumChars - len(@String)))
end

Disable cross domain web security in Firefox

For anyone finding this question while using Nightwatch.js (1.3.4), there's an acceptInsecureCerts: true setting in the config file:

_x000D_
_x000D_
firefox: {_x000D_
      desiredCapabilities: {_x000D_
        browserName: 'firefox',_x000D_
        alwaysMatch: {_x000D_
          // Enable this if you encounter unexpected SSL certificate errors in Firefox_x000D_
          acceptInsecureCerts: true,_x000D_
          'moz:firefoxOptions': {_x000D_
            args: [_x000D_
              // '-headless',_x000D_
              // '-verbose'_x000D_
            ],_x000D_
          }_x000D_
        }_x000D_
      }_x000D_
    },
_x000D_
_x000D_
_x000D_

A monad is just a monoid in the category of endofunctors, what's the problem?

The answers here do an excellent job in defining both monoids and monads, however, they still don't seem to answer the question:

And on a less important note, is this true and if so could you give an explanation (hopefully one that can be understood by someone who doesn't have much Haskell experience)?

The crux of the matter that is missing here, is the different notion of "monoid", the so-called categorification more precisely -- the one of monoid in a monoidal category. Sadly Mac Lane's book itself makes it very confusing:

All told, a monad in X is just a monoid in the category of endofunctors of X, with product × replaced by composition of endofunctors and unit set by the identity endofunctor.

Main confusion

Why is this confusing? Because it does not define what is "monoid in the category of endofunctors" of X. Instead, this sentence suggests taking a monoid inside the set of all endofunctors together with the functor composition as binary operation and the identity functor as a monoidal unit. Which works perfectly fine and turns into a monoid any subset of endofunctors that contains the identity functor and is closed under functor composition.

Yet this is not the correct interpretation, which the book fails to make clear at that stage. A Monad f is a fixed endofunctor, not a subset of endofunctors closed under composition. A common construction is to use f to generate a monoid by taking the set of all k-fold compositions f^k = f(f(...)) of f with itself, including k=0 that corresponds to the identity f^0 = id. And now the set S of all these powers for all k>=0 is indeed a monoid "with product × replaced by composition of endofunctors and unit set by the identity endofunctor".

And yet:

  • This monoid S can be defined for any functor f or even literally for any self-map of X. It is the monoid generated by f.
  • The monoidal structure of S given by the functor composition and the identity functor has nothing do with f being or not being a monad.

And to make things more confusing, the definition of "monoid in monoidal category" comes later in the book as you can see from the table of contents. And yet understanding this notion is absolutely critical to understanding the connection with monads.

(Strict) monoidal categories

Going to Chapter VII on Monoids (which comes later than Chapter VI on Monads), we find the definition of the so-called strict monoidal category as triple (B, *, e), where B is a category, *: B x B-> B a bifunctor (functor with respect to each component with other component fixed) and e is a unit object in B, satisfying the associativity and unit laws:

(a * b) * c = a * (b * c)
a * e = e * a = a

for any objects a,b,c of B, and the same identities for any morphisms a,b,c with e replaced by id_e, the identity morphism of e. It is now instructive to observe that in our case of interest, where B is the category of endofunctors of X with natural transformations as morphisms, * the functor composition and e the identity functor, all these laws are satisfied, as can be directly verified.

What comes after in the book is the definition of the "relaxed" monoidal category, where the laws only hold modulo some fixed natural transformations satisfying so-called coherence relations, which is however not important for our cases of the endofunctor categories.

Monoids in monoidal categories

Finally, in section 3 "Monoids" of Chapter VII, the actual definition is given:

A monoid c in a monoidal category (B, *, e) is an object of B with two arrows (morphisms)

mu: c * c -> c
nu: e -> c

making 3 diagrams commutative. Recall that in our case, these are morphisms in the category of endofunctors, which are natural transformations corresponding to precisely join and return for a monad. The connection becomes even clearer when we make the composition * more explicit, replacing c * c by c^2, where c is our monad.

Finally, notice that the 3 commutative diagrams (in the definition of a monoid in monoidal category) are written for general (non-strict) monoidal categories, while in our case all natural transformations arising as part of the monoidal category are actually identities. That will make the diagrams exactly the same as the ones in the definition of a monad, making the correspondence complete.

Conclusion

In summary, any monad is by definition an endofunctor, hence an object in the category of endofunctors, where the monadic join and return operators satisfy the definition of a monoid in that particular (strict) monoidal category. Vice versa, any monoid in the monoidal category of endofunctors is by definition a triple (c, mu, nu) consisting of an object and two arrows, e.g. natural transformations in our case, satisfying the same laws as a monad.

Finally, note the key difference between the (classical) monoids and the more general monoids in monoidal categories. The two arrows mu and nu above are not anymore a binary operation and a unit in a set. Instead, you have one fixed endofunctor c. The functor composition * and the identity functor alone do not provide the complete structure needed for the monad, despite that confusing remark in the book.

Another approach would be to compare with the standard monoid C of all self-maps of a set A, where the binary operation is the composition, that can be seen to map the standard cartesian product C x C into C. Passing to the categorified monoid, we are replacing the cartesian product x with the functor composition *, and the binary operation gets replaced with the natural transformation mu from c * c to c, that is a collection of the join operators

join: c(c(T))->c(T)

for every object T (type in programming). And the identity elements in classical monoids, which can be identified with images of maps from a fixed one-point-set, get replaced with the collection of the return operators

return: T->c(T) 

But now there are no more cartesian products, so no pairs of elements and thus no binary operations.

Throw HttpResponseException or return Request.CreateErrorResponse?

If you are not returning HttpResponseMessage and instead are returning entity/model classes directly, an approach which I have found useful is to add the following utility function to my controller

private void ThrowResponseException(HttpStatusCode statusCode, string message)
{
    var errorResponse = Request.CreateErrorResponse(statusCode, message);
    throw new HttpResponseException(errorResponse);
}

and simply call it with the appropriate status code and message

How to finish Activity when starting other activity in Android?

Intent i = new Intent(this,Here is your first activity.Class);
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(i);
    finish();

How do I quickly rename a MySQL database (change schema name)?

ALTER DATABASE is the proposed way around this by MySQL and RENAME DATABASE is dropped.

From 13.1.32 RENAME DATABASE Syntax:

RENAME {DATABASE | SCHEMA} db_name TO new_db_name;

This statement was added in MySQL 5.1.7, but it was found to be dangerous and was removed in MySQL 5.1.23.

AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?

As answered by @Dark Falcon, I simply dealt with it.

In my case, I am using node.js server, and creating a session if it does not exist. Since the OPTIONS method does not have the session details in it, it ended up creating a new session for every POST method request.

So in my app routine to create-session-if-not-exist, I just added a check to see if method is OPTIONS, and if so, just skip session creating part:

    app.use(function(req, res, next) {
        if (req.method !== "OPTIONS") {
            if (req.session && req.session.id) {
                 // Session exists
                 next();
            }else{
                 // Create session
                 next();
          }
        } else {
           // If request method is OPTIONS, just skip this part and move to the next method.
           next(); 
        }
    }

Dynamically generating a QR code with PHP

I have been using google qrcode api for sometime, but I didn't quite like this because it requires me to be on the Internet to access the generated image.

I did a little comand-line research and found out that linux has a command line tool qrencode for generating qr-codes.

I wrote this little script. And the good part is that the generated image is less than 1KB in size. Well the supplied data is simply a url.

$url = ($_SERVER['HTTPS'] ? "https://" : "http://").$_SERVER['HTTP_HOST'].'/profile.php?id='.$_GET['pid'];
$img = shell_exec('qrencode --output=- -m=1 '.escapeshellarg($url));

$imgData = "data:image/png;base64,".base64_encode($img);

Then in the html I load the image:

<img class="emrQRCode" src="<?=$imgData ?>" />

You just need to have installed it. [most imaging apps on linux would have installed it under the hood without you realizing.

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

I didn't figure out what exactly was happening, but I found a solution.

The CDN feature of OVH was the culprit. I had it installed on my host service but disabled for my domain because I didn't need it.

Somehow, when I enable it, everything works.

I think it forces Apache to use the HTTP2 protocol, but what I don't understand is that there indeed was an HTTP2 mention in each of my headers, which I presume means the server was answering using the right protocol.

So the solution for my very particular case was to enable the CDN option on all concerned domains.

If anyone understands better what could have happened here, feel free to share explanations.

How to implement oauth2 server in ASP.NET MVC 5 and WEB API 2

Gmail: OAuth

  • Goto the link
  • Login with your gmail username password
  • Click on the google menu at the top left
  • Click API Manager
  • Click on Credentials
  • Click Create Credentials and select OAuth Client
  • Select Web Application as Application type and Enter the Name-> Enter Authorised Redirect URL (Eg: http://localhost:53922/signin-google) ->Click on Create button. This will create the credentials. Pls make a note of Client ID and Secret ID. Finally click OK to close the credentials pop up.
  • Next important step is to enable the Google API. Click on Overview in the left pane.
  • Click on the Google API under Social APIs section.
  • Click Enable.

That’s all from the Google part.

Come back to your application, open App_start/Startup.Auth.cs and uncomment the following snippet

        app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
        {
            ClientId = "",
            ClientSecret = ""
        });

Update the ClientId and ClientSecret with the values from Google API credentials which you have created already.

  • Run your application
  • Click Login
  • You will see the Google button under ‘Use Another Section to log in’ section
  • Click on the Google button
  • Application will prompt you to enter the username and password
  • Enter the gmail username and password and click Sign In
  • This will perform the OAuth and come back to your application and prompting you to register with the Gmail id.
  • Click register to register the Gmail id into your application database.
  • You will see the Identity details appear in the top as normal registration
  • Try logout and login again thru Gmail. This will automatically logs you into the app.

How do I set the value property in AngularJS' ng-options?

If you want to change the value of your option elements because the form will eventually be submitted to the server, instead of doing this,

<select name="text" ng-model="text" ng-options="select p.text for p in resultOptions"></select>

You can do this:

<select ng-model="text" ng-options="select p.text for p in resultOptions"></select>
<input type="hidden" name="text" value="{{ text }}" />

The expected value will then be sent through the form under the correct name.

Bash script to run php script

If you don't do anything in your bash script than run the php one, you could simply run the php script from cron with a command like /usr/bin/php /path/to/your/file.php.

no matching function for call to ' '

You are trying to pass pointers (which you do not delete, thus leaking memory) where references are needed. You do not really need pointers here:

Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);

cout << "Numarul complex este: " << firstComplexNumber << endl;
//                                  ^^^^^^^^^^^^^^^^^^ No need to dereference now

// ...

Complex::distanta(firstComplexNumber, secondComplexNumber);

Make div (height) occupy parent remaining height

Abstract

I didn't find a fully satisfying answer so I had to find it out myself.

My requirements:

  • the element should take exactly the remaining space either when its content size is smaller or bigger than the remaining space size (in the second case scrollbar should be shown);
  • the solution should work when the parent height is computed, and not specified;
  • calc() should not be used as the remaining element shouldn't know anything about another element sizes;
  • modern and familar layout technique such as flexboxes should be used.

The solution

  • Turn into flexboxes all direct parents with computed height (if any) and the next parent whose height is specified;
  • Specify flex-grow: 1 to all direct parents with computed height (if any) and the element so they will take up all remaining space when the element content size is smaller;
  • Specify flex-shrink: 0 to all flex items with fixed height so they won't become smaller when the element content size is bigger than the remaining space size;
  • Specify overflow: hidden to all direct parents with computed height (if any) to disable scrolling and forbid displaying overflow content;
  • Specify overflow: auto to the element to enable scrolling inside it.

JSFiddle (element has direct parents with computed height)

JSFiddle (simple case: no direct parents with computed height)

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

As android latest update doesn't support 'compile' keyword use 'implementation' in place inside your module build.gradle file.

And check thoroughly in build.gradle for dependancy with + sign like this.

implementation 'com.android.support:support-v4:28.+'

If there are any dependencies like this, just update them with a specific version. After that:

  1. Sync gradle.
  2. Clean your project.
  3. Rebuild the project.

Speed tradeoff of Java's -Xms and -Xmx options

The speed tradeoffs between various settings of -Xms and -Xmx depend on the application and system that you run your Java application on. It also depends on your JVM and other garbage collection parameters you use.

This question is 11 years old, and since then the effects of the JVM parameters on performance have become even harder to predict in advance. So you can try different values and see the effects on performance, or use a free tool like Optimizer Studio that will find the optimal JVM parameter values automatically.

How to use css style in php

css :hover kinda is like js onmouseover

row1 {
    // your css
}
row1:hover {
    color: red;
}
row1:hover #a, .b, .c:nth-child[3] {
    border: 1px solid red;
}

not too sure how it works but css applies styles to echo'ed ids

How to use PowerShell select-string to find more than one pattern in a file?

To search for multiple matches in each file, we can sequence several Select-String calls:

Get-ChildItem C:\Logs |
  where { $_ | Select-String -Pattern 'VendorEnquiry' } |
  where { $_ | Select-String -Pattern 'Failed' } |
  ...

At each step, files that do not contain the current pattern will be filtered out, ensuring that the final list of files contains all of the search terms.

Rather than writing out each Select-String call manually, we can simplify this with a filter to match multiple patterns:

filter MultiSelect-String( [string[]]$Patterns ) {
  # Check the current item against all patterns.
  foreach( $Pattern in $Patterns ) {
    # If one of the patterns does not match, skip the item.
    $matched = @($_ | Select-String -Pattern $Pattern)
    if( -not $matched ) {
      return
    }
  }

  # If all patterns matched, pass the item through.
  $_
}

Get-ChildItem C:\Logs | MultiSelect-String 'VendorEnquiry','Failed',...


Now, to satisfy the "Logtime about 11:30 am" part of the example would require finding the log time corresponding to each failure entry. How to do this is highly dependent on the actual structure of the files, but testing for "about" is relatively simple:

function AboutTime( [DateTime]$time, [DateTime]$target, [TimeSpan]$epsilon ) {
  $time -le ($target + $epsilon) -and $time -ge ($target - $epsilon)
}

PS> $epsilon = [TimeSpan]::FromMinutes(5)
PS> $target = [DateTime]'11:30am'
PS> AboutTime '11:00am' $target $epsilon
False
PS> AboutTime '11:28am' $target $epsilon
True
PS> AboutTime '11:35am' $target $epsilon
True

Run a shell script with an html button

As stated by Luke you need to use a server side language, like php. This is a really simple php example:

<?php
if ($_GET['run']) {
  # This code will run if ?run=true is set.
  exec("/path/to/name.sh");
}
?>

<!-- This link will add ?run=true to your URL, myfilename.php?run=true -->
<a href="?run=true">Click Me!</a>

Save this as myfilename.php and place it on a machine with a web server with php installed. The same thing can be accomplished with asp, java, ruby, python, ...

SQL for ordering by number - 1,2,3,4 etc instead of 1,10,11,12

I assume your column type is STRING (CHAR, VARCHAR, etc) and sorting procedure is sorting it as a string. What you need to do is to convert value into numeric value. How to do it will depend on SQL system you use.

Multiple models in a view

a simple way to do that

we can call all model first

@using project.Models

then send your model with viewbag

// for list
ViewBag.Name = db.YourModel.ToList();

// for one
ViewBag.Name = db.YourModel.Find(id);

and in view

// for list
List<YourModel> Name = (List<YourModel>)ViewBag.Name ;

//for one
YourModel Name = (YourModel)ViewBag.Name ;

then easily use this like Model

Getting the actual usedrange

What sort of button, neither a Forms Control nor an ActiveX control should affect the used range.

It is a known problem that excel does not keep track of the used range very well. Any reference to the used range via VBA will reset the value to the current used range. So try running this sub procedure:

Sub ResetUsedRng()
    Application.ActiveSheet.UsedRange 
End Sub 

Failing that you may well have some formatting hanging round. Try clearing/deleting all the cells after your last row.

Regarding the above also see:

Excel Developer Tip

Another method to find the last used cell:

    Dim rLastCell As Range

    Set rLastCell = ActiveSheet.Cells.Find(What:="*", After:=.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _
    xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False)

Change the search direction to find the first used cell.

Get item in the list in Scala?

Please use parenthesis () to access the list elements list_name(index)

The right way of setting <a href=""> when it's a local file

By definition, file: URLs are system-dependent, and they have little use. A URL as in your example works when used locally, i.e. the linking page itself is in the user’s computer. But browsers generally refuse to follow file: links on a page that it has fetched with the HTTP protocol, so that the page's own URL is an http: URL. When you click on such a link, nothing happens. The purpose is presumably security: to prevent a remote page from accessing files in the visitor’s computer. (I think this feature was first implemented in Mozilla, then copied to other browsers.)

So if you work with HTML documents in your computer, the file: URLs should work, though there are system-dependent issues in their syntax (how you write path names and file names in such a URL).

If you really need to work with an HTML document on your computers and another HTML document on a web server, the way to make links work is to use the local file as primary and, if needed, use client-side scripting to fetch the document from the server,

Creating custom function in React component

You can try this.

// Author: Hannad Rehman Sat Jun 03 2017 12:59:09 GMT+0530 (India Standard Time)

import React from 'react';
import RippleButton from '../../Components/RippleButton/rippleButton.jsx';

class HtmlComponents extends React.Component {

    constructor(props){
        super(props);
        this.rippleClickFunction=this.rippleClickFunction.bind(this);
    }

    rippleClickFunction(){
        //do stuff. 
        // foo==bar
    }

    render() {
      return (
         <article>
             <h1>React Components</h1>
             <RippleButton onClick={this.rippleClickFunction}/>
         </article>
      );
   }
}

export default HtmlComponents;

Yhe only concern is you have to bind the context to the function

Check if two lists are equal

List<T> equality does not check them element-by-element. You can use LINQ's SequenceEqual method for that:

var a = ints1.SequenceEqual(ints2);

To ignore order, use SetEquals:

var a = new HashSet<int>(ints1).SetEquals(ints2);

This should work, because you are comparing sequences of IDs, which do not contain duplicates. If it does, and you need to take duplicates into account, the way to do it in linear time is to compose a hash-based dictionary of counts, add one for each element of the first sequence, subtract one for each element of the second sequence, and check if the resultant counts are all zeros:

var counts = ints1
    .GroupBy(v => v)
    .ToDictionary(g => g.Key, g => g.Count());
var ok = true;
foreach (var n in ints2) {
    int c;
    if (counts.TryGetValue(n, out c)) {
        counts[n] = c-1;
    } else {
        ok = false;
        break;
    }
}
var res = ok && counts.Values.All(c => c == 0);

Finally, if you are fine with an O(N*LogN) solution, you can sort the two sequences, and compare them for equality using SequenceEqual.

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

There is a really simple way to solve this. If you use the newish 'Set' javascript command. Set can take an array as input and output a new 'Set' that only contains unique values. Then by comparing the length of the array and the 'size' property of the set you can see if they differ. If they differ it must be due to a duplicate entry.

_x000D_
_x000D_
var array1 = ['value1','value2','value3','value1']; // contains duplicates_x000D_
var array2 = ['value1','value2','value3','value4']; // unique values_x000D_
_x000D_
console.log('array1 contains duplicates = ' + containsDuplicates(array1));_x000D_
console.log('array2 contains duplicates = ' + containsDuplicates(array2));_x000D_
_x000D_
_x000D_
function containsDuplicates(passedArray) {_x000D_
  let mySet = new Set(passedArray);_x000D_
  if (mySet.size !== passedArray.length) {_x000D_
    return true;_x000D_
  }_x000D_
  return false;_x000D_
}
_x000D_
_x000D_
_x000D_

If you run the above snippet you will get this output.

array1 contains duplicates = true

array2 contains duplicates = false

How do I print uint32_t and uint16_t variables value?

The macros defined in <inttypes.h> are the most correct way to print values of types uint32_t, uint16_t, and so forth -- but they're not the only way.

Personally, I find those macros difficult to remember and awkward to use. (Given the syntax of a printf format string, that's probably unavoidable; I'm not claiming I could have come up with a better system.)

An alternative is to cast the values to a predefined type and use the format for that type.

Types int and unsigned int are guaranteed by the language to be at least 16 bits wide, and therefore to be able to hold any converted value of type int16_t or uint16_t, respectively. Similarly, long and unsigned long are at least 32 bits wide, and long long and unsigned long long are at least 64 bits wide.

For example, I might write your program like this (with a few additional tweaks):

#include <stdio.h>
#include <stdint.h>
#include <netinet/in.h>  

int main(void)
{
    uint32_t a=12, a1;
    uint16_t b=1, b1;
    a1 = htonl(a);
    printf("%lu---------%lu\n", (unsigned long)a, (unsigned long)a1);
    b1 = htons(b);
    printf("%u-----%u\n", (unsigned)b, (unsigned)b1);
    return 0;
}

One advantage of this approach is that it can work even with pre-C99 implementations that don't support <inttypes.h>. Such an implementation most likely wouldn't have <stdint.h> either, but the technique is useful for other integer types.

Is String.Contains() faster than String.IndexOf()?

By using Reflector, you can see, that Contains is implemented using IndexOf. Here's the implementation.

public bool Contains(string value)
{
   return (this.IndexOf(value, StringComparison.Ordinal) >= 0);
}

So Contains is likely a wee bit slower than calling IndexOf directly, but I doubt that it will have any significance for the actual performance.

Convert PDF to image with high resolution

Personally I like this.

convert -density 300 -trim test.pdf -quality 100 test.jpg

It's a little over twice the file size, but it looks better to me.

-density 300 sets the dpi that the PDF is rendered at.

-trim removes any edge pixels that are the same color as the corner pixels.

-quality 100 sets the JPEG compression quality to the highest quality.

Things like -sharpen don't work well with text because they undo things your font rendering system did to make it more legible.

If you actually want it blown up use resize here and possibly a larger dpi value of something like targetDPI * scalingFactor That will render the PDF at the resolution/size you intend.

Descriptions of the parameters on imagemagick.org are here

Changing Jenkins build number

For multibranch pipeline projects, do this in the script console:

def project = Jenkins.instance.getItemByFullName("YourMultibranchPipelineProjectName")    
project.getAllJobs().each{ item ->   
    
    if(item.name == 'jobName'){ // master, develop, feature/......
      
      item.updateNextBuildNumber(#Number);
      item.saveNextBuildNumber();
      
      println('new build: ' + item.getNextBuildNumber())
    }
}

RuntimeError on windows trying python multiprocessing

Try putting your code inside a main function in testMain.py

import parallelTestModule

if __name__ ==  '__main__':
  extractor = parallelTestModule.ParallelExtractor()
  extractor.runInParallel(numProcesses=2, numThreads=4)

See the docs:

"For an explanation of why (on Windows) the if __name__ == '__main__' 
part is necessary, see Programming guidelines."

which say

"Make sure that the main module can be safely imported by a new Python interpreter without causing unintended side effects (such a starting a new process)."

... by using if __name__ == '__main__'

BULK INSERT with identity (auto-increment) column

Add an id column to the csv file and leave it blank:

id,Name,Address
,name1,addr test 1
,name2,addr test 2

Remove KEEPIDENTITY keyword from query:

BULK INSERT Employee  FROM 'path\tempFile.csv ' 
WITH (FIRSTROW = 2,FIELDTERMINATOR = ',' , ROWTERMINATOR = '\n');

The id identity field will be auto-incremented.

If you assign values to the id field in the csv, they'll be ignored unless you use the KEEPIDENTITY keyword, then they'll be used instead of auto-increment.

One DbContext per web request... why?

There are two contradicting recommendations by microsoft and many people use DbContexts in a completely divergent manner.

  1. One recommendation is to "Dispose DbContexts as soon as posible" because having a DbContext Alive occupies valuable resources like db connections etc....
  2. The other states that One DbContext per request is highly reccomended

Those contradict to each other because if your Request is doing a lot of unrelated to the Db stuff , then your DbContext is kept for no reason. Thus it is waste to keep your DbContext alive while your request is just waiting for random stuff to get done...

So many people who follow rule 1 have their DbContexts inside their "Repository pattern" and create a new Instance per Database Query so X*DbContext per Request

They just get their data and dispose the context ASAP. This is considered by MANY people an acceptable practice. While this has the benefits of occupying your db resources for the minimum time it clearly sacrifices all the UnitOfWork and Caching candy EF has to offer.

Keeping alive a single multipurpose instance of DbContext maximizes the benefits of Caching but since DbContext is not thread safe and each Web request runs on it's own thread, a DbContext per Request is the longest you can keep it.

So EF's team recommendation about using 1 Db Context per request it's clearly based on the fact that in a Web Application a UnitOfWork most likely is going to be within one request and that request has one thread. So one DbContext per request is like the ideal benefit of UnitOfWork and Caching.

But in many cases this is not true. I consider Logging a separate UnitOfWork thus having a new DbContext for Post-Request Logging in async threads is completely acceptable

So Finally it turns down that a DbContext's lifetime is restricted to these two parameters. UnitOfWork and Thread

Laravel Blade html image

Had the same problem with laravel 5.3... This is how I did it and very easy. for example logo in the blade page view

****<image img src="/img/logo.png" alt="Logo"></image>****

Proper way to assert type of variable in Python

You might want to try this example for version 2.6 of Python.

def my_print(text, begin, end):
    "Print text in UPPER between 'begin' and 'end' in lower."
    for obj in (text, begin, end):
        assert isinstance(obj, str), 'Argument of wrong type!'
    print begin.lower() + text.upper() + end.lower()

However, have you considered letting the function fail naturally instead?

Open firewall port on CentOS 7

Hello in Centos 7 firewall-cmd. Yes correct if you use firewall-cmd --zone=public --add-port=2888/tcp but if you reload firewal firewall-cmd --reload

your config not will be save

you need to add key

firewall-cmd --permanent --zone=public --add-port=2888/tcp

Can my enums have friendly names?

I suppose that you want to show your enum values to the user, therefore, you want them to have some friendly name.

Here's my suggestion:

Use an enum type pattern. Although it takes some effort to implement, it is really worth it.

public class MyEnum
{  
    public static readonly MyEnum Enum1=new MyEnum("This will work",1);
    public static readonly MyEnum Enum2=new MyEnum("This.will.work.either",2);
    public static readonly MyEnum[] All=new []{Enum1,Enum2};
    private MyEnum(string name,int value)
    {
        Name=name;
        Value=value;
    }

    public string Name{get;set;}
    public int Value{get;set;}

    public override string ToString()
    {
        return Name;    
    }
}

How to uncheck checkbox using jQuery Uniform library

If you are using uniform 1.5 then use this simple trick to add or remove attribute of check
Just add value="check" in your checkbox's input field.
Add this code in uniform.js > function doCheckbox(elem){ > .click(function(){

if ( $(elem+':checked').val() == 'check' ) {
    $(elem).attr('checked','checked');           
}
else {
    $(elem).removeAttr('checked');
}   

if you not want to add value="check" in your input box because in some cases you add two checkboxes so use this

if ($(elem).is(':checked')) {
 $(elem).attr('checked','checked');
}    
else
{    
 $(elem).removeAttr('checked');
}

If you are using uniform 2.0 then use this simple trick to add or remove attribute of check
in this classUpdateChecked($tag, $el, options) { function change

if ($el.prop) {
    // jQuery 1.6+
    $el.prop(c, isChecked);
}

To

if ($el.prop) {
    // jQuery 1.6+
    $el.prop(c, isChecked);
    if (isChecked) {
        $el.attr(c, c);
    } else {
        $el.removeAttr(c);
    }

}

How to configure welcome file list in web.xml

I saw a nice solution in this stackoverflow link that may help the readers of the defulat servlet handling issue by using the empty string URL pattern "" :

@WebServlet("")

or

<servlet-mapping>
    <servlet-name>yourHomeServlet</servlet-name>
    <url-pattern></url-pattern> <!-- Yes, empty string! -->
</servlet-mapping>

Postgresql - change the size of a varchar column to lower length

Here's the cache of the page described by Greg Smith. In case that dies as well, the alter statement looks like this:

UPDATE pg_attribute SET atttypmod = 35+4
WHERE attrelid = 'TABLE1'::regclass
AND attname = 'COL1';

Where your table is TABLE1, the column is COL1 and you want to set it to 35 characters (the +4 is needed for legacy purposes according to the link, possibly the overhead referred to by A.H. in the comments).

How do I make a fixed size formatted string in python?

Sure, use the .format method. E.g.,

print('{:10s} {:3d}  {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d}  {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d}  {:7.2f}'.format('zz', 42, 123.34))

will print

xxx        123    98.00
yyyy         3     1.00
zz          42   123.34

You can adjust the field sizes as desired. Note that .format works independently of print to format a string. I just used print to display the strings. Brief explanation:

10s format a string with 10 spaces, left justified by default

3d format an integer reserving 3 spaces, right justified by default

7.2f format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.

There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.

Update for f-string mode. E.g.,

text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d}  {other_number:7.2f}')

For right alignment

print(f'{text:>10} {number:3d}  {other_number:7.2f}')

How can one create an overlay in css?

I was just playing around with a similar problem on codepen, this is what I did to create an overlay using a simple css markup. I created a div element with class .box applied to it. Inside this div I created two divs, one with .inner class applied to it and the other with .notext class applied to it. Both of these classes inside the .box div are initially set to display:none but when the .box is hovered over, these are made visible.

_x000D_
_x000D_
.box{_x000D_
  height:450px;_x000D_
  width:450px;_x000D_
  border:1px solid black;_x000D_
  margin-top:50px;_x000D_
  display:inline-block;_x000D_
  margin-left:50px;_x000D_
  transition: width 2s, height 2s;_x000D_
  position:relative;_x000D_
  text-align: center;_x000D_
    background:url('https://upload.wikimedia.org/wikipedia/commons/c/cd/Panda_Cub_from_Wolong,_Sichuan,_China.JPG');_x000D_
  background-size:cover;_x000D_
  background-position:center;_x000D_
  _x000D_
}_x000D_
.box:hover{_x000D_
  width:490px;_x000D_
  height:490px;_x000D_
}_x000D_
.inner{_x000D_
  border:1px solid red;_x000D_
  position:relative;_x000D_
  width:100%;_x000D_
  height:100%;_x000D_
  top:0px;_x000D_
  left:0px;_x000D_
  display:none; _x000D_
  color:white;_x000D_
  font-size:xx-large;_x000D_
  z-index:10;_x000D_
}_x000D_
.box:hover > .inner{_x000D_
  display:inline-block;_x000D_
}_x000D_
.notext{_x000D_
  height:30px;_x000D_
  width:30px;_x000D_
  border:1px solid blue;_x000D_
  position:absolute;_x000D_
  top:0px;_x000D_
  left:0px;_x000D_
  width:100%;_x000D_
  height:100%;_x000D_
  display:none;_x000D_
}_x000D_
.box:hover > .notext{_x000D_
  background-color:black;_x000D_
  opacity:0.5;_x000D_
  display:inline-block;_x000D_
}
_x000D_
<div class="box">_x000D_
  <div class="inner">_x000D_
    <p>Panda!</p>_x000D_
  </div>_x000D_
  <div class="notext"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Hope this helps! :) Any suggestions are welcome.

startsWith() and endsWith() functions in PHP

Here’s an efficient solution for PHP 4. You could get faster results if on PHP 5 by using substr_compare instead of strcasecmp(substr(...)).

function stringBeginsWith($haystack, $beginning, $caseInsensitivity = false)
{
    if ($caseInsensitivity)
        return strncasecmp($haystack, $beginning, strlen($beginning)) === 0;
    else
        return strncmp($haystack, $beginning, strlen($beginning)) === 0;
}

function stringEndsWith($haystack, $ending, $caseInsensitivity = false)
{
    if ($caseInsensitivity)
        return strcasecmp(substr($haystack, strlen($haystack) - strlen($ending)), $haystack) === 0;
    else
        return strpos($haystack, $ending, strlen($haystack) - strlen($ending)) !== false;
}

How to terminate a Python script

Another way is:

raise SystemExit

How to find all trigger associated with a table with SQL Server?

select * from information_schema.TRIGGERS;

How can I login to a website with Python?

Web page automation ? Definitely "webbot"

webbot even works web pages which have dynamically changing id and classnames and has more methods and features than selenium or mechanize.

Here's a snippet :)

from webbot import Browser 
web = Browser()
web.go_to('google.com') 
web.click('Sign in')
web.type('[email protected]' , into='Email')
web.click('NEXT' , tag='span')
web.type('mypassword' , into='Password' , id='passwordFieldId') # specific selection
web.click('NEXT' , tag='span') # you are logged in ^_^

The docs are also pretty straight forward and simple to use : https://webbot.readthedocs.io

java build path problems

  1. Right click on project, Properties, Java Build Path.
  2. Remove the current JRE library.
  3. Click Add library > JRE System Library > Workspace default JRE.

How to show MessageBox on asp.net?

One of the options is to use the Javascript.

Here is a quick reference where you can start from.

Javascript alert messages

Ruby/Rails: converting a Date to a UNIX timestamp

The code date.to_time.to_i should work fine. The Rails console session below shows an example:

>> Date.new(2009,11,26).to_time
=> Thu Nov 26 00:00:00 -0800 2009
>> Date.new(2009,11,26).to_time.to_i
=> 1259222400
>> Time.at(1259222400)
=> Thu Nov 26 00:00:00 -0800 2009

Note that the intermediate DateTime object is in local time, so the timestamp might be a several hours off from what you expect. If you want to work in UTC time, you can use the DateTime's method "to_utc".

Getting Unexpected Token Export

My two cents

Export

ES6

myClass.js

export class MyClass1 {
}
export class MyClass2 {
}

other.js

import { MyClass1, MyClass2 } from './myClass';

CommonJS Alternative

myClass.js

class MyClass1 {
}
class MyClass2 {
}
module.exports = { MyClass1, MyClass2 }
// or
// exports = { MyClass1, MyClass2 };

other.js

const { MyClass1, MyClass2 } = require('./myClass');

Export Default

ES6

myClass.js

export default class MyClass {
}

other.js

import MyClass from './myClass';

CommonJS Alternative

myClass.js

module.exports = class MyClass1 {
}

other.js

const MyClass = require('./myClass');

Hope this helps

How do I get a class instance of generic type T?

Imagine you have an abstract superclass that is generic:

public abstract class Foo<? extends T> {}

And then you have a second class that extends Foo with a generic Bar that extends T:

public class Second extends Foo<Bar> {}

You can get the class Bar.class in the Foo class by selecting the Type (from bert bruynooghe answer) and infering it using Class instance:

Type mySuperclass = myFoo.getClass().getGenericSuperclass();
Type tType = ((ParameterizedType)mySuperclass).getActualTypeArguments()[0];
//Parse it as String
String className = tType.toString().split(" ")[1];
Class clazz = Class.forName(className);

You have to note this operation is not ideal, so it is a good idea to cache the computed value to avoid multiple calculations on this. One of the typical uses is in generic DAO implementation.

The final implementation:

public abstract class Foo<T> {

    private Class<T> inferedClass;

    public Class<T> getGenericClass(){
        if(inferedClass == null){
            Type mySuperclass = getClass().getGenericSuperclass();
            Type tType = ((ParameterizedType)mySuperclass).getActualTypeArguments()[0];
            String className = tType.toString().split(" ")[1];
            inferedClass = Class.forName(className);
        }
        return inferedClass;
    }
}

The value returned is Bar.class when invoked from Foo class in other function or from Bar class.

get value from DataTable

It looks like you have accidentally declared DataType as an array rather than as a string.

Change line 3 to:

Dim DataType As String = myTableData.Rows(i).Item(1)

That should work.

jquery change class name

In the event that you already have a class and need to alternate between classes as oppose to add a class, you can chain toggle events:

$('li.multi').click(function(e) {
    $(this).toggleClass('opened').toggleClass('multi-opened');
});

PHP foreach loop through multidimensional array

If you mean the first and last entry of the array when talking about a.first and a.last, it goes like this:

foreach ($arr_nav as $inner_array) {
    echo reset($inner_array); //apple, orange, pear
    echo end($inner_array); //My Apple, View All Oranges, A Pear
}

arrays in PHP have an internal pointer which you can manipulate with reset, next, end. Retrieving keys/values works with key and current, but using each might be better in many cases..

ssh script returns 255 error

It can very much be an ssh-agent issue. Check whether there is an ssh-agent PID currently running with eval "$(ssh-agent -s)"

Check whether your identity is added with ssh-add -l and if not, add it with ssh-add <pathToYourRSAKey>.

Then try again your ssh command (or any other command that spawns ssh daemons, like autossh for example) that returned 255.

"Exception has been thrown by the target of an invocation" error (mscorlib)

This can happen when invoking a method that doesn't exist.

MongoDB Aggregation: How to get total records count?

I needed the absolute total count after applying the aggregation. This worked for me:

db.mycollection.aggregate([
    {
        $group: { 
            _id: { field1: "$field1", field2: "$field2" },
        }
    },
    { 
        $group: { 
            _id: null, count: { $sum: 1 } 
        } 
    }
])

Result:

{
    "_id" : null,
    "count" : 57.0
}

Create an enum with string values

This works for me:

class MyClass {
    static MyEnum: { Value1; Value2; Value3; }
    = {
        Value1: "Value1",
        Value2: "Value2",
        Value3: "Value3"
    };
}

or

module MyModule {
    export var MyEnum: { Value1; Value2; Value3; }
    = {
        Value1: "Value1",
        Value2: "Value2",
        Value3: "Value3"
    };
}

8)

Update: Shortly after posting this I discovered another way, but forgot to post an update (however, someone already did mentioned it above):

enum MyEnum {
    value1 = <any>"value1 ", 
    value2 = <any>"value2 ", 
    value3 = <any>"value3 " 
}

Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610

Please

  1. locate the file [XAMPP Installation Directory]\php\php.ini (e.g. C:\xampp\php\php.ini)
  2. open php.ini in Notepad or any Text editor
  3. locate the line containing max_execution_time and
  4. increase the value from 30 to some larger number (e.g. set: max_execution_time = 90)
  5. then restart Apache web server from the XAMPP control panel

If there will still be the same error after that, try to increase the value for the max_execution_time further more.

In PHP with PDO, how to check the final SQL parametrized query?

I initially avoided turning on logging to monitor PDO because I thought that it would be a hassle but it is not hard at all. You don't need to reboot MySQL (after 5.1.9):

Execute this SQL in phpMyAdmin or any other environment where you may have high db privileges:

SET GLOBAL general_log = 'ON';

In a terminal, tail your log file. Mine was here:

>sudo tail -f /usr/local/mysql/data/myMacComputerName.log

You can search for your mysql files with this terminal command:

>ps auxww|grep [m]ysqld

I found that PDO escapes everything, so you can't write

$dynamicField = 'userName';
$sql = "SELECT * FROM `example` WHERE `:field` = :value";
$this->statement = $this->db->prepare($sql);
$this->statement->bindValue(':field', $dynamicField);
$this->statement->bindValue(':value', 'mick');
$this->statement->execute();

Because it creates:

SELECT * FROM `example` WHERE `'userName'` = 'mick' ;

Which did not create an error, just an empty result. Instead I needed to use

$sql = "SELECT * FROM `example` WHERE `$dynamicField` = :value";

to get

SELECT * FROM `example` WHERE `userName` = 'mick' ;

When you are done execute:

SET GLOBAL general_log = 'OFF';

or else your logs will get huge.

tell pip to install the dependencies of packages listed in a requirement file

simplifily, use:

pip install -r requirement.txt

it can install all listed in requirement file.

Print text instead of value from C enum

i'm new to this but a switch statement will defenitely work

#include <stdio.h>

enum mycolor;

int main(int argc, const char * argv[])

{
enum Days{Sunday=1,Monday=2,Tuesday=3,Wednesday=4,Thursday=5,Friday=6,Saturday=7};

enum Days TheDay;


printf("Please enter the day of the week (0 to 6)\n");

scanf("%d",&TheDay);

switch (TheDay)
 {

case Sunday:
        printf("the selected day is sunday");
        break;
    case Monday:
        printf("the selected day is monday");
        break;
    case Tuesday:
        printf("the selected day is Tuesday");
        break;
    case Wednesday:
        printf("the selected day is Wednesday");
        break;
    case Thursday:
        printf("the selected day is thursday");
        break;
    case Friday:
        printf("the selected day is friday");
        break;
    case Saturday:
        printf("the selected day is Saturaday");
        break;
    default:
        break;
}

return 0;
}

PHP sessions that have already been started

Try

<?php
    if(!isset($_SESSION)) 
    { 
        session_start(); 
    } 
?>

Is there any way to show a countdown on the lockscreen of iphone?

A today extension would be the most fitting solution.

Also you could do something on the lock screen with local notifications queued up to fire at regular intervals showing the latest countdown value.

vue.js 'document.getElementById' shorthand

you can find your answer in the combination of these two pages in the API:

ref is used to register a reference to an element or a child component. The reference will be registered under the parent component’s $refs object. If used on a plain DOM element, the reference will be that element

An object that holds child components that have ref registered.

Support for ES6 in Internet Explorer 11

The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.

If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.

How to "inverse match" with regex?

What language are you using? The capabilities and syntax of the regex implementation matter for this.

You could use look-ahead. Using python as an example

import re

not_andrea = re.compile('(?!Andrea)\w{6}', re.IGNORECASE)

To break that down:

(?!Andrea) means 'match if the next 6 characters are not "Andrea"'; if so then

\w means a "word character" - alphanumeric characters. This is equivalent to the class [a-zA-Z0-9_]

\w{6} means exactly 6 word characters.

re.IGNORECASE means that you will exclude "Andrea", "andrea", "ANDREA" ...

Another way is to use your program logic - use all lines not matching Andrea and put them through a second regex to check for 6 characters. Or first check for at least 6 word characters, and then check that it does not match Andrea.

ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead

First install your targeted version

npm i [email protected] --save-dev --save-exact

Then before compiling do

   npm i

Linq Select Group By

You should try it like this:

var result =
        from priceLog in PriceLogList
        group priceLog by priceLog.LogDateTime.ToString("MMM yyyy") into dateGroup
        select new {
            LogDateTime = dateGroup.Key,
            AvgPrice = dateGroup.Average(priceLog => priceLog.Price)
        };

Python - Join with newline

When you print it with this print 'I\nwould\nexpect\nmultiple\nlines' you would get:

I
would
expect
multiple
lines

The \n is a new line character specially used for marking END-OF-TEXT. It signifies the end of the line or text. This characteristics is shared by many languages like C, C++ etc.

Quicksort: Choosing the pivot

It is easier to break the quicksort into three sections doing this

  1. Exchange or swap data element function
  2. The partition function
  3. Processing the partitions

It is only slightly more inefficent than one long function but is alot easier to understand.

Code follows:

/* This selects what the data type in the array to be sorted is */

#define DATATYPE long

/* This is the swap function .. your job is to swap data in x & y .. how depends on
data type .. the example works for normal numerical data types .. like long I chose
above */

void swap (DATATYPE *x, DATATYPE *y){  
  DATATYPE Temp;

  Temp = *x;        // Hold current x value
  *x = *y;          // Transfer y to x
  *y = Temp;        // Set y to the held old x value
};


/* This is the partition code */

int partition (DATATYPE list[], int l, int h){

  int i;
  int p;          // pivot element index
  int firsthigh;  // divider position for pivot element

  // Random pivot example shown for median   p = (l+h)/2 would be used
  p = l + (short)(rand() % (int)(h - l + 1)); // Random partition point

  swap(&list[p], &list[h]);                   // Swap the values
  firsthigh = l;                                  // Hold first high value
  for (i = l; i < h; i++)
    if(list[i] < list[h]) {                 // Value at i is less than h
      swap(&list[i], &list[firsthigh]);   // So swap the value
      firsthigh++;                        // Incement first high
    }
  swap(&list[h], &list[firsthigh]);           // Swap h and first high values
  return(firsthigh);                          // Return first high
};



/* Finally the body sort */

void quicksort(DATATYPE list[], int l, int h){

  int p;                                      // index of partition 
  if ((h - l) > 0) {
    p = partition(list, l, h);              // Partition list 
    quicksort(list, l, p - 1);        // Sort lower partion
    quicksort(list, p + 1, h);              // Sort upper partition
  };
};

Read line with Scanner

next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...

next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.

nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

Read article :Difference between next() and nextLine()

Replace your while loop with :

while(r.hasNext()) {
                scan = r.next();
                System.out.println(scan);
                if(scan.length()==0) {continue;}
                //treatment
            }

Using hasNext() and next() methods will resolve the issue.

Simple VBA selection: Selecting 5 cells to the right of the active cell

This example selects a new Range of Cells defined by the current cell to a cell 5 to the right.

Note that .Offset takes arguments of Offset(row, columns) and can be quite useful.


Sub testForStackOverflow()
    Range(ActiveCell, ActiveCell.Offset(0, 5)).Copy
End Sub

Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls

try this :

public class FileStore
 {
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public Guid Id { get; set; }
   public string Name { get; set; }
   public string Path { get; set; }
 }

You can check this SO post.

Removing duplicate rows in Notepad++

Notepad++ with the TextFX plugin can do this, provided you wanted to sort by line, and remove the duplicate lines at the same time.

To install the TextFX in the latest release of Notepad++ you need to download it from here: https://sourceforge.net/projects/npp-plugins/files/TextFX

The TextFX plugin used to be included in older versions of Notepad++, or be possible to add from the menu by going to Plugins -> Plugin Manager -> Show Plugin Manager -> Available tab -> TextFX -> Install. In some cases it may also be called TextFX Characters, but this is the same thing.

The check boxes and buttons required will now appear in the menu under: TextFX -> TextFX Tools.

Make sure "sort outputs only unique..." is checked. Next, select a block of text (Ctrl+A to select the entire document). Finally, click "sort lines case sensitive" or "sort lines case insensitive"

menu layout in n++

Google maps responsive resize

After few years, I moved to leaflet map and I have fixed this issue completely, the following could be applied to google maps too:

    var headerHeight = $("#navMap").outerHeight();
    var footerHeight = $("footer").outerHeight();
    var windowHeight = window.innerHeight;
    var mapContainerHeight = headerHeight + footerHeight;
    var totalMapHeight = windowHeight - mapContainerHeight;
    $("#map").css("margin-top", headerHeight);
    $("#map").height(totalMapHeight);

    $(window).resize(function(){
        var headerHeight = $("#navMap").outerHeight();
        var footerHeight = $("footer").outerHeight();
        var windowHeight = window.innerHeight;
        var mapContainerHeight = headerHeight + footerHeight;
        var totalMapHeight = windowHeight - mapContainerHeight;
        $("#map").css("margin-top", headerHeight);
        $("#map").height(totalMapHeight);
        map.fitBounds(group1.getBounds());
    });

How to make rounded percentages add up to 100%

I'm not sure what level of accuracy you need, but what I would do is simply add 1 the first n numbers, n being the ceil of the total sum of decimals. In this case that is 3, so I would add 1 to the first 3 items and floor the rest. Of course this is not super accurate, some numbers might be rounded up or down when it shouldn't but it works okay and will always result in 100%.

So [ 13.626332, 47.989636, 9.596008, 28.788024 ] would be [14, 48, 10, 28] because Math.ceil(.626332+.989636+.596008+.788024) == 3

function evenRound( arr ) {
  var decimal = -~arr.map(function( a ){ return a % 1 })
    .reduce(function( a,b ){ return a + b }); // Ceil of total sum of decimals
  for ( var i = 0; i < decimal; ++i ) {
    arr[ i ] = ++arr[ i ]; // compensate error by adding 1 the the first n items
  }
  return arr.map(function( a ){ return ~~a }); // floor all other numbers
}

var nums = evenRound( [ 13.626332, 47.989636, 9.596008, 28.788024 ] );
var total = nums.reduce(function( a,b ){ return a + b }); //=> 100

You can always inform users that the numbers are rounded and may not be super-accurate...

placeholder for select tag

According to Mozilla Dev Network, placeholder is not a valid attribute on a <select> input.

Instead, add an option with an empty value and the selected attribute, as shown below. The empty value attribute is mandatory to prevent the default behaviour which is to use the contents of the <option> as the <option>'s value.

<select>
    <option value="" selected>select your beverage</option>
    <option value="tea">Tea</option>
    <option value="coffee">Coffee</option>
    <option value="soda">Soda</option>
</select>

In modern browsers, adding the required attribute to the <select> element will not allow the user to submit the form which the element is part of if the selected option has an empty value.

If you want to style the default option inside the list (which appears when clicking the element), there's a limited number of CSS properties that are well-supported. color and background-color are the 2 safest bets, other CSS properties are likely to be ignored.

In my option the best way (in HTML5) to mark the default option is using the custom data-* attributes.1 Here's how to style the default option to be greyed out:

_x000D_
_x000D_
select option[data-default] {_x000D_
  color: #888;_x000D_
}
_x000D_
<select>_x000D_
  <option value="" selected data-default>select your beverage</option>_x000D_
  <option value="tea">Tea</option>_x000D_
  <option value="coffee">Coffee</option>_x000D_
  <option value="soda">Soda</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

However, this will only style the item inside the drop-down list, not the value displayed on the input. If you want to style that with CSS, target your <select> element directly. In that case, you can only change the style of the currently selected element at any time.2

If you wanted to make it slightly harder for the user to select the default item, you could set the display: none; CSS rule on the <option>, but remember that this will not prevent users from selecting it (using e.g. arrow keys/typing), this just makes it harder for them to do so.


1 This answer previously advised the use of a default attribute which is non-standard and has no meaning on its own.
2 It's technically possible to style the select itself based on the selected value using JavaScript, but that's outside the scope of this question. This answer, however, covers this method.

Split column at delimiter in data frame

strsplit(c('a|b','b|c'),'|',fixed=TRUE)

How do I to insert data into an SQL table using C# as well as implement an upload function?

using System;
using System.Data;
using System.Data.SqlClient;

namespace InsertingData
{
    class sqlinsertdata
    {
        static void Main(string[] args)
        {
            try
            { 
            SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
            conn.Open();
                SqlCommand cmd = new SqlCommand("insert into <Table Name>values(1,'nagendra',10000);",conn);
                cmd.ExecuteNonQuery();
                Console.WriteLine("Inserting Data Successfully");
                conn.Close();
        }
            catch(Exception e)
            {
                Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t"  + e.GetType());
            }
            Console.ReadKey();

    }
    }
}

Nginx serves .php files as downloads, instead of executing them

Update nginx config /etc/nginx/sites-available/default or your config file

if you are using php7 use this

    location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php7.0-fpm.sock;      
    }

if you are using php5 use this

    location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php5-fpm.sock;
            fastcgi_index index.php;
            include fastcgi_params;
    }

Visit here for complete detail Detail here

Get properties of a class

Some answers are partially wrong, and some facts in them are partially wrong as well.

Answer your question: Yes! You can.

In Typescript

class A {
    private a1;
    private a2;


}

Generates the following code in Javascript:

var A = /** @class */ (function () {
    function A() {
    }
    return A;
}());

as @Erik_Cupal said, you could just do:

let a = new A();
let array = return Object.getOwnPropertyNames(a);

But this is incomplete. What happens if your class has a custom constructor? You need to do a trick with Typescript because it will not compile. You need to assign as any:

let className:any = A;
let a = new className();// the members will have value undefined

A general solution will be:

class A {
    private a1;
    private a2;
    constructor(a1:number, a2:string){
        this.a1 = a1;
        this.a2 = a2;
    }
}

class Describer{

   describeClass( typeOfClass:any){
       let a = new typeOfClass();
       let array = Object.getOwnPropertyNames(a);
       return array;//you can apply any filter here
   }
}

For better understanding this will reference depending on the context.

Bootstrap: Open Another Modal in Modal

try this

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
  <title></title>_x000D_
  <meta charset="utf-8">_x000D_
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>_x000D_
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#test1">Open Modal 1 </button>_x000D_
_x000D_
_x000D_
_x000D_
<div id="test1" class="modal fade" role="dialog" style="z-index: 1400;">_x000D_
  <div class="modal-dialog">_x000D_
    <!-- Modal content-->_x000D_
    <div class="modal-content">_x000D_
      _x000D_
      <div class="modal-body">_x000D_
       <button type="button" class="btn btn-info btn-lg" data-toggle="modal"      data-target="#test2">Open Modal 2</button>_x000D_
       _x000D_
      </div>      _x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<div id="test2" class="modal fade" role="dialog" style="z-index: 1600;">_x000D_
  <div class="modal-dialog">_x000D_
    <!-- Modal content-->_x000D_
    <div class="modal-content">_x000D_
      _x000D_
      <div class="modal-body">_x000D_
       _x000D_
        content_x000D_
       _x000D_
      </div>      _x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
  _x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

'tsc command not found' in compiling typescript

For windows:

Add the path by using command as below in command prompt:
path=%path%;C:\Users\\npm

As in my case, the above path was not registered for command.

%userprofile% in run windows, will give you path to C:\users\

Git/GitHub can't push to master

The fastest way yuo get over it is to replace origin with the suggestion it gives.

Instead of git push origin master, use:

git push [email protected]:my_user_name/my_repo.git master

Custom style to jquery ui dialogs

See http://jsfiddle.net/qP8DY/24/

You can add a class (such as "success-dialog" in my example) to div#success, either directly in your HTML, or in your JavaScript by adding to the dialogClass option, as I've done.

$('#success').dialog({
    height: 50,
    width: 350,
    modal: true,
    resizable: true,
    dialogClass: 'no-close success-dialog'
});

Then just add the success-dialog class to your CSS rules as appropriate. To indicate an element with two (or more) classes applied to it, just write them all together, with no spaces in between. For example:

.ui-dialog.success-dialog {
    font-family: Verdana,Arial,sans-serif;
    font-size: .8em;
}

Hibernate Criteria for Dates

try this,

    String dateStr = "17-April-2011 19:20:23.707000000 ";
    Date dateForm = new SimpleDateFormat("dd-MMMM-yyyy HH:mm:ss").parse(dateStr);
    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");  

    String newDate = format.format(dateForm);  

    Calendar today = Calendar.getInstance();
    Date fromDate = format.parse(newDate);
    today.setTime(fromDate);
    today.add(Calendar.DAY_OF_YEAR, 1);
    Date toDate= new SimpleDateFormat("dd-MM-yyyy").parse(format.format(today.getTime()));

    Criteria crit = sessionFactory.getCurrentSession().createCriteria(Model.class);
    crit.add(Restrictions.ge("dateFieldName", fromDate));
    crit.add(Restrictions.le("dateFieldName", toDate));
    return crit.list();

Is bool a native C type?

No, there is no bool in ISO C90.

Here's a list of keywords in standard C (not C99):

  • auto
  • break
  • case
  • char
  • const
  • continue
  • default
  • do
  • double
  • else
  • enum
  • extern
  • float
  • for
  • goto
  • if
  • int
  • long
  • register
  • return
  • short
  • signed
  • static
  • struct
  • switch
  • typedef
  • union
  • unsigned
  • void
  • volatile
  • while

Here's an article discussing some other differences with C as used in the kernel and the standard: http://www.ibm.com/developerworks/linux/library/l-gcc-hacks/index.html

how to use sqltransaction in c#

First you don't need a transaction since you are just querying select statements and since they are both select statement you can just combine them into one query separated by space and use Dataset to get the all the tables retrieved. Its better this way since you made only one transaction to the database because database transactions are expensive hence your code is faster. Second of you really have to use a transaction, just assign the transaction to the SqlCommand like

sqlCommand.Transaction = transaction;

And also just use one SqlCommand don't declare more than one, since variables consume space and we are also on the topic of making your code more efficient, do that by assigning commandText to different query string and executing them like

sqlCommand.CommandText = "select * from table1";
sqlCommand.ExecuteNonQuery();
sqlCommand.CommandText = "select * from table2";
sqlCommand.ExecuteNonQuery();

I am not able launch JNLP applications using "Java Web Start"?

Have a look at what happens if you run javaws.exe directly from the command line.

How to make Visual Studio copy a DLL file to the output directory?

The details in the comments section above did not work for me (VS 2013) when trying to copy the output dll from one C++ project to the release and debug folder of another C# project within the same solution.

I had to add the following post build-action (right click on the project that has a .dll output) then properties -> configuration properties -> build events -> post-build event -> command line

now I added these two lines to copy the output dll into the two folders:

xcopy /y $(TargetPath) $(SolutionDir)aeiscontroller\bin\Release
xcopy /y $(TargetPath) $(SolutionDir)aeiscontroller\bin\Debug

How to get duration, as int milli's and float seconds from <chrono>?

I don't know what "milliseconds and float seconds" means, but this should give you an idea:

#include <chrono>
#include <thread>
#include <iostream>

int main()
{
  auto then = std::chrono::system_clock::now();
  std::this_thread::sleep_for(std::chrono::seconds(1));
  auto now = std::chrono::system_clock::now();
  auto dur = now - then;
  typedef std::chrono::duration<float> float_seconds;
  auto secs = std::chrono::duration_cast<float_seconds>(dur);
  std::cout << secs.count() << '\n';
}

SVN remains in conflict?

One more solution below,

If the entire folder is removed and SVNis throwing the error "admin file .svn is missing", the following will be used to resolve the conflict to working state.

svn resolve --accept working "file / directory name "

Remove empty elements from an array in Javascript

foo = [0, 1, 2, "", , false, 3, "four", null]

foo.filter(function(e) {
    return e === 0 ? '0' : e
})

returns

[0, 1, 2, 3, "four"]

How to set an "Accept:" header on Spring RestTemplate request?

If, like me, you struggled to find an example that uses headers with basic authentication and the rest template exchange API, this is what I finally worked out...

private HttpHeaders createHttpHeaders(String user, String password)
{
    String notEncoded = user + ":" + password;
    String encodedAuth = Base64.getEncoder().encodeToString(notEncoded.getBytes());
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("Authorization", "Basic " + encodedAuth);
    return headers;
}

private void doYourThing() 
{
    String theUrl = "http://blah.blah.com:8080/rest/api/blah";
    RestTemplate restTemplate = new RestTemplate();
    try {
        HttpHeaders headers = createHttpHeaders("fred","1234");
        HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
        ResponseEntity<String> response = restTemplate.exchange(theUrl, HttpMethod.GET, entity, String.class);
        System.out.println("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody());
    }
    catch (Exception eek) {
        System.out.println("** Exception: "+ eek.getMessage());
    }
}

Batch files : How to leave the console window open

At here:

cmd.exe /k "<SomePath>\<My Batch File>.bat" & pause

Take a look what are you doing:

  1. (cmd /K) Start a NEW cmd instance.
  2. (& pause) Pause the CURRENT cmd instance.

How to resolve it? well,using the correct syntax, enclosing the argument for the new CMD instance:

cmd.exe /k ""<SomePath>\<My Batch File>.bat" & pause"

Relative paths based on file location instead of current working directory

What you want to do is get the absolute path of the script (available via ${BASH_SOURCE[0]}) and then use this to get the parent directory and cd to it at the beginning of the script.

#!/bin/bash
parent_path=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )

cd "$parent_path"
cat ../some.text

This will make your shell script work independent of where you invoke it from. Each time you run it, it will be as if you were running ./cat.sh inside dir.

Note that this script only works if you're invoking the script directly (i.e. not via a symlink), otherwise the finding the current location of the script gets a little more tricky)

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

I had no luck until I installed the 2010 version link here: https://www.microsoft.com/en-us/download/details.aspx?id=13255

I tried installing the 32 bit version, it still errored, so I uninstalled it and installed the 64 bit version and it started working.

Send email with PHPMailer - embed image in body

According to PHPMailer Manual, full answer would be :

$mail->AddEmbeddedImage(filename, cid, name);
//Example
$mail->AddEmbeddedImage('my-photo.jpg', 'my-photo', 'my-photo.jpg '); 

Use Case :

$mail->AddEmbeddedImage("rocks.png", "my-attach", "rocks.png");
$mail->Body = 'Embedded Image: <img alt="PHPMailer" src="cid:my-attach"> Here is an image!';

If you want to display an image with a remote URL :

$mail->addStringAttachment(file_get_contents("url"), "filename");

File count from a folder

Try following code to get count of files in the folder

string strDocPath = Server.MapPath('Enter your path here'); 
int docCount = Directory.GetFiles(strDocPath, "*", 
SearchOption.TopDirectoryOnly).Length;

Eclipse interface icons very small on high resolution screen in Windows 8.1

The compatibility mode for Windows Xp, it's only available for the Eclipse 32 bit version and after running in this compatibility mode the icons and text will be the right size, but blurry because they are scaled from their native resolution to the screen resolution and doing so the quality is lost.

Find the last time table was updated

Why not just run this: No need for special permissions

SELECT
    name, 
    object_id, 
    create_date, 
    modify_date
FROM
    sys.tables 
WHERE 
    name like '%yourTablePattern%'
ORDER BY
    modify_date

Checking version of angular-cli that's installed?

Simple run the following commands:

ng --version 

OR

 ng -v

Output on terminal:

      / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / ? \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
            |___/


Angular CLI: 6.0.8
Node: 10.15.0
OS: linux x64 

How do I apply a style to all children of an element

As commented by David Thomas, descendants of those child elements will (likely) inherit most of the styles assigned to those child elements.

You need to wrap your .myTestClass inside an element and apply the styles to descendants by adding .wrapper * descendant selector. Then, add .myTestClass > * child selector to apply the style to the elements children, not its grand children. For example like this:

JSFiddle - DEMO

_x000D_
_x000D_
.wrapper * {_x000D_
    color: blue;_x000D_
    margin: 0 100px; /* Only for demo */_x000D_
}_x000D_
.myTestClass > * {_x000D_
    color:red;_x000D_
    margin: 0 20px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
    <div class="myTestClass">Text 0_x000D_
        <div>Text 1</div>_x000D_
        <span>Text 1</span>_x000D_
        <div>Text 1_x000D_
            <p>Text 2</p>_x000D_
            <div>Text 2</div>_x000D_
        </div>_x000D_
        <p>Text 1</p>_x000D_
    </div>_x000D_
    <div>Text 0</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)?

With numpy, you can pass a slice for each component of the index - so, your x[0:2,0:2] example above works.

If you just want to evenly skip columns or rows, you can pass slices with three components (i.e. start, stop, step).

Again, for your example above:

>>> x[1:4:2, 1:4:2]
array([[ 5,  7],
       [13, 15]])

Which is basically: slice in the first dimension, with start at index 1, stop when index is equal or greater than 4, and add 2 to the index in each pass. The same for the second dimension. Again: this only works for constant steps.

The syntax you got to do something quite different internally - what x[[1,3]][:,[1,3]] actually does is create a new array including only rows 1 and 3 from the original array (done with the x[[1,3]] part), and then re-slice that - creating a third array - including only columns 1 and 3 of the previous array.

R: rJava package install failing

Wouldn't

apt-get install r-cran-rjava

have been easier? You could have asked me at useR! :)

How to initialize a vector with fixed length in R

?vector

X <- vector(mode="character", length=10)

This will give you empty strings which get printed as two adjacent double quotes, but be aware that there are no double-quote characters in the values themselves. That's just a side-effect of how print.default displays the values. They can be indexed by location. The number of characters will not be restricted, so if you were expecting to get 10 character element you will be disappointed.

>  X[5] <- "character element in 5th position"

>  X
 [1] ""                                  ""                                 
 [3] ""                                  ""                                 
 [5] "character element in 5th position" ""                                 
 [7] ""                                  ""                                 
 [9] ""                                  "" 
>  nchar(X)
 [1]  0  0  0  0 33  0  0  0  0  0

> length(X)
[1] 10

Hash Table/Associative Array in VBA

Here we go... just copy the code to a module, it's ready to use

Private Type hashtable
    key As Variant
    value As Variant
End Type

Private GetErrMsg As String

Private Function CreateHashTable(htable() As hashtable) As Boolean
    GetErrMsg = ""
    On Error GoTo CreateErr
        ReDim htable(0)
        CreateHashTable = True
    Exit Function

CreateErr:
    CreateHashTable = False
    GetErrMsg = Err.Description
End Function

Private Function AddValue(htable() As hashtable, key As Variant, value As Variant) As Long
    GetErrMsg = ""
    On Error GoTo AddErr
        Dim idx As Long
        idx = UBound(htable) + 1

        Dim htVal As hashtable
        htVal.key = key
        htVal.value = value

        Dim i As Long
        For i = 1 To UBound(htable)
            If htable(i).key = key Then Err.Raise 9999, , "Key [" & CStr(key) & "] is not unique"
        Next i

        ReDim Preserve htable(idx)

        htable(idx) = htVal
        AddValue = idx
    Exit Function

AddErr:
    AddValue = 0
    GetErrMsg = Err.Description
End Function

Private Function RemoveValue(htable() As hashtable, key As Variant) As Boolean
    GetErrMsg = ""
    On Error GoTo RemoveErr

        Dim i As Long, idx As Long
        Dim htTemp() As hashtable
        idx = 0

        For i = 1 To UBound(htable)
            If htable(i).key <> key And IsEmpty(htable(i).key) = False Then
                ReDim Preserve htTemp(idx)
                AddValue htTemp, htable(i).key, htable(i).value
                idx = idx + 1
            End If
        Next i

        If UBound(htable) = UBound(htTemp) Then Err.Raise 9998, , "Key [" & CStr(key) & "] not found"

        htable = htTemp
        RemoveValue = True
    Exit Function

RemoveErr:
    RemoveValue = False
    GetErrMsg = Err.Description
End Function

Private Function GetValue(htable() As hashtable, key As Variant) As Variant
    GetErrMsg = ""
    On Error GoTo GetValueErr
        Dim found As Boolean
        found = False

        For i = 1 To UBound(htable)
            If htable(i).key = key And IsEmpty(htable(i).key) = False Then
                GetValue = htable(i).value
                Exit Function
            End If
        Next i
        Err.Raise 9997, , "Key [" & CStr(key) & "] not found"

    Exit Function

GetValueErr:
    GetValue = ""
    GetErrMsg = Err.Description
End Function

Private Function GetValueCount(htable() As hashtable) As Long
    GetErrMsg = ""
    On Error GoTo GetValueCountErr
        GetValueCount = UBound(htable)
    Exit Function

GetValueCountErr:
    GetValueCount = 0
    GetErrMsg = Err.Description
End Function

To use in your VB(A) App:

Public Sub Test()
    Dim hashtbl() As hashtable
    Debug.Print "Create Hashtable: " & CreateHashTable(hashtbl)
    Debug.Print ""
    Debug.Print "ID Test   Add V1: " & AddValue(hashtbl, "Hallo_0", "Testwert 0")
    Debug.Print "ID Test   Add V2: " & AddValue(hashtbl, "Hallo_0", "Testwert 0")
    Debug.Print "ID Test 1 Add V1: " & AddValue(hashtbl, "Hallo.1", "Testwert 1")
    Debug.Print "ID Test 2 Add V1: " & AddValue(hashtbl, "Hallo-2", "Testwert 2")
    Debug.Print "ID Test 3 Add V1: " & AddValue(hashtbl, "Hallo 3", "Testwert 3")
    Debug.Print ""
    Debug.Print "Test 1 Removed V1: " & RemoveValue(hashtbl, "Hallo_1")
    Debug.Print "Test 1 Removed V2: " & RemoveValue(hashtbl, "Hallo_1")
    Debug.Print "Test 2 Removed V1: " & RemoveValue(hashtbl, "Hallo-2")
    Debug.Print ""
    Debug.Print "Value Test 3: " & CStr(GetValue(hashtbl, "Hallo 3"))
    Debug.Print "Value Test 1: " & CStr(GetValue(hashtbl, "Hallo_1"))
    Debug.Print ""
    Debug.Print "Hashtable Content:"

    For i = 1 To UBound(hashtbl)
        Debug.Print CStr(i) & ": " & CStr(hashtbl(i).key) & " - " & CStr(hashtbl(i).value)
    Next i

    Debug.Print ""
    Debug.Print "Count: " & CStr(GetValueCount(hashtbl))
End Sub

What do the python file extensions, .pyc .pyd .pyo stand for?

  • .py - Regular script
  • .py3 - (rarely used) Python3 script. Python3 scripts usually end with ".py" not ".py3", but I have seen that a few times
  • .pyc - compiled script (Bytecode)
  • .pyo - optimized pyc file (As of Python3.5, Python will only use pyc rather than pyo and pyc)
  • .pyw - Python script to run in Windowed mode, without a console; executed with pythonw.exe
  • .pyx - Cython src to be converted to C/C++
  • .pyd - Python script made as a Windows DLL
  • .pxd - Cython script which is equivalent to a C/C++ header
  • .pxi - MyPy stub
  • .pyi - Stub file (PEP 484)
  • .pyz - Python script archive (PEP 441); this is a script containing compressed Python scripts (ZIP) in binary form after the standard Python script header
  • .pywz - Python script archive for MS-Windows (PEP 441); this is a script containing compressed Python scripts (ZIP) in binary form after the standard Python script header
  • .py[cod] - wildcard notation in ".gitignore" that means the file may be ".pyc", ".pyo", or ".pyd".
  • .pth - a path configuration file; its contents are additional items (one per line) to be added to sys.path. See site module.

A larger list of additional Python file-extensions (mostly rare and unofficial) can be found at http://dcjtech.info/topic/python-file-extensions/

Convert float to std::string in C++

Important:
Read the note at the end.

Quick answer :
Use to_string(). (available since c++11)
example :

#include <iostream>   
#include <string>  

using namespace std;
int main ()
{
    string pi = "pi is " + to_string(3.1415926);
    cout<< "pi = "<< pi << endl;

  return 0;
}

run it yourself : http://ideone.com/7ejfaU
These are available as well :

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);

Important Note:
As @Michael Konecný rightfully pointed out, using to_string() is risky at best that is its very likely to cause unexpected results.
From http://en.cppreference.com/w/cpp/string/basic_string/to_string :

With floating point types std::to_string may yield unexpected results as the number of significant digits in the returned string can be zero, see the example.
The return value may differ significantly from what std::cout prints by default, see the example. std::to_string relies on the current locale for formatting purposes, and therefore concurrent calls to std::to_string from multiple threads may result in partial serialization of calls. C++17 provides std::to_chars as a higher-performance locale-independent alternative.

The best way would be to use stringstream as others such as @dcp demonstrated in his answer.:

This issue is demonstrated in the following example :
run the example yourself : https://www.jdoodle.com/embed/v0/T4k

#include <iostream>
#include <sstream>
#include <string>

template < typename Type > std::string to_str (const Type & t)
{
  std::ostringstream os;
  os << t;
  return os.str ();
}

int main ()
{

  // more info : https://en.cppreference.com/w/cpp/string/basic_string/to_string
  double    f = 23.43;
  double    f2 = 1e-9;
  double    f3 = 1e40;
  double    f4 = 1e-40;
  double    f5 = 123456789;
  std::string f_str = std::to_string (f);
  std::string f_str2 = std::to_string (f2); // Note: returns "0.000000"
  std::string f_str3 = std::to_string (f3); // Note: Does not return "1e+40".
  std::string f_str4 = std::to_string (f4); // Note: returns "0.000000"
  std::string f_str5 = std::to_string (f5);

  std::cout << "std::cout: " << f << '\n'
    << "to_string: " << f_str << '\n'
    << "ostringstream: " << to_str (f) << "\n\n"
    << "std::cout: " << f2 << '\n'
    << "to_string: " << f_str2 << '\n'
    << "ostringstream: " << to_str (f2) << "\n\n"
    << "std::cout: " << f3 << '\n'
    << "to_string: " << f_str3 << '\n'
    << "ostringstream: " << to_str (f3) << "\n\n"
    << "std::cout: " << f4 << '\n'
    << "to_string: " << f_str4 << '\n'
    << "ostringstream: " << to_str (f4) << "\n\n"
    << "std::cout: " << f5 << '\n'
    << "to_string: " << f_str5 << '\n'
    << "ostringstream: " << to_str (f5) << '\n';

  return 0;
}

output :

std::cout: 23.43
to_string: 23.430000
ostringstream: 23.43

std::cout: 1e-09
to_string: 0.000000
ostringstream: 1e-09

std::cout: 1e+40
to_string: 10000000000000000303786028427003666890752.000000
ostringstream: 1e+40

std::cout: 1e-40
to_string: 0.000000
ostringstream: 1e-40

std::cout: 1.23457e+08
to_string: 123456789.000000
ostringstream: 1.23457e+08 

mysql datatype for telephone number and address

i would use a varchar for telephone numbers. that way you can also store + and (), which is sometimes seen in tel numbers (as you mentioned yourself). and you don't have to worry about using up all bits in integers.

Where can I download Spring Framework jars without using Maven?

Please edit to keep this list of mirrors current

I found this maven repo where you could download from directly a zip file containing all the jars you need.

Alternate solution: Maven

The solution I prefer is using Maven, it is easy and you don't have to download each jar alone. You can do it with the following steps:

  1. Create an empty folder anywhere with any name you prefer, for example spring-source

  2. Create a new file named pom.xml

  3. Copy the xml below into this file

  4. Open the spring-source folder in your console

  5. Run mvn install

  6. After download finished, you'll find spring jars in /spring-source/target/dependencies

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>spring-source-download</groupId>
      <artifactId>SpringDependencies</artifactId>
      <version>1.0</version>
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
      <dependencies>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>3.2.4.RELEASE</version>
        </dependency>
      </dependencies>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.8</version>
            <executions>
              <execution>
                <id>download-dependencies</id>
                <phase>generate-resources</phase>
                <goals>
                  <goal>copy-dependencies</goal>
                </goals>
                <configuration>
                  <outputDirectory>${project.build.directory}/dependencies</outputDirectory>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </project>
    

Also, if you need to download any other spring project, just copy the dependency configuration from its corresponding web page.

For example, if you want to download Spring Web Flow jars, go to its web page, and add its dependency configuration to the pom.xml dependencies, then run mvn install again.

<dependency>
  <groupId>org.springframework.webflow</groupId>
  <artifactId>spring-webflow</artifactId>
  <version>2.3.2.RELEASE</version>
</dependency>

Is there a maximum number you can set Xmx to when trying to increase jvm memory?

I think a 32 bit JVM has a maximum of 2GB memory.This might be out of date though. If I understood correctly, you set the -Xmx on Eclipse launcher. If you want to increase the memory for the program you run from Eclipse, you should define -Xmx in the "Run->Run configurations..."(select your class and open the Arguments tab put it in the VM arguments area) menu, and NOT on Eclipse startup

Edit: details you asked for. in Eclipse 3.4

  1. Run->Run Configurations...

  2. if your class is not listed in the list on the left in the "Java Application" subtree, click on "New Launch configuration" in the upper left corner

  3. on the right, "Main" tab make sure the project and the class are the right ones

  4. select the "Arguments" tab on the right. this one has two text areas. one is for the program arguments that get in to the args[] array supplied to your main method. the other one is for the VM arguments. put into the one with the VM arguments(lower one iirc) the following:
    -Xmx2048m

    I think that 1024m should more than enough for what you need though!

  5. Click Apply, then Click Run

  6. Should work :)

Tomcat 8 Maven Plugin for Java 8

Plugin run Tomcat 7.0.47:

mvn org.apache.tomcat.maven:tomcat7-maven-plugin:2.2:run

 ...
 INFO: Starting Servlet Engine: Apache Tomcat/7.0.47

This is sample to run plugin with Tomcat 8 and Java 8: Cargo embedded tomcat: custom context.xml

Get MIME type from filename extension

Most of the solutions are working but why take so efforts while we also can get mime type very easily. In System.Web assembly, there is method for getting the mime type from file name. eg:

string mimeType = MimeMapping.GetMimeMapping(filename);