text:
Q: Appending to JSON array in Ruby I am looking to append to a JSON array in ruby. The JSON array looks like this:
{"data" : [{"name":"Chris","long":10,"lat":19}, {"name":"Scott","long":9,"lat":18}]}
I want to be able to append another object to this array e.g
{"name":"John","long":20,"lat":45}
How can I do this?

A: If you want to append existing hash, we can do as below-
hash = {}

I have another hash as-
sub_hash = {}

then-
hash.merge!(sub_hash)

will work great!!!

A: First convert the JSON to a Ruby hash this way:
require 'json'
rb_hash = JSON.parse('<your json>');
rb_hash["data"] << { name: "John", long: 20, lat: 45 }

rb_hash.to_json


text:
Q: Issue installing scikit-learn-0.14.1 on Mac 10.9.2 I'm getting the following error following pip install -U scikit-learn.  Any ideas are greatly appreciated.  Thanks!
error: Command "c++ -fno-strict-aliasing -fno-common -dynamic -arch x86_64
  -arch i386 -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv
  -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wshorten-64-to-32
  -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE
  -arch x86_64 -arch i386 -pipe
  -I/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/core/include
  -c sklearn/svm/src/libsvm/libsvm_template.cpp
  -o build/temp.macosx-10.9-intel-2.7/sklearn/svm/src/libsvm/libsvm_template.o"
  failed with exit status 1

A: You could try using easy_install instead. This blog post covers the steps to get through installing scikit-learn  on MacOSX.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django-Entangled multiple data in JsonField Working with django JsonField. Using django-entangled in form. I need data format like below. Need suggestion to avail this.
[
  {
    "name": "Test 1",
    "roll": 1,
    "section": "A"
  },
  {
    "name": "Test 2",
    "roll": 2,
    "section": "A"
  }
]

A: With django-entangled this is not possible, because that library does not offer multiple forms of the same kind.
You can however try my next form library django-formset, which can handle multiple forms of the same kind.


text:
Q: how to syncronize cordova and android studio for debugging? I have latest version of android studio and android sdk, but I always get gradle version error
commnad: "cordova run android"
so I can't run on device but I can run it on android studio with gradle updating.
what's the problem.

A: you should delete node-modules folder first and rebuild node-modules using packages.json file
{
  "name": "Your app name",
  "version": "1.1.0",
  "description": "Renelco FSE for Android 6.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "platforms": [
    "ios",
    "android"
  ],
  "cordovaPlatforms": [
    "android@6.0.1"
  ],
  "cordovaPlugins": [
    "cordova-plugin-camera@1.1.0",
    "cordova-plugin-contacts@1.1.0",
    "cordova-plugin-device@1.0.1",
    "cordova-plugin-file@2.1.0",
    "cordova-plugin-media@1.0.1",
    "cordova-plugin-media-capture@1.0.1",
    "cordova-plugin-network-information@1.0.1",
    "cordova-plugin-splashscreen@2.1.0",
    "cordova-plugin-statusbar@1.0.1",
    "cordova-plugin-vibration@1.2.0",
    "com.ionic.keyboard@1.0.5"
  ],
  "devDependencies": {
    "load-grunt-tasks": "~0.4.0",
    "time-grunt": "~0.3.1",
    "grunt": "~0.4.4",
    "grunt-shell": "~0.6.4"
  },
  "dependencies": {}

}


text:
Q: How do I calculate box bound collision between two scaled items in openGL? Both of the items are using different scales (e.g. item 1 = gl.glScalef(.25f, .25f, 1f) where as item 2 = gl.glScalef(.10f, .10f, 1f))
For detecting the collision between the two items, am I correct in assuming for the width and height values I use the scaled values ?? e.g. for item 1, the width is .25f?

A: I would transform the coordinates and sizes to world versions, and then use them to check for collisions, that way a simple transformation to convert from local to world coordinates (examples available here) and calculate sizes based on world dimenensions and you should be fine.
Let me know if you need more information:)


text:
Q: What's the difference between the different "rename" commands? Since Ubuntu 14.04 there are at least three rename commands:

*

*rename provided by the util-linux package, see man rename.ul

*rename provided by the perl package, see man prename

*rename provided by the rename package, see man file-rename
Questions:

*

*What exactly are the differences between those commands?

*How come there are multiple packages providing different commands using the same name – I suppose that's not an accident, or is it?

*Wouldn't it be rather straightforward for the perl package to either include the "full" rename command or not include any rename command at all? Why is this seemingly uncomplete split sustained until at least Ubuntu 17.04?

This question has already been asked on U&L (as I found out later):
What's with all the renames: prename, rename, file-rename?

A:
How come there are two packages providing different commands using the same name (if not by accident)?

That's not unusual. Authors typically pick the simplest command name they think of, so if two people write a command to rename files, it's likely they'll both name it rename. That's one of the reasons behind the Debian Alternatives system - it allows packages providing similarly-named commands to coexist, and for one package to replace another. For example, there are multiple AWK implementations - mawk, original-awk, gawk (though they all refer to themselves as awk). With the alternatives system, you can install them all at the same time, and conveniently switch between any of them as the default awk.
In this specific case, prename comes from the Perl source code. The Debian package maintainers originally had rename be the Perl one, then switched to the alternatives system, to accommodate the rename from util-linux. Then somebody wrote an improved version of Perl's rename in the File-Rename Perl module, which was then added as another alternative. But that's not even the only Perl module for renaming files.

Wouldn't it be rather straightforward for the perl package to either include the "full" rename command or not include any rename command at all? Why is this seemingly uncomplete split sustained until at least Ubuntu 17.04?

See Debian bug #735134 for how this situation evolved. Debian maintainers generally prefer going at least one release when doing something drastic, like replacing a working command with another. prename was kept around for jessie, and has now been removed for buster. In addition, it looks like rename will no longer be under the alternatives system, since rename.ul is too incompatible. rename will be just file-rename.
Since Ubuntu generally picks up packaging changes from Debian, what happens to rename in Debian will be picked up by Ubuntu sooner or later, probably in 18.04. It seems to be too late for 17.10.

What exactly are the differences between those commands?

Fundamentally, both prename and file-rename run Perl expressions to rename files. file-rename is just actively maintained and supports more options. rename from util-linux works entirely differently, has its own rules for patterns.


text:
Q: Do all hypotheticals use "were" or just counter-factual hypothetheticals I understand that all hypotheticals that are counterfactual use "Were" because of the subjunctive mood.

*

