text:
Q: Undefined in store reducer Im trying to write reducer for action in angular ngrx store architecture:
this is my reducer:
export const registration = (state: any, {type, payload}) => {
  switch (type) {
    case 'REGISTER_USER':
      console.log('reducer ' + payload, type);
      return payload;
    default:
      return state;
  }
};

and this is my function calling the reducer
register(user: RegistrationUser) {
    return this.http.post(Global.API_URL+'/register', user)
      .map(response => response.json())
      .map(data => ({type: 'REGISTER_USER', data}))
      .subscribe(action => {this.store.dispatch(action); console.log(action)});
  }

the problem Im having in that the payload is undefined. Where the
console.log(action);

returns object. And console log from reducer returns proper action type but undefined as object 'reducer undefined REGISTER_USER'

A: I think you need to just map data to payload: data:
register(user: RegistrationUser) {
    return this.http.post(Global.API_URL+'/register', user)
      .map(response => response.json())
      .map(data => ({type: 'REGISTER_USER', payload: data}))
      .subscribe(action => {this.store.dispatch(action); console.log(action)});
  }


text:
Q: Convert array size The following code gets input from a file and stores it in a 1D array. I want a matrix type of input like:
1,2,4
3,4,5
5,6,7

(or)
2,3,4,5
4,5,6,7
7,6,5,4
3,4,5,6

where the size of the matrix varies and they are separated by commas, to be stored in a 2D array.  What changes should I make to the following code?
#include <stdio.h>
#include <stdlib.h>

int main(){
    char file[51];
    int data, row, col, c, count, inc;
    int *array, capacity=50;
    char ch;
    array = (int*)malloc(sizeof(int) * capacity);
    printf("\nEnter the name of the file with its extention\n");
    scanf("%s", file);
    FILE *fp = fopen(file, "r");
    row = col = c = count = 0;
    while (EOF != (inc = fscanf(fp,"%d%c", &data, &ch)) && inc == 2){
        ++c; //COLUMN count
        if (capacity == count)
            array = (int*)realloc(array, sizeof(int) * (capacity *= 2));
        array[count++] = data;
        if(ch == '\n'){
            ++row;
            if (col == 0){
                col = c;
            } else if (col != c){
                fprintf(stderr, "format error of different Column of Row at %d\n", row);
                goto exit;
            }
            c = 0;
        } else if (ch != ',') {
            fprintf(stderr, "format error of different separator(%c) of Row at %d \n", ch, row);
            goto exit;
        }
    }
    {   //check print
        int i, j;
        //int (*matrix)[col] = array;
        for(i = 0; i < row; ++i){
            for(j = 0; j < col; ++j)
                printf("%d ", array[i * col + j]);//matrix[i][j]
            printf("\n");
        }
    }
exit:
    fclose(fp);
    free(array);
    return 0;
}

A: This uses fgets to read each line and strtol to parse integers from a line.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>

int get_int_range ( char *line, char **next, char *term, int *value, int min, int max);
int get_int_series ( int cols, int dest[][cols], int inputrow, int min, int max, char *line, char *delim);
int get_int_count ( int min, int max, char *line, char *delim);

int main( int argc, char *argv[])
{
    char line[900] = {'\0'};
    char file[100] = {'\0'};
    int valid = 0;
    int rows = 0;
    int cols = 0;
    int eachrow = 0;
    int eachcol = 0;
    FILE *fp = NULL;

    printf ( "Enter the name of the file with it's extension\n");
    fgets ( file, sizeof ( file), stdin);
    file[strcspn ( file, "\n")] = '\0';//remove trailing newline

    if ( ( fp = fopen ( file, "r")) != NULL) {

        fgets ( line, sizeof ( line), fp);//read a line
        rows = get_int_count ( INT_MIN, INT_MAX, line, ",\n");
        rewind ( fp);
        if ( rows) {
            cols = rows;
            //once the size is obtained, the array can be declared
            int array[rows][cols];

            for(eachrow = 0; eachrow < rows; eachrow++) {
                if ( ( fgets ( line, sizeof ( line), fp)) == NULL) {//read a line
                    fclose ( fp);
                    printf ( "Problem! not enough lines in file\n");
                    return 1;
                }
                valid = get_int_series ( cols, array, eachrow, INT_MIN, INT_MAX, line, ", \n");
                if ( !valid) {
                    fclose ( fp);
                    printf ( "Problem!\n");
                    return 1;
                }
            }
            if ( ( fgets ( line, sizeof ( line), fp)) != NULL) {//read a line
                fclose ( fp);
                printf ( "Problem! too many lines in file\n");
                return 1;
            }
            for(eachrow = 0; eachrow < rows; eachrow++) {
                for(eachcol = 0; eachcol < cols; eachcol++) {
                    printf("[%d] ", array[eachrow][eachcol]);
                }
                printf("\n");
            }
            printf("\nDone\n");
        }
        fclose ( fp);
    }
    return 0;
}

int get_int_range ( char *line, char **next, char *term, int *value, int min, int max)
{
    long int input = 0;
    char *end = NULL;

    errno = 0;
    input = strtol ( line, &end, 10);//get the integer from the line
    if ( end == line) {
        printf ( "input MUST be a number\n");
        return 0;
    }
    if ( *end != '\0' && ( strchr ( term, *end) == NULL)) {
        printf ( "problem with input: [%s] \n", line);
        return 0;
    }
    if ( ( errno == ERANGE && ( input == LONG_MAX || input == LONG_MIN))
    || ( errno != 0 && input == 0)){
        perror ( "input");
        return 0;
    }
    if ( input < min || input > max) {
        printf ( "input out of range %d to %d\n", min, max);
        return 0;
    }

    if ( next != NULL) {
        *next = end;
    }
    *value = input;//set the value
    return 1;
}

int get_int_series ( int cols, int dest[][cols], int inputrow, int min, int max, char *line, char *delim)
{
    char *end = NULL;
    char *each = NULL;
    int valid = 0;
    int input = 0;
    int count = 0;
    int temp[cols];

    each = line;
    do {
        valid = get_int_range ( each, &end, delim, &input, INT_MIN, INT_MAX);
        if ( !valid) {
            printf ( "input MUST be a number\n");
            return 0;
        }
        if ( valid) {
            temp[count] = input;
            count++;
            if ( count > cols) {
                printf ( "too many integers. %d entered. only enter %d\n", count, cols);
                return 0;
            }
        }
        while ( *end && strchr ( delim, *end)) {//skip any number of delimitors
            end++;
        }
        each = end;
    } while ( end && *end);

    if ( count < cols) {
        printf ( "too few integers. need %d entered. only entered %d\n", cols, count);
        return 0;
    }
    while ( count) {
        count--;
        dest[inputrow][count] = temp[count];//set the value
    }
    return 1;
}

int get_int_count ( int min, int max, char *line, char *delim)
{
    char *end = NULL;
    char *each = NULL;
    int valid = 0;
    int input = 0;
    int count = 0;

    each = line;
    do {
        valid = get_int_range ( each, &end, delim, &input, INT_MIN, INT_MAX);
        if ( !valid) {
            return count;
        }
        if ( valid) {
            count++;
        }
        while ( *end && strchr ( delim, *end)) {//skip any number of delimitors
            end++;
        }
        each = end;
    } while ( end && *end);

    return count;
}

A: Simply save and read the array always a single dimension string which length is the product of all dimensions by the sizeof the type. Then return a pointer to void that will be assigned to a pointer to an array of desired dimensions.
I.e.
void *MyReadFnc(char *filename, size_t size)
{
    char *p = malloc(size);
    //open file and load the data
    return (void *)p;
}
...
//Call the function to read in our array.
//For who don't see it we want assign to an array of 5 dimensions
//array[10][2][3][4][5]
//Note that the first dimension is omitted, but we have to use it in array size calcullation
int (*array)[2][3][4][5] = MyReadFnc("Filename.ext", 2*3*4*5*10*sizeof(int));
...
printf("element[9][1][2][3][4] = %d\n", array[9][1][2][3][4]);
...
//Again an array of 3 dimensions:
//array2[10][20][30]
int (*array2)[20][30] = MyReadFnc("Filename.ext", 20*30*10*sizeof(int));
...
printf("element[9][19][29] = %d\n", array[9][19][29]);

We use a void * as output, because the routine is generic and can handle whichever array (of any number of dimensions). And the use of void * is simply the standard and natural way of C language to handle such variegated types. This is the way C language works. If you wants stronger type checking you should change language.
The following is more generic code for reading arrays.
#include <stdio.h>
#include <stdlib.h>

//Because we read whole data as single stream like a 1 dimension array, totElems
//is the total number of elements expressed as the product of all dimensions of
//the final array
void *ReadArray(char *fname, size_t totElems, size_t ElemSize)
{
    FILE *fp = fopen(fname, "r");
    if (!fp)
    {
        fprintf(stderr, "Can't open file <%s>\n", fname);
        exit(-1);
    }

    int *p = calloc(totElems, ElemSize);
    if (!p)
    {
        fprintf(stderr, "Can't allocate memory\n");
        exit(-1);
    }

    for (size_t i=0; ; i++)
    {
        int a;

        if (EOF==fscanf(fp, "%d,", &a))
            break;
        p[i] = a;
    }

    fclose(fp);
    return (void *)p;
}

int main(void)
{
    char file[51];
    printf("\nEnter the name of the file with its extention\n");
    scanf("%s", file);

    printf("Array 4x4\n");
    //First sample: declare a pointer to a 2 dimension array 4x4 elements
    int (*array)[4];
    array = ReadArray(file, 16, sizeof(int));
    for (int i=0; i<4; i++)
    {
        for(int j=0; j<4; j++)
            printf("%d,", array[i][j]);
        printf("\n");
    }

    printf("Array 2x8\n");
    //Second sample: declare a pointer to a 2 dimension array 2x8 elements
    int (*array2)[8];
    array2 = ReadArray(file, 16, sizeof(int));
    for (int i=0; i<2; i++)
    {
        for(int j=0; j<8; j++)
            printf("%d,", array2[i][j]);
        printf("\n");
    }

    printf("Array 2x2x4\n");
    //Third sample: declare a pointer to a 3 dimension array 2x2x4 elements
    int (*array3)[2][4];
    array3 = ReadArray(file, 16, sizeof(int));
    for (int i=0; i<2; i++)
    {
        for(int j=0; j<2; j++)
        {
            if(j) printf (" - ");
            for (int k=0; k<4; k++)
                printf("%d,", array3[i][j][k]);
        }
        printf("\n");
    }

    return 0;
}

