Programs & Examples On #Package private

Package private is the default access-control modifier in Java. If a member of a class is not annotated with `private`, `protected`, or `public`, then the member is `package private` by default. When a member is `package-private`, it can only be accessed by the parent class, and other classes in the same package.

Android Studio - Emulator - eglSurfaceAttrib not implemented

Fix: Unlock your device before running it.

Hi Guys: Think I may have a fix for this:

Sounds ridiculous but try unlocking your Virtual Device; i.e. use your mouse to swipe and open. Your app should then work!!

How can I make a horizontal ListView in Android?

After reading this post, I have implemented my own horizontal ListView. You can find it here: http://dev-smart.com/horizontal-listview/ Let me know if this helps.

Java: Multiple class declarations in one file

1.Is there a tidy name for this technique (analogous to inner, nested, anonymous)?

Multi-class single-file demo.

2.The JLS says the system may enforce the restriction that these secondary classes can't be referred to by code in other compilation units of the package, e.g., they can't be treated as package-private. Is that really something that changes between Java implementations?

I'm not aware of any which don't have that restriction - all the file based compilers won't allow you to refer to source code classes in files which are not named the same as the class name. ( if you compile a multi-class file, and put the classes on the class path, then any compiler will find them )

What is the difference between public, protected, package-private and private in Java?

Access modifiers are there to restrict access at several levels.

Public: It is basically as simple as you can access from any class whether that is in same package or not.

To access if you are in same package you can access directly, but if you are in another package then you can create an object of the class.

Default: It is accessible in the same package from any of the class of package.

To access you can create an object of the class. But you can not access this variable outside of the package.

Protected: you can access variables in same package as well as subclass in any other package. so basically it is default + Inherited behavior.

To access protected field defined in base class you can create object of child class.

Private: it can be access in same class.

In non-static methods you can access directly because of this reference (also in constructors)but to access in static methods you need to create object of the class.

Javascript find json value

var obj = [
  {"name": "Afghanistan", "code": "AF"}, 
  {"name": "Åland Islands", "code": "AX"}, 
  {"name": "Albania", "code": "AL"}, 
  {"name": "Algeria", "code": "DZ"}
];

// the code you're looking for
var needle = 'AL';

// iterate over each element in the array
for (var i = 0; i < obj.length; i++){
  // look for the entry with a matching `code` value
  if (obj[i].code == needle){
     // we found it
    // obj[i].name is the matched result
  }
}

How do you use the "WITH" clause in MySQL?

'Common Table Expression' feature is not available in MySQL, so you have to go to make a view or temporary table to solve, here I have used a temporary table.

The stored procedure mentioned here will solve your need. If I want to get all my team members and their associated members, this stored procedure will help:

----------------------------------
user_id   |   team_id
----------------------------------
admin     |   NULL
ramu      |   admin
suresh    |   admin
kumar     |   ramu
mahesh    |   ramu
randiv    |   suresh
-----------------------------------

Code:

DROP PROCEDURE `user_hier`//
CREATE DEFINER=`root`@`localhost` PROCEDURE `user_hier`(in team_id varchar(50))
BEGIN
declare count int;
declare tmp_team_id varchar(50);
CREATE TEMPORARY TABLE res_hier(user_id varchar(50),team_id varchar(50))engine=memory;
CREATE TEMPORARY TABLE tmp_hier(user_id varchar(50),team_id varchar(50))engine=memory;
set tmp_team_id = team_id;
SELECT COUNT(*) INTO count FROM user_table WHERE user_table.team_id=tmp_team_id;
WHILE count>0 DO
insert into res_hier select user_table.user_id,user_table.team_id from user_table where user_table.team_id=tmp_team_id;
insert into tmp_hier select user_table.user_id,user_table.team_id from user_table where user_table.team_id=tmp_team_id;
select user_id into tmp_team_id from tmp_hier limit 0,1;
select count(*) into count from tmp_hier;
delete from tmp_hier where user_id=tmp_team_id;
end while;
select * from res_hier;
drop temporary table if exists res_hier;
drop temporary table if exists tmp_hier;
end

This can be called using:

mysql>call user_hier ('admin')//

Getting parts of a URL (Regex)

I'm a few years late to the party, but I'm surprised no one has mentioned the Uniform Resource Identifier specification has a section on parsing URIs with a regular expression. The regular expression, written by Berners-Lee, et al., is:

^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
 12            3  4          5       6  7        8 9

The numbers in the second line above are only to assist readability; they indicate the reference points for each subexpression (i.e., each paired parenthesis). We refer to the value matched for subexpression as $. For example, matching the above expression to

http://www.ics.uci.edu/pub/ietf/uri/#Related

results in the following subexpression matches:

$1 = http:
$2 = http
$3 = //www.ics.uci.edu
$4 = www.ics.uci.edu
$5 = /pub/ietf/uri/
$6 = <undefined>
$7 = <undefined>
$8 = #Related
$9 = Related

For what it's worth, I found that I had to escape the forward slashes in JavaScript:

^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?

Linux Command History with date and time

HISTTIMEFORMAT="%d/%m/%y %H:%M "

For any commands typed prior to this, it will not help since they will just get a default time of when you turned history on, but it will log the time of any further commands after this.

If you want it to log history for permanent, you should put the following line in your ~/.bashrc

export HISTTIMEFORMAT="%d/%m/%y %H:%M "

How to do encryption using AES in Openssl

I am trying to write a sample program to do AES encryption using Openssl.

This answer is kind of popular, so I'm going to offer something more up-to-date since OpenSSL added some modes of operation that will probably help you.

First, don't use AES_encrypt and AES_decrypt. They are low level and harder to use. Additionally, it's a software-only routine, and it will never use hardware acceleration, like AES-NI. Finally, its subject to endianess issues on some obscure platforms.

Instead, use the EVP_* interfaces. The EVP_* functions use hardware acceleration, like AES-NI, if available. And it does not suffer endianess issues on obscure platforms.

Second, you can use a mode like CBC, but the ciphertext will lack integrity and authenticity assurances. So you usually want a mode like EAX, CCM, or GCM. (Or you manually have to apply a HMAC after the encryption under a separate key.)

Third, OpenSSL has a wiki page that will probably interest you: EVP Authenticated Encryption and Decryption. It uses GCM mode.

Finally, here's the program to encrypt using AES/GCM. The OpenSSL wiki example is based on it.

#include <openssl/evp.h>
#include <openssl/aes.h>
#include <openssl/err.h>
#include <string.h>   

int main(int arc, char *argv[])
{
    OpenSSL_add_all_algorithms();
    ERR_load_crypto_strings();     

    /* Set up the key and iv. Do I need to say to not hard code these in a real application? :-) */

    /* A 256 bit key */
    static const unsigned char key[] = "01234567890123456789012345678901";

    /* A 128 bit IV */
    static const unsigned char iv[] = "0123456789012345";

    /* Message to be encrypted */
    unsigned char plaintext[] = "The quick brown fox jumps over the lazy dog";

    /* Some additional data to be authenticated */
    static const unsigned char aad[] = "Some AAD data";

    /* Buffer for ciphertext. Ensure the buffer is long enough for the
     * ciphertext which may be longer than the plaintext, dependant on the
     * algorithm and mode
     */
    unsigned char ciphertext[128];

    /* Buffer for the decrypted text */
    unsigned char decryptedtext[128];

    /* Buffer for the tag */
    unsigned char tag[16];

    int decryptedtext_len = 0, ciphertext_len = 0;

    /* Encrypt the plaintext */
    ciphertext_len = encrypt(plaintext, strlen(plaintext), aad, strlen(aad), key, iv, ciphertext, tag);

    /* Do something useful with the ciphertext here */
    printf("Ciphertext is:\n");
    BIO_dump_fp(stdout, ciphertext, ciphertext_len);
    printf("Tag is:\n");
    BIO_dump_fp(stdout, tag, 14);

    /* Mess with stuff */
    /* ciphertext[0] ^= 1; */
    /* tag[0] ^= 1; */

    /* Decrypt the ciphertext */
    decryptedtext_len = decrypt(ciphertext, ciphertext_len, aad, strlen(aad), tag, key, iv, decryptedtext);

    if(decryptedtext_len < 0)
    {
        /* Verify error */
        printf("Decrypted text failed to verify\n");
    }
    else
    {
        /* Add a NULL terminator. We are expecting printable text */
        decryptedtext[decryptedtext_len] = '\0';

        /* Show the decrypted text */
        printf("Decrypted text is:\n");
        printf("%s\n", decryptedtext);
    }

    /* Remove error strings */
    ERR_free_strings();

    return 0;
}

void handleErrors(void)
{
    unsigned long errCode;

    printf("An error occurred\n");
    while(errCode = ERR_get_error())
    {
        char *err = ERR_error_string(errCode, NULL);
        printf("%s\n", err);
    }
    abort();
}

int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *aad,
            int aad_len, unsigned char *key, unsigned char *iv,
            unsigned char *ciphertext, unsigned char *tag)
{
    EVP_CIPHER_CTX *ctx = NULL;
    int len = 0, ciphertext_len = 0;

    /* Create and initialise the context */
    if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();

    /* Initialise the encryption operation. */
    if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL))
        handleErrors();

    /* Set IV length if default 12 bytes (96 bits) is not appropriate */
    if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 16, NULL))
        handleErrors();

    /* Initialise key and IV */
    if(1 != EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv)) handleErrors();

    /* Provide any AAD data. This can be called zero or more times as
     * required
     */
    if(aad && aad_len > 0)
    {
        if(1 != EVP_EncryptUpdate(ctx, NULL, &len, aad, aad_len))
            handleErrors();
    }

    /* Provide the message to be encrypted, and obtain the encrypted output.
     * EVP_EncryptUpdate can be called multiple times if necessary
     */
    if(plaintext)
    {
        if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
            handleErrors();

        ciphertext_len = len;
    }

    /* Finalise the encryption. Normally ciphertext bytes may be written at
     * this stage, but this does not occur in GCM mode
     */
    if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors();
    ciphertext_len += len;

    /* Get the tag */
    if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, tag))
        handleErrors();

    /* Clean up */
    EVP_CIPHER_CTX_free(ctx);

    return ciphertext_len;
}

int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *aad,
            int aad_len, unsigned char *tag, unsigned char *key, unsigned char *iv,
            unsigned char *plaintext)
{
    EVP_CIPHER_CTX *ctx = NULL;
    int len = 0, plaintext_len = 0, ret;

    /* Create and initialise the context */
    if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();

    /* Initialise the decryption operation. */
    if(!EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL))
        handleErrors();

    /* Set IV length. Not necessary if this is 12 bytes (96 bits) */
    if(!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 16, NULL))
        handleErrors();

    /* Initialise key and IV */
    if(!EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv)) handleErrors();

    /* Provide any AAD data. This can be called zero or more times as
     * required
     */
    if(aad && aad_len > 0)
    {
        if(!EVP_DecryptUpdate(ctx, NULL, &len, aad, aad_len))
            handleErrors();
    }

    /* Provide the message to be decrypted, and obtain the plaintext output.
     * EVP_DecryptUpdate can be called multiple times if necessary
     */
    if(ciphertext)
    {
        if(!EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
            handleErrors();

        plaintext_len = len;
    }

    /* Set expected tag value. Works in OpenSSL 1.0.1d and later */
    if(!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, tag))
        handleErrors();

    /* Finalise the decryption. A positive return value indicates success,
     * anything else is a failure - the plaintext is not trustworthy.
     */
    ret = EVP_DecryptFinal_ex(ctx, plaintext + len, &len);

    /* Clean up */
    EVP_CIPHER_CTX_free(ctx);

    if(ret > 0)
    {
        /* Success */
        plaintext_len += len;
        return plaintext_len;
    }
    else
    {
        /* Verify failed */
        return -1;
    }
}

What does the ^ (XOR) operator do?

A little more information on XOR operation.

  • XOR a number with itself odd number of times the result is number itself.
  • XOR a number even number of times with itself, the result is 0.
  • Also XOR with 0 is always the number itself.

How to printf "unsigned long" in C?

Out of all the combinations you tried, %ld and %lu are the only ones which are valid printf format specifiers at all. %lu (long unsigned decimal), %lx or %lX (long hex with lowercase or uppercase letters), and %lo (long octal) are the only valid format specifiers for a variable of type unsigned long (of course you can add field width, precision, etc modifiers between the % and the l).

Get loop counter/index using for…of syntax in JavaScript

For-in-loops iterate over properties of an Object. Don't use them for Arrays, even if they sometimes work.

Object properties then have no index, they are all equal and not required to be run through in a determined order. If you want to count properties, you will have to set up the extra counter (as you did in your first example).

loop over an Array:

var a = [];
for (var i=0; i<a.length; i++) {
    i // is the index
    a[i] // is the item
}

loop over an Object:

var o = {};
for (var prop in o) {
    prop // is the property name
    o[prop] // is the property value - the item
}

How to create own dynamic type or dynamic object in C#?

ExpandoObject is what are you looking for.

dynamic MyDynamic = new ExpandoObject(); // note, the type MUST be dynamic to use dynamic invoking.
MyDynamic.A = "A";
MyDynamic.B = "B";
MyDynamic.C = "C";
MyDynamic.TheAnswerToLifeTheUniverseAndEverything = 42;

Test for existence of nested JavaScript object key

Based on a previous comment, here is another version where the main object could not be defined either:

// Supposing that our property is at first.second.third.property:
var property = (((typeof first !== 'undefined' ? first : {}).second || {}).third || {}).property;

How to declare 2D array in bash

For simulating a 2-dimensional array, I first load the first n-elements (the elements of the first column)

local pano_array=()  

i=0

for line in $(grep  "filename" "$file")
do 
  url=$(extract_url_from_xml $line)
  pano_array[i]="$url"
  i=$((i+1))
done

To add the second column, I define the size of the first column and calculate the values in an offset variable

array_len="${#pano_array[@]}"

i=0

while [[ $i -lt $array_len ]]
do
  url="${pano_array[$i]}"
  offset=$(($array_len+i)) 
  found_file=$(get_file $url)
  pano_array[$offset]=$found_file

  i=$((i+1))
done

Doctrine2: Best way to handle many-to-many with extra columns in reference table

This really useful example. It lacks in the documentation doctrine 2.

Very thank you.

For the proxies functions can be done :

class AlbumTrack extends AlbumTrackAbstract {
   ... proxy method.
   function getTitle() {} 
}

class TrackAlbum extends AlbumTrackAbstract {
   ... proxy method.
   function getTitle() {}
}

class AlbumTrackAbstract {
   private $id;
   ....
}

and

/** @OneToMany(targetEntity="TrackAlbum", mappedBy="album") */
protected $tracklist;

/** @OneToMany(targetEntity="AlbumTrack", mappedBy="track") */
protected $albumsFeaturingThisTrack;

"Could not find Developer Disk Image"

To run the project to latest devices from the older versions of Xcode, follow the following steps :

Go To Finder -> Applications -> Right Click on latest Xcode version -> select show package content -> Developer -> Platforms -> iPhoneOS.platform -> DeviceSupport -> Copy the latest version folder and paste at the same location of your old Xcode i.e in the DeviceSupport folder of your old Xcode.