*If I were President, I would enact a great number of new policies.
  (It's counterfactual because I am not president, right?)

I'm not sure what to do if there is a good possibility of it happening; do I still use "were"?

*If I was/were going to the store tonight, I'd be sure to pick up milk.
  (It's not nearly as impossible as the first example)

*If he was/were at the mall with you guys, I didn't see him
  (I'm not sure at all about ones like this)

A: [WARNING: In what follows I discuss usage in "actualization" conditionals—conditionals like your examples, which assert that if the event put forward in the condition occurs then the event put forward in the consequence occurs subsequently. Usage is more complicated in "inference" conditionals—conditionals which assert that the truth of the proposition put forward in the condition entails the proposition put forward in the consequence.]
There is more to this than a was/were distinction.
In this sort of non-past conditional if I was is a widespread colloquial variant of if I were, not a contrasting construction. The contrasting constructions are:

*

*counterfactual I was/were and factual I am in the protasis (if clause, condition clause), and

*counterfactual I would and factual I will in the apodosis (then clause, consequence clause).

Other things being equal, a non-past open condition—a condition whose factuality is not known—and its consequence are both expressed with the ordinary indicative form; the if is all that is needed to express the uncertainty.

NON-Counterfactual: If I am ... I will

BUT: In this case other things are NOT equal: your use of BE going to in the protasis introduces another twist. You may know already that futurive will is rarely used in the protasis, and the same thing is true of BE going to. These futurives† are not used to express an open condition:

∗ If I will go to the store tonight, I will be sure to pick up milk.
∗ If I am going to the store tonight, I will be sure to pick up milk.

Specifically, these futurives are used only to express a closed condition: a condition known to be factual, or accepted as factual for the discussion at hand.

okIf, as you tell me, I am going to the store tonight, I will be sure to pick up milk.
okIf, as you tell me, I am going to the store tonight, I will be sure to pick up milk.

You appear to specify, however, a situation in which the factuality of your going to the store is open. In that situation you employ a simple present in the protasis, with inferred future reference.

If I go to the store tonight, I will be sure to pick up milk.

† Here and subsequently I specify futurive uses, because will (but not BE going to) has a couple of non-futurive uses which are permitted in the protasis: it may be used to express willingness or assent ("If you will pick up the beer, I'll bring chips") or, with strong emphasis, to express habitual obstinacy ("If you will keep teasing the cat you can't complain if she scratches you").

A: Here are the answers:
If I were going to the store tonight, I'd be sure to pick up milk. (It's not nearly as impossible as the first example)
If he was at the mall with you guys, I didn't see him. (I'm not sure at all about ones like this)
The first one is counterfactual and takes "were" despite the possibility as you put it in such with your construction.  The second one is talking about something that possibly occurred in the past; therefore, "was" is correct.
Here is how you could make it subjunctive, but it would change the meaning:
"If he were at the mall with you guys, I wouldn't see him (because I wouldn't be at the mall to see him).
This one talks about something that is either happening now or in the near future, but is counterfactual; it does not mean the same thing as your example.


text:
Q: lightdm/unity-greeter wallpaper will not set I am trying to set the wallpaper on my login screen, but i cant seem to get anything to stick.  I have used gsettings set com.canonical.unity-greeter background '/path/to/pic.jpg' as user 'lightdm'. However, i then get the output (process:6517): dconf-CRITICAL **: unable to create directory '/run/user/1000/dconf': Permission denied.  dconf will not work properly. Any ideas? Thanks

A: I found a solution.  Though it displays an error message, the lightdm background does in fact change to whatever new background image you set.
Open a terminal and get root
sudo -i

(Type sudo password)
Allow the user lightdm to create a connection to the X server
xhost +SI:localuser:lightdm

Switch user to lightdm.  I had to use sudo to do this, other guides do not do so.
sudo su lightdm -s /bin/bash

Make sure you have turned off the option to dynamically change lightdm's background to match the user's desktop background.
gsettings set com.canonical.unity-greeter draw-user-backgrounds 'false'

Finally, set your desired lightdm background.
gsettings set com.canonical.unity-greeter background '/path/to/your/background.png'

This returns an error about dconf, ignore it. The new lightdm background should be present when you log out.  To double check, you can run
exit

twice, once to get out of lightdm and once to get out of root.  Then run
gsettings get com.canonical.unity-greeter background

Which should return the path of the image you chose.  Similarly, running
dconf-editor

Gets you to a nice GUI.  Choosing the drop-down for com, then canonical, then unity-greeter lets you check the path of lightdm's background image, and should allow you to edit it as well but I was never able to make a valid change from there.
Hope this helps.
EDIT: running
gsettings get com.canonical.unity-greeter background

after logging out does NOT return the new image path, but when lightdm is next used, the correct new image is set.  I know there's a way to run lightdm in test mode, which may be a more accurate way to test if the new background is set. I did not test that method, as the above method I used to change the background image worked for me.


text:
Q: Error when trying to RSA-decrypt a parameter string with libcrypto I am a beginner with the libcrypto library. I am trying to give an encrypted string to a function, decrypt it and return it decrypted. The string is encoded with my public key which which is 4096-bit sized.
char* decodeStr(const char* str, const size_t sizeStr)
{
    puts("Starting");
    FILE* file = fopen(PRIVATE_KEY_PATH, "r");
    if (file == NULL)
    {
        perror("Error while trying to access to Presto's private key.\n");
        return NULL;
    }

    RSA *privateKey = RSA_new();
    privateKey = PEM_read_RSAPrivateKey(file, &privateKey, NULL, NULL);
    if (privateKey == NULL)
    {
        fprintf(stderr, "Error loading RSA private key.\n");
        ERR_print_errors_fp(stderr);
        return NULL;
    }
    char* res = malloc(sizeStr);
    if (res == NULL)
    {
        perror("Memory allocating error ");
        return NULL;
    }
    const int sizeDecoded = RSA_private_decrypt(sizeStr, str, res, privateKey, RSA_PKCS1_PADDING);
    if (sizeDecoded == -1)
    {
        fprintf(stderr, "Error while decoding RSA-encoded wrapping key.\n");
        ERR_print_errors_fp(stderr);
        return NULL;
    }
    if ((res = realloc(res, (size_t)sizeDecoded)) == NULL)
    {
        perror("Memory allocating error ");
        return NULL;
    }
    return res;

}

The following code outputs :
Starting
Error while decoding RSA-encoded wrapping key.
6928:error;04069506C:lib<4>:func<101>:reason<108>:.\crypto\rsa\rsa_eay.c:518:

Since the error is unknown and I haven't been able to find any information about it on the net, and moreover I am a beginner with libcrypto, does strneed to be in a certain format ?
Obivously it is this which breaks the program but I can't be sure of it, neither do I know how to fix this.
const int sizeDecoded = RSA_private_decrypt(sizeStr, str, res, privateKey, RSA_PKCS1_PADDING);

EDIT : I have been working with a client  which provides me those encoded dat for me to decrypt them. I don't know how they are processed exactly. Unfortunately, the encoded strings are even more sensitive than the private key itself, so I can't share it. It looks like 0c79cc00deb89a614db6ebe42be748219089fb5356 but with 1024 characters.

A: The problem
Your encoded strings
0c79cc00deb89a614db6ebe42be748219089fb5356 but with thousands of characters.
look like hexadecimal representation of the encoded message. I think you really need to convert the message to a raw data, converting hex to bytes.
Your strings are composed by 1024 (hex) chars => 512 bytes (you need two hex digits to represent one byte) => 4096 bits, which is equal to the key length.
Try this simple function.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

void hex_2_bytes(uint8_t *des, char *source, size_t size);

int main()
{
                char *str = "0c79cc00deb89a614db6ebe42be748219089fb5356";
                uint8_t *dest = (uint8_t *) malloc(sizeof(uint8_t) * strlen(str) / 2);
                hex_2_bytes(dest, str, strlen(str));
                for(int i = 0; i < strlen(str) / 2; i++) {
                                printf(" %02X ", dest[i]);
                }
                return 0;
}

void hex_2_bytes(uint8_t *des, char *source, size_t size) {
                for(int i = 0; i < size - 1; i+=2) {
                                sscanf(source+i, "%02x", des + (i/2));
                }
}

What is raw data? Your encrypted message is a string, which is an array of characters. I see only digits (from 0 to 9) and the letters from a to f, which make me guess that your original message (which is, originally a binary string, raw data) has been represented as a very long number using hexadecimal digits. You need to convert it back.
If you have a message composed by n bytes, stored as a binary string (raw data), you will have an hexadecimal representation, stored as a text, which is 2*n bytes long.
Example:
uint8_t raw_data_message[] = {0x3c, 0x2f};  // 2 bytes
char hex_representation_as_string_message[] = {'3', 'c', '2', 'f'}; // 4 bytes

Your messages a like hex_representation_as_string_message, but you need them as raw_data_message.
The solution
Here's a fully working example:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <openssl/pem.h>
#include <openssl/err.h>

#define PRIVATE_KEY_PATH ".ssh/id_rsa"

/*
 * Generation of the encrypted message:
 * echo "Hello, this is a super secret message" | openssl rsautl -encrypt -pubin -inkey ~/.ssh/id_rsa.pub.pem >message.encrypted
 *
 * Resulting encrypted message in hex representation:
 * 917ab2ebd663bba1dcd0f22aef98b93b039f001e19c997f015d90eaaf35731eb1895c13dfb08250aa28a9dac4f3e1b5fefc53926d3f6422f8055124bb15c24e2b73645dc61f29486deaf278705987738e916a6288531aa923dff15b667dabf4465506e1ee68e6f27a06e3fb4f5040a7775ce69ba10ec337f5bc5ef45969a8fe7c672c9b51243296677385f1b613f4f3edceef620f6ab5dcadec5034c330331bf8e8c3b42554f01c6cf1c0dbc58f23c8f0068e750fc4bb97636b2b3455e7f3932ab9559ff4de5bfc6769bbafefec722441458066ab4a6fdfe99c78bfdd5c1851d411a451925c5ad7ecb0c93618304ae6bc5402193f58af6e6a65208075be35a00
 * (converted with: hexdump -ve '1/1 "%.2x"' message.encrypted)
 */

void hex_2_bytes (uint8_t *des, char *source, size_t size);

int decode (uint8_t *dest, const uint8_t *src, const size_t size);

int main (int argc, char **argv) {
    // Reading the encrypted message in hex representation
    FILE *file = fopen(argv[1], "r");
    printf("%s\n", argv[1]);
    if (file == NULL) {
        perror("Error while trying to access to the encrypted message"
                       ".\n");
        return -1;
    }
    fseek(file, 0, SEEK_END);
    long fsize = ftell(file);
    fseek(file, 0, SEEK_SET);
    char *hex_repr = malloc(fsize);
    fread(hex_repr, fsize, 1, file);
    fclose(file);

    printf("Hexadecimal representation of the encrypted message\n");
    for (int i = 0; i < fsize; ++i) {
        printf("%c", hex_repr[i]);
    }
    printf("\nSize: %d\n", fsize);

    // Converting to raw data
    size_t raw_data_size = fsize / 2;
    uint8_t *raw_data = (uint8_t *) malloc(
            raw_data_size * sizeof(uint8_t));
    hex_2_bytes(raw_data, hex_repr, (size_t) fsize);
    printf("Raw encrypted message\n");
    for (int i = 0; i < raw_data_size; ++i) {
        printf("%02X", raw_data[i]);
    }
    printf("\nSize: %d\n", raw_data_size);

    // Decryption
    char *res = malloc(raw_data_size * sizeof(char));
    if (res == NULL) {
        perror("Memory allocating error ");
        return -1;
    }
    int msg_size = decode(res, raw_data, raw_data_size);
    printf("Decrypted message:\n");
    for (int j = 0; j < msg_size; ++j) {
        printf("%c", res[j]);
    }
    printf("\nSize: %d\n", msg_size);

    return 0;
}

void hex_2_bytes (uint8_t *des, char *source, size_t size) {
    for (int i = 0; i < size - 1; i += 2) {
        sscanf(source + i, "%02x", des + (i / 2));
    }
}

int decode (uint8_t *res, const uint8_t *src, const size_t size) {
    puts("Starting");
    FILE *file = fopen(PRIVATE_KEY_PATH, "r");
    if (file == NULL) {
        perror("Error while trying to access to Presto's private key.\n");
        return -1;
    }

    RSA *privateKey = RSA_new();
    privateKey = PEM_read_RSAPrivateKey(file, &privateKey, NULL, NULL);
    if (privateKey == NULL) {
        fprintf(stderr, "Error loading RSA private key.\n");
        ERR_print_errors_fp(stderr);
        return -1;
    }
    const int sizeDecoded = RSA_private_decrypt(size, src, res,
                                                privateKey,
                                                RSA_PKCS1_PADDING);
    if (sizeDecoded == -1) {
        fprintf(stderr,
                "Error while decoding RSA-encoded wrapping key.\n");
        ERR_print_errors_fp(stderr);
        return -1;
    }
    return sizeDecoded;
}

And the results (as a proof of work):

Note that I'm using 2048 bit rsa keys.

A: I solved part of the issue. I added :
/* Load the human readable error strings for libcrypto */
    ERR_load_crypto_strings();

At the beginning of the function. The output turned into :
Starting
Error while decoding RSA-encoded wrapping key.
1124:errir:0406506C:rsa routines: RSA_EAY_PRIVATE_DECRYPT:data greater than mod len:.\crypto\rsa\rsa_eay.c:518:

Which I guess means that the length of the key is too small for the provided data. Still left to know if the data is wrong, the key is wrong and how to fix it.
Also, to avoid making such mistakes later, I added :
const size_t sizeRSA = RSA_size(prestoPrivateKey);
if (sizeRSA < sizeWrappingKey)
{
    fprintf(stderr, "Size of key : %d\n Size of data : %d\n The size of the key should higher than data length.\n", sizeRSA, sizeWrappingKey);
    return NULL;
}


text:
Q: VBA Nested IF compare statement Hi I am newbies about vba. I want to compare and count the cell number that continuously lowers the previous cell however the code just successfully counts 1-2 days and n/a only.
Thanks
data set
  Sub Mars()
   Dim i As Integer
   Sheets("working").Select
   For i = 2 To 111
       If Range("U" & i).Value > Range("T" & i).Value Then
           Range("W" & i).Value = "n/a"
       ElseIf Range("U" & i).Value < Range("T" & i).Value Then
           Range("W" & i).Value = "1"
       ElseIf Range("U" & i).Value < Range("T" & i).Value < Range("S" & i).Value Then
           Range("W" & i).Value = "2"
       ElseIf Range("U" & i).Value < Range("T" & i).Value < Range("S" & i).Value < Range("R" & i).Value Then
           Range("W" & i).Value = "3"
       ElseIf Range("U" & i).Value < Range("T" & i).Value < Range("S" & i).Value < Range("R" & i).Value < Range("Q" & i).Value Then
           Range("W" & i).Value = "4"
       ElseIf Range("U" & i).Value < Range("T" & i).Value < Range("S" & i).Value < Range("R" & i).Value < Range("Q" & i).Value < Range("P" & i).Value Then
           Range("W" & i).Value = "5"
       ElseIf Range("U" & i).Value < Range("T" & i).Value < Range("S" & i).Value < Range("R" & i).Value < Range("Q" & i).Value < Range("P" & i).Value < Range("O" & i).Value Then
           Range("W" & i).Value = "6"
       ElseIf Range("U" & i).Value < Range("T" & i).Value < Range("S" & i).Value < Range("R" & i).Value < Range("Q" & i).Value < Range("P" & i).Value < Range("O" & i).Value < Range("N" & i).Value Then
           Range("W" & i).Value = "7"
       ElseIf Range("U" & i).Value < Range("T" & i).Value < Range("S" & i).Value < Range("R" & i).Value < Range("Q" & i).Value < Range("P" & i).Value < Range("O" & i).Value < Range("N" & i).Value < Range("M" & i) Then
           Range("W" & i).Value = "8"
       ElseIf Range("U" & i).Value < Range("T" & i).Value < Range("S" & i).Value < Range("R" & i).Value < Range("Q" & i).Value < Range("P" & i).Value < Range("O" & i).Value < Range("N" & i).Value < Range("M" & i) < Range("L" & i).Value Then
           Range("W" & i).Value = "9"
       ElseIf Range("U" & i).Value < Range("T" & i).Value < Range("S" & i).Value < Range("R" & i).Value < Range("Q" & i).Value < Range("P" & i).Value < Range("O" & i).Value < Range("N" & i).Value < Range("M" & i) < Range("L" & i).Value < Range("K" & i).Value Then
           Range("W" & i).Value = "10"
       ElseIf Range("U" & i).Value < Range("T" & i).Value < Range("S" & i).Value < Range("R" & i).Value < Range("Q" & i).Value < Range("P" & i).Value < Range("O" & i).Value < Range("N" & i).Value < Range("M" & i) < Range("L" & i).Value < Range("K" & i).Value < Range("J" & i).Value Then
           Range("W" & i).Value = "11"
       ElseIf Range("U" & i).Value < Range("T" & i).Value < Range("S" & i).Value < Range("R" & i).Value < Range("Q" & i).Value < Range("P" & i).Value < Range("O" & i).Value < Range("N" & i).Value < Range("M" & i) < Range("L" & i).Value < Range("K" & i).Value < Range("J" & i).Value < Range("I" & i).Value Then
           Range("W" & i).Value = "12"
       ElseIf Range("U" & i).Value < Range("T" & i).Value < Range("S" & i).Value < Range("R" & i).Value < Range("Q" & i).Value < Range("P" & i).Value < Range("O" & i).Value < Range("N" & i).Value < Range("M" & i) < Range("L" & i).Value < Range("K" & i).Value < Range("J" & i).Value < Range("I" & i).Value < Range("H" & i).Value Then
           Range("W" & i).Value = "13"
       ElseIf Range("U" & i).Value < Range("T" & i).Value < Range("S" & i).Value < Range("R" & i).Value < Range("Q" & i).Value < Range("P" & i).Value < Range("O" & i).Value < Range("N" & i).Value < Range("M" & i) < Range("L" & i).Value < Range("K" & i).Value < Range("J" & i).Value < Range("I" & i).Value < Range("H" & i).Value < Range("G" & i).Value Then
           Range("W" & i).Value = "14"
       ElseIf Range("U" & i).Value < Range("T" & i).Value < Range("S" & i).Value < Range("R" & i).Value < Range("Q" & i).Value < Range("P" & i).Value < Range("O" & i).Value < Range("N" & i).Value < Range("M" & i) < Range("L" & i).Value < Range("K" & i).Value < Range("J" & i).Value < Range("I" & i).Value < Range("H" & i).Value < Range("G" & i).Value < Range("F" & i).Value Then
           Range("W" & i).Value = "15"
       ElseIf Range("U" & i).Value < Range("T" & i).Value < Range("S" & i).Value < Range("R" & i).Value < Range("Q" & i).Value < Range("P" & i).Value < Range("O" & i).Value < Range("N" & i).Value < Range("M" & i) < Range("L" & i).Value < Range("K" & i).Value < Range("J" & i).Value < Range("I" & i).Value < Range("H" & i).Value < Range("G" & i).Value < Range("F" & i).Value < Range("E" & i).Value Then
           Range("W" & i).Value = "16"
       ElseIf Range("U" & i).Value < Range("T" & i).Value < Range("S" & i).Value < Range("R" & i).Value < Range("Q" & i).Value < Range("P" & i).Value < Range("O" & i).Value < Range("N" & i).Value < Range("M" & i) < Range("L" & i).Value < Range("K" & i).Value < Range("J" & i).Value < Range("I" & i).Value < Range("H" & i).Value < Range("G" & i).Value < Range("F" & i).Value < Range("E" & i).Value < Range("D" & i).Value Then
           Range("W" & i).Value = "17"
       ElseIf Range("U" & i).Value < Range("T" & i).Value < Range("S" & i).Value < Range("R" & i).Value < Range("Q" & i).Value < Range("P" & i).Value < Range("O" & i).Value < Range("N" & i).Value < Range("M" & i) < Range("L" & i).Value < Range("K" & i).Value < Range("J" & i).Value < Range("I" & i).Value < Range("H" & i).Value < Range("G" & i).Value < Range("F" & i).Value < Range("E" & i).Value < Range("D" & i).Value < Range("C" & i).Value Then
            Range("W" & i).Value = "18"
       ElseIf Range("U" & i).Value < Range("T" & i).Value < Range("S" & i).Value < Range("R" & i).Value < Range("Q" & i).Value < Range("P" & i).Value < Range("O" & i).Value < Range("N" & i).Value < Range("M" & i) < Range("L" & i).Value < Range("K" & i).Value < Range("J" & i).Value < Range("I" & i).Value < Range("H" & i).Value < Range("G" & i).Value < Range("F" & i).Value < Range("E" & i).Value < Range("D" & i).Value < Range("C" & i).Value < Range("B" & i).Value Then
           Range("W" & i).Value = "19"
       End If
   Next I
 End Sub

A: In your code, the're a lot of this construction:
IF A < B < C < ...

This is not correct, it should be:
IF (A < B) AND (B < C) AND (C < ...) ...

For readability reasons, I would advise you the following formatting:
IF (A < B) AND_
   (B < C) AND_
   (C < ...) ...

(The underscore means that the "source code line" is not finished and continues on the next line.)


text:
Q: How to Deserialize Json Object - C# A web service returns JSON object as blew:
JsonString = "{"d":"[{\"sname\":\"S1\",\"region\":\"R1\",\"name\":\"Q1\"},{\"sname\":\"S2\",\"region\":\"R2\",\"name\":\"Q2\"}]"}"

I tried to Deserialize by doing this:

*

*Define the objects
public class RootResponseClass
{
    public ResponseParametersClass[] d { get; set; }
}

public class ResponseParametersClass
{
    public string sname { get; set; }
    public string region { get; set; }
    public string name { get; set; }
}

*Write the Deserialize Method
 JavaScriptSerializer ser2 = new JavaScriptSerializer();

 RootResponseClass obj = new RootResponseClass();

 obj = ser2.Deserialize<RootResponseClass>(JsonString);

But It is gives error "Cannot convert object of type 'System.String' to type 'NAS.Helpers.ResponseParametersClass[]", So how can i do it!
Solution
 public class RootResponseClass
    {
        public string d { get; set; }
    }

And for deserialize method :
JavaScriptSerializer ser2 = new JavaScriptSerializer();
RootResponseClass obj = new RootResponseClass();
obj = ser2.Deserialize<RootResponseClass>(JsonString);

List<ResponseParametersClass> obj2 = new List<ResponseParametersClass>();
obj2 = ser2.Deserialize<List<ResponseParametersClass>>(obj.d.ToString());

A: You can use the package using Newtonsoft.Json; for deserializing JSON
example
JsonString = "{"d":"[{\"sname\":\"S1\",\"region\":\"R1\",\"name\":\"Q1\"},{\"sname\":\"S2\",\"region\":\"R2\",\"name\":\"Q2\"}]"}";

var foo = JsonConvert.DeserializeObject<RootResponseClass>(JsonString);

foo is your deserialized object.
EDIT
As extra information why the initial way is not working is because your array is starting with quotes so its recognized as a string. After the "{"d": should be just [] instead of "[]"
Thanx Dnomyar96 for pointing that extra out.

A: Your Json string seems to contain another Json string. So in order to deserialize this, you'd need to deserialize as you're doing now, but change the ResponseParametersClass to string.
Then you'd need to deserialize the string you just got (as a List<ResponseParametersClass>). So in this case you'd need to deserialize in two seperate steps.


text:
Q: "With what" question! Can you give me the answer for this interrogative sentence?

"With what are you marked?"
"I am marked with white powder."

Is it grammatically correct? I have seen questions such as "to whom are you talking?" But this is the first time I see the question above.

A: It's grammatically okay to say so but remember that putting the word with at the end of the sentence would be better but as i said it's okay.see
With what are you painting the house? or What are you painting the house with?
as you see second one is more used in English.

A: It's grammatically correct, strictly speaking you should never end a sentence with a preposition. However, in general speech native speakers wouldn't usually use the "With what are you marked?" construction. We would say "What are you marked with?" even though it's incorrect grammar.

A: "What are you marked with?"
"White powder."
I believe that's what you're looking for. I may be wrong.


text:
Q: Incorrect time in Eclipse. How to change it? No idea why, but my Eclipse v 3.5.2 (that I use for Android development) seems to have the wrong time.
Logs in the LogCat window are a few days out. And more annoyingly if I do a Calendar.getInstance(), it will return that same wrong date/time.
I'm on Windows 7 64bit and my system HAS the correct time!
Any idea if this is configurable somewhere?
Thanks in advance!

A: What you see in the logcat is the time on your device/emulator, not the computers time. If you use an emulator, chances are that it has the wrong time.
Just go to the device/emulators preferences as you would do on a real phone and set the correct time (usually start at the homescreen, press the menu key, select Preferences -> Date and Time). This should solve the issue.


text:
Q:  sent with POST header we are using an payment extension that sends a POST response if the transaction was successful. For some reason the string contains some none UTF-8 characters.
The response looks like this OK The right resposne is OK
I have the same payment extension in other shop (different customer and server) and there the extension is working perfectly.
Does anyone have any experience what could be causing this change in the response?  I talked with the developers of the extension but they say it has to be something on the server side. I checked the encoding on server and its UTF-8.
I checked the response with Chrome extension Postman and the response comes without the strange characters - "OK".
I have no idea left what could be causing this change in response string. Where could be the  generated?
Thanks for any hints.

A: What you are currently seeing  is the Byte Order Mark. This happens when you display a UTF-8 response without the correct encoding. Depending on how you display the response you might be able to force UTF-8 decoding in your browser by adding header('Content-Type:text/html; charset=UTF-8'); before your output or an echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
In summary: I don't think there is an issue with the response itself just the way the content is interpreted.


text:
Q: Is localStorage/sessionStorage considered NoSQL database? according to https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API , there are essentially two Web Storage APIs, localStorage and sessionStorage, they are used to store key/value pairs.
And I learned that according to https://aws.amazon.com/nosql/key-value/

A key-value database is a type of nonrelational database that uses a
  simple key-value method to store data.

So my question is, is localStorage/sessionStorage considered NoSQL database?

A: No it's not a database. It's just a variable associated to the window object. In the AWS text, it says "a key value database is a...", but a variable is not a database.


text:
Q: How to measure Polyline with fabric.js? I would like to measure a polyline with fabric js (or regular js). So far I can draw the polyline but it only measures the distance from the mousedown to the mouseup rather than measuring the entire line distance. For example if I was to draw a circle it would return '0' for the distance because the start and end vertices are the same, whereas I would like to have measured the circle circumference. Here is the code:
                    var Calculate = {
                        lineLength: function (x1, y1, x2, y2) {
                            return normalizedSize * (Math.sqrt(Math.pow(x2 * 1 - x1 * 1, 2) + Math.pow(y2 * 1 - y1 * 1, 2)));
                        }
                    }

A: Fabric.Polyline.points contains all the points that are defining your polyline.
Instead of measuring with the mouse cursor, add the new point to the polyline and then do the calculation based on poins:
var Calculate = {
    lineLength: function (line) {
        var distance = 0;
        for (var i=0; i < line.points.length - 1; i++) {
            var p1 = line.points[i];
            var p2 = line.points[i + 1];
            distance += normalizedSize * (Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2)));
        }
        return distance;
    }
}

This should calculate the line distance correctly.


text:
Q: Kafka SSL handshake failed in custom Java producer Trying to produce some data using my Kafka producer application, but i get below error:

[SocketServer brokerId=0] Failed authentication with localhost/127.0.0.1 (SSL handshake failed) (org.apache.kafka.common.network.Selector)

I use SASL_SSL protocol with PLAIN mechanism to communicate with Kafka. When I use kafka-console-producer
sh kafka-console-producer.sh --broker-list localhost:9093 --topic kafka-topic --producer.config ../config/producer.properties
and kafka-console-consumer
sh kafka-console-consumer.sh --bootstrap-server localhost:9093 --topic kafka-topic --consumer.config ../config/consumer.properties
everything works fine. Here's a part of my server.properties:
listeners=PLAINTEXT://localhost:9092,SASL_SSL://localhost:9093
advertised.listeners=PLAINTEXT://localhost:9092,SASL_SSL://localhost:9093

listener.name.sasl_ssl.plain.sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required \
   username="admin" \
   password="admin-secret" \
   user_admin="admin-secret";

sasl.enabled.mechanisms=PLAIN
sasl.mechanism.inter.broker.protocol=PLAIN
security.inter.broker.protocol=SASL_SSL
ssl.endpoint.identification.algorithm=

authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer

allow.everyone.if.no.acl.found=true

ssl.keystore.location=/mnt/data/kafka/config/keystore/kafka.keystore.jks
ssl.keystore.password=password
ssl.key.password=password
ssl.truststore.location=/mnt/data/kafka/config/truststore/kafka.truststore.jks
ssl.truststore.password=password

ssl.client.auth=required
ssl.enabled.protocols=TLSv1.2,TLSv1.1,TLSv1
ssl.keystore.type=JKS
ssl.truststore.type=JKS
ssl.secure.random.implementation=SHA1PRNG

producer.properties
bootstrap.servers=localhost:9093
sasl.mechanism=PLAIN
security.protocol=SASL_SSL
sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required \
   username="admin" \
   password="admin-secret" \
   user_admin="admin-secret";
ssl.truststore.location=/mnt/data/kafka/config/truststore/kafka.truststore.jks
ssl.truststore.password=password

consumer.properties
bootstrap.servers=localhost:9093
group.id=test-consumer-group
sasl.mechanism=PLAIN
security.protocol=SASL_SSL
sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required \
   username="admin" \
   password="admin-secret" \
   user_admin="admin-secret";

ssl.truststore.location=/mnt/data/kafka/config/truststore/kafka.truststore.jks
ssl.truststore.password=password

And here's my Java Kafka producer application
private KafkaProducer<String, String> producer;
    private String address;
    private final int BATCH_SIZE = 16384 * 4;

    private Properties setProperties() {
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, address);
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        properties.put(ProducerConfig.BATCH_SIZE_CONFIG, BATCH_SIZE);
        properties.put(ProducerConfig.LINGER_MS_CONFIG, 200);
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "snappy");
        properties.put("acks", "all");
        properties.put("sasl.mechanism", "PLAIN");
        properties.put("security.protocol", "SASL_SSL");
        properties.put("sasl.jaas.config", "org.apache.kafka.common.security.plain.PlainLoginModule required username=\"admin\" password=\"admin-secret\" user_admin=\"admin-secret\";");
        properties.put("ssl.truststore.location", "/mnt/data/kafka/config/truststore/kafka.truststore.jks");
        properties.put("ssl.truststore.password", "password");
        return properties;
    }

    public void createTopicWithPartitions(String topicName, int partitionsCount) throws ExecutionException, InterruptedException {
        Properties properties = new Properties();
        properties.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, address);
        AdminClient adminClient = AdminClient.create(properties);

        boolean isTopicExists = adminClient.listTopics().names().get().stream()
                .anyMatch(name -> name.equals(topicName));

        if (isTopicExists) {
            System.out.println("Topic already exists");
        } else {
            NewTopic newTopic = new NewTopic(topicName, partitionsCount, (short) 1);
            adminClient.createTopics(Collections.singleton(newTopic)).all().get();
        }

        adminClient.close();
    }

    public void sendMessages(String topicName, String payload, int messagesCount) {
        for (int i = 0; i < messagesCount; i++) {
            String partitionKey = DataUtils.generateSourceDeviceId(15).toUpperCase();
            producer.send(new ProducerRecord<>(topicName, partitionKey, payload));
        }
    }

    public KafkaMessagesProducer(String address) {
        this.address = address;
        this.producer = new KafkaProducer<>(setProperties());
    }

    public int getBATCH_SIZE() {
        return BATCH_SIZE;
    }