You can assign the result to arrays of any dimensions ;). No casting is required because the array object is returned as a void * to allow maximum flexibility. Note also that because any C array is an array of array of array, etc, it is really dimensions independent. What is returned by the function is an array that could fit any definition respecting 2 claims: 1. the array is of a type having the same sizeof specified in ElemSize (that here for sake of simplicity is hardwired to int), 2. the product of whole dimensions is <=totElems.
This of course is just a sample to serve as base to develop more complex versions, a good development could be to make it able to handle any type of data (not only int). I'm sure that this is a good exercise for beginners that needs a starting point to use to improve themselves and expand their creativity.
Finally just consider that on a C99-C11 compliant compiler you can write:
printf("Array 2x2x4 using variables\n");
//Fourth sample: declare a pointer to a 3 dimension array 2x2x4 elements
//using variables for dimensions
int x = 2;
int y = 2;
int z = 4;
int (*array4)[y][z];
array4 = ReadArray(file, 16, sizeof(int));
for (int i=0; i<x; i++)
{
    for(int j=0; j<y; j++)
    {
        if(j) printf (" - ");
        for (int k=0; k<z; k++)
            printf("%d,", array4[i][j][k]);
    }
    printf("\n");
}

A: Ok, your present code already knows how to determine the number of cols at the end of first line and to control that all lines has same number of cols.
You can allocate a 2D array at the end of the first line that way:
capacity = cols * cols;
int (* arr)[cols] = malloc(sizeof(int) * capacity); // array is a 2D array cols x cols

(of course, you must have stored first line in another array, and you must copy those data in newly allocate arr...)
Then you assign that way:
arr[row][c] = data;

The only requirement is that your compiler accepts Variable Length Arrays. It is specified in C99 but some old MS compilers (at least up to 2008) do not accept it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: IBM Watson NLU in Ruby I am attempting to use the watson api client from https://github.com/suchowan/watson-api-client.
I have this written so far based on documentation from https://watson-api-explorer.ng.bluemix.net/listings/natural-language-understanding-v1.json:
require 'watson-api-client'

service = WatsonAPIClient::NaturalLanguageUnderstanding.new(
  :user=>"xxxxxxxxxxxx",
  :password=>"yyyyyyyyy",
  :verify_ssl=>OpenSSL::SSL::VERIFY_NONE
)

result = service.analyze(
  'version'          => "2018-03-16",
  'parameters'       => "keywords.sentiment",
  'source'           => "The quick brown fox jumps over the lazy cat"
)
p JSON.parse(result.body)

The issue is since there isn't anything I can find for sending the request through ruby I may be using the wrong parameters. For instance I get ArgumentError (Extra parameter(s) : 'source' with this current code. I've tried replacing source with text to no avail. Has anyone successfully made a request like this in Ruby or knows what the proper parameters needed are?
Thanks.

A: looking at the API at https://www.ibm.com/watson/developercloud/natural-language-understanding/api/v1/#post-analyze it looks like parameters should be a JSON object. I also do not see any source (as Simon's comment states, use text) parameter in the API documentation.
Perhaps before jumping into the watson-api-client gem, attempt to make a call using Net::HTTP (documentation https://docs.ruby-lang.org/en/2.0.0/Net/HTTP.html) This way you can see exactly what is expected. You also may be able to make a more tailored solution for connecting to the Watson API.
for example
    uri = URI('https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze?version=2018-03-16')
  Net::HTTP.start(uri.host, uri.port) do |http|
    request = Net::HTTP::Post.new uri
    request['Content-Type'] = 'application/json'
    request.body = {text: 'your test', keywords: {sentiment: true}}.to_json
    request.basic_auth 'username', 'password'

    response = http.request request # Net::HTTPResponse object
  end

Please note the above was just produced, not tested. Hope this helps out.


text:
Q: QuickLook Plugin: how does it work when 2 plugins handle the same file type? If a user has 2 or more quicklook plugins that handle the same kMDItemContentType what happens? Which plugin gets priority to do that actual work? Can that be set programmatically?

A: From a quick reading of the docs (Installing Quick Look Generators), the Quick Look daemon chooses a generator based on the following search order:

*

*Inside the app bundle: MyApp.app/Content/Library/QuickLook

*In ~/Library/QuickLook

*In /Library/QuickLook

*In /System/Library/QuickLook
They finish by saying that if there is more than one generator for a UTI, the one that ranks highest on that list is chosen. If there are two or more for the same UTI at the same level, Apple says there is no way to know which will be chosen; the generator that is found first in their search is used.

A: I've found you can modify the Info.plist file within a .qlgenerator plugin and remove a UTI entry from UTImportedTypeDeclarations to force Quicklook to use another generator for that UTI.  You may need to run qlmanage -r afterward for changes to take effect.


text:
Q: button group wraps label at full width bootstrap I have run into an issue I hope you can help solve.
I have a button group which when the browser expanded 100% wraps around the label.  What is the best method to stop this happening.  As I do not want the button group wrapping the label.
see html below.

                                    add and remove me

                                        <input name="selectme" id="selectme" placeholder="add and remove me" class="form-control" type="text">
                                       <button onclick="addItem()" type="button" class="btn btn-success btn-sm">
                                         Add
                                    </button>
                                    <button onclick="removeItem()" type="button" class="btn btn-secondary btn-sm">
                                         Remove
                                    </button>

A: Does simply adding
 after your input solve your issue? like this:

                                    add and remove me

                                        <input name="selectme" id="selectme" placeholder="add and remove me" class="form-control" type="text">

                                       <button onclick="addItem()" type="button" class="btn btn-success btn-sm">
                                         Add
                                    </button>
                                    <button onclick="removeItem()" type="button" class="btn btn-secondary btn-sm">
                                         Remove
                                    </button>


text:
Q: Ratio word problem total cost of magazine and number of customers who bought the magazine
During January of this year, Utopia Magazine sales reached a total of £ 488800. The ratio of normal price customer to discounted price customer was 5:2. How many customers in total bought this magazine?
I have tired to work this out by multiplying the total with each ratio and dividing by 7 but i dont seem to get the answer correct, can any one help with this problem?

A: Let $n$ be the number of normal price customers and $d$ be the number of discounted price customers. Then you have that
$$2n=5d$$
and
$$2.8n+2.1d=488,800$$
since $2.1=2.8-0.25\cdot 2.8$. Can you solve this system of equations for $n$ and $d$, and then calculate the total number of customers $n+d$?


text:
Q: How are strings stored as bytes in databases? This question may be a little vague, but let me try to explain it clearly. I have been reading a database related tutorial, and it mentioned tables are serialized to bytes to be persisted on the disk. When we deserialize them, we can locate each column based on the size of its type.
For example, we have a table:
---------------------------------------------------
| id (unsigned int 8) | timestamp (signed int 32) |
---------------------------------------------------
|      Some Id        |        Some time          |
---------------------------------------------------

When we are deserializing a byte array loaded from a file, we know the first 8 bits are the id, and the following 32 bits are the timestamp.
But the tutorial never mentioned how strings are handled in databases. They are not specific to a limited size, like 32 bits, and they are not predictable the size wise (there can always be a long long String, who knows). So how exactly does databases handle strings?
I know in RDBMS, you need to specify the size of the string as Varchar(45) for example, then it becomes easier. But what about dbs like MongoDB or Redis, which does not require a specification for string sizes, do they just assume it to be a specific length and increase the size once a longer one comes in?
That is basically my vague non-specific question, hope someone can give me some ideas on this. Thank you very much

A: In MongoDB, documents are serialized as BSON (Binary JSON-like objects). See BSON spec for more details regarding the datatypes for each type.
For string type, it is stored as:
<unsigned32 strsizewithnull><cstring>

From this line in the MongoDB source.
So a string field is stored with its length (including the null terminator) in the BSON object. The string itself is UTF-8 encoded as per BSON spec, so it can be encoded using a variable amount of bytes per symbol. Together with other fields that makes up a document, they are compressed using Snappy by default. This compressed representation is the one persisted to disk.
WiredTiger is a no-overwrite storage engine. If that document is updated, WiredTiger creates a new document and updates the internal pointer to the new one, and mark the old document as "space available for reuse".


text:
Q: Maximum of minimum Hamming distance between $2$ of $N$ unique binary strings of length $L$ So we have $L$ bits, which gives us a binary string of length $L$. We have $N$ of these, all different.
If we take $2$ and the $XOR$ gate, then count the number of $1$'s, this is the Hamming distance. In other words, the number of bits that are different.
We can do this for all combinations of our binary strings, and find the minimum.
What is the highest this value can be?

Note that this is not equivalent to finding an optimal ratio $f(N)$ so the value is $\lfloor Lf(N)\rfloor$. (unproven, just my guess)
If it works though, this easy construction provides a lower bound of $f(N)\ge \frac{1}{2}, \forall N$:

Begin with $[00,01,10,11] \implies N=4 \land L=2$.
Double the digits, replacing a $0$ with $00$ and $1$ with $11$. Make a copy of the list where all even numbered bits are flipped. Merge the lists. $N$ and $L$ have both doubled. Repeat this step until $N$ and $L$ are large enough, then throw away excess binary strings and trim length.

A tighter bound $f(N)=\frac{g(N)}{2g(N)-1},g(N)=2^{\lceil log_2(N)\rceil-1}$:

Set $k$ as the smallest power of $2$ for $k\ge N,k>L$. Construct the $k\times k$ Hadamard matrix. Replace $-1$ with $0$. Remove the first column (it's all $1$'s). Read the rows as binary strings. Trim as necessary to meet $N$ and $L$.

First few are $f(2)=1$ from $[0,1] \land f(3)=f(4)= \frac{2}{3}$ from $[000,011,101,110]$.

A: Let $d(x, y)$ be the number of different bits between words $x$ and $y$. If we have a set of binary words $C$, define $d(C) = \min \{d(x, y) : x\neq y\}$ to be the distance between the two closest words. You are trying to maximize $d(C)$ for a give $N=|C|$. Instead, fix $d(C)$ and maximize $N$.
For $L$ bits, $N = |C|$ strings, can we achieve a distance $r = d(C)$? Such a solution is called a $(L, N, r)$ code. This problem is well studied. The largest numbers of strings is given by the bound.
$$N \leq \frac{2^L}{\sum_{i=0}^{r}\binom{L}{i}}$$
The hamming bound is exact, in that there are codes (sets of strings) with
$$N = \frac{2^L}{\sum_{i=0}^{r}\binom{L}{i}}$$
See perfect codes.


text:
Q: Help understanding 60 Hz low pass filter behavior in oscilloscope I have been testing this circuit in simulation

which is supposed to be a low pass 60Hz filter, as far as i am concerned the simulation  works as intended in simulation starts filtering frequencies above 60Hz and after this the amplitude starts going down, i can use a bode plotter to confirm this and change the frequency of the function generator while i see how the sin wave gets less and less amplitude the higher the frequency

However when building this same circuit in the protoboard and using the oscilloscope at the output of the OPAMP something odd happens, i uploaded THIS VIDEO where you can see its behavior in the oscilloscope
The blue signal is the input while the yellow is the output
I start a with a 5v 30Hz signal, and slowly increase the frequency, after 60Hz the output  starts increasing the voltage up to 10v and only after reaching 300Hz, it starts filtering the signal, why is this happening? is it normal?

A: The values in the circuit produce a natural resonance at about 89Hz based on this formula: -
Natural resonance = \$\dfrac{1}{2\pi \sqrt{R_1R_2C_1C_2}}\$
This circuit can also produce what to the uninitiated might think of as strange behaviour - it can actually resonate i.e. produce a significnatly higher amplitude at a range of frequencies just when you might have expected it to be attenuating those frequencies. This is component value dependent.
I believe this is what you are seeing. I think you are seeing this because you have one of the capacitors at the wrong value. For instance, if the 47n were in fact a 1nF capacitor the circuit would resonate at about 600 Hz with a significant peak: -

I used an online sallen-key calculator and plugged in the R and C numbers to get this. Here is the link.
I would encourage you to check the capacitor and resistor values you used.


text:
Q: Android right-left justification of view element in layout How do you get a view to position itself left, right and center in a TableLayout row? Or linear layout?

A: You can use the android:gravity property to set the alignment you want.
<TableRow android:gravity="center">
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:gravity="center">
    </LinearLayout>
</TableRow>

When working on the TableLayout, look for the streachColoum property. Also make it * if you want all the table columns to auto fit.


text:
Q: Overload Function with List as a Parameter I want to create a function with C# List datatype as a parameter.
public void foo(List<Something> obj)
{
...
}

But I want to pass anykind of List type to the function, I mean, like this
List<Class1> obj1 = new List<Class1>();
foo(obj1);

List<Class2> obj2 = new List<Class2>();
foo(obj2);

Can I do something like this? How to do this? Thanks in advance

A: Add a generic argument to your foo method.
public void foo<T>(List<T> obj)
{
...
}

You can find more about them here.

A: use generics.
public void foo<T>(List<T> obj)
{
...
}

call like
 foo<Class1>(new List<Class1>());
 foo<Class2>(new List<Class2>());

The above can be simplified further to by making use of generics type inference
 foo(new List<Class1>());
 foo(new List<Class2>());


text:
Q: Can python's mechanize extract the text associated with a control? I'm writing a crawler, and I keep encountering forms controls for which mechanize can give me no information beyond type. Is there any way that I can get the human-readable text associated with the control? I know this is a bit of a fuzzy area, since there's no perfect way of getting that information, but perhaps something can help?

A: Look for text on the sibling nodes and the parent node's text, because that's where they frequently are.  LXML might be able to help if you actually have to parse the html.


text:
Q: Move Files on Mass By Name to New Directory I have a folder containing nearly 100 sub folders, each of those having their own subdirectories containing models, effects etc. I need to move roughly half of them to a different folder. All the files and folders follow the same naming scheme, for example m8a_rev1 m8a_rev2 m8a_rev3
I have a list of each item that needs to be moved so I'm looking for a way that I can move these folders and files by name as opposed to having to do it manually due to time constraints. The best I could find so far is wildcards but I'm unsure how I could use an entire list with them
Thanks for any support

A: If you're trying to move every file to the same directory, use xcopy <source> <destination> -q -e -t. This moves all of the files within the directory, as well as every subdirectory and file within each subdirectory.
-q suppresses the info in the xcopy window, which you can omit if you want to see file progress.
-e copies all subdirectories.
-t copies the subdirectory tree, allowing the files to be moved to their correct subdirectory.


text:
Q: Не срабатывает wp_head() Файл functions.php содержит в себе такой код:
<?php
    add_action('wp_enqueue_scripts', 'add_theme_styles' );

    function add_theme_styles() {
        echo "Themes added ";
    }

Файл header.php имеет в теге head такое содержимое:
<head>
    <?php wp_head(); ?>
</head>

Как видите очень простой код, но тем не менее на странице нигде не выводится текст Themes added, не могу понять в чем проблема, подскажите почему не срабатывает действие wp_head() ?

P.S. Так же после вызова wp_head() в теге head на странице появился отступ сверху, примерно 30px, значит ли это что wp_head() на самом деле сработал, а ошибка в файле functions.php?

A: Этот хук для подключения стилей и скрпитов, а не вывода строки. Вы все выводите в Head документа, а не в тело документа.
add_action('wp_enqueue_scripts', 'my_wp_head_css' ); // хук автоматом сработает во время wp_head
function my_wp_head_css() {
    wp_enqueue_style( 'my_head_style', get_stylesheet_directory_uri() .'/css/my_style.css', array(), null );
}

как еще вариант:
## CSS в head документа
add_action( 'wp_head', 'hook_css' );
function hook_css(){
    echo '<style>.wp_head_example{ background-color : #f1f1f1; } </style>';
}

## JS в head документа
add_action( 'wp_head','hook_javascript' );
function hook_javascript() {
    echo "<script> alert('Page is loading...'); </script>";
}


text:
Q: binary file from java to javascript via websocket I have a Java-Server with an open websocket connection to the javascript client.
I want to transfer a binary file from the java server to the javascript client so that the user just has to save the file somewhere in the filesystem.
On client side I could easily handle a Blob.
On server side I have a java.io.File and a javax.websocket.Session.
I could simply write to the javax.websocket.Session.getBasicRemote().getSendStream().
Does anyone have such an example or can tell me if I am right and what I have to do on client side?


text:
Q: JTable - Getting a cell into Edit mode on pressing Tab This is possibly has a trivial solution, but I am at the end of my tether so I hope somebody can help out.
I use a JTable which has a custom renderer and a custom editor for a set of columns.
The renderer uses a JLabel component and the editor uses a JSpinner component.
Our users want to be able to enter values in a column, and then press TAB or ENTER to move to the next editable cell in the table.
If I understand correctly, this is the default behaviour for a JTable.
However, this doesn't seem to work correctly for me.  Until the user clicks on the cell, only the JLabel is displayed.
The JSpinner (i.e. CellEditor) is only displayed when a user double clicks on the cell.  So, it looks like the cell is going into "edit" mode only on MouseEvents, but not when it has focus.
How do I get the cell to go into edit mode as soon as it has focus?

A: You can achieve this programatically, you simply listen to the focus events on the cell, on focus and editing allowed, start editing.
More on this thread and example

A: Here's a code snippet that I put together for a project that I was working on.  The code has been tested and verified for a table that has non-editable cells in the first and last column.  The class restricts tabbing to only the editable cells of the table.  It also supports shift-tabbing to tab in reverse.
public class JTableCellTabbing {
/**
 *
 * Creates a new {@code JTableCellTabbing} object.
 *
 *
 */
private JTableCellTabbing() {
}

/**
 *
 * Set Action Map for tabbing and shift-tabbing for the JTable
 *
 *
 * @param theTable - Jtable with NRows and MCols of cells
 * @param startRow - valid start row for tabbing [ 0 - (numRows-1) ]
 * @param numRows - Number of rows for tabbing
 * @param startCol - valid start col for tabbing [ 0 - (numCols-1) ]
 * @param numCols -  Number of columns for tabbing
 */
@SuppressWarnings("serial")
static public void setTabMapping(final JTable theTable, final int startRow, final int numRows, final int startCol, final int numCols) {
    if (theTable == null) {
        throw new IllegalArgumentException("theTable is null");
    }

    // Calculate last row and column for tabbing
    final int endRow = startRow + (numRows - 1);
    final int endCol = startCol + (numCols - 1);

    // Check for valid range
    if ((startRow > endRow) || (startCol > endCol)) {
        throw new IllegalArgumentException("Table Size incorrect");
    }

    // Get Input and Action Map to set tabbing order on the JTable
    InputMap im = theTable.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    ActionMap am = theTable.getActionMap();

    // Get Tab Keystroke
    KeyStroke tabKey = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
    am.put(im.get(tabKey), new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int row = theTable.getSelectedRow();
            int col = theTable.getSelectedColumn();

            col++;

            // Move to next row and left column
            if (col > endCol) {
                col = startCol;
                row++;
            }

            // Move to top row
            if (row > endRow ) {
                row = startRow;
            }

            // Move cell selection
            theTable.changeSelection(row, col, false, false);
        }
    });

    // Get Shift tab Keystroke
    KeyStroke shiftTab =
        KeyStroke.getKeyStroke(KeyEvent.VK_TAB, java.awt.event.InputEvent.SHIFT_DOWN_MASK);
    am.put(im.get(shiftTab), new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int row = theTable.getSelectedRow();
            int col = theTable.getSelectedColumn();

            col--;

            // Move to top right cell
            if (col < startCol) {
                col = endCol;
                row--;
            }

            // Move to bottom row
            if (row < startRow ) {
                row = endRow;
            }

            // Move cell selection
            theTable.changeSelection(row, col, false, false);
        }
    });
}

}
And here's how the class is used for your table:
JTable myTable = new JTable();
// Set up table attributes....
JTableCellTabbing.setTabMapping(myTable, 0, NUM_ROWS, 1, (NUM_COLS-1));

