Programs & Examples On #Embedded

Embedded refers to embedded systems, which involves areas such as microcontroller/DSP firmware programming, real-time systems, electronic interfaces, hardware drivers, serial bus communication etc.

Unit Testing C Code

I'm surprised that no one mentioned Cutter (http://cutter.sourceforge.net/) You can test C and C++, it seamlessly integrates with autotools and has a really nice tutorial available.

What is the difference between C and embedded C?

In the C standard, a standalone implementation doesn't have to provide all of the library functions that a hosted implementation has to provide. The C standard doesn't care about embedded, but vendors of embedded systems usually provide standalone implementations with whatever amount of libraries they're willing to provide.

C is a widely used general purpose high level programming language mainly intended for system programming.

Embedded C is an extension to C programming language that provides support for developing efficient programs for embedded devices.It is not a part of the C language

You can also refer to the articles below:

How do you implement a class in C?

Use a struct to simulate the data members of a class. In terms of method scope you can simulate private methods by placing the private function prototypes in the .c file and the public functions in the .h file.

Understanding Linux /proc/id/maps

Each row in /proc/$PID/maps describes a region of contiguous virtual memory in a process or thread. Each row has the following fields:

address           perms offset  dev   inode   pathname
08048000-08056000 r-xp 00000000 03:0c 64593   /usr/sbin/gpm
  • address - This is the starting and ending address of the region in the process's address space
  • permissions - This describes how pages in the region can be accessed. There are four different permissions: read, write, execute, and shared. If read/write/execute are disabled, a - will appear instead of the r/w/x. If a region is not shared, it is private, so a p will appear instead of an s. If the process attempts to access memory in a way that is not permitted, a segmentation fault is generated. Permissions can be changed using the mprotect system call.
  • offset - If the region was mapped from a file (using mmap), this is the offset in the file where the mapping begins. If the memory was not mapped from a file, it's just 0.
  • device - If the region was mapped from a file, this is the major and minor device number (in hex) where the file lives.
  • inode - If the region was mapped from a file, this is the file number.
  • pathname - If the region was mapped from a file, this is the name of the file. This field is blank for anonymous mapped regions. There are also special regions with names like [heap], [stack], or [vdso]. [vdso] stands for virtual dynamic shared object. It's used by system calls to switch to kernel mode. Here's a good article about it: "What is linux-gate.so.1?"

You might notice a lot of anonymous regions. These are usually created by mmap but are not attached to any file. They are used for a lot of miscellaneous things like shared memory or buffers not allocated on the heap. For instance, I think the pthread library uses anonymous mapped regions as stacks for new threads.

What does this GCC error "... relocation truncated to fit..." mean?

Minimal example that generates the error

main.S moves an address into %eax (32-bit).

main.S

_start:
    mov $_start, %eax

linker.ld

SECTIONS
{
    /* This says where `.text` will go in the executable. */
    . = 0x100000000;
    .text :
    {
        *(*)
    }
}

Compile on x86-64:

as -o main.o main.S
ld -o main.out -T linker.ld main.o

Outcome of ld:

(.text+0x1): relocation truncated to fit: R_X86_64_32 against `.text'

Keep in mind that:

  • as puts everything on the .text if no other section is specified
  • ld uses the .text as the default entry point if ENTRY. Thus _start is the very first byte of .text.

How to fix it: use this linker.ld instead, and subtract 1 from the start:

SECTIONS
{
    . = 0xFFFFFFFF;
    .text :
    {
        *(*)
    }
}

Notes:

  • we cannot make _start global in this example with .global _start, otherwise it still fails. I think this happens because global symbols have alignment constraints (0xFFFFFFF0 works). TODO where is that documented in the ELF standard?

  • the .text segment also has an alignment constraint of p_align == 2M. But our linker is smart enough to place the segment at 0xFFE00000, fill with zeros until 0xFFFFFFFF and set e_entry == 0xFFFFFFFF. This works, but generates an oversized executable.

Tested on Ubuntu 14.04 AMD64, Binutils 2.24.

Explanation

First you must understand what relocation is with a minimal example: https://stackoverflow.com/a/30507725/895245

Next, take a look at objdump -Sr main.o:

0000000000000000 <_start>:
   0:   b8 00 00 00 00          mov    $0x0,%eax
                        1: R_X86_64_32  .text

If we look into how instructions are encoded in the Intel manual, we see that:

  • b8 says that this is a mov to %eax
  • 0 is an immediate value to be moved to %eax. Relocation will then modify it to contain the address of _start.

When moving to 32-bit registers, the immediate must also be 32-bit.

But here, the relocation has to modify those 32-bit to put the address of _start into them after linking happens.

0x100000000 does not fit into 32-bit, but 0xFFFFFFFF does. Thus the error.

This error can only happen on relocations that generate truncation, e.g. R_X86_64_32 (8 bytes to 4 bytes), but never on R_X86_64_64.

And there are some types of relocation that require sign extension instead of zero extension as shown here, e.g. R_X86_64_32S. See also: https://stackoverflow.com/a/33289761/895245

R_AARCH64_PREL32

Asked at: How to prevent "main.o:(.eh_frame+0x1c): relocation truncated to fit: R_AARCH64_PREL32 against `.text'" when creating an aarch64 baremetal program?

Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

Here is a generalized solution to this kind of problem:

General procedure

The taken approach is as follows. The algorithm operates on a single buffer of 32-bit words. It performs the following procedure in a loop:

  • We start with a buffer filled with compressed data from the last iteration. The buffer looks like this

    |compressed sorted|empty|

  • Calculate the maximum amount of numbers that can be stored in this buffer, both compressed and uncompressed. Split the buffer into these two sections, beginning with the space for compressed data, ending with the uncompressed data. The buffer looks like

    |compressed sorted|empty|empty|

  • Fill the uncompressed section with numbers to be sorted. The buffer looks like

    |compressed sorted|empty|uncompressed unsorted|

  • Sort the new numbers with an in-place sort. The buffer looks like

    |compressed sorted|empty|uncompressed sorted|

  • Right-align any already compressed data from the previous iteration in the compressed section. At this point the buffer is partitioned

    |empty|compressed sorted|uncompressed sorted|

  • Perform a streaming decompression-recompression on the compressed section, merging in the sorted data in the uncompressed section. The old compressed section is consumed as the new compressed section grows. The buffer looks like

    |compressed sorted|empty|

This procedure is performed until all numbers have been sorted.

Compression

This algorithm of course only works when it's possible to calculate the final compressed size of the new sorting buffer before actually knowing what will actually be compressed. Next to that, the compression algorithm needs to be good enough to solve the actual problem.

The used approach uses three steps. First, the algorithm will always store sorted sequences, therefore we can instead store purely the differences between consecutive entries. Each difference is in the range [0, 99999999].

These differences are then encoded as a unary bitstream. A 1 in this stream means "Add 1 to the accumulator, A 0 means "Emit the accumulator as an entry, and reset". So difference N will be represented by N 1's and one 0.

The sum of all differences will approach the maximum value that the algorithm supports, and the count of all differences will approach the amount of values inserted in the algorithm. This means we expect the stream to, at the end, contain max value 1's and count 0's. This allows us to calculate the expected probability of a 0 and 1 in the stream. Namely, the probability of a 0 is count/(count+maxval) and the probability of a 1 is maxval/(count+maxval).

We use these probabilities to define an arithmetic coding model over this bitstream. This arithmetic code will encode exactly this amounts of 1's and 0's in optimal space. We can calculate the space used by this model for any intermediate bitstream as: bits = encoded * log2(1 + amount / maxval) + maxval * log2(1 + maxval / amount). To calculate the total required space for the algorithm, set encoded equal to amount.

To not require a ridiculous amount of iterations, a small overhead can be added to the buffer. This will ensure that the algorithm will at least operate on the amount of numbers that fit in this overhead, as by far the largest time cost of the algorithm is the arithmetic coding compression and decompression each cycle.

Next to that, some overhead is necessary to store bookkeeping data and to handle slight inaccuracies in the fixed-point approximation of the arithmetic coding algorithm, but in total the algorithm is able to fit in 1MiB of space even with an extra buffer that can contain 8000 numbers, for a total of 1043916 bytes of space.

Optimality

Outside of reducing the (small) overhead of the algorithm it should be theoretically impossible to get a smaller result. To just contain the entropy of the final result, 1011717 bytes would be necessary. If we subtract the extra buffer added for efficiency this algorithm used 1011916 bytes to store the final result + overhead.

Compiling an application for use in highly radioactive environments

Perhaps it would help to know does it mean for the hardware to be "designed for this environment". How does it correct and/or indicates the presence of SEU errors ?

At one space exploration related project, we had a custom MCU, which would raise an exception/interrupt on SEU errors, but with some delay, i.e. some cycles may pass/instructions be executed after the one insn which caused the SEU exception.

Particularly vulnerable was the data cache, so a handler would invalidate the offending cache line and restart the program. Only that, due to the imprecise nature of the exception, the sequence of insns headed by the exception raising insn may not be restartable.

We identified the hazardous (not restartable) sequences (like lw $3, 0x0($2), followed by an insn, which modifies $2 and is not data-dependent on $3), and I made modifications to GCC, so such sequences do not occur (e.g. as a last resort, separating the two insns by a nop).

Just something to consider ...

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 set up a Web API controller for multipart/form-data

5 years later on and .NET Core 3.1 allows you to do specify the media type like this:

[HttpPost]
[Consumes("multipart/form-data")]
public IActionResult UploadLogo()
{
    return Ok();
}

npm install error - MSB3428: Could not load the Visual C++ component "VCBuild.exe"

I managed to get it working by following Option 2 on the Windows installation instructions on the following page: https://github.com/nodejs/node-gyp.

I had to close the current command line interface and reopen it after doing the installation on another one logged in as Administrator.

What do the icons in Eclipse mean?

In eclipse help documentation, we can all icons information as follows. Common path for all eclipse versions except eclipse version:

enter image description here

https://help.eclipse.org/2019-09/index.jsp?nav=%2F1

Select count(*) from multiple tables

    select 
    t1.Count_1,t2.Count_2
    from 
(SELECT count(1) as Count_1 FROM tab1) as t1, 
(SELECT count(1) as Count_2 FROM tab2) as t2

how to break the _.each function in underscore.js

worked in my case

var arr2 = _.filter(arr, function(item){
    if ( item == 3 ) return item;
});

Understanding REST: Verbs, error codes, and authentication

For the examples you stated I'd use the following:

activate_login

POST /users/1/activation

deactivate_login

DELETE /users/1/activation

change_password

PUT /passwords (this assumes the user is authenticated)

add_credit

POST /credits (this assumes the user is authenticated)

For errors you'd return the error in the body in the format that you got the request in, so if you receive:

DELETE /users/1.xml

You'd send the response back in XML, the same would be true for JSON etc...

For authentication you should use http authentication.

Insert Unicode character into JavaScript

One option is to put the character literally in your script, e.g.:

const omega = 'O';

This requires that you let the browser know the correct source encoding, see Unicode in JavaScript

However, if you can't or don't want to do this (e.g. because the character is too exotic and can't be expected to be available in the code editor font), the safest option may be to use new-style string escape or String.fromCodePoint:

const omega = '\u{3a9}';

// or:

const omega = String.fromCodePoint(0x3a9);

This is not restricted to UTF-16 but works for all unicode code points. In comparison, the other approaches mentioned here have the following downsides:

  • HTML escapes (const omega = '&#937';): only work when rendered unescaped in an HTML element
  • old style string escapes (const omega = '\u03A9';): restricted to UTF-16
  • String.fromCharCode: restricted to UTF-16

MySQL JOIN the most recent row only?

You can also do this

SELECT    CONCAT(title, ' ', forename, ' ', surname) AS name
FROM      customer c
LEFT JOIN  (
              SELECT * FROM  customer_data ORDER BY id DESC
          ) customer_data ON (customer_data.customer_id = c.customer_id)
GROUP BY  c.customer_id          
WHERE     CONCAT(title, ' ', forename, ' ', surname) LIKE '%Smith%' 
LIMIT     10, 20;

How can I read a text file from the SD card in Android?

In response to

Don't hardcode /sdcard/

Sometimes we HAVE TO hardcode it as in some phone models the API method returns the internal phone memory.

Known types: HTC One X and Samsung S3.

Environment.getExternalStorageDirectory().getAbsolutePath() gives a different path - Android

Extracting time from POSIXct

The data.table package has a function 'as.ITime', which can do this efficiently use below:

library(data.table)
x <- "2012-03-07 03:06:49 CET"
as.IDate(x) # Output is "2012-03-07"
as.ITime(x) # Output is "03:06:49"

How can I get key's value from dictionary in Swift?

From Apple Docs

You can use subscript syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists, a dictionary’s subscript returns an optional value of the dictionary’s value type. If the dictionary contains a value for the requested key, the subscript returns an optional value containing the existing value for that key. Otherwise, the subscript returns nil:

https://developer.apple.com/documentation/swift/dictionary

if let airportName = airports["DUB"] {
    print("The name of the airport is \(airportName).")
} else {
    print("That airport is not in the airports dictionary.")
}
// prints "The name of the airport is Dublin Airport."

Extracting text from HTML file using Python

While alot of people mentioned using regex to strip html tags, there are a lot of downsides.

for example:

<p>hello&nbsp;world</p>I love you

Should be parsed to:

Hello world
I love you

Here's a snippet I came up with, you can cusomize it to your specific needs, and it works like a charm

import re
import html
def html2text(htm):
    ret = html.unescape(htm)
    ret = ret.translate({
        8209: ord('-'),
        8220: ord('"'),
        8221: ord('"'),
        160: ord(' '),
    })
    ret = re.sub(r"\s", " ", ret, flags = re.MULTILINE)
    ret = re.sub("<br>|<br />|</p>|</div>|</h\d>", "\n", ret, flags = re.IGNORECASE)
    ret = re.sub('<.*?>', ' ', ret, flags=re.DOTALL)
    ret = re.sub(r"  +", " ", ret)
    return ret

Loop through a comma-separated shell variable

Not messing with IFS
Not calling external command

variable=abc,def,ghij
for i in ${variable//,/ }
do
    # call your procedure/other scripts here below
    echo "$i"
done

Using bash string manipulation http://www.tldp.org/LDP/abs/html/string-manipulation.html

How to add certificate chain to keystore?

From the keytool man - it imports certificate chain, if input is given in PKCS#7 format, otherwise only the single certificate is imported. You should be able to convert certificates to PKCS#7 format with openssl, via openssl crl2pkcs7 command.

Convert pandas dataframe to NumPy array

It seems like df.to_records() will work for you. The exact feature you're looking for was requested and to_records pointed to as an alternative.

I tried this out locally using your example, and that call yields something very similar to the output you were looking for:

rec.array([(1, nan, 0.2, nan), (2, nan, nan, 0.5), (3, nan, 0.2, 0.5),
       (4, 0.1, 0.2, nan), (5, 0.1, 0.2, 0.5), (6, 0.1, nan, 0.5),
       (7, 0.1, nan, nan)],
      dtype=[(u'ID', '<i8'), (u'A', '<f8'), (u'B', '<f8'), (u'C', '<f8')])

Note that this is a recarray rather than an array. You could move the result in to regular numpy array by calling its constructor as np.array(df.to_records()).

How to select current date in Hive SQL

Yes... I am using Hue 3.7.0 - The Hadoop UI and to get current date/time information we can use below commands in Hive:

SELECT from_unixtime(unix_timestamp()); --/Selecting Current Time stamp/

SELECT CURRENT_DATE; --/Selecting Current Date/

SELECT CURRENT_TIMESTAMP; --/Selecting Current Time stamp/

However, in Impala you will find that only below command is working to get date/time details:

SELECT from_unixtime(unix_timestamp()); --/Selecting Current Timestamp /

Hope it resolves your query :)

Python/Django: log to console under runserver, log to file under Apache

I use this:

logging.conf:

[loggers]
keys=root,applog
[handlers]
keys=rotateFileHandler,rotateConsoleHandler

[formatters]
keys=applog_format,console_format

[formatter_applog_format]
format=%(asctime)s-[%(levelname)-8s]:%(message)s

[formatter_console_format]
format=%(asctime)s-%(filename)s%(lineno)d[%(levelname)s]:%(message)s

[logger_root]
level=DEBUG
handlers=rotateFileHandler,rotateConsoleHandler

[logger_applog]
level=DEBUG
handlers=rotateFileHandler
qualname=simple_example

[handler_rotateFileHandler]
class=handlers.RotatingFileHandler
level=DEBUG
formatter=applog_format
args=('applog.log', 'a', 10000, 9)

[handler_rotateConsoleHandler]
class=StreamHandler
level=DEBUG
formatter=console_format
args=(sys.stdout,)

testapp.py:

import logging
import logging.config

def main():
    logging.config.fileConfig('logging.conf')
    logger = logging.getLogger('applog')

    logger.debug('debug message')
    logger.info('info message')
    logger.warn('warn message')
    logger.error('error message')
    logger.critical('critical message')
    #logging.shutdown()

if __name__ == '__main__':
    main()

How to add an action to a UIAlertView button using Swift iOS

this is for swift 4.2, 5 and 5+

let alert = UIAlertController(title: "ooops!", message: "Unable to login", preferredStyle: .alert)

alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))