Then Restart Xcode.enter image description here

JFrame Maximize window

If you're using a JFrame, try this

JFrame frame = new JFrame();
//...
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);

How to create a md5 hash of a string in C?

It would appear that you should

  • Create a struct MD5context and pass it to MD5Init to get it into a proper starting condition
  • Call MD5Update with the context and your data
  • Call MD5Final to get the resulting hash

These three functions and the structure definition make a nice abstract interface to the hash algorithm. I'm not sure why you were shown the core transform function in that header as you probably shouldn't interact with it directly.

The author could have done a little more implementation hiding by making the structure an abstract type, but then you would have been forced to allocate the structure on the heap every time (as opposed to now where you can put it on the stack if you so desire).

The imported project "C:\Microsoft.CSharp.targets" was not found

Open your csproj file in notepad (or notepad++) Find the line:

<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

and change it to

<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />

How are zlib, gzip and zip related? What do they have in common and how are they different?

Short form:

.zip is an archive format using, usually, the Deflate compression method. The .gz gzip format is for single files, also using the Deflate compression method. Often gzip is used in combination with tar to make a compressed archive format, .tar.gz. The zlib library provides Deflate compression and decompression code for use by zip, gzip, png (which uses the zlib wrapper on deflate data), and many other applications.

Long form:

The ZIP format was developed by Phil Katz as an open format with an open specification, where his implementation, PKZIP, was shareware. It is an archive format that stores files and their directory structure, where each file is individually compressed. The file type is .zip. The files, as well as the directory structure, can optionally be encrypted.

The ZIP format supports several compression methods:

    0 - The file is stored (no compression)
    1 - The file is Shrunk
    2 - The file is Reduced with compression factor 1
    3 - The file is Reduced with compression factor 2
    4 - The file is Reduced with compression factor 3
    5 - The file is Reduced with compression factor 4
    6 - The file is Imploded
    7 - Reserved for Tokenizing compression algorithm
    8 - The file is Deflated
    9 - Enhanced Deflating using Deflate64(tm)
   10 - PKWARE Data Compression Library Imploding (old IBM TERSE)
   11 - Reserved by PKWARE
   12 - File is compressed using BZIP2 algorithm
   13 - Reserved by PKWARE
   14 - LZMA
   15 - Reserved by PKWARE
   16 - IBM z/OS CMPSC Compression
   17 - Reserved by PKWARE
   18 - File is compressed using IBM TERSE (new)
   19 - IBM LZ77 z Architecture 
   20 - deprecated (use method 93 for zstd)
   93 - Zstandard (zstd) Compression 
   94 - MP3 Compression 
   95 - XZ Compression 
   96 - JPEG variant
   97 - WavPack compressed data
   98 - PPMd version I, Rev 1
   99 - AE-x encryption marker (see APPENDIX E)

Methods 1 to 7 are historical and are not in use. Methods 9 through 98 are relatively recent additions and are in varying, small amounts of use. The only method in truly widespread use in the ZIP format is method 8, Deflate, and to some smaller extent method 0, which is no compression at all. Virtually every .zip file that you will come across in the wild will use exclusively methods 8 and 0, likely just method 8. (Method 8 also has a means to effectively store the data with no compression and relatively little expansion, and Method 0 cannot be streamed whereas Method 8 can be.)

The ISO/IEC 21320-1:2015 standard for file containers is a restricted zip format, such as used in Java archive files (.jar), Office Open XML files (Microsoft Office .docx, .xlsx, .pptx), Office Document Format files (.odt, .ods, .odp), and EPUB files (.epub). That standard limits the compression methods to 0 and 8, as well as other constraints such as no encryption or signatures.

Around 1990, the Info-ZIP group wrote portable, free, open-source implementations of zip and unzip utilities, supporting compression with the Deflate format, and decompression of that and the earlier formats. This greatly expanded the use of the .zip format.

In the early '90s, the gzip format was developed as a replacement for the Unix compress utility, derived from the Deflate code in the Info-ZIP utilities. Unix compress was designed to compress a single file or stream, appending a .Z to the file name. compress uses the LZW compression algorithm, which at the time was under patent and its free use was in dispute by the patent holders. Though some specific implementations of Deflate were patented by Phil Katz, the format was not, and so it was possible to write a Deflate implementation that did not infringe on any patents. That implementation has not been so challenged in the last 20+ years. The Unix gzip utility was intended as a drop-in replacement for compress, and in fact is able to decompress compress-compressed data (assuming that you were able to parse that sentence). gzip appends a .gz to the file name. gzip uses the Deflate compressed data format, which compresses quite a bit better than Unix compress, has very fast decompression, and adds a CRC-32 as an integrity check for the data. The header format also permits the storage of more information than the compress format allowed, such as the original file name and the file modification time.

Though compress only compresses a single file, it was common to use the tar utility to create an archive of files, their attributes, and their directory structure into a single .tar file, and to then compress it with compress to make a .tar.Z file. In fact, the tar utility had and still has an option to do the compression at the same time, instead of having to pipe the output of tar to compress. This all carried forward to the gzip format, and tar has an option to compress directly to the .tar.gz format. The tar.gz format compresses better than the .zip approach, since the compression of a .tar can take advantage of redundancy across files, especially many small files. .tar.gz is the most common archive format in use on Unix due to its very high portability, but there are more effective compression methods in use as well, so you will often see .tar.bz2 and .tar.xz archives.

Unlike .tar, .zip has a central directory at the end, which provides a list of the contents. That and the separate compression provides random access to the individual entries in a .zip file. A .tar file would have to be decompressed and scanned from start to end in order to build a directory, which is how a .tar file is listed.

Shortly after the introduction of gzip, around the mid-1990s, the same patent dispute called into question the free use of the .gif image format, very widely used on bulletin boards and the World Wide Web (a new thing at the time). So a small group created the PNG losslessly compressed image format, with file type .png, to replace .gif. That format also uses the Deflate format for compression, which is applied after filters on the image data expose more of the redundancy. In order to promote widespread usage of the PNG format, two free code libraries were created. libpng and zlib. libpng handled all of the features of the PNG format, and zlib provided the compression and decompression code for use by libpng, as well as for other applications. zlib was adapted from the gzip code.

All of the mentioned patents have since expired.

The zlib library supports Deflate compression and decompression, and three kinds of wrapping around the deflate streams. Those are: no wrapping at all ("raw" deflate), zlib wrapping, which is used in the PNG format data blocks, and gzip wrapping, to provide gzip routines for the programmer. The main difference between zlib and gzip wrapping is that the zlib wrapping is more compact, six bytes vs. a minimum of 18 bytes for gzip, and the integrity check, Adler-32, runs faster than the CRC-32 that gzip uses. Raw deflate is used by programs that read and write the .zip format, which is another format that wraps around deflate compressed data.

zlib is now in wide use for data transmission and storage. For example, most HTTP transactions by servers and browsers compress and decompress the data using zlib, specifically HTTP header Content-Encoding: deflate means deflate compression method wrapped inside the zlib data format.

Different implementations of deflate can result in different compressed output for the same input data, as evidenced by the existence of selectable compression levels that allow trading off compression effectiveness for CPU time. zlib and PKZIP are not the only implementations of deflate compression and decompression. Both the 7-Zip archiving utility and Google's zopfli library have the ability to use much more CPU time than zlib in order to squeeze out the last few bits possible when using the deflate format, reducing compressed sizes by a few percent as compared to zlib's highest compression level. The pigz utility, a parallel implementation of gzip, includes the option to use zlib (compression levels 1-9) or zopfli (compression level 11), and somewhat mitigates the time impact of using zopfli by splitting the compression of large files over multiple processors and cores.

REST API Best practices: Where to put parameters?

It's a very interesting question.

You can use both of them, there's not any strict rule about this subject, but using URI path variables has some advantages:

  • Cache: Most of the web cache services on the internet don't cache GET request when they contains query parameters. They do that because there are a lot of RPC systems using GET requests to change data in the server (fail!! Get must be a safe method)

But if you use path variables, all of this services can cache your GET requests.

  • Hierarchy: The path variables can represent hierarchy: /City/Street/Place

It gives the user more information about the structure of the data.

But if your data doesn't have any hierarchy relation you can still use Path variables, using comma or semi-colon:

/City/longitude,latitude

As a rule, use comma when the ordering of the parameters matter, use semi-colon when the ordering doesn't matter:

/IconGenerator/red;blue;green

Apart of those reasons, there are some cases when it's very common to use query string variables:

  • When you need the browser to automatically put HTML form variables into the URI
  • When you are dealing with algorithm. For example the google engine use query strings:

http:// www.google.com/search?q=rest

To sum up, there's not any strong reason to use one of this methods but whenever you can, use URI variables.

Looping through a Scripting.Dictionary using index/item number

Using d.Keys()(i) method is a very bad idea, because on each call it will re-create a new array (you will have significant speed reduction).

Here is an analogue of Scripting.Dictionary called "Hash Table" class from @TheTrick, that support such enumerator: http://www.cyberforum.ru/blogs/354370/blog2905.html

Dim oDict As clsTrickHashTable

Sub aaa()
    Set oDict = New clsTrickHashTable

    oDict.Add "a", "aaa"
    oDict.Add "b", "bbb"

    For i = 0 To oDict.Count - 1
        Debug.Print oDict.Keys(i) & " - " & oDict.Items(i)
    Next
End Sub

How to get Device Information in Android

Try this:

// Code For IMEI AND IMSI NUMBER

String serviceName = Context.TELEPHONY_SERVICE;
TelephonyManager m_telephonyManager = (TelephonyManager) getSystemService(serviceName);
String IMEI,IMSI;
IMEI = m_telephonyManager.getDeviceId();
IMSI = m_telephonyManager.getSubscriberId();

dll missing in JDBC

Set java.library.path to a directory containing this DLL which Java uses to find native libraries. Specify -D switch on the command line

java -Djava.library.path=C:\Java\native\libs YourProgram

C:\Java\native\libs should contain sqljdbc_auth.dll

Look at this SO post if you are using Eclipse or at this blog if you want to set programatically.

How to save an image to localStorage and display it on the next page?

To whoever also needs this problem solved:

Firstly, I grab my image with getElementByID, and save the image as a Base64. Then I save the Base64 string as my localStorage value.

bannerImage = document.getElementById('bannerImg');
imgData = getBase64Image(bannerImage);
localStorage.setItem("imgData", imgData);

Here is the function that converts the image to a Base64 string:

function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    var dataURL = canvas.toDataURL("image/png");

    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

Then, on my next page I created an image with a blank src like so:

<img src="" id="tableBanner" />

And straight when the page loads, I use these next three lines to get the Base64 string from localStorage, and apply it to the image with the blank src I created:

var dataImage = localStorage.getItem('imgData');
bannerImg = document.getElementById('tableBanner');
bannerImg.src = "data:image/png;base64," + dataImage;

Tested it in quite a few different browsers and versions, and it seems to work quite well.

android:layout_height 50% of the screen size

You can use android:weightSum="2" on the parent layout combined with android:layout_height="1" on the child layout.

           <LinearLayout
                android:layout_height="match_parent"
                android:layout_width="wrap_content"
                android:weightSum="2"
                >

                <ImageView
                    android:layout_height="1"
                    android:layout_width="wrap_content" />

            </LinearLayout>

What are callee and caller saved registers?

Caller-saved registers (AKA volatile registers, or call-clobbered) are used to hold temporary quantities that need not be preserved across calls.

For that reason, it is the caller's responsibility to push these registers onto the stack or copy them somewhere else if it wants to restore this value after a procedure call.

It's normal to let a call destroy temporary values in these registers, though.

Callee-saved registers (AKA non-volatile registers, or call-preserved) are used to hold long-lived values that should be preserved across calls.

When the caller makes a procedure call, it can expect that those registers will hold the same value after the callee returns, making it the responsibility of the callee to save them and restore them before returning to the caller. Or to not touch them.

How to change XML Attribute

Here's the beginnings of a parser class to get you started. This ended up being my solution to a similar problem:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace XML
{
    public class Parser
    {

        private string _FilePath = string.Empty;

        private XDocument _XML_Doc = null;


        public Parser(string filePath)
        {
            _FilePath = filePath;
            _XML_Doc = XDocument.Load(_FilePath);
        }


        /// <summary>
        /// Replaces values of all attributes of a given name (attributeName) with the specified new value (newValue) in all elements.
        /// </summary>
        /// <param name="attributeName"></param>
        /// <param name="newValue"></param>
        public void ReplaceAtrribute(string attributeName, string newValue)
        {
            ReplaceAtrribute(string.Empty, attributeName, new List<string> { }, newValue);
        }

        /// <summary>
        /// Replaces values of all attributes of a given name (attributeName) with the specified new value (newValue) in elements with a given name (elementName).
        /// </summary>
        /// <param name="elementName"></param>
        /// <param name="attributeName"></param>
        /// <param name="newValue"></param>
        public void ReplaceAtrribute(string elementName, string attributeName, string newValue)
        {
            ReplaceAtrribute(elementName, attributeName, new List<string> { }, newValue);
        }


        /// <summary>
        /// Replaces values of all attributes of a given name (attributeName) and value (oldValue)  
        /// with the specified new value (newValue) in elements with a given name (elementName).
        /// </summary>
        /// <param name="elementName"></param>
        /// <param name="attributeName"></param>
        /// <param name="oldValue"></param>
        /// <param name="newValue"></param>
        public void ReplaceAtrribute(string elementName, string attributeName, string oldValue, string newValue)
        {
            ReplaceAtrribute(elementName, attributeName, new List<string> { oldValue }, newValue);              
        }


        /// <summary>
        /// Replaces values of all attributes of a given name (attributeName), which has one of a list of values (oldValues), 
        /// with the specified new value (newValue) in elements with a given name (elementName).
        /// If oldValues is empty then oldValues will be ignored.
        /// </summary>
        /// <param name="elementName"></param>
        /// <param name="attributeName"></param>
        /// <param name="oldValues"></param>
        /// <param name="newValue"></param>
        public void ReplaceAtrribute(string elementName, string attributeName, List<string> oldValues, string newValue)
        {
            List<XElement> elements = _XML_Doc.Elements().Descendants().ToList();

            foreach (XElement element in elements)
            {
                if (elementName == string.Empty | element.Name.LocalName.ToString() == elementName)
                {
                    if (element.Attribute(attributeName) != null)
                    {

                        if (oldValues.Count == 0 || oldValues.Contains(element.Attribute(attributeName).Value))
                        { element.Attribute(attributeName).Value = newValue; }
                    }
                }
            }

        }

        public void SaveChangesToFile()
        {
            _XML_Doc.Save(_FilePath);
        }

    }
}

Loop through all nested dictionary values?

Iterative solution as an alternative:

def traverse_nested_dict(d):
    iters = [d.iteritems()]

    while iters:
        it = iters.pop()
        try:
            k, v = it.next()
        except StopIteration:
            continue

        iters.append(it)

        if isinstance(v, dict):
            iters.append(v.iteritems())
        else:
            yield k, v