A: Thank you n00213f.  The thread and example from your post were helpful.  By overloading the changeSelection method in JTable as hinted to in the thread, JTable checks if a cell is editable every time the selection is changed.  If the cell is editable, it will show the CellEditor and transfer focus to the editor component.
For completeness, here is my solution:
  JTable myTable = new javax.swing.JTable()
  {
            public void changeSelection(final int row, final int column, boolean toggle, boolean extend)
            {
                super.changeSelection(row, column, toggle, extend);
                myTable.editCellAt(row, column);
                myTable.transferFocus();
            }
  };


text:
Q: Selenium WebDriver throws WebDriverException while locating any element of Page with AJAX call on MAC Safari I have an issue with Selenium Webdriver on Mac Safari. Selenium throwing WebDriverException on Safari while locating an element on a Page which contains AJAX calls in the code. The problem comes on all Selenium 3+ versions. On Selenium 2.53, it was working fine.
Is there any other way to locate those elements? Please suggest.


text:
Q: Why are order-k differential forms sections of the kth exterior power of the cotangent bundle? The question I ask is in the title. This should be quite well-known, and in fact probably I am going to get the response that it is the definition. To convey my confusion, I have to convey my understanding of what is a differential form and what is the contangent bundle. To simplify things, we assume that our whole setup is immersed in the Euclidean space.
$1$. Differential forms.
We take the definitions from Rudin, Principles of Mathematical Analysis. This is for an open set in $\mathbb R^n$.
Suppose $E$ is an an open set in $\mathbb R^n$. A $k$-surface in $E$ is a differentiable mapping $\Phi$ from a compact subset $D \subset \mathbb R^k$ into $E$. $D$ is called the parameter domain of $\Phi$ consisting of points $\mathbf u = ( u_{i_1}, \cdots , u_{i_k} )$.
A differential form of order $k \geq 1$ in $E$ is a function $\omega$, symbolically represented by the sum
$$\omega = \sum a_{i_1, \cdots , i_k}(\mathbf x) dx_{i_1}\wedge \cdots \wedge dx_{i_k}$$
where the indices $i_1, \cdots , i_k$ range independently from $1$ to $n$, and so that $\omega$ assigns to each $k$-surface $\Phi$ in $E$ a number$\omega(\Phi) = \int_\Phi \omega$
, according to the rule
$$\int_\Phi \omega = \int_D \sum a_{i_1, \cdots , i_k}(\Phi((\mathbf{u})) \frac{\partial ( x_{i_1}, \cdots , x_{i_k})}{\partial ( u_{i_1}, \cdots , u_{i_k})}d\mathbf u $$
where $D$ is the parameter domain of $\Phi$, and the functions $a_{i_1}, \cdots, a_{i_k}$ are assumed to be real and continuous in $D$.
So in the above definition the differential $k$-form is a certain integral for functions on compact $k$-surfaces. Thus a differential form can be treated as a measure for the $k$-surfaces, which can be integrated.
$2$. Cotangent bundle
We take this from wikipedia.
Let $M \times M$ be the Cartesian product of $M$ with itself.  The diagonal mapping $\Delta$  sends a point $p$ in $M$ to the point $(p,p)$ of $M \times M$.  The image of $\Delta$ is called the diagonal.  Let $\mathcal{I}$ be the sheaf of germs of smooth functions on $M \times M$ which vanish on the diagonal.  Then the quotient sheaf $\mathcal{I}/\mathcal{I}^2$  consists of equivalence classes of functions which vanish on the diagonal modulo higher order terms.  The cotangent sheaf $\Omega$ is the pullback of this sheaf to $M$.
Now, Def 2: A differential form $k$-form $\omega$ is a section of $\wedge^k\ \Omega$.
Question.
We consider an open set in the Euclidean space and look at the two definitions. A priori, to my eyes, both appear to be different things. It needs to be proved that they are the same. Please help me out with a reference with the required proofs.

A: You have to work a bit to get those two definitions to agree, but it is all standard lore in differential geometry.  Both of the references in the comments - Spivak and Madsen & Tornehave - are good and should have what you need, the latter a bit more useful in my opinion.  But I am writing this answer because in neither text (or virtually any other introductory differential geometry text) will you encounter explicitly your definition of the cotangent bundle, or for that matter words like "sheaf" and "germ".  Such notions are useful in differential geometry, but it is not so crucial to incorporate them into the foundations the way it is in algebraic geometry.
A definition that you will see in books (in some form) proceeds as follows.  Given a point $p$ in $M$, define the tangent space $T_p M$ to be the vector space of point derivations of $C^\infty(M)$ at $p$.  If $(x_1, \ldots, x_n): U \subseteq M \to \mathbb{R}^n$ is a local coordinate system near $p$ then the directional derivative derivations $\frac{\partial}{\partial x_i}|_{p}$ form a basis of $T_p M$.  Construct a vector bundle $TM$ whose fiber over a point $x$ in $M$ is $T_x M$, and form its dual $T^*M$.  This is the cotangent bundle, and it takes only some basic techniques with sheaves to prove that it is the same as what you defined.
The equivalence of this definition with your first definition is just a bunch of coordinate calculations, complicated by the fact that Rudin defines surfaces extrinsically (in contrast to the intrinsic definitions that you and I produced).  From the intrinsic point of view, a differential k-form is a smooth section of the bundle $\wedge^k T^*M$.  As above, a local coordinate system $(x_1 \ldots x_n)$ on an open neighborhood $U$ of $M$ yields a trivializing frame $\frac{\partial}{\partial x_1}, \ldots, \frac{\partial}{\partial x_n}$ for $TM$ over $U$, and the corresponding dual frame for $T^*M$ over $U$ is denoted by $dx_1 \ldots dx_n$.  Thus a trivializing frame for $\wedge^k T^*M$ is given by $\{ dx_{i_{1}} \wedge \ldots \wedge dx_{i_{k}}: 1 \leq i_{1} \leq \ldots \leq i_{k} \leq n\}$, which more or less explains the local formula in your question.  The details of your integral formula are explained by noting that Rudin is defining a $k$ form on $\mathbb{R}^n$ with its standard coordinate system and pulling it back to a $k$ form on the surface along the embedding of the surface in $\mathbb{R}^n$.  Thus it is necessary to sort out how an intrinsic differential form behaves under coordinate change (from $\mathbb{R}^n$ coordinates to coordinates on the surface), and the whole point of the theory is that they change in a way which makes integration coordinate invariant.
One last comment.  Rudin defines differential k-forms for k-dimensional surfaces in $\mathbb{R}^n$ which comes naturally equipped with a notion of integration.  Of course most interesting manifolds (e.g. the sphere) are not the images of compact domains in $\mathbb{R}^k$ embedded in $\mathbb{R}^n$; this is the right LOCAL picture, but not the right global picture.  So to properly define the integral of a k-form over a k-manifold, it is necessary to define the global integral in terms of patched-together local integrals via a partition of unity.  Most books set up the theory this way and prove that the integral doesn't depend on the choice of partition of unity, but no books explain why, for example, the intrinsic integral of an n-form $f dx_1 \wedge \ldots \wedge dx_n$ over an open set in $\mathbb{R}^n$ (involving partitions of unity) agrees with standard Lebesgue integral of $f$ over that open set.  I suspect that one would have to sort out this kind of issue in order to REALLY prove that your two notions of differential form agree.  It's possible to work this out on your own, but Brian Conrad sorted it out in his "How to compute integrals" handout here:
http://math.stanford.edu/~conrad/diffgeomPage/handouts.html
You might find some of the other handouts helpful too.


text:
Q: subprocess.getoutput with sed shell command in Python 3 returns null string I use the following command in sh or bash to obtain the resolution of a movie file:
/opt/local/bin/ffmpeg -i TEST.mp4 2>&1 | sed -n "s/.*, \(.*\) \[.*/\1/p"

...and it returns a string like "640x480" for the input file resolution. Great.
Converting this over to a Python 3.4 script, I can't seem to get it to work:
import subprocess
stdoutstr = subprocess.getoutput('/opt/local/bin/ffmpeg -i /Users/alexis/TEST.mp4 2>&1 | /usr/bin/sed -n "s/.*, \(.*\) \[.*/\1/p"')
print("stdoutstr:" + stdoutstr.split()[0])

The Python 3 code above returns a null string. How can I get this to work?

A: If you used subprocess.check_output it will throw an exception if the command fails. This would give you an idea of what is going wrong.
But the real issue is that you must specify shell=True to allow the shell to interpret your redirections. Otherwise the executed command will contain the literal metacharacters like | and space which you probably don't want.
Without shell=True, it is just like if you put single quotes around the entire command at the shell prompt. That will obviously fail with a command not found error.
This should work for you:
stdoutstr = subprocess.check_output(
    """/opt/local/bin/ffmpeg -i /Users/alexis/TEST.mp4 2>&1 | /usr/bin/sed -n 's/.*, \(.*\) \[.*/\\1/p'""",
    shell=True, universal_newlines=True)

I'll warn you that on my machine ffmpeg is not located in /opt/local/bin and sed is not located in /usr/bin/sed. On my machine, ffmpeg is in /usr/bin and sed is in /bin/sed, so I had to tweak the command slightly to put it back in your original example. Alternatively, if these locations are already in your PATH, you could just remove them entirely:
stdoutstr = subprocess.check_output(
    """ffmpeg -i /Users/alexis/TEST.mp4 2>&1 | sed -n 's/.*, \(.*\) \[.*/\\1/p'""",
    shell=True, universal_newlines=True)


text:
Q: Google Batch API, multiple authorization headers Looking for some help with the Google Batch API,
got two valid access tokens for two different accounts under the same domain/organization and want to batch two calls, each with it's own authorization header.
If I'm reading into it correctly, it should be possible according to the API docs:

The HTTP headers for the outer batch request, except for the Content- headers such as Content-Type, apply to every request in the batch. If you specify a given HTTP header in both the outer request and an individual call, then the individual call header's value overrides the outer batch request header's value. The headers for an individual call apply only to that call.
For example, if you provide an Authorization header for a specific call, then that header applies only to that call. If you provide an Authorization header for the outer request, then that header applies to all of the individual calls unless they override it with Authorization headers of their own.

Testing it out with Postman (POST https://www.googleapis.com/batch)
when the request has no authentication header but the inner request has valid authentication headers:
--batch_foobarbaz
Authorization:Bearer <accesstoken1>
Content-Type: application/http Content-ID: one

GET /gmail/v1/users/me/profile

--batch_foobarbaz
Authorization:Bearer <accesstoken2>
Content-Type: application/http
Content-ID: two

GET /gmail/v1/users/me/profile

--batch_foobarbaz--

I get as a response "Login Required" for both of the requests:
--batch_x-oYQ5TohrI_AAd7PA4mQcg
Content-Type: application/http
Content-ID: response-one

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="https://accounts.google.com/"
Content-Type: application/json; charset=UTF-8
Date: Sun, 12 Nov 2017 12:28:55 GMT
Expires: Sun, 12 Nov 2017 12:28:55 GMT
Cache-Control: private, max-age=0
Content-Length: 238

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Login Required",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Login Required"
 }
}