self.present(alert, animated: true)

In practice, what are the main uses for the new "yield from" syntax in Python 3.3?

In applied usage for the Asynchronous IO coroutine, yield from has a similar behavior as await in a coroutine function. Both of which is used to suspend the execution of coroutine.

For Asyncio, if there's no need to support an older Python version (i.e. >3.5), async def/await is the recommended syntax to define a coroutine. Thus yield from is no longer needed in a coroutine.

But in general outside of asyncio, yield from <sub-generator> has still some other usage in iterating the sub-generator as mentioned in the earlier answer.

What EXACTLY is meant by "de-referencing a NULL pointer"?

It means

myclass *p = NULL;
*p = ...;  // illegal: dereferencing NULL pointer
... = *p;  // illegal: dereferencing NULL pointer
p->meth(); // illegal: equivalent to (*p).meth(), which is dereferencing NULL pointer

myclass *p = /* some legal, non-NULL pointer */;
*p = ...;  // Ok
... = *p;  // Ok
p->meth(); // Ok, if myclass::meth() exists

basically, almost anything involving (*p) or implicitly involving (*p), e.g. p->... which is a shorthand for (*p). ...; except for pointer declaration.

invalid operands of types int and double to binary 'operator%'

Because % is only defined for integer types. That's the modulus operator.

5.6.2 of the standard:

The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]

As Oli pointed out, you can use fmod(). Don't forget to include math.h.

Convert pandas timezone-aware DateTimeIndex to naive timestamp, but in certain timezone

Building on D.A.'s suggestion that "the only way to do what you want is to modify the underlying data" and using numpy to modify the underlying data...

This works for me, and is pretty fast:

def tz_to_naive(datetime_index):
    """Converts a tz-aware DatetimeIndex into a tz-naive DatetimeIndex,
    effectively baking the timezone into the internal representation.

    Parameters
    ----------
    datetime_index : pandas.DatetimeIndex, tz-aware

    Returns
    -------
    pandas.DatetimeIndex, tz-naive
    """
    # Calculate timezone offset relative to UTC
    timestamp = datetime_index[0]
    tz_offset = (timestamp.replace(tzinfo=None) - 
                 timestamp.tz_convert('UTC').replace(tzinfo=None))
    tz_offset_td64 = np.timedelta64(tz_offset)

    # Now convert to naive DatetimeIndex
    return pd.DatetimeIndex(datetime_index.values + tz_offset_td64)

Git diff between current branch and master but not including unmerged master commits

As also noted by John Szakmeister and VasiliNovikov, the shortest command to get the full diff from master's perspective on your branch is:

git diff master...

This uses your local copy of master.

To compare a specific file use:

git diff master... filepath

Output example:

Example usage

Check if item is in an array / list

You can also use the same syntax for an array. For example, searching within a Pandas series:

ser = pd.Series(['some', 'strings', 'to', 'query'])

if item in ser.values:
    # do stuff

Can I give the col-md-1.5 in bootstrap?

This question is quite old, but I have made it that way (in TYPO3).

Firstly, I have made a own accessible css-class which I can choose on every content element manually.

Then, I have made a outer three column element with 11 columns (1 - 9 - 1), finally, I have modified the column width of the first and third column with CSS to 12.499999995%.

Can you use if/else conditions in CSS?

I've devised the below demo using a mix of tricks which allows simulating if/else scenarios for some properties. Any property which is numerical in its essence is easy target for this method, but properties with text values are.

This code has 3 if/else scenarios, for opacity, background color & width. All 3 are governed by two Boolean variables bool and its opposite notBool.

Those two Booleans are the key to this method, and to achieve a Boolean out of a none-boolean dynamic value, requires some math which luckily CSS allows using min & max functions.

Obviously those functions (min/max) are supported in recent browsers' versions which also supports CSS custom properties (variables).

_x000D_
_x000D_
var elm = document.querySelector('div')

setInterval(()=>{
  elm.style.setProperty('--width', Math.round(Math.random()*80 + 20))
}, 1000)
_x000D_
:root{
   --color1: lightgreen;
   --color2: salmon;
   --width: 70;  /* starting value, randomly changed by javascript every 1 second */
}

div{
 --widthThreshold: 50;
 --is-width-above-limit: Min(1, Max(var(--width) - var(--widthThreshold), 0));
 --is-width-below-limit: calc(1 - var(--is-width-above-limit));
 
 --opacity-wide: .4;     /* if width is ABOVE 50 */
 --radius-narrow: 10px;  /* if width is BELOW 50 */
 --radius-wide: 60px;    /* if width is ABOVE 50 */
 --height-narrow: 80px;  /* if width is ABOVE 50 */
 --height-wide: 160px;   /* if width is ABOVE 50 */
 
 --radiusToggle: Max(var(--radius-narrow), var(--radius-wide) * var(--is-width-above-limit));
 --opacityToggle: calc(calc(1 + var(--opacity-wide)) - var(--is-width-above-limit));
 --colorsToggle: var(--color1) calc(100% * var(--is-width-above-limit)), 
                 var(--color2) calc(100% * var(--is-width-above-limit)), 
                 var(--color2) calc(100% * (1 - var(--is-width-above-limit)));
  
 --height: Max(var(--height-wide) * var(--is-width-above-limit), var(--height-narrow));
 
 height: var(--height);
 text-align: center;
 line-height: var(--height);

 width: calc(var(--width) * 1%);
 opacity: var(--opacityToggle);
 border-radius: var(--radiusToggle);
 background: linear-gradient(var(--colorsToggle));

 transition: .3s;
}

/* prints some variables */
div::before{
  counter-reset: aa var(--width);
  content: counter(aa)"%";
}

div::after{
  counter-reset: bb var(--is-width-above-limit);
  content: " is over 50% ? "counter(bb);
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Another simply way using clamp:

_x000D_
_x000D_
label{ --width: 150 }
input:checked + div{ --width: 400 }

div{
  --isWide: Clamp(0,   (var(--width) - 150) * 99999  , 1);
  width: calc(var(--width) * 1px);
  height: 150px;
  border-radius: calc(var(--isWide) * 20px); /* if wide - add radius */
  background: lightgreen;
}
_x000D_
<label>
<input type='checkbox' hidden> 
<div>Click to toggle width</div>
</label>
_x000D_
_x000D_
_x000D_

Best so far:

I have come up with a totally unique method, which is even simpler!

This method is so cool because it is so easy to implement and also to understand. it is based on animation step() function.

Since bool can be easily calculated as either 0 or 1, this value can be used in the step! if only a single step is defined, then the if/else problem is solved.

Using the keyword forwards persist the changes.

_x000D_
_x000D_
var elm = document.querySelector('div')

setInterval(()=>{
  elm.style.setProperty('--width', Math.round(Math.random()*80 + 20))
}, 1000)
_x000D_
:root{
   --color1: salmon;
   --color2: lightgreen;
}

@keyframes if-over-threshold--container{
  to{ 
     --height: 160px;
     --radius: 30px;
     --color: var(--color2);
     opacity: .4; /* consider this as additional, never-before, style */
  }
}

@keyframes if-over-threshold--after{
  to{ 
    content: "true"; 
    color: green; 
  }
}

div{
 --width: 70;           /* must be unitless */
 --height: 80px;
 --radius: 10px;
 --color: var(--color1);
 --widthThreshold: 50;
 --is-width-over-threshold: Min(1, Max(var(--width) - var(--widthThreshold), 0));

 
 text-align: center;
 white-space: nowrap;
 transition: .3s;
 
 /* if element is narrower than --widthThreshold */
 width: calc(var(--width) * 1%);
 height: var(--height);
 line-height: var(--height);
 border-radius: var(--radius);
 background: var(--color);

 /* else */
 animation: if-over-threshold--container forwards steps(var(--is-width-over-threshold));
}

/* prints some variables */
div::before{
  counter-reset: aa var(--width);
  content: counter(aa)"% is over 50% width ? ";
}

div::after{
  content: 'false'; 
  font-weight: bold; 
  color: darkred;
  
  /* if element is wider than --widthThreshold */
  animation: if-over-threshold--after forwards steps(var(--is-width-over-threshold)) ;
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_


I've found a Chrome bug which I have reported that can affect this method in some situations where specific type of calculations is necessary, but there's a way around it.

https://bugs.chromium.org/p/chromium/issues/detail?id=1138497

Java SSLHandshakeException "no cipher suites in common"

I got this error with this ... unfortunate... package I have to use and I don't have source for. After much digging (thank you, Stack Overflow) and trying endless combinations, I finally got things running by:

  1. Creating the JKS with the entire certificate chain.

  2. Making sure the key in the JKS had the alias of the FQDN of the machine.

  3. Renaming the alias of the certificate for my machine ${FQDN}.cert

This took endless experimentation with the java command line options:

-Djavax.net.debug=ssl:handshake:verbose:keymanager:trustmanager 
-Djava.security.debug=access:stack

My key and CSR were produced in OpenSSL so I had to import the key with:

openssl pkcs12 -export -in  cert.pem -inkey  cert.key -CAfile fullChain.pem -name ${FQDN} -out cert.p12
keytool -importkeystore -destkeystore cert.jks -srckeystore cert.p12 -srcstoretype PKCS12

keytool complains about the format so I converted the format followed by adding my cert chain:

keytool -importkeystore -srckeystore cert.jks -destkeystore cert_p12.jks -deststoretype pkcs12
keytool -import -trustcacerts -alias 'DigiCert Global Root G2 IntermediateCA' -keystore cert_p12.jks -file cert2.pem -storepass "$STOREPASS" -keypass "$KEYPASS" 
keytool -import -trustcacerts -alias 'DigiCert Global Root G2'                -keystore cert_p12.jks -file cert3.pem -storepass "$STOREPASS" -keypass "$KEYPASS"

(where cert2.pem and cert3.pem were downloaded from the DigiCert web site and converted to PEM format.) When I restarted the application with the resulting jks file, things started to work.

Something else I figured out as part of this. You can check the certificate chain by using:

openssl x509 -in cert2.pem -noout -text

for all your certificates and studying the output, paying attention to the X509v3 Authority Key Identifier: and X509v3 Authority Key Identifier: lines. The X509v3 Authority Key Identifier: of one level matches the X509v3 Subject Key Identifier: of the next higher level. You found the top of chain when the Issuer: string matches the Subject: string.

I hope this can save somebody some of the time it took me.

How to get JSON response from http.Get

The ideal way is not to use ioutil.ReadAll, but rather use a decoder on the reader directly. Here's a nice function that gets a url and decodes its response onto a target structure.

var myClient = &http.Client{Timeout: 10 * time.Second}

func getJson(url string, target interface{}) error {
    r, err := myClient.Get(url)
    if err != nil {
        return err
    }
    defer r.Body.Close()

    return json.NewDecoder(r.Body).Decode(target)
}

Example use:

type Foo struct {
    Bar string
}

func main() {
    foo1 := new(Foo) // or &Foo{}
    getJson("http://example.com", foo1)
    println(foo1.Bar)

    // alternately:

    foo2 := Foo{}
    getJson("http://example.com", &foo2)
    println(foo2.Bar)
}

You should not be using the default *http.Client structure in production as this answer originally demonstrated! (Which is what http.Get/etc call to). The reason is that the default client has no timeout set; if the remote server is unresponsive, you're going to have a bad day.

Convert Map<String,Object> to Map<String,String>

Use the Java 8 way of converting a Map<String, Object> to Map<String, String>. This solution handles null values.

Map<String, String> keysValuesStrings = keysValues.entrySet().stream()
    .filter(entry -> entry.getValue() != null)
    .collect(Collectors.toMap(Entry::getKey, entry -> entry.getValue().toString()));

Java: object to byte[] and byte[] to object converter (for Tokyo Cabinet)

public static byte[] serialize(Object obj) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ObjectOutputStream os = new ObjectOutputStream(out);
    os.writeObject(obj);
    return out.toByteArray();
}
public static Object deserialize(byte[] data) throws IOException, ClassNotFoundException {
    ByteArrayInputStream in = new ByteArrayInputStream(data);
    ObjectInputStream is = new ObjectInputStream(in);
    return is.readObject();
}

What's the easiest way to install a missing Perl module?

Sometimes you can use the yum search foo to search the relative perl module, then use yum install xxx to install.

Git pull a certain branch from GitHub

I am not sure I fully understand the problem, but pulling an existing branch is done like this (at least it works for me :)

git pull origin BRANCH

This is assuming that your local branch is created off of the origin/BRANCH.

How can I change an element's class with JavaScript?

try

element.className='second'

_x000D_
_x000D_
function change(box) { box.className='second' }
_x000D_
.first  { width:  70px; height:  70px; background: #ff0                 }_x000D_
.second { width: 150px; height: 150px; background: #f00; transition: 1s }
_x000D_
<div onclick="change(this)" class="first">Click me</div>
_x000D_
_x000D_
_x000D_

How to clear react-native cache?

I went into this issue today, too. The cause was kinda silly -- vscode auto imported something from express-validator and caused the bug.

Just mentioning this in case anyone has done all the steps to clear cache/ delete modules or what not.

How to refresh app upon shaking the device?

You might want to try open source tinybus. With it shake detection is as easy as this.

public class MainActivity extends Activity {

    private Bus mBus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...

        // Create a bus and attach it to activity
        mBus = TinyBus.from(this).wire(new ShakeEventWire());
    }

    @Subscribe
    public void onShakeEvent(ShakeEvent event) {
        Toast.makeText(this, "Device has been shaken", 
                Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mBus.register(this);
    }

    @Override
    protected void onStop() {
        mBus.unregister(this);
        super.onStop();
    }
}

It uses seismic for shake detection.

How to run a PowerShell script from a batch file

I explain both why you would want to call a PowerShell script from a batch file and how to do it in my blog post here.

This is basically what you are looking for:

PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& 'C:\Users\SE\Desktop\ps.ps1'"

And if you need to run your PowerShell script as an admin, use this:

PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""C:\Users\SE\Desktop\ps.ps1""' -Verb RunAs}"

Rather than hard-coding the entire path to the PowerShell script though, I recommend placing the batch file and PowerShell script file in the same directory, as my blog post describes.

Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id}

The route engine uses the same sequence as you add rules into it. Once it gets the first matched rule, it will stop checking other rules and take this to search for controller and action.

So, you should:

  1. Put your specific rules ahead of your general rules(like default), which means use RouteTable.Routes.MapHttpRoute to map "WithActionApi" first, then "DefaultApi".

  2. Remove the defaults: new { id = System.Web.Http.RouteParameter.Optional } parameter of your "WithActionApi" rule because once id is optional, url like "/api/{part1}/{part2}" will never goes into "DefaultApi".

  3. Add an named action to your "DefaultApi" to tell the route engine which action to enter. Otherwise once you have more than one actions in your controller, the engine won't know which one to use and throws "Multiple actions were found that match the request: ...". Then to make it matches your Get method, use an ActionNameAttribute.

So your route should like this:

// Map this rule first
RouteTable.Routes.MapRoute(
     "WithActionApi",
     "api/{controller}/{action}/{id}"
 );

RouteTable.Routes.MapRoute(
    "DefaultApi",
    "api/{controller}/{id}",
    new { action="DefaultAction", id = System.Web.Http.RouteParameter.Optional }
);

And your controller:

[ActionName("DefaultAction")] //Map Action and you can name your method with any text
public string Get(int id)
{
    return "object of id id";
}        

[HttpGet]
public IEnumerable<string> ByCategoryId(int id)
{
    return new string[] { "byCategory1", "byCategory2" };
}

Invalid length parameter passed to the LEFT or SUBSTRING function

This is because the CHARINDEX-1 is returning a -ive value if the look-up for " " (space) is 0. The simplest solution would be to avoid '-ve' by adding

ABS(CHARINDEX(' ', PostCode ) -1))

which will return only +ive values for your length even if CHARINDEX(' ', PostCode ) -1) is a -ve value. Correct me if I'm wrong!