As I described before console producer/consumer works fine, my Java application gets SSL handshake error, but with switched off SASL_SSL protocol my Java app works fine.
UPD: Certificate generation tool used from this website:
https://github.com/confluentinc/confluent-platform-security-tools/blob/master/kafka-generate-ssl.sh

A: I had a problem with createTopicWithPartitions method. I rewrote properties created in setProperties() method by (AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, address)


text:
Q: Short Story About Man Who Seeks Something "Real" or "Natural" I have been looking for this story since 1990.
A man goes about, dissatisfied by his man-made, mechanized life. He decides to try to find something real or natural. He goes as high up in the buildings as he can, but can only see buildings and sidewalks. He goes down into the basement, but can only find more floors down and metal stopping him from finding any earth.
Distraught, he finally decides to go for a walk and ends up in a beautiful park that he's never seen before. It is filled with green grass and flowers and birds and bees. He is overjoyed, until he realizes the bees are mechanical and so are the flowers, etc.
He has a meltdown and the ambulance is called. It arrives and the attendants turn off his switch; he himself was not "real" or "natural".
I found this in a sci-fi anthology.

A: This is "Quest" by Lee Harding.  It was originally published in New Worlds Science Fiction, April 1963.  You can read it at the Internet Archive.  If you read it in an anthology, it may have been Lambda I and Other Stories (1964) (reprinted in 1977).
The protagonist, Harry Johnston, starts out the story asking the Divisional Controller where he can find something not made by man.  He gets no help, so sets out to find something.  He journeys to the base of the city (27 miles down) and finds nothing but city reaching down to the core of the Earth.  He then tries first walking, then taking an air car in search of something other than city.  Finally, he finds a patch of green that turns out to be the Great Park.  He glories in grass, trees, flowers, ants and birds, wandering until he meets the Caretaker.  The Caretaker tries to send him back to his normal life, but as he leaves he tries to pick a rose.  The rose is fake, and it turns out the entire park is fake too.
The story is much as you describe except for the ending; he despairs of finding anything real and tries to kill himself, only to realize he isn't real either just before he is deactivated.