--batch_x-oYQ5TohrI_AAd7PA4mQcg
Content-Type: application/http
Content-ID: response-two

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="https://accounts.google.com/"
Content-Type: application/json; charset=UTF-8
Date: Sun, 12 Nov 2017 12:28:55 GMT
Expires: Sun, 12 Nov 2017 12:28:55 GMT
Cache-Control: private, max-age=0
Content-Length: 238

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Login Required",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Login Required"
 }
}

--batch_x-oYQ5TohrI_AAd7PA4mQcg--

As Google commands me, on my second attempt I put an authentication header on the request with "accesstoken1" hoping the inner requests headers would override it:
--batch_foobarbaz
Content-Type: application/http
Content-ID: one
Authorization: Bearer <accesstoken1>

GET /gmail/v1/users/me/profile

--batch_foobarbaz
Content-Type: application/http
Content-ID: two
Authorization: Bearer <accesstoken2>

GET /gmail/v1/users/me/profile

--batch_foobarbaz--

However, the inner Authorization headers gets ignored and I get the same response for both inner requests:
--batch_acwJ2jJl7Vk_AAwDDvF7GqQ
Content-Type: application/http
Content-ID: response-one

HTTP/1.1 200 OK
ETag: "Sa8s0oAMlJSbjHHTmOHVq5KXvZM/ij85zVL5i9x1u7LOtgNBEd-PGZY"
Content-Type: application/json; charset=UTF-8
Date: Sun, 12 Nov 2017 12:52:16 GMT
Expires: Sun, 12 Nov 2017 12:52:16 GMT
Cache-Control: private, max-age=0
Content-Length: 108

{
 "emailAddress": "user1@whatever.com",
 "messagesTotal": 16,
 "threadsTotal": 13,
 "historyId": "7294"
}

--batch_acwJ2jJl7Vk_AAwDDvF7GqQ
Content-Type: application/http
Content-ID: response-two

HTTP/1.1 200 OK
ETag: "Sa8s0oAMlJSbjHHTmOHVq5KXvZM/ij85zVL5i9x1u7LOtgNBEd-PGZY"
Content-Type: application/json; charset=UTF-8
Date: Sun, 12 Nov 2017 12:52:16 GMT
Expires: Sun, 12 Nov 2017 12:52:16 GMT
Cache-Control: private, max-age=0
Content-Length: 108

{
 "emailAddress": "user1@whatever.com",
 "messagesTotal": 16,
 "threadsTotal": 13,
 "historyId": "7294"
}