receiver type *** for instance message is a forward declaration

Check if you imported the header files of classes that are throwing this error.

C++ equivalent of StringBuffer/StringBuilder?

std::string is the C++ equivalent: It's mutable.

TypeScript enum to object array

If you are using ES8

For this case only it will work perfectly fine. It will give you value array of the given enum.

enum Colors {
  WHITE = 0,
  BLACK = 1,
  BLUE = 3
}

const colorValueArray = Object.values(Colors); //[ 'WHITE', 'BLACK', 'BLUE', 0, 1, 3 ]

You will get colorValueArray like this [ 'WHITE', 'BLACK', 'BLUE', 0, 1, 3 ]. All the keys will be in first half of the array and all the values in second half.

Even this kind of enum will work fine

enum Operation {
    READ,
    WRITE,
    EXECUTE
}

But this solution will not work for Heterogeneous enums like this

enum BooleanLikeHeterogeneousEnum {
  No = 0,
  Yes = "YES",
}

C++ multiline string literal

A probably convenient way to enter multi-line strings is by using macro's. This only works if quotes and parentheses are balanced and it does not contain 'top level' comma's:

#define MULTI_LINE_STRING(a) #a
const char *text = MULTI_LINE_STRING(
  Using this trick(,) you don't need to use quotes.
  Though newlines and     multiple     white   spaces
  will be replaced by a single whitespace.
);
printf("[[%s]]\n",text);

Compiled with gcc 4.6 or g++ 4.6, this produces: [[Using this trick(,) you don't need to use quotes. Though newlines and multiple white spaces will be replaced by a single whitespace.]]

Note that the , cannot be in the string, unless it is contained within parenthesis or quotes. Single quotes is possible, but creates compiler warnings.

Edit: As mentioned in the comments, #define MULTI_LINE_STRING(...) #__VA_ARGS__ allows the use of ,.

How to implement OnFragmentInteractionListener

With me it worked delete this code:

@Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

Ending like this:

@Override
public void onAttach(Context context) {
    super.onAttach(context);
}

How to run different python versions in cmd

I also met the case to use both python2 and python3 on my Windows machine. Here's how i resolved it:

  1. download python2x and python3x, installed them.
  2. add C:\Python35;C:\Python35\Scripts;C:\Python27;C:\Python27\Scripts to environment variable PATH.
  3. Go to C:\Python35 to rename python.exe to python3.exe, also to C:\Python27, rename python.exe to python2.exe.
  4. restart your command window.
  5. type python2 scriptname.py, or python3 scriptname.py in command line to switch the version you like.

iText - add content to existing PDF file

Gutch's code is close, but it'll only work right if:

  • There are no annotations (links, fields, etc), no Document Structure/Marked Content, no bookmarks, no document-level script, etc, etc, etc...
  • The page size happens to be A.4 (decent odds, but it won't work on any ol' PDF you happen to come across)
  • You don't mind losing all the original document metadata (producer, creation date, possibly author/title/keywords), and maybe the document ID. You can't copy the creation date and doc ID unless you do some pretty deep hackery on iText itself).

The Approved Method is to do it the other way around. Open the existing document with a PdfStamper, and use the returned PdfContentByte from getOverContent() to write text (and whatever else you might need) directly to the page. No second document needed.

And you can use a ColumnText to handle layout and such for you... no need to get down and dirty with beginText(),setFontAndSize(),drawText(),drawText()...,endText().

Error: getaddrinfo ENOTFOUND in nodejs for get call

When I tried to install a new ionic app, I got the same error as follows, I tried many sources and found the mistake made in User Environment and System Environment unnecessarily included the PROXY value. I removed the ```user variables http://host:port PROXY

system Variables http_proxy http://username:password@host:port ```` and now it is working fine without trouble.

[ERROR] Network connectivity error occurred, are you offline?

        If you are behind a firewall and need to configure proxy settings, see: https://ion.link/cli-proxy-docs

        Error: getaddrinfo ENOTFOUND host host:80

Java inner class and static nested class

The instance of the inner class is created when instance of the outer class is created. Therefore the members and methods of the inner class have access to the members and methods of the instance (object) of the outer class. When the instance of the outer class goes out of scope, also the inner class instances cease to exist.

The static nested class doesn't have a concrete instance. It's just loaded when it's used for the first time (just like the static methods). It's a completely independent entity, whose methods and variables doesn't have any access to the instances of the outer class.

The static nested classes are not coupled with the outer object, they are faster, and they don't take heap/stack memory, because its not necessary to create instance of such class. Therefore the rule of thumb is to try to define static nested class, with as limited scope as possible (private >= class >= protected >= public), and then convert it to inner class (by removing "static" identifier) and loosen the scope, if it's really necessary.

Default SecurityProtocol in .NET 4.5

I got the problem when my customer upgraded TLS from 1.0 to 1.2. My application is using .net framework 3.5 and run on server. So i fixed it by this way:

  1. Fix the program

Before call HttpWebRequest.GetResponse() add this command:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolTypeExtensions.Tls11 | SecurityProtocolTypeExtensions.Tls12;

Extensions 2 DLLs by adding 2 new classes: System.Net and System.Security.Authentication

    namespace System.Net
    {
        using System.Security.Authentication;
        public static class SecurityProtocolTypeExtensions
        {
            public const SecurityProtocolType Tls12 = (SecurityProtocolType)SslProtocolsExtensions.Tls12;
            public const SecurityProtocolType Tls11 = (SecurityProtocolType)SslProtocolsExtensions.Tls11;
            public const SecurityProtocolType SystemDefault = (SecurityProtocolType)0;
        }
    } 

    namespace System.Security.Authentication
    {
        public static class SslProtocolsExtensions
        {
            public const SslProtocols Tls12 = (SslProtocols)0x00000C00;
            public const SslProtocols Tls11 = (SslProtocols)0x00000300;
        }
    } 
  1. Update Microsoft batch

Download batch:

  • For windows 2008 R2: windows6.1-kb3154518-x64.msu
  • For windows 2012 R2: windows8.1-kb3154520-x64.msu

For download batch and more details you can see here:

https://support.microsoft.com/en-us/help/3154518/support-for-tls-system-default-versions-included-in-the-.net-framework-3.5.1-on-windows-7-sp1-and-server-2008-r2-sp1

What are functional interfaces used for in Java 8?

As others have said, a functional interface is an interface which exposes one method. It may have more than one method, but all of the others must have a default implementation. The reason it's called a "functional interface" is because it effectively acts as a function. Since you can pass interfaces as parameters, it means that functions are now "first-class citizens" like in functional programming languages. This has many benefits, and you'll see them quite a lot when using the Stream API. Of course, lambda expressions are the main obvious use for them.

Searching multiple files for multiple words

If you are using Notepad++ editor Goto ctrl + F choose tab 3 find in files and enter:

  1. Find What = text1*.*text2
  2. Filters : .
  3. Search mode = Regular Expression
  4. Directory = enter the path of the directory you want to search in. You can check Follow current doc. to have the path of the current file to be filled.

This application has no explicit mapping for /error

If you have annotated the interface with requestMapping, make sure you also annotate the Class which implements the interface with @Component.

How to run a javascript function during a mouseover on a div

 <div onmouseover='alert("welcome")' id="sub1 sub2 sub3">some text</div>

Or something like this

Zsh: Conda/Pip installs command not found

If anaconda is fully updated, a simple "conda init zsh" should work. Navigate into the anaconda3 folder using

cd /path/to/anaconda3/

of course replacing "/path/to/anaconda/" with "~/anaconda3" or "/anaconda3" or wherever the "anaconda3" folder is kept.

To make sure it's updated, run

./bin/conda update --prefix . anaconda

After this, running

./bin/conda init zsh

(or whatever shell you're using) will finish the job cleanly.

Remove Style on Element

Just use like this

 $("#sample_id").css("width", "");
 $("#sample_id").css("height", "");

Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style

If you are using vscode I would recommend you to click the option at the bottom-right of the window and set it to LF from CRLF..this fixed my errors

How to round each item in a list of floats to 2 decimal places?

You might want to look at Python's decimal module, which can make using floating point numbers and doing arithmetic with them a lot more intuitive. Here's a trivial example of one way of using it to "clean up" your list values:

>>> from decimal import *
>>> mylist = [0.30000000000000004, 0.5, 0.20000000000000001]
>>> getcontext().prec = 2
>>> ["%.2f" % e for e in mylist]
['0.30', '0.50', '0.20']
>>> [Decimal("%.2f" % e) for e in mylist]
[Decimal('0.30'), Decimal('0.50'), Decimal('0.20')]
>>> data = [float(Decimal("%.2f" % e)) for e in mylist]
>>> data
[0.3, 0.5, 0.2]

How to escape single quotes in MySQL

If you use prepared statements, the driver will handle any escaping. For example (Java):

Connection conn = DriverManager.getConnection(driverUrl);
conn.setAutoCommit(false);
PreparedStatement prepped = conn.prepareStatement("INSERT INTO tbl(fileinfo) VALUES(?)");
String line = null;
while ((line = br.readLine()) != null) {
    prepped.setString(1, line);
    prepped.executeQuery();
}
conn.commit();
conn.close();

TSQL select into Temp table from dynamic sql

Take a look at OPENROWSET, and do something like:

SELECT * INTO #TEMPTABLE FROM OPENROWSET('SQLNCLI'
     , 'Server=(local)\SQL2008;Trusted_Connection=yes;',
     'SELECT * FROM ' + @tableName)

How to make unicode string with python3

the easiest way in python 3.x

text = "hi , I'm text"
text.encode('utf-8')

How to get the first and last date of the current year?

The best way to get First Date and Last Date of a year Is

SELECT CAST(CAST(YEAR(DATEADD(YEAR,-1,GETDATE())) AS VARCHAR) + '-' + '01' + '-' + '01' AS DATE) FIRST_DATE
SELECT CAST(CAST(YEAR(DATEADD(YEAR,-1,GETDATE())) AS VARCHAR) + '-' + '12' + '-' + '31' AS DATE) LAST_DATE

Execute and get the output of a shell command in node.js

You can use the util library that comes with nodejs to get a promise from the exec command and can use that output as you need. Use restructuring to store the stdout and stderr in variables.

_x000D_
_x000D_
const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function lsExample() {
  const {
    stdout,
    stderr
  } = await exec('ls');
  console.log('stdout:', stdout);
  console.error('stderr:', stderr);
}
lsExample();
_x000D_
_x000D_
_x000D_

nodemon command is not recognized in terminal for node js server

The Set-ExecutionPolicy cmdlet's default execution policy is Restricted for Windows. You can try installing nodemon by setting this policy to Unrestricted.

execute command : Set-ExecutionPolicy Unrestricted and then try installing nodemon and execute command: nodemon -v

Understanding Popen.communicate

Do not use communicate(input=""). It writes input to the process, closes its stdin and then reads all output.

Do it like this:

p=subprocess.Popen(["python","1st.py"],stdin=PIPE,stdout=PIPE)

# get output from process "Something to print"
one_line_output = p.stdout.readline()

# write 'a line\n' to the process
p.stdin.write('a line\n')

# get output from process "not time to break"
one_line_output = p.stdout.readline() 

# write "n\n" to that process for if r=='n':
p.stdin.write('n\n') 

# read the last output from the process  "Exiting"
one_line_output = p.stdout.readline()

What you would do to remove the error:

all_the_process_will_tell_you = p.communicate('all you will ever say to this process\nn\n')[0]

But since communicate closes the stdout and stdin and stderr, you can not read or write after you called communicate.

jQuery Toggle Text?

Improving and Simplifying @Nate's answer:

jQuery.fn.extend({
    toggleText: function (a, b){
        var that = this;
            if (that.text() != a && that.text() != b){
                that.text(a);
            }
            else
            if (that.text() == a){
                that.text(b);
            }
            else
            if (that.text() == b){
                that.text(a);
            }
        return this;
    }
});

Use as:

$("#YourElementId").toggleText('After', 'Before');

Best way to convert an ArrayList to a string

How about this function:

public static String toString(final Collection<?> collection) {
    final StringBuilder sb = new StringBuilder("{");
    boolean isFirst = true;
    for (final Object object : collection) {
        if (!isFirst)
            sb.append(',');
        else
            isFirst = false;
        sb.append(object);
    }
    sb.append('}');
    return sb.toString();
}

it works for any type of collection...

How to set up java logging using a properties file? (java.util.logging)

Logger log = Logger.getLogger("myApp");
log.setLevel(Level.ALL);
log.info("initializing - trying to load configuration file ...");

//Properties preferences = new Properties();
try {
    //FileInputStream configFile = new //FileInputStream("/path/to/app.properties");
    //preferences.load(configFile);
    InputStream configFile = myApp.class.getResourceAsStream("app.properties");
    LogManager.getLogManager().readConfiguration(configFile);
} catch (IOException ex)
{
    System.out.println("WARNING: Could not open configuration file");
    System.out.println("WARNING: Logging not configured (console output only)");
}
log.info("starting myApp");

this is working..:) you have to pass InputStream in readConfiguration().

Client on Node.js: Uncaught ReferenceError: require is not defined

In my case I used another solution.

As the project doesn't require CommonJS and it must have ES3 compatibility (modules not supported) all you need is just remove all export and import statements from your code, because your tsconfig doesn't contain

"module": "commonjs"

But use import and export statements in your referenced files

import { Utils } from "./utils"
export interface Actions {}

Final generated code will always have(at least for TypeScript 3.0) such lines

"use strict";
exports.__esModule = true;
var utils_1 = require("./utils");
....
utils_1.Utils.doSomething();

Toolbar Navigation Hamburger Icon missing

Here is the simplest solution that worked for me.

The ActionBarDrawerToggle has two types constructors. One of them take toolbar as a parameter. Use that (second one below) to get the animated hamburger.

ActionBarDrawerToggle(this, mDrawerLayout, R.string.content_desc_drawer_open, 
R.string.content_desc_drawer_close);

ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.content_desc_drawer_open, 
R.string.content_desc_drawer_close);`  //use this constructor

python: sys is not defined

Move import sys outside of the try-except block:

import sys
try:
    # ...
except ImportError:
    # ...

If any of the imports before the import sys line fails, the rest of the block is not executed, and sys is never imported. Instead, execution jumps to the exception handling block, where you then try to access a non-existing name.

sys is a built-in module anyway, it is always present as it holds the data structures to track imports; if importing sys fails, you have bigger problems on your hand (as that would indicate that all module importing is broken).

How to right-align and justify-align in Markdown?

In a generic Markdown document, use:

<style>body {text-align: right}</style>

or

<style>body {text-align: justify}</style>

Does not seem to work with Jupyter though.

How to export data to an excel file using PHPExcel

I currently use this function in my project after a series of googling to download excel file from sql statement

    // $sql = sql query e.g "select * from mytablename"
    // $filename = name of the file to download 
        function queryToExcel($sql, $fileName = 'name.xlsx') {
                // initialise excel column name
                // currently limited to queries with less than 27 columns
        $columnArray = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
                // Execute the database query
                $result =  mysql_query($sql) or die(mysql_error());

                // Instantiate a new PHPExcel object
                $objPHPExcel = new PHPExcel();
                // Set the active Excel worksheet to sheet 0
                $objPHPExcel->setActiveSheetIndex(0);
                // Initialise the Excel row number
                $rowCount = 1;
    // fetch result set column information
                $finfo = mysqli_fetch_fields($result);
// initialise columnlenght counter                
$columnlenght = 0;
                foreach ($finfo as $val) {
// set column header values                   
  $objPHPExcel->getActiveSheet()->SetCellValue($columnArray[$columnlenght++] . $rowCount, $val->name);
                }
// make the column headers bold
                $objPHPExcel->getActiveSheet()->getStyle($columnArray[0]."1:".$columnArray[$columnlenght]."1")->getFont()->setBold(true);

                $rowCount++;
                // Iterate through each result from the SQL query in turn
                // We fetch each database result row into $row in turn

                while ($row = mysqli_fetch_array($result, MYSQL_NUM)) {
                    for ($i = 0; $i < $columnLenght; $i++) {
                        $objPHPExcel->getActiveSheet()->SetCellValue($columnArray[$i] . $rowCount, $row[$i]);
                    }
                    $rowCount++;
                }
// set header information to force download
                header('Content-type: application/vnd.ms-excel');
                header('Content-Disposition: attachment; filename="' . $fileName . '"');
                // Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file        
                // Write the Excel file to filename some_excel_file.xlsx in the current directory                
                $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); 
                // Write the Excel file to filename some_excel_file.xlsx in the current directory
                $objWriter->save('php://output');
            }