text:
Q: Modificar datos de usuario logueado (PHP + MySQL) Estoy haciendo una web en la que he añadido registros de usuario, y estoy intentando que un usuario ya logueado pueda meterse en su perfil y modificar sus datos de usuario a través de una consulta en la BD, pero me da el siguiente error y no sé como hacerlo exactamente...

Código del formulario para modificar los datos del usuario
<?php
session_start();
    require_once ("navegacion.php");
    require_once ('index.php');

    if (isset($_SESSION['usuario']))
        $mostrarUsuario =$_SESSION['usuario'];
    else {
        header("location:login.php");
    }

    if (isset($_POST['actualizar'])) {

        $controlador = new ControladorUsuario();
        $controlador->actualizar();
    }

    ?>

<!DOCTYPE html>

        <title>Saving Paws</title>
        <meta charset="utf-8">
        <link rel="stylesheet" href="css.css">

        <form method="POST" id="registro">

                    <form class="register-form">

Modificar datos de usuario

                        <input type="text" placeholder="Nombre" id="nombre" name="nombre_a" required="" />

                        <input type="text" placeholder="Apellidos" id="apellidos" name="apellidos_a" required=""/>

                        <input type="password" placeholder="Contraseña" id="contraseña" name="password_a" required=""/>

                        <input type="text" placeholder="Dirección" id="direccion" name="direccion_a" required=""/>

                        <input type="text" placeholder="Ciudad" id="ciudad" name="ciudad_a" required=""/>

                        <input type="email" placeholder="Correo electrónico" id="email" name="email_a" required=""/>

                        <input  type="number" id="telefono" placeholder="Teléfono" name="numero_a" required=""/>

                        <input type="submit" value="Actualizar" name="actualizar" id="botones"/>
                    </form>

Este es el código donde tengo las clases y esta es la función de registro, donde creo la variable de inicio de sesión:
class ControladorUsuario {

    public function registro() {
        require 'config.php';
        if (isset($_POST['registrarse'])) { //si has pulsado el boton de registrarse
            $name_reg = $_POST['name_reg'];
            $lastname_reg = $_POST['lastname_reg'];
            $email_reg = $_POST['email_reg'];
            $password_reg = $_POST['password_reg'];
            $password_regconf = $_POST['password_regconf'];
            $direction_reg = $_POST['direction_reg'];
            $city_reg = $_POST['city_reg'];
            $number_reg = $_POST['number_reg'];

            //para saber si el usuario que se va a registrar existe:
            $existente = $base->query("SELECT * FROM usuario WHERE email='$email_reg'");
            //busca en la tabla de usuarios si ya existe el email que se intenta registrar
            if ($existente->rowCount() > 0) { //si da un nº de filas superior a 0, significa que ya esta este email
                echo 'Ya existe el email';
            } else if ($password_reg != $password_regconf) { //comprueba que la pass sea igual
                echo 'Las contraseñas no coinciden';
            } else {
                try {
                    $nuevoUsuario = $base->prepare("INSERT INTO usuario(nombre, apellidos, email,
            password, direccion, ciudad, telefono) VALUES (:name_reg, :lastname_reg, :email_reg,
            :password_reg, :direction_reg, :city_reg, :number_reg)");
                    $nuevoUsuario->bindParam(':name_reg', $name_reg, PDO::PARAM_STR, 40); //significa q sera string
                    $nuevoUsuario->bindParam(':lastname_reg', $lastname_reg, PDO::PARAM_STR, 20);
                    $nuevoUsuario->bindParam(':email_reg', $email_reg, PDO::PARAM_STR, 30);
                    $nuevoUsuario->bindParam(':password_reg', $password_reg, PDO::PARAM_STR, 10);
                    $nuevoUsuario->bindParam(':direction_reg', $direction_reg, PDO::PARAM_STR, 60);
                    $nuevoUsuario->bindParam('city_reg', $city_reg, PDO::PARAM_STR, 25);
                    $nuevoUsuario->bindParam(':number_reg', $number_reg, PDO::PARAM_INT, 15);

                    $nuevoUsuario->execute();
                } catch (PDOException $error) {//si hay algun error imprime:
                    print 'ERROR' . $error->getMessage();
                    echo 'Error al registrarse, intentalo de nuevo';
                    print 'ERROR' . $error->getMessage();
                }

//muestra el ultimo registro añadido a la bd
                $lastInsertId = $base->lastInsertId();
                if ($lastInsertId > 0) {

                    echo "
 Bienvenido $name_reg
";
                } else {
                    echo "
 No se ha podido agregar
";

                    print_r($nuevoUsuario->errorInfo());
                }
            }
        } else {
            echo "Función POST no ejecutada";
        }
    }