--batch_acwJ2jJl7Vk_AAwDDvF7GqQ--

If anyone can make sense of this I'd be forever grateful
Thanks!

A: I guess your inner authentication headers would come after the GET/POST requests.
For example
GET https://www.googleapis.com/calendar/v3/calendars/primary/events
Authorization:Bearer XXXXXXXXXXXXXXXXXXXX
instead of
Authorization:Bearer XXXXXXXXXXXXXXXXXXXX
GET https://www.googleapis.com/calendar/v3/calendars/primary/events.
In your example, it would be
--batch_foobarbaz
Content-Type: application/http
Content-ID: one
GET /gmail/v1/users/me/profile
Authorization: Bearer
This worked for me. Let me know if this is working for you.


text:
Q: To create Swipeable tabs without ActionBar I would like to create swipeable tabs without action bar at its top as shown as in the link. I've used the following lines : setDisplayShowHomeEnabled(false);
 setDisplayShowTitleEnabled(false);
Also here is my Layout xml.
Can anyone please help me how I can achieve this.

A: Your layout should be set up similar to this:
<LinearLayout>
    <ToolBar/>
    <TabBar/>
    <ViewPager/>
</LinearLayout>

Also you should choose a theme without ActionBar (i.E. Theme.AppCompat.Light.NoActionBar) for your application, and not call setSupportActionbar()


text:
Q: How to filter and display image with respect to text in Angular I want to display flag image from asset folder with respect to country code which I am getting in API response.
HTML:-

{{contacts.purpose}}

{{contacts.contactNumber}}

Componen file :-
ngOnInit(): void {

  //initialize
  this.keycontact = this.keyContactService.getKeyContacts()

    //Subscribe
    this.keyContactService.updatedkeyContacts.subscribe((contacts)=>{
      this.keycontact = contacts
      console.log(this.keycontact);
    })

    // Api Call
    this.keyContactApis.fetkeyContDetails();
  }

response as :-
    {
                "id": 28,
                "purpose": "HR related queries",
                "contactNumber": "+1 201-350-8620",
                "contactPerson": "Abhishek  Kaashyap",
                "location": "NA",
                "employeeSubsidiary": "LLC",
                "region": "US",
                "workCity": "US",
                "beforeFlip": "NULL",
                "initials": "HR"
            },
{
                "id": 29,
                "purpose": "HR related queries",
                "contactNumber": "+91 995-350-8620",
                "contactPerson": "Abhishek  Kaashyap",
                "location": "NA",
                "employeeSubsidiary": "LLC",
                "region": "IND",
                "workCity": "IND",
                "beforeFlip": "NULL",
                "initials": "HR"
            }

The response is dynamic with more objects.How I can pick region key and check text = US or IND or more other countries and accordingly pass flag image path in the  in HTML ?

A: You can use Angular Intepolation just how you did in your p tags:

{{contacts.purpose}}

so your img tag can look something like this:

Edit
With Property Bindng you can dynamically get your file with a method:

and in your .ts file declare a method:
public getFlag(region: string): string {
    // your logic
}

A: You can maintain a constants file with the mappings and fetch the url using that.
constants.ts
class Constants

public static flagImageNames = {
    'usa': 'us',
    'can': 'can',
    ...
}

ts
public flagNames = Constants.flagImageNames;

html


text:
Q: Only let HTML continue once all images have loaded I recycled a lot of code from an old JS project I made back in the very beginning of my learning process, and back then I knew nothing about DOM events. Specifically in this case, onload. What I am looking for is someway to only let the website begin to run once all images have loaded, without putting everything into one big onload function, or rewriting all my code. Is there anyway to do this?

A: The simplest solution would be to set the display property of the body to none when the page is loading, and then have continue() make it visible.
CSS:
body {
    display: none;
}

JS:
function continue() {
    document.body.style.display = "";
}

A: If the images aren't going to be dynamically added to DOM  you can simply just do the followingaIf the images aren't going to be dynamically added to DOM  you can simply just do the following

If images are going to be dynamically added you could go for Mutation Observer, let me know if thats the case will add that too.


text:
Q: Gnome Disks' false report? I have a 3.5" HDD connected to my laptop via a SATA-USB adapter (JMicron). Gnome Disks "Assessment" section says:

Disk is OK, one bad sector

And the "SMART Data & Self-Tests" window looks like this:
Main "SMART Data & Self-Tests" window
With the strange "Updated: 52 years, 9 months and 23 days ago" field.
Refreshing and starting self-tests also not functioning:
Refresh error
Self-Test error
However, smartctl -a doesn't show any bad sectors (if I'm correct):
smartctl 7.3 2022-02-28 r5338 [x86_64-linux-5.19.15-201.fc36.x86_64] (local build)
Copyright (C) 2002-22, Bruce Allen, Christian Franke, www.smartmontools.org

=== START OF INFORMATION SECTION ===
Model Family:     SAMSUNG SpinPoint F3
Device Model:     SAMSUNG HD103SJ
Firmware Version: 1AJ10001
User Capacity:    1,000,204,886,016 bytes [1.00 TB]
Sector Size:      512 bytes logical/physical
Rotation Rate:    7200 rpm
Form Factor:      3.5 inches
Device is:        In smartctl database 7.3/5319
ATA Version is:   ATA8-ACS T13/1699-D revision 6
SATA Version is:  SATA 2.6, 3.0 Gb/s
SMART support is: Available - device has SMART capability.
SMART support is: Enabled

=== START OF READ SMART DATA SECTION ===
SMART overall-health self-assessment test result: PASSED

General SMART Values:
Offline data collection status:  (0x00) Offline data collection activity
                    was never started.
                    Auto Offline Data Collection: Disabled.
Self-test execution status:      (   0) The previous self-test routine completed
                    without error or no self-test has ever
                    been run.
Total time to complete Offline
data collection:        ( 9240) seconds.
Offline data collection
capabilities:            (0x5b) SMART execute Offline immediate.
                    Auto Offline data collection on/off support.
                    Suspend Offline collection upon new
                    command.
                    Offline surface scan supported.
                    Self-test supported.
                    No Conveyance Self-test supported.
                    Selective Self-test supported.
SMART capabilities:            (0x0003) Saves SMART data before entering
                    power-saving mode.
                    Supports SMART auto save timer.
Error logging capability:        (0x01) Error logging supported.
                    General Purpose Logging supported.
Short self-test routine
recommended polling time:    (   2) minutes.
Extended self-test routine
recommended polling time:    ( 154) minutes.
SCT capabilities:          (0x003f) SCT Status supported.
                    SCT Error Recovery Control supported.
                    SCT Feature Control supported.
                    SCT Data Table supported.

SMART Attributes Data Structure revision number: 16
Vendor Specific SMART Attributes with Thresholds:
ID# ATTRIBUTE_NAME          FLAG     VALUE WORST THRESH TYPE      UPDATED  WHEN_FAILED RAW_VALUE
  1 Raw_Read_Error_Rate     0x002f   100   100   051    Pre-fail  Always       -       48
  2 Throughput_Performance  0x0026   056   056   000    Old_age   Always       -       8387
  3 Spin_Up_Time            0x0023   071   069   025    Pre-fail  Always       -       9027
  4 Start_Stop_Count        0x0032   088   088   000    Old_age   Always       -       12587
  5 Reallocated_Sector_Ct   0x0033   252   252   010    Pre-fail  Always       -       0
  7 Seek_Error_Rate         0x002e   252   252   051    Old_age   Always       -       0
  8 Seek_Time_Performance   0x0024   252   252   015    Old_age   Offline      -       0
  9 Power_On_Hours          0x0032   100   100   000    Old_age   Always       -       11581
 10 Spin_Retry_Count        0x0032   252   252   051    Old_age   Always       -       0
 11 Calibration_Retry_Count 0x0032   252   252   000    Old_age   Always       -       0
 12 Power_Cycle_Count       0x0032   089   089   000    Old_age   Always       -       11952
191 G-Sense_Error_Rate      0x0022   100   100   000    Old_age   Always       -       107
192 Power-Off_Retract_Count 0x0022   252   252   000    Old_age   Always       -       0
194 Temperature_Celsius     0x0002   063   053   000    Old_age   Always       -       37 (Min/Max 16/47)
195 Hardware_ECC_Recovered  0x003a   100   100   000    Old_age   Always       -       0
196 Reallocated_Event_Count 0x0032   252   252   000    Old_age   Always       -       0
197 Current_Pending_Sector  0x0032   252   100   000    Old_age   Always       -       0
198 Offline_Uncorrectable   0x0030   252   252   000    Old_age   Offline      -       0
199 UDMA_CRC_Error_Count    0x0036   100   100   000    Old_age   Always       -       21
200 Multi_Zone_Error_Rate   0x002a   100   100   000    Old_age   Always       -       1423
223 Load_Retry_Count        0x0032   252   252   000    Old_age   Always       -       0
225 Load_Cycle_Count        0x0032   099   099   000    Old_age   Always       -       12629

SMART Error Log Version: 1
No Errors Logged

SMART Self-test log structure revision number 1
Num  Test_Description    Status                  Remaining  LifeTime(hours)  LBA_of_first_error
# 1  Extended offline    Completed without error       00%     11581         -
# 2  Short offline       Completed without error       00%     11560         -
# 3  Extended offline    Completed without error       00%     11530         -
# 4  Extended offline    Completed without error       00%     11442         -
# 5  Extended offline    Aborted by host               90%     11440         -
# 6  Short offline       Completed without error       00%     11440         -
# 7  Short offline       Completed without error       00%       133         -
# 8  Short offline       Completed without error       00%       133         -
# 9  Short offline       Aborted by host               60%       133         -
#10  Short offline       Aborted by host               90%       133         -

SMART Selective self-test log data structure revision number 0
Note: revision number not 1 implies that no selective self-test has ever been run
 SPAN  MIN_LBA  MAX_LBA  CURRENT_TEST_STATUS
    1        0        0  Completed [00% left] (0-65535)
    2        0        0  Not_testing
    3        0        0  Not_testing
    4        0        0  Not_testing
    5        0        0  Not_testing
Selective self-test flags (0x0):
  After scanning selected spans, do NOT read-scan remainder of disk.
If Selective self-test is pending on power-up, resume after 0 minute delay.

What's going on? Could someone please explain this?

A: You should run the following SMART Tests first:
sudo smartctl --test=long /dev/sdX

And then you can run
sudo smartctl --log=selftest
sudo smartctl --log=error

This output should give you more insights.
But please understand SMART tests are self tests performed by the disk firmware itself. What if the firmware is designed to show false positives? While GNOME disks utility is showing you the real data?
There is another program which also helps detect bad blocks
sudo badblocks -v /dev/sdX > bad-sectors.txt

The above command shall write the information about bad-blocks to the file (or stdout if you remopve the redirection) while it will give status information in stderr. Just be aware that this command takes a considerable amount of time to run.
I had also faced a similar problem. Bad blocks gave me the following output, while GNOME disks utility still kept saying 1 bad sector