How to change indentation in Visual Studio Code?

Code Formatting Shortcut:

VSCode on Windows - Shift + Alt + F

VSCode on MacOS - Shift + Option + F

VSCode on Ubuntu - Ctrl + Shift + I

You can also customize this shortcut using preference setting if needed.

column selection with keyboard Ctrl + Shift + Alt + Arrow

Generating UML from C++ code?

I find that Wikipedia can be a great source of information about such tools, especially for comparison tables. There's a page on UML tools. See in particular the reverse engineered languages column.

Validation error: "No validator could be found for type: java.lang.Integer"

As the question is asked simply use @Min(1) instead of @size on integer fields and it will work.

Tomcat view catalina.out log file

 cd /usr/local/tomcat/logs
 tail -f catalina.out

server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

The first thing you should check for is the file permission of /etc/ssl and /etc/ssl/certs.

I made the mistake of dropping file permissions (or blowing away the SSL rm -rf /etc/ssl/* directories) when using ssl-cert group name/ID while working on my Certificate Authority Management Tool.

It was then that I noticed the exact same error message for wget and curl CLI browser tools:

server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

Once I brought the /etc/ssl and /etc/ssl/cert directories' file permission up to o+rx-w, those CLI browser tools started to breath a bit easier:

mkdir -p /etc/ssl/certs
chmod u+rwx,go+rx /etc/ssl /etc/ssl/certs

I also had to recreate Java subdirectory and reconstruct the Trusted CA certificate directories:

mkdir /etc/ssl/certs/java
chmod u+rwx,go+rx /etc/ssl/certs/java
update-ca-certificates

and the coast was clear.

Could not find or load main class org.gradle.wrapper.GradleWrapperMain

In my case it was a global .gitignore, as explained in @HankCa's answer.

Instead of forcefully adding the jar, which you'll need to remember to do in each Gradle project, I added an override to re-include the wrapper jar in my global .gitignore:

*.jar
!gradle/wrapper/gradle-wrapper.jar

This is useful to me as I have many projects that use Gradle; Git will now remind me to include the wrapper jar.

This override will work so long as no directories above gradle-wrapper.jar (such as gradle and wrapper) are ignored -- git will not descend in to ignored directories for performance reasons.

Update OpenSSL on OS X with Homebrew

I had this issue and found that the installation of the newer openssl did actually work, but my PATH was setup incorrectly for it -- my $PATH had the ports path placed before my brew path so it always found the older version of openssl.

The fix for me was to put the path to brew (/usr/local/bin) at the front of my $PATH.

To find out where you're loading openssl from, run which openssl and note the output. It will be the location of the version your system is using when you run openssl. Its going to be somewhere other than the brewpath of "/usr/local/bin". Change your $PATH, close that terminal tab and open a new one, and run which openssl. You should see a different path now, probably under /usr/local/bin. Now run openssl version and you should see the new version you installed "OpenSSL 1.0.1e 11 Feb 2013".

Updating records codeigniter

How to update in codeignitor?

whenever you want to update same status with multiple rows you use where_in insteam of where or if you want to change only single record can use where.

below is my code

$conditionArray = array(1, 3, 4, 6);
$this->db->where_in("ip_id", $conditionArray);
$this->db->update($this->table, array("status" => 'active'));

its working perfect.

Uses for the '&quot;' entity in HTML

Reason #1

There was a point where buggy/lazy implementations of HTML/XHTML renderers were more common than those that got it right. Many years ago, I regularly encountered rendering problems in mainstream browsers resulting from the use of unencoded quote chars in regular text content of HTML/XHTML documents. Though the HTML spec has never disallowed use of these chars in text content, it became fairly standard practice to encode them anyway, so that non-spec-compliant browsers and other processors would handle them more gracefully. As a result, many "old-timers" may still do this reflexively. It is not incorrect, though it is now probably unnecessary, unless you're targeting some very archaic platforms.

Reason #2

When HTML content is generated dynamically, for example, by populating an HTML template with simple string values from a database, it's necessary to encode each value before embedding it in the generated content. Some common server-side languages provided a single function for this purpose, which simply encoded all chars that might be invalid in some context within an HTML document. Notably, PHP's htmlspecialchars() function is one such example. Though there are optional arguments to htmlspecialchars() that will cause it to ignore quotes, those arguments were (and are) rarely used by authors of basic template-driven systems. The result is that all "special chars" are encoded everywhere they occur in the generated HTML, without regard for the context in which they occur. Again, this is not incorrect, it's simply unnecessary.

Android Fragment onAttach() deprecated

you are probably using android.support.v4.app.Fragment. For this instead of onAttach method, just use getActivity() to get the FragmentActivity with which the fragment is associated with. Else you could use onAttach(Context context) method.

Batch program to to check if process exists

TASKLIST doesn't set an exit code that you could check in a batch file. One workaround to checking the exit code could be parsing its standard output (which you are presently redirecting to NUL). Apparently, if the process is found, TASKLIST will display its details, which include the image name too. Therefore, you could just use FIND or FINDSTR to check if the TASKLIST's output contains the name you have specified in the request. Both FIND and FINDSTR set a non-null exit code if the search was unsuccessful. So, this would work:

@echo off
tasklist /fi "imagename eq notepad.exe" | find /i "notepad.exe" > nul
if not errorlevel 1 (taskkill /f /im "notepad.exe") else (
  specific commands to perform if the process was not found
)
exit

There's also an alternative that doesn't involve TASKLIST at all. Unlike TASKLIST, TASKKILL does set an exit code. In particular, if it couldn't terminate a process because it simply didn't exist, it would set the exit code of 128. You could check for that code to perform your specific actions that you might need to perform in case the specified process didn't exist:

@echo off
taskkill /f /im "notepad.exe" > nul
if errorlevel 128 (
  specific commands to perform if the process
  was not terminated because it was not found
)
exit

Bootstrap button drop-down inside responsive table not visible because of scroll

This has been fixed in Bootstrap v4.1 and above by adding data-boundary="viewport" (Bootstrap Dropdowns Docs)

But for earlier versions (v4.0 and below), I found this javascript snippet that works perfectly. It works for small tables and scrolling tables:

$('.table-responsive').on('shown.bs.dropdown', function (e) {
    var t = $(this),
        m = $(e.target).find('.dropdown-menu'),
        tb = t.offset().top + t.height(),
        mb = m.offset().top + m.outerHeight(true),
        d = 20; // Space for shadow + scrollbar.
    if (t[0].scrollWidth > t.innerWidth()) {
        if (mb + d > tb) {
            t.css('padding-bottom', ((mb + d) - tb));
        }
    }
    else {
        t.css('overflow', 'visible');
    }
}).on('hidden.bs.dropdown', function () {
    $(this).css({'padding-bottom': '', 'overflow': ''});
});

Log4j2 configuration - No log4j2 configuration file found

You need to choose one of the following solutions:

  1. Put the log4j2.xml file in resource directory in your project so the log4j will locate files under class path.
  2. Use system property -Dlog4j.configurationFile=file:/path/to/file/log4j2.xml

Get Substring between two characters using javascript

Use split()

var s = 'MyLongString:StringIWant;';
var arrStr = s.split(/[:;]/);
alert(arrStr);

arrStr will contain all the string delimited by : or ;
So access every string through for-loop

for(var i=0; i<arrStr.length; i++)
    alert(arrStr[i]);

How to Navigate from one View Controller to another using Swift

In Swift 4.1 and Xcode 10

Here AddFileViewController is second view controller.

Storyboard id is AFVC

let next = self.storyboard?.instantiateViewController(withIdentifier: "AFVC") as! AddFileViewController
self.present(next, animated: true, completion: nil)

//OR

//If your VC is DashboardViewController
let dashboard = self.storyboard?.instantiateViewController(withIdentifier: "DBVC") as! DashboardViewController
self.navigationController?.pushViewController(dashboard, animated: true)

If required use thread.

Ex:

DispatchQueue.main.async { 
    let next = self.storyboard?.instantiateViewController(withIdentifier: "AFVC") as! AddFileViewController
    self.present(next, animated: true, completion: nil) 
}

If you want move after some time.

EX:

//To call or execute function after some time(After 5 sec)
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
    let next = self.storyboard?.instantiateViewController(withIdentifier: "AFVC") as! AddFileViewController
    self.present(next, animated: true, completion: nil) 
} 

Java array assignment (multiple values)

Java does not provide a construct that will assign of multiple values to an existing array's elements. The initializer syntaxes can ONLY be used when creation a new array object. This can be at the point of declaration, or later on. But either way, the initializer is initializing a new array object, not updating an existing one.

jQuery 'each' loop with JSON array

My solutions in one of my own sites, with a table:

$.getJSON("sections/view_numbers_update.php", function(data) {
 $.each(data, function(index, objNumber) {
  $('#tr_' + objNumber.intID).find("td").eq(3).html(objNumber.datLastCalled);
  $('#tr_' + objNumber.intID).find("td").eq(4).html(objNumber.strStatus);
  $('#tr_' + objNumber.intID).find("td").eq(5).html(objNumber.intDuration);
  $('#tr_' + objNumber.intID).find("td").eq(6).html(objNumber.blnWasHuman);
 });
});

sections/view_numbers_update.php Returns something like:

[{"intID":"19","datLastCalled":"Thu, 10 Jan 13 08:52:20 +0000","strStatus":"Completed","intDuration":"0:04 secs","blnWasHuman":"Yes","datModified":1357807940},
{"intID":"22","datLastCalled":"Thu, 10 Jan 13 08:54:43 +0000","strStatus":"Completed","intDuration":"0:00 secs","blnWasHuman":"Yes","datModified":1357808079}]

HTML table:

<table id="table_numbers">
 <tr>
  <th>[...]</th>
  <th>[...]</th>
  <th>[...]</th>
  <th>Last Call</th>
  <th>Status</th>
  <th>Duration</th>
  <th>Human?</th>
  <th>[...]</th>
 </tr>
 <tr id="tr_123456">
  [...]
 </tr>
</table>

This essentially gives every row a unique id preceding with 'tr_' to allow for other numbered element ids, at server script time. The jQuery script then just gets this TR_[id] element, and fills the correct indexed cell with the json return.

The advantage is you could get the complete array from the DB, and either foreach($array as $record) to create the table html, OR (if there is an update request) you can die(json_encode($array)) before displaying the table, all in the same page, but same display code.

Generics/templates in python?

Python uses duck typing, so it doesn't need special syntax to handle multiple types.

If you're from a C++ background, you'll remember that, as long as the operations used in the template function/class are defined on some type T (at the syntax level), you can use that type T in the template.

So, basically, it works the same way:

  1. define a contract for the type of items you want to insert in the binary tree.
  2. document this contract (i.e. in the class documentation)
  3. implement the binary tree using only operations specified in the contract
  4. enjoy

You'll note however, that unless you write explicit type checking (which is usually discouraged), you won't be able to enforce that a binary tree contains only elements of the chosen type.

jQuery location href

I think you are looking for:

window.location = 'http://someUrl.com';

It's not jQuery; it's pure JavaScript.

Changing the cursor in WPF sometimes works, sometimes doesn't

Do you need the cursor to be a "wait" cursor only when it's over that particular page/usercontrol? If not, I'd suggest using Mouse.OverrideCursor:

Mouse.OverrideCursor = Cursors.Wait;
try
{
    // do stuff
}
finally
{
    Mouse.OverrideCursor = null;
}

This overrides the cursor for your application rather than just for a part of its UI, so the problem you're describing goes away.

What are the ways to sum matrix elements in MATLAB?

Avoid for loops whenever possible.

sum(A(:))

is great however if you have some logical indexing going on you can't use the (:) but you can write

% Sum all elements under 45 in the matrix
sum ( sum ( A *. ( A < 45 ) )

Since sum sums the columns and sums the row vector that was created by the first sum. Note that this only works if the matrix is 2-dim.

Add Text on Image using PIL

One thing not mentioned in other answers is checking the text size. It is often needed to make sure the text fits the image (e.g. shorten the text if oversized) or to determine location to draw the text (e.g. aligned text top center). Pillow/PIL offers two methods to check the text size, one via ImageFont and one via ImageDraw. As shown below, the font doesn't handle multiple lined, while ImageDraw does.

In [28]: im = Image.new(mode='RGB',size=(240,240))                                                            
In [29]: font = ImageFont.truetype('arial')
In [30]: draw = ImageDraw.Draw(im)
In [31]: t1 = 'hello world!'
In [32]: t2 = 'hello \nworld!'
In [33]: font.getsize(t1), font.getsize(t2) # the height is the same
Out[33]: ((52, 10), (60, 10)) 
In [35]: draw.textsize(t1, font), draw.textsize(t2, font)  # handles multi-lined text
Out[35]: ((52, 10), (27, 24)) 

Find and replace strings in vim on multiple lines

We don't need to bother entering the current line number.

If you would like to change each foo to bar for current line (.) and the two next lines (+2), simply do:

:.,+2s/foo/bar/g

If you want to confirm before changes are made, replace g with gc:

:.,+2s/foo/bar/gc

How to use `replace` of directive definition?

As the documentation states, 'replace' determines whether the current element is replaced by the directive. The other option is whether it is just added to as a child basically. If you look at the source of your plnkr, notice that for the second directive where replace is false that the div tag is still there. For the first directive it is not.

First result:

<span myd1="">directive template1</span>

Second result:

<div myd2=""><span>directive template2</span></div>

What in the world are Spring beans?

First let us understand Spring:

Spring is a lightweight and flexible framework.

Analogy:
enter image description here

Bean: is an object, which is created, managed and destroyed in Spring Container. We can inject an object into the Spring Container through the metadata(either xml or annotation), which is called inversion of control.

Analogy: Let us assume farmer is having a farmland cultivating by seeds(or beans). Here, Farmer is Spring Framework, Farmland land is Spring Container, Beans are Spring Beans, Cultivating is Spring Processors.

enter image description here

Like bean life-cycle, spring beans too having it's own life-cycle.

enter image description here

enter image description here

img source

Following is sequence of a bean lifecycle in Spring:

  • Instantiate: First the spring container finds the bean’s definition from the XML file and instantiates the bean.

  • Populate properties: Using the dependency injection, spring populates all of the properties as specified in the bean definition.

  • Set Bean Name: If the bean implements BeanNameAware interface, spring passes the bean’s id to setBeanName() method.

  • Set Bean factory: If Bean implements BeanFactoryAware interface, spring passes the beanfactory to setBeanFactory() method.

  • Pre-Initialization: Also called post process of bean. If there are any bean BeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization() method.

  • Initialize beans: If the bean implements IntializingBean,its afterPropertySet() method is called. If the bean has init method declaration, the specified initialization method is called.

  • Post-Initialization: – If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.

  • Ready to use: Now the bean is ready to use by the application

  • Destroy: If the bean implements DisposableBean, it will call the destroy() method

submitting a form when a checkbox is checked

You can submit form by just clicking on checkbox by simple method in JavaScript. Inside form tag or Input attribute add following attribute:

    onchange="this.form.submit()"

Example:

<form>
      <div>
           <input type="checkbox">
      </div>
</form>

Styling text input caret

In CSS3, there is now a native way to do this, without any of the hacks suggested in the existing answers: the caret-color property.

There are a lot of things you can do to with the caret, as seen below. It can even be animated.

/* Keyword value */
caret-color: auto;
color: transparent;
color: currentColor;

/* <color> values */
caret-color: red;
caret-color: #5729e9;
caret-color: rgb(0, 200, 0);
caret-color: hsla(228, 4%, 24%, 0.8);

The caret-color property is supported from Firefox 55, and Chrome 60. Support is also available in the Safari Technical Preview and in Opera (but not yet in Edge). You can view the current support tables here.

Using AES encryption in C#

Using AES or implementing AES? To use AES, there is the System.Security.Cryptography.RijndaelManaged class.

Accessing session from TWIG template

Setup twig

$twig = new Twig_Environment(...);    
$twig->addGlobal('session', $_SESSION);

Then within your template access session values for example

$_SESSION['username'] in php file Will be equivalent to {{ session.username }} in your twig template

How to set up Automapper in ASP.NET Core

I solved it this way (similar to above but I feel like it's a cleaner solution) Works with .NET Core 3.x

Create MappingProfile.cs class and populate constructor with Maps (I plan on using a single class to hold all my mappings)

    public class MappingProfile : Profile
    {
        public MappingProfile()
        {
            CreateMap<Source, Dest>().ReverseMap();
        }
    }

In Startup.cs, add below to add to DI (the assembly arg is for the class that holds your mapping configs, in my case, it's the MappingProfile class).

//add automapper DI
services.AddAutoMapper(typeof(MappingProfile));

In Controller, use it like you would any other DI object

    [Route("api/[controller]")]
    [ApiController]
    public class AnyController : ControllerBase
    {
        private readonly IMapper _mapper;

        public AnyController(IMapper mapper)
        {
            _mapper = mapper;
        }
        
        public IActionResult Get(int id)
        {
            var entity = repository.Get(id);
            var dto = _mapper.Map<Dest>(entity);
            
            return Ok(dto);
        }
    }


What is the meaning of "POSIX"?

POSIX is:

POSIX (pronounced /'p?z?ks/) or "Portable Operating System Interface [for Unix]"1 is the name of a family of related standards specified by the IEEE to define the application programming interface (API), along with shell and utilities interfaces for software compatible with variants of the Unix operating system, although the standard can apply to any operating system.

Basically it was a set of measures to ease the pain of development and usage of different flavours of UNIX by having a (mostly) common API and utilities. Limited POSIX compliance also extended to various versions of Windows.

How can I kill whatever process is using port 8080 so that I can vagrant up?

It can be Cisco AnyConnect. Check if /Library/LaunchDaemons/com.cisco.anyconnect.vpnagentd.plist exists. Then unload it with launchctl and delete from /Library/LaunchDaemons

Oracle DateTime in Where Clause?

Yes: TIME_CREATED contains a date and a time. Use TRUNC to strip the time:

SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TRUNC(TIME_CREATED) = TO_DATE('26/JAN/2011','dd/mon/yyyy')

UPDATE:
As Dave Costa points out in the comment below, this will prevent Oracle from using the index of the column TIME_CREATED if it exists. An alternative approach without this problem is this:

SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE TIME_CREATED >= TO_DATE('26/JAN/2011','dd/mon/yyyy') 
      AND TIME_CREATED < TO_DATE('26/JAN/2011','dd/mon/yyyy') + 1

How to concatenate two numbers in javascript?

You can also use toString function to convert it to string and concatenate.

var a = 5;
var b = 6;
var value = a.toString() + b.toString();

Hibernate Criteria Join with 3 Tables

The fetch mode only says that the association must be fetched. If you want to add restrictions on an associated entity, you must create an alias, or a subcriteria. I generally prefer using aliases, but YMMV:

Criteria c = session.createCriteria(Dokument.class, "dokument");
c.createAlias("dokument.role", "role"); // inner join by default
c.createAlias("role.contact", "contact");
c.add(Restrictions.eq("contact.lastName", "Test"));
return c.list();

This is of course well explained in the Hibernate reference manual, and the javadoc for Criteria even has examples. Read the documentation: it has plenty of useful information.

String delimiter in string.split method

StringTokenizer st = new StringTokenizer("1||1||Abdul-Jabbar||Karim||1996||1974",
             "||");
while(st.hasMoreTokens()){
     System.out.println(st.nextElement());
}

Answer will print

1 1 Abdul-Jabbar Karim 1996 1974

When to use pthread_exit() and when to use pthread_join() in Linux?

Hmm.

POSIX pthread_exit description from http://pubs.opengroup.org/onlinepubs/009604599/functions/pthread_exit.html:

After a thread has terminated, the result of access to local (auto) variables of the thread is 
undefined. Thus, references to local variables of the exiting thread should not be used for 
the pthread_exit() value_ptr parameter value.

Which seems contrary to the idea that local main() thread variables will remain accessible.

What is the difference between 127.0.0.1 and localhost

There is nothing different. One is easier to remember than the other. Generally, you define a name to associate with an IP address. You don't have to specify localhost for 127.0.0.1, you could specify any name you want.

How to check if a number is a power of 2

After posting the question I thought of the following solution:

We need to check if exactly one of the binary digits is one. So we simply shift the number right one digit at a time, and return true if it equals 1. If at any point we come by an odd number ((number & 1) == 1), we know the result is false. This proved (using a benchmark) slightly faster than the original method for (large) true values and much faster for false or small values.

private static bool IsPowerOfTwo(ulong number)
{
    while (number != 0)
    {
        if (number == 1)
            return true;

        if ((number & 1) == 1)
            // number is an odd number and not 1 - so it's not a power of two.
            return false;

        number = number >> 1;
    }
    return false;
}

Of course, Greg's solution is much better.

Bootstrap Columns Not Working

Your Nesting DIV structure was missing, you must add another ".row" div when creating nested divs in bootstrap :

Here is the Code:

<div class="container">
   <div class="row">
            <div class="col-md-12">
                <div class="row">
                    <div class="col-md-4"> <a href="">About</a>
    
                    </div>
                    <div class="col-md-4">
                        <img src="https://www.google.ca/images/srpr/logo11w.png" width="100px" />
                    </div>
                    <div class="col-md-4"> <a href="#myModal1" data-toggle="modal">SHARE</a>
    
                    </div>
                </div>
            </div>
        </div>
    </div>

Refer the Bootstrap example description for the same:

http://getbootstrap.com/css/

Nesting columns

To nest your content with the default grid, add a new .row and set of .col-sm-* columns within an existing .col-sm-* column. Nested rows should include a set of columns that add up to 12 or less (it is not required that you use all 12 available columns).


Here is the working Fiddle of your code: http://jsfiddle.net/52j6avkb/1/embedded/result/

Dynamically add item to jQuery Select2 control that uses AJAX

$("#my_select").select2('destroy').empty().select2({data: [{id: 1, text: "new_item"}]});

How do I remove the last comma from a string using PHP?

You can use substr function to remove this.

$t_string = "'test1', 'test2', 'test3',";
echo substr($t_string, 0, -1);

How to use class from other files in C# with visual studio?

Yeah, I just made the same 'noob' error and found this thread. I had in fact added the class to the solution and not to the project. So it looked like this:

Wrong and right description

Just adding this in the hope to be of help to someone.

How to fix "unable to write 'random state' " in openssl

just enter this line in the command line :

set RANDFILE=.rnd

show more/Less text with just HTML and JavaScript

Hope this Code you are looking for HTML:

            <div class="showmore">
                <div class="shorten_txt">
                    <h4> #@item.Title</h4>
                    <p>Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text </p>
                </div>
            </div>

SCRIPT:

    var showChar = 100;
    var ellipsestext = "[...]";
    $('.showmore').each(function () {
        $(this).find('.shorten_txt p').addClass('more_p').hide();
        $(this).find('.shorten_txt p:first').removeClass('more_p').show();
        $(this).find('.shorten_txt ul').addClass('more_p').hide();
        //you can do this above with every other element
        var teaser = $(this).find('.shorten_txt p:first').html();
        var con_length = parseInt(teaser.length);
        var c = teaser.substr(0, showChar);
        var h = teaser.substr(showChar, con_length - showChar);
        var html = '<span class="teaser_txt">' + c + '<span class="moreelipses">' + ellipsestext +
        '</span></span><span class="morecontent_txt">' + h
        + '</span>';
        if (con_length > showChar) {
            $(this).find(".shorten_txt p:first").html(html);
            $(this).find(".shorten_txt p:first span.morecontent_txt").toggle();
        }
    });
    $(".showmore").click(function () {
        if ($(this).hasClass("less")) {
            $(this).removeClass("less");
        } else {
            $(this).addClass("less");
        }
        $(this).find('.shorten_txt p:first span.moreelipses').toggle();
        $(this).find('.shorten_txt p:first span.morecontent_txt').toggle();
        $(this).find('.shorten_txt .more_p').toggle();
        return false;
    });

How, in general, does Node.js handle 10,000 concurrent requests?

Adding to slebetman's answer for more clarity on what happens while executing the code.

The internal thread pool in nodeJs just has 4 threads by default. and its not like the whole request is attached to a new thread from the thread pool the whole execution of request happens just like any normal request (without any blocking task) , just that whenever a request has any long running or a heavy operation like db call ,a file operation or a http request the task is queued to the internal thread pool which is provided by libuv. And as nodeJs provides 4 threads in internal thread pool by default every 5th or next concurrent request waits until a thread is free and once these operations are over the callback is pushed to the callback queue. and is picked up by event loop and sends back the response.

Now here comes another information that its not once single callback queue, there are many queues.

  1. NextTick queue
  2. Micro task queue
  3. Timers Queue
  4. IO callback queue (Requests, File ops, db ops)
  5. IO Poll queue
  6. Check Phase queue or SetImmediate
  7. close handlers queue

Whenever a request comes the code gets executing in this order of callbacks queued.

It is not like when there is a blocking request it is attached to a new thread. There are only 4 threads by default. So there is another queueing happening there.

Whenever in a code a blocking process like file read occurs , then calls a function which utilises thread from thread pool and then once the operation is done , the callback is passed to the respective queue and then executed in the order.

Everything gets queued based on the the type of callback and processed in the order mentioned above.

Java, how to compare Strings with String Arrays

I presume you are wanting to check if the array contains a certain value, yes? If so, use the contains method.

if(Arrays.asList(codes).contains(userCode))

How to customize the background color of a UITableViewCell?

To extend on N.Berendt's answer - If you want to set cell color based on some state in the actual cell data object, at the time you are configuring the rest of the information for the table cell, which is typically when you are in the cellForRowAtIndexPath method, you can do this by overriding the willDisplayCell method to set the cell background color from the content view background color - this gets around the issue of the disclosure button backgrounds etc. not being right but still lets you control color in the cellForRowAtIndexPath method where you are doing all of your other cell customisation.

So: If you add this method to your table view delegate:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.backgroundColor = cell.contentView.backgroundColor;
}

Then in your cellForRowAtIndexPath method you can do:

if (myCellDataObject.hasSomeStateThatMeansItShouldShowAsBlue) {
    cell.contentView.backgroundColor = [UIColor blueColor];
}

This saves having to retrieve your data objects again in the willDisplayCell method and also saves having two places where you do tailoring/customisation of your table cell - all customisation can go in the cellForRowAtIndexPath method.

How to delete a specific line in a file?

I like this method using fileinput and the 'inplace' method:

import fileinput
for line in fileinput.input(fname, inplace =1):
    line = line.strip()
    if not 'UnwantedWord' in line:
        print(line)

It's a little less wordy than the other answers and is fast enough for

How to get element by innerText

Functional approach. Returns array of all matched elements and trims spaces around while checking.

function getElementsByText(str, tag = 'a') {
  return Array.prototype.slice.call(document.getElementsByTagName(tag)).filter(el => el.textContent.trim() === str.trim());
}

Usage

getElementsByText('Text here'); // second parameter is optional tag (default "a")

if you're looking through different tags i.e. span or button

getElementsByText('Text here', 'span');
getElementsByText('Text here', 'button');

The default value tag = 'a' will need Babel for old browsers

Bold black cursor in Eclipse deletes code, and I don't know how to get rid of it

This issue can happen not only in but also in any of the .

On systems, in my case, this issue arose when the shift and insert key was pressed in tandem unintentionally which takes the user to the overwrite mode.

To get back to insert mode you need to press shift and insert in tandem again.

How do I run a simple bit of code in a new thread?

If you are going to use the raw Thread object then you need to set IsBackground to true at a minimum and you should also set the Threading Apartment model (probably STA).

public static void DoWork()
{
    // do some work
}

public static void StartWorker()
{
    Thread worker = new Thread(DoWork);
    worker.IsBackground = true;
    worker.SetApartmentState(System.Threading.ApartmentState.STA);
    worker.Start()
}

I would recommend the BackgroundWorker class if you need UI interaction.

joining two select statements

SELECT *
FROM
  (First_query) AS ONE
LEFT OUTER JOIN
  (Second_query ) AS TWO ON ONE.First_query_ID = TWO.Second_Query_ID;

How do I initialize a TypeScript Object with a JSON-Object?

This is my approach (very simple):

const jsonObj: { [key: string]: any } = JSON.parse(jsonStr);

for (const key in jsonObj) {
  if (!jsonObj.hasOwnProperty(key)) {
    continue;
  }

  console.log(key); // Key
  console.log(jsonObj[key]); // Value
  // Your logic...
}

Splitting a string into chunks of a certain size

How's this for a one-liner?

List<string> result = new List<string>(Regex.Split(target, @"(?<=\G.{4})", RegexOptions.Singleline));

With this regex it doesn't matter if the last chunk is less than four characters, because it only ever looks at the characters behind it.

I'm sure this isn't the most efficient solution, but I just had to toss it out there.

Simulating group_concat MySQL function in Microsoft SQL Server 2005?

For my fellow Googlers out there, here's a very simple plug-and-play solution that worked for me after struggling with the more complex solutions for a while:

SELECT
distinct empName,
NewColumnName=STUFF((SELECT ','+ CONVERT(VARCHAR(10), projID ) 
                     FROM returns 
                     WHERE empName=t.empName FOR XML PATH('')) , 1 , 1 , '' )
FROM 
returns t

Notice that I had to convert the ID into a VARCHAR in order to concatenate it as a string. If you don't have to do that, here's an even simpler version:

SELECT
distinct empName,
NewColumnName=STUFF((SELECT ','+ projID
                     FROM returns 
                     WHERE empName=t.empName FOR XML PATH('')) , 1 , 1 , '' )
FROM 
returns t

All credit for this goes to here: https://social.msdn.microsoft.com/Forums/sqlserver/en-US/9508abc2-46e7-4186-b57f-7f368374e084/replicating-groupconcat-function-of-mysql-in-sql-server?forum=transactsql

How to calculate a time difference in C++

See std::clock() function.

const clock_t begin_time = clock();
// do something
std::cout << float( clock () - begin_time ) /  CLOCKS_PER_SEC;

If you want calculate execution time for self ( not for user ), it is better to do this in clock ticks ( not seconds ).

EDIT:
responsible header files - <ctime> or <time.h>

What is the best way to clone/deep copy a .NET generic Dictionary<string, T>?

(Note: although the cloning version is potentially useful, for a simple shallow copy the constructor I mention in the other post is a better option.)

How deep do you want the copy to be, and what version of .NET are you using? I suspect that a LINQ call to ToDictionary, specifying both the key and element selector, will be the easiest way to go if you're using .NET 3.5.

For instance, if you don't mind the value being a shallow clone:

var newDictionary = oldDictionary.ToDictionary(entry => entry.Key,
                                               entry => entry.Value);

If you've already constrained T to implement ICloneable:

var newDictionary = oldDictionary.ToDictionary(entry => entry.Key, 
                                               entry => (T) entry.Value.Clone());

(Those are untested, but should work.)

ActionLink htmlAttributes

@Html.ActionLink("display name", "action", "Contorller"
    new { id = 1 },Html Attribute=new {Attribute1="value"})

Difference in months between two dates

LINQ Solution,

DateTime ToDate = DateTime.Today;
DateTime FromDate = ToDate.Date.AddYears(-1).AddDays(1);

int monthCount = Enumerable.Range(0, 1 + ToDate.Subtract(FromDate).Days)
                    .Select(x => FromDate.AddDays(x))
                    .ToList<DateTime>()
                    .GroupBy(z => new { z.Year, z.Month })
                    .Count();

How to get the number of columns from a JDBC ResultSet?

PreparedStatement ps=con.prepareStatement("select * from stud");

ResultSet rs=ps.executeQuery();

ResultSetMetaData rsmd=rs.getMetaData();

System.out.println("columns: "+rsmd.getColumnCount());  
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));  
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1)); 