    public function login() {
        require 'config.php';

        $sql = "SELECT * FROM usuario WHERE email= :email AND password= :password";

        $resultado = $base->prepare($sql);

        $email = htmlentities(addslashes($_POST["email"]));

        $password = htmlentities(addslashes($_POST["password"]));

        $resultado->bindValue(":email", $email);

        $resultado->bindValue(":password", $password);

        $resultado->execute();

        $numero_registro = $resultado->rowCount(); //creamos variable

        if ($numero_registro != 0) { //si el usuario si existe en nuestra bd inicia sesion
            session_start();

            $_SESSION["usuario"] = $resultado->fetch(PDO::FETCH_OBJ); //almacenamos en la variable super global sesion el login del usuario

 /*           if (!isset($_SESSION['usuario'])){

            }*/

            header("location:portada.php"); //redirige a menu de users registrados si esta todo correcto
        } else {
            echo 'datos incorrectos';
            header("location:login.php"); //redirige de nuevo al login si el usuario se equivoca en los datos
        }
    }

y esta es la función en la que hago la consulta a la base de datos para modificar los datos del usuario logueado
 public function actualizar() {
        require 'config.php';

        if (isset($_POST['actualizar'])) {

$nombre=($_POST['nombre_a']);
$apellidos=($_POST['apellidos_a']);
$email=($_POST['email_a']);
$password=($_POST['password_a']);
$direccion=($_POST['direccion_a']);
$ciudad=($_POST['email_a']);
$telefono=($_POST['numero_a']);
$id=$_SESSION['usuario'];

        }

        $modificar = $base->prepare( "UPDATE usuario
SET nombre = :nombre, apellidos = :apellidos, email = :email, password = :password,
direccion = :direccion, ciudad = :ciudad, telefono = :telefono
WHERE :id = $id");

        $modificar->bindParam(":nombre",$nombre,PDO::PARAM_STR, 25);
        $modificar->bindParam(":apellidos",$apellidos,PDO::PARAM_STR, 25);
        $modificar->bindParam(":email",$email,PDO::PARAM_STR,25);
        $modificar->bindParam(":password",$password,PDO::PARAM_STR,25);
        $modificar->bindParam(":direccion",$direccion,PDO::PARAM_STR);
        $modificar->bindParam(":ciudad",$ciudad,PDO::PARAM_STR);
        $modificar->bindParam(":telefono",$telefono,PDO::PARAM_INT);
        $modificar->bindParam(":id",$id->id, PDO::PARAM_INT);

        $modificar->execute();

        header('location:perfilUsuario.php');

    }

A: Lo que sucede es que en tu consulta estas utilizando tu variable $id que es un objeto como si fuera un String, en este caso, para construir la consulta debes pasarla como un parámetro para que con el bindParam funcione la asignación del valor del ID.
En este caso $modificar quedaría de la siguiente forma:
$modificar = $base->prepare( "UPDATE usuario
SET nombre = :nombre, apellidos = :apellidos, email = :email, password = :password,
direccion = :direccion, ciudad = :ciudad, telefono = :telefono
WHERE id = :id");


text:
Q: I coded lazy loading for videos, background images and images but it didn't work on safari I coded lazy loading for videos, background images and images but didn't work on ios safari.
I want show the background images/images/video with IntersectionObserver method.
below codes are for background image and video.

QTech QT190 Journey

<video data-src="/wp-content/uploads/2019/03/Aristospray-QTech-Q5-2-minute-montage-v3-android-pad-compress.mp4"
    poster="{{ get_template_directory_uri() }}/assets/images/vid-images/pistol-suction.jpg"
    width="100%" height="auto"
    class="lazy"
    aria-label="video"
    data-id="vid1">
    </video>

and this is my JS =

    const lazy ={
        img:(img)=>{
            img.src = img.dataset.src;
        },
        background:(bg)=>{
            bg.style.backgroundImage = `url(${bg.dataset.srcset})`;
        },
        video:(vid)=>{
            vid.load();
            fetchVideoAndPlay(vid);
        },
    }

    function fetchVideoAndPlay(video){
        const preloadHolder = (document.querySelector(`#${video.dataset.id}`));
        //console.log(video.dataset.src);
        fetch(video.dataset.src)
        .then(response=> {
            video.setAttribute('data-src','');
            return response.blob();
            })
        .then(blob=>{
            video.src = URL.createObjectURL(blob);
            video.muted = true;
            preloadHolder.remove();
            return video.play();
        })
        .then(()=>{
            console.log('Played');
        })
        .catch( (e)=>{
            console.error(e);
        });
    }

    const lazyItems = [].slice.call(document.querySelectorAll('.lazy'));
    const configInterSection = {root: null,rootMargin: '0px',threshold: [0]};

    if ('IntersectionObserver' in window) {
        let lazyObserver = new IntersectionObserver(function(entries){
            // fire lazy loading
            entries.forEach(function(item) {
                if (item.isIntersecting) {

                    if(item.target.ariaLabel == 'background') lazy.background(item.target);
                    if(item.target.ariaLabel == 'image') lazy.img(item.target);
                    if(item.target.ariaLabel == 'video') lazy.video(item.target);

                    // remove & add classes
                    item.target.classList.remove('lazy');
                    item.target.classList.add('lazy-loaded');

                    //unboud
                    lazyObserver.unobserve(item.target);
                }
            });
        }, configInterSection);

        if(Array.isArray(lazyItems)){
            lazyItems.forEach(function(lazy) {
                lazyObserver.observe(lazy);
            });
        }

    }

-Is there a way to modify this code in ios Safari?

*

*Also this codes didn't work on the Firefox.

A: item.target.ariaLabel is availbale in v8 engine (chrome). hence I changed it to item.target.getAttribute('aria-label')
now it works.


text:
Q: Change drawable resource programmatically I have the following xml resource code that is a background layout for a list of card items
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#CABBBBBB"/>
            <corners android:radius="2dp" />
        </shape>
    </item>

    <item
        android:left="0dp"
        android:right="0dp"
        android:top="0dp"
        android:bottom="2dp"
        android:drawable="@drawable/kpop">
        <shape android:shape="rectangle">
            <solid android:color="#151B54"/>
            <corners android:radius="2dp" />
        </shape>
    </item>
</layer-list>

My problem is that I would like to change the drawable resource programmatically
android:drawable="@drawable/kpop"

(so that each card item would have a different background image)
Any idea/tip how I can do that?

A: Here is how you can achieve that:

*

*Obtain a reference to your layer-list
LayerDrawable layer  = (LayerDrawable)yourView.getBackground();
Or
LayerDrawable layer = (LayerDrawable)context.getResources().getDrawable(R.id.yourLayerDrawable);

*Create a new instance of the layer drawable internally
layer.Mutate();
Android internally caches drawables, which means that if you modify a drawable obtaind through the above method, all other drawables will be affected. To prevent that, you can call Drawable.Mutate()  to tell the system to retain a separate copy of the drawable so that it won't affect the other drawables.

*Set id for item to be modified
android:id="@+id/image_background"
Like this:

<item
    android:left="0dp"
    android:right="0dp"
    android:top="0dp"
    android:bottom="2dp"
    android:id="@+id/image_background" <----
    android:drawable="@drawable/kpop">
    <shape android:shape="rectangle">
        <solid android:color="#151B54"/>
        <corners android:radius="2dp" />
    </shape>
</item>

*Set/reset the drawable for that item
layer.setDrawableByLayerId(R.id.image_background, yourNewDrawable);

*Redraw layer
layer.invalidateSelf();

A: You did not post your java code .. i think it helps you.
try to use this code in your own logic.
yourCard.setBackgroundDrawable( getResources().getDrawable(R.drawable.kpop) );
or
yourCard.setBackground(R.drawable.kpop);

code is not tested but i think it will work..  comment please to ask anything.


text:
Q: Contour plot using matlab fails I am trying to make a contour plot using the following matlab code:
x=linspace(-10,10);
y=linspace(-10,10);
[X,Y]=meshgrid(x,y);
Z=X.^3-Y.^3;
figure
[c,h]=contour(X,Y,Z,[3]);
clabel(c,h)

This gives me the wrong picture actually:

I really don't understand what goes wrong here, because when I do [c,h]=contour(X,Y,Z,[3 0]) for example, it does give me the correct contour plots for the levels 3 and 0, I need help.

A: The fourth argument of contour can be two things.
If it is an array of numbers (more than 1) then its the contour value you want to show. Else, if its a single value, its the amount of contour lines you want to show.
Example:
x=linspace(-10,10);
y=linspace(-10,10);
[X,Y]=meshgrid(x,y);
Z=X.^3-Y.^3;
figure
subplot(121)
[c,h]=contour(X,Y,Z,[10]);
clabel(c,h)
subplot(122)
[c,h]=contour(X,Y,Z,[1000 -1000 50 -70 3 0]);
clabel(c,h)

A: If you only give a single number to contour there, it interprets it as the number of contour lines you want and picks the levels automatically.  From the docs:

contour(Z,v) draws a contour plot of matrix Z with contour lines at the data values specified in the monotonically increasing vector v. To display a single contour line at a particular value, define v as a two-element vector with both elements equal to the desired contour level. For example, to draw contour lines at level k, use contour(Z,[k k]). Specifying the vector v sets the LevelListMode property to manual.

e.g. to get a single contour at "3", you need to do it this way instead:
figure
[c,h]=contour(X,Y,Z,[3,3]);
clabel(c,h)


text:
Q: Why do we have to add 'View' as parameter in onClick method and what it does? I'm setting up a Event Listener on a Button in Android Studio for changing the text inside the TextView and came to this point were we define OnClickmethod. In its parameter list it ask for View Object. Can anyone explain what it does? I can't understand where the object of View class is going to get used.

A: It is there to let you reuse event handlers like the OnClick method, the View parameter is in your case the Button instance that has fired the method - multiple Buttons can have the same OnClick handler, inside the method you can check which of the Buttons has fired (if there are more than one) and react accordingly.
Actually it is very typical for event-driven programming not only on Android but all contemporary UI programming - iOS, Windows, OS/X, etc.
There is a little bit more to that: the parameter's type is View and not Button because not only Buttons react to OnClick and the common type of UI objects reacting to OnClick is View.
Now not only you can handle the event differently, you have also direct access to the source of the event so that you can work on it - in the example of the Button you can change its caption and you know for sure that you are changing the caption of the very UI object that fired the event.
So it has a lot of sense to do event-driven APIs in this manner.
UPDATE
One of the methods to register an event handler (or ClickListener in Android-world) is assigning the method name to the onClick Attribute directly in the layout - provided of course that the method has the proper signature, that is expect one Parameter of type View and has void return type - you can see an example in the other answer.
The other is to assign an anonymous inner class as a Listener like this:
findViewById(R.id.someButton).setOnClickListener(
    new View.OnClickListener() {

      @Override
      public void onClick(View v) {
        doSomething();
      }

    });

You can also have an instance of a class implementing the View.OnClickListener interface, even the `Activity' itself could do it, and then register it as a listener.
In fact all of them work the same - there is an instance of a class implementing View.OnClickListener interface registered in the button instance, the button (or a view for that matter) recognizes a click inside its boundaries and calls a listener passing itself (this) to the listener.
Im my personal opinion the third way is the worst - you can only have one method of a name in the class but many buttons in a layout, so all of them would need to be handled using conditional code.
The first is nice because you can set it visually, yet given that it is all in XML files and you could have multiple layouts for an activity it can be quite a mess to keep it under control in a larger project.
My favorite is thus the second one - it allows you to keep all the logic on one place in the code, for example if you register all you handlers in the onCreate method of an activity.

A: Using view parameter to find the caller, see code:
public void buttonOnClick(View view) {
    switch (view.getId()) {
      case R.id.button1:
        doSomething1();
        break;
      case R.id.button2:
        doSomething2();
        break;
      }
}

So it is possible to use the same method on multiple objects:
android:onClick="buttonOnClick"


text: Q: Appropriate notion of derived category over condensed set If we have a compact Hausdorff space $S$, then my understanding is that the appropriate notion of the derived category of sheaves of condensed abelian groups is to consider the derived category $D_{\text{cond}}(S;\mathbb{Z})$ of sheaves of abelian groups on $*_{\text{proet}}/S$ (with the appropriate choice of the pro-etale site: compact Hausdorff spaces with finite jointly surjective covers). In this case, condensed cohomology of $S$ (which agrees with sheaf cohomology for discrete constant coefficients) is obtained using the usual formalism. Now, if $S$ is no-longer compact, but a compactly generated topological space, then there is a condensed set $\underline{S}$ associated to it. Is there a site such that sheaves of abelian groups on it gives an appropriate notion of $D_{\text{cond}}(\underline{S},\mathbb{Z})$? For example, should one take covers to be given by compactly generated spaces that pullback under any compact Hausdorff subspace of $S$ to a covering by compact Hausdorff spaces finitely many of which are jointly surjective? One property I want it to have is that "condensed cohomology" $H^i_{\text{cond}}(\underline{S};A)$ for a condensed abelian group $A$ should be the one computed on this site. Basically, I want to know if there is a nice "condensed" site for topological spaces that are not necessarily compact.


text:
Q: How to add a CSS transition when there are no changing properties? I know this may sound weird but how could I add a transition to a header when it changes it's size? The thing is that it has no height related css value, It's only text with top and bottom padding, and as the text changes, the height does too. So how could I implement something like a transition?
Let me demonstrate what I mean through code:

$(document).ready(function() {
    $('.header').click(function() {
      if ($('.header').html() == 'Hello World (Click this header)') {
          $('.header').html('Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Praesent dapibus. Nullam eget nisl. Nunc auctor. Morbi leo mi, nonummy eget tristique non, rhoncus non leo. Praesent vitae arcu tempor neque lacinia pretium. Morbi leo mi, nonummy eget tristique non, rhoncus non leo. Duis sapien nunc, commodo et, interdum suscipit, sollicitudin et, dolor. Curabitur ligula sapien, pulvinar a vestibulum quis, facilisis vel sapien. Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? Sed ac dolor sit amet purus malesuada congue. Pellentesque arcu.');
      } else {
          $('.header').html('Hello World (Click this header)');
      }
  });
});

.header {
  color: #fff;
  font-family: helvetica;
  position: fixed;
  right: 0px;
  left: 0px;
  top: 0px;
  padding: 30px 15px;
  background-color: #4d5366;
  cursor: pointer;
  transition: all 0.3s ease-in-out;
  user-select: none;
 }

Hello World (Click this header)

A: Here is an idea adjusting the bottom value that will control the height:

$(document).ready(function() {
  $('.header').css('bottom', 'calc(100vh - ' + $('.header div').css('height') + ' - 60px)')
  $('.header').click(function() {
    if ($('.header div').html() == 'Hello World (Click this header)') {
      $('.header div').html('Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Praesent dapibus. Nullam eget nisl. Nunc auctor. Morbi leo mi, nonummy eget tristique non, rhoncus non leo. Praesent vitae arcu tempor neque lacinia pretium. Morbi leo mi, nonummy eget tristique non, rhoncus non leo. Duis sapien nunc, commodo et, interdum suscipit, sollicitudin et, dolor. Curabitur ligula sapien, pulvinar a vestibulum quis, facilisis vel sapien. Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? Sed ac dolor sit amet purus malesuada congue. Pellentesque arcu.');
    } else {
      $('.header div').html('Hello World (Click this header)');
    }
    $('.header').css('bottom', 'calc(100vh - ' + $('.header div').css('height') + ' - 60px)')
  });
});
.header {
  color: #fff;
  font-family: helvetica;
  position: fixed;
  width: 100%;
  left: 0px;
  top: 0px;
  padding: 30px 15px;
  box-sizing: border-box;
  background-color: #4d5366;
  cursor: pointer;
  transition: all 0.3s ease-in-out;
  user-select: none;
}

Hello World (Click this header)

A: Okay, So you want to set the height of .header to auto first of all. Then when you change it's contents get the height of .header using JQuery, so use var headerHeight = $('.header').outerHeight(); then set .headers height to that height, rather than auto using $('.header').css({'height': headerHeight}). But every time you add new content you have to set the height back to auto, in order to get the height of the new .header div with the new content in it.
Obviously you then want to add to .header the transition as follows or something similar: transition: height 0.25s ease-in-out;. I hope that helps. Let me know if I've misunderstood your question or if I can help further. : )

A: The text-swap occurs instantaneously between screen refreshes, so unless you can explicitly define and set/reset the height of the element (inline or stylesheet) it will not 'grow or shrink' when you swap the text.
A way around this is to poll the dimensions of your header with long and short text-snippets, store these values, and explicitly define the height of the element when the event is triggered according to each state.
Here's a quick and dirty explanation of the principle in vanilla JavaScript...

Hello World!

/*** CSS ***/
#header {
    position: fixed;
    right: 0; left: 0; top: 0;
    height:auto;

    color: #fff;
    background-color: #4d5366;

    font-family: helvetica;
    font-size:1rem;
    line-height:1.6;

    padding: 2rem 1rem;

    cursor: pointer;
    transition: all 0.3s ease-in-out;
    user-select: none;
    overflow: hidden;
}
#header.offpage {
    top: -110%;
}

/*** JS ***/
var text = {
    longText: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
    shortText: "Hello World!"
};

var header;

function setHeaderDimensions() {
    /* grab the height of default text
       and store it in inline data-* attribute */
    var headerHeight = header.clientHeight
    header.setAttribute("data-dims-shortText", headerHeight);

    /* swap text and grab height of longText */
    header.textContent = text.longText;
    header.setAttribute("data-dims-longText", header.clientHeight);

    /* reset default text */
    header.textContent = text.shortText;

    /* define explicit height of default state */
    header.style.height = headerHeight + "px";

    /* display to page */
    header.classList.remove("offpage");
}

function changeHeaderText(e) {
    /* poll current state */
    var flag = header.classList.contains("long");

    /* set text accordingly */
    header.textContent = text[flag ? "shortText" : "longText"];

    /* grab required stored height */
    header.style.height = header.getAttribute(
        flag ? "data-dims-shortText" : "data-dims-longText"
    ) + "px";

    /* toggle state */
    header.classList.toggle("long");

}

function onPageLoaded() {
    header = document.getElementById("header");

    /* grab and set #header dimensions
       for each text-state (long & short) */
    setHeaderDimensions();

    /* add event handler */
    header.addEventListener("click", changeHeaderText, !1);
}

document.addEventListener("DOMContentLoaded", onPageLoaded, !1);

That's the theory anyway.  Hopefully you can take that and run with it.  :D


text:
Q: Doubt in Bruce Berndt and Armin Straub's paper Here on page $6$ and $7$, Bruce Berndt and Armin Straub show that
$$ (- \beta)^{-m}\,\sum_{n = 1}^{\infty}\dfrac{\coth(\beta n)}{n^{2m + 1}} - \alpha^{-m}\,\sum_{n = 1}^{\infty}\dfrac{\coth(\alpha n)}{n^{2m + 1}}$$
$$ = 2^{2m}\,\sum_{k = 0}^{m + 1}\,(-1)^{k}\,\dfrac{B_n\,B_{2m + 2 - 2k}}{(2k)!\,(2m + 2 - 2k)!}\,\,\alpha^{m + 1 - k}\beta^k \tag{1}\label{1}$$
where $B_n$ is $n$-th Bernoulli number. Substituting $m = 2m + 1$ and $\alpha = \beta = \pi$ in $\eqref{1}$ we get
$$\sum_{n = 1}^{\infty}\dfrac{\coth(\pi n)}{n^{4m + 3}} = 2^{4m + 2}\pi^{4m+3}\sum_{k = 0}^{2m + 2}\,(-1)^{k+ 1}\dfrac{B_{2k}}{(2k)!}\dfrac{B_{4m + 4 - 2k}}{(4m + 4 - 2k)!} \tag{3}$$
However what if we substitute $m = 2m$ and $\alpha = \beta = \pi$ in $\eqref{1}$?
Do we get a an equation similar to $(3)$?  I'm struggling with the substitution for quite some time. I'm only interested in the expression we get after substituting $m = 2m$ and $\alpha = \beta = \pi$ in $\eqref{1}$.
Thanks.


text:
Q: Makefile dependencies and Timestamps I have a makefile that I am using to generate artifacts using a third party IDL compiler (rtiddsgen).  This takes in idl files and spits out C/Ada files relating to them.  The C files are then compiled and put into a library (idl_dds_types.a)
I have the IDL files listed in the IDL_TYPES variable.  Each IDL_TYPES file will generate (through rtiddsgen) files of the following form (For example with alerts.idl):
alerts.c
alerts.h
alerts_idl.ads
alerts_idl.adb

So, what I want to happen is when alerts.idl's timestamp is newer than the alerts.c (or the obj.Linux-i686/alerts.o) file, then the alerts.c file is regenerated.  This doesn't seem to be happening.  Any ideas what I need to do to make this happen?  I've tested by "touch"-ing the idl file and then re-running make.
Here is the makefile:
DDS_OUT_DIR = $(MY_HOME)/DDS/DDS_Types/src

IDL_DIR=$(MY_HOME)/DDS/DDS_Types/IDL
IDL_TYPES=common.idl alerts.idl summary.idl
GENERATED_SOURCES =  $(IDL_TYPES:%.idl=%.c)
GENERATED_HEADERS =  $(IDL_TYPES:%.idl=%.h)

LIBNAME  = idl_dds_types

OBJS_DIR       = obj.$(CPUTYPE)

GENERATED_OBJS = $(GENERATED_SOURCES:%.c=$(OBJS_DIR)/%.o)

LIBDIR   = $(DDS_OUT_DIR)/../../lib.$(CPUTYPE)
BINDIR   = $(DDS_OUT_DIR)/../../../../bin.$(CPUTYPE)
CC       = $(C_COMPILER)
CXX      = $(CPP_COMPILER)
OS       = $(shell uname)
DDSCOMMON = $(DDS_OUT_DIR)/../../Common/src

CFLAGS   = -m32 -g -DRTI_UNIX -DRTI_32BIT
CXXFLAGS = -m32 -g
LDFLAGS  = -m32 -static-libgcc
SYSLIBS  = -ldl -lnsl -lpthread -lm -lc

DEFINES_ARCH_SPECIFIC = -DRTI_UNIX

DEFINES = $(DEFINES_ARCH_SPECIFIC) $(cxx_DEFINES_ARCH_SPECIFIC)

INCLUDES  = -I. -I$(NDDSHOME)/include -I$(NDDSHOME)/include/ndds
INCLUDES += -I$(DDSCOMMON)

LIBS = -L$(NDDSLIBDIR) -L$(LIBDIR) -lrt \
      -lnddscppz -lnddscz -lnddscorez $(SYSLIBS) $(OS_SPECIFIC_LIBS)

COMMONLIBSRC  = $(DDSCOMMON)/dds_common.cxx
COMMONLIBOBJS = $(DDSCOMMON)/obj.$(CPUTYPE)/%.o

$(shell mkdir -p $(OBJS_DIR) $(DDSCOMMON)/obj.$(CPUTYPE) $(DDS_CPP_DIR))

default:        $(GENERATED_OBJS) $(LIBDIR)/lib$(LIBNAME).a

$(OBJS_DIR)/%.o : %.idl $(DDSCOMMON)/dds_common.h
       $(C_COMPILER)  -o $(OBJS_DIR)/$(*F).o $(DEFINES) $(INCLUDES) $(CFLAGS) -c $(*F).c; \
       $(C_COMPILER)  -o $(OBJS_DIR)/$(*F)Support.o $(DEFINES) $(INCLUDES) $(CFLAGS) -c $(*F)Support.c; \
       $(C_COMPILER)  -o $(OBJS_DIR)/$(*F)Plugin.o $(DEFINES) $(INCLUDES) $(CFLAGS) -c $(*F)Plugin.c; \

$(LIBDIR)/lib$(LIBNAME).a: $(GENERATED_OBJS) $(CPP_OBJS)
       @echo "Adding these to lib: " $(OBJS_DIR)/*.o; \
       mkdir -p $(LIBDIR)
       rm -f $(LIBDIR)/lib$(LIBNAME).a
       $(AR) -cr $(LIBDIR)/lib$(LIBNAME).a $(OBJS_DIR)/*.o
       ranlib $(LIBDIR)/lib$(LIBNAME).a

%.idl:
       @echo "Generating C and Ada from $@ ..."; \
       $(NDDSHOME)/scripts/rtiddsgen ${IDL_DIR}/$@ -d $(DDS_OUT_DIR) -I ${IDL_DIR} -replace -language Ada; # -example i86Linux2.6gcc4.1.2;

clean:
       rm -rf $(LIBDIR)/lib$(LIBNAME).a; \
       rm -rf $(DDS_OUT_DIR)/*.h; \
   rm -rf $(DDS_OUT_DIR)/*.c; \
       rm -rf $(DDS_OUT_DIR)/*.gpr; \
       rm -rf $(DDS_OUT_DIR)/samples; \
       rm -rf $(DDS_OUT_DIR)/*.xml; \
       rm -rf $(DDS_OUT_DIR)/makefile_*; \
       rm -rf $(DDS_OUT_DIR)/bin; \
       rm -rf $(DDS_OUT_DIR)/summary_idl*; \
       rm -rf $(DDS_OUT_DIR)/common_idl*; \
       rm -rf $(DDS_OUT_DIR)/alerts_idl*; \
       rm -rf $(DDS_OUT_DIR)/$(OBJS_DIR);

A: A rule like your %.idl: rule tells make how to generate .idl files, not how to generate things from .idl files.  You want to change this to %.c: %.idl -- how to generate .c files from .idl files.
That will do most of what you want -- the only problem is if you ever want to be able to generate .ads/.adb files WITHOUT generating .c files or rebuilding the library.


text:
Q: Angular 2 Test verify API was called I am creating a service in Angular 2 which should call an API url to retrieve its data.
For unit testing I would like to verify that the service actually calls the API. To do this TDD, the service getPicture method is currently empty:
@Injectable()
export class ImageService {

  getPicture(id: string) {
    //To be implemented later
  }

}

My test is as follows:
describe('ImageService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpModule],
      providers: [
        ImageService,
        { provide: XHRBackend, useClass: MockBackend }
      ]
    });
  });

  afterEach(inject([XHRBackend], (mockBackend) => mockBackend.verifyNoPendingRequests()));

  describe('getPicture', () => {

    it('should call picture API', inject([ImageService, XHRBackend], (service: ImageService, mockBackend) => {
      mockBackend.connections.subscribe((connection) => {
          expect(connection.request.url).toBe('localhost/some/url/picture');
      });
      service.getPicture('id');
    }));

  });

});

Wherever I look, I see code to deal with any incoming requests. However, I can't find anything that will cause a failed test when no request is made.
I could set some variable (request received) to false, set it true in the subscribe block but this feels clumsy and something that should have a proper implementation already.
How can I verify that the/any http request was made?


text:
Q: MySQL complaining about foreign key constraint inside CREATE TABLE I have the following ~/mydb.sql file:
CREATE DATABASE IF NOT EXISTS my_db CHARACTER SET utf8 COLLATE utf8_general_ci;
SET default_storage_engine=INNODB;

USE my_db;

CREATE TABLE IF NOT EXISTS countries (
    country_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    country_name VARCHAR(250) NOT NULL,
    country_label VARCHAR(250) NOT NULL,
    country_description VARCHAR(500) NOT NULL,
    country_code VARCHAR(25) NOT NULL,

    CONSTRAINT pk_countries PRIMARY KEY (country_id),
    INDEX idx_country_label (country_label),
    INDEX idx_country_code (country_code),
    CONSTRAINT uc_countries_name UNIQUE (country_name),
    CONSTRAINT uc_countries_label UNIQUE (country_label),
    CONSTRAINT uc_countries_desc UNIQUE (country_description),
    CONSTRAINT uc_country_code UNIQUE (country_code)
);

CREATE TABLE IF NOT EXISTS states (
    state_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    state_name VARCHAR(250) NOT NULL,
    state_label VARCHAR(250) NOT NULL,
    state_description VARCHAR(500) NOT NULL,
    state_abbrev VARCHAR(25) NOT NULL,

    CONSTRAINT pk_states PRIMARY KEY (state_id),
    INDEX idx_state_label (state_label),
    INDEX idx_state_abbrev (state_abbrev),
    CONSTRAINT uc_states_name UNIQUE (state_name),
    CONSTRAINT uc_states_label UNIQUE (state_label),
    CONSTRAINT uc_states_desc UNIQUE (state_description),
    CONSTRAINT uc_state_abbrev UNIQUE (state_abbrev)
);

CREATE TABLE IF NOT EXISTS addresses (
    address_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    state_id BIGINT UNSIGNED NOT NULL,
    country_id BIGINT UNSIGNED NOT NULL,
    address_line_1 VARCHAR(250) NOT NULL,
    address_line_2 VARCHAR(250),
    address_line_3 VARCHAR(250),
    address_city VARCHAR(250),
    address_postal_code VARCHAR(25) NOT NULL,

    CONSTRAINT pk_addresses PRIMARY KEY (address_id),
    CONSTRAINT fk_addresses_states_state_id FOREIGN KEY state_id REFERENCES states (state_id),
    CONSTRAINT fk_addresses_countries_country_id FOREIGN KEY country_id REFERENCES countries (country_id),
    INDEX idx_addresses_line1_postal (address_line_1, address_postal_code),
    CONSTRAINT uc_addresses_all UNIQUE (address_line_1, address_line_2, address_line_3, address_postal_code)
);

When I log into the mysql command line and run it I get an error on a foreign key definition for my addresses table:
mysql> source ~/mydb.sql
Query OK, 2 rows affected (0.01 sec)

mysql> source ~/tmp/testdb.sql
Query OK, 1 row affected (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Database changed
Query OK, 0 rows affected (0.02 sec)

Query OK, 0 rows affected (0.02 sec)

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'REFERENCES states(state_id),
    CONSTRAINT fk_addresses_countries_country_id FO' at line 12

I've check and rechecked the syntax and cannot figure out where I'm going awry. Can anybody spot it?

A: Try this CREATE TABLE -
CREATE TABLE IF NOT EXISTS addresses (
    address_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    state_id BIGINT UNSIGNED NOT NULL,
    country_id BIGINT UNSIGNED NOT NULL,
    address_line_1 VARCHAR(250) NOT NULL,
    address_line_2 VARCHAR(250),
    address_line_3 VARCHAR(250),
    address_city VARCHAR(250),
    address_postal_code VARCHAR(25) NOT NULL,

    CONSTRAINT pk_addresses PRIMARY KEY (address_id),
    CONSTRAINT fk_addresses_states_state_id FOREIGN KEY (state_id) REFERENCES states (state_id),
    CONSTRAINT fk_addresses_countries_country_id FOREIGN KEY (country_id) REFERENCES countries (country_id),
    INDEX idx_addresses_line1_postal (address_line_1, address_postal_code),
    CONSTRAINT uc_addresses_all UNIQUE (address_line_1, address_line_2, address_line_3, address_postal_code)
);

Problem with brackets.


text:
Q: How much static analysis history should a company keep? Supposing you work in a very large global company with lot of code at all levels (e.g. from embedded to mobile platform application code), and projects can last anything between 6 months to 5 years...
What would be considered the best practice in terms of keeping static analysis information?, assuming traceability between defects and static warnings is important for the organization (e.g. aerospace, automotive, government, etc.)

A: I don't believe that you need to keep much static analysis information, if any at all. However, to support this, you need good configuration management practices.
First, you should be regularly tagging the code in your source code repository. Consider tagging (git, Subversion, ClearCase - most version control systems should support similar functionality) any builds that you do. By tagging crucial builds with a unique identifier (like a build number or timestamp), you can relate things like a particular snapshot of source code to entries in a defect tracking database or static analysis results.
Now that you have tags, you can map static analysis results to specific source code repositories. It's commonly accepted that you shouldn't keep generated code in version control. I would argue that you shouldn't keep anything that can be directly generated from the source code, which includes static analysis. However, for traceability purposes, you will need to be able to associate defects derived from static analysis to the build that caused the finding.
Realistically, you may want to keep some static analysis results. For example, the results of analysis prior to an external release may be included as part of a formal test report. Even if it isn't part of a test report, you may want to keep this in a project archive. You may also consider including a static analysis summary (such as number of findings, number of findings per source line of code, number of findings by module, number of findings by criticality, or number of findings by type).
You may also want to consider how you manage your static analysis tool, especially if you are using it as part of some kind of formal testing or report. You need to be able to consider the version of the tool as well as the configuration file or parameters used when executing the tool over a given version of the code base. If you don't manage your tool version and configuration, it becomes harder to be able to regenerate the exact same report for a given code base.

A: I find that keeping static analysis results is a very good practice. I wouldn't necessarily be so interested as to "which build introduced this warning", because that should be relatively easy to see from your version control system. In addition, if you are interested in tracing the history of a certain static analysis warning, you probably have already done something else wrong by not fixing that warning when it appeared in the first place.
The main reason why I like the histories of static analysis results is that it allows me to see trends. For example, I can see the amount of lines of code, number of issues, and the code coverage metrics. Issues, for example, should be in a linear relationship with the lines of code. If the number of issues grows faster than the lines of code, someone is probably doing something wrong. Similarly, it helps to establish a baseline of desired test coverage, and you can see if it starts to dip, if someone forgets to create tests.
As to your actual question on how long to keep the static analysis information. I'd say you should keep it right from the beginning of the project, but you don't need to keep all of it. SonarQube, for example, which would be my weapon of choice, automatically prunes some its old snapshots. (A snapshot is a set of static analysis results on a particular build.) The default rules are described at http://docs.sonarqube.org/display/SONAR/History+and+Events and the most relevant part is this:

*

*only one snapshot per day is kept after 1 day. Snapshots marked by an event are not deleted.

*only one snapshot per week is kept after 1 month. Snapshots marked by an event are not deleted.

*only one snapshot per month is kept after 1 year. Snapshots marked by an event are not deleted.

*all snapshots older than 5 years are deleted, including snapshots marked by an event.

So for the current day you see all of the analyses, but tomorrow only the last analysis of the previous day is available, the others have been deleted. At the end of April all but the last analysis of March are deleted. Etc. So go for a different resolution for different time periods. This allows you to efficiently save several years of data.


text:
Q: Apply Angular.js to new DOM Element in Chrome Extension Content Script Okay, so I've been at this for a while.
In the red box, I want to have some angular functionality (ng-repeats, data binding, etc...) This red box appears when text on any webpage is double clicked. However, I can't seem to find out how to actually get angular wired/hooked up to the text box example in the red popup.
It seems fairly trivial to use angular in a badge popup in chrome, as well as on options pages, etc...but I can't seem to get it working in this instance.

inject.js (which is included as a content script in manifest, below)
    var displayPopup = function(event) {

    var mydiv = document.createElement('div');
    var $div = $('#divid').closest('.sentence');
    mydiv.innerHTML = getSelectionText();
    mydiv.innerHTML += currentSentence.innerHTML;

        //Next line is where I want to apply some angular functionality
        mydiv.innerHTML += '
<input type="text" ng-model="data.test">
{{data.test}}

';

    mydiv.id = "popup";
    mydiv.style.position = "fixed";
    mydiv.style.top = event.clientY + "px";
    mydiv.style.left = event.clientX + "px";
    mydiv.style.border = "4px solid #d00";
    mydiv.style.background = "#fcc";

        $("body").append(mydiv);

    $.getJSON('http://local.wordly.com:3000/words/definitions/test', function(data) {
      console.log(data);
    });
  }

and my manifest.json content script array looks like:
"content_scripts": [
    {
      "matches": [
        "https://www.google.com/*"
      ],
      "css": [
        "src/inject/inject.css"
      ]
    },
    {
      "matches": [
        "http://*/*",
        "https://*/*"
      ],
      "js": [
        "js/angular/angular.js", "app.js", "js/jquery/jquery.js", "src/inject/inject.js"
      ]
    }
  ]

and app.js, also included in manifest, for just some skeletal app to get up and running.
var myApp = angular.module("myApp", []);

myApp.factory('Data', function(){
    //return {message: "I'm data from a service"};
});

myApp.controller("SecondCtrl", function($scope, $http){

});

A: You need to bootstrap manually if you're injecting the markup after the page loads. Angular will only run ng-app if it's present when the document is loaded. Afterwards, you pass the module name to angular.bootstrap:
angular.bootstrap(mydiv, ['myApp'])

Example.


text:
Q: Expand Event in Full Calendar V5 To Fill Row What would be a way to expand an event in the timeline view of FullCalendar v5 on hover to expand it to the entire row on hover? I found the event is handled by fc-event so I added the following:
.fc-event:hover {
    opacity: 0.9;
    text-align: center;
    position: absolute;
    z-index:10000 !important;
    width: 100%;
}

However setting the width to 100% doesn't work, setting it to a fixed value does work however it will only expand it to the right as below:

If the event is in the middle of the calendar this becomes a problem as it only expands out to the right, I'd prefer for it to fill the entire row from the start of the row.
Looking at the source I see fc-timeline-lane-frame handles the row but I'm not sure how to set the div to the width of this. Any help would be appreciated!


text:
Q: Elasticsearch - Search fails after upgrading to 2.1.1 I am working on a Java EE 7 WebApplication (running in wildfly 10) using an embedded Elasticsearch.
After upgrading to elasticsearch 2.1.1 searching is not working anymore. (indexing seems to work)
Dependencies that worked:
    <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch</artifactId>
        <version>2.0.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.lucene</groupId>
        <artifactId>lucene-core</artifactId>
        <version>5.2.1</version>
    </dependency>

Upgraded dependencies:
    <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch</artifactId>
        <version>2.1.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.lucene</groupId>
        <artifactId>lucene-core</artifactId>
        <version>5.3.1</version>
    </dependency>

After indexing a very basic document (indexing seems to work), searching fails with the following exception:
org.elasticsearch.action.search.SearchPhaseExecutionException : all shards failed [Proxied because : Original exception caused: class java.io.NotSerializableException: org.elasticsearch.action.search.ShardSearchFailure]
at org.elasticsearch.action.search.type.TransportSearchTypeAction$BaseAsyncAction.onFirstPhaseResult(TransportSearchTypeAction.java:228)
at org.elasticsearch.action.search.type.TransportSearchTypeAction$BaseAsyncAction$1.onFailure(TransportSearchTypeAction.java:174)
at org.elasticsearch.action.ActionListenerResponseHandler.handleException(ActionListenerResponseHandler.java:46)
at org.elasticsearch.transport.local.LocalTransport.handleException(LocalTransport.java:354)
at org.elasticsearch.transport.local.LocalTransport.handlerResponseError(LocalTransport.java:345)
at org.elasticsearch.transport.local.LocalTransport.messageReceived(LocalTransport.java:241)
at org.elasticsearch.transport.local.LocalTransportChannel$2.run(LocalTransportChannel.java:99)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.elasticsearch.common.io.stream.NotSerializableExceptionWrapper: _byteSymbolCanonicalizer
at com.fasterxml.jackson.dataformat.smile.SmileFactory._createParser(SmileFactory.java:404)
at com.fasterxml.jackson.dataformat.smile.SmileFactory.createParser(SmileFactory.java:327)
at org.elasticsearch.common.xcontent.smile.SmileXContent.createParser(SmileXContent.java:107)
at org.elasticsearch.common.xcontent.smile.SmileXContent.createParser(SmileXContent.java:113)
at org.elasticsearch.search.SearchService.parseSource(SearchService.java:817)
at org.elasticsearch.search.SearchService.createContext(SearchService.java:651)
at org.elasticsearch.search.SearchService.createAndPutContext(SearchService.java:617)
at org.elasticsearch.search.SearchService.executeDfsPhase(SearchService.java:262)
at org.elasticsearch.search.action.SearchServiceTransportAction$SearchDfsTransportHandler.messageReceived(SearchServiceTransportAction.java:360)
at org.elasticsearch.search.action.SearchServiceTransportAction$SearchDfsTransportHandler.messageReceived(SearchServiceTransportAction.java:357)
at org.elasticsearch.transport.local.LocalTransport$2.doRun(LocalTransport.java:280)
at org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:37)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

This is how my search looks like:
QueryStringQueryBuilder qb = QueryBuilders.queryStringQuery(queryString);
SearchResponse searchResponse = this.client.prepareSearch(INDEX_NAME)
            .setTypes(typeName)
            .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
            .setQuery(qb)
            .setFrom(offset)
            .setSize(limit)
            .execute()
            .actionGet();

A: I got around that problem by shading elasticsearch dependencies
1. I created a separate maven-module:
<project>
...
<dependencies>
    <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch</artifactId>
        <version>2.3.4</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.4.1</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <relocations>
                            <relocation>
                                <pattern>com.fasterxml.jackson</pattern>
                                <shadedPattern>shaded.elasticsearch.jackson</shadedPattern>
                            </relocation>
                        </relocations>
                        <transformers>
                            <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer" />
                        </transformers>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
...
</project>

2. And then used that module as a dependency in my main project
    <dependency>
        <groupId>drivve</groupId>
        <artifactId>elasticsearch-shaded</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>
    <dependency>
        <groupId>org.apache.lucene</groupId>
        <artifactId>lucene-core</artifactId>
        <version>5.5.0</version><!-- be sure to match the version required by elasticsearch-shaded -->
    </dependency>

Everything works fine now and is not that hard to managed.
More info on shading es dependencies can be found here.


text:
Q: Find complexity of iterative algorithm with i and j Problem

Hi guys! I am trying to find the complexity of the following algorithm.
Currently, what I've done is the following - I've realised that:

*

*i increases n times

*i increases whenever j > i^2

soo:
j > 1
j > 4
...
j > n^2
And I'm thinking that maybe the complexity of the algorithm is
My solution

Thanks all!


text:
Q: proof by induction to fourier problem So if $h_n (t) = e^{\pi t^2}\frac{d^n}{dt^n}(e^{-2\pi t^2})$. Show proof by induction that $$\widehat{h_n}=(-i)^n h_n$$ Any ideas how to go about with this one? When $n=0  \to \widehat{h_0}=h_0$.

A: Your Fourier transform is defined as
$$\hat{h_n}(v) = \int_{-\infty}^{\infty} dt \, e^{-i 2 \pi v t} h_n(t)$$
Note that
$$h_0(t) = e^{-\pi t^2} \implies \hat{h_0}(v) = e^{-\pi v^2}$$
Assume that
$$\int_{-\infty}^{\infty} dt \, e^{-i 2 \pi v t} e^{\pi t^2} \frac{d^n}{dt^n} e^{-2 \pi t^2} = (-i)^n e^{\pi v^2} \frac{d^n}{dv^n} e^{-2 \pi v^2}$$
Then we seek
$$\int_{-\infty}^{\infty} dt \, e^{-i 2 \pi v t} e^{\pi t^2} \frac{d^{n+1}}{dt^{n+1}} e^{-2 \pi t^2}$$
We start by integrating by parts; this integral is
$$\begin{align} &= \underbrace{\left [e^{-i 2 \pi v t} e^{\pi t^2} \frac{d^n}{dt^n} e^{-2 \pi t^2} \right ]_{-\infty}^{\infty}}_{\text{This is equal to 0}} - \int_{-\infty}^{\infty} dt \, (2 \pi t - i 2 \pi v) e^{-i 2 \pi v t} e^{\pi t^2} \frac{d^n}{dt^n} e^{-2 \pi t^2}\\ &= i 2 \pi v (-i)^n e^{\pi v^2} \frac{d^n}{dv^n} e^{-2 \pi v^2} - 2 \pi \int_{-\infty}^{\infty} dt \,t \, e^{-i 2 \pi v t} e^{\pi t^2} \frac{d^n}{dt^n} e^{-2 \pi t^2}\\ &= i 2 \pi v (-i)^n e^{\pi v^2} \frac{d^n}{dv^n} e^{-2 \pi v^2} - \frac{2 \pi}{-i 2 \pi} \frac{d}{dv} \int_{-\infty}^{\infty} dt \, e^{-i 2 \pi v t} e^{\pi t^2} \frac{d^n}{dt^n} e^{-2 \pi t^2}\\ &= i 2 \pi v (-i)^n e^{\pi v^2} \frac{d^n}{dv^n} e^{-2 \pi v^2} - i (-i)^n \frac{d}{dv} \left [e^{\pi v^2} \frac{d^n}{dv^n} e^{-2 \pi v^2} \right ]\\ &=i 2 \pi v (-i)^n e^{\pi v^2} \frac{d^n}{dv^n} e^{-2 \pi v^2} - i (-i)^n \left [2 \pi v e^{\pi v^2} \frac{d^n}{dv^n} e^{-2 \pi v^2} + e^{\pi v^2} \frac{d^{n+1}}{dv^{n+1}} e^{-2 \pi v^2}\right ] \\ &= (-i)^{n+1} e^{\pi v^2} \frac{d^{n+1}}{dv^{n+1}} e^{-2 \pi v^2}\end{align}$$
which was to be shown.


text:
Q: AppendNode in a linked list Whenever I go to use my showInfo function:
EDIT: it operates once but breaks the second time through.
void showInfo(){
    node * temp = head;
    while (temp){
        temp->showInfo();
        temp = temp->getNext();
    }
}

with temp->showInfo(); pointing at:
void showInfo(){
        cout << data << endl;
    }

I encounter the 0x0000005 error as it tries to access NULL. I'm assuming it's my appendNode function:
void appendNode(node * n){
        if (head == nullptr){
            head = n;
        }
        else{
            node * iter = head;
            while (iter->getNext()){
                iter = iter->getNext();
            }
            iter->setNext(n);
        }
        size++;
    }

The nodes are assigned as follows:
int main(){

    char * data1 = "g";
    char * data2 = "b";
    char * data3 = "k";

    linkedList * list = new linkedList();

    node * g = new node();
    g->setData(data1);
    list->setHead(g);
    node * b = new node();
    list->appendNode(b);
    node * k = new node();
    list->appendNode(k);
    list->showInfo();
return 0;
}

any hints and direction is appreciated.
EDIT: stepping through shows it breaks within iosfwd. the code it breaks in is:
static size_t __CLRCALL_OR_CDECL length(const _Elem *_First)
        {   // find length of null-terminated string
        return (*_First == 0 ? 0
            : _CSTD strlen(_First));
        }