Checking blocks 0 to 500107607
Checking for bad blocks (read-only test): done
Pass completed, 0 bad blocks found. (0/0/0 errors)


text:
Q: Memory used by SparseArray objects In dealing with a quantum mechanics problem, I am representing some many-body states in two different ways in Mathematica. For two parameters n and l the representations are

*

*A list of length n which is a partition of l into integers, 0 included, sorted in decreasing order.

*A list of length l+1 counting how many times each integer 0,...,l occurs in representation 1.

An example: for n=4,l=5, a state could be either represented as

*

*{3,1,1,0}

*{1,2,0,1,0,0}
where the latter list is interpreted as "one 0, two 1's, zero 2's etc".
Typically n is small, 10 or so, while l is maximally l=n(n-1). This means that representation 2 is often very sparse when all integer partitions are considered, so I'm using SparseArray's to store them. However today I did the followig:
Sum[ByteCount[c2[a]], {a, dim}]
(* 4 087 776 *)

Sum[ByteCount[Normal@c2[a]], {a, dim}]
(* 2 009 328 *)

where c2[a] is representaton 2 of state number a and dim is the number of states. What gives??
EDIT: I generate the set of all representation-1 lists with
c1 = IntegerPartitions[l, {n}, Range[0, l]];
dim = Length[c1];