How to change a nullable column to not nullable in a Rails migration?

Per the Strong Migrations gem, using change_column_null in production is a bad idea because it blocks reads and writes while all records are checked.

The recommended way to handle these migrations (Postgres specific) is to separate this process into two migrations.

One to alter the table with the constraint:

class SetSomeColumnNotNull < ActiveRecord::Migration[6.0]
  def change
    safety_assured do
      execute 'ALTER TABLE "users" ADD CONSTRAINT "users_some_column_null" CHECK ("some_column" IS NOT NULL) NOT VALID'
    end
  end
end

And a separate migration to validate it:

class ValidateSomeColumnNotNull < ActiveRecord::Migration[6.0]
  def change
    safety_assured do
      execute 'ALTER TABLE "users" VALIDATE CONSTRAINT "users_some_column_null"'
    end
  end
end

The above examples are pulled (and slightly altered) from the linked documentation. Apparently for Postgres 12+ you can also add NOT NULL to the schema and then drop the constraint after the validation has been run:

class ValidateSomeColumnNotNull < ActiveRecord::Migration[6.0]
  def change
    safety_assured do
      execute 'ALTER TABLE "users" VALIDATE CONSTRAINT "users_some_column_null"'
    end

    # in Postgres 12+, you can then safely set NOT NULL on the column
    change_column_null :users, :some_column, false
    safety_assured do
      execute 'ALTER TABLE "users" DROP CONSTRAINT "users_some_column_null"'
    end
  end