d = {"a": 1, "b": 2, "c": {"d": 3, "e": {"f": 4}}}
for k, v in traverse_nested_dict(d):
    print k, v

@UniqueConstraint annotation in Java

@UniqueConstraint this annotation is used for annotating single or multiple unique keys at the table level separated by comma, which is why you get an error. it will only work if you let JPA create your tables

Example

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Builder(builderClassName = "Builder", toBuilder = true)
@Entity
@Table(name = "users", uniqueConstraints = @UniqueConstraint(columnNames = {"person_id", "company_id"}))
public class AppUser extends BaseEntity {

    @Column(name = "person_id")
    private Long personId;

    @ManyToOne
    @JoinColumn(name = "company_id")
    private Company company;
}

https://docs.jboss.org/hibernate/jpa/2.1/api/javax/persistence/UniqueConstraint.html

On the other hand To ensure a field value is unique you can write

@Column(unique=true)
String username;

Page redirect with successful Ajax request

I think you can do that with:

window.location = "your_url";

jQuery textbox change event

The HTML4 spec for the <input> element specifies the following script events are available:

onfocus, onblur, onselect, onchange, onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup

here's an example that bind's to all these events and shows what's going on http://jsfiddle.net/pxfunc/zJ7Lf/

I think you can filter out which events are truly relevent to your situation and detect what the text value was before and after the event to determine a change

Adding onClick event dynamically using jQuery

You can use the click event and call your function or move your logic into the handler:

$("#bfCaptchaEntry").click(function(){ myFunction(); });

You can use the click event and set your function as the handler:

$("#bfCaptchaEntry").click(myFunction);

.click()

Bind an event handler to the "click" JavaScript event, or trigger that event on an element.

http://api.jquery.com/click/


You can use the on event bound to "click" and call your function or move your logic into the handler:

$("#bfCaptchaEntry").on("click", function(){ myFunction(); });

You can use the on event bound to "click" and set your function as the handler:

$("#bfCaptchaEntry").on("click", myFunction);

.on()

Attach an event handler function for one or more events to the selected elements.

http://api.jquery.com/on/

MySQL compare now() (only date, not time) with a datetime field

Compare date only instead of date + time (NOW) with:

CURDATE()

How to run the Python program forever?

I have a small script interruptableloop.py that runs the code at an interval (default 1sec), it pumps out a message to the screen while it's running, and traps an interrupt signal that you can send with CTL-C:

#!/usr/bin/python3
from interruptableLoop import InterruptableLoop

loop=InterruptableLoop(intervalSecs=1) # redundant argument
while loop.ShouldContinue():
   # some python code that I want 
   # to keep on running
   pass

When you run the script and then interrupt it you see this output, (the periods pump out on every pass of the loop):

[py36]$ ./interruptexample.py
CTL-C to stop   (or $kill -s SIGINT pid)
......^C
Exiting at  2018-07-28 14:58:40.359331

interruptableLoop.py:

"""
    Use to create a permanent loop that can be stopped ...

    ... from same terminal where process was started and is running in foreground: 
        CTL-C

    ... from same user account but through a different terminal 
        $ kill -2 <pid> 
        or $ kill -s SIGINT <pid>

"""
import signal
import time
from datetime import datetime as dtt
__all__=["InterruptableLoop",]
class InterruptableLoop:
    def __init__(self,intervalSecs=1,printStatus=True):
        self.intervalSecs=intervalSecs
        self.shouldContinue=True
        self.printStatus=printStatus
        self.interrupted=False
        if self.printStatus:
            print ("CTL-C to stop\t(or $kill -s SIGINT pid)")
        signal.signal(signal.SIGINT, self._StopRunning)
        signal.signal(signal.SIGQUIT, self._Abort)
        signal.signal(signal.SIGTERM, self._Abort)

    def _StopRunning(self, signal, frame):
        self.shouldContinue = False

    def _Abort(self, signal, frame):
        raise 

    def ShouldContinue(self):
        time.sleep(self.intervalSecs)
        if self.shouldContinue and self.printStatus: 
            print( ".",end="",flush=True)
        elif not self.shouldContinue and self.printStatus:
            print ("Exiting at ",dtt.now())
        return self.shouldContinue

The split() method in Java does not work on a dot (.)

Try:

String words[]=temp.split("\\.");

The method is:

String[] split(String regex) 

"." is a reserved char in regex

How to retrieve inserted id after inserting row in SQLite using Python?

You could use cursor.lastrowid (see "Optional DB API Extensions"):

connection=sqlite3.connect(':memory:')
cursor=connection.cursor()
cursor.execute('''CREATE TABLE foo (id integer primary key autoincrement ,
                                    username varchar(50),
                                    password varchar(50))''')
cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',
               ('test','test'))
print(cursor.lastrowid)
# 1

If two people are inserting at the same time, as long as they are using different cursors, cursor.lastrowid will return the id for the last row that cursor inserted:

cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',
               ('blah','blah'))

cursor2=connection.cursor()
cursor2.execute('INSERT INTO foo (username,password) VALUES (?,?)',
               ('blah','blah'))

print(cursor2.lastrowid)        
# 3
print(cursor.lastrowid)
# 2

cursor.execute('INSERT INTO foo (id,username,password) VALUES (?,?,?)',
               (100,'blah','blah'))
print(cursor.lastrowid)
# 100

Note that lastrowid returns None when you insert more than one row at a time with executemany:

cursor.executemany('INSERT INTO foo (username,password) VALUES (?,?)',
               (('baz','bar'),('bing','bop')))
print(cursor.lastrowid)
# None

How to select multiple rows filled with constants?

Here is how I populate static data in Oracle 10+ using a neat XML trick.

create table prop
(ID NUMBER,
 NAME varchar2(10),
 VAL varchar2(10),
 CREATED timestamp,
 CONSTRAINT PK_PROP PRIMARY KEY(ID)
);

merge into Prop p
using (
select 
  extractValue(value(r), '/R/ID') ID,
  extractValue(value(r), '/R/NAME') NAME,
  extractValue(value(r), '/R/VAL') VAL
from
(select xmltype('
<ROWSET>
   <R><ID>1</ID><NAME>key1</NAME><VAL>value1</VAL></R>
   <R><ID>2</ID><NAME>key2</NAME><VAL>value2</VAL></R>
   <R><ID>3</ID><NAME>key3</NAME><VAL>value3</VAL></R>
</ROWSET>
') xml from dual) input,
 table(xmlsequence(input.xml.extract('/ROWSET/R'))) r
) p_new
on (p.ID = p_new.ID)
when not matched then
insert
(ID, NAME, VAL, CREATED)
values
( p_new.ID, p_new.NAME, p_new.VAL, SYSTIMESTAMP );

The merge only inserts the rows that are missing in the original table, which is convenient if you want to rerun your insert script.

How are echo and print different in PHP?

As the PHP.net manual suggests, take a read of this discussion.

One major difference is that echo can take multiple parameters to output. E.g.:

echo 'foo', 'bar';   // Concatenates the 2 strings
print('foo', 'bar'); // Fatal error

If you're looking to evaluate the outcome of an output statement (as below) use print. If not, use echo.

$res = print('test');
var_dump($res); //bool(true)

Random string generation with upper case letters and digits

A simpler, faster but slightly less random way is to use random.sample instead of choosing each letter separately, If n-repetitions are allowed, enlarge your random basis by n times e.g.

import random
import string

char_set = string.ascii_uppercase + string.digits
print ''.join(random.sample(char_set*6, 6))

Note: random.sample prevents character reuse, multiplying the size of the character set makes multiple repetitions possible, but they are still less likely then they are in a pure random choice. If we go for a string of length 6, and we pick 'X' as the first character, in the choice example, the odds of getting 'X' for the second character are the same as the odds of getting 'X' as the first character. In the random.sample implementation, the odds of getting 'X' as any subsequent character are only 6/7 the chance of getting it as the first character

Local and global temporary tables in SQL Server

1.) A local temporary table exists only for the duration of a connection or, if defined inside a compound statement, for the duration of the compound statement.

Local temp tables are only available to the SQL Server session or connection (means single user) that created the tables. These are automatically deleted when the session that created the tables has been closed. Local temporary table name is stared with single hash ("#") sign.

CREATE TABLE #LocalTemp
(
 UserID int,
 Name varchar(50), 
 Address varchar(150)
)
GO
insert into #LocalTemp values ( 1, 'Name','Address');
GO
Select * from #LocalTemp

The scope of Local temp table exist to the current session of current user means to the current query window. If you will close the current query window or open a new query window and will try to find above created temp table, it will give you the error.


2.) A global temporary table remains in the database permanently, but the rows exist only within a given connection. When connection is closed, the data in the global temporary table disappears. However, the table definition remains with the database for access when database is opened next time.

Global temp tables are available to all SQL Server sessions or connections (means all the user). These can be created by any SQL Server connection user and these are automatically deleted when all the SQL Server connections have been closed. Global temporary table name is stared with double hash ("##") sign.

CREATE TABLE ##GlobalTemp
(
 UserID int,
 Name varchar(50), 
 Address varchar(150)
)
GO
insert into ##GlobalTemp values ( 1, 'Name','Address');
GO
Select * from ##GlobalTemp

Global temporary tables are visible to all SQL Server connections while Local temporary tables are visible to only current SQL Server connection.

How to stop a thread created by implementing runnable interface?

Stopping the thread in midway using Thread.stop() is not a good practice. More appropriate way is to make the thread return programmatically. Let the Runnable object use a shared variable in the run() method. Whenever you want the thread to stop, use that variable as a flag.

EDIT: Sample code

class MyThread implements Runnable{
    
    private Boolean stop = false;
    
    public void run(){
        
        while(!stop){
            
            //some business logic
        }
    }
    public Boolean getStop() {
        return stop;
    }

    public void setStop(Boolean stop) {
        this.stop = stop;
    }       
}

public class TestStop {
    
    public static void main(String[] args){
        
        MyThread myThread = new MyThread();
        Thread th = new Thread(myThread);
        th.start();
        
        //Some logic goes there to decide whether to 
        //stop the thread or not. 
        
        //This will compell the thread to stop
        myThread.setStop(true);
    }
}

How to change active class while click to another link in bootstrap use jquery?

You can use cookies for save postback data from one page to another page.After spending a lot time finally i was able to make this happen. I am suggesting my answer to you(this is fully working since I also needed this).

first give your li tag to valid id name like

_x000D_
_x000D_
<ul class="nav nav-list">_x000D_
    <li id="tab1" class="active"><a href="/">Link 1</a></li>_x000D_
    <li id="tab2"><a href="/link2">Link 2</a></li>_x000D_
    <li id="tab3"><a href="/link3">Link 3</a></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

After that copy and paste this script. since I have written some javascript for reading, deleting and creating cookies.

_x000D_
_x000D_
 $('.nav li a').click(function (e) {_x000D_
  _x000D_
        var $parent = $(this).parent();_x000D_
        document.cookie = eraseCookie("tab");_x000D_
        document.cookie = createCookie("tab", $parent.attr('id'),0);_x000D_
 });_x000D_
_x000D_
    $().ready(function () {_x000D_
        var $activeTab = readCookie("tab");_x000D_
        if (!$activeTab =="") {_x000D_
        $('#tab1').removeClass('ActiveTab');_x000D_
          }_x000D_
       // alert($activeTab.toString());_x000D_
       _x000D_
        $('#'+$activeTab).addClass('active');_x000D_
    });_x000D_
_x000D_
function createCookie(name, value, days) {_x000D_
    if (days) {_x000D_
        var date = new Date();_x000D_
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));_x000D_
        var expires = "; expires=" + date.toGMTString();_x000D_
    }_x000D_
    else var expires = "";_x000D_
_x000D_
    document.cookie = name + "=" + value + expires + "; path=/";_x000D_
}_x000D_
_x000D_
function readCookie(name) {_x000D_
    var nameEQ = name + "=";_x000D_
    var ca = document.cookie.split(';');_x000D_
    for (var i = 0; i < ca.length; i++) {_x000D_
        var c = ca[i];_x000D_
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);_x000D_
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);_x000D_
    }_x000D_
    return null;_x000D_
}_x000D_
_x000D_
function eraseCookie(name) {_x000D_
    createCookie(name, "", -1);_x000D_
}
_x000D_
_x000D_
_x000D_

Note: Make sure you have implmeted according to your requirement. I have written this script according to my implementation and its working fine for me.

Doing HTTP requests FROM Laravel to an external API

We can use package Guzzle in Laravel, it is a PHP HTTP client to send HTTP requests.

You can install Guzzle through composer

composer require guzzlehttp/guzzle:~6.0

Or you can specify Guzzle as a dependency in your project's existing composer.json

{
   "require": {
      "guzzlehttp/guzzle": "~6.0"
   }
}

Example code in laravel 5 using Guzzle as shown below,

use GuzzleHttp\Client;
class yourController extends Controller {

    public function saveApiData()
    {
        $client = new Client();
        $res = $client->request('POST', 'https://url_to_the_api', [
            'form_params' => [
                'client_id' => 'test_id',
                'secret' => 'test_secret',
            ]
        ]);
        echo $res->getStatusCode();
        // 200
        echo $res->getHeader('content-type');
        // 'application/json; charset=utf8'
        echo $res->getBody();
        // {"type":"User"...'
}

How to remove multiple deleted files in Git repository

You can use

git commit -m "remove files" -a
git push

After you had delete files manually.

ORA-29283: invalid file operation ORA-06512: at "SYS.UTL_FILE", line 536

I had been facing this problem for two days and I found that the directory you create in Oracle also needs to created first on your physical disk.

I didn't find this point mentioned anywhere i tried to look up the solution to this.

Example

If you created a directory, let's say, 'DB_DIR'.

CREATE OR REPLACE DIRECTORY DB_DIR AS 'E:\DB_WORKS';

Then you need to ensure that DB_WORKS exists in your E:\ drive and also file system level Read/Write permissions are available to the Oracle process.

My understanding of UTL_FILE from my experiences is given below for this kind of operation.

UTL_FILE is an object under SYS user. GRANT EXECUTE ON SYS.UTL_FILE TO PUBLIC; needs to given while logged in as SYS. Otherwise, it will give declaration error in procedure. Anyone can create a directory as shown:- CREATE OR REPLACE DIRECTORY DB_DIR AS 'E:\DBWORKS'; But CREATE DIRECTORY permission should be in place. This can be granted as shown:- GRANT CREATE ALL DIRECTORY TO user; while logged in as SYS user. However, if this needs to be used by another user, grants need to be given to that user otherwise it will throw error. GRANT READ, WRITE, EXECUTE ON DB_DIR TO user; while loggedin as the user who created the directory. Then, compile your package. Before executing the procedure, ensure that the Directory exists physically on your Disk. Otherwise it will throw 'Invalid File Operation' error. (V. IMPORTANT) Ensure that Filesystem level Read/Write permissions are in place for the Oracle process. This is separate from the DB level permissions granted.(V. IMPORTANT) Execute procedure. File should get populated with the result set of your query.

String or binary data would be truncated. The statement has been terminated

Specify a size for the item and warehouse like in the [dbo].[testing1] FUNCTION

@trackingItems1 TABLE (
item       nvarchar(25)  NULL, -- 25 OR equal size of your item column
warehouse   nvarchar(25) NULL, -- same as above
price int   NULL

) 

Since in MSSQL only saying only nvarchar is equal to nvarchar(1) hence the values of the column from the stock table are truncated

C# Debug - cannot start debugging because the debug target is missing

For those with this kind of problem - another solution: Pay attention also to Warnings when you build solution. For example, I had referenced a dll built with higher version of .NET (4.5.2) than my main project (4.5) After I referenced a dll built with 4.0 build process was successful.

Iif equivalent in C#

booleanExpression ? trueValue : falseValue;

Example:

string itemText = count > 1 ? "items" : "item";

http://zamirsblog.blogspot.com/2011/12/c-vb-equivalent-of-iif.html

Convert spark DataFrame column to python list

See, why this way that you are doing is not working. First, you are trying to get integer from a Row Type, the output of your collect is like this:

>>> mvv_list = mvv_count_df.select('mvv').collect()
>>> mvv_list[0]
Out: Row(mvv=1)

If you take something like this:

>>> firstvalue = mvv_list[0].mvv
Out: 1

You will get the mvv value. If you want all the information of the array you can take something like this:

>>> mvv_array = [int(row.mvv) for row in mvv_list.collect()]
>>> mvv_array
Out: [1,2,3,4]

But if you try the same for the other column, you get:

>>> mvv_count = [int(row.count) for row in mvv_list.collect()]
Out: TypeError: int() argument must be a string or a number, not 'builtin_function_or_method'

This happens because count is a built-in method. And the column has the same name as count. A workaround to do this is change the column name of count to _count:

>>> mvv_list = mvv_list.selectExpr("mvv as mvv", "count as _count")
>>> mvv_count = [int(row._count) for row in mvv_list.collect()]

But this workaround is not needed, as you can access the column using the dictionary syntax:

>>> mvv_array = [int(row['mvv']) for row in mvv_list.collect()]
>>> mvv_count = [int(row['count']) for row in mvv_list.collect()]

And it will finally work!

How to iterate through range of Dates in Java?

Here is Java 8 code. I think this code will solve your problem.Happy Coding