Then, the following sets up representation 2:
counter[i_, l_] :=
 Block[{tally},
  tally = Tally@Reverse@c1[[i]];
  c2[i] = SparseArray[{#1 + 1} -> #2 & @@@ tally, l + 1]
  ];
Scan[counter[#,l]&,Range[dim]]


text:
Q: "indigenous culture" or "native culture" The different development paths of indigenous culture/ native culture in the drainage basins of the Red River, Ma River, Ca River, etc converged into the formation of Dong Son Culture. This was the period that the first state in Vietnam was born under the form of a community, primitive tribes developed into a nation therefrom.
I'm writing about Vietnamese culture. I want to convey the meaning the culture of local inhabitants in those areas. But I get confused between the indigenous and native culture as they're a bit similar.
Plus, I used the term indigenous culture once and was pointed out that it might cause misleading information. In particular, people might understand it as the culture of people before the colonization by other countries
I'm not sure what to use. Please help

A:
The Dongson were late bronze/early iron age metallurgists, and their
cities and villages were located in the deltas of the Hong, Ma and Ca
rivers of northern Vietnam: as of 2010, more than 70 sites had been
discovered in a variety of environmental contexts.*
Article on the Dongson

Indigenous is the most inclusive term, as there are Indigenous peoples on every continent throughout the world – such as the Sami in
Sweden, the First Nations in Canada, Mayas in Mexico and Guatemala,
and the Ainu in Japan – fighting to remain culturally intact on their
land bases.
indigenous peoples_from UCLA-Equity

Changes:
The different development paths of the indigenous culture in the deltas of the Red River, Ma River and Ca River were the foundation of the Dongson Culture.
Note: drainage basis sounds hydrological, not really geographic.

A: If the culture was made up of entirely, or almost entirely, of people whose ancestors had lived in the area for centuries, 'indigenous' is correct.
If the population was a mix of such people and migrants and/or conquerors, (even if they were, nonetheless settled), then 'native' would be a better option.


text:
Q: class def not found in jboss as 7.X I have a project structure as
eardirectory.Ear
  lib/
    my-custom-classes.jar
    .....
    .....
  my-custom-ejb.jar
  META-INF/
    ....

//Now I tried to load classes from classloader as
ClassLoader cl = Thread.currentThread().getContextClassLoader();
clazz = Class.forName(my-custom-classes.class1.class.getName(), true, cl);

but this will not work as current thread is of jboss and jboss has not any identification of my-custom-classes.jar.So my question is how this can be done with jboss? I have to have to load class definition at runtime.
Is there any way in "jboss-deployment-structure" I can define how to load classes before deploying EAR?

A: Follow the steps to create module it should work
Step-1
In jboss-as-7.1.1.Final/modules/com/company/gyani/main/
                      -module.xml
                      -my-custom-classes.jar

  Content of  module.xml

 <?xml version="1.0" encoding="UTF-8"?>
      <module xmlns="urn:jboss:module:1.0" name="com.company.gyani">
    <resources>
      <resource-root path="my-custom-classes.jar"/>
    </resources>
    <dependencies>
      <module name="javax.api"/>
         </dependencies>
      </module>

Step-2 Now IN my.ear/META-INF/
      -jboss-deployment-structure.xml
      -MANIFEST.MF

Content of MANIFEST.MF
    Manifest-Version: 1.0
    Dependencies: com.company.gyani

A: You need to use concept of module(s) provided by JBoss AS7.
Here you configure your classes/jars/property files as modules and these are loaded while starting JBoss at server scope and are accessible to any deployed application that carries a dependency on this module.
Read through How to configure module


text:
Q: Does the six library comes shipped with default python today? How to install the Six module in Python2.7 shows that six has to be pip installed.
But does the six library comes shipped with default python python2.7.x and python3.x today?

A: No.  You can see the list of standard library modules here.


text:
Q: Strange Errors. Using rand() and arrays within a loop I really can not explain what is going on with my program. I really can't spot what may be causing the problems. It occurs within this function
void test()
{
    srand(time(NULL));

    questionNo = 1;

    for (testLoop = 0; testLoop < 10; ++testLoop)
    {
        const char opArray[3] = { 'x', '+', '-' };
        int pickValue = rand() % 3;
        char Operator = opArray[pickValue];

        int n1 = rand() % 20 + 1;
        int n2 = rand() % 20 + 1;

        if (Operator = '+')
            answer = n1 + n2;
        else if (Operator = '-')
            answer = n1 - n2;
        else
            answer = n1 * n2;

        cout << "Question " << questionNo << "\n";
        ++questionNo;
        cout << n1 + " " << Operator + " " << n2 << "?";
        userAnswer = cin.get();

        if (userAnswer = answer)
        {
            cout << "\n\n Correct!\n";
            system("cls");
            ++score;
        }
        else
        {
        cout << "\n\n Incorrect!\n";
        system("cls");
        }
        Sleep(500);
    }
    cout << "You scored " << score << " out of 10!";
    fileWrite(score);
}

An example of what occurs is the following.
This outputs to console
Question 1
@Øÿ×╝׳×0ƒ11?
What even is that???
It also skips two questions every time. For example it goes
"Question 1"
"Question 3"
"Question 5"

A: You are using the assignment operator = instead of the comparison operator == in this code snippet
    if (Operator = '+')
        answer = n1 + n2;
    else if (Operator = '-')
        answer = n1 - n2;
    else
        answer = n1 * n2;

Chnage it the following way
    if (Operator == '+')
        answer = n1 + n2;
    else if (Operator == '-')
        answer = n1 - n2;
    else
        answer = n1 * n2;

There is the same error in this statement
   if (userAnswer = answer)

Also instead of
   userAnswer = cin.get();

use operator >>.
sin >> userAnswer;

There is also a typo in this statement
    cout << n1 + " " << Operator + " " << n2 << "?";

There should be
    cout << n1 << " " << Operator << " " << n2 << "?";

A: You have:
cout << n1 + " " << Operator + " " << n2 << "?";

You should be using << in place of + both times:
cout << n1 << " " << Operator << " " << n2 << "?";

The n1 + " " term is adding the value of n1 to the address where the one-blank string is stored, generating a char *, and then the << is printing whatever garbage it finds beyond the end of that string (assuming n1 is positive and greater than 1, or what it finds before the string if it is negative).  Effectively, you've written &" "[n1] for that term. Similarly with the other addition expression.
This explains the peculiar output you are getting.  You also have multiple problems with assignment = where you intend comparison ==.


text:
Q: validating a drop down list using javascript <?PHP
session_start();
if (isset($_SESSION['login']) && $_SESSION['login'] = '1') {
        //=========================================================
        //The following page is used to create a dynamic survey.
        //=========================================================
        $qNum = 'q1';
        $question = 'Question not set';
        $answerA = 'unchecked';
        $answerB = 'unchecked';
        $answerC = 'unchecked';
        $qID = array();
        $question = array();
        $A = array();
        $B = array();
        $C = array();
        $D = array();
        $E = array();
        $quesType = array();
        $survey_Answers1 = '';
        $nominatefriend = '';
        //============================================
        //  OPEN A CONNECTION TO THE DATABASE
        //============================================
        $user_name = "root";
        $password = "";
        $database = "surveyTest";
        $server = "127.0.0.1";
        $mysqli = new mysqli($server, $user_name, $password, $database);
        $SID = $_SESSION['user'];
        if (!mysqli_connect_errno()) {
            $result = $mysqli->query("SELECT * FROM tblquestions ORDER BY SUBSTRING(QID,2)+0");
            $numRows = mysqli_num_rows($result); //return number of rows in the table
            //var_dump($numRows);
            echo '<FORM NAME ="form1" METHOD ="POST" ACTION ="survey.php">';
            for ($i = 1; $i <= $numRows; $i++)
            {
                //var_dump ($mysqli->error);
                //var_dump($i);
                $db_field = mysqli_fetch_assoc($result);
                //var_dump($db_field);
                $qID[$i] = $db_field['QID'];
                $question[$i] = $db_field['Question'];
                $quesType = $db_field['qType'];
                //var_dump($quesType);
                $A[$i] = $db_field['qA'];
                $B[$i] = $db_field['qB'];
                $C[$i] = $db_field['qC'];
                $D[$i] = $db_field['qD'];
                $E[$i] = $db_field['qE'];
                if ($quesType == 'rating')
                {
                    echo '
';
                    print $qNum.': '.$question[$i];
                    echo '
';
                    if ($A[$i] != ""){
                        echo "<INPUT TYPE = 'Radio' Name = '".$qNum."'  value= '".$A[$i]."' id = '".$qNum."'>";
                        print $A[$i];
                    }
                    echo '
';
                    if ($B[$i] != ""){
                        echo "<INPUT TYPE = 'Radio' Name = '".$qNum."'  value= '".$B[$i]."' id = '".$qNum."'>";
                        print $B[$i];
                    }
                    echo '
';
                    if ($C[$i] != ""){
                        echo "<INPUT TYPE = 'Radio' Name = '".$qNum."'  value= '".$C[$i]."' id = '".$qNum."'>";
                        print $C[$i];
                    }
                    echo '
';
                    if ($D[$i] != ""){
                        echo "<INPUT TYPE = 'Radio' Name = '".$qNum."'  value= '".$D[$i]."' id = '".$qNum."'>";
                        print $D[$i];
                    }
                    echo '
';
                    if ($E[$i] != ""){
                        echo "<INPUT TYPE = 'Radio' Name = '".$qNum."'  value= '".$E[$i]."' id = '".$qNum."'>";
                        print $E[$i];
                    }
                    echo "";
                    if (isset($_POST[$qNum])){
                        $survey_Answers1 = $survey_Answers1.', '.$_POST["$qNum"];
                        var_dump($survey_Answers1);
                    }
                    $question_Number = ltrim($qNum,'q');
                    $question_Number++;
                    $qNum ='q'.$question_Number;
                }
                else if ($quesType == 'nominate')
                {
                    //echo "<INPUT TYPE = 'hidden' Name = '".$qNum."'  id = '".$qNum."'>";
                    $number_of_Combos = $A[$i];
                    //var_dump($number_of_Combos);
                    echo '
';
                    print $qNum.': '.$question[$i];
                    echo '
';
                    for ($j = 1; $j <=  $number_of_Combos; $j++)
                    {
                        $nominatefriend = $qNum.$j;
                        //var_dump($nominatefriend);
                        $result_Combo = $mysqli->query("SELECT SID, fName, lName FROM students WHERE SID!='$SID'");
                        echo "<select name  = '".$nominatefriend."' id = '".$qNum."'>";
                        echo "<option value = '0'>".'Select a Name'."</option>";
                        while ($select_query_array = mysqli_fetch_array($result_Combo))
                        {
                            echo "<option value='".$select_query_array['SID']."'>".$select_query_array['fName'].' '.$select_query_array['lName']."</option>";
                        }
                        echo "</select>";
                    }

                    $question_Number = ltrim($qNum,'q');
                    $question_Number++;
                    $qNum ='q'.$question_Number;
                    //var_dump ($qNum);
                }
            }
            echo '
';
            echo "<INPUT TYPE = 'hidden' Name = 'h2'  VALUE = '".$survey_Answers1."'>";
                        echo '
';
            echo '<INPUT TYPE = "Submit" Name = "Submit1"  VALUE = "Click here to vote">';
            echo '</form>';

                        //$value1 = $_POST['nominateFriend1'];
                        //var_dump($value1);
                        //$value2 = $_POST['nominateFriend2'];
                        //var_dump($value2);
                        //$value3 = $_POST['nominateFriend3'];
                        //var_dump($value3);

            mysqli_close($mysqli);
        }
        else {
            print "Error getting Survey";
            mysqli_close($mysqli);
        }
    }
    else
    {
        header("location:login.php");
    }
    $_SESSION['user'] = $SID;  // refers to student ID from the login page
?>

<title>Radio Buttons</title>

I'm trying to validate the drop down list which is created dynamically based on a value in mysql database. However, I'm getting the following error: TypeError: document.form1.nominatefriend is undefined in the following if condition:
if (document.form1[nominatefriend[i]].selected) {
  chosen[j] = document.form1.nominatefriend[i].value;
  alert (chosen[j]);
}

A: $nominatefriend = $qNum.$j;

echo "<select name  = '".$nominatefriend."' id = '".$qNum."'>";

so it's just undefined yet

A: The error says that nominatefriend is undefined.
If I look into your PHP file code I find that in line number 99 and 102 you have as
$nominatefriend = $qNum.$j;

echo "<select name  = '".$nominatefriend."' id = '".$qNum."'>";

If I look into more I find $qNum as
$qNum = 'q1';

Thus it will be probably document.form1.q1[i] rather than document.form1.nominatefriend[i].
Error is in the naming, so if you can view source the page, you will probably find the right value that should be used in your js.


text:
Q: listStatus endpoint include recipient status in response Is there a way to include the recipient statuses in the response body for the listStatus endpoint?
Here is the curl request I am making
curl -X PUT \
  https://na2.docusign.net/restapi/v2/accounts/XXXXX/envelopes/status?envelope_ids=request_body \
  -H 'Accept: application/json' \
  -H 'Content-Type: application/json' \
  -H 'X-DocuSign-Authentication: { ... }' \
  -d '{
    "envelopeIds": [
        "SOME ENVELOPE ID",
        "ANOTHER ENVELOPE ID"
    ]
  }'

Here is the result I am getting
{
    "resultSetSize": "76",
    "totalSetSize": "76",
    "startPosition": "0",
    "endPosition": "75",
    "nextUri": "",
    "previousUri": "",
    "envelopes": [
        {
            "status": "sent",
            "documentsUri": "/envelopes/XXXX/documents",
            "recipientsUri": "/envelopes/XXXX/recipients",
            "attachmentsUri": "/envelopes/XXXX/attachments",
            "envelopeUri": "/envelopes/XXXX",
            "envelopeId": "XXXX",
            "customFieldsUri": "/envelopes/XXXX/custom_fields",
            "notificationUri": "/envelopes/12da3965-99cb-4c2d-9d3d-587a32fca118/notification",
            "statusChangedDateTime": "2017-08-07T14:34:38.4530000Z",
            "documentsCombinedUri": "/envelopes/XXXX/documents/combined",
            "certificateUri": "/envelopes/XXXX/documents/certificate",
            "templatesUri": "/envelopes/XXXX/templates"
        },
        ...
    ]
}

In the documentation page, it shows an example response that includes
{
    "resultSetSize": "76",
    "totalSetSize": "76",
    "startPosition": "0",
    "endPosition": "75",
    "nextUri": "",
    "previousUri": "",
    "envelopes": [
        {
            "status": "sent",
            "documentsUri": "/envelopes/XXXX/documents",
            "recipientsUri": "/envelopes/XXXX/recipients",
            "attachmentsUri": "/envelopes/XXXX/attachments",
            "envelopeUri": "/envelopes/XXXX",
            "envelopeId": "XXXX",
            "customFieldsUri": "/envelopes/XXXX/custom_fields",
            "notificationUri": "/envelopes/12da3965-99cb-4c2d-9d3d-587a32fca118/notification",
            "statusChangedDateTime": "2017-08-07T14:34:38.4530000Z",
            "documentsCombinedUri": "/envelopes/XXXX/documents/combined",
            "certificateUri": "/envelopes/XXXX/documents/certificate",
            "templatesUri": "/envelopes/XXXX/templates",
            "recipients": {
              "signers": [
                {
                   "status": "sent",
                   ...
                }
              ]
            },
        },
        ...
    ]
}

I am not sure what I need to do to my original request to includes that recipients section in the response. Does anyone know if I am missing some kind of url param or body param or something?

A: This is not possible in the Envelopes: listStatus endpoint, it seems the response which you are seeing in sample JSON is autocreated by Swagger for the Envelope class. If you want to see all the details in one call then you need to make such call for each envelope using below endpoint,
/restapi/v2/accounts/{{AccountIdVal}}/envelopes/{envelopeId}?include=custom_fields,recipients,tabs&advanced_update=true


text:
Q: mod_wsgi-express: error: no such option: --url-alias I'm deploying an application with mod_wsgi-express, and I've a new error when launching the service :
oct. 12 09:15:29 Angara mod_wsgi-express[12284]: Usage: mod_wsgi-express start-server script [options]
oct. 12 09:15:29 Angara mod_wsgi-express[12284]: mod_wsgi-express: error: no such option: --url-alias /static /var/www/agenda-v3.example.tld/static     --url-alias /media /var/www/agenda-v3.example.tld/media

The mod_wsgi-express application fails to launch...
I've added the --log-directory directive to route logs to the ${SERVER_PATH}/log, which works great (I can read the log files now),
Have you any idea ? It worked before...
I've checked the /var/www/agenda-v3.example.tld/media and /var/www/agenda-v3.example.tld/static directories, they exist for now.
Thanks for your help !

A: The problem is that WSGI_URL_ALIASES is being passed through and interpreted as a single value rather than three separate arguments.
IOW, the argument is seen as single value of:
--url-alias /static /var/www/agenda-v3.example.tld/static

What I would actually suggest you do is use setup-server to pre-setup the mod_wsgi-express directory with the options you required. The only thing your init files then need to do is apachectl start and apachectl stop. All the stuff about options is recorded in scripts in the mod_wsgi-express directory.
See the PyPi page about using setup-server.

*

*https://pypi.python.org/pypi/mod_wsgi


text:
Q: Count the total (N) of duplicates in a column I'm attempting to count the total number of duplicates in a column (not the individual duplicates).
from outputs
GROUP BY journal_id
HAVING ( COUNT(doi) > 1 )
WHERE journal_id = 1

SQL TABLE
doi   journal_id
123       1
123       2
123       1
124       1

The expected answer is 2

A: The number of entire row duplicates can be calculated by taking the total number of rows and subtracting the number of distinct rows:
select a.cnt_all - d.cnt_individual
from (select count(*) as cnt_all
      from outputs
     ) a cross join
     (select count(*) as cnt_individual
      from (select distinct *
            from outputs
           ) d
     ) d;

If you know your columns and your database supports multiple arguments to count(distinct), this can be radically simplified to:
select count(*) - count(distinct doi, journal_id)
from outputs;

Or, if your database doesn't support this:
select sum(cnt - 1)
from (select doi, journal_id, count(*) as cnt
      from outputs
      group by doi, journal_id
     ) o;

A: Just sum up the count of the individual duplicates by journal id.
SELECT
  SUM(COUNT(doi)) AS total_duplicates
from
  outputs
WHERE
  journal_id = 1
GROUP BY
  journal_id
HAVING
  (COUNT(doi) > 1)


text:
Q: How to include a header file in Visual Studio? I have a problem in VS2012, where I want to include a header file:
#include <FileReader>

The problem is that I want to read a file and store it into a matrix. However, the include directive fails so that I am unable to read it:
#include <mpi.h>
#include <iostream>
#include <FileReader>

int main(int argc, char* argv[])
{
int rows, cols;
float a[10];

//std::vector<float> vec;

FileReader fr("./SampleData.txt");

fr.getSize(rows, cols);

fr.getVector(a);

for (int i = 0; i < cols; i++)
    fr.getNextRow(a);

int i;

std::cin >> i;

return 0;
};

Could you please explain why this program does not compile?

A: The answer depends on what FileReader refers to.
Assuming that it refers to a header file for a class you designed yourself:

*

*Your should rename this header file into FileReader.h, as names without extension are by convention reserved to the compiler libraries;

*You should then enclose the header file name between double-quotes rather than angular brackets, as angular brackets are to be used for compiler libraries, or possibly for third-party libraries used in your project (boost...)

Thus, once FileReader is renamed into FileReader.h, the include directive should looks as shown below:
`#include "FileReader.h"`

UPDATE
The additional errors you encounter are *linker errors'. They mean that:

*

*Compilation of your source files works fine;

*However, some methods are declared in FileReader.h but no compiled code can be found for these methods.

The most likely explanation is that the source code for these methods is not included in the project. Thus, you must add this source code to your VS project. It is probably a file named FileReader.c or FileReader.cpp.


text:
Q: AWS EKS update-kubeconfig does not respect --role-arn flag Whenever I run the following command with the role that that was used to create the eks cluster...
aws eks update-kubeconfig --name eks-cluster --role-arn arn:aws:iam::999999999999:role/eksServiceRole

... I get the following error:
An error occurred (AccessDeniedException) when calling the DescribeCluster operation: User: arn:aws:iam::111111111111:user/username is not authorized to perform: eks:DescribeCluster on resource: arn:aws:eks:us-east-1:561353845098:cluster/eks-cluster

Does anybody have any advice on how to go about diagnosing and rectifying this error?

A: A couple of suggestions that may, or may not help:

*

*You may include --verbose to your command to perhaps get better details as to where it fails. Could it be that case that the user you are authenticated as are not able to assume the role specified?

*In the manual for aws-cli --role-arn is passed as a string, you should try to encapsulate it with double-quotes:
aws eks update-kubeconfig --name eks-cluster --role-arn "arn:aws:iam::999999999999:role/eksServiceRole"

*

*Try to manually assume the role through aws-cli.

*

*Verify your current authenticated session:
aws sts get-caller-identity

*Attempt to assume the role: aws sts assume-role --role-arn "arn:aws:iam::999999999999:role/eksServiceRole" --role-session-name test-eks-role

A: --role-arn is the role which will be used by aws-iam-authenticator when you run kubectl to get a token and is only injected in to the generated config; it is not used for fetching EKS resources in any way by the command.
The error you are hitting is because the AWS credentials you're using to run the update-kubeconfig command don't have permissions to describe that cluster.

A: I'm not that familiar with EKS but I guess the user that you're running the aws eks command as needs privileges to describe the cluster.
Does this run successfully?
~ $ aws eks describe-cluster --name eks-cluster

If not you'll need to check your aws-cli permissions and make that work first.
It's just a guess but hope that helps :)

A: If you receive an AccessDeniedException when calling an AWS API operation, then the AWS Identity and Access Management (IAM) user or role credentials that you are using do not have the required permissions to make that call.
To provide Amazon EKS admin permissions to a user, see Creating Amazon EKS IAM Policies.
(Reference:
https://docs.aws.amazon.com/eks/latest/userguide/troubleshooting.html#iam-error)

A: I came up with the same error. But after I updating the correct access key and secret key in the file .aws/credentials, problem was resolved.
Please note that you need to use access key and the secret key of a user who allows to perform AWS EKS realted actions.

A: Use sts assume-role method and then reassign credentials values from there
#!/bin/bash
export AWS_ACCESS_KEY_ID=xxx
export AWS_SECRET_ACCESS_KEY=xxx
ROLE_ARN="arn:aws:iam::xxx:role/Administrator"
CRED=$(aws sts assume-role --role-arn "${ROLE_ARN}" --role-session-name AWSCLI-Session)
export AWS_ACCESS_KEY_ID=$(echo "${CRED}"| jq -r '.Credentials.AccessKeyId')
export AWS_SECRET_ACCESS_KEY=$(echo "${CRED}"| jq -r '.Credentials.SecretAccessKey')
export AWS_SESSION_TOKEN=$(echo "${CRED}"| jq -r '.Credentials.SessionToken')
aws sts get-caller-identity
aws eks update-kubeconfig --name my-cluster --region region

A: Is your user ID with which you are creating the cluster MFA enabled? If so, you need to get the token and update the credentials file

A: Confirming that this bug with aws eks is still present as of 2020/04. I ran into the same issue as OP despite all configurations being correct. Eventually I found that aws eks update-kubeconfig --name eks-cluster --profile profilename succeeds if the IAM role to be assumed is defined in the config, an alternative that is supposed to do the exact same thing, so definitely a bug with aws eks

A: In my case this issue came as missing "profile" word in .aws/config for named profiles. If named profiles are not used, i.e. only default profile exist, "profile" is not needed.
Source: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html


text:
Q: EOF error in VS-code (not Working in terminal also) I use vs-code on Manjaro ann I've had numerous issues with it explained in this question following VS- CODE errors on manjaro, auto quit, can't open folder
I have the following code
import cv2
from random import randrange
#load data
trained_face_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

#Choose image
webcam = cv2.VideoCapture(0)

while True:
    successful_frame_read, frame = webcam.read()

    #convert to greyscale
    greyscaled_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    #detect faces
    face_coordinates = trained_face_data.detectMultiScale(greyscaled_img)

    #Draw a rectangle around the Face
    for (x, y, w, h) in face_coordinates:
        cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 255, 0, 10)

    #Display the image with the faces spotted
    cv2.imshow('Face detector', frame)
    key = cv2.waitKey(1)

    #stop if Q is pressed
    if key==81 or key==113:
    break

webcam.release()
print("code completed")

In the beginning, I had a syntax  error at
  File "Face_detector.py", line 24
    cv2.imshow('Face detector', frame)
    ^
SyntaxError: invalid syntax

I commented out the line but got the same error in the next line
  File "Face_detector.py", line 25
    key = cv2.waitKey(1)
    ^
SyntaxError: invalid syntax

So I went ahead and commented out every sing line till the end
and now I got an EOF error
 File "Face_detector.py", line 33

                            ^
SyntaxError: unexpected EOF while parsing

I tried running the script from the terminal but still has the exact same error
Here is an image of running the uncommented code from the terminal
Here is an image of running the final commented out code from the terminal

A: You are missing a parentheses at this line:
#Draw a rectangle around the Face
for (x, y, w, h) in face_coordinates:
    cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 255, 0, 10) # <-- Missing parentheses here


text:
Q: Simple Neural Network Transfer Function for 1 to -1 Output I am new to Neural Networks and currently in need of guidance for a question I was presented with.
Question: Consider a single-input neuron with a bias. We would like the output to be -1 for inputs less than 3 and +1 for inputs greater than or equal to 3. What kind of transfer function is required, and what bias would you suggest?
Again, I am new to this, and I am fairly certain the answer is obvious but I have little to go on right now. I originally considered going with either the Signum function or a Threshold function, but I do not achieve the answers I need. Any help or information will be greatly appreciated.

A: As you require such an immediate transition (i.e. <3 should be -1 and >=3 should equal 1) the the most appropriate activation function you could select to achieve this goal would be a binary step or threshold function as you rightly suggested:
Other common activation function are typically continuous and will not allow for this sort of transition.


text:
Q: How to add Google Calendar as a Unity launcher? Despite that I am able to create Unity launchers for Google Keep, Play Music, Inbox & Drawing; the same does not work for Google Calendar. I added Google Calendar to my Chrome as an application from extensions.google.com as I did for others.
Any ideas about how to add Google Calendar into Unity as a launcher?
p.s. I do not (want to) use Ubuntu Web Apps.

A: Not every Chrome-app brings its own menu-entry.
But you can create so-called app-shortcuts from Chrome-menu for any website you want. Those apps are placed on your desktop and/or application-menu and start in an own minimal browser-instance without menus, tabs or an address-bar.


text:
Q: Adding Strike-through effect in SSRS report textbox I am working on a SSRS report.
Business Requirement: One of the business req is that if the statusId which we get back comes as 3 then add a strikethrough line over the textbox. This textbox is outside the dataregion.
Here is what I have gotten so far but I am getting errors.
I right clicked on the textbox -> went to Properties. -> went to Font. ->
   clicked Expression button from effects and applied this syntax in
   there:
=IIf(sum(Fields!RequestStatusId.Value, "GetRequestById") = 3 "Default", "LineThrough")

Below is the error that I am getting:

Severity  Code    Description Project File    Line    Suppression State
  Error       [rsCompilerErrorInExpression] The TextDecoration expression for the textrun 'Textbox158.Paragraphs[0].TextRuns[0]' contains an error: [BC30455] Argument not specified for parameter 'TruePart' of 'Public Function IIf(Expression As Boolean, TruePart As Object, FalsePart As Object) As Object'.

What am I doing wrong ? Can someone help me with my expression which I applied. Thanks!

A: Missing a comma after the 3, assuming that is exactly the expression being used.
=IIf(sum(Fields!RequestStatusId.Value, "GetRequestById") = 3, "Default", "LineThrough")


text:
Q: Array of doubles to an Array of CLLocationCoordinate2D I upload the user's longitude and lattiude to firebase under two seperate key value pairs and then on the mapView I take a snapshot and obtain the longitude and the lattiude. I had to store them as strings, but I change them to doubles and store them in a 2D array of doubles. I then need to store it in a CLLocationCoordinate2D array. Then after that I need to plot those on the MapView. I am getting stuck on how to turn them into the CLLocationCoordinate2D array and then ploting those locations so that they all show up on the map.
My 2D array looks like this: bookLoc[[121.09900,56.5999],[123.94949, 45.0099]] //etc there are more points but I think this gets the point accoss.
I am not sure how to give CLLocationCoordinate2DMake given multiple coordinates. Thank you

A: Use map:
let arr = [[121.09900,56.5999], [123.94949, 45.0099], [...] ]
let coordinates = arr.map { CLLocationCoordinate2D(latitude: $0[0], longitude: $0[1]) }


text:
Q: Missing character 1 in font bbold11 I have a problem with my (freshly updated) MiKTeX installation: I like to use \mathbbold{1} from the bbold package to obtain a blackboard bold 1. This works with TeX Live under Linux, but for font size 11 it does not work with MiKTeX. If I compile
\documentclass[11pt]{article}
\DeclareSymbolFont{bbold}{U}{bbold}{m}{n}
\DeclareSymbolFontAlphabet{\mathbbold}{bbold}
\newcommand{\ind}{\mathbbold{1}}
\begin{document}
$a$ \tracingall $\mathbbold{1}$
\end{document}

then in the log file I get the line
Missing character: There is no 1 in font bbold11!

and no blackboard bold 1 in the output. With TeX Live (and with font size 10) everything works as expected.
The problem seems to be that under TeX Live, bbold/Ubbold.fd is loaded, whereas under MiKTeX, jknappen\ubbold.fd is loaded. The former uses bbold10.tfm, the latter bbold11.tfm.
How can I solve this problem?

A: In revision 4975 of TeX Live (2007-09-18) we find the annotation

omit ubbold.fd from jknapltx, clash with Ubbold.fd + sauter bbold disfunctional? (Zdenek Wagner, 9 Aug 2007 16:20:21 +0200)

So my suggestion is to remove the file ubbold.fd from your system and file a bug report to MiKTeX's maintainer.

A: I wouldn't count it as a miktex bug if two packages uses the same file name and imho the package maintainer should sort this out and not the tex distribuations.
When such name clashes in the same branch of a texmf tree exists the search result is not predictable -- it can e.g. depend on the installation order, date or whatever.
So you have imho the following possibilities:

*

*Move the correct fd-file to tex\latex in a root which is searched first (e.g. your local texmf).

*Copy the font definitions directly to your document. Then no fd-file will be loaded:
\documentclass[11pt]{article}
\DeclareFontEncoding{U}{}{}
\DeclareFontFamily{U}{bbold}{}
\DeclareFontShape{U}{bbold}{m}{n}
 {  <5> <6> <7> <8> <9> gen * bbold
   <10> <10.95> bbold10
  <12> <14.4> bbold12
 <17.28> <20.74> <24.88> bbold17
  }{}
\DeclareSymbolFont{bbold}{U}{bbold}{m}{n}
\DeclareSymbolFontAlphabet{\mathbbold}{bbold}

\begin{document}
$\mathbbold{1}$
\end{document}

*Make a copy of the correct fd-file e.g. as Umybbold.fd and store it somewhere where it can be found and then call declare the font as
\DeclareSymbolFont{bbold}{U}{mybbold}{m}{n}