end

Naturally, this means your schema will not show that the column is NOT NULL for earlier versions of Postgres, so I'd also advise setting a model level validation to require the value to be present (though I'd suggest the same even for versions of PG that do allow this step).

Further, before running these migrations you'll want to update all existing records with a value other than null, and make sure any production code that writes to the table is not writing null for the value(s).

How to create Android Facebook Key Hash?

Run either this in your app :

FacebookSdk.sdkInitialize(getApplicationContext());
Log.d("AppLog", "key:" + FacebookSdk.getApplicationSignature(this)+"=");

Or this:

public static void printHashKey(Context context) {
    try {
        final PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
        for (android.content.pm.Signature signature : info.signatures) {
            final MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            final String hashKey = new String(Base64.encode(md.digest(), 0));
            Log.i("AppLog", "key:" + hashKey + "=");
        }
    } catch (Exception e) {
        Log.e("AppLog", "error:", e);
    }
}

And then look at the logs.

The result should end with "=" .

Solution is based on here and here .

Get data from file input in JQuery

input element, of type file

<input id="fileInput" type="file" />

On your input change use the FileReader object and read your input file property:

$('#fileInput').on('change', function () {
    var fileReader = new FileReader();
    fileReader.onload = function () {
      var data = fileReader.result;  // data <-- in this var you have the file data in Base64 format
    };
    fileReader.readAsDataURL($('#fileInput').prop('files')[0]);
});

FileReader will load your file and in fileReader.result you have the file data in Base64 format (also the file content-type (MIME), text/plain, image/jpg, etc)

How to temporarily disable a click handler in jQuery?

I just barely ran into this problem when trying to display a loading spinner while I waited for a function to complete. Because I was appending the spinner into the HTML, the spinner would be duplicated each time the button was clicked, if you're not against defining a variable on the global scale, then this worked well for me.

    var hasCardButtonBeenClicked = '';
    $(".js-mela-card-button").on("click", function(){  
        if(!hasCardButtonBeenClicked){
            hasCardButtonBeenClicked = true;
            $(this).append('<i class="fa fa-circle-o-notch fa-spin" style="margin-left: 3px; font-size: 15px;" aria-hidden="true"></i>');
        }    
    });

Notice, all I'm doing is declaring a variable, and as long as its value is null, the actions following the click will occur and then subsequently set the variables value to "true" (it could be any value, as long as it's not empty), further disabling the button until the browser is refreshed or the variable is set to null.

Looking back it probably would have made more sense to just set the hasCardButtonBeenClicked variable to "false" to begin with, and then alternate between "true" and "false" as needed.

AttributeError: 'dict' object has no attribute 'predictors'

#Try without dot notation
sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age']) # 29

LINQ to SQL: Multiple joins ON multiple Columns. Is this possible?

Joining on multiple columns in Linq to SQL is a little different.

var query =
    from t1 in myTABLE1List // List<TABLE_1>
    join t2 in myTABLE1List
      on new { t1.ColumnA, t1.ColumnB } equals new { t2.ColumnA, t2.ColumnB }
    ...

You have to take advantage of anonymous types and compose a type for the multiple columns you wish to compare against.

This seems confusing at first but once you get acquainted with the way the SQL is composed from the expressions it will make a lot more sense, under the covers this will generate the type of join you are looking for.

EDIT Adding example for second join based on comment.

var query =
    from t1 in myTABLE1List // List<TABLE_1>
    join t2 in myTABLE1List
      on new { A = t1.ColumnA, B = t1.ColumnB } equals new { A = t2.ColumnA, B = t2.ColumnB }
    join t3 in myTABLE1List
      on new { A = t2.ColumnA, B =  t2.ColumnB } equals new { A = t3.ColumnA, B = t3.ColumnB }
    ...

How to escape special characters of a string with single backslashes

Simply using re.sub might also work instead of str.maketrans. And this would also work in python 2.x

>>> print(re.sub(r'(\-|\]|\^|\$|\*|\.|\\)',lambda m:{'-':'\-',']':'\]','\\':'\\\\','^':'\^','$':'\$','*':'\*','.':'\.'}[m.group()],"^stack.*/overflo\w$arr=1"))
\^stack\.\*/overflo\\w\$arr=1

How to convert seconds to HH:mm:ss in moment.js

My solution for changing seconds (number) to string format (for example: 'mm:ss'):

const formattedSeconds = moment().startOf('day').seconds(S).format('mm:ss');

Write your seconds instead 'S' in example. And just use the 'formattedSeconds' where you need.

How to show full object in Chrome console?

var gandalf = {
  "real name": "Gandalf",
  "age (est)": 11000,
  "race": "Maia",
  "haveRetirementPlan": true,
  "aliases": [
    "Greyhame",
    "Stormcrow",
    "Mithrandir",
    "Gandalf the Grey",
    "Gandalf the White"
  ]
};
//to console log object, we cannot use console.log("Object gandalf: " + gandalf);
console.log("Object gandalf: ");
//this will show object gandalf ONLY in Google Chrome NOT in IE
console.log(gandalf);
//this will show object gandalf IN ALL BROWSERS!
console.log(JSON.stringify(gandalf));
//this will show object gandalf IN ALL BROWSERS! with beautiful indent
console.log(JSON.stringify(gandalf, null, 4));

setSupportActionBar toolbar cannot be applied to (android.widget.Toolbar) error

In your Activity.java import android.support.v7.widget.Toolbar instead of android.widget.Toolbar:

import android.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v7.widget.Toolbar;


public class rutaActivity extends AppCompactActivity {

private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ruta);

    getSupportActionBar().hide();//Ocultar ActivityBar anterior

    toolbar = (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(toolbar); //NO PROBLEM !!!!

Update:

If you are using androidx, replace

import android.support.v7.widget.Toolbar;
import android.support.v7.app.AppCompatActivity;

with newer imports

import androidx.appcompat.widget.Toolbar;
import androidx.appcompat.app.AppCompatActivity;

Can't Find Theme.AppCompat.Light for New Android ActionBar Support

Forget everything. Just use the appcompat library downloaded using the Android Studio. It has all the missing definitions. No matter whether you are using in Eclipse or not.

Split Div Into 2 Columns Using CSS

For whatever reason I've never liked the clearing approaches, I rely on floats and percentage widths for things like this.

Here's something that works in simple cases:

#content { 
  overflow:auto; 
  width: 600px; 
  background: gray; 
} 

#left, #right { 
  width: 40%; 
  margin:5px; 
  padding: 1em; 
  background: white; 
} 

#left  { float:left;  }
#right { float:right; } 

If you put some content in you'll see that it works:

<div id="content">
  <div id="left">
     <div id="object1">some stuff</div>
     <div id="object2">some more stuff</div>
  </div>

  <div id="right">
     <div id="object3">unas cosas</div>
     <div id="object4">mas cosas para ti</div>
  </div>
</div>

You can see it here: http://cssdesk.com/d64uy

Calling one Activity from another in Android

I used following code on my sample application to start new activity.

Button next = (Button) findViewById(R.id.TEST);
next.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
        Intent myIntent = new Intent( view.getContext(), MyActivity.class);
        startActivityForResult(myIntent, 0);
    }
});

Serving static web resources in Spring Boot & Spring Security application

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

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

        String[] resources = new String[]{
                "/", "/home","/pictureCheckCode","/include/**",
                "/css/**","/icons/**","/images/**","/js/**","/layer/**"
        };

        http.authorizeRequests()
                .antMatchers(resources).permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout().logoutUrl("/404")
                .permitAll();
        super.configure(http);
    }
}

JavaScript click event listener on class

Also consider that if you click a button, the target of the event listener is not necessaily the button itself, but whatever content inside the button you clicked on. You can reference the element to which you assigned the listener using the currentTarget property. Here is a pretty solution in modern ES using a single statement:

    document.querySelectorAll(".myClassName").forEach(i => i.addEventListener(
        "click",
        e => {
            alert(e.currentTarget.dataset.myDataContent);
        }));

How can I combine two HashMap objects containing the same types?

    HashMap<Integer,String> hs1 = new HashMap<>();
    hs1.put(1,"ram");
    hs1.put(2,"sita");
    hs1.put(3,"laxman");
    hs1.put(4,"hanuman");
    hs1.put(5,"geeta");

    HashMap<Integer,String> hs2 = new HashMap<>();
    hs2.put(5,"rat");
    hs2.put(6,"lion");
    hs2.put(7,"tiger");
    hs2.put(8,"fish");
    hs2.put(9,"hen");

    HashMap<Integer,String> hs3 = new HashMap<>();//Map is which we add

    hs3.putAll(hs1);
    hs3.putAll(hs2);

    System.out.println(" hs1 : " + hs1);
    System.out.println(" hs2 : " + hs2);
    System.out.println(" hs3 : " + hs3);

Duplicate items will not be added(that is duplicate keys) as when we will print hs3 we will get only one value for key 5 which will be last value added and it will be rat. **[Set has a property of not allowing the duplicate key but values can be duplicate]

bodyParser is deprecated express 4

It means that using the bodyParser() constructor has been deprecated, as of 2014-06-19.

app.use(bodyParser()); //Now deprecated

You now need to call the methods separately

app.use(bodyParser.urlencoded());

app.use(bodyParser.json());

And so on.

If you're still getting a warning with urlencoded you need to use

app.use(bodyParser.urlencoded({
  extended: true
}));

The extended config object key now needs to be explicitly passed, since it now has no default value.

If you are using Express >= 4.16.0, body parser has been re-added under the methods express.json() and express.urlencoded().

Convert DateTime in C# to yyyy-MM-dd format and Store it to MySql DateTime Field

Use DateTime.Now.ToString("yyyy-MM-dd h:mm tt");. See this.

Best C++ Code Formatter/Beautifier

AStyle can be customized in great detail for C++ and Java (and others too)

This is a source code formatting tool.


clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way.

It can be integrated with Visual Studio, Emacs, Vim (and others) and can format just the selected lines (or with git/svn to format some diff).

It can be configured with a variety of options listed here.

When using config files (named .clang-format) styles can be per directory - the closest such file in parent directories shall be used for a particular file.

Styles can be inherited from a preset (say LLVM or Google) and can later override different options

It is used by Google and others and is production ready.


Also look at the project UniversalIndentGUI. You can experiment with several indenters using it: AStyle, Uncrustify, GreatCode, ... and select the best for you. Any of them can be run later from a command line.


Uncrustify has a lot of configurable options. You'll probably need Universal Indent GUI (in Konstantin's reply) as well to configure it.

Jquery, set value of td in a table?

$("#button_id").click(function(){ $("#detailInfo").html("WHAT YOU WANT") })

Check whether an input string contains a number in javascript

Using Regular Expressions with JavaScript. A regular expression is a special text string for describing a search pattern, which is written in the form of /pattern/modifiers where "pattern" is the regular expression itself, and "modifiers" are a series of characters indicating various options.
         The character class is the most basic regex concept after a literal match. It makes one small sequence of characters match a larger set of characters. For example, [A-Z] could stand for the upper case alphabet, and \d could mean any digit.

From below example

  • contains_alphaNumeric « It checks for string contains either letter or number (or) both letter and number. The hyphen (-) is ignored.
  • onlyMixOfAlphaNumeric « It checks for string contain both letters and numbers only of any sequence order.

Example:

function matchExpression( str ) {
    var rgularExp = {
        contains_alphaNumeric : /^(?!-)(?!.*-)[A-Za-z0-9-]+(?<!-)$/,
        containsNumber : /\d+/,
        containsAlphabet : /[a-zA-Z]/,

        onlyLetters : /^[A-Za-z]+$/,
        onlyNumbers : /^[0-9]+$/,
        onlyMixOfAlphaNumeric : /^([0-9]+[a-zA-Z]+|[a-zA-Z]+[0-9]+)[0-9a-zA-Z]*$/
    }

    var expMatch = {};
    expMatch.containsNumber = rgularExp.containsNumber.test(str);
    expMatch.containsAlphabet = rgularExp.containsAlphabet.test(str);
    expMatch.alphaNumeric = rgularExp.contains_alphaNumeric.test(str);

    expMatch.onlyNumbers = rgularExp.onlyNumbers.test(str);
    expMatch.onlyLetters = rgularExp.onlyLetters.test(str);
    expMatch.mixOfAlphaNumeric = rgularExp.onlyMixOfAlphaNumeric.test(str);

    return expMatch;
}

// HTML Element attribute's[id, name] with dynamic values.
var id1 = "Yash", id2="777", id3= "Yash777", id4= "Yash777Image4"
    id11= "image5.64", id22= "55-5.6", id33= "image_Yash", id44= "image-Yash"
    id12= "_-.";
console.log( "Only Letters:\n ", matchExpression(id1) );
console.log( "Only Numbers:\n ", matchExpression(id2) );
console.log( "Only Mix of Letters and Numbers:\n ", matchExpression(id3) );
console.log( "Only Mix of Letters and Numbers:\n ", matchExpression(id4) );

console.log( "Mixed with Special symbols" );
console.log( "Letters and Numbers :\n ", matchExpression(id11) );
console.log( "Numbers [-]:\n ", matchExpression(id22) );
console.log( "Letters :\n ", matchExpression(id33) );
console.log( "Letters [-]:\n ", matchExpression(id44) );

console.log( "Only Special symbols :\n ", matchExpression(id12) );

Out put:

Only Letters:
  {containsNumber: false, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: true, mixOfAlphaNumeric: false}
Only Numbers:
  {containsNumber: true, containsAlphabet: false, alphaNumeric: true, onlyNumbers: true, onlyLetters: false, mixOfAlphaNumeric: false}
Only Mix of Letters and Numbers:
  {containsNumber: true, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: true}
Only Mix of Letters and Numbers:
  {containsNumber: true, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: true}