    LocalDate start = LocalDate.now();
    LocalDate end = LocalDate.of(2016, 9, 1);//JAVA 9 release date
    Long duration = start.until(end, ChronoUnit.DAYS);
    System.out.println(duration);
     // Do Any stuff Here there after
    IntStream.iterate(0, i -> i + 1)
             .limit(duration)
             .forEach((i) -> {});
     //old way of iteration
    for (int i = 0; i < duration; i++)
     System.out.print("" + i);// Do Any stuff Here

Defining TypeScript callback type

If you want a generic function you can use the following. Although it doesn't seem to be documented anywhere.

class CallbackTest {
  myCallback: Function;
}   

Redirecting to authentication dialog - "An error occurred. Please try again later"

When working with Dialogues, Facebook provide a 'show_error' attribute that defaults to no but can be set to true in a Development environment and is really helpful for debugging purposes.

show_error - If this is set to true, the error code and error description will be displayed in the event of an error.

Instructions of it's use can be found in the Facebook Docs.

I'd been debugging "An Error occurred. Please try later." dialogue before i found this attribute in the docs. Once i started using it, i could see the following message too:

API Error Code: 191

API Error Description: The specified URL is not owned by the application

Error Message: redirect_uri is not owned by the application.

How to copy files from host to Docker container?

The solution is given below,

From the Docker shell,

root@123abc:/root#  <-- get the container ID

From the host

cp thefile.txt /var/lib/docker/devicemapper/mnt/123abc<bunch-o-hex>/rootfs/root

The file shall be directly copied to the location where the container sits on the filesystem.

Find object in list that has attribute equal to some value (that meets any condition)

You could also implement rich comparison via __eq__ method for your Test class and use in operator. Not sure if this is the best stand-alone way, but in case if you need to compare Test instances based on value somewhere else, this could be useful.

class Test:
    def __init__(self, value):
        self.value = value

