Programs & Examples On #Printf

`printf` is a common function for formatted output. C and many other languages have a whole family of related functions. Only use this tag if the question is directly concerned with `printf` or related functions.

How do I align a number like this in C?

So, you want an 8-character wide field with spaces as the padding? Try "%8d". Here's a reference.

EDIT: What you're trying to do is not something that can be handled by printf alone, because it will not know what the longest number you are writing is. You will need to calculate the largest number before doing any printfs, and then figure out how many digits to use as the width of your field. Then you can use snprintf or similar to make a printf format on the spot.

char format[20];
snprintf(format, 19, "%%%dd\\n", max_length);
while (got_output) {
    printf(format, number);
    got_output = still_got_output();
}

Printing hexadecimal characters in C

You can use hh to tell printf that the argument is an unsigned char. Use 0 to get zero padding and 2 to set the width to 2. x or X for lower/uppercase hex characters.

uint8_t a = 0x0a;
printf("%02hhX", a); // Prints "0A"
printf("0x%02hhx", a); // Prints "0x0a"

Edit: If readers are concerned about 2501's assertion that this is somehow not the 'correct' format specifiers I suggest they read the printf link again. Specifically:

Even though %c expects int argument, it is safe to pass a char because of the integer promotion that takes place when a variadic function is called.

The correct conversion specifications for the fixed-width character types (int8_t, etc) are defined in the header <cinttypes>(C++) or <inttypes.h> (C) (although PRIdMAX, PRIuMAX, etc is synonymous with %jd, %ju, etc).

As for his point about signed vs unsigned, in this case it does not matter since the values must always be positive and easily fit in a signed int. There is no signed hexideximal format specifier anyway.

Edit 2: ("when-to-admit-you're-wrong" edition):

If you read the actual C11 standard on page 311 (329 of the PDF) you find:

hh: Specifies that a following d, i, o, u, x, or X conversion specifier applies to a signed char or unsigned char argument (the argument will have been promoted according to the integer promotions, but its value shall be converted to signed char or unsigned char before printing); or that a following n conversion specifier applies to a pointer to a signed char argument.

What is the use of the %n format specifier in C?

From here we see that it stores the number of characters printed so far.

n The argument shall be a pointer to an integer into which is written the number of bytes written to the output so far by this call to one of the fprintf() functions. No argument is converted.

An example usage would be:

int n_chars = 0;
printf("Hello, World%n", &n_chars);

n_chars would then have a value of 12.

What is the difference between printf() and puts() in C?

When comparing puts() and printf(), even though their memory consumption is almost the same, puts() takes more time compared to printf().

Strings and character with printf

If you try this:

#include<stdio.h>

void main()
{
 char name[]="siva";
 printf("name = %p\n", name);
 printf("&name[0] = %p\n", &name[0]);
 printf("name printed as %%s is %s\n",name);
 printf("*name = %c\n",*name);
 printf("name[0] = %c\n", name[0]);
}

Output is:

name = 0xbff5391b  
&name[0] = 0xbff5391b
name printed as %s is siva
*name = s
name[0] = s

So 'name' is actually a pointer to the array of characters in memory. If you try reading the first four bytes at 0xbff5391b, you will see 's', 'i', 'v' and 'a'

Location     Data
=========   ======

0xbff5391b    0x73  's'  ---> name[0]
0xbff5391c    0x69  'i'  ---> name[1]
0xbff5391d    0x76  'v'  ---> name[2]
0xbff5391e    0x61  'a'  ---> name[3]
0xbff5391f    0x00  '\0' ---> This is the NULL termination of the string

To print a character you need to pass the value of the character to printf. The value can be referenced as name[0] or *name (since for an array name = &name[0]).

To print a string you need to pass a pointer to the string to printf (in this case 'name' or '&name[0]').

How I can print to stderr in C?

If you don't want to modify current codes and just for debug usage.

Add this macro:

#define printf(args...) fprintf(stderr, ##args)
//under GCC
#define printf(args...) fprintf(stderr, __VA_ARGS__)
//under MSVC

Change stderr to stdout if you want to roll back.

It's helpful for debug, but it's not a good practice.

What is the difference between conversion specifiers %i and %d in formatted IO functions (*printf / *scanf)

These are identical for printf but different for scanf. For printf, both %d and %i designate a signed decimal integer. For scanf, %d and %i also means a signed integer but %i inteprets the input as a hexadecimal number if preceded by 0x and octal if preceded by 0 and otherwise interprets the input as decimal.

printf format specifiers for uint32_t and size_t

Try

#include <inttypes.h>
...

printf("i [ %zu ] k [ %"PRIu32" ]\n", i, k);

The z represents an integer of length same as size_t, and the PRIu32 macro, defined in the C99 header inttypes.h, represents an unsigned 32-bit integer.

Double % formatting question for printf in Java

Following is the list of conversion characters that you may use in the printf:

%d – for signed decimal integer

%f – for the floating point

%o – octal number

%c – for a character

%s – a string

%i – use for integer base 10

%u – for unsigned decimal number

%x – hexadecimal number

%% – for writing % (percentage)

%n – for new line = \n

Using floats with sprintf() in embedded C

Many embedded systems have a limited snprintf function that doesn't handle floats. I wrote this, and it does the trick fairly efficiently. I chose to use 64-bit unsigned integers to be able to handle large floats, so feel free to reduce them down to 16-bit or whatever needs you may have with limited resources.

#include <stdio.h>   // for uint64_t support.


int  snprintf_fp( char destination[], size_t available_chars, int decimal_digits,
                  char tail[], float source_number )
{
    int   chars_used  = 0;    // This will be returned.


    if ( available_chars > 0 )
    {
        // Handle a negative sign.
        if ( source_number < 0 )
        {
            // Make it positive
            source_number = 0 - source_number;
            destination[ 0 ] = '-';
            ++chars_used;
        }

        // Handle rounding
        uint64_t zeros = 1;
        for ( int i = decimal_digits; i > 0; --i )
            zeros *= 10;

        uint64_t source_num = (uint64_t)( ( source_number * (float)zeros ) + 0.5f );

        // Determine sliding divider max position.
        uint64_t  div_amount = zeros;       // Give it a head start
        while ( ( div_amount * 10 ) <= source_num )
            div_amount *= 10;

        // Process the digits
        while ( div_amount > 0 )
        {
            uint64_t whole_number = source_num / div_amount;
            if ( chars_used < (int)available_chars )
            {
                destination[ chars_used ] = '0' + (char)whole_number;
                ++chars_used;

                if ( ( div_amount == zeros ) && ( zeros > 1 ) )
                {
                    destination[ chars_used ] = '.';
                    ++chars_used;
                }
            }
            source_num -= ( whole_number * div_amount );
            div_amount /= 10;
        }


        // Store the zero.
        destination[ chars_used ] = 0;

        // See if a tail was specified.
        size_t tail_len = strlen( tail );

        if ( ( tail_len > 0 ) && ( tail_len + chars_used < available_chars ) )
        {
            for ( size_t i = 0; i <= tail_len; ++i )
                destination[ chars_used + i ] = tail[ i ];
            chars_used += tail_len;
        }
    }

    return chars_used;
}

main()
{
    #define TEMP_BUFFER_SIZE 30
    char temp_buffer[ TEMP_BUFFER_SIZE ];
    char  degrees_c[] = { (char)248, 'C', 0 };
    float  float_temperature = 26.845f;

    int len = snprintf_fp( temp_buffer, TEMP_BUFFER_SIZE, 2, degrees_c, float_temperature );
}

How to format strings using printf() to get equal length in the output

Start with the use of tabs - the \t character modifier. It will advance to a fixed location (columns, terminal lingo).

However, it doesn't help if there are differences of more than the column width (4 characters, if I recall correctly).

To fix that, write your "OK/NOK" stuff using a fixed number of tabs (5? 6?, try it). Then return (\r) without new-lining, and write your message.

Printf width specifier to maintain precision of floating-point value

No, there is no such printf width specifier to print floating-point with maximum precision. Let me explain why.

The maximum precision of float and double is variable, and dependent on the actual value of the float or double.

Recall float and double are stored in sign.exponent.mantissa format. This means that there are many more bits used for the fractional component for small numbers than for big numbers.

enter image description here

For example, float can easily distinguish between 0.0 and 0.1.

float r = 0;
printf( "%.6f\n", r ) ; // 0.000000
r+=0.1 ;
printf( "%.6f\n", r ) ; // 0.100000

But float has no idea of the difference between 1e27 and 1e27 + 0.1.

r = 1e27;
printf( "%.6f\n", r ) ; // 999999988484154753734934528.000000
r+=0.1 ;
printf( "%.6f\n", r ) ; // still 999999988484154753734934528.000000

This is because all the precision (which is limited by the number of mantissa bits) is used up for the large part of the number, left of the decimal.

The %.f modifier just says how many decimal values you want to print from the float number as far as formatting goes. The fact that the accuracy available depends on the size of the number is up to you as the programmer to handle. printf can't/doesn't handle that for you.

What do \t and \b do?

Backspace and tab both move the cursor position. Neither is truly a 'printable' character.

Your code says:

  1. print "foo"
  2. move the cursor back one space
  3. move the cursor forward to the next tabstop
  4. output "bar".

To get the output you expect, you need printf("foo\b \tbar"). Note the extra 'space'. That says:

  1. output "foo"
  2. move the cursor back one space
  3. output a ' ' (this replaces the second 'o').
  4. move the cursor forward to the next tabstop
  5. output "bar".

Most of the time it is inappropriate to use tabs and backspace for formatting your program output. Learn to use printf() formatting specifiers. Rendering of tabs can vary drastically depending on how the output is viewed.

This little script shows one way to alter your terminal's tab rendering. Tested on Ubuntu + gnome-terminal:

#!/bin/bash
tabs -8 
echo -e "\tnormal tabstop"
for x in `seq 2 10`; do
  tabs $x
  echo -e "\ttabstop=$x"
 done

tabs -8
echo -e "\tnormal tabstop"

Also see man setterm and regtabs.

And if you redirect your output or just write to a file, tabs will quite commonly be displayed as fewer than the standard 8 chars, especially in "programming" editors and IDEs.

So in otherwords:

printf("%-8s%s", "foo", "bar"); /* this will ALWAYS output "foo     bar" */
printf("foo\tbar"); /* who knows how this will be rendered */

IMHO, tabs in general are rarely appropriate for anything. An exception might be generating output for a program that requires tab-separated-value input files (similar to comma separated value).

Backspace '\b' is a different story... it should never be used to create a text file since it will just make a text editor spit out garbage. But it does have many applications in writing interactive command line programs that cannot be accomplished with format strings alone. If you find yourself needing it a lot, check out "ncurses", which gives you much better control over where your output goes on the terminal screen. And typically, since it's 2011 and not 1995, a GUI is usually easier to deal with for highly interactive programs. But again, there are exceptions. Like writing a telnet server or console for a new scripting language.

How to display (print) vector in Matlab?

Here is a more generalized solution that prints all elements of x the vector x in this format:

x=randperm(3);
s = repmat('%d,',1,length(x));
s(end)=[]; %Remove trailing comma

disp(sprintf(['Answer: (' s ')'], x))

what do these symbolic strings mean: %02d %01d?

The answer from Alexander refers to complete docs...

Your simple example from the question simply prints out these values with 2 digits - appending leading 0 if necessary.

How do you allow spaces to be entered using scanf?

You can use the fgets() function to read a string or use scanf("%[^\n]s",name); so string reading will terminate upon encountering a newline character.

'printf' with leading zeros in C

Your format specifier is incorrect. From the printf() man page on my machine:

0 A zero '0' character indicating that zero-padding should be used rather than blank-padding. A '-' overrides a '0' if both are used;

Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);

Precision: An optional period, '.', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;

For your case, your format would be %09.3f:

#include <stdio.h>

int main(int argc, char **argv)
{
  printf("%09.3f\n", 4917.24);
  return 0;
}

Output:

$ make testapp
cc     testapp.c   -o testapp
$ ./testapp 
04917.240

Note that this answer is conditional on your embedded system having a printf() implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.

Java: Literal percent sign in printf statement

The percent sign is escaped using a percent sign:

System.out.printf("%s\t%s\t%1.2f%%\t%1.2f%%\n",ID,pattern,support,confidence);

The complete syntax can be accessed in java docs. This particular information is in the section Conversions of the first link.

The reason the compiler is generating an error is that only a limited amount of characters may follow a backslash. % is not a valid character.

Display the binary representation of a number in C?

Use a lookup table, like:

char *table[16] = {"0000", "0001", .... "1111"};

then print each nibble like this

printf("%s%s", table[a / 0x10], table[a % 0x10]);

Surely you can use just one table, but it will be marginally faster and too big.

How to pass variable number of arguments to printf/sprintf

Have a look at the example http://www.cplusplus.com/reference/clibrary/cstdarg/va_arg/, they pass the number of arguments to the method but you can ommit that and modify the code appropriately (see the example).

The "backspace" escape character '\b': unexpected behavior?

..........
^ <= pointer to "print head"
            /* part1 */
            printf("hello worl");
hello worl
          ^ <= pointer to "print head"
            /* part2 */
            printf("\b");
hello worl
         ^ <= pointer to "print head"
            /* part3 */
            printf("\b");
hello worl
        ^ <= pointer to "print head"
            /* part4 */
            printf("d\n");
hello wodl

^ <= pointer to "print head" on the next line

printf \t option

A tab is a tab. How many spaces it consumes is a display issue, and depends on the settings of your shell.

If you want to control the width of your data, then you could use the width sub-specifiers in the printf format string. Eg. :

printf("%5d", 2);

It's not a complete solution (if the value is longer than 5 characters, it will not be truncated), but might be ok for your needs.

If you want complete control, you'll probably have to implement it yourself.

printf with std::string?

It's compiling because printf isn't type safe, since it uses variable arguments in the C sense1. printf has no option for std::string, only a C-style string. Using something else in place of what it expects definitely won't give you the results you want. It's actually undefined behaviour, so anything at all could happen.

The easiest way to fix this, since you're using C++, is printing it normally with std::cout, since std::string supports that through operator overloading:

std::cout << "Follow this command: " << myString;

If, for some reason, you need to extract the C-style string, you can use the c_str() method of std::string to get a const char * that is null-terminated. Using your example:

#include <iostream>
#include <string>
#include <stdio.h>

int main()
{
    using namespace std;

    string myString = "Press ENTER to quit program!";
    cout << "Come up and C++ me some time." << endl;
    printf("Follow this command: %s", myString.c_str()); //note the use of c_str
    cin.get();

    return 0;
}

If you want a function that is like printf, but type safe, look into variadic templates (C++11, supported on all major compilers as of MSVC12). You can find an example of one here. There's nothing I know of implemented like that in the standard library, but there might be in Boost, specifically boost::format.


[1]: This means that you can pass any number of arguments, but the function relies on you to tell it the number and types of those arguments. In the case of printf, that means a string with encoded type information like %d meaning int. If you lie about the type or number, the function has no standard way of knowing, although some compilers have the ability to check and give warnings when you lie.

Unsigned values in C

When you initialize unsigned int a to -1; it means that you are storing the 2's complement of -1 into the memory of a.
Which is nothing but 0xffffffff or 4294967295.

Hence when you print it using %x or %u format specifier you get that output.

By specifying signedness of a variable to decide on the minimum and maximum limit of value that can be stored.

Like with unsigned int: the range is from 0 to 4,294,967,295 and int: the range is from -2,147,483,648 to 2,147,483,647

For more info on signedness refer this

Using colors with printf

man printf.1 has a note at the bottom: "...your shell may have its own version of printf...". This question is tagged for bash, but if at all possible, I try to write scripts portable to any shell. dash is usually a good minimum baseline for portability - so the answer here works in bash, dash, & zsh. If a script works in those 3, it's most likely portable to just about anywhere.

The latest implementation of printf in dash[1] doesn't colorize output given a %s format specifier with an ANSI escape character \e -- but, a format specifier %b combined with octal \033 (equivalent to an ASCII ESC) will get the job done. Please comment for any outliers, but AFAIK, all shells have implemented printf to use the ASCII octal subset at a bare minimum.

To the title of the question "Using colors with printf", the most portable way to set formatting is to combine the %b format specifier for printf (as referenced in an earlier answer from @Vlad) with an octal escape \033.


portable-color.sh

#/bin/sh
P="\033["
BLUE=34
printf "-> This is %s %-6s %s text \n" $P"1;"$BLUE"m" "blue" $P"0m"
printf "-> This is %b %-6s %b text \n" $P"1;"$BLUE"m" "blue" $P"0m"

Outputs:

$ ./portable-color.sh
-> This is \033[1;34m blue   \033[0m text
-> This is  blue    text

...and 'blue' is blue in the second line.

The %-6s format specifier from the OP is in the middle of the format string between the opening & closing control character sequences.


[1] Ref: man dash Section "Builtins" :: "printf" :: "Format"

printf and long double

In C99 the length modifier for long double seems to be L and not l. man fprintf (or equivalent for windows) should tell you for your particular platform.

Printing leading 0's in C

sprintf(mystring, "%05d", myInt);

Here, "05" says "use 5 digits with leading zeros".

In C can a long printf statement be broken up into multiple lines?

I don't think using one printf statement to print string literals as seen above is a good programming practice; rather, one can use the piece of code below:

printf("name: %s\t",sp->name);
printf("args: %s\t",sp->args);
printf("value: %s\t",sp->value);
printf("arraysize: %s\t",sp->name); 

Left-pad printf with spaces

If you want exactly 40 spaces before the string then you should just do:

printf("                                        %s\n", myStr );

If that is too dirty, you can do (but it will be slower than manually typing the 40 spaces): printf("%40s%s", "", myStr );

If you want the string to be lined up at column 40 (that is, have up to 39 spaces proceeding it such that the right most character is in column 40) then do this: printf("%40s", myStr);

You can also put "up to" 40 spaces AfTER the string by doing: printf("%-40s", myStr);

How do I properly 'printf' an integer and a string in C?

Try this code my friend...

#include<stdio.h>
int main(){
   char *s1, *s2;
   char str[10];

   printf("type a string: ");
   scanf("%s", str);

   s1 = &str[0];
   s2 = &str[2];

   printf("%c\n", *s1);   //use %c instead of %s and *s1 which is the content of position 1
   printf("%c\n", *s2);   //use %c instead of %s and *s3 which is the content of position 1

   return 0;
}

How do you format an unsigned long long int using printf?

Compile it as x64 with VS2005:

%llu works well.

Align printf output in Java

You can try the below example. Do use '-' before the width to ensure left indentation. By default they will be right indented; which may not suit your purpose.

System.out.printf("%2d. %-20s $%.2f%n",  i + 1, BOOK_TYPE[i], COST[i]);

Format String Syntax: http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax

Formatting Numeric Print Output: https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

PS: This could go as a comment to DwB's answer, but i still don't have permissions to comment and so answering it.

What does %s and %d mean in printf in the C language?

%(letter) denotes the format type of the replacement text. %s specifies a string, %d an integer, and %c a char.

JavaScript equivalent to printf/String.Format

I'm surprised no one used reduce, this is a native concise and powerful JavaScript function.

ES6 (EcmaScript2015)

_x000D_
_x000D_
String.prototype.format = function() {_x000D_
  return [...arguments].reduce((p,c) => p.replace(/%s/,c), this);_x000D_
};_x000D_
_x000D_
console.log('Is that a %s or a %s?... No, it\'s %s!'.format('plane', 'bird', 'SOman'));
_x000D_
_x000D_
_x000D_

< ES6

function interpolate(theString, argumentArray) {
    var regex = /%s/;
    var _r=function(p,c){return p.replace(regex,c);}
    return argumentArray.reduce(_r, theString);
}

interpolate("%s, %s and %s", ["Me", "myself", "I"]); // "Me, myself and I"

How it works:

reduce applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

_x000D_
_x000D_
var _r= function(p,c){return p.replace(/%s/,c)};_x000D_
_x000D_
console.log(_x000D_
  ["a", "b", "c"].reduce(_r, "[%s], [%s] and [%s]") + '\n',_x000D_
  [1, 2, 3].reduce(_r, "%s+%s=%s") + '\n',_x000D_
  ["cool", 1337, "stuff"].reduce(_r, "%s %s %s")_x000D_
);
_x000D_
_x000D_
_x000D_

Does C have a string type?

C does not and never has had a native string type. By convention, the language uses arrays of char terminated with a null char, i.e., with '\0'. Functions and macros in the language's standard libraries provide support for the null-terminated character arrays, e.g., strlen iterates over an array of char until it encounters a '\0' character and strcpy copies from the source string until it encounters a '\0'.

The use of null-terminated strings in C reflects the fact that C was intended to be only a little more high-level than assembly language. Zero-terminated strings were already directly supported at that time in assembly language for the PDP-10 and PDP-11.

It is worth noting that this property of C strings leads to quite a few nasty buffer overrun bugs, including serious security flaws. For example, if you forget to null-terminate a character string passed as the source argument to strcpy, the function will keep copying sequential bytes from whatever happens to be in memory past the end of the source string until it happens to encounter a 0, potentially overwriting whatever valuable information follows the destination string's location in memory.

In your code example, the string literal "Hello, world!" will be compiled into a 14-byte long array of char. The first 13 bytes will hold the letters, comma, space, and exclamation mark and the final byte will hold the null-terminator character '\0', automatically added for you by the compiler. If you were to access the array's last element, you would find it equal to 0. E.g.:

const char foo[] = "Hello, world!";
assert(foo[12] == '!');
assert(foo[13] == '\0');

However, in your example, message is only 10 bytes long. strcpy is going to write all 14 bytes, including the null-terminator, into memory starting at the address of message. The first 10 bytes will be written into the memory allocated on the stack for message and the remaining four bytes will simply be written on to the end of the stack. The consequence of writing those four extra bytes onto the stack is hard to predict in this case (in this simple example, it might not hurt a thing), but in real-world code it usually leads to corrupted data or memory access violation errors.

How to repeat a char using printf?

If you have a compiler that supports the alloca() function, then this is possible solution (quite ugly though):

printf("%s", (char*)memset(memset(alloca(10), '\0', 10), 'x', 9));

It basically allocates 10 bytes on the stack which are filled with '\0' and then the first 9 bytes are filled with 'x'.

If you have a C99 compiler, then this might be a neater solution:

for (int i = 0;  i < 10;  i++, printf("%c", 'x'));

How to print an unsigned char in C?

In case you cannot change the declaration for whatever reason, you can do:

char ch = 212;
printf("%d", (unsigned char) ch);

Why does printf not flush after the call unless a newline is in the format string?

It's probably like that because of efficiency and because if you have multiple programs writing to a single TTY, this way you don't get characters on a line interlaced. So if program A and B are outputting, you'll usually get:

program A output
program B output
program B output
program A output
program B output

This stinks, but it's better than

proprogrgraam m AB  ououtputputt
prproogrgram amB A  ououtputtput
program B output

Note that it isn't even guaranteed to flush on a newline, so you should flush explicitly if flushing matters to you.

Padding characters in printf

There's no way to pad with anything but spaces using printf. You can use sed:

printf "%-50s@%s\n" $PROC_NAME [UP] | sed -e 's/ /-/g' -e 's/@/ /' -e 's/-/ /'

printf not printing on console

Apparently this is a known bug of Eclipse. This bug is resolved with the resolution of WONT-FIX. I have no idea why though. here is the link: Eclipse C Console Bug.

How to escape the % (percent) sign in C's printf?

You can escape it by posting a double '%' like this: %%

Using your example:

printf("hello%%");

Escaping '%' sign is only for printf. If you do:

char a[5];
strcpy(a, "%%");
printf("This is a's value: %s\n", a);

It will print: This is a's value: %%

What is the argument for printf that formats a long?

On most platforms, long and int are the same size (32 bits). Still, it does have its own format specifier:

long n;
unsigned long un;
printf("%ld", n); // signed
printf("%lu", un); // unsigned

For 64 bits, you'd want a long long:

long long n;
unsigned long long un;
printf("%lld", n); // signed
printf("%llu", un); // unsigned

Oh, and of course, it's different in Windows:

printf("%l64d", n); // signed
printf("%l64u", un); // unsigned

Frequently, when I'm printing 64-bit values, I find it helpful to print them in hex (usually with numbers that big, they are pointers or bit fields).

unsigned long long n;
printf("0x%016llX", n); // "0x" followed by "0-padded", "16 char wide", "long long", "HEX with 0-9A-F"

will print:

0x00000000DEADBEEF

Btw, "long" doesn't mean that much anymore (on mainstream x64). "int" is the platform default int size, typically 32 bits. "long" is usually the same size. However, they have different portability semantics on older platforms (and modern embedded platforms!). "long long" is a 64-bit number and usually what people meant to use unless they really really knew what they were doing editing a piece of x-platform portable code. Even then, they probably would have used a macro instead to capture the semantic meaning of the type (eg uint64_t).

char c;       // 8 bits
short s;      // 16 bits
int i;        // 32 bits (on modern platforms)
long l;       // 32 bits
long long ll; // 64 bits 

Back in the day, "int" was 16 bits. You'd think it would now be 64 bits, but no, that would have caused insane portability issues. Of course, even this is a simplification of the arcane and history-rich truth. See wiki:Integer

Two decimal places using printf( )

For %d part refer to this How does this program work? and for decimal places use %.2f

Correct format specifier for double in printf

"%f" is the (or at least one) correct format for a double. There is no format for a float, because if you attempt to pass a float to printf, it'll be promoted to double before printf receives it1. "%lf" is also acceptable under the current standard -- the l is specified as having no effect if followed by the f conversion specifier (among others).

Note that this is one place that printf format strings differ substantially from scanf (and fscanf, etc.) format strings. For output, you're passing a value, which will be promoted from float to double when passed as a variadic parameter. For input you're passing a pointer, which is not promoted, so you have to tell scanf whether you want to read a float or a double, so for scanf, %f means you want to read a float and %lf means you want to read a double (and, for what it's worth, for a long double, you use %Lf for either printf or scanf).


1. C99, §6.5.2.2/6: "If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type float are promoted to double. These are called the default argument promotions." In C++ the wording is somewhat different (e.g., it doesn't use the word "prototype") but the effect is the same: all the variadic parameters undergo default promotions before they're received by the function.

How can I print a quotation mark in C?

#include<stdio.h>
int main(){
char ch='"';
printf("%c",ch);
return 0;
}

Output: "

%i or %d to print integer in C using printf()?

%d seems to be the norm for printing integers, I never figured out why, they behave identically.

printf() formatting for hex

The %#08X conversion must precede the value with 0X; that is required by the standard. There's no evidence in the standard that the # should alter the behaviour of the 08 part of the specification except that the 0X prefix is counted as part of the length (so you might want/need to use %#010X. If, like me, you like your hex presented as 0x1234CDEF, then you have to use 0x%08X to achieve the desired result. You could use %#.8X and that should also insert the leading zeroes.

Try variations on the following code:

#include <stdio.h>

int main(void)
{
    int j = 0;
    printf("0x%.8X = %#08X = %#.8X = %#010x\n", j, j, j, j);
    for (int i = 0; i < 8; i++)
    {
        j = (j << 4) | (i + 6);
        printf("0x%.8X = %#08X = %#.8X = %#010x\n", j, j, j, j);
    }
    return(0);
}

On an RHEL 5 machine, and also on Mac OS X (10.7.5), the output was:

0x00000000 = 00000000 = 00000000 = 0000000000
0x00000006 = 0X000006 = 0X00000006 = 0x00000006
0x00000067 = 0X000067 = 0X00000067 = 0x00000067
0x00000678 = 0X000678 = 0X00000678 = 0x00000678
0x00006789 = 0X006789 = 0X00006789 = 0x00006789
0x0006789A = 0X06789A = 0X0006789A = 0x0006789a
0x006789AB = 0X6789AB = 0X006789AB = 0x006789ab
0x06789ABC = 0X6789ABC = 0X06789ABC = 0x06789abc
0x6789ABCD = 0X6789ABCD = 0X6789ABCD = 0x6789abcd

I'm a little surprised at the treatment of 0; I'm not clear why the 0X prefix is omitted, but with two separate systems doing it, it must be standard. It confirms my prejudices against the # option.


The treatment of zero is according to the standard.

ISO/IEC 9899:2011 §7.21.6.1 The fprintf function

¶6 The flag characters and their meanings are:
...
# The result is converted to an "alternative form". ... For x (or X) conversion, a nonzero result has 0x (or 0X) prefixed to it. ...

(Emphasis added.)


Note that using %#X will use upper-case letters for the hex digits and 0X as the prefix; using %#x will use lower-case letters for the hex digits and 0x as the prefix. If you prefer 0x as the prefix and upper-case letters, you have to code the 0x separately: 0x%X. Other format modifiers can be added as needed, of course.

For printing addresses, use the <inttypes.h> header and the uintptr_t type and the PRIXPTR format macro:

#include <inttypes.h>
#include <stdio.h>

int main(void)
{
    void *address = &address;  // &address has type void ** but it converts to void *
    printf("Address 0x%.12" PRIXPTR "\n", (uintptr_t)address);
    return 0;
}

Example output:

Address 0x7FFEE5B29428

Choose your poison on the length — I find that a precision of 12 works well for addresses on a Mac running macOS. Combined with the . to specify the minimum precision (digits), it formats addresses reliably. If you set the precision to 16, the extra 4 digits are always 0 in my experience on the Mac, but there's certainly a case to be made for using 16 instead of 12 in portable 64-bit code (but you'd use 8 for 32-bit code).

Code for printf function in C

Here's the GNU version of printf... you can see it passing in stdout to vfprintf:

__printf (const char *format, ...)
{
   va_list arg;
   int done;

   va_start (arg, format);
   done = vfprintf (stdout, format, arg);
   va_end (arg);

   return done;
}

See here.

Here's a link to vfprintf... all the formatting 'magic' happens here.

The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)

How to print binary number via printf

printf() doesn't directly support that. Instead you have to make your own function.

Something like:

while (n) {
    if (n & 1)
        printf("1");
    else
        printf("0");

    n >>= 1;
}
printf("\n");

Printing a char with printf

In C char gets promoted to int in expressions. That pretty much explains every question, if you think about it.

Source: The C Programming Language by Brian W.Kernighan and Dennis M.Ritchie

A must read if you want to learn C.

Also see this stack overflow page, where people much more experienced then me can explain it much better then I ever can.

What primitive data type is time_t?

Unfortunately, it's not completely portable. It's usually integral, but it can be any "integer or real-floating type".

How to display hexadecimal numbers in C?

Your code has no problem. It does print the way you want. Alternatively, you can do this:

printf("%04x",a);

Avoid trailing zeroes in printf()

This can't be done with the normal printf format specifiers. The closest you could get would be:

printf("%.6g", 359.013); // 359.013
printf("%.6g", 359.01);  // 359.01

but the ".6" is the total numeric width so

printf("%.6g", 3.01357); // 3.01357

breaks it.

What you can do is to sprintf("%.20g") the number to a string buffer then manipulate the string to only have N characters past the decimal point.

Assuming your number is in the variable num, the following function will remove all but the first N decimals, then strip off the trailing zeros (and decimal point if they were all zeros).

char str[50];
sprintf (str,"%.20g",num);  // Make the number.
morphNumericString (str, 3);
:    :
void morphNumericString (char *s, int n) {
    char *p;
    int count;

    p = strchr (s,'.');         // Find decimal point, if any.
    if (p != NULL) {
        count = n;              // Adjust for more or less decimals.
        while (count >= 0) {    // Maximum decimals allowed.
             count--;
             if (*p == '\0')    // If there's less than desired.
                 break;
             p++;               // Next character.
        }

        *p-- = '\0';            // Truncate string.
        while (*p == '0')       // Remove trailing zeros.
            *p-- = '\0';

        if (*p == '.') {        // If all decimals were zeros, remove ".".
            *p = '\0';
        }
    }
}

If you're not happy with the truncation aspect (which would turn 0.12399 into 0.123 rather than rounding it to 0.124), you can actually use the rounding facilities already provided by printf. You just need to analyse the number before-hand to dynamically create the widths, then use those to turn the number into a string:

#include <stdio.h>

void nDecimals (char *s, double d, int n) {
    int sz; double d2;

    // Allow for negative.

    d2 = (d >= 0) ? d : -d;
    sz = (d >= 0) ? 0 : 1;

    // Add one for each whole digit (0.xx special case).

    if (d2 < 1) sz++;
    while (d2 >= 1) { d2 /= 10.0; sz++; }

    // Adjust for decimal point and fractionals.

    sz += 1 + n;

    // Create format string then use it.

    sprintf (s, "%*.*f", sz, n, d);
}

int main (void) {
    char str[50];
    double num[] = { 40, 359.01335, -359.00999,
        359.01, 3.01357, 0.111111111, 1.1223344 };
    for (int i = 0; i < sizeof(num)/sizeof(*num); i++) {
        nDecimals (str, num[i], 3);
        printf ("%30.20f -> %s\n", num[i], str);
    }
    return 0;
}

The whole point of nDecimals() in this case is to correctly work out the field widths, then format the number using a format string based on that. The test harness main() shows this in action:

  40.00000000000000000000 -> 40.000
 359.01335000000000263753 -> 359.013
-359.00999000000001615263 -> -359.010
 359.00999999999999090505 -> 359.010
   3.01357000000000008200 -> 3.014
   0.11111111099999999852 -> 0.111
   1.12233439999999995429 -> 1.122

Once you have the correctly rounded value, you can once again pass that to morphNumericString() to remove trailing zeros by simply changing:

nDecimals (str, num[i], 3);

into:

nDecimals (str, num[i], 3);
morphNumericString (str, 3);

(or calling morphNumericString at the end of nDecimals but, in that case, I'd probably just combine the two into one function), and you end up with:

  40.00000000000000000000 -> 40
 359.01335000000000263753 -> 359.013
-359.00999000000001615263 -> -359.01
 359.00999999999999090505 -> 359.01
   3.01357000000000008200 -> 3.014
   0.11111111099999999852 -> 0.111
   1.12233439999999995429 -> 1.122

Scanf/Printf double variable C

For variable argument functions like printf and scanf, the arguments are promoted, for example, any smaller integer types are promoted to int, float is promoted to double.

scanf takes parameters of pointers, so the promotion rule takes no effect. It must use %f for float* and %lf for double*.

printf will never see a float argument, float is always promoted to double. The format specifier is %f. But C99 also says %lf is the same as %f in printf:

C99 §7.19.6.1 The fprintf function

l (ell) Specifies that a following d, i, o, u, x, or X conversion specifier applies to a long int or unsigned long int argument; that a following n conversion specifier applies to a pointer to a long int argument; that a following c conversion specifier applies to a wint_t argument; that a following s conversion specifier applies to a pointer to a wchar_t argument; or has no effect on a following a, A, e, E, f, F, g, or G conversion specifier.

Is there a printf converter to print in binary format?

void print_bits (uintmax_t n)
{
    for (size_t i = 8 * sizeof (int); i-- != 0;)
    {
        char c;
        if ((n & (1UL << i)) != 0)
            c = '1';
        else
            c = '0';

        printf ("%c", c);

    }
}

Not a cover-absolutely-everywhere solution but if you want something quick, and easy to understand, I'm suprised no one has proposed this solution yet.

What is the printf format specifier for bool?

If you like C++ better than C, you can try this:

#include <ios>
#include <iostream>

bool b = IsSomethingTrue();
std::cout << std::boolalpha << b;

Is there a way to have printf() properly print out an array (of floats, say)?

C is not object oriented programming (OOP) language. So you can not use properties in OOP. Eg. There is no .length property in C. So you need to use loops for your task.

How to print a float with 2 decimal places in Java?

You can use the printf method, like so:

System.out.printf("%.2f", val);

In short, the %.2f syntax tells Java to return your variable (val) with 2 decimal places (.2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).

There are other conversion characters you can use besides f:

  • d: decimal integer
  • o: octal integer
  • e: floating-point in scientific notation

Format specifier %02x

%x is a format specifier that format and output the hex value. If you are providing int or long value, it will convert it to hex value.

%02x means if your provided value is less than two digits then 0 will be prepended.

You provided value 16843009 and it has been converted to 1010101 which a hex value.

Difference between fprintf, printf and sprintf?

You can also do very useful things with vsnprintf() function:

$ cat test.cc
#include <exception>
#include <stdarg.h>
#include <stdio.h>

struct exception_fmt : std::exception
{
    exception_fmt(char const* fmt, ...) __attribute__ ((format(printf,2,3)));
    char const* what() const throw() { return msg_; }
    char msg_[0x800];
};

exception_fmt::exception_fmt(char const* fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    vsnprintf(msg_, sizeof msg_, fmt, ap);
    va_end(ap);
}

int main(int ac, char** av)
{
    throw exception_fmt("%s: bad number of arguments %d", *av, ac);
}

$ g++ -Wall -o test test.cc

$ ./test
terminate called after throwing an instance of 'exception_fmt'
  what():  ./test: bad number of arguments 1
Aborted (core dumped)

Printing chars and their ASCII-code in C

Nothing can be more simple than this

#include <stdio.h>  

int main()  
{  
    int i;  

    for( i=0 ; i<=255 ; i++ ) /*ASCII values ranges from 0-255*/  
    {  
        printf("ASCII value of character %c = %d\n", i, i);  
    }  

    return 0;  
}   

Source: program to print ASCII value of all characters

printf formatting (%d versus %u)

%u is used for unsigned integer. Since the memory address given by the signed integer address operator %d is -12, to get this value in unsigned integer, Compiler returns the unsigned integer value for this address.

Where is `%p` useful with printf?

When you need to debug, use printf with %p option is really helpful. You see 0x0 when you have a NULL value.

'printf' vs. 'cout' in C++

With primitives, it probably doesn't matter entirely which one you use. I say where it gets usefulness is when you want to output complex objects.

For example, if you have a class,

#include <iostream>
#include <cstdlib>

using namespace std;

class Something
{
public:
        Something(int x, int y, int z) : a(x), b(y), c(z) { }
        int a;
        int b;
        int c;

        friend ostream& operator<<(ostream&, const Something&);
};

ostream& operator<<(ostream& o, const Something& s)
{
        o << s.a << ", " << s.b << ", " << s.c;
        return o;
}

int main(void)
{
        Something s(3, 2, 1);

        // output with printf
        printf("%i, %i, %i\n", s.a, s.b, s.c);

        // output with cout
        cout << s << endl;

        return 0;
}

Now the above might not seem all that great, but let's suppose you have to output this in multiple places in your code. Not only that, let's say you add a field "int d." With cout, you only have to change it in once place. However, with printf, you'd have to change it in possibly a lot of places and not only that, you have to remind yourself which ones to output.

With that said, with cout, you can reduce a lot of times spent with maintenance of your code and not only that if you re-use the object "Something" in a new application, you don't really have to worry about output.

Is there a way to specify how many characters of a string to print out using printf()?

The basic way is:

printf ("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars");

The other, often more useful, way is:

printf ("Here are the first %d chars: %.*s\n", 8, 8, "A string that is more than 8 chars");

Here, you specify the length as an int argument to printf(), which treats the '*' in the format as a request to get the length from an argument.

You can also use the notation:

printf ("Here are the first 8 chars: %*.*s\n",
        8, 8, "A string that is more than 8 chars");

This is also analogous to the "%8.8s" notation, but again allows you to specify the minimum and maximum lengths at runtime - more realistically in a scenario like:

printf("Data: %*.*s Other info: %d\n", minlen, maxlen, string, info);

The POSIX specification for printf() defines these mechanisms.

How can one print a size_t variable portably using the printf family?

For C89, use %lu and cast the value to unsigned long:

size_t foo;
...
printf("foo = %lu\n", (unsigned long) foo);

For C99 and later, use %zu:

size_t foo;
...
printf("foo = %zu\n", foo);

How to print a string in C++

#include <iostream>
std::cout << someString << "\n";

or

printf("%s\n",someString.c_str());

printf() prints whole array

Incase of arrays, the base address (i.e. address of the array) is the address of the 1st element in the array. Also the array name acts as a pointer.

Consider a row of houses (each is an element in the array). To identify the row, you only need the 1st house address.You know each house is followed by the next (sequential).Getting the address of the 1st house, will also give you the address of the row.

Incase of string literals(character arrays defined at declaration), they are automatically appended by \0.

printf prints using the format specifier and the address provided. Since, you use %s it prints from the 1st address (incrementing the pointer using arithmetic) until '\0'

Integer ASCII value to character in BASH using printf

For capital letters:

i=67
letters=({A..Z})
echo "${letters[$i-65]}"

Output:

C

How can you print multiple variables inside a string using printf?

printf("\nmaximum of %d and %d is = %d",a,b,c);

How to append strings using sprintf?

int length = 0;
length += sprintf(Buffer+length, "Hello World");
length += sprintf(Buffer+length, "Good Morning");
length += sprintf(Buffer+length, "Good Afternoon");

Here is a version with some resistance to errors. It is useful if you do not care when errors happen so long as you can continue along your merry way when they do.

int bytes_added( int result_of_sprintf )
{
    return (result_of_sprintf > 0) ? result_of_sprintf : 0;
}

int length = 0;
length += bytes_added(sprintf(Buffer+length, "Hello World"));
length += bytes_added(sprintf(Buffer+length, "Good Morning"));
length += bytes_added(sprintf(Buffer+length, "Good Afternoon"));

How to print multiple variable lines in Java

Or try this one:

System.out.println("First Name: " + firstname + " Last Name: "+ lastname +".");

Good luck!

How to printf "unsigned long" in C?

  • %lu for unsigned long
  • %llu for unsigned long long

Printing 1 to 1000 without loop or conditionals

Amazing how easy it becomes if you drop the "has to be in C or C++" requirement:

Unix shell:

echo {1..1000} | tr ' ' '\n'

or

yes | nl | awk '{print $1}' | head -1000

If you're running on a Unix variant that doesn't have the yes command, use some other process that generates at least 1000 lines:

find / 2> /dev/null | nl | awk '{print $1}' | head -1000

or

cat /dev/zero | uuencode - | nl | awk '{print $1}' | head -1000

or

head -1000 /etc/termcap | nl -s: | cut -d: -f1

Printf long long int in C with GCC?

Try to update your compiler, I'm using GCC 4.7 on Windows 7 Starter x86 with MinGW and it compiles fine with the same options both in C99 and C11.

How to change Android usb connect mode to charge only?

Nothing worked until I went this way: Settings>Developer options>Default USB configuration now you can choose your default USB connection purpose.

JSON.stringify output to div in pretty print way

Consider your REST API returns:

{"Intent":{"Command":"search","SubIntent":null}}

Then you can do the following to print it in a nice format:

<pre id="ciResponseText">Output will de displayed here.</pre>   

var ciResponseText = document.getElementById('ciResponseText');
var obj = JSON.parse(http.response);
ciResponseText.innerHTML = JSON.stringify(obj, undefined, 2);   

How to check that Request.QueryString has a specific value or not in ASP.NET?

To resolve your problem, write the following line on your page's Page_Load method.

if (String.IsNullOrEmpty(Request.QueryString["aspxerrorpath"])) return;

.Net 4.0 provides more closer look to null, empty or whitespace strings, use it as shown in the following line:

if(string.IsNullOrWhiteSpace(Request.QueryString["aspxerrorpath"])) return;

This will not run your next statements (your business logics) if query string does not have aspxerrorpath.

Automatically add all files in a folder to a target using CMake?

Extension for @Kleist answer:

Since CMake 3.12 additional option CONFIGURE_DEPENDS is supported by commands file(GLOB) and file(GLOB_RECURSE). With this option there is no needs to manually re-run CMake after addition/deletion of a source file in the directory - CMake will be re-run automatically on next building the project.

However, the option CONFIGURE_DEPENDS implies that corresponding directory will be re-checked every time building is requested, so build process would consume more time than without CONFIGURE_DEPENDS.

Even with CONFIGURE_DEPENDS option available CMake documentation still does not recommend using file(GLOB) or file(GLOB_RECURSE) for collect the sources.

How To Convert A Number To an ASCII Character?

you can simply cast it.

char c = (char)100;

Get user info via Google API

scope - https://www.googleapis.com/auth/userinfo.profile

return youraccess_token = access_token

get https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=youraccess_token

you will get json:

{
 "id": "xx",
 "name": "xx",
 "given_name": "xx",
 "family_name": "xx",
 "link": "xx",
 "picture": "xx",
 "gender": "xx",
 "locale": "xx"
}

To Tahir Yasin:

This is a php example.
You can use json_decode function to get userInfo array.

$q = 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=xxx';
$json = file_get_contents($q);
$userInfoArray = json_decode($json,true);
$googleEmail = $userInfoArray['email'];
$googleFirstName = $userInfoArray['given_name'];
$googleLastName = $userInfoArray['family_name'];

An explicit value for the identity column in table can only be specified when a column list is used and IDENTITY_INSERT is ON SQL Server

SET IDENTITY_INSERT tableA ON

You have to make a column list for your INSERT statement:

INSERT Into tableA ([id], [c2], [c3], [c4], [c5] ) 
SELECT [id], [c2], [c3], [c4], [c5] FROM tableB

not like "INSERT Into tableA SELECT ........"

SET IDENTITY_INSERT tableA OFF

How to check if an array is empty?

Your test:

if (numberSet.length < 2) {
    return 0;
}

should be done before you allocate an array of that length in the below statement:

int[] differenceArray = new int[numberSet.length-1];

else you are already creating an array of size -1, when the numberSet.length = 0. That is quite odd. So, move your if statement as the first statement in your method.

Docker can't connect to docker daemon

A lot of answers already but in the hope that this helps someone. This is an issue that occurs when you install docker via snap. Running via sudo would allow you to connect to the daemon, but this leads to other issues. The solution is to perform some steps BEFORE you install the snap package making the complete list of steps:

sudo addgroup --system docker
sudo adduser $USER docker
newgrp docker
sudo snap install docker

After doing this, docker will connect to the daemon and work without sudo, no restart required.

https://github.com/docker-archive/docker-snap/issues/1#issuecomment-423778054

Not an enclosing class error Android Studio

you are calling the context of not existing activity...so just replace your code in onClick(View v) as Intent intent=new Intent(this,Katra_home.class); startActivity(intent); it will definitely works....

How to delete mysql database through shell command

You can remove database directly as:

$ mysqladmin -h [host] -u [user] -p drop [database_name]

[Enter Password]

Do you really want to drop the 'hairfree' database [y/N]: y

How to determine if string contains specific substring within the first X characters

shorter version:

found = Value1.StartsWith("abc");

sorry, but I am a stickler for 'less' code.


Given the edit of the questioner I would actually go with something that accepted an offset, this may in fact be a Great place to an Extension method that overloads StartsWith

public static class StackOverflowExtensions
{
    public static bool StartsWith(this String val, string findString, int count)
    {
        return val.Substring(0, count).Contains(findString);
    }
}

SQL to search objects, including stored procedures, in Oracle

i'm not sure if i understand you, but to query the source code of your triggers, procedures, package and functions you can try with the "user_source" table.

select * from user_source

How to Alter a table for Identity Specification is identity SQL Server

You don't set value to default in a table. You should clear the option "Default value or Binding" first.

Is it possible to create static classes in PHP (like in C#)?

you can have those "static"-like classes. but i suppose, that something really important is missing: in php you don't have an app-cycle, so you won't get a real static (or singleton) in your whole application...

see Singleton in PHP

How to merge every two lines into one from the command line?

A slight variation on glenn jackman's answer using paste: if the value for the -d delimiter option contains more than one character, paste cycles through the characters one by one, and combined with the -s options keeps doing that while processing the same input file.

This means that we can use whatever we want to have as the separator plus the escape sequence \n to merge two lines at a time.

Using a comma:

$ paste -s -d ',\n' infile
KEY 4048:1736 string,3
KEY 0:1772 string,1
KEY 4192:1349 string,1
KEY 7329:2407 string,2
KEY 0:1774 string,1

and the dollar sign:

$ paste -s -d '$\n' infile
KEY 4048:1736 string$3
KEY 0:1772 string$1
KEY 4192:1349 string$1
KEY 7329:2407 string$2
KEY 0:1774 string$1

What this cannot do is use a separator consisting of multiple characters.

As a bonus, if the paste is POSIX compliant, this won't modify the newline of the last line in the file, so for an input file with an odd number of lines like

KEY 4048:1736 string
3
KEY 0:1772 string

paste won't tack on the separation character on the last line:

$ paste -s -d ',\n' infile
KEY 4048:1736 string,3
KEY 0:1772 string

Java: How to read a text file

Look at this example, and try to do your own:

import java.io.*;

public class ReadFile {

    public static void main(String[] args){
        String string = "";
        String file = "textFile.txt";

        // Reading
        try{
            InputStream ips = new FileInputStream(file);
            InputStreamReader ipsr = new InputStreamReader(ips);
            BufferedReader br = new BufferedReader(ipsr);
            String line;
            while ((line = br.readLine()) != null){
                System.out.println(line);
                string += line + "\n";
            }
            br.close();
        }
        catch (Exception e){
            System.out.println(e.toString());
        }

        // Writing
        try {
            FileWriter fw = new FileWriter (file);
            BufferedWriter bw = new BufferedWriter (fw);
            PrintWriter fileOut = new PrintWriter (bw);
                fileOut.println (string+"\n test of read and write !!");
            fileOut.close();
            System.out.println("the file " + file + " is created!");
        }
        catch (Exception e){
            System.out.println(e.toString());
        }
    }
}

Return background color of selected cell

If you are looking at a Table, a Pivot Table, or something with conditional formatting, you can try:

ActiveCell.DisplayFormat.Interior.Color

This also seems to work just fine on regular cells.

Adding Image to xCode by dragging it from File

Add the image to Your project by clicking File -> "Add Files to ...".

Then choose the image in ImageView properties (Utilities -> Attributes Inspector).

Why do table names in SQL Server start with "dbo"?

dbo is the default schema in SQL Server. You can create your own schemas to allow you to better manage your object namespace.

how to convert image to byte array in java?

If you are using JDK 7 you can use the following code..

import java.nio.file.Files;
import java.io.File;

File fi = new File("myfile.jpg");
byte[] fileContent = Files.readAllBytes(fi.toPath())

Mismatched anonymous define() module

Or you can use this approach.

  • Add require.js in your code base
  • then load your script through that code

<script data-main="js/app.js" src="js/require.js"></script>

What it will do it will load your script after loading require.js.

Calculate the center point of multiple latitude/longitude coordinate pairs

very nice solutions, just what i needed for my swift project, so here's a swift port. thanks & here's also a playground project: https://github.com/ppoh71/playgounds/tree/master/centerLocationPoint.playground

/*
* calculate the center point of multiple latitude longitude coordinate-pairs
*/

import CoreLocation
import GLKit

var LocationPoints = [CLLocationCoordinate2D]()

//add some points to Location ne, nw, sw, se , it's a rectangle basicaly
LocationPoints.append(CLLocationCoordinate2D(latitude: 37.627512369999998, longitude: -122.38780611999999))
LocationPoints.append(CLLocationCoordinate2D(latitude: 37.627512369999998, longitude:  -122.43105867))
LocationPoints.append(CLLocationCoordinate2D(latitude: 37.56502528, longitude: -122.43105867))
LocationPoints.append(CLLocationCoordinate2D(latitude: 37.56502528, longitude: -122.38780611999999))

// center func
func getCenterCoord(LocationPoints: [CLLocationCoordinate2D]) -> CLLocationCoordinate2D{

    var x:Float = 0.0;
    var y:Float = 0.0;
    var z:Float = 0.0;

    for points in LocationPoints {

     let lat = GLKMathDegreesToRadians(Float(points.latitude));
     let long = GLKMathDegreesToRadians(Float(points.longitude));

        x += cos(lat) * cos(long);
        y += cos(lat) * sin(long);
        z += sin(lat);
    }

    x = x / Float(LocationPoints.count);
    y = y / Float(LocationPoints.count);
    z = z / Float(LocationPoints.count);

    let resultLong = atan2(y, x);
    let resultHyp = sqrt(x * x + y * y);
    let resultLat = atan2(z, resultHyp);



    let result = CLLocationCoordinate2D(latitude: CLLocationDegrees(GLKMathRadiansToDegrees(Float(resultLat))), longitude: CLLocationDegrees(GLKMathRadiansToDegrees(Float(resultLong))));

    return result;

}

//get the centerpoint
var centerPoint = getCenterCoord(LocationPoints)
print("Latitude: \(centerPoint.latitude) / Longitude: \(centerPoint.longitude)")

Having both a Created and Last Updated timestamp columns in MySQL 4.0

For mysql 5.7.21 I use the following and works fine:

CREATE TABLE Posts ( modified_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP )

Table fixed header and scrollable body

First add some markup for a bootstrap table. Here I created a striped table but also have added a custom table class .table-scroll which adds vertical scroll bar to the table and makes the table header fixed while scrolling down.

<div class="col-xs-8 col-xs-offset-2 well">
    <table class="table table-scroll table-striped">
        <thead>
            <tr>
                <th>#</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>County</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>Andrew</td>
                <td>Jackson</td>
                <td>Washington</td>
            </tr>
            <tr>
                <td>2</td>
                <td>Thomas</td>
                <td>Marion</td>
                <td>Jackson</td>
            </tr>
            <tr>
                <td>3</td>
                <td>Benjamin</td>
                <td>Warren</td>
                <td>Lincoln</td>
            </tr>
            <tr>
                <td>4</td>
                <td>Grant</td>
                <td>Wayne</td>
                <td>Union</td>
            </tr>
            <tr>
                <td>5</td>
                <td>John</td>
                <td>Adams</td>
                <td>Marshall</td>
            </tr>
            <tr>
                <td>6</td>
                <td>Morgan</td>
                <td>Lee</td>
                <td>Lake</td>
            </tr>
            <tr>
                <td>7</td>
                <td>John</td>
                <td>Henry</td>
                <td>Brown</td>
            </tr>
            <tr>
                <td>8</td>
                <td>William</td>
                <td>Jacob</td>
                <td>Orange</td>
            </tr>
            <tr>
                <td>9</td>
                <td>Kelly</td>
                <td>Davidson</td>
                <td>Taylor</td>
            </tr>
            <tr>
                <td>10</td>
                <td>Colleen</td>
                <td>Hurst</td>
                <td>Randolph</td>
            </tr>
            <tr>
                <td>11</td>
                <td>Rhona</td>
                <td>Herrod</td>
                <td>Cumberland</td>
            </tr>
            <tr>
                <td>12</td>
                <td>Jane</td>
                <td>Paul</td>
                <td>Marshall</td>
            </tr>
            <tr>
                <td>13</td>
                <td>Ashton</td>
                <td>Fox</td>
                <td>Calhoun</td>
            </tr>
            <tr>
                <td>14</td>
                <td>Garrett</td>
                <td>John</td>
                <td>Madison</td>
            </tr>
            <tr>
                <td>15</td>
                <td>Fredie</td>
                <td>Winters</td>
                <td>Washington</td>
            </tr>
        </tbody>
    </table>
</div>

css

.table-scroll tbody {
    position: absolute;
    overflow-y: scroll;
    height: 250px;
}

.table-scroll tr {
    width: 100%;
    table-layout: fixed;
    display: inline-table;
}

.table-scroll thead > tr > th {
    border: none;
}

How to connect android emulator to the internet

I have a windows 7 machine(64bit) and my emulator wasn't working. After a lot of looking around, I ended up statical adding my router to the network DNS properties(192.168.1.1). And it started working.

add new row in gridview after binding C#, ASP.net

You can run this example directly.

aspx page:

<asp:GridView ID="grd" runat="server" DataKeyNames="PayScale" AutoGenerateColumns="false">
    <Columns>
        <asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Pay Scale">
            <ItemTemplate>
                <asp:TextBox ID="txtPayScale" runat="server" Text='<%# Eval("PayScale") %>'></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Increment Amount">
            <ItemTemplate>
                <asp:TextBox ID="txtIncrementAmount" runat="server" Text='<%# Eval("IncrementAmount") %>'></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderStyle-HorizontalAlign="Left" HeaderText="Period">
            <ItemTemplate>
                <asp:TextBox ID="txtPeriod" runat="server" Text='<%# Eval("Period") %>'></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<asp:Button ID="btnAddRow" runat="server" OnClick="btnAddRow_Click" Text="Add Row" />

C# code:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        grd.DataSource = GetTableWithInitialData(); // get first initial data
        grd.DataBind();
    }
}

public DataTable GetTableWithInitialData() // this might be your sp for select
{
    DataTable table = new DataTable();
    table.Columns.Add("PayScale", typeof(string));
    table.Columns.Add("IncrementAmount", typeof(string));
    table.Columns.Add("Period", typeof(string));

    table.Rows.Add(1, "David", "1");
    table.Rows.Add(2, "Sam", "2");
    table.Rows.Add(3, "Christoff", "1.5");
    return table;
}

protected void btnAddRow_Click(object sender, EventArgs e)
{
    DataTable dt = GetTableWithNoData(); // get select column header only records not required
    DataRow dr;

    foreach (GridViewRow gvr in grd.Rows)
    {
        dr = dt.NewRow();

        TextBox txtPayScale = gvr.FindControl("txtPayScale") as TextBox;
        TextBox txtIncrementAmount = gvr.FindControl("txtIncrementAmount") as TextBox;
        TextBox txtPeriod = gvr.FindControl("txtPeriod") as TextBox;

        dr[0] = txtPayScale.Text;
        dr[1] = txtIncrementAmount.Text;
        dr[2] = txtPeriod.Text;

        dt.Rows.Add(dr); // add grid values in to row and add row to the blank table
    }

    dr = dt.NewRow(); // add last empty row
    dt.Rows.Add(dr);

    grd.DataSource = dt; // bind new datatable to grid
    grd.DataBind();
}

public DataTable GetTableWithNoData() // returns only structure if the select columns
{
    DataTable table = new DataTable();
    table.Columns.Add("PayScale", typeof(string));
    table.Columns.Add("IncrementAmount", typeof(string));
    table.Columns.Add("Period", typeof(string));
    return table;
}

How do I specify unique constraint for multiple columns in MySQL?

MySql 5 or higher behaves like this (I've just tested):

  • you can define unique constraints involving nullable columns. Say you define a constraint unique (A, B) where A is not nullable but B is
  • when evaluating such a constraint you can have (A, null) as many times you want (same A value!)
  • you can only have one (A, not null B) pair

Example: PRODUCT_NAME, PRODUCT_VERSION 'glass', null 'glass', null 'wine', 1

Now if you try to insert ('wine' 1) again it will report a constraint violation Hope this helps

Pass a datetime from javascript to c# (Controller)

The following format should work:

$.ajax({
    type: "POST",
    url: "@Url.Action("refresh", "group")",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({ 
        myDate: '2011-04-02 17:15:45'
    }),
    success: function (result) {
        //do something
    },
    error: function (req, status, error) {
        //error                        
    }
});

MessageBodyWriter not found for media type=application/json

Ensure that you have following JARS in place: 1) jackson-core-asl-1.9.13 2) jackson-jaxrs-1.9.13 3) jackson-mapper-asl-1.9.13 4) jackson-xc-1.9.13

rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

OK - I had the same problem. I didn't want to use "config.assets.compile = true" - I had to add all of my .css files to the list in config/environments/production.rb:

config.assets.precompile += %w( carts.css )

Then I had to create (and later delete) tmp/restart.txt

I consistently used the stylesheet_link_tag helper, so I found all the extra css files I needed to add with:

find . \( -type f -o -type l \) -exec grep stylesheet_link_tag {} /dev/null \;

Spring - No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call

boardRepo.deleteByBoardId(id);

Faced the same issue. GOT javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread

I resolved it by adding @Transactional annotation above the controller/service.

Should I set max pool size in database connection string? What happens if I don't?

We can define maximum pool size in following way:

                <pool> 
               <min-pool-size>5</min-pool-size>
                <max-pool-size>200</max-pool-size>
                <prefill>true</prefill>
                <use-strict-min>true</use-strict-min>
                <flush-strategy>IdleConnections</flush-strategy>
                </pool>

Is there a <meta> tag to turn off caching in all browsers?

Try using

    <META HTTP-EQUIV="Pragma" CONTENT="no-cache">
    <META HTTP-EQUIV="Expires" CONTENT="-1">

Cause of No suitable driver found for

great I had the similar problem. The advice for all is to check jdbc url sintax

The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

You may get your answer here: Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

UPDATE

It might be due to various issues.I cant say which one is there in your case. It may be because:

  • DCOM is not enabled in host pc or target pc or on both
  • your firewall or even your antivirus is preventing the access
  • any WMI related service is disabled

Some WMI related services are:

  • Remote Access Auto Connection Manager
  • Remote Access Connection Manager
  • Remote Procedure Call (RPC)
  • Remote Procedure Call (RPC) Locator
  • Remote Registry

For DCOM settings refer to registry key HKLM\Software\Microsoft\OLE, value EnableDCOM. The value should be set to 'Y'.

How to enumerate an object's properties in Python?

If you're looking for reflection of all properties, the answers above are great.

If you're simply looking to get the keys of a dictionary (which is different from an 'object' in Python), use

my_dict.keys()

my_dict = {'abc': {}, 'def': 12, 'ghi': 'string' }
my_dict.keys() 
> ['abc', 'def', 'ghi']

Aesthetics must either be length one, or the same length as the dataProblems

I hit this error because I was specifying a label attribute in my geom (geom_text) but was specifying a color in the top level aes:

df <- read.table('match-stats.tsv', sep='\t')
library(ggplot2)

# don't do this!
ggplot(df, aes(x=V6, y=V1, color=V1)) +
  geom_text(angle=45, label=df$V1, size=2)

To fix this, I just moved the label attribute out of the geom and into the top level aes:

df <- read.table('match-stats.tsv', sep='\t')
library(ggplot2)

# do this!
ggplot(df, aes(x=V6, y=V1, color=V1, label=V1)) +
  geom_text(angle=45, size=2)

AngularJS resource promise

/*link*/
$q.when(scope.regions).then(function(result) {
    console.log(result);
});
var Regions = $resource('mocks/regions.json');
$scope.regions = Regions.query().$promise.then(function(response) {
    return response;
});

Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings

Here's some future-proof code for browsers that may lack escape/unescape(). Note that IE 9 and older don't support atob/btoa(), so you'd need to use custom base64 functions for them.

// Polyfill for escape/unescape
if( !window.unescape ){
    window.unescape = function( s ){
        return s.replace( /%([0-9A-F]{2})/g, function( m, p ) {
            return String.fromCharCode( '0x' + p );
        } );
    };
}
if( !window.escape ){
    window.escape = function( s ){
        var chr, hex, i = 0, l = s.length, out = '';
        for( ; i < l; i ++ ){
            chr = s.charAt( i );
            if( chr.search( /[A-Za-z0-9\@\*\_\+\-\.\/]/ ) > -1 ){
                out += chr; continue; }
            hex = s.charCodeAt( i ).toString( 16 );
            out += '%' + ( hex.length % 2 != 0 ? '0' : '' ) + hex;
        }
        return out;
    };
}

// Base64 encoding of UTF-8 strings
var utf8ToB64 = function( s ){
    return btoa( unescape( encodeURIComponent( s ) ) );
};
var b64ToUtf8 = function( s ){
    return decodeURIComponent( escape( atob( s ) ) );
};

A more comprehensive example for UTF-8 encoding and decoding can be found here: http://jsfiddle.net/47zwb41o/

Convert Mat to Array/Vector in OpenCV

byte * matToBytes(Mat image)
{
   int size = image.total() * image.elemSize();
   byte * bytes = new byte[size];  //delete[] later
   std::memcpy(bytes,image.data,size * sizeof(byte));
}

How to change MySQL data directory?

In case you're a Windows user and landed here to find out that all answers are for Linux Users, don't get disappointed! I won't let you waste time the way I did.

A little of bullshit talk before solution:

MySQL uses a Data directory to store the data of different databases you create. Well, in the end, it has to store them in the form of files with some added jugglery in the application and file format to ensure the Database promises that you learned in Databases classes are intact.

Now you want to make sure there is enough space to store large databases which you might create in future, and so you thought, Hey! I want to put it into another drive which has got more space.

So you do the following.

Step - 1 : Stopping MySQL service.

  Window Key + R - will open Run
  servies.msc    - will open services manager
  Locate MySQL80 (80 is for version 8.0, look for the one you've).
  Stop it.       (Right click, Stop)

Step - 2 : Finding out the current Data directory

 Goto C:\ProgramData\MySQL\MySQL Server 8.0

By default, there should be a folder here named Data, this is the one which is used by MySQL in default setting (provided they haven't found another better location), but let's check that out.

Find my.ini file, should be right there.

Open it in an editor (Notepad++ maybe).

Do a CTRL+F to find out datadir in the file.

Whatever is mentioned here is the actual location currently under use by MySQL for data directory. This is what you want to change.

Step - 3 : Replacing it with a new data directory.

Let's say you want your new data directory to be W:__MySQL_Data. Let's change datadir value in my.ini file to this value. Keep the previous value commented so that you won't have to remember it.

 # Path to the database root
 # datadir=C:/ProgramData/MySQL/MySQL Server 8.0/Data
   datadir=W:/__MySQL_Data

Now use xcopy to copy the default datadir to W:\. Launch command prompt (Window + R, cmd, Enter)

 >> xcopy "\C:\ProgramData\MySQL\MySQL Server 8.0" "W:\" /E /H /K /O /X

And rename the copied folder to the new datadir value that you changed. Here: W:/__MySQL_Data

Why not simply copy? Well because that's not COOL!, this helps you not lose permissions on the copied folder, so that when you restart MySQL80, it won't give a stupid error: "The MySQL80 service on Local Computer started and then stopped. Some services stop automatically if they are not in use by other services or programs." - Courtesy:Microsoft

Step - 4 : Restarting the service

 Well, go back to the Services Manager to Start again, 
 "MySQL80" that you stopped, to restart it again.

Step - 5 : Done! Now get back to work !!

Reading DataSet

If this is from a SQL Server datebase you could issue this kind of query...

Select Top 1 DepartureTime From TrainSchedule where DepartureTime > 
GetUTCDate()
Order By DepartureTime ASC

GetDate() could also be used, not sure how dates are being stored.

I am not sure how the data is being stored and/or read.

Linq to Entities join vs groupjoin

Behaviour

Suppose you have two lists:

Id  Value
1   A
2   B
3   C

Id  ChildValue
1   a1
1   a2
1   a3
2   b1
2   b2

When you Join the two lists on the Id field the result will be:

Value ChildValue
A     a1
A     a2
A     a3
B     b1
B     b2

When you GroupJoin the two lists on the Id field the result will be:

Value  ChildValues
A      [a1, a2, a3]
B      [b1, b2]
C      []

So Join produces a flat (tabular) result of parent and child values.
GroupJoin produces a list of entries in the first list, each with a group of joined entries in the second list.

That's why Join is the equivalent of INNER JOIN in SQL: there are no entries for C. While GroupJoin is the equivalent of OUTER JOIN: C is in the result set, but with an empty list of related entries (in an SQL result set there would be a row C - null).

Syntax

So let the two lists be IEnumerable<Parent> and IEnumerable<Child> respectively. (In case of Linq to Entities: IQueryable<T>).

Join syntax would be

from p in Parent
join c in Child on p.Id equals c.Id
select new { p.Value, c.ChildValue }

returning an IEnumerable<X> where X is an anonymous type with two properties, Value and ChildValue. This query syntax uses the Join method under the hood.

GroupJoin syntax would be

from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }

returning an IEnumerable<Y> where Y is an anonymous type consisting of one property of type Parent and a property of type IEnumerable<Child>. This query syntax uses the GroupJoin method under the hood.

We could just do select g in the latter query, which would select an IEnumerable<IEnumerable<Child>>, say a list of lists. In many cases the select with the parent included is more useful.

Some use cases

1. Producing a flat outer join.

As said, the statement ...

from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }

... produces a list of parents with child groups. This can be turned into a flat list of parent-child pairs by two small additions:

from p in parents
join c in children on p.Id equals c.Id into g // <= into
from c in g.DefaultIfEmpty()               // <= flattens the groups
select new { Parent = p.Value, Child = c?.ChildValue }

The result is similar to

Value Child
A     a1
A     a2
A     a3
B     b1
B     b2
C     (null)

Note that the range variable c is reused in the above statement. Doing this, any join statement can simply be converted to an outer join by adding the equivalent of into g from c in g.DefaultIfEmpty() to an existing join statement.

This is where query (or comprehensive) syntax shines. Method (or fluent) syntax shows what really happens, but it's hard to write:

parents.GroupJoin(children, p => p.Id, c => c.Id, (p, c) => new { p, c })
       .SelectMany(x => x.c.DefaultIfEmpty(), (x,c) => new { x.p.Value, c?.ChildValue } )

So a flat outer join in LINQ is a GroupJoin, flattened by SelectMany.

2. Preserving order

Suppose the list of parents is a bit longer. Some UI produces a list of selected parents as Id values in a fixed order. Let's use:

var ids = new[] { 3,7,2,4 };

Now the selected parents must be filtered from the parents list in this exact order.

If we do ...

var result = parents.Where(p => ids.Contains(p.Id));

... the order of parents will determine the result. If the parents are ordered by Id, the result will be parents 2, 3, 4, 7. Not good. However, we can also use join to filter the list. And by using ids as first list, the order will be preserved:

from id in ids
join p in parents on id equals p.Id
select p

The result is parents 3, 7, 2, 4.

Assigning strings to arrays of characters

You can use this:

yylval.sval=strdup("VHDL + Volcal trance...");

Where yylval is char*. strdup from does the job.

Failed to load the JNI shared Library (JDK)

Working pairings of OS, JDK and Eclipse:


  • 32-bit OS | 32-bit JDK | 32-bit Eclipse (32-bit only)
  • 64-bit OS | 32-bit JDK | 32-bit Eclipse
  • 64-bit OS | 64-bit JDK | 64bit Eclipse (64-bit only)

I had several JDKs and JREs installed.

Each of them had their own entry in the PATH variable, all was working more or less.

Judging from the PATH variables, some installations were completely useless, since they were never used. Of course, the "inactive" Javas could be referenced manually from within Eclipse if I needed, but I never did that, so I really did not need them. (At least I thought so at that time...)

I cleaned up the mess, deinstalled all current Java's, installed only JDK + JRE 1.7 64-bit.

One of the Eclipse 'installations' failed afterwards with the Failed to Load the JNI shared Library and a given path relative to the fresh installed JDK where it thought the jvm.dll to be.

The failing Eclipse was the only one of all my IDEs that was still a 32-bit version on my otherwise all-64-bit setup.

Adding VM arguments, like so often mentioned, in the eclipse.ini was no use in my case (because I had only the wrong JDK/JRE to relate to.)

I was also unable to find out how to check if this Eclipse was a 32-bit or 64-bit version (I could not look it up in the Task Manager, since this Eclipse 'installation' would not start up. And since it had been a while since I had set it up, I could not remember its version either.)

In case you use a newer JDK and a older JRE you might be in for trouble, too, but then it is more likely a java.lang.UnsupportedClassVersionError appears, IIRC.

Using grep to search for a string that has a dot in it

You can escape the dot and other special characters using \

eg. grep -r "0\.49"

PHP check if file is an image

Native way to get the mimetype:

For PHP < 5.3 use mime_content_type()
For PHP >= 5.3 use finfo_open() or mime_content_type()

Alternatives to get the MimeType are exif_imagetype and getimagesize, but these rely on having the appropriate libs installed. In addition, they will likely just return image mimetypes, instead of the whole list given in magic.mime.

While mime_content_type is available from PHP 4.3 and is part of the FileInfo extension (which is enabled by default since PHP 5.3, except for Windows platforms, where it must be enabled manually, for details see here).

If you don't want to bother about what is available on your system, just wrap all four functions into a proxy method that delegates the function call to whatever is available, e.g.

function getMimeType($filename)
{
    $mimetype = false;
    if(function_exists('finfo_open')) {
        // open with FileInfo
    } elseif(function_exists('getimagesize')) {
        // open with GD
    } elseif(function_exists('exif_imagetype')) {
       // open with EXIF
    } elseif(function_exists('mime_content_type')) {
       $mimetype = mime_content_type($filename);
    }
    return $mimetype;
}

How to return PDF to browser in MVC?

I've run into similar problems and I've stumbled accross a solution. I used two posts, one from stack that shows the method to return for download and another one that shows a working solution for ItextSharp and MVC.

public FileStreamResult About()
{
    // Set up the document and the MS to write it to and create the PDF writer instance
    MemoryStream ms = new MemoryStream();
    Document document = new Document(PageSize.A4.Rotate());
    PdfWriter writer = PdfWriter.GetInstance(document, ms);

    // Open the PDF document
    document.Open();

    // Set up fonts used in the document
    Font font_heading_1 = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 19, Font.BOLD);
    Font font_body = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 9);

    // Create the heading paragraph with the headig font
    Paragraph paragraph;
    paragraph = new Paragraph("Hello world!", font_heading_1);

    // Add a horizontal line below the headig text and add it to the paragraph
    iTextSharp.text.pdf.draw.VerticalPositionMark seperator = new iTextSharp.text.pdf.draw.LineSeparator();
    seperator.Offset = -6f;
    paragraph.Add(seperator);

    // Add paragraph to document
    document.Add(paragraph);

    // Close the PDF document
    document.Close();

    // Hat tip to David for his code on stackoverflow for this bit
    // https://stackoverflow.com/questions/779430/asp-net-mvc-how-to-get-view-to-generate-pdf
    byte[] file = ms.ToArray();
    MemoryStream output = new MemoryStream();
    output.Write(file, 0, file.Length);
    output.Position = 0;

    HttpContext.Response.AddHeader("content-disposition","attachment; filename=form.pdf");


    // Return the output stream
    return File(output, "application/pdf"); //new FileStreamResult(output, "application/pdf");
}

Use string value from a cell to access worksheet of same name

This will only work to column Z, but you can drag this horizontally and vertically.

=INDIRECT("'"&$D$2&"'!"&CHAR((COLUMN()+64))&ROW())

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

We also had this problem when upgrading our system to Revive. After turning of GZIP we found the problem still persisted. Upon further investigation we found the file permissions where not correct after the upgrade. A simple recursive chmod did the trick.

Windows equivalent of $export

To translate your *nix style command script to windows/command batch style it would go like this:

SET PROJ_HOME=%USERPROFILE%/proj/111
SET PROJECT_BASEDIR=%PROJ_HOME%/exercises/ex1
mkdir "%PROJ_HOME%"

mkdir on windows doens't have a -p parameter : from the MKDIR /? help:

MKDIR creates any intermediate directories in the path, if needed.

which basically is what mkdir -p (or --parents for purists) on *nix does, as taken from the man guide

What is sharding and why is it important?

Sharding does more than just horizontal partitioning. According to the wikipedia article,

Horizontal partitioning splits one or more tables by row, usually within a single instance of a schema and a database server. It may offer an advantage by reducing index size (and thus search effort) provided that there is some obvious, robust, implicit way to identify in which partition a particular row will be found, without first needing to search the index, e.g., the classic example of the 'CustomersEast' and 'CustomersWest' tables, where their zip code already indicates where they will be found.

Sharding goes beyond this: it partitions the problematic table(s) in the same way, but it does this across potentially multiple instances of the schema. The obvious advantage would be that search load for the large partitioned table can now be split across multiple servers (logical or physical), not just multiple indexes on the same logical server.

Also,

Splitting shards across multiple isolated instances requires more than simple horizontal partitioning. The hoped-for gains in efficiency would be lost, if querying the database required both instances to be queried, just to retrieve a simple dimension table. Beyond partitioning, sharding thus splits large partitionable tables across the servers, while smaller tables are replicated as complete units

How to handle invalid SSL certificates with Apache HttpClient?

Used the following along with DefaultTrustManager and it worked in httpclient like charm. Thanks a ton!! @Kevin and every other contributor

    SSLContext ctx = null;
    SSLConnectionSocketFactory sslsf = null;
    try {

        ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
        SSLContext.setDefault(ctx);

        sslsf = new SSLConnectionSocketFactory(
                ctx,
                new String[] { "TLSv1" },
                null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());

    } catch (Exception e) {
        e.printStackTrace();
    }

     CloseableHttpClient client = HttpClients.custom()
            .setSSLSocketFactory(sslsf)
            .build();

How do I make a semi transparent background?

Although dated, not one answer on this thread can be used universally. Using rgba to create transparent color masks - that doesn't exactly explain how to do so with background images.

My solution works for background images or color backgrounds.

_x000D_
_x000D_
#parent {_x000D_
    font-family: 'Open Sans Condensed', sans-serif;_x000D_
    font-size: 19px;_x000D_
    text-transform: uppercase;_x000D_
    border-radius: 50%;_x000D_
    margin: 20px auto;_x000D_
    width: 125px;_x000D_
    height: 125px;_x000D_
    background-color: #476172;_x000D_
    background-image: url('https://unsplash.it/200/300/?random');_x000D_
    line-height: 29px;_x000D_
    text-align:center;_x000D_
}_x000D_
_x000D_
#content {_x000D_
    color: white;_x000D_
    height: 125px !important;_x000D_
    width: 125px !important;_x000D_
    display: table-cell;_x000D_
    border-radius: 50%;_x000D_
    vertical-align: middle;_x000D_
    background: rgba(0,0,0, .3);_x000D_
}
_x000D_
<h1 id="parent"><a href="" id="content" title="content" rel="home">Example</a></h1>
_x000D_
_x000D_
_x000D_

How to return an array from an AJAX call?

Use JSON to transfer data types (arrays and objects) between client and server.

In PHP:

In JavaScript:

PHP:

echo json_encode($id_numbers);

JavaScript:

id_numbers = JSON.parse(msg);

As Wolfgang mentioned, you can give a fourth parameter to jQuery to automatically decode JSON for you.

id_numbers = new Array();
$.ajax({
    url:"Example.php",
    type:"POST",
    success:function(msg){
        id_numbers = msg;
    },
    dataType:"json"
});

How to convert ActiveRecord results into an array of hashes

For current ActiveRecord (4.2.4+) there is a method to_hash on the Result object that returns an array of hashes. You can then map over it and convert to symbolized hashes:

# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
      {"id" => 2, "title" => "title_2", "body" => "body_2"},
      ...
     ]

result.to_hash.map(&:symbolize_keys)
# => [{:id => 1, :title => "title_1", :body => "body_1"},
      {:id => 2, :title => "title_2", :body => "body_2"},
      ...
     ]

See the ActiveRecord::Result docs for more info.

Sort array by value alphabetically php

asort() - Maintains key association: yes.

sort() - Maintains key association: no.

Source: http://php.net/manual/en/array.sorting.php

Owl Carousel Won't Autoplay

In my case autoPlay not working but autoplay is working fine

I only used this

<script src="plugins/owlcarousel/owl.carousel.js"></script>

no owl.autoplay.js is need it & my owl carousel version is @version 2.0.0

hope this thing help you :)

One-liner if statements, how to convert this if-else-statement

All you'd need in your case is:

return expression;

The reason why is that the expression itself evaluates to a boolean value of true or false, so it's redundant to have an if block (or even a ?: operator).

How to Customize a Progress Bar In Android

In case of complex ProgressBar like this,

enter image description here

use ClipDrawable.

NOTE : I've not used ProgressBar here in this example. I've achieved this using ClipDrawable by clipping image with Animation.

A Drawable that clips another Drawable based on this Drawable's current level value. You can control how much the child Drawable gets clipped in width and height based on the level, as well as a gravity to control where it is placed in its overall container. Most often used to implement things like progress bars, by increasing the drawable's level with setLevel().

NOTE : The drawable is clipped completely and not visible when the level is 0 and fully revealed when the level is 10,000.

I've used this two images to make this CustomProgressBar.

scall.png

scall.png

ballon_progress.png

ballon_progress.png

MainActivity.java

public class MainActivity extends ActionBarActivity {

private EditText etPercent;
private ClipDrawable mImageDrawable;

// a field in your class
private int mLevel = 0;
private int fromLevel = 0;
private int toLevel = 0;

public static final int MAX_LEVEL = 10000;
public static final int LEVEL_DIFF = 100;
public static final int DELAY = 30;

private Handler mUpHandler = new Handler();
private Runnable animateUpImage = new Runnable() {

    @Override
    public void run() {
        doTheUpAnimation(fromLevel, toLevel);
    }
};

private Handler mDownHandler = new Handler();
private Runnable animateDownImage = new Runnable() {

    @Override
    public void run() {
        doTheDownAnimation(fromLevel, toLevel);
    }
};

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

    etPercent = (EditText) findViewById(R.id.etPercent);

    ImageView img = (ImageView) findViewById(R.id.imageView1);
    mImageDrawable = (ClipDrawable) img.getDrawable();
    mImageDrawable.setLevel(0);
}

private void doTheUpAnimation(int fromLevel, int toLevel) {
    mLevel += LEVEL_DIFF;
    mImageDrawable.setLevel(mLevel);
    if (mLevel <= toLevel) {
        mUpHandler.postDelayed(animateUpImage, DELAY);
    } else {
        mUpHandler.removeCallbacks(animateUpImage);
        MainActivity.this.fromLevel = toLevel;
    }
}

private void doTheDownAnimation(int fromLevel, int toLevel) {
    mLevel -= LEVEL_DIFF;
    mImageDrawable.setLevel(mLevel);
    if (mLevel >= toLevel) {
        mDownHandler.postDelayed(animateDownImage, DELAY);
    } else {
        mDownHandler.removeCallbacks(animateDownImage);
        MainActivity.this.fromLevel = toLevel;
    }
}

public void onClickOk(View v) {
    int temp_level = ((Integer.parseInt(etPercent.getText().toString())) * MAX_LEVEL) / 100;

    if (toLevel == temp_level || temp_level > MAX_LEVEL) {
        return;
    }
    toLevel = (temp_level <= MAX_LEVEL) ? temp_level : toLevel;
    if (toLevel > fromLevel) {
        // cancel previous process first
        mDownHandler.removeCallbacks(animateDownImage);
        MainActivity.this.fromLevel = toLevel;

        mUpHandler.post(animateUpImage);
    } else {
        // cancel previous process first
        mUpHandler.removeCallbacks(animateUpImage);
        MainActivity.this.fromLevel = toLevel;

        mDownHandler.post(animateDownImage);
    }
}
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
android:orientation="vertical"
tools:context=".MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <EditText
        android:id="@+id/etPercent"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:inputType="number"
        android:maxLength="3" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Ok"
        android:onClick="onClickOk" />

</LinearLayout>

<FrameLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center">

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/scall" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/clip_source" />

</FrameLayout>

clip_source.xml

<?xml version="1.0" encoding="utf-8"?>
<clip xmlns:android="http://schemas.android.com/apk/res/android"
    android:clipOrientation="vertical"
    android:drawable="@drawable/ballon_progress"
    android:gravity="bottom" />

In case of complex HorizontalProgressBar just change cliporientation in clip_source.xml like this,

android:clipOrientation="horizontal"

You can download complete demo from here.

HTML/Javascript Button Click Counter

Through this code, you can get click count on a button.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Button</title>
    <link rel="stylesheet" type="text/css" href="css/button.css">
</head>
<body>
    <script src="js/button.js" type="text/javascript"></script>

    <button id="btn" class="btnst" onclick="myFunction()">0</button>
</body>
</html>
 ----------JAVASCRIPT----------
let count = 0;
function myFunction() {
  count+=1;
  document.getElementById("btn").innerHTML = count;

 }

How do I modify fields inside the new PostgreSQL JSON datatype?

The following plpython snippet might come in handy.

CREATE EXTENSION IF NOT EXISTS plpythonu;
CREATE LANGUAGE plpythonu;

CREATE OR REPLACE FUNCTION json_update(data json, key text, value text)
 RETURNS json
 AS $$
    import json
    json_data = json.loads(data)
    json_data[key] = value
    return json.dumps(json_data, indent=4)
 $$ LANGUAGE plpythonu;

-- Check how JSON looks before updating

SELECT json_update(content::json, 'CFRDiagnosis.mod_nbs', '1')
FROM sc_server_centre_document WHERE record_id = 35 AND template = 'CFRDiagnosis';

-- Once satisfied update JSON inplace

UPDATE sc_server_centre_document SET content = json_update(content::json, 'CFRDiagnosis.mod_nbs', '1')
WHERE record_id = 35 AND template = 'CFRDiagnosis';

Stop form refreshing page on submit

You can use this code for form submission without a page refresh. I have done this in my project.

$(function () {
    $('#myFormName').on('submit',function (e) {

              $.ajax({
                type: 'post',
                url: 'myPageName.php',
                data: $('#myFormName').serialize(),
                success: function () {
                 alert("Email has been sent!");
                }
              });
          e.preventDefault();
        });
});

How to style a disabled checkbox?

You can't style a disabled checkbox directly because it's controlled by the browser / OS.

However you can be clever and replace the checkbox with a label that simulates a checkbox using pure CSS. You need to have an adjacent label that you can use to style a new "pseudo checkbox". Essentially you're completely redrawing the thing but it gives you complete control over how it looks in any state.

I've thrown up a basic example so that you can see it in action: http://jsfiddle.net/JohnSReid/pr9Lx5th/3/

Here's the sample:

_x000D_
_x000D_
input[type="checkbox"] {_x000D_
    display: none;_x000D_
}_x000D_
_x000D_
label:before {_x000D_
    background: linear-gradient(to bottom, #fff 0px, #e6e6e6 100%) repeat scroll 0 0 rgba(0, 0, 0, 0);_x000D_
    border: 1px solid #035f8f;_x000D_
    height: 36px;_x000D_
    width: 36px;_x000D_
    display: block;_x000D_
    cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
    content: '';_x000D_
    background: linear-gradient(to bottom, #e6e6e6 0px, #fff 100%) repeat scroll 0 0 rgba(0, 0, 0, 0);_x000D_
    border-color: #3d9000;_x000D_
    color: #96be0a;_x000D_
    font-size: 38px;_x000D_
    line-height: 35px;_x000D_
    text-align: center;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:disabled + label:before {_x000D_
    border-color: #eee;_x000D_
    color: #ccc;_x000D_
    background: linear-gradient(to top, #e6e6e6 0px, #fff 100%) repeat scroll 0 0 rgba(0, 0, 0, 0);_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
    content: '?';_x000D_
}
_x000D_
<div><input id="cb1" type="checkbox" disabled checked /><label for="cb1"></label></div>_x000D_
<div><input id="cb2" type="checkbox" disabled /><label for="cb2"></label></div>_x000D_
<div><input id="cb3" type="checkbox" checked /><label for="cb3"></label></div>_x000D_
<div><input id="cb4" type="checkbox" /><label for="cb4"></label></div>
_x000D_
_x000D_
_x000D_

Depending on your level of browser compatibility and accessibility, some additional tweaks will need to be made.

How to mention C:\Program Files in batchfile

I had a similar issue as you, although I was trying to use start to open Chrome and using the file path. I used only start chrome.exe and it opened just fine. You may want to try to do the same with exe file. Using the file path may be unnecessary.

Here are some examples (using the file name you gave in a comment on another answer):

  • Instead of C:\Program^ Files\temp.exe you can try temp.exe.

  • Instead of start C:\Program^ Files\temp.exe you can try start temp.exe

Create Windows service from executable

To create a Windows Service from an executable, you can use sc.exe:

sc.exe create <new_service_name> binPath= "<path_to_the_service_executable>"

You must have quotation marks around the actual exe path, and a space after the binPath=.

More information on the sc command can be found in Microsoft KB251192.

Note that it will not work for just any executable: the executable must be a Windows Service (i.e. implement ServiceMain). When registering a non-service executable as a service, you'll get the following error upon trying to start the service:

Error 1053: The service did not respond to the start or control request in a timely fashion.

There are tools that can create a Windows Service from arbitrary, non-service executables, see the other answers for examples of such tools.

How to get active user's UserDetails

Preamble: Since Spring-Security 3.2 there is a nice annotation @AuthenticationPrincipal described at the end of this answer. This is the best way to go when you use Spring-Security >= 3.2.

When you:

  • use an older version of Spring-Security,
  • need to load your custom User Object from the Database by some information (like the login or id) stored in the principal or
  • want to learn how a HandlerMethodArgumentResolver or WebArgumentResolver can solve this in an elegant way, or just want to an learn the background behind @AuthenticationPrincipal and AuthenticationPrincipalArgumentResolver (because it is based on a HandlerMethodArgumentResolver)

then keep on reading — else just use @AuthenticationPrincipal and thank to Rob Winch (Author of @AuthenticationPrincipal) and Lukas Schmelzeisen (for his answer).

(BTW: My answer is a bit older (January 2012), so it was Lukas Schmelzeisen that come up as the first one with the @AuthenticationPrincipal annotation solution base on Spring Security 3.2.)


Then you can use in your controller

public ModelAndView someRequestHandler(Principal principal) {
   User activeUser = (User) ((Authentication) principal).getPrincipal();
   ...
}

That is ok if you need it once. But if you need it several times its ugly because it pollutes your controller with infrastructure details, that normally should be hidden by the framework.

So what you may really want is to have a controller like this:

public ModelAndView someRequestHandler(@ActiveUser User activeUser) {
   ...
}

Therefore you only need to implement a WebArgumentResolver. It has a method

Object resolveArgument(MethodParameter methodParameter,
                   NativeWebRequest webRequest)
                   throws Exception

That gets the web request (second parameter) and must return the User if its feels responsible for the method argument (the first parameter).

Since Spring 3.1 there is a new concept called HandlerMethodArgumentResolver. If you use Spring 3.1+ then you should use it. (It is described in the next section of this answer))

public class CurrentUserWebArgumentResolver implements WebArgumentResolver{

   Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) {
        if(methodParameter is for type User && methodParameter is annotated with @ActiveUser) {
           Principal principal = webRequest.getUserPrincipal();
           return (User) ((Authentication) principal).getPrincipal();
        } else {
           return WebArgumentResolver.UNRESOLVED;
        }
   }
}

You need to define the Custom Annotation -- You can skip it if every instance of User should always be taken from the security context, but is never a command object.

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ActiveUser {}

In the configuration you only need to add this:

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"
    id="applicationConversionService">
    <property name="customArgumentResolver">
        <bean class="CurrentUserWebArgumentResolver"/>
    </property>
</bean>

@See: Learn to customize Spring MVC @Controller method arguments

It should be noted that if you're using Spring 3.1, they recommend HandlerMethodArgumentResolver over WebArgumentResolver. - see comment by Jay


The same with HandlerMethodArgumentResolver for Spring 3.1+

public class CurrentUserHandlerMethodArgumentResolver
                               implements HandlerMethodArgumentResolver {

     @Override
     public boolean supportsParameter(MethodParameter methodParameter) {
          return
              methodParameter.getParameterAnnotation(ActiveUser.class) != null
              && methodParameter.getParameterType().equals(User.class);
     }

     @Override
     public Object resolveArgument(MethodParameter methodParameter,
                         ModelAndViewContainer mavContainer,
                         NativeWebRequest webRequest,
                         WebDataBinderFactory binderFactory) throws Exception {

          if (this.supportsParameter(methodParameter)) {
              Principal principal = webRequest.getUserPrincipal();
              return (User) ((Authentication) principal).getPrincipal();
          } else {
              return WebArgumentResolver.UNRESOLVED;
          }
     }
}

In the configuration, you need to add this

<mvc:annotation-driven>
      <mvc:argument-resolvers>
           <bean class="CurrentUserHandlerMethodArgumentResolver"/>         
      </mvc:argument-resolvers>
 </mvc:annotation-driven>

@See Leveraging the Spring MVC 3.1 HandlerMethodArgumentResolver interface


Spring-Security 3.2 Solution

Spring Security 3.2 (do not confuse with Spring 3.2) has own build in solution: @AuthenticationPrincipal (org.springframework.security.web.bind.annotation.AuthenticationPrincipal) . This is nicely described in Lukas Schmelzeisen`s answer

It is just writing

ModelAndView someRequestHandler(@AuthenticationPrincipal User activeUser) {
    ...
 }

To get this working you need to register the AuthenticationPrincipalArgumentResolver (org.springframework.security.web.bind.support.AuthenticationPrincipalArgumentResolver) : either by "activating" @EnableWebMvcSecurity or by registering this bean within mvc:argument-resolvers - the same way I described it with may Spring 3.1 solution above.

@See Spring Security 3.2 Reference, Chapter 11.2. @AuthenticationPrincipal


Spring-Security 4.0 Solution

It works like the Spring 3.2 solution, but in Spring 4.0 the @AuthenticationPrincipal and AuthenticationPrincipalArgumentResolver was "moved" to an other package:

(But the old classes in its old packges still exists, so do not mix them!)

It is just writing

import org.springframework.security.core.annotation.AuthenticationPrincipal;
ModelAndView someRequestHandler(@AuthenticationPrincipal User activeUser) {
    ...
}

To get this working you need to register the (org.springframework.security.web.method.annotation.) AuthenticationPrincipalArgumentResolver : either by "activating" @EnableWebMvcSecurity or by registering this bean within mvc:argument-resolvers - the same way I described it with may Spring 3.1 solution above.

<mvc:annotation-driven>
    <mvc:argument-resolvers>
        <bean class="org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver" />
    </mvc:argument-resolvers>
</mvc:annotation-driven>

@See Spring Security 5.0 Reference, Chapter 39.3 @AuthenticationPrincipal

How to get JSON from webpage into Python script

you can use json.dumps:

import json

# Hier comes you received data

data = json.dumps(response)

print(data)

for loading json and write it on file the following code is useful:

data = json.loads(json.dumps(Response, sort_keys=False, indent=4))
with open('data.json', 'w') as outfile:
json.dump(data, outfile, sort_keys=False, indent=4)

List Highest Correlation Pairs from a Large Correlation Matrix in Pandas?

Combining most the answers above into a short snippet:

def top_entries(df):
    mat = df.corr().abs()
    
    # Remove duplicate and identity entries
    mat.loc[:,:] = np.tril(mat.values, k=-1)
    mat = mat[mat>0]

    # Unstack, sort ascending, and reset the index, so features are in columns
    # instead of indexes (allowing e.g. a pretty print in Jupyter).
    # Also rename these it for good measure.
    return (mat.unstack()
             .sort_values(ascending=False)
             .reset_index()
             .rename(columns={
                 "level_0": "feature_a",
                 "level_1": "feature_b",
                 0: "correlation"
             }))

Maven 3 Archetype for Project With Spring, Spring MVC, Hibernate, JPA

Possible duplicate: Is there a maven 2 archetype for spring 3 MVC applications?

That said, I would encourage you to think about making your own archetype. The reason is, no matter what you end up getting from someone else's, you can do better in not that much time, and a decent sized Java project is going to end up making a lot of jar projects.

How to reset a select element with jQuery

If you want to reset by id

$('select[id="baba"]').empty();

If you want to reset by name


$('select[name="baba"]').empty();

Jquery - How to make $.post() use contentType=application/json?

You can't send application/json directly -- it has to be a parameter of a GET/POST request.

So something like

$.post(url, {json: "...json..."}, function());

How to resize an image with OpenCV2.0 and Python2.6

Here's a function to upscale or downscale an image by desired width or height while maintaining aspect ratio

# Resizes a image and maintains aspect ratio
def maintain_aspect_ratio_resize(image, width=None, height=None, inter=cv2.INTER_AREA):
    # Grab the image size and initialize dimensions
    dim = None
    (h, w) = image.shape[:2]

    # Return original image if no need to resize
    if width is None and height is None:
        return image

    # We are resizing height if width is none
    if width is None:
        # Calculate the ratio of the height and construct the dimensions
        r = height / float(h)
        dim = (int(w * r), height)
    # We are resizing width if height is none
    else:
        # Calculate the ratio of the width and construct the dimensions
        r = width / float(w)
        dim = (width, int(h * r))

    # Return the resized image
    return cv2.resize(image, dim, interpolation=inter)

Usage

import cv2

image = cv2.imread('1.png')
cv2.imshow('width_100', maintain_aspect_ratio_resize(image, width=100))
cv2.imshow('width_300', maintain_aspect_ratio_resize(image, width=300))
cv2.waitKey()

Using this example image

enter image description here

Simply downscale to width=100 (left) or upscale to width=300 (right)

enter image description here enter image description here

How to do a newline in output

Use "\n" instead of '\n'

How to replace ${} placeholders in a text file?

Use /bin/sh. Create a small shell script that sets the variables, and then parse the template using the shell itself. Like so (edit to handle newlines correctly):

File template.txt:

the number is ${i}
the word is ${word}

File script.sh:

#!/bin/sh

#Set variables
i=1
word="dog"

#Read in template one line at the time, and replace variables (more
#natural (and efficient) way, thanks to Jonathan Leffler).
while read line
do
    eval echo "$line"
done < "./template.txt"

Output:

#sh script.sh
the number is 1
the word is dog

image.onload event and browser cache

There are two possible solutions for these kind of situations:

  1. Use the solution suggested on this post
  2. Add a unique suffix to the image src to force browser downloading it again, like this:

    var img = new Image();
    img.src = "img.jpg?_="+(new Date().getTime());
    img.onload = function () {
        alert("image is loaded");
    }
    

In this code every time adding current timestamp to the end of the image URL you make it unique and browser will download the image again

change pgsql port

There should be a line in your postgresql.conf file that says:

port = 1486

Change that.

The location of the file can vary depending on your install options. On Debian-based distros it is /etc/postgresql/8.3/main/

On Windows it is C:\Program Files\PostgreSQL\9.3\data

Don't forget to sudo service postgresql restart for changes to take effect.

How can I group data with an Angular filter?

Both answers were good so I moved them in to a directive so that it is reusable and a second scope variable doesn't have to be defined.

Here is the fiddle if you want to see it implemented

Below is the directive:

var uniqueItems = function (data, key) {
    var result = [];
    for (var i = 0; i < data.length; i++) {
        var value = data[i][key];
        if (result.indexOf(value) == -1) {
            result.push(value);
        }
    }
    return result;
};

myApp.filter('groupBy',
            function () {
                return function (collection, key) {
                    if (collection === null) return;
                    return uniqueItems(collection, key);
        };
    });

Then it can be used as follows:

<div ng-repeat="team in players|groupBy:'team'">
    <b>{{team}}</b>
    <li ng-repeat="player in players | filter: {team: team}">{{player.name}}</li>        
</div>

R: += (plus equals) and ++ (plus plus) equivalent from c++/c#/java, etc.?

We can also use inplace

library(inplace)
x <- 1
x %+<-% 2

Format Date/Time in XAML in Silverlight

For me this worked:

<TextBlock Text="{Binding Date , StringFormat=g}" Width="130"/>

If want to show seconds also using G instead of g :

<TextBlock Text="{Binding Date , StringFormat=G}" Width="130"/>

Also if want for changing date type to another like Persian , using Language :

<TextBlock Text="{Binding Date , StringFormat=G}" Width="130" Language="fa-IR"/>

How to install the Sun Java JDK on Ubuntu 10.10 (Maverick Meerkat)?

sudo add-apt-repository ppa:sun-java-community-team/sun-java6

sudo apt-get update

sudo apt-get install sun-java6-jre sun-java6-bin sun-java6-jdk

Correct way to import lodash

If you are using webpack 4, the following code is tree shakable.

import { has } from 'lodash-es';

The points to note;

  1. CommonJS modules are not tree shakable so you should definitely use lodash-es, which is the Lodash library exported as ES Modules, rather than lodash (CommonJS).

  2. lodash-es's package.json contains "sideEffects": false, which notifies webpack 4 that all the files inside the package are side effect free (see https://webpack.js.org/guides/tree-shaking/#mark-the-file-as-side-effect-free).

  3. This information is crucial for tree shaking since module bundlers do not tree shake files which possibly contain side effects even if their exported members are not used in anywhere.

Edit

As of version 1.9.0, Parcel also supports "sideEffects": false, threrefore import { has } from 'lodash-es'; is also tree shakable with Parcel. It also supports tree shaking CommonJS modules, though it is likely tree shaking of ES Modules is more efficient than CommonJS according to my experiment.

Check/Uncheck a checkbox on datagridview

While all the other answers are correct, I'll add another simple option which worked for me:

var r = dataGridView.Rows[rIndex];
var c = r.Cells[cIndex];
var value = (bool) c.Value; 
c.Value = !value;

Compressed:

var r = dataGridView.Rows[rIndex];
r.Cells[cIndex].Value = !((bool) r.Cells[cIndex].Value)

As long as cIndex refers to a cell that is of type DataGridViewCheckBoxCell, this will work fine. Hope this helps somone.

Git fast forward VS no fast forward merge

When we work on development environment and merge our code to staging/production branch then Git no fast forward can be a better option. Usually when we work in development branch for a single feature we tend to have multiple commits. Tracking changes with multiple commits can be inconvenient later on. If we merge with staging/production branch using Git no fast forward then it will have only 1 commit. Now anytime we want to revert the feature, just revert that commit. Life is easy.

Change bundle identifier in Xcode when submitting my first app in IOS

Just edit the Project name by single click on the Top of project navigator window, will work in this case. You need not to try any other thing. :)

Server http:/localhost:8080 requires a user name and a password. The server says: XDB

Just change the port number used e.g. 8000 then call the http://localhost:8080

How to use new PasswordEncoder from Spring Security

I had a similar issue. I needed to keep the legacy encrypted passwords (Base64/SHA-1/Random salt Encoded) as users will not want to change their passwords or re-register. However I wanted to use the BCrypt encoder moving forward too.

My solution was to write a bespoke decoder that checks to see which encryption method was used first before matching (BCrypted ones start with $).

To get around the salt issue, I pass into the decoder a concatenated String of salt + encrypted password via my modified user object.

Decoder

@Component
public class LegacyEncoder implements PasswordEncoder {

    private static final String BCRYP_TYPE = "$";
    private static final PasswordEncoder BCRYPT = new BCryptPasswordEncoder();

    @Override
    public String encode(CharSequence rawPassword) {

    return BCRYPT.encode(rawPassword);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {

    if (encodedPassword.startsWith(BCRYP_TYPE)) {
        return BCRYPT.matches(rawPassword, encodedPassword);
    }

    return sha1SaltMatch(rawPassword, encodedPassword);
    }

    @SneakyThrows
    private boolean sha1SaltMatch(CharSequence rawPassword, String encodedPassword) {

    String[] saltHash = encodedPassword.split(User.SPLIT_CHAR);

    // Legacy code from old system   
    byte[] b64salt = Base64.getDecoder().decode(saltHash[0].getBytes());
    byte[] validHash = Base64.getDecoder().decode(saltHash[1]);
    byte[] checkHash = Utility.getHash(5, rawPassword.toString(), b64salt);

    return Arrays.equals(checkHash, validHash);
    }

}

User Object

public class User implements UserDetails {

    public static final String SPLIT_CHAR = ":";

    @Id
    @Column(name = "user_id", nullable = false)
    private Integer userId;

    @Column(nullable = false, length = 60)
    private String password;

    @Column(nullable = true, length = 32)
    private String salt;

.
.

    @PostLoad
    private void init() {

    username = emailAddress; //To comply with UserDetails
    password = salt == null ? password : salt + SPLIT_CHAR + password;
    }        

You can also add a hook to re-encode the password in the new BCrypt format and replace it. Thus phasing out the old method.

Remove gutter space for a specific div only

Interesting...

Removing the gutter in Twitter Bootstrap's Default grid, that is, 940px wide. And that the default grid has a 940px wide container and has the bootstrap-responsive.css in it's stylesheet.

If I got your question right, this is how I did it...

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Stackoverflow Question</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <!-- Le styles -->
    <link rel="stylesheet" href="assets/css/bootstrap.css">
    <link rel="stylesheet" href="assets/css/bootstrap-responsive.css">

    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="assets/js/html5shiv.js"></script>
    <![endif]-->




    <style type="text/css">
        #main_content [class*="span"] {
            margin-left: 0;
            width: 25%;
        }

        @media (min-width: 768px) and (max-width: 979px) {
            #main_content [class*="span"] {
            margin-left: 0;
            width: 25%;
            }
        }


        @media (max-width: 767px) {
            #main_content [class*="span"] {
            margin-left: 0;
            width: 100%;
            }
        }

        @media (max-width: 480px) {
            #main_content [class*="span"] {
            margin-left: 0;
            width: 100%;
            }
        }

        <!-- For Visual Aid Only -->
        .bg1 {
            background-color: #C2C2C2;
        }

        .bg2 {
            background-color: #D2D2D2;
        }
    </style>
  <body>
    <div id="wrap">
        <div class="container">
            <div class="row-fluid">
                <div class="span1 text-center bg1">01</div>
                <div class="span1 text-center bg2">02</div>
                <div class="span1 text-center bg1">03</div>
                <div class="span1 text-center bg2">04</div>
                <div class="span1 text-center bg1">05</div>
                <div class="span1 text-center bg2">06</div>
                <div class="span1 text-center bg1">07</div>
                <div class="span1 text-center bg2">08</div>
                <div class="span1 text-center bg1">09</div>
                <div class="span1 text-center bg2">10</div>
                <div class="span1 text-center bg1">11</div>
                <div class="span1 text-center bg2">12</div>
            </div>



            <div id="main_content">
                <div class="row-fluid">
                    <div class="span3 text-center bg1">1</div>
                    <div class="span3 text-center bg2">2</div>
                    <div class="span3 text-center bg1">3</div>
                    <div class="span3 text-center bg2">4</div>
                </div>
            </div>
        </div><!--/container-->
    </div>
  </body>
</html>

And the result is..

enter image description here

The 4 div span with no gutter will remain spanned for Small tablet landscape (800x600). Anything size smaller than that will collapse the 4 divs and it will be stacked vertically. Of course you will have to tweak it to fit your needs.

UIScrollView scroll to bottom programmatically

I found that contentSize doesn't really reflect the actual size of the text, so when trying to scroll to the bottom, it will be a little bit off. The best way to determine the actual content size is actually to use the NSLayoutManager's usedRectForTextContainer: method:

UITextView *textView;
CGSize textSize = [textView.layoutManager usedRectForTextContainer:textView.textContainer].size;

To determine how much text actually is shown in the UITextView, you can calculate it by subtracting the text container insets from the frame height.

UITextView *textView;
UIEdgeInsets textInsets = textView.textContainerInset;
CGFloat textViewHeight = textView.frame.size.height - textInsets.top - textInsets.bottom;

Then it becomes easy to scroll:

// if you want scroll animation, use contentOffset
UITextView *textView;
textView.contentOffset = CGPointMake(textView.contentOffset.x, textSize - textViewHeight);

// if you don't want scroll animation
CGRect scrollBounds = textView.bounds;
scrollBounds.origin = CGPointMake(textView.contentOffset.x, textSize - textViewHeight);
textView.bounds = scrollBounds;

Some numbers for reference on what the different sizes represent for an empty UITextView.

textView.frame.size = (width=246, height=50)
textSize = (width=10, height=16.701999999999998)
textView.contentSize = (width=246, height=33)
textView.textContainerInset = (top=8, left=0, bottom=8, right=0)

How to create strings containing double quotes in Excel formulas?

Three double quotes: " " " x " " " = "x" Excel will auto change to one double quote. e.g.:

=CONCATENATE("""x"""," hi")  

= "x" hi

Show Curl POST Request Headers? Is there a way to do this?

You can make you request headers by yourself using:

// open a socket connection on port 80
$fp = fsockopen($host, 80);

// send the request headers:
fputs($fp, "POST $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Referer: $referer\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ". strlen($data) ."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $data);

$result = ''; 
while(!feof($fp)) {
    // receive the results of the request
    $result .= fgets($fp, 128);
}

// close the socket connection:
fclose($fp);

Like writen on how make request

undefined reference to WinMain@16 (codeblocks)

When there's no project, Code::Blocks only compiles and links the current file. That file, from your picture, is secrypt.cpp, which does not have a main function. In order to compile and link both source files, you'll need to do it manually or add them to the same project.

Contrary to what others are saying, using a Windows subsystem with main will still work, but there will be no console window.

Your other attempt, compiling and linking just trial.cpp, never links secrypt.cpp. This would normally result in an undefined reference to jRegister(), but you've declared the function inside main instead of calling it. Change main to:

int main()
{
    jRegister();

    return 0;
}

How to remove the querystring and get only the url?

You can use strtok to get string before first occurence of ?

$url = strtok($_SERVER["REQUEST_URI"], '?');

strtok() represents the most concise technique to directly extract the substring before the ? in the querystring. explode() is less direct because it must produce a potentially two-element array by which the first element must be accessed.

Some other techniques may break when the querystring is missing or potentially mutate other/unintended substrings in the url -- these techniques should be avoided.

A demonstration:

$urls = [
    'www.example.com/myurl.html?unwantedthngs#hastag',
    'www.example.com/myurl.html'
];

foreach ($urls as $url) {
    var_export(['strtok: ', strtok($url, '?')]);
    echo "\n";
    var_export(['strstr/true: ', strstr($url, '?', true)]); // not reliable
    echo "\n";
    var_export(['explode/2: ', explode('?', $url, 2)[0]]);  // limit allows func to stop searching after first encounter
    echo "\n";
    var_export(['substr/strrpos: ', substr($url, 0, strrpos( $url, "?"))]);  // not reliable; still not with strpos()
    echo "\n---\n";
}

Output:

array (
  0 => 'strtok: ',
  1 => 'www.example.com/myurl.html',
)
array (
  0 => 'strstr/true: ',
  1 => 'www.example.com/myurl.html',
)
array (
  0 => 'explode/2: ',
  1 => 'www.example.com/myurl.html',
)
array (
  0 => 'substr/strrpos: ',
  1 => 'www.example.com/myurl.html',
)
---
array (
  0 => 'strtok: ',
  1 => 'www.example.com/myurl.html',
)
array (
  0 => 'strstr/true: ',
  1 => false,                       // bad news
)
array (
  0 => 'explode/2: ',
  1 => 'www.example.com/myurl.html',
)
array (
  0 => 'substr/strrpos: ',
  1 => '',                          // bad news
)
---

How can I get a channel ID from YouTube?

2017 Update: Henry's answer may be a little off the mark here. If you look for data-channel-external-id in the source code you may find more than one ID, and only the first occurrence is actually correct. Get the channel_id used in <link rel="alternate" type="application/rss+xml" title="RSS" href="https://www.youtube.com/feeds/videos.xml?channel_id=<VALUE_HERE"> instead.

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

Conclusion: we regard big O, big ? and big O as the same thing.

Why? I will tell the reason below:

Firstly, I will clarify one wrong statement, some people think that we just care the worst time complexity, so we always use big O instead of big ?. I will say this man is bullshitting. Upper and lower bound are used to describe one function, not used to describe the time complexity. The worst time function has its upper and lower bound; the best time function has its upper and lower bound too.

In order to explain clearly the relation between big O and big ?, I will explain the relation between big O and small o first. From the definition, we can easily know that small o is a subset of big O. For example:

T(n)= n^2 + n, we can say T(n)=O(n^2), T(n)=O(n^3), T(n)=O(n^4). But for small o, T(n)=o(n^2) does not meet the definition of small o. So just T(n)=o(n^3), T(n)=o(n^4) are correct for small o. The redundant T(n)=O(n^2) is what? It's big ?!

Generally, we say big O is O(n^2), hardly to say T(n)=O(n^3), T(n)=O(n^4). Why? Because we regard big O as big ? subconsciously.

Similarly, we also regard big O as big ? subconsciously.

In one word, big O, big ? and big O are not the same thing from the definitions, but they are the same thing in our mouth and brain.

Why "Data at the root level is invalid. Line 1, position 1." for XML Document?

if you are using XDocument.Load(url); to fetch xml from another domain, it's possible that the host will reject the request and return and unexpected (non-xml) result, which results in the above XmlException

See my solution to this eventuality here: XDocument.Load(feedUrl) returns "Data at the root level is invalid. Line 1, position 1."

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

I just wrote a blog post addressing this. You could install ASP.NET MVC on your server OR you can follow the steps here.


EDIT: (by jcolebrand) I went through this link, then had the same issue as Victor below, so I suggest you also add these:

* Microsoft.Web.Infrastructure
* System.Web.Razor
* System.Web.WebPages.Deployment
* System.Web.WebPages.Razor

how to change attribute "hidden" in jquery

$(':checkbox').change(function(){
    $('#delete').removeAttr('hidden');
});

Note, thanks to tip by A.Wolff, you should use removeAttr instead of setting to false. When set to false, the element will still be hidden. Therefore, removing is more effective.

How can I use pickle to save a dict?

# Save a dictionary into a pickle file.
import pickle

favorite_color = {"lion": "yellow", "kitty": "red"}  # create a dictionary
pickle.dump(favorite_color, open("save.p", "wb"))  # save it into a file named save.p

# -------------------------------------------------------------
# Load the dictionary back from the pickle file.
import pickle

favorite_color = pickle.load(open("save.p", "rb"))
# favorite_color is now {"lion": "yellow", "kitty": "red"}

Playing a video in VideoView in Android

Well ! if you are using a android Compatibility Video then the only cause of this alert is you must be using a video sized more then the 300MB. Android doesn't support large Video (>300MB). We can get it by using NDK optimization.

How to check if directory exist using C++ and winAPI

0.1 second Google search:

BOOL DirectoryExists(const char* dirName) {
  DWORD attribs = ::GetFileAttributesA(dirName);
  if (attribs == INVALID_FILE_ATTRIBUTES) {
    return false;
  }
  return (attribs & FILE_ATTRIBUTE_DIRECTORY);
}

Using Bootstrap Modal window as PartialView

Put the modal and javascript into the partial view. Then call the partial view in your page. This will handle form submission too.

Partial View

<div id="confirmDialog" class="modal fade" data-backdrop="false">
 <div class="modal-dialog" data-backdrop="false">
    <div class="modal-content">
        <div class="modal-header">
            <h4 class="modal-title">Missing Service Order</h4>
        </div>
        <div class="modal-body">
            <p>You have not entered a Service Order. Do you want to continue?</p>
        </div>
        <div class="modal-footer">
            <input id="btnSubmit" type="submit" class="btn btn-primary" 
              value="Submit" href="javascript:" 
               onClick="document.getElementById('Coordinate').submit()" />
            <button type="button" class="btn btn-default" data- 
                                               dismiss="modal">Cancel</button>
        </div>
    </div>
  </div>
</div>

Javascript

  <script type="text/javascript" language="javascript">
$(document).ready(function () {
    $("#Coordinate").on('submit',
        function (e) {
            if ($("#ServiceOrder").val() == '') {
                e.preventDefault();
                $('#confirmDialog').modal('show');
               }
            });
    });
</script>

Then just call your partial inside the form of your page.

Create.cshtml

 @using (Html.BeginForm("Edit","Home",FormMethod.Post, new {id ="Coordinate"}))
 {
     //Form Code

     @Html.Partial("ConfirmDialog") 
 }

What is the use of style="clear:both"?

Just to add to RichieHindle's answer, check out Floatutorial, which walks you through how CSS floating and clearing works.

JavaScript: location.href to open in new window/tab?

For example:

    $(document).on('click','span.external-link',function(){
        var t               = $(this), 
            URL             = t.attr('data-href');        
        $('<a href="'+ URL +'" target="_blank">External Link</a>')[0].click();

    });

Working example.

Handling of non breaking space: <p>&nbsp;</p> vs. <p> </p>

In HTML, elements containing nothing but normal whitespace characters are considered empty. A paragraph that contains just a normal space character will have zero height. A non-breaking space is a special kind of whitespace character that isn't considered to be insignificant, so it can be used as content for a non-empty paragraph.

Even if you consider CSS margins on paragraphs, since an "empty" paragraph has zero height, its vertical margins will collapse. This causes it to have no height and no margins, making it appear as if it were never there at all.

Removing rounded corners from a <select> element in Chrome/Webkit

Eliminating the arrows should be avoided. A solution that preserves the dropdown arrows is to first remove styles from the dropdown:

.myDropdown {
  background-color: #yourbg;
  border-style: none;
}

Then create div directly before the dropdown in your HTML:

<div class="myDiv"></div>
<select class="myDropdown...">...</select>

And style the div like this:

.myDiv {
  background-color: #yourbg;
  border-style: none;
  position: absolute;
  display: inline;
  border: 1px solid #acolor;
}

Display inline will keep the div from going to a new line, position absolute removes it from the flow of the page. The end result is a nice clean underline you can style as you'd like, and your dropdown still behaves as the user would expect.

jquery onclick change css background image

Use your jquery like this

$('.home').css({'background-image':'url(images/tabs3.png)'});

Extracting columns from text file with different delimiters in Linux

If the command should work with both tabs and spaces as the delimiter I would use awk:

awk '{print $100,$101,$102,$103,$104,$105}' myfile > outfile

As long as you just need to specify 5 fields it is imo ok to just type them, for longer ranges you can use a for loop:

awk '{for(i=100;i<=105;i++)print $i}' myfile > outfile

If you want to use cut, you need to use the -f option:

cut -f100-105 myfile > outfile

If the field delimiter is different from TAB you need to specify it using -d:

cut -d' ' -f100-105 myfile > outfile

Check the man page for more info on the cut command.

Initializing array of structures

This is quite simple: my_data is a before defined structure type. So you want to declare an my_data-array of some elements, as you would do with

char a[] = { 'a', 'b', 'c', 'd' };

So the array would have 4 elements and you initialise them as

a[0] = 'a', a[1] = 'b', a[1] = 'c', a[1] ='d';

This is called a designated initializer (as i remember right).

and it just indicates that data has to be of type my_dat and has to be an array that needs to store so many my_data structures that there is a structure with each type member name Peter, James, John and Mike.

Why am I getting a NoClassDefFoundError in Java?

I got this error when I add Maven dependency of another module to my project, the issue was finally solved by add -Xss2m to my program's JVM option(It's one megabyte by default since JDK5.0). It's believed the program does not have enough stack to load class.

Why doesn't importing java.util.* include Arrays and Lists?

I have just compile it and it compiles fine without the implicit import, probably you're seeing a stale cache or something of your IDE.

Have you tried compiling from the command line?

I have the exact same version:

here it is

Probably you're thinking the warning is an error.

UPDATE

It looks like you have a Arrays.class file in the directory where you're trying to compile ( probably created before ). That's why the explicit import solves the problem. Try copying your source code to a clean new directory and try again. You'll see there is no error this time. Or, clean up your working directory and remove the Arrays.class

Bootstrap 3 - set height of modal window according to screen size

Similar to Bass, I had to also set the overflow-y. That could actually be done in the CSS

$('#myModal').on('show.bs.modal', function () {
    $('.modal .modal-body').css('overflow-y', 'auto'); 
    $('.modal .modal-body').css('max-height', $(window).height() * 0.7);
});

C++ deprecated conversion from string constant to 'char*'

In fact a string constant literal is neither a const char * nor a char* but a char[]. Its quite strange but written down in the c++ specifications; If you modify it the behavior is undefined because the compiler may store it in the code segment.

How to get selected value of a html select with asp.net

<%@ Page Language="C#" AutoEventWireup="True" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">    
<head>
    <title> HtmlSelect Example </title>
    <script runat="server">
      void Button_Click (Object sender, EventArgs e)
      {
         Label1.Text = "Selected index: " + Select1.SelectedIndex.ToString()
                       + ", value: " + Select1.Value;    
      }    
   </script>    
</head>    
<body>    
   <form id="form1" runat="server">

      Select an item: 

      <select id="Select1" runat="server">    
         <option value="Text for Item 1" selected="selected"> Item 1 </option>
         <option value="Text for Item 2"> Item 2 </option>
         <option value="Text for Item 3"> Item 3 </option>
         <option value="Text for Item 4"> Item 4 </option>
      </select>

      <button onserverclick="Button_Click" runat="server" Text="Submit"/>

      <asp:Label id="Label1" runat="server"/>    
   </form>
</body>
</html>

Source from Microsoft. Hope this is helpful!

how to POST/Submit an Input Checkbox that is disabled?

Since:

  • setting readonly attribute to checkbox isn't valid according to HTML specification,
  • using hidden element to submit value isn't very pretty way and
  • setting onclick JavaScript that prevents from changing value isn't very nice too

I'm gonna offer you another possibility:

Set your checkbox as disabled as normal. And before the form is submitted by user enable this checkbox by JavaScript.

<script>
    function beforeSumbit() {
        var checkbox = document.getElementById('disabledCheckbox');
        checkbox.disabled = false;
    }
</script>
...
<form action="myAction.do" method="post" onSubmit="javascript: beforeSubmit();">
    <checkbox name="checkboxName" value="checkboxValue" disabled="disabled" id="disabledCheckbox" />
    <input type="submit />
</form>

Because the checkbox is enabled before the form is submitted, its value is posted in common way. Only thing that isn't very pleasant about this solution is that this checkbox becomes enabled for a while and that can be seen by users. But it's just a detail I can live with.

Filtering array of objects with lodash based on property value

_x000D_
_x000D_
let myArr = [_x000D_
    { name: "john", age: 23 },_x000D_
    { name: "john", age: 43 },_x000D_
    { name: "jim", age: 101 },_x000D_
    { name: "bob", age: 67 },_x000D_
];_x000D_
_x000D_
// this will return old object (myArr) with items named 'john'_x000D_
let list = _.filter(myArr, item => item.name === 'jhon');_x000D_
_x000D_
//  this will return new object referenc (new Object) with items named 'john' _x000D_
let list = _.map(myArr, item => item.name === 'jhon').filter(item => item.name);
_x000D_
_x000D_
_x000D_

How do I convert a dictionary to a JSON String in C#?

It seems a lot of different libraries and what not have seem to come and go over the previous years. However as of April 2016, this solution worked well for me. Strings easily replaced by ints.

TL/DR; Copy this if that's what you came here for:

    //outputfilename will be something like: "C:/MyFolder/MyFile.txt"
    void WriteDictionaryAsJson(Dictionary<string, List<string>> myDict, string outputfilename)
    {
        DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Dictionary<string, List<string>>));
        MemoryStream ms = new MemoryStream();
        js.WriteObject(ms, myDict); //Does the serialization.

        StreamWriter streamwriter = new StreamWriter(outputfilename);
        streamwriter.AutoFlush = true; // Without this, I've run into issues with the stream being "full"...this solves that problem.

        ms.Position = 0; //ms contains our data in json format, so let's start from the beginning
        StreamReader sr = new StreamReader(ms); //Read all of our memory
        streamwriter.WriteLine(sr.ReadToEnd()); // and write it out.

        ms.Close(); //Shutdown everything since we're done.
        streamwriter.Close();
        sr.Close();
    }

Two import points. First, be sure to add System.Runtime.Serliazation as a reference in your project inside Visual Studio's Solution Explorer. Second, add this line,

using System.Runtime.Serialization.Json;

at the top of the file with the rest of your usings, so the DataContractJsonSerializer class can be found. This blog post has more information on this method of serialization.

Data Format (Input / Output)

My data is a dictionary with 3 strings, each pointing to a list of strings. The lists of strings have lengths 3, 4, and 1. The data looks like this:

StringKeyofDictionary1 => ["abc","def","ghi"]
StringKeyofDictionary2 => ["String01","String02","String03","String04"]
Stringkey3 => ["someString"]

The output written to file will be on one line, here is the formatted output:

 [{
     "Key": "StringKeyofDictionary1",
     "Value": ["abc",
     "def",
     "ghi"]
 },
 {
     "Key": "StringKeyofDictionary2",
     "Value": ["String01",
     "String02",
     "String03",
     "String04",
 ]
 },
 {
     "Key": "Stringkey3",
     "Value": ["SomeString"]
 }]

sorting dictionary python 3

Dictionaries are unordered by definition, What would be the main reason for ordering by key? A list of tuples created by the sort method can be used for whatever the need may have been, but changing the list of tuples back into a dictionary will return a random order

>>> myDic
{10: 'b', 3: 'a', 5: 'c'}
>>> sorted(myDic.items())
[(3, 'a'), (5, 'c'), (10, 'b')]
>>> print(dict(myDic.items()))
{10: 'b', 3: 'a', 5: 'c'}

Entity Framework - Code First - Can't Store List<String>

You can use this ScalarCollection container that confines an array and provides some manipulation options (Gist):

Usage:

public class Person
{
    public int Id { get; set; }
    //will be stored in database as single string.
    public SaclarStringCollection Phones { get; set; } = new ScalarStringCollection();
}

Code:

using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;

namespace System.Collections.Specialized
{
#if NET462
  [ComplexType]
#endif
  public abstract class ScalarCollectionBase<T> :
#if NET462
    Collection<T>,
#else
    ObservableCollection<T>
#endif
  {
    public virtual string Separator { get; } = "\n";
    public virtual string ReplacementChar { get; } = " ";
    public ScalarCollectionBase(params T[] values)
    {
      if (values != null)
        foreach (var item in Items)
          Items.Add(item);
    }

#if NET462
    [Browsable(false)]
#endif
    [EditorBrowsable(EditorBrowsableState.Never)]
    [Obsolete("Not to be used directly by user, use Items property instead.")]
    public string Data
    {
      get
      {
        var data = Items.Select(item => Serialize(item)
          .Replace(Separator, ReplacementChar.ToString()));
        return string.Join(Separator, data.Where(s => s?.Length > 0));
      }
      set
      {
        Items.Clear();
        if (string.IsNullOrWhiteSpace(value))
          return;

        foreach (var item in value
            .Split(new[] { Separator }, 
              StringSplitOptions.RemoveEmptyEntries).Select(item => Deserialize(item)))
          Items.Add(item);
      }
    }

    public void AddRange(params T[] items)
    {
      if (items != null)
        foreach (var item in items)
          Add(item);
    }

    protected abstract string Serialize(T item);
    protected abstract T Deserialize(string item);
  }

  public class ScalarStringCollection : ScalarCollectionBase<string>
  {
    protected override string Deserialize(string item) => item;
    protected override string Serialize(string item) => item;
  }

  public class ScalarCollection<T> : ScalarCollectionBase<T>
    where T : IConvertible
  {
    protected override T Deserialize(string item) =>
      (T)Convert.ChangeType(item, typeof(T));
    protected override string Serialize(T item) => Convert.ToString(item);
  }
}

LaTeX source code listing like in professional books

I wonder why nobody mentioned the Minted package. It has far better syntax highlighting than the LaTeX listing package. It uses Pygments.

$ pip install Pygments

Example in LaTeX:

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}

\usepackage{minted}

\begin{document}
\begin{minted}{python}
import numpy as np

def incmatrix(genl1,genl2):
    m = len(genl1)
    n = len(genl2)
    M = None #to become the incidence matrix
    VT = np.zeros((n*m,1), int)  #dummy variable

    #compute the bitwise xor matrix
    M1 = bitxormatrix(genl1)
    M2 = np.triu(bitxormatrix(genl2),1) 

    for i in range(m-1):
        for j in range(i+1, m):
            [r,c] = np.where(M2 == M1[i,j])
            for k in range(len(r)):
                VT[(i)*n + r[k]] = 1;
                VT[(i)*n + c[k]] = 1;
                VT[(j)*n + r[k]] = 1;
                VT[(j)*n + c[k]] = 1;

                if M is None:
                    M = np.copy(VT)
                else:
                    M = np.concatenate((M, VT), 1)

                VT = np.zeros((n*m,1), int)

    return M
\end{minted}
\end{document}

Which results in:

enter image description here

You need to use the flag -shell-escape with the pdflatex command.

For more information: https://www.sharelatex.com/learn/Code_Highlighting_with_minted

How do I create sql query for searching partial matches?

First of all, this approach won't scale in the large, you'll need a separate index from words to item (like an inverted index).

If your data is not large, you can do

SELECT DISTINCT(name) FROM mytable WHERE name LIKE '%mall%' OR description LIKE '%mall%'

using OR if you have multiple keywords.

Ruby: Merging variables in to a string

["The", animal, action, "the", second_animal].join(" ")

is another way to do it.

Youtube autoplay not working on mobile devices with embedded HTML5 player

As it turns out, autoplay cannot be done on iOS devices (iPhone, iPad, iPod touch) and Android.

See https://stackoverflow.com/a/8142187/2054512 and https://stackoverflow.com/a/3056220/2054512

How to fix Git error: object file is empty?

This also happens to me almost regularly. Haven't made a protocol when this happens exactly, but I have a suspicion that it occurs whenever my virtual machine exists "unexpectedly". If I close the VM window (I am using Ubuntu 18.04) and start again, things always(?) work. But if the VM window is still open when my laptop is shut down (Windows host system), then I encounter this problem rather frequently.

As to all the answers given here:

  1. thank you - they are very useful; I usually save a local copy of my code, restore the repo from remote, and move the backup copy back into the local folder.

  2. as the underlying problem is not really a git issue, but rather a VM and/or Linux issue, I wonder if there shouldn't be a way to cure the reason rather the symptoms? Doesn't this kind of error indicate that some file system changes are not "applied" in any reasonable time, but only cached? (see for example https://unix.stackexchange.com/questions/464184/are-file-edits-in-linux-directly-saved-into-disk) -- to me it appears as if virtual Linux machines don't fsynch their stuff frequently enough. Whether this is an issue of Oracle's VirtualBox (which otherwise works very nicely) or of the guest file system, or of some settings, which we all overlook, is beyond my expertise. But I would be happy if someone could shed light on this.

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

YourString = YourString.Remove(YourString.Length - 1);

How to force reloading php.ini file?

To force a reload of the php.ini you should restart apache.

Try sudo service apache2 restart from the command line. Or sudo /etc/init.d/apache2 restart

HTML Button Close Window

When in the onclick attribute you do not need to specify that it is Javascript.

<button type="button" 
        onclick="window.open('', '_self', ''); window.close();">Discard</button>

This should do it. In order to close it your page needs to be opened by the script, hence the window.open. Here is an article explaining this in detail:

Click Here

If all else fails, you should also add a message asking the user to manually close the window, as there is no cross-browser solution for this, especially with older browsers such as IE 8.

How can I add new dimensions to a Numpy array?

There is no structure in numpy that allows you to append more data later.

Instead, numpy puts all of your data into a contiguous chunk of numbers (basically; a C array), and any resize requires allocating a new chunk of memory to hold it. Numpy's speed comes from being able to keep all the data in a numpy array in the same chunk of memory; e.g. mathematical operations can be parallelized for speed and you get less cache misses.

So you will have two kinds of solutions:

  1. Pre-allocate the memory for the numpy array and fill in the values, like in JoshAdel's answer, or
  2. Keep your data in a normal python list until it's actually needed to put them all together (see below)

images = []
for i in range(100):
    new_image = # pull image from somewhere
    images.append(new_image)
images = np.stack(images, axis=3)

Note that there is no need to expand the dimensions of the individual image arrays first, nor do you need to know how many images you expect ahead of time.

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

In case of windows if there is any space in path to jdk like ("C:\Program Files\jdk") then it doesn't work, but if we keep jdk in a location which doesn't have space then it works fine like ("C:\jdk")

How to output MySQL query results in CSV format?

To expand on previous answers, the following one-liner exports a single table as a tab-separated file. It's suitable for automation, exporting the database every day or so.

mysql -B -D mydatabase -e 'select * from mytable'

Conveniently, we can use the same technique to list out MySQL's tables, and to describe the fields on a single table:

mysql -B -D mydatabase -e 'show tables'

mysql -B -D mydatabase -e 'desc users'

Field   Type    Null    Key Default Extra
id  int(11) NO  PRI NULL    auto_increment
email   varchar(128)    NO  UNI NULL    
lastName    varchar(100)    YES     NULL    
title   varchar(128)    YES UNI NULL    
userName    varchar(128)    YES UNI NULL    
firstName   varchar(100)    YES     NULL    

Dealing with timestamps in R

You want the (standard) POSIXt type from base R that can be had in 'compact form' as a POSIXct (which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt (which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)

Quick example:

R> now <- Sys.time()
R> now
[1] "2009-12-25 18:39:11 CST"
R> as.numeric(now)
[1] 1.262e+09
R> now + 10  # adds 10 seconds
[1] "2009-12-25 18:39:21 CST"
R> as.POSIXlt(now)
[1] "2009-12-25 18:39:11 CST"
R> str(as.POSIXlt(now))
 POSIXlt[1:9], format: "2009-12-25 18:39:11"
R> unclass(as.POSIXlt(now))
$sec
[1] 11.79

$min
[1] 39

$hour
[1] 18

$mday
[1] 25

$mon
[1] 11

$year
[1] 109

$wday
[1] 5

$yday
[1] 358

$isdst
[1] 0

attr(,"tzone")
[1] "America/Chicago" "CST"             "CDT"            
R> 

As for reading them in, see help(strptime)

As for difference, easy too:

R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
R> difftime(now, Jan1, unit="week")
Time difference of 51.25 weeks
R> 

Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.

Disable XML validation in Eclipse

You have two options:

  1. Configure Workspace Settings (disable the validation for the current workspace): Go to Window > Preferences > Validation and uncheck the manual and build for: XML Schema Validator, XML Validator

  2. Check enable project specific settings (disable the validation for this project): Right-click on the project, select Properties > Validation and uncheck the manual and build for: XML Schema Validator, XML Validator

Right-click on the project and select Validate to make the errors disappear.

git: 'credential-cache' is not a git command

I realize I'm a little late to the conversation, but I encountered the exact same issue In my git config I had two entries credentials…

In my .gitconfig file

[credential]
helper = cached
[credentials]
helper = wincred

The Fix: Changed my .gitconfig file to the settings below

[credential]
helper = wincred
[credentials]
helper = wincred

How to save username and password in Git?

Just put your credentials in the Url like this:

https://Username:Password@github.com/myRepoDir/myRepo.git

You may store it like this:

git remote add myrepo https://Userna...

...example to use it:

git push myrepo master


Now that is to List the url aliases:

git remote -v

...and that the command to delete one of them:

git remote rm myrepo

xlsxwriter: is there a way to open an existing worksheet in my workbook?

You cannot append to an existing xlsx file with xlsxwriter.

There is a module called openpyxl which allows you to read and write to preexisting excel file, but I am sure that the method to do so involves reading from the excel file, storing all the information somehow (database or arrays), and then rewriting when you call workbook.close() which will then write all of the information to your xlsx file.

Similarly, you can use a method of your own to "append" to xlsx documents. I recently had to append to a xlsx file because I had a lot of different tests in which I had GPS data coming in to a main worksheet, and then I had to append a new sheet each time a test started as well. The only way I could get around this without openpyxl was to read the excel file with xlrd and then run through the rows and columns...

i.e.

cells = []
for row in range(sheet.nrows):
    cells.append([])
    for col in range(sheet.ncols):
        cells[row].append(workbook.cell(row, col).value)

You don't need arrays, though. For example, this works perfectly fine:

import xlrd
import xlsxwriter

from os.path import expanduser
home = expanduser("~")

# this writes test data to an excel file
wb = xlsxwriter.Workbook("{}/Desktop/test.xlsx".format(home))
sheet1 = wb.add_worksheet()
for row in range(10):
    for col in range(20):
        sheet1.write(row, col, "test ({}, {})".format(row, col))
wb.close()

# open the file for reading
wbRD = xlrd.open_workbook("{}/Desktop/test.xlsx".format(home))
sheets = wbRD.sheets()

# open the same file for writing (just don't write yet)
wb = xlsxwriter.Workbook("{}/Desktop/test.xlsx".format(home))

# run through the sheets and store sheets in workbook
# this still doesn't write to the file yet
for sheet in sheets: # write data from old file
    newSheet = wb.add_worksheet(sheet.name)
    for row in range(sheet.nrows):
        for col in range(sheet.ncols):
            newSheet.write(row, col, sheet.cell(row, col).value)

for row in range(10, 20): # write NEW data
    for col in range(20):
        newSheet.write(row, col, "test ({}, {})".format(row, col))
wb.close() # THIS writes

However, I found that it was easier to read the data and store into a 2-dimensional array because I was manipulating the data and was receiving input over and over again and did not want to write to the excel file until it the test was over (which you could just as easily do with xlsxwriter since that is probably what they do anyway until you call .close()).

How would you make two <div>s overlap?

Just use negative margins, in the second div say:

<div style="margin-top: -25px;">

And make sure to set the z-index property to get the layering you want.

What does \d+ mean in regular expression terms?

\d is a digit, + is 1 or more, so a sequence of 1 or more digits

PHP mysql insert date format

The simplest method is

$dateArray = explode('/', $_POST['date']);
$date = $dateArray[2].'-'.$dateArray[0].'-'.$dateArray[1];

$sql = mysql_query("INSERT INTO user_date (column,column,column) VALUES('',$name,$date)") or die (mysql_error());

ASP.NET MVC Dropdown List From SelectList

You are missing setting what field is the Text and Value in the SelectList itself. That is why it does a .ToString() on each object in the list. You could think that given it is a list of SelectListItem it should be smart enough to detect this... but it is not.

u.UserTypeOptions = new SelectList(
    new List<SelectListItem>
    {
        new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
        new SelectListItem { Selected = false, Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
        new SelectListItem { Selected = false, Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
    }, "Value" , "Text", 1);

BTW, you can use a list of array of any type... and then just set the name of the properties that will act as Text and Value.

I think it is better to do it like this:

u.UserTypeOptions = new SelectList(
    new List<SelectListItem>
    {
        new SelectListItem { Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
        new SelectListItem { Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
    }, "Value" , "Text");

I removed the -1 item, and the setting of each items selected true/false.

Then, in your view:

@Html.DropDownListFor(m => m.UserType, Model.UserTypeOptions, "Select one")

This way, if you set the "Select one" item, and you don't set one item as selected in the SelectList, the UserType will be null (the UserType need to be int? ).

If you need to set one of the SelectList items as selected, you can use:

u.UserTypeOptions = new SelectList(options, "Value" , "Text", userIdToBeSelected);

XPath: select text node

your xpath should work . i have tested your xpath and mine in both MarkLogic and Zorba Xquery/ Xpath implementation.

Both should work.

/node/child::text()[1] - should return Text1
/node/child::text()[2] - should return text2


/node/text()[1] - should return Text1
/node/text()[2] - should return text2

ERROR 1064 (42000): You have an error in your SQL syntax; Want to configure a password as root being the user

On MySQL 8.0.15 (maybe earlier than this too): the PASSWORD() function does not work anymore, so you have to do:

Make sure you have stopped MySQL first (Go to: 'System Preferences' >> 'MySQL' and stop MySQL).

Run the server in safe mode with privilege bypass:

sudo mysqld_safe --skip-grant-tables
mysql -u root
UPDATE mysql.user SET authentication_string=null WHERE User='root';
FLUSH PRIVILEGES;
exit;

Then

mysql -u root
ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'yourpasswd';

Finally, start your MySQL again.

Enlighten by @OlatunjiYso in this GitHub issue.

Error: allowDefinition='MachineToApplication' beyond application level

tip 1: clean & then rebuild.

tip 2: just close VS and open again.

tip 3: the downloaded project may be inside another sub folder... open the folder which has you .net files.

c:/demo1/demo/ (all files)

You should have to open demo from vs... not demo1.

Calculate difference in keys contained in two Python dictionaries

If you want a built-in solution for a full comparison with arbitrary dict structures, @Maxx's answer is a good start.

import unittest

test = unittest.TestCase()
test.assertEqual(dictA, dictB)

Load More Posts Ajax Button in WordPress

If I'm not using any category then how can I use this code? Actually, I want to use this code for custom post type.

How do I execute code AFTER a form has loaded?

First time it WILL NOT start "AfterLoading",
It will just register it to start NEXT Load.

private void Main_Load(object sender, System.EventArgs e)
{
    //Register it to Start in Load 
    //Starting from the Next time.
    this.Activated += AfterLoading;
}

private void AfterLoading(object sender, EventArgs e)
{
    this.Activated -= AfterLoading;
    //Write your code here.
}

Creating a LinkedList class from scratch

How about a fully functional implementation of a non-recursive Linked List?

I created this for my Algorithms I class as a stepping stone to gain a better understanding before moving onto writing a doubly-linked queue class for an assignment.

Here's the code:

import java.util.Iterator;
import java.util.NoSuchElementException;

public class LinkedList<T> implements Iterable<T> {
    private Node first;
    private Node last;
    private int N;

    public LinkedList() {
        first = null;
        last = null;
        N = 0;
    }

    public void add(T item) {
        if (item == null) { throw new NullPointerException("The first argument for addLast() is null."); }
        if (!isEmpty()) {
            Node prev = last;
            last = new Node(item, null);
            prev.next = last;
        }
        else {
            last = new Node(item, null);
            first = last;
        }
        N++;
    }

    public boolean remove(T item) {
        if (isEmpty()) { throw new IllegalStateException("Cannot remove() from and empty list."); }
        boolean result = false;
        Node prev = first;
        Node curr = first;
        while (curr.next != null || curr == last) {
            if (curr.data.equals(item)) {
                // remove the last remaining element
                if (N == 1) { first = null; last = null; }
                // remove first element
                else if (curr.equals(first)) { first = first.next; }
                // remove last element
                else if (curr.equals(last)) { last = prev; last.next = null; }
                // remove element
                else { prev.next = curr.next; }
                N--;
                result = true;
                break;
            }
            prev = curr;
            curr = prev.next;
        }
        return result;
    }

    public int size() {
        return N;
    }

    public boolean isEmpty() {
        return N == 0;
    }

    private class Node {
        private T data;
        private Node next;

        public Node(T data, Node next) {
            this.data = data;
            this.next = next;
        }
    }

    public Iterator<T> iterator() { return new LinkedListIterator(); }

    private class LinkedListIterator implements Iterator<T> {
        private Node current = first;

        public T next() {
            if (!hasNext()) { throw new NoSuchElementException(); }
            T item = current.data;
            current = current.next;
            return item;
        }

        public boolean hasNext() { return current != null; }

        public void remove() { throw new UnsupportedOperationException(); }
    }

    @Override public String toString() {
        StringBuilder s = new StringBuilder();
        for (T item : this)
            s.append(item + " ");
        return s.toString();
    }

    public static void main(String[] args) {
        LinkedList<String> list = new LinkedList<>();
        while(!StdIn.isEmpty()) {
            String input = StdIn.readString();
            if (input.equals("print")) { StdOut.println(list.toString()); continue; }
            if (input.charAt(0) == ('+')) { list.add(input.substring(1)); continue; }
            if (input.charAt(0) == ('-')) { list.remove(input.substring(1)); continue; }
            break;
        }
    }
}

Note: It's a pretty basic implementation of a singly-linked-list. The 'T' type is a generic type placeholder. Basically, this linked list should work with any type that inherits from Object. If you use it for primitive types be sure to use the nullable class equivalents (ex 'Integer' for the 'int' type). The 'last' variable isn't really necessary except that it shortens insertions to O(1) time. Removals are slow since they run in O(N) time but it allows you to remove the first occurrence of a value in the list.

If you want you could also look into implementing:

  • addFirst() - add a new item to the beginning of the LinkedList
  • removeFirst() - remove the first item from the LinkedList
  • removeLast() - remove the last item from the LinkedList
  • addAll() - add a list/array of items to the LinkedList
  • removeAll() - remove a list/array of items from the LinkedList
  • contains() - check to see if the LinkedList contains an item
  • contains() - clear all items in the LinkedList

Honestly, it only takes a few lines of code to make this a doubly-linked list. The main difference between this and a doubly-linked-list is that the Node instances of a doubly-linked list require an additional reference that points to the previous element in the list.

The benefit of this over a recursive implementation is that it's faster and you don't have to worry about flooding the stack when you traverse large lists.

There are 3 commands to test this in the debugger/console:

  • Prefixing a value by a '+' will add it to the list.
  • Prefixing with a '-' will remove the first occurrence from the list.
  • Typing 'print' will print out the list with the values separated by spaces.

If you have never seen the internals of how one of these works I suggest you step through the following in the debugger:

  • add() - tacks a new node onto the end or initializes the first/last values if the list is empty
  • remove() - walks the list from the start-to-end. If it finds a match it removes that item and connects the broken links between the previous and next links in the chain. Special exceptions are added when there is no previous or next link.
  • toString() - uses the foreach iterator to simply walk the list chain from beginning-to-end.

While there are better and more efficient approaches for lists like array-lists, understanding how the application traverses via references/pointers is integral to understanding how many higher-level data structures work.

Laravel 4: how to "order by" using Eloquent ORM

This is how I would go about it.

$posts = $this->post->orderBy('id', 'DESC')->get();

Simplest way to detect a pinch

detect two fingers pinch zoom on any element, easy and w/o hassle with 3rd party libs like Hammer.js (beware, hammer has issues with scrolling!)

function onScale(el, callback) {
    let hypo = undefined;

    el.addEventListener('touchmove', function(event) {
        if (event.targetTouches.length === 2) {
            let hypo1 = Math.hypot((event.targetTouches[0].pageX - event.targetTouches[1].pageX),
                (event.targetTouches[0].pageY - event.targetTouches[1].pageY));
            if (hypo === undefined) {
                hypo = hypo1;
            }
            callback(hypo1/hypo);
        }
    }, false);


    el.addEventListener('touchend', function(event) {
        hypo = undefined;
    }, false);
}

Log to the base 2 in python

If you are on python 3.3 or above then it already has a built-in function for computing log2(x)

import math
'finds log base2 of x'
answer = math.log2(x)

If you are on older version of python then you can do like this

import math
'finds log base2 of x'
answer = math.log(x)/math.log(2)

How do I find out what is hammering my SQL Server?

You can find some useful query here:

Investigating the Cause of SQL Server High CPU

For me this helped a lot:

SELECT s.session_id,
    r.status,
    r.blocking_session_id 'Blk by',
    r.wait_type,
    wait_resource,
    r.wait_time / (1000 * 60) 'Wait M',
    r.cpu_time,
    r.logical_reads,
    r.reads,
    r.writes,
    r.total_elapsed_time / (1000 * 60) 'Elaps M',
    Substring(st.TEXT,(r.statement_start_offset / 2) + 1,
    ((CASE r.statement_end_offset
WHEN -1
THEN Datalength(st.TEXT)
ELSE r.statement_end_offset
END - r.statement_start_offset) / 2) + 1) AS statement_text,
    Coalesce(Quotename(Db_name(st.dbid)) + N'.' + Quotename(Object_schema_name(st.objectid, st.dbid)) + N'.' +
    Quotename(Object_name(st.objectid, st.dbid)), '') AS command_text,
    r.command,
    s.login_name,
    s.host_name,
    s.program_name,
    s.last_request_end_time,
    s.login_time,
    r.open_transaction_count
FROM sys.dm_exec_sessions AS s
    JOIN sys.dm_exec_requests AS r
ON r.session_id = s.session_id
    CROSS APPLY sys.Dm_exec_sql_text(r.sql_handle) AS st
WHERE r.session_id != @@SPID
ORDER BY r.cpu_time desc

In the fields of status, wait_type and cpu_time you can find the most cpu consuming task that is running right now.

How to embed a video into GitHub README.md?

just to extend @GabLeRoux's answer:

[<img src="https://img.youtube.com/vi/<VIDEO ID>/maxresdefault.jpg" width="50%">](https://youtu.be/<VIDEO ID>)

this way you will be able to adjust the size of the thumbnail image in the README.md file on you Github repo.

jQuery Select first and second td

You can just pick the next td:

$(".location table tbody tr td:first-child").next("td").addClass("black");

Python foreach equivalent

For a dict we can use a for loop to iterate through the index, key and value:

dictionary = {'a': 0, 'z': 25}
for index, (key, value) in enumerate(dictionary.items()):
     ## Code here ##

Generate HTML table from 2D JavaScript array

This is pretty easy to do with a double for loop.

function makeTableHTML(myArray) {
    var result = "<table border=1>";
    for(var i=0; i<myArray.length; i++) {
        result += "<tr>";
        for(var j=0; j<myArray[i].length; j++){
            result += "<td>"+myArray[i][j]+"</td>";
        }
        result += "</tr>";
    }
    result += "</table>";

    return result;
}

Android lollipop change navigation bar color

It can be done inside styles.xml using

<item name="android:navigationBarColor">@color/theme_color</item>

or

window.setNavigationBarColor(@ColorInt int color)

http://developer.android.com/reference/android/view/Window.html#setNavigationBarColor(int)

Note that the method was introduced in Android Lollipop and won't work on API version < 21.

The second method (works on KitKat) is to set windowTranslucentNavigation to true in the manifest and place a colored view beneath the navigation bar.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

If nothing happens even if you added all the annotation needed, try to add this dependency to your pom.xml, I just faced the same problem and resolved it by adding this one here:

<dependency>
   <groupId>commons-configuration</groupId>
   <artifactId>commons-configuration</artifactId>
   <version>1.9</version>
</dependency>

Python, compute list difference

You can do a

list(set(A)-set(B))

and

list(set(B)-set(A))

regular expression to match exactly 5 digits

I am reading a text file and want to use regex below to pull out numbers with exactly 5 digit, ignoring alphabets.

Try this...

var str = 'f 34 545 323 12345 54321 123456',
    matches = str.match(/\b\d{5}\b/g);

console.log(matches); // ["12345", "54321"]

jsFiddle.

The word boundary \b is your friend here.

Update

My regex will get a number like this 12345, but not like a12345. The other answers provide great regexes if you require the latter.

How to convert any date format to yyyy-MM-dd

if (DateTime.TryParse(datetoparser, out dateValue))
{
   string formatedDate = dateValue.ToString("yyyy-MM-dd");
}

How to use SQL Select statement with IF EXISTS sub query?

Use a CASE statement and do it like this:

SELECT 
    T1.Id [Id]
    ,CASE WHEN T2.Id IS NOT NULL THEN 'TRUE' ELSE 'FALSE' END [Has Foreign Key in T2]
FROM
    TABLE1 [T1]
    LEFT OUTER JOIN
        TABLE2 [T2]
        ON
        T2.Id = T1.Id

Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."

I ran into this and it was caused by the entity's ID (key) field not being set. Thus when the context went to save the data, it could not find an ID = 0. Be sure to place a break point in your update statement and verify that the entity's ID has been set.

From Paul Bellora's comment

I had this exact issue, caused by forgetting to include the hidden ID input in the .cshtml edit page

How do I get to IIS Manager?

To open IIS Manager, click Start, type inetmgr in the Search Programs and Files box, and then press ENTER.

if the IIS Manager doesn't open that means you need to install it.

So, Follow the instruction at this link: https://docs.microsoft.com/en-us/iis/install/installing-iis-7/installing-iis-on-windows-vista-and-windows-7

How to fix error "Updating Maven Project". Unsupported IClasspathEntry kind=4?

This issue has been fixed in m2e 1.5.0 which is available for Eclipse Kepler (4.3) and Luna (4.4)

Please see https://bugs.eclipse.org/bugs/show_bug.cgi?id=374332#c14

The problem is caused by the fact that STS (the Spring IDE/Eclipse), as well Eclipse and other Eclipse based IDE's, use the m2e(clipse) plugin but that eclipse:eclipse has been probably been run on the project. When m2e encounters a "var" .classpath entry, it throws this error.

The update sites are specified at the following url:
http://eclipse.org/m2e/m2e-downloads.html

If you can't use m2e 1.5.0 for any reason, then :

  1. Disable the maven nature for the project (via the right-click menu)

  2. Run mvn eclipse:clean (while your project is open in STS/eclipse). Depending on the timing, you might need to do a refresh or two on the project before re-enabling the maven nature. You should be able to see that your project has lost it's Maven nature. (The eclipse:clean goal just deletes the .project, .classpath and .settings/ files/directories. You can also just remove those files (again while the project is open) instead of running mvn eclipse:clean.)

  3. Re-enable the maven nature.
    (Most of the time, this can be done by right-clicking on the project in question in the package explorer pane, and then choosing 'Configure'-> 'Convert to Maven Project')

Excel date to Unix timestamp

Here is a mapping for reference, assuming UTC for spreadsheet systems like Microsoft Excel:

                         Unix  Excel Mac    Excel    Human Date  Human Time
Excel Epoch       -2209075200      -1462        0    1900/01/00* 00:00:00 (local)
Excel = 2011 Mac† -2082758400          0     1462    1904/12/31  00:00:00 (local)
Unix Epoch                  0      24107    25569    1970/01/01  00:00:00 UTC
Example Below      1234567890      38395.6  39857.6  2009/02/13  23:31:30 UTC
Signed Int Max     2147483648      51886    50424    2038/01/19  03:14:08 UTC

One Second                  1       0.0000115740…             —  00:00:01
One Hour                 3600       0.0416666666…             -  01:00:00
One Day                 86400          1        1             -  24:00:00

*  “Jan Zero, 1900” is 1899/12/31; see the Bug section below. Excel 2011 for Mac (and older) use the 1904 date system.

 

As I often use awk to process CSV and space-delimited content, I developed a way to convert UNIX epoch to timezone/DST-appropriate Excel date format:

echo 1234567890 |awk '{ 
  # tries GNU date, tries BSD date on failure
  cmd = sprintf("date -d@%d +%%z 2>/dev/null || date -jf %%s %d +%%z", $1, $1)
  cmd |getline tz                                # read in time-specific offset
  hours = substr(tz, 2, 2) + substr(tz, 4) / 60  # hours + minutes (hi, India)
  if (tz ~ /^-/) hours *= -1                     # offset direction (east/west)
  excel = $1/86400 + hours/24 + 25569            # as days, plus offset
  printf "%.9f\n", excel
}'

I used echo for this example, but you can pipe a file where the first column (for the first cell in .csv format, call it as awk -F,) is a UNIX epoch. Alter $1 to represent your desired column/cell number or use a variable instead.

This makes a system call to date. If you will reliably have the GNU version, you can remove the 2>/dev/null || date … +%%z and the second , $1. Given how common GNU is, I wouldn't recommend assuming BSD's version.

The getline reads the time zone offset outputted by date +%z into tz, which is then translated into hours. The format will be like -0700 (PDT) or +0530 (IST), so the first substring extracted is 07 or 05, the second is 00 or 30 (then divided by 60 to be expressed in hours), and the third use of tz sees whether our offset is negative and alters hours if needed.

The formula given in all of the other answers on this page is used to set excel, with the addition of the daylight-savings-aware time zone adjustment as hours/24.

If you're on an older version of Excel for Mac, you'll need to use 24107 in place of 25569 (see the mapping above).

To convert any arbitrary non-epoch time to Excel-friendly times with GNU date:

echo "last thursday" |awk '{ 
  cmd = sprintf("date -d \"%s\" +\"%%s %%z\"", $0)
  cmd |getline
  hours = substr($2, 2, 2) + substr($2, 4) / 60
  if ($2 ~ /^-/) hours *= -1
  excel = $1/86400 + hours/24 + 25569
  printf "%.9f\n", excel
}'

This is basically the same code, but the date -d no longer has an @ to represent unix epoch (given how capable the string parser is, I'm actually surprised the @ is mandatory; what other date format has 9-10 digits?) and it's now asked for two outputs: the epoch and the time zone offset. You could therefore use e.g. @1234567890 as an input.

Bug

Lotus 1-2-3 (the original spreadsheet software) intentionally treated 1900 as a leap year despite the fact that it was not (this reduced the codebase at a time when every byte counted). Microsoft Excel retained this bug for compatibility, skipping day 60 (the fictitious 1900/02/29), retaining Lotus 1-2-3's mapping of day 59 to 1900/02/28. LibreOffice instead assigned day 60 to 1900/02/28 and pushed all previous days back one.

Any date before 1900/03/01 could be as much as a day off:

Day        Excel   LibreOffice
-1            -1    1899/12/29
 0    1900/01/00*   1899/12/30
 1    1900/01/01    1899/12/31
 2    1900/01/02    1900/01/01
 …
59    1900/02/28    1900/02/27
60    1900/02/29(!) 1900/02/28
61    1900/03/01    1900/03/01

Excel doesn't acknowledge negative dates and has a special definition of the Zeroth of January (1899/12/31) for day zero. Internally, Excel does indeed handle negative dates (they're just numbers after all), but it displays them as numbers since it doesn't know how to display them as dates (nor can it convert older dates into negative numbers). Feb 29 1900, a day that never happened, is recognized by Excel but not LibreOffice.

On - window.location.hash - Change?

You could easily implement an observer (the "watch" method) on the "hash" property of "window.location" object.

Firefox has its own implementation for watching changes of object, but if you use some other implementation (such as Watch for object properties changes in JavaScript) - for other browsers, that will do the trick.

The code will look like this:

window.location.watch(
    'hash',
    function(id,oldVal,newVal){
        console.log("the window's hash value has changed from "+oldval+" to "+newVal);
    }
);

Then you can test it:

var myHashLink = "home";
window.location = window.location + "#" + myHashLink;

And of course that will trigger your observer function.

Is there a way to access the "previous row" value in a SELECT statement?

select t2.col from (
select col,MAX(ID) id from 
(
select ROW_NUMBER() over(PARTITION by col order by col) id ,col from testtab t1) as t1
group by col) as t2

How do I partially update an object in MongoDB so the new object will overlay / merge with the existing one

Yeah, the best way is to convert the object notation to a flat key-value string representation, as mentioned in this comment: https://stackoverflow.com/a/39357531/2529199

I wanted to highlight an alternative method using this NPM library: https://www.npmjs.com/package/dot-object which lets you manipulate different objects using dot notation.

I used this pattern to programatically create a nested object property when accepting the key-value as a function variable, as follows:

const dot = require('dot-object');

function(docid, varname, varvalue){
  let doc = dot.dot({
      [varname]: varvalue 
  });

  Mongo.update({_id:docid},{$set:doc});
}

This pattern lets me use nested as well as single-level properties interchangeably, and insert them cleanly into Mongo.

If you need to play around with JS Objects beyond just Mongo, especially on the client-side but have consistency when working with Mongo, this library gives you more options than the earlier mentioned mongo-dot-notation NPM module.

P.S I originally wanted to just mention this as a comment but apparently my S/O rep isn't high enough to post a comment. So, not trying to muscle in on SzybkiSasza's comment, just wanted to highlight providing an alternative module.

How to use external ".js" files

Note :- Do not use script tag in external JavaScript file.

<html>
<head>

</head>
<body>
    <p id="cn"> Click on the button to change the light button</p>
    <button type="button" onclick="changefont()">Click</button>

     <script src="external.js"></script>
</body>

External Java Script file:-

        function changefont()
            {

                var x = document.getElementById("cn");
                x.style.fontSize = "25px";           
                x.style.color = "red"; 
            }

Inverse of matrix in R

You can use the function ginv() (Moore-Penrose generalized inverse) in the MASS package

How to remove empty cells in UITableView?

in the below method:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (([array count]*65) > [UIScreen mainScreen].bounds.size.height - 66)
    {
        Table.frame = CGRectMake(0, 66, self.view.frame.size.width, [array count]*65)); 
    }
    else
    {
        Table.frame = CGRectMake(0, 66, self.view.frame.size.width, [UIScreen mainScreen].bounds.size.height - 66);
    }
    return [array count];
}

here 65 is the height of the cell and 66 is the height of the navigation bar in UIViewController.

Repeat each row of data.frame the number of times specified in a column

Another dplyr alternative with slice where we repeat each row number freq times

library(dplyr)

df %>%  
  slice(rep(seq_len(n()), freq)) %>% 
  select(-freq)

#  var1 var2
#1    a    d
#2    b    e
#3    b    e
#4    c    f
#5    c    f
#6    c    f

seq_len(n()) part can be replaced with any of the following.

df %>% slice(rep(1:nrow(df), freq)) %>% select(-freq)
#Or
df %>% slice(rep(row_number(), freq)) %>% select(-freq)
#Or
df %>% slice(rep(seq_len(nrow(.)), freq)) %>% select(-freq)

Start an external application from a Google Chrome Extension?

Previously, you would do this through NPAPI plugins.

However, Google is now phasing out NPAPI for Chrome, so the preferred way to do this is using the native messaging API. The external application would have to register a native messaging host in order to exchange messages with your application.

How to write a JSON file in C#?

var responseData = //Fetch Data
string jsonData = JsonConvert.SerializeObject(responseData, Formatting.None);
System.IO.File.WriteAllText(Server.MapPath("~/JsonData/jsondata.txt"), jsonData);

How to layout multiple panels on a jFrame? (java)

You'll want to use a number of layout managers to help you achieve the basic results you want.

Check out A Visual Guide to Layout Managers for a comparision.

You could use a GridBagLayout but that's one of the most complex (and powerful) layout managers available in the JDK.

You could use a series of compound layout managers instead.

I'd place the graphics component and text area on a single JPanel, using a BorderLayout, with the graphics component in the CENTER and the text area in the SOUTH position.

I'd place the text field and button on a separate JPanel using a GridBagLayout (because it's the simplest I can think of to achieve the over result you want)

I'd place these two panels onto a third, master, panel, using a BorderLayout, with the first panel in the CENTER and the second at the SOUTH position.

But that's me

How to add checkboxes to JTABLE swing

1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,

2) AbstractTableModel should be useful, where is in the JTable required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel,

3) consider using DefaultTableModel, (if you are not sure about how to works) instead of AbstractTableModel,

table_with_BooleanType_column

could be generated from simple code:

import javax.swing.*;
import javax.swing.table.*;

public class TableCheckBox extends JFrame {

    private static final long serialVersionUID = 1L;
    private JTable table;

    public TableCheckBox() {
        Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
        Object[][] data = {
            {"Buy", "IBM", new Integer(1000), new Double(80.50), false},
            {"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
            {"Sell", "Apple", new Integer(3000), new Double(7.35), true},
            {"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
        };
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        table = new JTable(model) {

            private static final long serialVersionUID = 1L;

            /*@Override
            public Class getColumnClass(int column) {
            return getValueAt(0, column).getClass();
            }*/
            @Override
            public Class getColumnClass(int column) {
                switch (column) {
                    case 0:
                        return String.class;
                    case 1:
                        return String.class;
                    case 2:
                        return Integer.class;
                    case 3:
                        return Double.class;
                    default:
                        return Boolean.class;
                }
            }
        };
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);
        getContentPane().add(scrollPane);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                TableCheckBox frame = new TableCheckBox();
                frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocation(150, 150);
                frame.setVisible(true);
            }
        });
    }
}

What are "res" and "req" parameters in Express functions?

req is an object containing information about the HTTP request that raised the event. In response to req, you use res to send back the desired HTTP response.

Those parameters can be named anything. You could change that code to this if it's more clear:

app.get('/user/:id', function(request, response){
  response.send('user ' + request.params.id);
});

Edit:

Say you have this method:

app.get('/people.json', function(request, response) { });

The request will be an object with properties like these (just to name a few):

  • request.url, which will be "/people.json" when this particular action is triggered
  • request.method, which will be "GET" in this case, hence the app.get() call.
  • An array of HTTP headers in request.headers, containing items like request.headers.accept, which you can use to determine what kind of browser made the request, what sort of responses it can handle, whether or not it's able to understand HTTP compression, etc.
  • An array of query string parameters if there were any, in request.query (e.g. /people.json?foo=bar would result in request.query.foo containing the string "bar").

To respond to that request, you use the response object to build your response. To expand on the people.json example:

app.get('/people.json', function(request, response) {
  // We want to set the content-type header so that the browser understands
  //  the content of the response.
  response.contentType('application/json');

  // Normally, the data is fetched from a database, but we can cheat:
  var people = [
    { name: 'Dave', location: 'Atlanta' },
    { name: 'Santa Claus', location: 'North Pole' },
    { name: 'Man in the Moon', location: 'The Moon' }
  ];

  // Since the request is for a JSON representation of the people, we
  //  should JSON serialize them. The built-in JSON.stringify() function
  //  does that.
  var peopleJSON = JSON.stringify(people);

  // Now, we can use the response object's send method to push that string
  //  of people JSON back to the browser in response to this request:
  response.send(peopleJSON);
});

Installing the Android USB Driver in Windows 7

Just download and install "Samsung Kies" from this link. and everything would work as required.

Before installing, uninstall the drivers you have installed for your device.

Update:

Two possible solutions:

  1. Try with the Google USB driver which comes with the SDK.
  2. Download and install the Samsung USB driver from this link as suggested by Mauricio Gracia Gutierrez

How to position absolute inside a div?

The problem is described (among other) in this article.

#box is relatively positioned, which makes it part of the "flow" of the page. Your other divs are absolutely positioned, so they are removed from the page's "flow".

Page flow means that the positioning of an element effects other elements in the flow.

In other words, as #box now sees the dom, .a and .b are no longer "inside" #box.

To fix this, you would want to make everything relative, or everything absolute.

One way would be:

.a {
   position:relative;
   margin-top:10px;
   margin-left:10px;
   background-color:red;
   width:210px;
   padding: 5px;
}

Prevent scrolling of parent element when inner element scroll position reaches top/bottom?

This actually works in AngularJS. Tested on Chrome and Firefox.

.directive('stopScroll', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            element.bind('mousewheel', function (e) {
                var $this = $(this),
                    scrollTop = this.scrollTop,
                    scrollHeight = this.scrollHeight,
                    height = $this.height(),
                    delta = (e.type == 'DOMMouseScroll' ?
                    e.originalEvent.detail * -40 :
                        e.originalEvent.wheelDelta),
                    up = delta > 0;

                var prevent = function() {
                    e.stopPropagation();
                    e.preventDefault();
                    e.returnValue = false;
                    return false;
                };

                if (!up && -delta > scrollHeight - height - scrollTop) {
                    // Scrolling down, but this will take us past the bottom.
                    $this.scrollTop(scrollHeight);
                    return prevent();
                } else if (up && delta > scrollTop) {
                    // Scrolling up, but this will take us past the top.
                    $this.scrollTop(0);
                    return prevent();
                }
            });
        }
    };
})

exception.getMessage() output with class name

My guess is that you've got something in method1 which wraps one exception in another, and uses the toString() of the nested exception as the message of the wrapper. I suggest you take a copy of your project, and remove as much as you can while keeping the problem, until you've got a short but complete program which demonstrates it - at which point either it'll be clear what's going on, or we'll be in a better position to help fix it.

Here's a short but complete program which demonstrates RuntimeException.getMessage() behaving correctly:

public class Test {
    public static void main(String[] args) {
        try {
            failingMethod();
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }       

    private static void failingMethod() {
        throw new RuntimeException("Just the message");
    }
}

Output:

Error: Just the message

Verify External Script Is Loaded

Create the script tag with a specific ID and then check if that ID exists?

Alternatively, loop through script tags checking for the script 'src' and make sure those are not already loaded with the same value as the one you want to avoid ?

Edit: following feedback that a code example would be useful:

(function(){
    var desiredSource = 'https://sitename.com/js/script.js';
    var scripts       = document.getElementsByTagName('script');
    var alreadyLoaded = false;

    if(scripts.length){
        for(var scriptIndex in scripts) {
            if(!alreadyLoaded && desiredSource === scripts[scriptIndex].src) {
                alreadyLoaded = true;
            }
        }
    }
    if(!alreadyLoaded){
        // Run your code in this block?
    }
})();

As mentioned in the comments (https://stackoverflow.com/users/1358777/alwin-kesler), this may be an alternative (not benchmarked):

(function(){
    var desiredSource = 'https://sitename.com/js/script.js';
    var scripts = document.getElementsByTagName('script');
    var alreadyLoaded = false;

    for(var scriptIndex in document.scripts) {
        if(!alreadyLoaded && desiredSource === scripts[scriptIndex].src) {
            alreadyLoaded = true;
        }
    }
    if(!alreadyLoaded){
        // Run your code in this block?
    }
})();

Passing on command line arguments to runnable JAR

You can pass program arguments on the command line and get them in your Java app like this:

public static void main(String[] args) {
  String pathToXml = args[0];
....
}

Alternatively you pass a system property by changing the command line to:

java -Dpath-to-xml=enwiki-20111007-pages-articles.xml -jar wiki2txt

and your main class to:

public static void main(String[] args) {
  String pathToXml = System.getProperty("path-to-xml");
....
}

Error: Cannot pull with rebase: You have unstaged changes

If you want to keep your working changes while performing a rebase, you can use --autostash. From the documentation:

Before starting rebase, stash local modifications away (see git-stash[1]) if needed, and apply the stash when done.

For example:

git pull --rebase --autostash

show and hide divs based on radio button click

The hide selector was incorrect. I hid the blocks at page load and showed the selected value. I also changed the car div id's to make it easier to append the radio button value and create the proper id selector.

<div id="myRadioGroup">
  2 Cars<input type="radio" name="cars" checked="checked" value="2"  />
  3 Cars<input type="radio" name="cars" value="3" />
  <div id="car-2">
  2 Cars
  </div>
  <div id="car-3">
  3 Cars
  </div>
</div>

<script type="text/javascript">
$(document).ready(function(){ 
  $("div div").hide();
  $("#car-2").show();
  $("input[name$='cars']").click(function() {
      var test = $(this).val();
      $("div div").hide();
      $("#car-"+test).show();
  }); 
});
</script>

Initialize static variables in C++ class?

Optionally, move all your constants to .cpp file without declaration in .h file. Use anonymous namespace to make them invisible beyond the cpp module.

// MyClass.cpp

#include "MyClass.h"

// anonymous namespace
namespace
{
    string RE_ANY = "([^\\n]*)";
    string RE_ANY_RELUCTANT = "([^\\n]*?)";
}

// member function (static or not)
bool MyClass::foo()
{
    // logic that uses constants
    return RE_ANY_RELUCTANT.size() > 0;
}

Inner join vs Where

They're both inner joins that do the same thing, one simply uses the newer ANSI syntax.

Angular CLI - Please add a @NgModule annotation when using latest

The problem is the import of ProjectsListComponent in your ProjectsModule. You should not import that, but add it to the export array, if you want to use it outside of your ProjectsModule.

Other issues are your project routes. You should add these to an exportable variable, otherwise it's not AOT compatible. And you should -never- import the BrowserModule anywhere else but in your AppModule. Use the CommonModule to get access to the *ngIf, *ngFor...etc directives:

@NgModule({
  declarations: [
     ProjectsListComponent
  ],
  imports: [
    CommonModule,
    RouterModule.forChild(ProjectRoutes)
  ],
  exports: [
     ProjectsListComponent
  ]
})

export class ProjectsModule {}

project.routes.ts

export const ProjectRoutes: Routes = [
      { path: 'projects', component: ProjectsListComponent }
]

Ways to eliminate switch in code

Switch is not a good way to go as it breaks the Open Close Principal. This is how I do it.

public class Animal
{
       public abstract void Speak();
}


public class Dog : Animal
{
   public virtual void Speak()
   {
       Console.WriteLine("Hao Hao");
   }
}

public class Cat : Animal
{
   public virtual void Speak()
   {
       Console.WriteLine("Meauuuu");
   }
}

And here is how to use it (taking your code):

foreach (var animal in zoo) 
{
    echo animal.speak();
}

Basically what we are doing is delegating the responsibility to the child class instead of having the parent decide what to do with children.

You might also want to read up on "Liskov Substitution Principle".

Singleton with Arguments in Java

Use getters and setters to set the variable and make the default constructor private. Then use:

Singleton.getInstance().setX(value);

Displaying the Error Messages in Laravel after being Redirected from controller

@if ($errors->has('category'))
    <span class="error">{{ $errors->first('category') }}</span>
@endif

Merge 2 arrays of objects

Posting this because unlike the previous answers this one is generic, no external libraries, O(n), actually filters out the duplicate and keeps the order the OP is asking for (by placing the last matching element in place of first appearance):

function unique(array, keyfunc) {
    return array.reduce((result, entry) => {
        const key = keyfunc(entry)
        if(key in result.seen) {
            result.array[result.seen[key]] = entry
        } else {
            result.seen[key] = result.array.length
            result.array.push(entry)
        }
        return result
    }, { array: [], seen: {}}).array
}

Usage:

var arr1 = new Array({name: "lang", value: "English"}, {name: "age", value: "18"})
var arr2 = new Array({name : "childs", value: '5'}, {name: "lang", value: "German"})

var arr3 = unique([...arr1, ...arr2], x => x.name)
/* arr3 == [ 
    {name: "lang", value: "German"}, 
    {name: "age", value: "18"},
    {name: "childs", value: "5"}
]*/

bash echo number of lines of file given in a bash variable without the file name

I normally use the 'back tick' feature of bash

export NUM_LINES=`wc -l filename`

Note the 'tick' is the 'back tick' e.g. ` not the normal single quote

Converting HTML to Excel?

Change the content type to ms-excel in the html and browser shall open the html in the Excel as xls. If you want control over the transformation of HTML to excel use POI libraries to do so.

How to make Git "forget" about a file that was tracked but is now in .gitignore?

I always use this command to remove those untracked files. One-line, Unix-style, clean output:

git ls-files --ignored --exclude-standard | sed 's/.*/"&"/' | xargs git rm -r --cached

It lists all your ignored files, replace every output line with a quoted line instead to handle paths with spaces inside, and pass everything to git rm -r --cached to remove the paths/files/dirs from the index.

Generating CSV file for Excel, how to have a newline inside a value

You should have space characters at the start of fields ONLY where the space characters are part of the data. Excel will not strip off leading spaces. You will get unwanted spaces in your headings and data fields. Worse, the " that should be "protecting" that line-break in the third column will be ignored because it is not at the start of the field.

If you have non-ASCII characters (encoded in UTF-8) in the file, you should have a UTF-8 BOM (3 bytes, hex EF BB BF) at the start of the file. Otherwise Excel will interpret the data according to your locale's default encoding (e.g. cp1252) instead of utf-8, and your non-ASCII characters will be trashed.

Following comments apply to Excel 2003, 2007 and 2013; not tested on Excel 2000

If you open the file by double-clicking on its name in Windows Explorer, everything works OK.

If you open it from within Excel, the results vary:

  1. You have only ASCII characters in the file (and no BOM): works.
  2. You have non-ASCII characters (encoded in UTF-8) in the file, with a UTF-8 BOM at the start: it recognises that your data is encoded in UTF-8 but it ignores the csv extension and drops you into the Text Import not-a-Wizard, unfortunately with the result that you get the line-break problem.

Options include:

  1. Train the users not to open the files from within Excel :-(
  2. Consider writing an XLS file directly ... there are packages/libraries available for doing that in Python/Perl/PHP/.NET/etc

React: Expected an assignment or function call and instead saw an expression

Expected an assignment or function call and instead saw an expression.

I had this similar error with this code:

const mapStateToProps = (state) => {
    players: state
}

To correct all I needed to do was add parenthesis around the curved brackets

const mapStateToProps = (state) => ({
    players: state
});

Show "loading" animation on button click

The best loading and blocking that particular div for ajax call until it succeeded is Blockui

go through this link http://www.malsup.com/jquery/block/#element

example usage:

 <span class="no-display smallLoader"><img src="/images/loader-small.png" /></span>

script

jQuery.ajax(
{   
 url: site_path+"/restaurantlist/addtocart",
 type: "POST",
 success: function (data) {
   jQuery("#id").unblock(); 
},
beforeSend:function (data){
    jQuery("#id").block({ 
    message: jQuery(".smallLoader").html(), 
    css: { 
         border: 'none', 
         backgroundColor: 'none'
    },
    overlayCSS: { backgroundColor: '#afafaf' } 
    });

}
});

hope this helps really it is very interactive.

Convert a string to a datetime

Try converting date like this:

    Dim expenddt as Date = Date.ParseExact(edate, "dd/mm/yyyy", 
System.Globalization.DateTimeFormatInfo.InvariantInfo);

Hope this helps.

How to automatically insert a blank row after a group of data

I have a large file in excel dealing with purchase and sale of mutual fund units. Number of rows in a worksheet exceeds 4000. I have no experience with VBA and would like to work with basic excel. Taking the cue from the solutions suggested above, I tried to solve the problem ( to insert blank rows automatically) in the following manner:

  1. I sorted my file according to control fields
  2. I added a column to the file
  3. I used the "IF" function to determine when there is a change in the control data .
  4. If there is a change the result will indicate "yes", otherwise "no"
  5. Then I filtered the data to group all "yes" items
  6. I copied mutual fund names, folio number etc (no financial data)
  7. Then I removed the filter and sorted the file again. The result is a row added at the desired place. (It is not entirely a blank row, because if it is fully blank, sorting will not place the row at the desired place.)
  8. After sorting, you can easily delete all values to get a completely blank row.

This method also may be tried by the readers.