Mixed with Special symbols
Letters and Numbers :
  {containsNumber: true, containsAlphabet: true, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Numbers [-]:
  {containsNumber: true, containsAlphabet: false, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Letters :
  {containsNumber: false, containsAlphabet: true, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Letters [-]:
  {containsNumber: false, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Only Special symbols :
  {containsNumber: false, containsAlphabet: false, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}

java Pattern Matching with Regular Expressions.

Explanation of JSONB introduced by PostgreSQL

Regarding the differences between json and jsonb datatypes, it worth mentioning the official explanation:

PostgreSQL offers two types for storing JSON data: json and jsonb. To implement efficient query mechanisms for these data types, PostgreSQL also provides the jsonpath data type described in Section 8.14.6.

The json and jsonb data types accept almost identical sets of values as input. The major practical difference is one of efficiency. The json data type stores an exact copy of the input text, which processing functions must reparse on each execution; while jsonb data is stored in a decomposed binary format that makes it slightly slower to input due to added conversion overhead, but significantly faster to process, since no reparsing is needed. jsonb also supports indexing, which can be a significant advantage.

Because the json type stores an exact copy of the input text, it will preserve semantically-insignificant white space between tokens, as well as the order of keys within JSON objects. Also, if a JSON object within the value contains the same key more than once, all the key/value pairs are kept. (The processing functions consider the last value as the operative one.) By contrast, jsonb does not preserve white space, does not preserve the order of object keys, and does not keep duplicate object keys. If duplicate keys are specified in the input, only the last value is kept.

In general, most applications should prefer to store JSON data as jsonb, unless there are quite specialized needs, such as legacy assumptions about ordering of object keys.

PostgreSQL allows only one character set encoding per database. It is therefore not possible for the JSON types to conform rigidly to the JSON specification unless the database encoding is UTF8. Attempts to directly include characters that cannot be represented in the database encoding will fail; conversely, characters that can be represented in the database encoding but not in UTF8 will be allowed.

Source: https://www.postgresql.org/docs/current/datatype-json.html

Put buttons at bottom of screen with LinearLayout?

Add android:windowSoftInputMode="adjustPan" to manifest - to the corresponding activity:

  <activity android:name="MyActivity"
    ...
    android:windowSoftInputMode="adjustPan"
    ...
  </activity>

How to delete an app from iTunesConnect / App Store Connect

As the instructions state on the iTuneconnect Developer Guidelines you need to ensure that you are the "team agent" to delete apps. This is stated in the quote below from the developer guidelines.

If the Delete App button isn’t displayed, check that you’re the team agent and that the app is in one of the statuses that allow the app to be deleted.

I have just checked on my account by logging in as the main account holder and the delete button is there for an app that I have previously removed from sale but when I have looked in as another user they don't have this permission, only the main account holder seems to have it.

Appending pandas dataframes generated in a for loop

Use pd.concat to merge a list of DataFrame into a single big DataFrame.

appended_data = []
for infile in glob.glob("*.xlsx"):
    data = pandas.read_excel(infile)
    # store DataFrame in list
    appended_data.append(data)
# see pd.concat documentation for more info
appended_data = pd.concat(appended_data)
# write DataFrame to an excel sheet 
appended_data.to_excel('appended.xlsx')

ReactJS and images in public folder

You don't need any webpack configuration for this..

In your component just give image path. By default react will know its in public directory.

<img src="/image.jpg" alt="image" />

If Cell Starts with Text String... Formula

I'm not sure lookup is the right formula for this because of multiple arguments. Maybe hlookup or vlookup but these require you to have tables for values. A simple nested series of if does the trick for a small sample size

Try =IF(A1="a","pickup",IF(A1="b","collect",IF(A1="c","prepaid","")))

Now incorporate your left argument

=IF(LEFT(A1,1)="a","pickup",IF(LEFT(A1,1)="b","collect",IF(LEFT(A1,1)="c","prepaid","")))

Also note your usage of left, your argument doesn't specify the number of characters, but a set.


7/8/15 - Microsoft KB articles for the above mentioned functions. I don't think there's anything wrong with techonthenet, but I rather link to official sources.

How to use ADB in Android Studio to view an SQLite DB

The issue you are having is common and not explained well in the documentation. Normal devices do not include the sqlite3 database binary which is why you are getting an error. the Android Emeulator, OSX, Linux (if installed) and Windows (after installed) have the binary so you can open a database locally on your machine.

The workaround is to copy the Database from your device to your local machine. This can be accomplished with ADB but requires a number of steps.

Before you start you will need some information:

  • path of the SDK (if not included in your OS environment)
  • your <package name>, for example, com.example.application
  • a <local path> to place your database, eg. ~/Desktop or %userprofile%\Desktop

Next you will need to understand what terminal each command gets written to the first character in the examples below does not get typed but lets you know what shell we are in:

  • > = you OS command prompt
  • $ = ADB shell command Prompt
  • ! = ADB shell as admin command prompt
  • %

Next enter the following commands from Terminal or Command (don't enter first character or text in ())

> adb shell
$ su
! cp /data/data/<package name>/Databases/<database name> /sdcard
! exit
$ exit
> adb pull /sdcard/<database name> <local path>
> sqlite3 <local db path>
% .dump
% .exit  (to exit sqldb)

This is a really round about way of copying the database to your local machine and locally reading the database. There are SO and other resources explaining how to install the sqlite3 binary onto your device from an emulator but for one time access this process works.

If you need to access the database interactively I would suggest running your app in an emulator (that already had sqlite3) or installing sqlite onto your devices /xbin path.

Understanding the map function

map doesn't relate to a Cartesian product at all, although I imagine someone well versed in functional programming could come up with some impossible to understand way of generating a one using map.

map in Python 3 is equivalent to this:

def map(func, iterable):
    for i in iterable:
        yield func(i)

and the only difference in Python 2 is that it will build up a full list of results to return all at once instead of yielding.

Although Python convention usually prefers list comprehensions (or generator expressions) to achieve the same result as a call to map, particularly if you're using a lambda expression as the first argument:

[func(i) for i in iterable]

As an example of what you asked for in the comments on the question - "turn a string into an array", by 'array' you probably want either a tuple or a list (both of them behave a little like arrays from other languages) -

 >>> a = "hello, world"
 >>> list(a)
['h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
>>> tuple(a)
('h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd')

A use of map here would be if you start with a list of strings instead of a single string - map can listify all of them individually:

>>> a = ["foo", "bar", "baz"]
>>> list(map(list, a))
[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]

Note that map(list, a) is equivalent in Python 2, but in Python 3 you need the list call if you want to do anything other than feed it into a for loop (or a processing function such as sum that only needs an iterable, and not a sequence). But also note again that a list comprehension is usually preferred:

>>> [list(b) for b in a]
[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]

How do I redirect to the previous action in ASP.NET MVC?

try:

public ActionResult MyNextAction()
{
    return Redirect(Request.UrlReferrer.ToString());
}

alternatively, touching on what darin said, try this:

public ActionResult MyFirstAction()
{
    return RedirectToAction("MyNextAction",
        new { r = Request.Url.ToString() });
}

then:

public ActionResult MyNextAction()
{
    return Redirect(Request.QueryString["r"]);
}

Assertion failure in dequeueReusableCellWithIdentifier:forIndexPath:

In Swift this problem can be solved by adding the following code in your

viewDidLoad

method.

tableView.registerClass(UITableViewCell.classForKeyedArchiver(), forCellReuseIdentifier: "your_reuse_identifier")

int array to string

To avoid the creation of an extra array you could do the following.

var builder = new StringBuilder();
Array.ForEach(arr, x => builder.Append(x));
var res = builder.ToString();

Sum up a column from a specific row down

You all seem to love complication. Just click on column(to select entire column), press and hold CTRL and click on cells that you want to exclude(C1 to C5 in you case). Now you have selected entire column C (right to the end of sheet) without starting cells. All you have to do now is to rightclick and "Define Name" for your selection(ex. asdf ). In formula you use SUM(asdf). And now you're done. Good luck

Allways find the easyest way ;)

Good ways to manage a changelog using git?

Based on bithavoc, it lists the last tag until HEAD. But I hope to list the logs between 2 tags.

// 2 or 3 dots between `YOUR_LAST_VERSION_TAG` and `HEAD`
git log YOUR_LAST_VERSION_TAG..HEAD --no-merges --format=%B

List logs between 2 tags.

// 2 or 3 dots between 2 tags
git log FROM_TAG...TO_TAG

For example, it will list logs from v1.0.0 to v1.0.1.

git log v1.0.0...v1.0.1 --oneline --decorate

How to get first and last day of week in Oracle?

Unless this is a one-off data conversion, chances are you will benefit from using a calendar table.

Having such a table makes it really easy to filter or aggregate data for non-standard periods in addition to regular ISO weeks. Weeks usually behave a bit differently across companies and the departments within them. As soon as you leave "ISO-land" the built-in date functions can't help you.

create table calender(
   day           date      not null -- Truncated date
  ,iso_year_week number(6) not null -- ISO Year week  (IYYYIW)
  ,retail_week   number(6) not null -- Monday to Sunday (YYYYWW)
  ,purchase_week number(6) not null -- Sunday to Saturday (YYYYWW)
  ,primary key(day)
);

You can either create additional tables for "purchase_weeks" or "retail_weeks", or simply aggregate on the fly:

select a.colA
      ,a.colB
      ,b.first_day
      ,b.last_day
  from your_table_with_weeks a
  join (select iso_year_week
              ,min(day) as first_day
              ,max(day) as last_day
          from calendar
         group  
            by iso_year_week
       ) b on(a.iso_year_week = b.iso_year_week)

If you process a large number of records, aggregating on the fly won't make a noticable difference, but if you are performing single-row you would benefit from creating tables for the weeks as well.

Using calendar tables provides a subtle performance benefit in that the optimizer can provide better estimates on static columns than on nested add_months(to_date(to_char())) function calls.

Convert to/from DateTime and Time in Ruby

You can use to_date, e.g.

> Event.last.starts_at
=> Wed, 13 Jan 2021 16:49:36.292979000 CET +01:00
> Event.last.starts_at.to_date
=> Wed, 13 Jan 2021

Differences between .NET 4.0 and .NET 4.5 in High level in .NET

You can find the latest features of the .NET Framework 4.5 beta here

It breaks down the changes to the framework in the following categories:

  • .NET for Metro style Apps
  • Portable Class Libraries
  • Core New Features and Improvements
  • Parallel Computing
  • Web
  • Networking
  • Windows Presentation Foundation (WPF)
  • Windows Communication Foundation (WCF)
  • Windows Workflow Foundation (WF)

You sound like you are more interested in the Web section as this shows the changes to ASP.NET 4.5. The rest of the changes can be found under the other headings.

You can also see some of the features that were new when the .NET Framework 4.0 was shipped here.

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

Since you are using bash, you don't need to create a child process for doing this. Here is one solution which performs it entirely within bash:

[[ $TEST =~ ^(.*):\ +(.*)$ ]] && TEST=${BASH_REMATCH[1]}:${BASH_REMATCH[2]}

Explanation: The groups before and after the sequence "colon and one or more spaces" are stored by the pattern match operator in the BASH_REMATCH array.

preg_match in JavaScript?

var myregexp = /\[(\d+)\]\[(\d+)\]/;
var match = myregexp.exec(text);
if (match != null) {
    var productId = match[1];
    var shopId = match[2];
} else {
    // no match
}

VarBinary vs Image SQL Server Data Type to Store Binary Data?

Since image is deprecated, you should use varbinary.

per Microsoft (thanks for the link @Christopher)

ntext , text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.

Fixed and variable-length data types for storing large non-Unicode and Unicode character and binary data. Unicode data uses the UNICODE UCS-2 character set.

How to load images dynamically (or lazily) when users scrolls them into view

This Link work for me demo

1.Load the jQuery loadScroll plugin after jQuery library, but before the closing body tag.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script><script src="jQuery.loadScroll.js"></script>

2.Add the images into your webpage using Html5 data-src attribute. You can also insert placeholders using the regular img's src attribute.

<img data-src="1.jpg" src="Placeholder.jpg" alt="Image Alt"><img data-src="2.jpg" src="Placeholder.jpg" alt="Image Alt"><img data-src="3.jpg" src="Placeholder.jpg" alt="Image Alt">

3.Call the plugin on the img tags and specify the duration of the fadeIn effect as your images are come into view

$('img').loadScroll(500); // in ms

Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g

You need to merge the remote branch into your current branch by running git pull.

If your local branch is already up-to-date, you may also need to run git pull --rebase.

A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.

Regarding Java switch statements - using return and omitting breaks in each case

Though the question is old enough it still can be referenced nowdays.

Semantically that is exactly what Java 12 introduced (https://openjdk.java.net/jeps/325), thus, exactly in that simple example provided I can't see any problem or cons.

Filtering Pandas Dataframe using OR statement

From the docs:

Another common operation is the use of boolean vectors to filter the data. The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses.

http://pandas.pydata.org/pandas-docs/version/0.15.2/indexing.html#boolean-indexing

Try:

alldata_balance = alldata[(alldata[IBRD] !=0) | (alldata[IMF] !=0)]

How to make button look like a link?

You can't style buttons as links reliably throughout browsers. I've tried it, but there's always some weird padding, margin or font issues in some browser. Either live with letting the button look like a button, or use onClick and preventDefault on a link.

Can I use an image from my local file system as background in HTML?

It seems you can provide just the local image name, assuming it is in the same folder...

It suffices like:

background-image: url("img1.png")

How to include css files in Vue 2

If you want to append this css file to header you can do it using mounted() function of the vue file. See the example.
Note: Assume you can access the css file as http://www.yoursite/assets/styles/vendor.css in the browser.

mounted() {
        let style = document.createElement('link');
        style.type = "text/css";
        style.rel = "stylesheet";
        style.href = '/assets/styles/vendor.css';
        document.head.appendChild(style);
    }

LEFT JOIN vs. LEFT OUTER JOIN in SQL Server

What is the difference between left join and left outer join?

Nothing. LEFT JOIN and LEFT OUTER JOIN are equivalent.

How do I get the first element from an IEnumerable<T> in .net?

Just in case you're using .NET 2.0 and don't have access to LINQ:

 static T First<T>(IEnumerable<T> items)
 {
     using(IEnumerator<T> iter = items.GetEnumerator())
     {
         iter.MoveNext();
         return iter.Current;
     }
 }

This should do what you're looking for...it uses generics so you to get the first item on any type IEnumerable.

Call it like so:

List<string> items = new List<string>() { "A", "B", "C", "D", "E" };
string firstItem = First<string>(items);

Or

int[] items = new int[] { 1, 2, 3, 4, 5 };
int firstItem = First<int>(items);

You could modify it readily enough to mimic .NET 3.5's IEnumerable.ElementAt() extension method:

static T ElementAt<T>(IEnumerable<T> items, int index)
{
    using(IEnumerator<T> iter = items.GetEnumerator())
    {
        for (int i = 0; i <= index; i++, iter.MoveNext()) ;
        return iter.Current;
    }
} 

Calling it like so:

int[] items = { 1, 2, 3, 4, 5 };
int elemIdx = 3;
int item = ElementAt<int>(items, elemIdx);

Of course if you do have access to LINQ, then there are plenty of good answers posted already...

How to document a method with parameter(s)?

Based on my experience, the numpy docstring conventions (PEP257 superset) are the most widely-spread followed conventions that are also supported by tools, such as Sphinx.

One example:

Parameters
----------
x : type
    Description of parameter `x`.

How to trim white space from all elements in array?

Add commons-lang3-3.1.jar in your application build path. Use the below code snippet to trim the String array.

String array = {" String", "Tom Selleck "," Fish "};
array = StringUtils.stripAll(array);

How Do I 'git fetch' and 'git merge' from a Remote Tracking Branch (like 'git pull')

Git pull is actually a combo tool: it runs git fetch (getting the changes) and git merge (merging them with your current copy)

Are you sure you are on the correct branch?

In Flask, What is request.args and how is it used?

request.args is a MultiDict with the parsed contents of the query string. From the documentation of get method:

get(key, default=None, type=None)

Return the default value if the requested data doesn’t exist. If type is provided and is a callable it should convert the value, return it or raise a ValueError if that is not possible.

Remove Select arrow on IE

In case you want to use the class and pseudo-class:

.simple-control is your css class

:disabled is pseudo class

select.simple-control:disabled{
         /*For FireFox*/
        -webkit-appearance: none;
        /*For Chrome*/
        -moz-appearance: none;
}

/*For IE10+*/
select:disabled.simple-control::-ms-expand {
        display: none;
}

php - insert a variable in an echo string

Single quotes will not parse PHP variables inside of them. Either use double quotes or use a dot to extend the echo.

$variableName = 'Ralph';
echo 'Hello '.$variableName.'!';

OR

echo "Hello $variableName!";

And in your case:

$i = 1;
echo '<p class="paragraph'.$i.'"></p>';
++i;

OR

$i = 1;
echo "<p class='paragraph$i'></p>";
++i;

Conditionally formatting if multiple cells are blank (no numerics throughout spreadsheet )

enter image description here

How about just > Format only cells that contain - in the drop down box select Blanks

Unzip files programmatically in .net

Use the DotNetZip library at http://www.codeplex.com/DotNetZip

class library and toolset for manipulating zip files. Use VB, C# or any .NET language to easily create, extract, or update zip files...

DotNetZip works on PCs with the full .NET Framework, and also runs on mobile devices that use the .NET Compact Framework. Create and read zip files in VB, C#, or any .NET language, or any scripting environment...

If all you want is a better DeflateStream or GZipStream class to replace the one that is built-into the .NET BCL, DotNetZip has that, too. DotNetZip's DeflateStream and GZipStream are available in a standalone assembly, based on a .NET port of Zlib. These streams support compression levels and deliver much better performance than the built-in classes. There is also a ZlibStream to complete the set (RFC 1950, 1951, 1952)...

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

There is no difference between the %i and %d format specifiers for printf. We can see this by going to the draft C99 standard section 7.19.6.1 The fprintf function which also covers printf with respect to format specifiers and it says in paragraph 8:

The conversion specifiers and their meanings are:

and includes the following bullet:

d,i     The int argument is converted to signed decimal in the style
        [-]dddd. The precision specifies the minimum number of digits to
        appear; if the value being converted can be represented in fewer
        digits, it is expanded with leading zeros. The default precision is
        1. The result of converting a zero value with a precision of zero is
        no characters.

On the other hand for scanf there is a difference, %d assume base 10 while %i auto detects the base. We can see this by going to section 7.19.6.2 The fscanf function which covers scanf with respect to format specifier, in paragraph 12 it says:

The conversion specifiers and their meanings are:

and includes the following:

d     Matches an optionally signed decimal integer, whose format is the
      same as expected for the subject sequence of the strtol function with
      the value 10 for the base argument. The corresponding argument shall
      be a pointer to signed integer.

i     Matches an optionally signed integer, whose format is the same as
      expected for the subject sequence of the strtol function with the
      value 0 for the base argument. The corresponding argument shall be a
      pointer to signed integer.

RegExp matching string not starting with my

Wouldn't it be significantly more readable to do a positive match and reject those strings - rather than match the negative to find strings to accept?

/^my/

How to rename a file using Python

File may be inside a directory, in that case specify the path:

import os
old_file = os.path.join("directory", "a.txt")
new_file = os.path.join("directory", "b.kml")
os.rename(old_file, new_file)

Android Studio Could not initialize class org.codehaus.groovy.runtime.InvokerHelper

I face this issue when I was Building my Flutter Application. This error is due to the gradle version that you are using in your Android Project. Follow the below steps:

distributionUrl = https://services.gradle.org/distributions/gradle-6.3-all.zip

Now Save the File (Ctrl + S), Go to the console and run the command

flutter run

It will take some time, but the issue that you were facing will be solved.

'AND' vs '&&' as operator

Let me explain the difference between “and” - “&&” - "&".

"&&" and "and" both are logical AND operations and they do the same thing, but the operator precedence is different.

The precedence (priority) of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator.

Mixing them together in single operation, could give you unexpected results in some cases I recommend always using &&, but that's your choice.


On the other hand "&" is a bitwise AND operation. It's used for the evaluation and manipulation of specific bits within the integer value.

Example if you do (14 & 7) the result would be 6.

7   = 0111
14  = 1110
------------
    = 0110 == 6

How can I insert values into a table, using a subquery with more than one result?

INSERT INTO prices(group, id, price)
SELECT 7, articleId, 1.50
FROM article where name like 'ABC%';

Image encryption/decryption using AES256 symmetric block ciphers

For AES/CBC/PKCS7 encryption/decryption, Just Copy and paste the following code and replace SecretKey and IV with your own.

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import android.util.Base64;


public class CryptoHandler {

    String SecretKey = "xxxxxxxxxxxxxxxxxxxx";
    String IV = "xxxxxxxxxxxxxxxx";

    private static CryptoHandler instance = null;

    public static CryptoHandler getInstance() {

        if (instance == null) {
            instance = new CryptoHandler();
        }
        return instance;
    }

    public String encrypt(String message) throws NoSuchAlgorithmException,
            NoSuchPaddingException, IllegalBlockSizeException,
            BadPaddingException, InvalidKeyException,
            UnsupportedEncodingException, InvalidAlgorithmParameterException {

        byte[] srcBuff = message.getBytes("UTF8");
        //here using substring because AES takes only 16 or 24 or 32 byte of key 
        SecretKeySpec skeySpec = new 
        SecretKeySpec(SecretKey.substring(0,32).getBytes(), "AES");
        IvParameterSpec ivSpec = new 
        IvParameterSpec(IV.substring(0,16).getBytes());
        Cipher ecipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        ecipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec);
        byte[] dstBuff = ecipher.doFinal(srcBuff);
        String base64 = Base64.encodeToString(dstBuff, Base64.DEFAULT);
        return base64;
    }

    public String decrypt(String encrypted) throws NoSuchAlgorithmException,
            NoSuchPaddingException, InvalidKeyException,
            InvalidAlgorithmParameterException, IllegalBlockSizeException,
            BadPaddingException, UnsupportedEncodingException {

        SecretKeySpec skeySpec = new 
        SecretKeySpec(SecretKey.substring(0,32).getBytes(), "AES");
        IvParameterSpec ivSpec = new 
        IvParameterSpec(IV.substring(0,16).getBytes());
        Cipher ecipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        ecipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
        byte[] raw = Base64.decode(encrypted, Base64.DEFAULT);
        byte[] originalBytes = ecipher.doFinal(raw);
        String original = new String(originalBytes, "UTF8");
        return original;
    }
}