    def __eq__(self, other):
        """To implement 'in' operator"""
        # Comparing with int (assuming "value" is int)
        if isinstance(other, int):
            return self.value == other
        # Comparing with another Test object
        elif isinstance(other, Test):
            return self.value == other.value

import random

value = 5

test_list = [Test(random.randint(0,100)) for x in range(1000)]

if value in test_list:
    print "i found it"

Value of type 'T' cannot be converted to

Both lines have the same problem

T newT1 = "some text";
T newT2 = (string)t;

The compiler doesn't know that T is a string and so has no way of knowing how to assign that. But since you checked you can just force it with

T newT1 = "some text" as T;
T newT2 = t; 

you don't need to cast the t since it's already a string, also need to add the constraint

where T : class

Is it possible to do a sparse checkout without checking out the whole repository first?

Steps to sparse checkout only specific folder:

1) git clone --no-checkout  <project clone url>  
2) cd <project folder>
3) git config core.sparsecheckout true   [You must do this]
4) echo "<path you want to sparce>/*" > .git/info/sparse-checkout
    [You must enter /* at the end of the path such that it will take all contents of that folder]
5) git checkout <branch name> [Ex: master]

How to define multiple CSS attributes in jQuery?

Using a plain object, you can pair up strings that represent property names with their corresponding values. Changing the background color, and making text bolder, for instance would look like this:

$("#message").css({
    "background-color": "#0F0", 
    "font-weight"     : "bolder"
});

Alternatively, you can use the JavaScript property names too:

$("#message").css({
    backgroundColor: "rgb(128, 115, 94)",
    fontWeight     : "700"
});

More information can be found in jQuery's documentation.

Query to convert from datetime to date mysql

Either Cybernate or OMG Ponies solution will work. The fundamental problem is that the DATE_FORMAT() function returns a string, not a date. When you wrote

(Select Date_Format(orders.date_purchased,'%m/%d/%Y')) As Date 

I think you were essentially asking MySQL to try to format the values in date_purchased according to that format string, and instead of calling that column date_purchased, call it "Date". But that column would no longer contain a date, it would contain a string. (Because Date_Format() returns a string, not a date.)

I don't think that's what you wanted to do, but that's what you were doing.

Don't confuse how a value looks with what the value is.

Passing a URL with brackets to curl

I was getting this error though there were no (obvious) brackets in my URL, and in my situation the --globoff command will not solve the issue.

For example (doing this on on mac in iTerm2):

for endpoint in $(grep some_string output.txt); do curl "http://1.2.3.4/api/v1/${endpoint}" ; done

I have grep aliased to "grep --color=always". As a result, the above command will result in this error, with some_string highlighted in whatever colour you have grep set to:

curl: (3) bad range in URL position 31:
http://1.2.3.4/api/v1/lalalasome_stringlalala

The terminal was transparently translating the [colour\codes]some_string[colour\codes] into the expected no-special-characters URL when viewed in terminal, but behind the scenes the colour codes were being sent in the URL passed to curl, resulting in brackets in your URL.

Solution is to not use match highlighting.

Cut Java String at a number of character

String strOut = str.substring(0, 8) + "...";

Git: How to find a deleted file in the project commit history?

If you prefer to see the size of all deleted file

as well as the associated SHA

git log --all --stat --diff-filter=D --oneline

add a -p to see the contents too

git log --all --stat --diff-filter=D -p

To narrow down to any file simply pipe to grep and search for file name

git log --all --stat --diff-filter=D --oneline | grep someFileName

You might also like this one if you know where the file is

git log --all --full-history -- someFileName

How to convert string to datetime format in pandas python?

Use to_datetime, there is no need for a format string the parser is man/woman enough to handle it:

In [51]:
pd.to_datetime(df['I_DATE'])

Out[51]:
0   2012-03-28 14:15:00
1   2012-03-28 14:17:28
2   2012-03-28 14:50:50
Name: I_DATE, dtype: datetime64[ns]

To access the date/day/time component use the dt accessor:

In [54]:
df['I_DATE'].dt.date

Out[54]:
0    2012-03-28
1    2012-03-28
2    2012-03-28
dtype: object

In [56]:    
df['I_DATE'].dt.time

Out[56]:
0    14:15:00
1    14:17:28
2    14:50:50
dtype: object

You can use strings to filter as an example:

In [59]:
df = pd.DataFrame({'date':pd.date_range(start = dt.datetime(2015,1,1), end = dt.datetime.now())})
df[(df['date'] > '2015-02-04') & (df['date'] < '2015-02-10')]

Out[59]:
         date
35 2015-02-05
36 2015-02-06
37 2015-02-07
38 2015-02-08
39 2015-02-09

How to Install gcc 5.3 with yum on CentOS 7.2?

You can use the centos-sclo-rh-testing repo to install GCC v7 without having to compile it forever, also enable V7 by default and let you switch between different versions if required.

sudo yum install -y yum-utils centos-release-scl;
sudo yum -y --enablerepo=centos-sclo-rh-testing install devtoolset-7-gcc;
echo "source /opt/rh/devtoolset-7/enable" | sudo tee -a /etc/profile;
source /opt/rh/devtoolset-7/enable;
gcc --version;

WPF Button with Image

<Button x:Name="myBtn_DetailsTab_Save" FlowDirection="LeftToRight"  HorizontalAlignment="Left" Margin="835,544,0,0" VerticalAlignment="Top"  Width="143" Height="53" BorderBrush="#FF0F6287" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontFamily="B Titr" FontSize="15" FontWeight="Bold" BorderThickness="2" Click="myBtn_DetailsTab_Save_Click">
    <StackPanel HorizontalAlignment="Stretch" Background="#FF1FB3F5" Cursor="Hand" >
        <Image HorizontalAlignment="Left"  Source="image/bg/Save.png" Height="36" Width="124" />
        <TextBlock HorizontalAlignment="Center" Width="84" Height="22" VerticalAlignment="Top" Margin="0,-31,-58,0" Text="??? ?????" />
    </StackPanel>
</Button>

DropDownList in MVC 4 with Razor

//ViewModel

public class RegisterViewModel
{

    public RegisterViewModel()
    {
        ActionsList = new List<SelectListItem>();
    }

    public IEnumerable<SelectListItem> ActionsList { get; set; }

    public string StudentGrade { get; set; }

  }

//Enum Class:

public enum GradeTypes
{
    A,
    B,
    C,
    D,
    E,
    F,
    G,
    H
}

//Controller Action

 public ActionResult Student()
    {
RegisterViewModel vm = new RegisterViewModel();
IEnumerable<GradeTypes> actionTypes = Enum.GetValues(typeof(GradeTypes))
                                             .Cast<GradeTypes>();
        vm.ActionsList = from action in actionTypes
                         select new SelectListItem
                         {
                             Text = action.ToString(),
                             Value = action.ToString()
                         };
        return View(vm);
    }

//view Action

 <div class="form-group">
                                <label class="col-lg-2 control-label" for="hobies">Student Grade:</label>
                                <div class="col-lg-10">
                                   @Html.DropDownListFor(model => model.StudentGrade, Model.ActionsList, new { @class = "form-control" })
                                </div>

R * not meaningful for factors ERROR

new[,2] is a factor, not a numeric vector. Transform it first

new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5

HTML5 tag for horizontal line break

Simply use hr tag in HTML file and add below code in CSS file .

    hr {
       display: block;
       position: relative;
       padding: 0;
       margin: 8px auto;
       height: 0;
       width: 100%;
       max-height: 0;
       font-size: 1px;
       line-height: 0;
       clear: both;
       border: none;
       border-top: 1px solid #aaaaaa;
       border-bottom: 1px solid #ffffff;
    }

it works perfectly .

JSONException: Value of type java.lang.String cannot be converted to JSONObject

The 3 characters at the beginning of your json string correspond to Byte Order Mask (BOM), which is a sequence of Bytes to identify the file as UTF8 file.

Be sure that the file which sends the json is encoded with utf8 (no bom) encoding.

(I had the same issue, with TextWrangler editor. Use save as - utf8 (no bom) to force the right encoding.)

Hope it helps.

Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time

You are definitely missing a small thing and that is you are not setting a default value:

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

So the code would look like:

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Calendar cal_Two = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println(cal_Two.getTime());

Explanation: If you want to change the time zone, set the default time zone using TimeZone.setDefault()

How does bitshifting work in Java?

You can use e.g. this API if you would like to see bitString presentation of your numbers. Uncommons Math

Example (in jruby)

bitString = org.uncommons.maths.binary.BitString.new(java.math.BigInteger.new("12").toString(2))
bitString.setBit(1, true)
bitString.toNumber => 14

edit: Changed api link and add a little example

Get column from a two dimensional array

You have to loop through each element in the 2d-array, and get the nth column.

    function getCol(matrix, col){
       var column = [];
       for(var i=0; i<matrix.length; i++){
          column.push(matrix[i][col]);
       }
       return column;
    }

    var array = [new Array(20), new Array(20), new Array(20)]; //..your 3x20 array
    getCol(array, 0); //Get first column

EL access a map value by Integer key

Based on the above post i tried this and this worked fine I wanted to use the value of Map B as keys for Map A:

<c:if test="${not empty activityCodeMap and not empty activityDescMap}">
<c:forEach var="valueMap" items="${auditMap}">
<tr>
<td class="activity_white"><c:out value="${activityCodeMap[valueMap.value.activityCode]}"/></td>
<td class="activity_white"><c:out value="${activityDescMap[valueMap.value.activityDescCode]}"/></td>
<td class="activity_white">${valueMap.value.dateTime}</td>
</tr>
</c:forEach>
</c:if>

How to not wrap contents of a div?

I don't know the reasoning behind this, but I set my parent container to display:flex and the child containers to display:inline-block and they stayed inline despite the combined width of the children exceeding the parent.

Didn't need to toy with max-width, max-height, white-space, or anything else.

Hope that helps someone.

Convert Base64 string to an image file?

The problem is that data:image/png;base64, is included in the encoded contents. This will result in invalid image data when the base64 function decodes it. Remove that data in the function before decoding the string, like so.

function base64_to_jpeg($base64_string, $output_file) {
    // open the output file for writing
    $ifp = fopen( $output_file, 'wb' ); 

    // split the string on commas
    // $data[ 0 ] == "data:image/png;base64"
    // $data[ 1 ] == <actual base64 string>
    $data = explode( ',', $base64_string );

    // we could add validation here with ensuring count( $data ) > 1
    fwrite( $ifp, base64_decode( $data[ 1 ] ) );

    // clean up the file resource
    fclose( $ifp ); 

    return $output_file; 
}

How do I use WebRequest to access an SSL encrypted site using https?

This one worked for me:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Google Maps Api v3 - find nearest markers

The formula above didn't work for me, but I used this without any issue. Pass your current location to the function, and loop through an array of markers to find the closest:

function find_closest_marker( lat1, lon1 ) {    
    var pi = Math.PI;
    var R = 6371; //equatorial radius
    var distances = [];
    var closest = -1;

    for( i=0;i<markers.length; i++ ) {  
        var lat2 = markers[i].position.lat();
        var lon2 = markers[i].position.lng();

        var chLat = lat2-lat1;
        var chLon = lon2-lon1;

        var dLat = chLat*(pi/180);
        var dLon = chLon*(pi/180);

        var rLat1 = lat1*(pi/180);
        var rLat2 = lat2*(pi/180);

        var a = Math.sin(dLat/2) * Math.sin(dLat/2) + 
                    Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(rLat1) * Math.cos(rLat2); 
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
        var d = R * c;

        distances[i] = d;
        if ( closest == -1 || d < distances[closest] ) {
            closest = i;
        }
    }

    // (debug) The closest marker is:
    console.log(markers[closest]);
}

Add some word to all or some rows in Excel?

Insert a column, for instance a new A column. Then use this function;

="k"&B1

and copy it down.

Then you can hide the new column A if you need too.

how to convert rgb color to int in java

int color = (A & 0xff) << 24 | (R & 0xff) << 16 | (G & 0xff) << 8 | (B & 0xff);

Linux find file names with given string recursively

use ack its simple. just type ack <string to be searched>

Check if a string is null or empty in XSLT

Use simple categoryName/text() Such test works fine on <categoryName/> and also <categoryName></categoryName>.

<xsl:choose>
    <xsl:when test="categoryName/text()">
        <xsl:value-of select="categoryName" />
    </xsl:when>
    <xsl:otherwise>
        <xsl:value-of select="other" />
    </xsl:otherwise>
</xsl:choose>

Access denied; you need (at least one of) the SUPER privilege(s) for this operation

When you restore backup, Make sure to try with the same username for the old one and the new one.

How do I do multiple CASE WHEN conditions using SQL Server 2008?

There are two formats of case expression. You can do CASE with many WHEN as;

CASE  WHEN Col1 = 1 OR Col3 = 1  THEN 1 
      WHEN Col1 = 2 THEN 2
      ...
      ELSE 0 END as Qty

Or a Simple CASE expression

CASE Col1 WHEN 1 THEN 11 WHEN 2 THEN 21 ELSE 13 END

Or CASE within CASE as;

CASE  WHEN Col1 < 2 THEN  
                    CASE Col2 WHEN 'X' THEN 10 ELSE 11 END
      WHEN Col1 = 2 THEN 2
      ...
      ELSE 0 END as Qty

Create a BufferedImage from file and make it TYPE_INT_ARGB

try {
    File img = new File("somefile.png");
    BufferedImage image = ImageIO.read(img ); 
    System.out.println(image);
} catch (IOException e) { 
    e.printStackTrace(); 
}

Example output for my image file:

BufferedImage@5d391d: type = 5 ColorModel: #pixelBits = 24 
numComponents = 3 color 
space = java.awt.color.ICC_ColorSpace@50a649 
transparency = 1 
has alpha = false 
isAlphaPre = false 
ByteInterleavedRaster: 
width = 800 
height = 600 
#numDataElements 3 
dataOff[0] = 2

You can run System.out.println(object); on just about any object and get some information about it.

How to run TypeScript files from command line?

This answer may be premature, but deno supports running both TS and JS out of the box.

Based on your development environment, moving to Deno (and learning about it) might be too much, but hopefully this answer helps someone in the future.

How can I make a link from a <td> table cell

I would recommend using an actual anchor element, and set it as block.

<div class="divBox">
    <a href="#">Link</a>
</div>

.divBox
{
    width: 300px;
    height: 100px;
}
.divBox a
{
    width: 100%;
    height: 100%;
    display: block;
}

This will set the anchor to the same dimensions of the parent div.

How to Run the Procedure?

In SQL Plus:

VAR rc REFCURSOR
EXEC gokul_proc(1,'GOKUL', :rc);
print rc

Pods stuck in Terminating status

I stumbled upon this recently when removing rook ceph namespace - it got stuck in Terminating state.

The only thing that helped was removing kubernetes finalizer by directly calling k8s api with curl as suggested here.

  • kubectl get namespace rook-ceph -o json > tmp.json
  • delete kubernetes finalizer in tmp.json (leave empty array "finalizers": [])
  • run kubectl proxy in another terminal for auth purposes and run following curl request to returned port
  • curl -k -H "Content-Type: application/json" -X PUT --data-binary @tmp.json 127.0.0.1:8001/k8s/clusters/c-mzplp/api/v1/namespaces/rook-ceph/finalize
  • namespace is gone

Detailed rook ceph teardown here.

Groovy Shell warning "Could not open/create prefs root node ..."

This happened to me.

Apparently it is because Java does not have permission to create registry keys.

See: Java: java.util.Preferences Failing

Is it necessary to write HEAD, BODY and HTML tags?

It's true that the HTML specs permit certain tags to be omitted in certain cases, but generally doing so is unwise.

It has two effects - it makes the spec more complex, which in turn makes it harder for browser authors to write correct implementations (as demonstrated by IE getting it wrong).

This makes the likelihood of browser errors in these parts of the spec high. As a website author you can avoid the issue by including these tags - so while the spec doesn't say you have to, doing so reduces the chance of things going wrong, which is good engineering practice.

What's more, the latest HTML 5.1 WG spec currently says (bear in mind it's a work in progress and may yet change).

A body element's start tag may be omitted if the element is empty, or if the first thing inside the body element is not a space character or a comment, except if the first thing inside the body element is a meta, link, script, style, or template element.

http://www.w3.org/html/wg/drafts/html/master/sections.html#the-body-element

This is a little subtle. You can omit body and head, and the browser will then infer where those elements should be inserted. This carries the risk of not being explicit, which could cause confusion.

So this

<html>
  <h1>hello</h1>
  <script ... >
  ...

results in the script element being a child of the body element, but this

<html>
  <script ... >
  <h1>hello</h1>

would result in the script tag being a child of the head element.

You could be explicit by doing this

<html>
    <body>
      <script ... >
      <h1>hello</h1>

and then whichever you have first, the script or the h1, they will both, predictably appear in the body element. These are things which are easy to overlook while refactoring and debugging code. (say for example, you have JS which is looking for the 1st script element in the body - in the second snippet it would stop working).

As a general rule, being explicit about things is always better than leaving things open to interpretation. In this regard XHTML is better because it forces you to be completely explicit about your element structure in your code, which makes it simpler, and therefore less prone to misinterpretation.

So yes, you can omit them and be technically valid, but it is generally unwise to do so.

How can I do an UPDATE statement with JOIN in SQL Server?

A standard SQL approach would be

UPDATE ud
SET assid = (SELECT assid FROM sale s WHERE ud.id=s.id)

On SQL Server you can use a join

UPDATE ud
SET assid = s.assid
FROM ud u
JOIN sale s ON u.id=s.id

SELECT query with CASE condition and SUM()

I don't think you need a case statement. You just need to update your where clause and make sure you have correct parentheses to group the clauses.

SELECT Sum(CAMount) as PaymentAmount 
from TableOrderPayment 
where (CStatus = 'Active' AND CPaymentType = 'Cash') 
OR (CStatus = 'Active' and CPaymentType = 'Check' and CDate<=SYSDATETIME())

The answers posted before mine assume that CDate<=SYSDATETIME() is also appropriate for Cash payment type as well. I think I split mine out so it only looks for that clause for check payments.

In Gradle, is there a better way to get Environment Variables?

Well; this works as well:

home = "$System.env.HOME"

It's not clear what you're aiming for.

How do I return clean JSON from a WCF Service?

If you want nice json without hardcoding attributes into your service classes,

use <webHttp defaultOutgoingResponseFormat="Json"/> in your behavior config

Why does make think the target is up to date?

my mistake was making the target name "filename.c:" instead of just "filename:"

Python strip() multiple characters?

Because strip() only strips trailing and leading characters, based on what you provided. I suggest:

>>> import re
>>> name = "Barack (of Washington)"
>>> name = re.sub('[\(\)\{\}<>]', '', name)
>>> print(name)
Barack of Washington

how to get the value of a textarea in jquery?

$('textarea#message') cannot be undefined (if by $ you mean jQuery of course).

$('textarea#message') may be of length 0 and then $('textarea#message').val() would be empty that's all

Docker: How to use bash with an Alpine based docker image?

Try using RUN /bin/sh instead of bash.

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

Edit: isMounted is deprecated and will probably be removed in later versions of React. See this and this, isMounted is an Antipattern.


As the warning states, you are calling this.setState on an a component that was mounted but since then has been unmounted.

To make sure your code is safe, you can wrap it in

if (this.isMounted()) {
    this.setState({'time': remainTimeInfo});
}

to ensure that the component is still mounted.

Android: show/hide status bar/power bar

Reference - https://developer.android.com/training/system-ui/immersive.html

// This snippet shows the system bars. It does this by removing all the flags
// except for the ones that make the content appear under the system bars.
private void showSystemUI() {
    mDecorView.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}

showDialog deprecated. What's the alternative?

From http://developer.android.com/reference/android/app/Activity.html

public final void showDialog (int id) Added in API level 1

This method was deprecated in API level 13. Use the new DialogFragment class with FragmentManager instead; this is also available on older platforms through the Android compatibility package.

Simple version of showDialog(int, Bundle) that does not take any arguments. Simply calls showDialog(int, Bundle) with null arguments.

Why

  • A fragment that displays a dialog window, floating on top of its activity's window. This fragment contains a Dialog object, which it displays as appropriate based on the fragment's state. Control of the dialog (deciding when to show, hide, dismiss it) should be done through the API here, not with direct calls on the dialog.
  • Here is a nice discussion Android DialogFragment vs Dialog
  • Another nice discussion DialogFragment advantages over AlertDialog

How to solve?

More

Adding Only Untracked Files

git add . (add all files in this directory)

git add -all (add all files in all directories)

git add -N can be helpful for for listing which ones for later....

Set div height equal to screen size

try this

$(document).ready(function(){
    $('#content').height($(window).height());
});

Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

I had the same issue.

I was adding items to my ArrayList outside the UI thread.

Solution: I have done both, adding the items and called notifyDataSetChanged() in the UI thread.

Rails raw SQL example

You can do this:

sql = "Select * from ... your sql query here"
records_array = ActiveRecord::Base.connection.execute(sql)

records_array would then be the result of your sql query in an array which you can iterate through.

Spark difference between reduceByKey vs groupByKey vs aggregateByKey vs combineByKey

While both reducebykey and groupbykey will produce the same answer, the reduceByKey example works much better on a large dataset. That's because Spark knows it can combine output with a common key on each partition before shuffling the data.

On the other hand, when calling groupByKey - all the key-value pairs are shuffled around. This is a lot of unnessary data to being transferred over the network.

for more detailed check this below link

https://databricks.gitbooks.io/databricks-spark-knowledge-base/content/best_practices/prefer_reducebykey_over_groupbykey.html

How to find tags with only certain attributes - BeautifulSoup

Adding a combination of Chris Redford's and Amr's answer, you can also search for an attribute name with any value with the select command:

from bs4 import BeautifulSoup as Soup
html = '<td valign="top">.....</td>\
    <td width="580" valign="top">.......</td>\
    <td>.....</td>'
soup = Soup(html, 'lxml')
results = soup.select('td[valign]')

Cannot retrieve string(s) from preferences (settings)

All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if to bind them all together in the way I believe you intend.

Check if multiple strings exist in another string

Yet another solution with set. using set.intersection. For a one-liner.

subset = {"some" ,"words"} 
text = "some words to be searched here"
if len(subset & set(text.split())) == len(subset):
   print("All values present in text")

if subset & set(text.split()):
   print("Atleast one values present in text")

How to change heatmap.2 color range in R?

I think you need to set symbreaks = FALSE That should allow for asymmetrical color scales.

How do I execute a PowerShell script automatically using Windows task scheduler?

I also could not launch scripts, after heavy searching nothing helped. No -ExecutionPolicy, no commands, no files and no difference between "" and ''.

I simply put the command I ran in powershell in the argument tab: ./scripts.ps1 parameter1 11 parameter2 xx and so on. Now the scheduler works. Program: Powershell.exe Start in: C:/location/of/script/

How to Specify "Vary: Accept-Encoding" header in .htaccess

To gzip up your font files as well!

add "x-font/otf x-font/ttf x-font/eot"

as in:

AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml x-font/otf x-font/ttf x-font/eot

Decimal to Hexadecimal Converter in Java

The following converts decimal to Hexa Decimal with Time Complexity : O(n) Linear Time with out any java inbuilt function

private static String decimalToHexaDecimal(int N) {
    char hexaDecimals[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
    StringBuilder builder = new StringBuilder();
    int base= 16;
    while (N != 0) {
        int reminder = N % base;
        builder.append(hexaDecimals[reminder]);
        N = N / base;
    }

    return builder.reverse().toString();
}

How to count the number of lines of a string in javascript

 <script type="text/javascript">
      var multilinestr = `
        line 1
        line 2
        line 3
        line 4
        line 5
        line 6`;
      totallines = multilinestr.split("\n");
lines = str.split("\n"); 
console.log(lines.length);
</script>

thats works in my case

"git pull" or "git merge" between master and development branches

This workflow works best for me:

git checkout -b develop

...make some changes...

...notice master has been updated...

...commit changes to develop...

git checkout master
git pull

...bring those changes back into develop...

git checkout develop
git rebase master

...make some more changes...

...commit them to develop...

...merge them into master...

git checkout master
git pull
git merge develop

Count items in a folder with PowerShell

You can also use an alias

(ls).Count

Get current date in Swift 3?

You can do it in this way with Swift 3.0:

let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)

let year =  components.year
let month = components.month
let day = components.day

print(year)
print(month)
print(day)

How do I format a number in Java?

There are two approaches in the standard library. One is to use java.text.DecimalFormat. The other more cryptic methods (String.format, PrintStream.printf, etc) based around java.util.Formatter should keep C programmers happy(ish).

Node update a specific package

Use npm outdated to see Current and Latest version of all packages.


Then npm i packageName@versionNumber to install specific version : example npm i [email protected].

Or npm i packageName@latest to install latest version : example npm i browser-sync@latest.

How can I tell how many objects I've stored in an S3 bucket?

If you use the s3cmd command-line tool, you can get a recursive listing of a particular bucket, outputting it to a text file.

s3cmd ls -r s3://logs.mybucket/subfolder/ > listing.txt

Then in linux you can run a wc -l on the file to count the lines (1 line per object).

wc -l listing.txt

How to call a php script/function on a html button click

Modify the_script.php like this.

<script>
the_function() {
    alert("You win");
}
</script>

Upgrading React version and it's dependencies by reading package.json

Use this command to update react npm install --save [email protected] Don't forget to change 16.12.0 to the latest version or the version you need to setup.

Create folder with batch but only if it doesn't already exist

You just use this: if not exist "C:\VTS\" mkdir C:\VTS it wll create a directory only if the folder does not exist.

Note that this existence test will return true only if VTS exists and is a directory. If it is not there, or is there as a file, the mkdir command will run, and should cause an error. You might want to check for whether VTS exists as a file as well.

Real mouse position in canvas

You can get the mouse positions by using this snippet:

function getMousePos(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: (evt.clientX - rect.left) / (rect.right - rect.left) * canvas.width,
        y: (evt.clientY - rect.top) / (rect.bottom - rect.top) * canvas.height
    };
}

This code takes into account both changing coordinates to canvas space (evt.clientX - rect.left) and scaling when canvas logical size differs from its style size (/ (rect.right - rect.left) * canvas.width see: Canvas width and height in HTML5).

Example: http://jsfiddle.net/sierawski/4xezb7nL/

Source: jerryj comment on http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/

Pipe to/from the clipboard in Bash script

just searched the same stuff on my KDE environment. Feel free to use clipcopy and clippaste

KDE:

> echo "TEST CLIP FROM TERMINAL" | clipcopy 
> clippaste 
TEST CLIP FROM TERMINAL

What is android:weightSum in android, and how does it work?

From developer documentation

This can be used for instance to give a single child 50% of the total available space by giving it a layout_weight of 0.5 and setting the weightSum to 1.0.

Addition to @Shubhayu answer

rest 3/5 can be used for other child layouts which really doesn't need any specific portion of containing layout.

this is potential use of android:weightSum property.

How to add jQuery code into HTML Page

Make sure that you embedd the jQuery library into your page by adding the below shown line into your <head> block:

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

What is the difference between "mvn deploy" to a local repo and "mvn install"?

"matt b" has it right, but to be specific, the "install" goal copies your built target to the local repository on your file system; useful for small changes across projects not currently meant for the full group.

The "deploy" goal uploads it to your shared repository for when your work is finished, and then can be shared by other people who require it for their project.

In your case, it seems that "install" is used to make the management of the deployment easier since CI's local repo is the shared repo. If CI was on another box, it would have to use the "deploy" goal.

Pandas How to filter a Series

From pandas version 0.18+ filtering a series can also be done as below

test = {
383:    3.000000,
663:    1.000000,
726:    1.000000,
737:    9.000000,
833:    8.166667
}

pd.Series(test).where(lambda x : x!=1).dropna()

Checkout: http://pandas.pydata.org/pandas-docs/version/0.18.1/whatsnew.html#method-chaininng-improvements

Setting Camera Parameters in OpenCV/Python

Not all parameters are supported by all cameras - actually, they are one of the most troublesome part of the OpenCV library. Each camera type - from android cameras to USB cameras to professional ones offer a different interface to modify its parameters. There are many branches in OpenCV code to support as many of them, but of course not all possibilities are covered.

What you can do is to investigate your camera driver, write a patch for OpenCV and send it to code.opencv.org. This way others will enjoy your work, the same way you enjoy others'.

There is also a possibility that your camera does not support your request - most USB cams are cheap and simple. Maybe that parameter is just not available for modifications.

If you are sure the camera supports a given param (you say the camera manufacturer provides some code) and do not want to mess with OpenCV, you can wrap that sample code in C++ with boost::python, to make it available in Python. Then, enjoy using it.

What is the difference between Task.Run() and Task.Factory.StartNew()

The second method, Task.Run, has been introduced in a later version of the .NET framework (in .NET 4.5).

However, the first method, Task.Factory.StartNew, gives you the opportunity to define a lot of useful things about the thread you want to create, while Task.Run doesn't provide this.

For instance, lets say that you want to create a long running task thread. If a thread of the thread pool is going to be used for this task, then this could be considered an abuse of the thread pool.

One thing you could do in order to avoid this would be to run the task in a separate thread. A newly created thread that would be dedicated to this task and would be destroyed once your task would have been completed. You cannot achieve this with the Task.Run, while you can do so with the Task.Factory.StartNew, like below:

Task.Factory.StartNew(..., TaskCreationOptions.LongRunning);

As it is stated here:

So, in the .NET Framework 4.5 Developer Preview, we’ve introduced the new Task.Run method. This in no way obsoletes Task.Factory.StartNew, but rather should simply be thought of as a quick way to use Task.Factory.StartNew without needing to specify a bunch of parameters. It’s a shortcut. In fact, Task.Run is actually implemented in terms of the same logic used for Task.Factory.StartNew, just passing in some default parameters. When you pass an Action to Task.Run:

Task.Run(someAction);

that’s exactly equivalent to:

Task.Factory.StartNew(someAction, 
    CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);

Force flushing of output to a file while bash script is still running

I had this problem with a background process in Mac OS X using the StartupItems. This is how I solve it:

If I make sudo ps aux I can see that mytool is launched.

I found that (due to buffering) when Mac OS X shuts down mytool never transfers the output to the sed command. However, if I execute sudo killall mytool, then mytool transfers the output to the sed command. Hence, I added a stop case to the StartupItems that is executed when Mac OS X shuts down:

start)
    if [ -x /sw/sbin/mytool ]; then
      # run the daemon
      ConsoleMessage "Starting mytool"
      (mytool | sed .... >> myfile.txt) & 
    fi
    ;;
stop)
    ConsoleMessage "Killing mytool"
    killall mytool
    ;;

Correct way to initialize empty slice

The two alternative you gave are semantically identical, but using make([]int, 0) will result in an internal call to runtime.makeslice (Go 1.14).

You also have the option to leave it with a nil value:

var myslice []int

As written in the Golang.org blog:

a nil slice is functionally equivalent to a zero-length slice, even though it points to nothing. It has length zero and can be appended to, with allocation.

A nil slice will however json.Marshal() into "null" whereas an empty slice will marshal into "[]", as pointed out by @farwayer.

None of the above options will cause any allocation, as pointed out by @ArmanOrdookhani.

The request failed or the service did not respond in a timely fashion?

If you are running SQL Server in a local environment and not over a TCP/IP connection. Go to Protocols under SQL Server Configuration Manager, Properties, and disable TCP/IP. Once this is done then the error message will go away when restarting the service.

Playing mp3 song on python

Another quick and simple option...

import os

os.system('start path/to/player/executable path/to/file.mp3')

Now you might need to make some slight changes to make it work. For example, if the player needs extra arguments or you don't need to specify the full path. But this is a simple way of doing it.

How to build an APK file in Eclipse?

For testing on a device, you can connect the device using USB and run from Eclipse just as an emulator.

If you need to distribute the app, then use the export feature:

alt text

alt text

Then follow instructions. You will have to create a key in the process.

Styling an input type="file" button

As JGuo and CorySimmons mentioned, you can use the clickable behaviour of a stylable label, hiding the less flexible file input element.

<!DOCTYPE html>
<html>
<head>
<title>Custom file input</title>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
</head>

<body>

<label for="upload-file" class="btn btn-info"> Choose file... </label>
<input id="upload-file" type="file" style="display: none"
onchange="this.nextElementSibling.textContent = this.previousElementSibling.title = this.files[0].name">
<div></div>

</body>
</html>

How to get the first five character of a String

string str = "GoodMorning"

string strModified = str.Substring(0,5);

Entity Framework change connection at runtime

The created class is 'partial'!

public partial class Database1Entities1 : DbContext
{
    public Database1Entities1()
        : base("name=Database1Entities1")
    {
    }

... and you call it like this:

using (var ctx = new Database1Entities1())
      {
        #if DEBUG
        ctx.Database.Log = Console.Write;
        #endif

so, you need only create a partial own class file for original auto-generated class (with same class name!) and add a new constructor with connection string parameter, like Moho's answer before.

After it you able to use parametrized constructor against original. :-)

example:

using (var ctx = new Database1Entities1(myOwnConnectionString))
      {
        #if DEBUG
        ctx.Database.Log = Console.Write;
        #endif

efficient way to implement paging

The approach that I am giving is the fastest pagination that SQL server can achieve. I have tested this on 5 million records. This approach is far better than "OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY" provided by SQL Server.

-- The below given code computes the page numbers and the max row of previous page
-- Replace <<>> with the correct table data.
-- Eg. <<IdentityColumn of Table>> can be EmployeeId and <<Table>> will be dbo.Employees

DECLARE @PageNumber int=1; --1st/2nd/nth page. In stored proc take this as input param.
DECLARE @NoOfRecordsPerPage int=1000;

 DECLARE @PageDetails TABLE
       (
        <<IdentityColumn of Table>> int,
        rownum int,
        [PageNumber] int
       )           
       INSERT INTO @PageDetails values(0, 0, 0)
       ;WITH CTE AS
       (
       SELECT <<IdentityColumn of Table>>, ROW_NUMBER() OVER(ORDER BY <<IdentityColumn of Table>>) rownum FROM <<Table>>
       )
       Insert into @PageDetails 
       SELECT <<IdentityColumn of Table>>, CTE.rownum, ROW_NUMBER() OVER (ORDER BY rownum) as [PageNumber] FROM CTE WHERE CTE.rownum%@NoOfRecordsPerPage=0


--SELECT * FROM @PageDetails 

-- Actual pagination
SELECT TOP (@NoOfRecordsPerPage)
FROM <<Table>> AS <<Table>>
WHERE <<IdentityColumn of Table>> > (SELECT <<IdentityColumn of Table>> FROM 
@PageDetails WHERE PageNumber=@PageNumber)
ORDER BY <<Identity Column of Table>>

Find index of a value in an array

For arrays you can use: Array.FindIndex<T>:

int keyIndex = Array.FindIndex(words, w => w.IsKey);

For lists you can use List<T>.FindIndex:

int keyIndex = words.FindIndex(w => w.IsKey);

You can also write a generic extension method that works for any Enumerable<T>:

///<summary>Finds the index of the first item matching an expression in an enumerable.</summary>
///<param name="items">The enumerable to search.</param>
///<param name="predicate">The expression to test the items against.</param>
///<returns>The index of the first matching item, or -1 if no items match.</returns>
public static int FindIndex<T>(this IEnumerable<T> items, Func<T, bool> predicate) {
    if (items == null) throw new ArgumentNullException("items");
    if (predicate == null) throw new ArgumentNullException("predicate");

    int retVal = 0;
    foreach (var item in items) {
        if (predicate(item)) return retVal;
        retVal++;
    }
    return -1;
}

And you can use LINQ as well:

int keyIndex = words
    .Select((v, i) => new {Word = v, Index = i})
    .FirstOrDefault(x => x.Word.IsKey)?.Index ?? -1;

How do I programmatically click a link with javascript?

Client Side JS function to automatically click a link when...

Here is an example where you check the value of a hidden form input, which holds an error passed down from the server.. your client side JS then checks the value of it and populates an error in another location that you specify..in this case a pop-up login modal.

var signUperror = document.getElementById('handleError')

if (signUperror) {
  if(signUperror.innerHTML != ""){
  var clicker = function(){
    document.getElementById('signup').click()
  }
  clicker()
  }
}

Pandas sum by groupby, but exclude certain columns

The agg function will do this for you. Pass the columns and function as a dict with column, output:

df.groupby(['Country', 'Item_Code']).agg({'Y1961': np.sum, 'Y1962': [np.sum, np.mean]})  # Added example for two output columns from a single input column

This will display only the group by columns, and the specified aggregate columns. In this example I included two agg functions applied to 'Y1962'.

To get exactly what you hoped to see, included the other columns in the group by, and apply sums to the Y variables in the frame:

df.groupby(['Code', 'Country', 'Item_Code', 'Item', 'Ele_Code', 'Unit']).agg({'Y1961': np.sum, 'Y1962': np.sum, 'Y1963': np.sum})

Determine if map contains a value for a key?

To succinctly summarize some of the other answers:

If you're not using C++ 20 yet, you can write your own mapContainsKey function:

bool mapContainsKey(std::map<int, int>& map, int key)
{
  if (map.find(key) == map.end()) return false;
  return true;
}

If you'd like to avoid many overloads for map vs unordered_map and different key and value types, you can make this a template function.

If you're using C++ 20 or later, there will be a built-in contains function:

std::map<int, int> myMap;

// do stuff with myMap here

int key = 123;

if (myMap.contains(key))
{
  // stuff here
}

how to find 2d array size in c++

Along with the _countof() macro you can refer to the array size using pointer notation, where the array name by itself refers to the row, the indirection operator appended by the array name refers to the column.

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    int beans[3][4]{
        { 1, 2, 3, 4 }, 
        { 5, 6, 7, 8 }, 
        { 9, 10, 11, 12 }
    };

    cout << "Row size = " << _countof(beans)  // Output row size
        << "\nColumn size = " << _countof(*beans);  // Output column size
    cout << endl;

    // Used in a for loop with a pointer.

    int(*pbeans)[4]{ beans };

    for (int i{}; i < _countof(beans); ++i) {

        cout << endl;

        for (int j{}; j < _countof(*beans); ++j) {

            cout << setw(4) << pbeans[i][j];
        }
    };

    cout << endl;
}

String representation of an Enum

Unfortunately reflection to get attributes on enums is quite slow:

See this question: Anyone know a quick way to get to custom attributes on an enum value?

The .ToString() is quite slow on enums too.

You can write extension methods for enums though:

public static string GetName( this MyEnum input ) {
    switch ( input ) {
        case MyEnum.WINDOWSAUTHENTICATION:
            return "Windows";
        //and so on
    }
}

This isn't great, but will be quick and not require the reflection for attributes or field name.


C#6 Update

If you can use C#6 then the new nameof operator works for enums, so nameof(MyEnum.WINDOWSAUTHENTICATION) will be converted to "WINDOWSAUTHENTICATION" at compile time, making it the quickest way to get enum names.

Note that this will convert the explicit enum to an inlined constant, so it doesn't work for enums that you have in a variable. So:

nameof(AuthenticationMethod.FORMS) == "FORMS"

But...

var myMethod = AuthenticationMethod.FORMS;
nameof(myMethod) == "myMethod"

Is it possible to execute multiple _addItem calls asynchronously using Google Analytics?

From the docs:

_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.

So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.

Edit: Further reading led me here:

http://www.analyticsmarket.com/blog/edit-ecommerce-data

Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.

Android Error [Attempt to invoke virtual method 'void android.app.ActionBar' on a null object reference]

If you encounter this error

"java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setTitle (java.lang.CharSequence)' on a null object reference. "

Just use

setSupportActionBar (toolbar). 

How to add additional fields to form before submit?

Try this:

$('#form').submit(function(eventObj) {
    $(this).append('<input type="hidden" name="field_name" value="value" /> ');
    return true;
});

Scrolling a flexbox with overflowing content

Working with position:absolute; along with flex:

Position the flex item with position: relative. Then inside of it, add another <div> element with:

position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;

This extends the element to the boundaries of its relative-positioned parent, but does not allow to extend it. Inside, overflow: auto; will then work as expected.

  • the code snippet included in the answer - Click on enter image description here and then click on Full Page after running the snippet OR
  • Click here for the CODEPEN
  • The result: enter image description here

_x000D_
_x000D_
.all-0 {_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
}_x000D_
p {_x000D_
  text-align: justify;_x000D_
}_x000D_
.bottom-0 {_x000D_
  bottom: 0;_x000D_
}_x000D_
.overflow-auto {_x000D_
  overflow: auto;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
<div class="p-5 w-100">_x000D_
  <div class="row bg-dark m-0">_x000D_
    <div class="col-sm-9 p-0 d-flex flex-wrap">_x000D_
      <!-- LEFT-SIDE - ROW-1 -->_x000D_
      <div class="row m-0 p-0">_x000D_
        <!-- CARD 1 -->_x000D_
        <div class="col-md-8 p-0 d-flex">_x000D_
          <div class="my-card-content bg-white p-2 m-2 d-flex flex-column">_x000D_
            <img class="img img-fluid" src="https://via.placeholder.com/700x250">_x000D_
            <h4>Heading 1</h4>_x000D_
            <p>_x000D_
              Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old..._x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- CARD 2 -->_x000D_
        <div class="col-md-4 p-0 d-flex">_x000D_
          <div class="my-card-content bg-white p-2 m-2 d-flex flex-column">_x000D_
            <img class="img img-fluid" src="https://via.placeholder.com/400x250">_x000D_
            <h4>Heading 1</h4>_x000D_
            <p>_x000D_
              Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old..._x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="row m-0">_x000D_
        <!-- CARD 3 -->_x000D_
        <div class="col-md-4 p-0 d-flex">_x000D_
          <div class="my-card-content bg-white p-2 m-2 d-flex flex-column">_x000D_
            <img class="img img-fluid" src="https://via.placeholder.com/400x250">_x000D_
            <h4>Heading 1</h4>_x000D_
            <p>_x000D_
              Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old..._x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- CARD 4 -->_x000D_
        <div class="col-md-4 p-0 d-flex">_x000D_
          <div class="my-card-content bg-white p-2 m-2 d-flex flex-column">_x000D_
            <img class="img img-fluid" src="https://via.placeholder.com/400x250">_x000D_
            <h4>Heading 1</h4>_x000D_
            <p>_x000D_
              Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old..._x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- CARD 5-->_x000D_
        <div class="col-md-4 p-0 d-flex">_x000D_
          <div class="my-card-content bg-white p-2 m-2 d-flex flex-column">_x000D_
            <img class="img img-fluid" src="https://via.placeholder.com/400x250">_x000D_
            <h4>Heading 1</h4>_x000D_
            <p>_x000D_
              Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old..._x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="col-sm-3 p-0">_x000D_
      <div class="bg-white m-2 p-2 position-absolute all-0 d-flex flex-column">_x000D_
        <h4>Social Sidebar...</h4>_x000D_
        <hr />_x000D_
        <div class="d-flex overflow-auto">_x000D_
          <p>_x000D_
            Topping candy tiramisu soufflé fruitcake ice cream chocolate bar. Bear claw ice cream chocolate bar donut sweet tart. Pudding cupcake danish apple pie apple pie. Halva fruitcake ice cream chocolate bar. Bear claw ice cream chocolate bar donut sweet tart._x000D_
            opping candy tiramisu soufflé fruitcake ice cream chocolate bar. Bear claw ice cream chocolate bar donut sweet tart. Pudding cupcake danish apple pie apple pie. Halva fruitcake ice cream chocolate bar. Bear claw ice cream chocolate bar donut sweet tart._x000D_
            opping candy tiramisu soufflé fruitcake ice cream chocolate bar. Bear claw ice cream chocolate bar donut sweet tart. Pudding cupcake danish apple pie apple pie. Halva fruitcake ice cream chocolate bar. Bear claw ice cream chocolate bar donut sweet tart._x000D_
            Pudding cupcake danish apple pie apple pie. Halvafruitcake ice cream chocolate bar. Bear claw ice cream chocolate bar donut sweet tart. Pudding cupcake danish apple pie apple pie. Halvafruitcake ice cream chocolate bar. Bear claw ice cream_x000D_
            chocolate bar donut sweet tart. Pudding cupcake danish apple pie apple pie. Halvafruitcake ice cream chocolate bar. Bear claw ice cream chocolate bar donut sweet tart. Pudding cupcake danish apple pie apple pie. Halvafruitcake ice cream chocolate_x000D_
            bar. Bear claw ice cream chocolate bar donut sweet tart. Pudding cupcake danish apple pie apple pie. Halva_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>
_x000D_
_x000D_
_x000D_

Good Luck...

matplotlib does not show my drawings although I call pyplot.show()

What solved my problem was just using the below two lines in ipython notebook at the top

%matplotib inline
%pylab inline

And it worked. I'm using Ubuntu16.04 and ipython-5.1

javascript: get a function's variable's value within another function

you need a return statement in your first function.

function first(){
    var nameContent = document.getElementById('full_name').value;
    return nameContent;
}

and then in your second function can be:

function second(){
    alert(first());
}

How to add title to subplots in Matplotlib?

If you want to make it shorter, you could write :

import matplolib.pyplot as plt
for i in range(4):
    plt.subplot(2,2,i+1).set_title('Subplot n°{}' .format(i+1))
plt.show()

It makes it maybe less clear but you don't need more lines or variables

Google Maps API v3: How do I dynamically change the marker icon?

This thread might be dead, but StyledMarker is available for API v3. Just bind the color change you want to the correct DOM event using the addDomListener() method. This example is pretty close to what you want to do. If you look at the page source, change:

google.maps.event.addDomListener(document.getElementById("changeButton"),"click",function() {
  styleIcon.set("color","#00ff00");
  styleIcon.set("text","Go");
});

to something like:

google.maps.event.addDomListener("mouseover",function() {
  styleIcon.set("color","#00ff00");
  styleIcon.set("text","Go");
});

That should be enough to get you moving along.

The Wikipedia page on DOM Events will also help you target the event that you want to capture on the client-side.

Good luck (if you still need it)

Using Cygwin to Compile a C program; Execution error

Regarding your updated question about the missing cygwin1.dll.

From the Cygwin terminal check,

ls /usr/bin/cygwin1.dll

If it is not present (I doubt that), your installation is not properly done.

Then, check your path with,

echo $PATH

This will give : separated list of paths. It MUST contain /usr/bin. If you find that missing add it with,

export PATH=/usr/bin:$PATH

Finally,

  • I hope you are using Cygwin from the cygwin terminal (the little green+black icon installed with Cygwin), or MinTTY (if you installed that).
  • And, you have not moved the compiled EXE to a different machine which does not have Cygwin installed (if you do that, you will need to carry the cygwin1.dll to that machine -- keep it in the same folder as the compiled EXE).

Sleep Command in T-SQL?

Look at the WAITFOR command.

E.g.

-- wait for 1 minute
WAITFOR DELAY '00:01'

-- wait for 1 second
WAITFOR DELAY '00:00:01'

This command allows you a high degree of precision but is only accurate within 10ms - 16ms on a typical machine as it relies on GetTickCount. So, for example, the call WAITFOR DELAY '00:00:00:001' is likely to result in no wait at all.

Running shell command and capturing the output

Something like that:

def runProcess(exe):    
    p = subprocess.Popen(exe, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    while(True):
        # returns None while subprocess is running
        retcode = p.poll() 
        line = p.stdout.readline()
        yield line
        if retcode is not None:
            break

Note, that I'm redirecting stderr to stdout, it might not be exactly what you want, but I want error messages also.

This function yields line by line as they come (normally you'd have to wait for subprocess to finish to get the output as a whole).

For your case the usage would be:

for line in runProcess('mysqladmin create test -uroot -pmysqladmin12'.split()):
    print line,

Angular and debounce

You can create an RxJS (v.6) Observable that does whatever you like.

view.component.html

<input type="text" (input)="onSearchChange($event.target.value)" />

view.component.ts

import { Observable } from 'rxjs';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';

export class ViewComponent {
    searchChangeObserver;

  onSearchChange(searchValue: string) {

    if (!this.searchChangeObserver) {
      Observable.create(observer => {
        this.searchChangeObserver = observer;
      }).pipe(debounceTime(300)) // wait 300ms after the last event before emitting last event
        .pipe(distinctUntilChanged()) // only emit if value is different from previous value
        .subscribe(console.log);
    }

    this.searchChangeObserver.next(searchValue);
  }  


}

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

The alternative for explode in php is split.

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

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

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

Access index of last element in data frame

You want .iloc with double brackets.

import pandas as pd
df = pd.DataFrame({"date": range(10, 64, 8), "not_date": "fools"})
df.index += 17
df.iloc[[0,-1]][['date']]

You give .iloc a list of indexes - specifically the first and last, [0, -1]. That returns a dataframe from which you ask for the 'date' column. ['date'] will give you a series (yuck), and [['date']] will give you a dataframe.

Linux command to translate DomainName to IP

Use this

$ dig +short stackoverflow.com

69.59.196.211

or this

$ host stackoverflow.com

stackoverflow.com has address 69.59.196.211
stackoverflow.com mail is handled by 30 alt2.aspmx.l.google.com.
stackoverflow.com mail is handled by 40 aspmx2.googlemail.com.
stackoverflow.com mail is handled by 50 aspmx3.googlemail.com.
stackoverflow.com mail is handled by 10 aspmx.l.google.com.
stackoverflow.com mail is handled by 20 alt1.aspmx.l.google.com.

Prevent Default on Form Submit jQuery

$('#cpa-form input[name="Next"]').on('click', function(e){
    e.preventDefault();
});

Is either GET or POST more secure than the other?

I'm not about to repeat all the other answers, but there's one aspect that I haven't yet seen mentioned - it's the story of disappearing data. I don't know where to find it, but...

Basically it's about a web application that mysteriously every few night did loose all its data and nobody knew why. Inspecting the Logs later revealed that the site was found by google or another arbitrary spider, that happily GET (read: GOT) all the links it found on the site - including the "delete this entry" and "are you sure?" links.

Actually - part of this has been mentioned. This is the story behind "don't change data on GET but only on POST". Crawlers will happily follow GET, never POST. Even robots.txt doesn't help against misbehaving crawlers.

Fixed point vs Floating point number

A fixed point number has a specific number of bits (or digits) reserved for the integer part (the part to the left of the decimal point) and a specific number of bits reserved for the fractional part (the part to the right of the decimal point). No matter how large or small your number is, it will always use the same number of bits for each portion. For example, if your fixed point format was in decimal IIIII.FFFFF then the largest number you could represent would be 99999.99999 and the smallest non-zero number would be 00000.00001. Every bit of code that processes such numbers has to have built-in knowledge of where the decimal point is.

A floating point number does not reserve a specific number of bits for the integer part or the fractional part. Instead it reserves a certain number of bits for the number (called the mantissa or significand) and a certain number of bits to say where within that number the decimal place sits (called the exponent). So a floating point number that took up 10 digits with 2 digits reserved for the exponent might represent a largest value of 9.9999999e+50 and a smallest non-zero value of 0.0000001e-49.

Whats the CSS to make something go to the next line in the page?

There are two options that I can think of, but without more details, I can't be sure which is the better:

#elementId {
    display: block;
}

This will force the element to a 'new line' if it's not on the same line as a floated element.

#elementId {
     clear: both;
}

This will force the element to clear the floats, and move to a 'new line.'

In the case of the element being on the same line as another that has position of fixed or absolute nothing will, so far as I know, force a 'new line,' as those elements are removed from the document's normal flow.

Rails: How to list database tables/objects using the Rails console?

Its a start, it can list:

models = Dir.new("#{RAILS_ROOT}/app/models").entries

Looking some more...

HTML-encoding lost when attribute read from input field

Here is a simple javascript solution. It extends String object with a method "HTMLEncode" which can be used on an object without parameter, or with a parameter.

String.prototype.HTMLEncode = function(str) {
  var result = "";
  var str = (arguments.length===1) ? str : this;
  for(var i=0; i<str.length; i++) {
     var chrcode = str.charCodeAt(i);
     result+=(chrcode>128) ? "&#"+chrcode+";" : str.substr(i,1)
   }
   return result;
}
// TEST
console.log("stetaewteaw æø".HTMLEncode());
console.log("stetaewteaw æø".HTMLEncode("æåøåæå"))

I have made a gist "HTMLEncode method for javascript".

PHP - include a php file and also send query parameters

If you are going to write this include manually in the PHP file - the answer of Daff is perfect.

Anyway, if you need to do what was the initial question, here is a small simple function to achieve that:

<?php
// Include php file from string with GET parameters
function include_get($phpinclude)
{
    // find ? if available
    $pos_incl = strpos($phpinclude, '?');
    if ($pos_incl !== FALSE)
    {
        // divide the string in two part, before ? and after
        // after ? - the query string
        $qry_string = substr($phpinclude, $pos_incl+1);
        // before ? - the real name of the file to be included
        $phpinclude = substr($phpinclude, 0, $pos_incl);
        // transform to array with & as divisor
        $arr_qstr = explode('&',$qry_string);
        // in $arr_qstr you should have a result like this:
        //   ('id=123', 'active=no', ...)
        foreach ($arr_qstr as $param_value) {
            // for each element in above array, split to variable name and its value
            list($qstr_name, $qstr_value) = explode('=', $param_value);
            // $qstr_name will hold the name of the variable we need - 'id', 'active', ...
            // $qstr_value - the corresponding value
            // $$qstr_name - this construction creates variable variable
            // this means from variable $qstr_name = 'id', adding another $ sign in front you will receive variable $id
            // the second iteration will give you variable $active and so on
            $$qstr_name = $qstr_value;
        }
    }
    // now it's time to include the real php file
    // all necessary variables are already defined and will be in the same scope of included file
    include($phpinclude);
}

?>

I'm using this variable variable construction very often.

How to count days between two dates in PHP?

i created a function in which if you pass two dates than it will return day wise value. For better understanding please see the output of start date : 2018-11-12 11:41:19 and End Date 2018-11-16 12:07:26

private function getTimeData($str1,$str2){
$datetime1 = strtotime($str1);
$datetime2 = strtotime($str2);
$myArray = array();
if(date('d', $datetime2) != date('d', $datetime1) ||  date('m', $datetime2) != date('m', $datetime1) || date('y', $datetime2) != date('y', $datetime1)){
    $exStr1 = explode(' ',$str1);
    $exStr2 = explode(' ',$str2);
    $datediff = strtotime($exStr2[0]) - strtotime($exStr1[0]);
    $totalDays = round($datediff / (60 * 60 * 24));
    $actualDate1 = $datetime1;
    $actualDate2 = date('Y-m-d', $datetime1)." 23:59:59";
    $interval  = abs(strtotime($actualDate2)-$actualDate1);
    $minutes   = round($interval / 60);
    $myArray[0]['startDate'] = date('Y-m-d H:i:s', $actualDate1); 
    $myArray[0]['endDate'] = $actualDate2;
    $myArray[0]['minutes'] = $minutes;
    $i = 1;
    if($totalDays > 1){    
        for($i=1; $i<$totalDays; $i++){
            $dayString = "+".$i." day";
            $edate = strtotime($dayString, $actualDate1);
            $myArray[$i]['startDate'] = date('Y-m-d', $edate)." 00:00:00"; 
            $myArray[$i]['endDate'] = date('Y-m-d', $edate)." 23:59:59"; 
            $myArray[$i]['minutes'] = 1440;
        }
    }
    $actualSecDate1 = date('Y-m-d', $datetime2)." 00:00:00";
    $actualSecDate2 = $datetime2;
    $interval  = abs(strtotime($actualSecDate1)-$actualSecDate2);
    $minutes   = round($interval / 60);
    $myArray[$i]['startDate'] = $actualSecDate1; 
    $myArray[$i]['endDate'] = date('Y-m-d H:i:s', $actualSecDate2); 
    $myArray[$i]['minutes'] = $minutes;
}
else{
    $interval  = abs($datetime2-$datetime1);
    $minutes   = round($interval / 60);
    $myArray[0]['startDate'] = date('Y-m-d H:i:s', $datetime1); 
    $myArray[0]['endDate'] = date('Y-m-d H:i:s', $datetime2);
    $myArray[0]['minutes'] = $minutes;
}

return $myArray;
}

Output

Array
(
[0] => Array
    (
        [startDate] => 2018-11-12 11:41:19
        [endDate] => 2018-11-12 23:59:59
        [minutes] => 739
    )

[1] => Array
    (
        [startDate] => 2018-11-13 00:00:00
        [endDate] => 2018-11-13 23:59:59
        [minutes] => 1440
    )

[2] => Array
    (
        [startDate] => 2018-11-14 00:00:00
        [endDate] => 2018-11-14 23:59:59
        [minutes] => 1440
    )

[3] => Array
    (
        [startDate] => 2018-11-15 00:00:00
        [endDate] => 2018-11-15 23:59:59
        [minutes] => 1440
    )

[4] => Array
    (
        [startDate] => 2018-11-16 00:00:00
        [endDate] => 2018-11-16 12:07:26
        [minutes] => 727
    )
)

How Can I Set the Default Value of a Timestamp Column to the Current Timestamp with Laravel Migrations?

As additional possibility for future googlers

I find it more useful to have null in the updated_at column when the record is been created but has never been modified. It reduces the db size (ok, just a little) and its possible to see it at the first sight that the data has never been modified.

As of this I use:

$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->default(DB::raw('NULL ON UPDATE CURRENT_TIMESTAMP'))->nullable();

(In Laravel 7 with mysql 8).

SQL Server equivalent of MySQL's NOW()?

SYSDATETIME() and SYSUTCDATETIME()

are the DateTime2 equivalents of

GetDate() and GetUTCDate()

which return a DateTime.

DateTime2 is now the preferred method for storing the date and time in SQL Server 2008+. See the following StackOverflow Post.

How do I tell CMake to link in a static library in the source directory?

If you don't want to include the full path, you can do

add_executable(main main.cpp)
target_link_libraries(main bingitup)

bingitup is the same name you'd give a target if you create the static library in a CMake project:

add_library(bingitup STATIC bingitup.cpp)

CMake automatically adds the lib to the front and the .a at the end on Linux, and .lib at the end on Windows.

If the library is external, you might want to add the path to the library using

link_directories(/path/to/libraries/)

ReactJS SyntheticEvent stopPropagation() only works with React events?

From the React documentation: The event handlers below are triggered by an event in the bubbling phase. To register an event handler for the capture phase, append Capture. (emphasis added)

If you have a click event listener in your React code and you don't want it to bubble up, I think what you want to do is use onClickCapture instead of onClick. Then you would pass the event to the handler and do event.nativeEvent.stopPropagation() to keep the native event from bubbling up to a vanilla JS event listener (or anything that's not react).

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing

In my case setting the referenced object to NULL in my object before the merge o save method solve the problem, in my case the referenced object was catalog, that doesn't need to be saved, because in some cases I don't have it even.

    fisEntryEB.setCatStatesEB(null);

    (fisEntryEB) getSession().merge(fisEntryEB);

Remove all the children DOM elements in div

If you are looking for a modern >1.7 Dojo way of destroying all node's children this is the way:

// Destroys all domNode's children nodes
// domNode can be a node or its id:
domConstruct.empty(domNode);

Safely empty the contents of a DOM element. empty() deletes all children but keeps the node there.

Check "dom-construct" documentation for more details.

// Destroys domNode and all it's children
domConstruct.destroy(domNode);

Destroys a DOM element. destroy() deletes all children and the node itself.

Maximum on http header values?

If you are going to use any DDOS provider like Akamai, they have a maximum limitation of 8k in the response header size. So essentially try to limit your response header size below 8k.

How do I properly force a Git push?

This was our solution for replacing master on a corporate gitHub repository while maintaining history.

push -f to master on corporate repositories is often disabled to maintain branch history. This solution worked for us.

git fetch desiredOrigin
git checkout -b master desiredOrigin/master // get origin master

git checkout currentBranch  // move to target branch
git merge -s ours master  // merge using ours over master
// vim will open for the commit message
git checkout master  // move to master
git merge currentBranch  // merge resolved changes into master

push your branch to desiredOrigin and create a PR

How to call external JavaScript function in HTML

If a <script> has a src then the text content of the element will be not be executed as JS (although it will appear in the DOM).

You need to use multiple script elements.

  1. a <script> to load the external script
  2. a <script> to hold your inline code (with the call to the function in the external script)

    scroll_messages();

Sending websocket ping/pong frame from browser

There is no Javascript API to send ping frames or receive pong frames. This is either supported by your browser, or not. There is also no API to enable, configure or detect whether the browser supports and is using ping/pong frames. There was discussion about creating a Javascript ping/pong API for this. There is a possibility that pings may be configurable/detectable in the future, but it is unlikely that Javascript will be able to directly send and receive ping/pong frames.

However, if you control both the client and server code, then you can easily add ping/pong support at a higher level. You will need some sort of message type header/metadata in your message if you don't have that already, but that's pretty simple. Unless you are planning on sending pings hundreds of times per second or have thousands of simultaneous clients, the overhead is going to be pretty minimal to do it yourself.

What are sessions? How do they work?

"Session" is the term used to refer to a user's time browsing a web site. It's meant to represent the time between their first arrival at a page in the site until the time they stop using the site. In practice, it's impossible to know when the user is done with the site. In most servers there's a timeout that automatically ends a session unless another page is requested by the same user.

The first time a user connects some kind of session ID is created (how it's done depends on the web server software and the type of authentication/login you're using on the site). Like cookies, this usually doesn't get sent in the URL anymore because it's a security problem. Instead it's stored along with a bunch of other stuff that collectively is also referred to as the session. Session variables are like cookies - they're name-value pairs sent along with a request for a page, and returned with the page from the server - but their names are defined in a web standard.

Some session variables are passed as HTTP headers. They're passed back and forth behind the scenes of every page browse so they don't show up in the browser and tell everybody something that may be private. Among them are the USER_AGENT, or type of browser requesting the page, the REFERRER or the page that linked to the page being requested, etc. Some web server software adds their own headers or transfer additional session data specific to the server software. But the standard ones are pretty well documented.

Hope that helps.

Add Keypair to existing EC2 instance

I didn't find an easy way to add a new key pair via the console, but you can do it manually.

Just ssh into your EC2 box with the existing key pair. Then edit the ~/.ssh/authorized_keys and add the new key on a new line. Exit and ssh via the new machine. Success!

How to check whether a select box is empty using JQuery/Javascript

Another correct way to get selected value would be using this selector:

$("option[value="0"]:selected")

Best for you!

Filtering a spark dataframe based on date

Don't use this as suggested in other answers

.filter(f.col("dateColumn") < f.lit('2017-11-01'))

But use this instead

.filter(f.col("dateColumn") < f.unix_timestamp(f.lit('2017-11-01 00:00:00')).cast('timestamp'))

This will use the TimestampType instead of the StringType, which will be more performant in some cases. For example Parquet predicate pushdown will only work with the latter.

Virtual member call in a constructor

One important missing bit is, what is the correct way to resolve this issue?

As Greg explained, the root problem here is that a base class constructor would invoke the virtual member before the derived class has been constructed.

The following code, taken from MSDN's constructor design guidelines, demonstrates this issue.

public class BadBaseClass
{
    protected string state;

    public BadBaseClass()
    {
        this.state = "BadBaseClass";
        this.DisplayState();
    }

    public virtual void DisplayState()
    {
    }
}

public class DerivedFromBad : BadBaseClass
{
    public DerivedFromBad()
    {
        this.state = "DerivedFromBad";
    }

    public override void DisplayState()
    {   
        Console.WriteLine(this.state);
    }
}

When a new instance of DerivedFromBad is created, the base class constructor calls to DisplayState and shows BadBaseClass because the field has not yet been update by the derived constructor.

public class Tester
{
    public static void Main()
    {
        var bad = new DerivedFromBad();
    }
}

An improved implementation removes the virtual method from the base class constructor, and uses an Initialize method. Creating a new instance of DerivedFromBetter displays the expected "DerivedFromBetter"

public class BetterBaseClass
{
    protected string state;

    public BetterBaseClass()
    {
        this.state = "BetterBaseClass";
        this.Initialize();
    }

    public void Initialize()
    {
        this.DisplayState();
    }

    public virtual void DisplayState()
    {
    }
}

public class DerivedFromBetter : BetterBaseClass
{
    public DerivedFromBetter()
    {
        this.state = "DerivedFromBetter";
    }

    public override void DisplayState()
    {
        Console.WriteLine(this.state);
    }
}

How can I iterate over the elements in Hashmap?

Need Key & Value in Iteration

Use entrySet() to iterate through Map and need to access value and key:

Map<String, Person> hm = new HashMap<String, Person>();

hm.put("A", new Person("p1"));
hm.put("B", new Person("p2"));
hm.put("C", new Person("p3"));
hm.put("D", new Person("p4"));
hm.put("E", new Person("p5"));

Set<Map.Entry<String, Person>> set = hm.entrySet();

for (Map.Entry<String, Person> me : set) {
  System.out.println("Key :"+me.getKey() +" Name : "+ me.getValue().getName()+"Age :"+me.getValue().getAge());

}

Need Key in Iteration

If you want just to iterate over keys of map you can use keySet()

for(String key: map.keySet()) {
     Person value = map.get(key); 
}

Need Value in Iteration

If you just want to iterate over values of map you can use values()

for(Person person: map.values()) {

}

How to correct "TypeError: 'NoneType' object is not subscriptable" in recursive function?

What is a when you call Ancestors('A',a)? If a['A'] is None, or if a['A'][0] is None, you'd receive that exception.

Getting Error "Form submission canceled because the form is not connected"

You must ensure that the form is in the document. You can append the form to the body.

Flutter - Layout a Grid

Use whichever suits your need.

  1. GridView.count(...)

    GridView.count(
      crossAxisCount: 2,
      children: <Widget>[
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
      ],
    )
    
  2. GridView.builder(...)

    GridView.builder(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
      itemBuilder: (_, index) => FlutterLogo(),
      itemCount: 4,
    )
    
  3. GridView(...)

    GridView(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
      children: <Widget>[
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
      ],
    )
    
  4. GridView.custom(...)

    GridView.custom(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
      childrenDelegate: SliverChildListDelegate(
        [
          FlutterLogo(),
          FlutterLogo(),
          FlutterLogo(),
          FlutterLogo(),
        ],
      ),
    )
    
  5. GridView.extent(...)

    GridView.extent(
      maxCrossAxisExtent: 400,
      children: <Widget>[
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
      ],
    )
    

Output (same for all):

enter image description here

Responsive dropdown navbar with angular-ui bootstrap (done in the correct angular kind of way)

You can do it using the "collapse" directive: http://jsfiddle.net/iscrow/Es4L3/ (check the two "Note" in the HTML).

        <!-- Note: set the initial collapsed state and change it when clicking -->
        <a ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed" class="btn btn-navbar">
           <span class="icon-bar"></span>
           <span class="icon-bar"></span>
           <span class="icon-bar"></span>
        </a>
        <a class="brand" href="#">Title</a>
           <!-- Note: use "collapse" here. The original "data-" settings are not needed anymore. -->
           <div collapse="navCollapsed" class="nav-collapse collapse navbar-responsive-collapse">
              <ul class="nav">

That is, you need to store the collapsed state in a variable, and changing the collapsed also by (simply) changing the value of that variable.


Release 0.14 added a uib- prefix to components:

https://github.com/angular-ui/bootstrap/wiki/Migration-guide-for-prefixes

Change: collapse to uib-collapse.

How to comment multiple lines with space or indent

Pressing Ctrl+K+C or Ctrl+E+C After selecting the lines you want to comment will not give space after slashes. you can use multiline select to provide space as suggested by Habib

Perhaps, you can use /* before the lines you want to comment and after */ in that case you might not need to provide spaces.

/*
  First Line to Comment
  Second Line to Comment
  Third Line to Comment      
*/

Referring to the null object in Python

Use f string for getting this solved.

year=None
year_val= 'null' if year is None else  str(year)
print(f'{year_val}')

null

spring autowiring with unique beans: Spring expected single matching bean but found 2

For me it was case of having two beans implementing the same interface. One was a fake ban for the sake of unit test which was conflicting with original bean. If we use

@component("suggestionServicefake")

, it still references with suggestionService. So I removed @component and only used

@Qualifier("suggestionServicefake")

which solved the problem

How can we generate getters and setters in Visual Studio?

You just simply press Alt + Ins in Android Studio.

After declaring variables, you will get the getters and setters in the generated code.

Write a number with two decimal places SQL Server

Use Str() Function. It takes three arguments(the number, the number total characters to display, and the number of decimal places to display

  Select Str(12345.6789, 12, 3)

displays: ' 12345.679' ( 3 spaces, 5 digits 12345, a decimal point, and three decimal digits (679). - it rounds if it has to truncate, (unless the integer part is too large for the total size, in which case asterisks are displayed instead.)

for a Total of 12 characters, with 3 to the right of decimal point.

How to get Map data using JDBCTemplate.queryForMap

You can do something like this.

 List<Map<String, Object>> mapList = jdbctemplate.queryForList(query));
    return mapList.stream().collect(Collectors.toMap(k -> (Long) k.get("userid"), k -> (String) k.get("username")));

Output:

 {
  1: "abc",
  2: "def",
  3: "ghi"
}

how to set ul/li bullet point color?

http://www.w3schools.com/cssref/pr_list-style-type.asp

You need to use list-style-type: to change bullet type/style and the above link has all of the options listed. As others have stated the color is changed using the color property on the ul itself

To create 'black filled' bullets, use 'disc' instead of 'circle',i.e.:

list-style-type:disc

Using msbuild to execute a File System Publish Profile

Still had trouble after trying all of the answers above (I use Visual Studio 2013). Nothing was copied to the publish folder.

The catch was that if I run MSBuild with an individual project instead of a solution, I have to put an additional parameter that specifies Visual Studio version:

/p:VisualStudioVersion=12.0

12.0 is for VS2013, replace with the version you use. Once I added this parameter, it just worked.

The complete command line looks like this:

MSBuild C:\PathToMyProject\MyProject.csproj /p:DeployOnBuild=true /p:PublishProfile=MyPublishProfile /p:VisualStudioVersion=12.0

I've found it here:

http://www.asp.net/mvc/overview/deployment/visual-studio-web-deployment/command-line-deployment

They state:

If you specify an individual project instead of a solution, you have to add a parameter that specifies the Visual Studio version.

How do I get the localhost name in PowerShell?

An analogue of the bat file code in Powershell

Cmd

wmic path Win32_ComputerSystem get Name

Powershell

Get-WMIObject Win32_ComputerSystem | Select-Object -ExpandProperty name

and ...

hostname.exe