问:
Splitting user input into strings of specific length
I'm writing a C program that parses user input into a char, and two strings of set length. The user input is stored into a buffer using fgets, and then parsed with sscanf. The trouble is, the three fields have a maximum length. If a string exceeds this length, the remaining characters before the next whitespace should be consumed/discarded.

```<code>#include <stdio.h>
#define IN_BUF_SIZE 256

int main(void) {
    char inputStr[IN_BUF_SIZE];
    char command;
    char firstname[6];
    char surname[6];

    fgets(inputStr, IN_BUF_SIZE, stdin);
    sscanf(inputStr, "%c %5s %5s", &command, firstname, surname);
    printf("%c %s %s\n", command, firstname, surname);
}
</code>```

So, with an input of

a bbbbbbbb cc

the desired output would be

a bbbbb cc

but is instead the output is

a bbbbb bbb

Using a format specifier "%c%*s %5s%*s %5s%*s" runs into the opposite problem, where each substring needs to exceed the set length to get to the desired outcome.

Is there way to achieve this by using format specifiers, or is the only way saving the substrings in buffers of their own before cutting them down to the desired length?

答:
In addition to the other answers, never forget when facing string parsing problems, you always have the option of simply walking a pointer down the string to accomplish any type parsing you require. When you read your string into buffer (my buf below), you have an array of characters you are free to analyze manually (either with array indexes, e.g. buffer[i] or by assigning a pointer to the beginning, e.g. char *p = buffer;) With your string, you have the following in buffer with p pointing to the first character in buffer:

```<code>--------------------------------
|a| |b|b|b|b|b|b|b|b| |c|c|\n|0|    contents
--------------------------------
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4      index
 |
 p
</code>```

To test the character pointed to by p, you simply dereference the pointer, e.g. *p. So to test whether you have an initial character between a-z followed by a space at the beginning of buffer, you simply need do:

```<code>    /* validate first char is 'a-z' and followed by ' ' */
    if (*p && 'a' <= *p && *p <= 'z' && *(p + 1) == ' ') {
        cmd = *p;
        p += 2;     /* advance pointer to next char following ' ' */
    }
</code>```

note:, you are testing *p first, (which is the shorthand for *p != 0 or the equivalent *p != '\0') to validate the string is not empty (e.g. the first char isn't the nul-byte) before proceeding with further tests. You would also include an else { /* handle error */ } in the event any one of the tests failed (meaning you have no command followed by a space).

When you are done, your are left with p pointing to the third character in buffer, e.g.:

```<code>--------------------------------
|a| |b|b|b|b|b|b|b|b| |c|c|\n|0|    contents
--------------------------------
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4      index
     |
     p
</code>```

Now your job is simply, just advance by no more than 5 characters (or until the next space is encountered, assigning the characters to firstname and then nul-terminate following the last character:

```<code>    /* read up to NLIM chars into fname */
    for (n = 0; n < NMLIM && *p && *p != ' ' && *p != '\n'; p++)
        fname[n++] = *p;
    fname[n] = 0;           /* nul terminate */
</code>```

note: since fgets reads and includes the trailing '\n' in buffer, you should also test for the newline.

When you exit the loop, p is pointing to the seventh character in the buffer as follows:

```<code>--------------------------------
|a| |b|b|b|b|b|b|b|b| |c|c|\n|0|    contents
--------------------------------
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4      index
             |
             p
</code>```

You now simply read forward until you encounter the next space and then advance past the space, e.g.:

```<code>    /* discard remaining chars up to next ' ' */
    while (*p && *p != ' ') p++;

    p++;    /* advance to next char */
</code>```

note: if you exited the firstname loop pointing at a space, the above code does not execute.

Finally, all you do is repeat the same loop for surname that you did for firstname. Putting all the pieces of the puzzle together, you could do something similar to the following:

```<code>#include <stdio.h>

enum { NMLIM = 5, BUFSIZE = 256 };

int main (void) {

    char buf[BUFSIZE] = "";

    while (fgets (buf, BUFSIZE, stdin)) {
        char *p = buf, cmd,                 /* start & end pointers */
            fname[NMLIM+1] = "",
            sname[NMLIM+1] = "";
        size_t n = 0;

        /* validate first char is 'a-z' and followed by ' ' */
        if (*p && 'a' <= *p && *p <= 'z' && *(p + 1) == ' ') {
            cmd = *p;
            p += 2;     /* advance pointer to next char following ' ' */
        }
        else {  /* handle error */
            fprintf (stderr, "error: no single command followed by space.\n");
            return 1;
        }

        /* read up to NLIM chars into fname */
        for (n = 0; n < NMLIM && *p && *p != ' ' && *p != '\n'; p++)
            fname[n++] = *p;
        fname[n] = 0;           /* nul terminate */

        /* discard remaining chars up to next ' ' */
        while (*p && *p != ' ') p++;

        p++;    /* advance to next char */

        /* read up to NLIM chars into sname */
        for (n = 0; n < NMLIM && *p && *p != ' ' && *p != '\n'; p++)
            sname[n++] = *p;
        sname[n] = 0;           /* nul terminate */

        printf ("input  : %soutput : %c %s %s\n",
                buf, cmd, fname, sname);
    }

    return 0;
}
</code>```

Example Use/Output

```<code>$ echo  "a bbbbbbbb cc" | ./bin/walkptr
input  : a bbbbbbbb cc
output : a bbbbb cc
</code>```

Look things over an let me know if you have any questions. No matter how elaborate the string or what you need from it, you can always get what you need by simply walking a pointer (or a pair of pointers) down the length of the string.

Body:
I'm writing a C program that parses user input into a char, and two strings of set length. The user input is stored into a buffer using fgets, and then parsed with sscanf. The trouble is, the three fields have a maximum length. If a string exceeds this length, the remaining characters before the next whitespace should be consumed/discarded.

#include <stdio.h>
#define IN_BUF_SIZE 256

int main(void) {
    char inputStr[IN_BUF_SIZE];
    char command;
    char firstname[6];
    char surname[6];

    fgets(inputStr, IN_BUF_SIZE, stdin);
    sscanf(inputStr, "%c %5s %5s", &command, firstname, surname);
    printf("%c %s %s\n", command, firstname, surname);
}

So, with an input of

a bbbbbbbb cc

the desired output would be

a bbbbb cc

but is instead the output is

a bbbbb bbb

Using a format specifier "%c%*s %5s%*s %5s%*s" runs into the opposite problem, where each substring needs to exceed the set length to get to the desired outcome.

Is there way to achieve this by using format specifiers, or is the only way saving the substrings in buffers of their own before cutting them down to the desired length?

Body:
In addition to the other answers, never forget when facing string parsing problems, you always have the option of simply walking a pointer down the string to accomplish any type parsing you require. When you read your string into buffer (my buf below), you have an array of characters you are free to analyze manually (either with array indexes, e.g. buffer[i] or by assigning a pointer to the beginning, e.g. char *p = buffer;) With your string, you have the following in buffer with p pointing to the first character in buffer:

--------------------------------
|a| |b|b|b|b|b|b|b|b| |c|c|\n|0|    contents
--------------------------------
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4      index
 |
 p

To test the character pointed to by p, you simply dereference the pointer, e.g. *p. So to test whether you have an initial character between a-z followed by a space at the beginning of buffer, you simply need do:

    /* validate first char is 'a-z' and followed by ' ' */
    if (*p && 'a' <= *p && *p <= 'z' && *(p + 1) == ' ') {
        cmd = *p;
        p += 2;     /* advance pointer to next char following ' ' */
    }

note:, you are testing *p first, (which is the shorthand for *p != 0 or the equivalent *p != '\0') to validate the string is not empty (e.g. the first char isn't the nul-byte) before proceeding with further tests. You would also include an else { /* handle error */ } in the event any one of the tests failed (meaning you have no command followed by a space).

When you are done, your are left with p pointing to the third character in buffer, e.g.:

--------------------------------
|a| |b|b|b|b|b|b|b|b| |c|c|\n|0|    contents
--------------------------------
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4      index
     |
     p

Now your job is simply, just advance by no more than 5 characters (or until the next space is encountered, assigning the characters to firstname and then nul-terminate following the last character:

    /* read up to NLIM chars into fname */
    for (n = 0; n < NMLIM && *p && *p != ' ' && *p != '\n'; p++)
        fname[n++] = *p;
    fname[n] = 0;           /* nul terminate */

note: since fgets reads and includes the trailing '\n' in buffer, you should also test for the newline.

When you exit the loop, p is pointing to the seventh character in the buffer as follows:

--------------------------------
|a| |b|b|b|b|b|b|b|b| |c|c|\n|0|    contents
--------------------------------
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4      index
             |
             p

You now simply read forward until you encounter the next space and then advance past the space, e.g.:

    /* discard remaining chars up to next ' ' */
    while (*p && *p != ' ') p++;

    p++;    /* advance to next char */

note: if you exited the firstname loop pointing at a space, the above code does not execute.

Finally, all you do is repeat the same loop for surname that you did for firstname. Putting all the pieces of the puzzle together, you could do something similar to the following:

#include <stdio.h>

enum { NMLIM = 5, BUFSIZE = 256 };

int main (void) {

    char buf[BUFSIZE] = "";

    while (fgets (buf, BUFSIZE, stdin)) {
        char *p = buf, cmd,                 /* start & end pointers */
            fname[NMLIM+1] = "",
            sname[NMLIM+1] = "";
        size_t n = 0;

        /* validate first char is 'a-z' and followed by ' ' */
        if (*p && 'a' <= *p && *p <= 'z' && *(p + 1) == ' ') {
            cmd = *p;
            p += 2;     /* advance pointer to next char following ' ' */
        }
        else {  /* handle error */
            fprintf (stderr, "error: no single command followed by space.\n");
            return 1;
        }

        /* read up to NLIM chars into fname */
        for (n = 0; n < NMLIM && *p && *p != ' ' && *p != '\n'; p++)
            fname[n++] = *p;
        fname[n] = 0;           /* nul terminate */

        /* discard remaining chars up to next ' ' */
        while (*p && *p != ' ') p++;

        p++;    /* advance to next char */

        /* read up to NLIM chars into sname */
        for (n = 0; n < NMLIM && *p && *p != ' ' && *p != '\n'; p++)
            sname[n++] = *p;
        sname[n] = 0;           /* nul terminate */

        printf ("input  : %soutput : %c %s %s\n",
                buf, cmd, fname, sname);
    }

    return 0;
}

Example Use/Output

$ echo  "a bbbbbbbb cc" | ./bin/walkptr
input  : a bbbbbbbb cc
output : a bbbbb cc

Look things over an let me know if you have any questions. No matter how elaborate the string or what you need from it, you can always get what you need by simply walking a pointer (or a pair of pointers) down the length of the string.


来源: stackexchange

问:
Import Android projects in Android Studio
I want to use a sample Android project in Android Studio.
it project struct is different. how to use that sample project.

the project structure is like

what I tried:

I try to open projects as "Open projects as Eclipse ADT, Gradle, etc..".
After opening, the application is not runnable using the run icon (icon not in green color).

答: You need to open Android studio and and import the project from there. </p>

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Download file from webpage which does not have a download link
I am trying to download this excel file using Python.

http://www.bseindia.com/markets/equity/EQReports/MarketWatch.aspx?expandable=2. The excel file is on the right side in the box which says "Top Turnovers - All Market".

I am not an HTML expert but usually all files embedded in web I see has a download link (when I rightclick on download button). This one is just an image of excel icon with no pointer to the download link. However, when you click on it a file is downloaded. This could be a common HTML feature but I am not able to figure it out where the file is located. Even the source code is pointing out to icon image.

However my end goal is to able to download this file through python. I thought I could use beautifulsoup and with my limited knowledge on that I think I need to point to a download link. In this case I do not have one. So is there some other way to do it? May be I am missing something basic but any help on how to download this file would be great. I am not looking for a full code or even a working code. Just some pointers on how to go about it and which package to use. I can find my way once I know what I am suppose to use.

答:
The task of clicking we can do it through the javascript, for this use selenium and the chromedriver.

Code:

```<code>from selenium import webdriver

chromedriver = '/usr/bin/chromedriver'
url = "http://www.bseindia.com/markets/equity/EQReports/MarketWatch.aspx?expandable=2"
chrome = webdriver.Chrome(chromedriver)
chrome.get(url)

chrome.execute_script("document.getElementById('ctl00_ContentPlaceHolder1_imgDownload').click();")
</code>```

Body:
The task of clicking we can do it through the javascript, for this use selenium and the chromedriver.

Code:

from selenium import webdriver

chromedriver = '/usr/bin/chromedriver'
url = "http://www.bseindia.com/markets/equity/EQReports/MarketWatch.aspx?expandable=2"
chrome = webdriver.Chrome(chromedriver)
chrome.get(url)

chrome.execute_script("document.getElementById('ctl00_ContentPlaceHolder1_imgDownload').click();")


问:
A better way to access n-d array element with a 1-d index array in C++?
Recently, I'm doing something about C++ pointers, I got this question when I want to access elements in multi-dimensional array with a 1-dimensional array which contains index.

Say I have a array arr, which is a 4-dimensional array with all elements set to 0 except for arr[1][2][3][4] is 1, and a array idx which contains index in every dimension for arr, I can access this element by using arr[idx[0]][idx[1]][idx[2]][idx[3]], or by using *(*(*(*(arr + idx[0]) + idx[1]) + idx[2]) + idx[3]).

The question comes with when n is large, this would be not so good, so I wonder if there is a better way to work with multi-dimensional accessing?

```<code>#include <bits/stdc++.h>
using namespace std;

#define N 10

int main()
{
    int arr[N][N][N][N] = {0};
    int idx[4] = {1, 2, 3, 4};
    arr[1][2][3][4] = 1;
    cout<<"Expected: "<<arr[1][2][3][4]<<" at "<<&arr[1][2][3][4]<<endl;
    cout<<"Got with ****: ";
    cout<<*(*(*(*(arr + idx[0]) + idx[1]) + idx[2]) + idx[3])<<endl;
    return 0;
}
</code>```

output

```<code>Expected: 1 at 0x7fff54c61f28
Got with ****: 1
</code>```

答:
The way you constructor your algorithm for indexing a multi dimensional array will vary depending on the language of choice; you have tagged this question with both C and C++. I will stick with the latter since my answer would pertain to C++. For a little while now I've been working on something similar but different so this becomes an interesting question as I was building a multipurpose multidimensional matrix class template.

What I have discovered about higher levels of multi dimensional vectors and matrices is that the order of 3 repetitiously works miracles in understanding the nature of higher dimensions. Think of this in the geometrical perspective before considering the algorithmic software implementation side of it.

Mathematically speaking Let's consider the lowest dimension of 0 with the first shape that is a 0 Dimensional object. This happens to be any arbitrary point where this point can have an infinite amount of coordinate location properties. Points such as p0(0), p1(1), p2(2,2), p3(3,3,3),... pn(n,n,...n) where each of these objects point to a specific locale with the defined number of dimensional attributes. This means that there is no linear distance such as length, width, or height and conversely a magnitude in any direction or dimension where this shape or object that has no bounds of magnitude does not define any area, volume or higher dimensions of volume. Also with these 0 dimensional points there is no awareness of direction which also implies that there is no angle of rotation that defines magnitude. Another thing to consider is that any arbitrary point is also the zero vector. Another thing to help in understand this is by the use of algebraic polynomials such that f(x) = mx+b which is linear is a One Dimensional equation, shape(in this case a line) or graph, f(x) = x^2 is Two Dimensional, f(x) = x^3 is Three Dimensional, f(x) = x^4 is Four Dimensional and so on up to f(x) = x^n where this would be N Dimensional. Length or Magnitude, Direction or Angle of Rotation, Area, Volume, and others can not be defined until you relate two distinct points to give you at least 1 line segment or vector with a specified direction. Once you have an implied direction you then have slope.

When looking at operations in mathematics the simplest is addition and it is nothing more than a linear translation and once you introduce addition you also introduce all other operations such as subtraction, multiplication, division, powers, and radicals; once you have multiplication and division you define rotation, angles of rotation, area, volume, rates of change, slope (also tangent function), which thus defines geometry and trigonometry which then also leads into integrations and derivatives. Yes, we have all had our math lessons but I think that this is important in to understanding how to construct the relationships of one order of magnitude to another, which then will help us to work through higher dimensional orders with ease once you know how to construct it. Once you can understand that even your higher orders of operations are nothing more than expansions of addition and subtraction you will begin to learn that their continuous operations are still linear in nature it is just that they expand into multiple dimensions.

Early I stated that the order of 3 repetitiously works miracles so let me explain my meaning. Since we perceive things on a daily basis in the perspective of 3D; we can only visualize 3 distinct vectors that are orthogonal to each other giving you our natural 3 Dimensions of Space such as Left & Right, Forward & Backward giving you the Horizontal axis and planes and Up & Down giving you the Vertical axis and planes. We can not visualize anything higher so dimensions of the order of x^4, x^5, x^6 etc... we can not visualize but yet they do exist. If we begin to look at the graphs of the mathematical polynomials we can begin to see a pattern between odd and even functions where x^4, x^6, x^8 are similar where they are nothing more than expansions of x^2 and functions of x^5, x^7 & x^9 are nothing more than expansions of x^3. So I consider the first few dimensions as normal: Zero - Point, 1st - Linear, 2nd - Area, and 3rd - Volume and as for the 4th and higher dimensions I call all of them Volumetric.

So if you see me use Volume then it relates directly to the 3rd Dimension where if I refer to Volumetric it relates to any Dimension higher than the 3rd. Now lets consider a matrix such that you have seen in regular algebra where the common matrices are defined by MxN. Well this is a 2D flat matrix that has M * N elements and this matrix also has an area of M * N as well. Let's expand to a higher dimensional matrix such as MxNxO this is a 3D Matrix with M * N * O elements and now has M * N * O Volume. So when you visualize this think of the MxN 2D part as being a page to a book and the O components represents each page of a book or slice of a box. The elements of these matrices can be anything from a simple value, to an applied operation, to an equation, system of equations, sets or just an arbitrary object as in a storage container. So now when we have a matrix that is of the 4th order such as MxNxOxP this now has a 4th dimensional aspect but the easiest way to visualize this is that This would be a 1 dimensional array or vector to where all of its P elements would be a 3D Matrix of a Volume of MxNxO. When you have a matrix of MxNxOxPxQ now you have a 2D Area Matrix of PxQ where each of those elements are a MxNxO Volume Matrix. Then again if you have a MxNxOxPxQxR you now have a 6th dimensional matrix and this time you have a 3D Volume Matrix where each of the PxQxR elements are in fact 3D Matrices of MxNxO. And once you go higher and higher this patter repeats and merges again. So the order of how arbitrary matrices behave is that these dimensionalities repeat: 1D are Linear Vectors or Matrices, 2D are Area or Planar Matrices and 3D is Volume Matrices and any thing of a higher repeats this process compressing the previous step of Volumes thus the terminology of Volumetric Matrices. Take a Look at this table:

```<code>// Order of Magnitude And groupings
-----------------------------------
Linear         Area          Volume
x^1            x^2           x^3
x^4            x^5           x^6
x^7            x^8           x^9
x^10           x^11          x^12
...            ...           ...
----------------------------------
</code>```

Now it is just a matter of using a little bit of calculus to know which order of magnitude to index into which higher level of dimensionality. Once you know a specific dimension it is simple to take multiple derivatives to give you a linear expression; then traverse the space, then integrate to the same orders of the multiple derivatives to give the results. This should eliminate a good amount of intermediate work by at first ignoring the least significant lower dimensions in a high dimensional order. If you are working in something that has 12 dimensions you can assume that the first 3 dimensions that define the first set of volume is packed tight being an element to another 3D Volumetric Matrix and then once again that 2d order of Volumetric Matrix is itself an element of another 3D Volumetric Matrix. Thus we have a repeating pattern and now it's just a matter of apply this to construct an algorithm and once you have an algorithm; it should be quite easy to implement the methods in any programmable language. So you may have to have a 3 case switch to determine which algorithmic approach to use knowing the overall dimensionality of your matrix or n-d array where one handles orders of linearity, another to handle area, and the final to handle volumes and if they are 4th+ then the overall process becomes recursive in nature.

Body:
Recently, I'm doing something about C++ pointers, I got this question when I want to access elements in multi-dimensional array with a 1-dimensional array which contains index.

Say I have a array arr, which is a 4-dimensional array with all elements set to 0 except for arr[1][2][3][4] is 1, and a array idx which contains index in every dimension for arr, I can access this element by using arr[idx[0]][idx[1]][idx[2]][idx[3]], or by using *(*(*(*(arr + idx[0]) + idx[1]) + idx[2]) + idx[3]).

The question comes with when n is large, this would be not so good, so I wonder if there is a better way to work with multi-dimensional accessing?

#include <bits/stdc++.h>
using namespace std;

#define N 10

int main()
{
    int arr[N][N][N][N] = {0};
    int idx[4] = {1, 2, 3, 4};
    arr[1][2][3][4] = 1;
    cout<<"Expected: "<<arr[1][2][3][4]<<" at "<<&arr[1][2][3][4]<<endl;
    cout<<"Got with ****: ";
    cout<<*(*(*(*(arr + idx[0]) + idx[1]) + idx[2]) + idx[3])<<endl;
    return 0;
}

output

Expected: 1 at 0x7fff54c61f28
Got with ****: 1

Body:
The way you constructor your algorithm for indexing a multi dimensional array will vary depending on the language of choice; you have tagged this question with both C and C++. I will stick with the latter since my answer would pertain to C++. For a little while now I've been working on something similar but different so this becomes an interesting question as I was building a multipurpose multidimensional matrix class template.

What I have discovered about higher levels of multi dimensional vectors and matrices is that the order of 3 repetitiously works miracles in understanding the nature of higher dimensions. Think of this in the geometrical perspective before considering the algorithmic software implementation side of it.

Mathematically speaking Let's consider the lowest dimension of 0 with the first shape that is a 0 Dimensional object. This happens to be any arbitrary point where this point can have an infinite amount of coordinate location properties. Points such as p0(0), p1(1), p2(2,2), p3(3,3,3),... pn(n,n,...n) where each of these objects point to a specific locale with the defined number of dimensional attributes. This means that there is no linear distance such as length, width, or height and conversely a magnitude in any direction or dimension where this shape or object that has no bounds of magnitude does not define any area, volume or higher dimensions of volume. Also with these 0 dimensional points there is no awareness of direction which also implies that there is no angle of rotation that defines magnitude. Another thing to consider is that any arbitrary point is also the zero vector. Another thing to help in understand this is by the use of algebraic polynomials such that f(x) = mx+b which is linear is a One Dimensional equation, shape(in this case a line) or graph, f(x) = x^2 is Two Dimensional, f(x) = x^3 is Three Dimensional, f(x) = x^4 is Four Dimensional and so on up to f(x) = x^n where this would be N Dimensional. Length or Magnitude, Direction or Angle of Rotation, Area, Volume, and others can not be defined until you relate two distinct points to give you at least 1 line segment or vector with a specified direction. Once you have an implied direction you then have slope.

When looking at operations in mathematics the simplest is addition and it is nothing more than a linear translation and once you introduce addition you also introduce all other operations such as subtraction, multiplication, division, powers, and radicals; once you have multiplication and division you define rotation, angles of rotation, area, volume, rates of change, slope (also tangent function), which thus defines geometry and trigonometry which then also leads into integrations and derivatives. Yes, we have all had our math lessons but I think that this is important in to understanding how to construct the relationships of one order of magnitude to another, which then will help us to work through higher dimensional orders with ease once you know how to construct it. Once you can understand that even your higher orders of operations are nothing more than expansions of addition and subtraction you will begin to learn that their continuous operations are still linear in nature it is just that they expand into multiple dimensions.

Early I stated that the order of 3 repetitiously works miracles so let me explain my meaning. Since we perceive things on a daily basis in the perspective of 3D; we can only visualize 3 distinct vectors that are orthogonal to each other giving you our natural 3 Dimensions of Space such as Left & Right, Forward & Backward giving you the Horizontal axis and planes and Up & Down giving you the Vertical axis and planes. We can not visualize anything higher so dimensions of the order of x^4, x^5, x^6 etc... we can not visualize but yet they do exist. If we begin to look at the graphs of the mathematical polynomials we can begin to see a pattern between odd and even functions where x^4, x^6, x^8 are similar where they are nothing more than expansions of x^2 and functions of x^5, x^7 & x^9 are nothing more than expansions of x^3. So I consider the first few dimensions as normal: Zero - Point, 1st - Linear, 2nd - Area, and 3rd - Volume and as for the 4th and higher dimensions I call all of them Volumetric.

So if you see me use Volume then it relates directly to the 3rd Dimension where if I refer to Volumetric it relates to any Dimension higher than the 3rd. Now lets consider a matrix such that you have seen in regular algebra where the common matrices are defined by MxN. Well this is a 2D flat matrix that has M * N elements and this matrix also has an area of M * N as well. Let's expand to a higher dimensional matrix such as MxNxO this is a 3D Matrix with M * N * O elements and now has M * N * O Volume. So when you visualize this think of the MxN 2D part as being a page to a book and the O components represents each page of a book or slice of a box. The elements of these matrices can be anything from a simple value, to an applied operation, to an equation, system of equations, sets or just an arbitrary object as in a storage container. So now when we have a matrix that is of the 4th order such as MxNxOxP this now has a 4th dimensional aspect but the easiest way to visualize this is that This would be a 1 dimensional array or vector to where all of its P elements would be a 3D Matrix of a Volume of MxNxO. When you have a matrix of MxNxOxPxQ now you have a 2D Area Matrix of PxQ where each of those elements are a MxNxO Volume Matrix. Then again if you have a MxNxOxPxQxR you now have a 6th dimensional matrix and this time you have a 3D Volume Matrix where each of the PxQxR elements are in fact 3D Matrices of MxNxO. And once you go higher and higher this patter repeats and merges again. So the order of how arbitrary matrices behave is that these dimensionalities repeat: 1D are Linear Vectors or Matrices, 2D are Area or Planar Matrices and 3D is Volume Matrices and any thing of a higher repeats this process compressing the previous step of Volumes thus the terminology of Volumetric Matrices. Take a Look at this table:

// Order of Magnitude And groupings
-----------------------------------
Linear         Area          Volume
x^1            x^2           x^3
x^4            x^5           x^6
x^7            x^8           x^9
x^10           x^11          x^12
...            ...           ...
----------------------------------

Now it is just a matter of using a little bit of calculus to know which order of magnitude to index into which higher level of dimensionality. Once you know a specific dimension it is simple to take multiple derivatives to give you a linear expression; then traverse the space, then integrate to the same orders of the multiple derivatives to give the results. This should eliminate a good amount of intermediate work by at first ignoring the least significant lower dimensions in a high dimensional order. If you are working in something that has 12 dimensions you can assume that the first 3 dimensions that define the first set of volume is packed tight being an element to another 3D Volumetric Matrix and then once again that 2d order of Volumetric Matrix is itself an element of another 3D Volumetric Matrix. Thus we have a repeating pattern and now it's just a matter of apply this to construct an algorithm and once you have an algorithm; it should be quite easy to implement the methods in any programmable language. So you may have to have a 3 case switch to determine which algorithmic approach to use knowing the overall dimensionality of your matrix or n-d array where one handles orders of linearity, another to handle area, and the final to handle volumes and if they are 4th+ then the overall process becomes recursive in nature.


问:
Objective-C: Memory leak with CGDataProviderCopyData
With the help of the instrument, it is shown that CGDataProviderCopyData is using too much memory. How to fix the issue?

```<code>-(UIImage*)imageNamed:(NSString*)name {

UIImage *uiimage = [UIImage imageNamed:name];

CGImageRef originalImage = [uiimage CGImage];
CFDataRef imageData = CGDataProviderCopyData(
         CGImageGetDataProvider(originalImage));
CGDataProviderRef imageDataProvider = CGDataProviderCreateWithCFData(imageData);
CFRelease(imageData);
CGImageRef image = CGImageCreate(
         CGImageGetWidth(originalImage),
         CGImageGetHeight(originalImage),
         CGImageGetBitsPerComponent(originalImage),
         CGImageGetBitsPerPixel(originalImage),
         CGImageGetBytesPerRow(originalImage),
         CGImageGetColorSpace(originalImage),
         CGImageGetBitmapInfo(originalImage),
         imageDataProvider,
         CGImageGetDecode(originalImage),
         CGImageGetShouldInterpolate(originalImage),
         CGImageGetRenderingIntent(originalImage));
CGDataProviderRelease(imageDataProvider);

return [UIImage imageWithCGImage:image];
}
</code>```

答:
Finally, I was able to solve this. Actually there were few extra unnecessary steps which were causing memory leaks. Here is the updated function:

```<code>-(UIImage*)imageNamed:(NSString*)name {

 UIImage *uiimage = [UIImage imageNamed:name];

 CGImageRef originalImage = [uiimage CGImage];

 CGImageRef image = CGImageCreate(
     CGImageGetWidth(originalImage),
     CGImageGetHeight(originalImage),
     CGImageGetBitsPerComponent(originalImage),
     CGImageGetBitsPerPixel(originalImage),
     CGImageGetBytesPerRow(originalImage),
     CGImageGetColorSpace(originalImage),
     CGImageGetBitmapInfo(originalImage),
     CGImageGetDataProvider(originalImage),
     CGImageGetDecode(originalImage),
     CGImageGetShouldInterpolate(originalImage),
     CGImageGetRenderingIntent(originalImage));

 return [UIImage imageWithCGImage:image];
}
</code>```

CGImageGetDataProvider(originalImage) returns CGDataProviderRef and that is required as 8th parameter in CGImageCreate function. Above steps to copy image data and then creating CGDataProviderRef were unnecessary.

Body:
With the help of the instrument, it is shown that CGDataProviderCopyData is using too much memory. How to fix the issue?

-(UIImage*)imageNamed:(NSString*)name {

UIImage *uiimage = [UIImage imageNamed:name];

CGImageRef originalImage = [uiimage CGImage];
CFDataRef imageData = CGDataProviderCopyData(
         CGImageGetDataProvider(originalImage));
CGDataProviderRef imageDataProvider = CGDataProviderCreateWithCFData(imageData);
CFRelease(imageData);
CGImageRef image = CGImageCreate(
         CGImageGetWidth(originalImage),
         CGImageGetHeight(originalImage),
         CGImageGetBitsPerComponent(originalImage),
         CGImageGetBitsPerPixel(originalImage),
         CGImageGetBytesPerRow(originalImage),
         CGImageGetColorSpace(originalImage),
         CGImageGetBitmapInfo(originalImage),
         imageDataProvider,
         CGImageGetDecode(originalImage),
         CGImageGetShouldInterpolate(originalImage),
         CGImageGetRenderingIntent(originalImage));
CGDataProviderRelease(imageDataProvider);

return [UIImage imageWithCGImage:image];
}

Body:
Finally, I was able to solve this. Actually there were few extra unnecessary steps which were causing memory leaks. Here is the updated function:

-(UIImage*)imageNamed:(NSString*)name {

 UIImage *uiimage = [UIImage imageNamed:name];

 CGImageRef originalImage = [uiimage CGImage];

 CGImageRef image = CGImageCreate(
     CGImageGetWidth(originalImage),
     CGImageGetHeight(originalImage),
     CGImageGetBitsPerComponent(originalImage),
     CGImageGetBitsPerPixel(originalImage),
     CGImageGetBytesPerRow(originalImage),
     CGImageGetColorSpace(originalImage),
     CGImageGetBitmapInfo(originalImage),
     CGImageGetDataProvider(originalImage),
     CGImageGetDecode(originalImage),
     CGImageGetShouldInterpolate(originalImage),
     CGImageGetRenderingIntent(originalImage));

 return [UIImage imageWithCGImage:image];
}

CGImageGetDataProvider(originalImage) returns CGDataProviderRef and that is required as 8th parameter in CGImageCreate function. Above steps to copy image data and then creating CGDataProviderRef were unnecessary.


问:
AWS API Gateway Custom Authorizer based on User Groups
I'm attempting to design a system where users are created in my AWS user pool and assigned to one of four user groups. These user groups have roles attached to them which specify the API Calls they are allowed to make. I've created a user for each group and I'm able to successfully log into them in my Android Application. My User Pool is also attached to an Identity Pool for handling Single Sign On with Identity Federation.

The problem is that rather than assuming the Role assigned to the user group, when I log into the user, the role assigned to the user seems to be coming from the Identity Pool rather than their User Group, and as a result they're unable to make the api calls that they should have access to.

I'm attempting to fix this by implementing a Custom Authorizer in Node.js, but the script appears to be running into some problems. Whenever it enters the ValidateToken() method, it fails saying that the token isn't a JWT token.

```<code>console.log('Loading function');

var jwt = require('jsonwebtoken');
var request = require('request');
var jwkToPem = require('jwk-to-pem');

var groupName = 'MY_GROUP_NAME';
var roleName = 'MY_ROLE_NAME';
var policyName = 'MY_POLICY_NAME';
var userPoolId = 'MY_USER_POOL_ID';
var region = 'MY_REGION';
var iss = 'https://cognito-idp.' + region + '.amazonaws.com/' + userPoolId;
var pems;

exports.handler = function(event, context) {
//Download PEM for your UserPool if not already downloaded
if (!pems) {
//Download the JWKs and save it as PEM
request({
   url: iss + '/.well-known/jwks.json',
   json: true
 }, function (error, response, body) {
    if (!error && response.statusCode === 200) {
        pems = {};
        var keys = body['keys'];
        for(var i = 0; i < keys.length; i++) {
            //Convert each key to PEM
            var key_id = keys[i].kid;
            var modulus = keys[i].n;
            var exponent = keys[i].e;
            var key_type = keys[i].kty;
            var jwk = { kty: key_type, n: modulus, e: exponent};
            var pem = jwkToPem(jwk);
            pems[key_id] = pem;
        }
        //Now continue with validating the token
        ValidateToken(pems, event, context);
    } else {
        //Unable to download JWKs, fail the call
        context.fail("error");
    }
});
} else {
    //PEMs are already downloaded, continue with validating the token
    ValidateToken(pems, event, context);
};
};

function ValidateToken(pems, event, context) {

var token = event.authorizationToken;
//Fail if the token is not jwt
var decodedJwt = jwt.decode(token, {complete: true});
if (!decodedJwt) {
    //THIS IS WHERE THE SCRIPT ENDS UP
    console.log("Not a valid JWT token");
    context.fail("Unauthorized - Invalid Token Provided");
    return;
}

//Fail if token is not from your UserPool
if (decodedJwt.payload.iss != iss) {
    console.log("invalid issuer");
    context.fail("Unauthorized - Invalid Issuer Provided");
    return;
}

//Reject the jwt if it's not an 'Access Token'
if (decodedJwt.payload.token_use != 'access') {
    console.log("Not an access token");
    context.fail("Unauthorized - Not an Access Token");
    return;
}

//Get the kid from the token and retrieve corresponding PEM
var kid = decodedJwt.header.kid;
var pem = pems[kid];
if (!pem) {
    console.log('Invalid access token');
    context.fail("Unauthorized - Invalid Access Token Provided");
    return;
}

//Verify the signature of the JWT token to ensure it's really coming from your User Pool
jwt.verify(token, pem, { issuer: iss }, function(err, payload) {
  if(err) {
        console.log(err, err.stack); // an error occurred
        context.fail("Unauthorized - Could not verify token signature");
  }
  else {
    //Valid token. Generate the API Gateway policy for the user
    //Always generate the policy on value of 'sub' claim and not for 'username' because username is reassignable
    //sub is UUID for a user which is never reassigned to another user.
    var principalId = payload.sub;
    var username = payload.username;

    var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
    var params = {
        UserPoolId: userPoolId, /* ID of the Target User Pool */
        Username: username, /* Provided by event object??? */
        Limit: 0,
        NextToken: ''       //May need actual token value
    };

    cognitoidentityserviceprovider.adminListGroupsForUser(params, function(err, data) {
        if (err){
            console.log(err, err.stack); // an error occurred
            context.fail("Unauthorized - Could not obtain Groups for User");
        }
        else{
            var groups = data.Groups;
            var numGroups = groups.length;
            var isFound = false;
            for(var i = 0; i < numGroups; i++){
                if(groups[i].GroupName == groupName){
                    isFound = true;
                }
            }

            if(isFound){
                var iam = new AWS.IAM();
                var iamParams = {
                    PolicyName: policyName, /* Name of the Policy in the User Group Role */
                    RoleName: roleName /* Name of the User Group Role */
                };

                iam.getRolePolicy(params, function(err, data) {
                    if (err){
                        console.log(err, err.stack); // an error occurred
                        context.fail("Unauthorized - Could not acquire Policy for User Group Role");
                    }
                    else {
                        var policy = data.PolicyDocument;
                        context.succeed(policy);        //May need to build policy
                    }
                });
            }
            else{
                context.fail("Unauthorized - Could not find the required User Group under the User");
            }
        }
    });
  }
});
}
</code>```

Can anybody identify the problem with this script, or perhaps help me identify why the tokens being set aren't valid JWT tokens? The tokens are sent by an Android Application using the AWS Cognito SDK.

EDIT: Upon further investigation, the token retrieved from event.authorizationToken is of the following format (the [VALUE] blocks are to hide potentially sensitive information):

```<code>AWS4-HMAC-SHA256 Credential=[VALUE1]/20170329/us-east-1/execute-api/aws4_request,
SignedHeaders=host;x-amz-date;x-amz-security-token,
Signature=[VALUE2]
</code>```

答:
If clients are getting the AWS credentials after login, you can only use AWS_IAM authorization type on the API Gateway Methods. The authorizationToken value you are seeing is the AWS signature generated by the client using the credentials vended by Cognito. It will not be possible for you to validate the AWS signature in a custom authorizer.

Are you following this Cognito blog post? If so, I think you might be confusing the User Group role with the authenticated role selection on the Identity Pool. When you use the federated identities with User Pool provider, your client will get back AWS credentials that have the permissions of the 'Authenticated role' from that section in the Cognito tab in the Identity Pool. In the blog post this would be the 'EngineerRole' set on the Identity Pool.

Body:
I'm attempting to design a system where users are created in my AWS user pool and assigned to one of four user groups. These user groups have roles attached to them which specify the API Calls they are allowed to make. I've created a user for each group and I'm able to successfully log into them in my Android Application. My User Pool is also attached to an Identity Pool for handling Single Sign On with Identity Federation.

The problem is that rather than assuming the Role assigned to the user group, when I log into the user, the role assigned to the user seems to be coming from the Identity Pool rather than their User Group, and as a result they're unable to make the api calls that they should have access to.

I'm attempting to fix this by implementing a Custom Authorizer in Node.js, but the script appears to be running into some problems. Whenever it enters the ValidateToken() method, it fails saying that the token isn't a JWT token.

console.log('Loading function');

var jwt = require('jsonwebtoken');
var request = require('request');
var jwkToPem = require('jwk-to-pem');

var groupName = 'MY_GROUP_NAME';
var roleName = 'MY_ROLE_NAME';
var policyName = 'MY_POLICY_NAME';
var userPoolId = 'MY_USER_POOL_ID';
var region = 'MY_REGION';
var iss = 'https://cognito-idp.' + region + '.amazonaws.com/' + userPoolId;
var pems;

exports.handler = function(event, context) {
//Download PEM for your UserPool if not already downloaded
if (!pems) {
//Download the JWKs and save it as PEM
request({
   url: iss + '/.well-known/jwks.json',
   json: true
 }, function (error, response, body) {
    if (!error && response.statusCode === 200) {
        pems = {};
        var keys = body['keys'];
        for(var i = 0; i < keys.length; i++) {
            //Convert each key to PEM
            var key_id = keys[i].kid;
            var modulus = keys[i].n;
            var exponent = keys[i].e;
            var key_type = keys[i].kty;
            var jwk = { kty: key_type, n: modulus, e: exponent};
            var pem = jwkToPem(jwk);
            pems[key_id] = pem;
        }
        //Now continue with validating the token
        ValidateToken(pems, event, context);
    } else {
        //Unable to download JWKs, fail the call
        context.fail("error");
    }
});
} else {
    //PEMs are already downloaded, continue with validating the token
    ValidateToken(pems, event, context);
};
};

function ValidateToken(pems, event, context) {

var token = event.authorizationToken;
//Fail if the token is not jwt
var decodedJwt = jwt.decode(token, {complete: true});
if (!decodedJwt) {
    //THIS IS WHERE THE SCRIPT ENDS UP
    console.log("Not a valid JWT token");
    context.fail("Unauthorized - Invalid Token Provided");
    return;
}

//Fail if token is not from your UserPool
if (decodedJwt.payload.iss != iss) {
    console.log("invalid issuer");
    context.fail("Unauthorized - Invalid Issuer Provided");
    return;
}

//Reject the jwt if it's not an 'Access Token'
if (decodedJwt.payload.token_use != 'access') {
    console.log("Not an access token");
    context.fail("Unauthorized - Not an Access Token");
    return;
}

//Get the kid from the token and retrieve corresponding PEM
var kid = decodedJwt.header.kid;
var pem = pems[kid];
if (!pem) {
    console.log('Invalid access token');
    context.fail("Unauthorized - Invalid Access Token Provided");
    return;
}

//Verify the signature of the JWT token to ensure it's really coming from your User Pool
jwt.verify(token, pem, { issuer: iss }, function(err, payload) {
  if(err) {
        console.log(err, err.stack); // an error occurred
        context.fail("Unauthorized - Could not verify token signature");
  }
  else {
    //Valid token. Generate the API Gateway policy for the user
    //Always generate the policy on value of 'sub' claim and not for 'username' because username is reassignable
    //sub is UUID for a user which is never reassigned to another user.
    var principalId = payload.sub;
    var username = payload.username;

    var cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
    var params = {
        UserPoolId: userPoolId, /* ID of the Target User Pool */
        Username: username, /* Provided by event object??? */
        Limit: 0,
        NextToken: ''       //May need actual token value
    };

    cognitoidentityserviceprovider.adminListGroupsForUser(params, function(err, data) {
        if (err){
            console.log(err, err.stack); // an error occurred
            context.fail("Unauthorized - Could not obtain Groups for User");
        }
        else{
            var groups = data.Groups;
            var numGroups = groups.length;
            var isFound = false;
            for(var i = 0; i < numGroups; i++){
                if(groups[i].GroupName == groupName){
                    isFound = true;
                }
            }

            if(isFound){
                var iam = new AWS.IAM();
                var iamParams = {
                    PolicyName: policyName, /* Name of the Policy in the User Group Role */
                    RoleName: roleName /* Name of the User Group Role */
                };

                iam.getRolePolicy(params, function(err, data) {
                    if (err){
                        console.log(err, err.stack); // an error occurred
                        context.fail("Unauthorized - Could not acquire Policy for User Group Role");
                    }
                    else {
                        var policy = data.PolicyDocument;
                        context.succeed(policy);        //May need to build policy
                    }
                });
            }
            else{
                context.fail("Unauthorized - Could not find the required User Group under the User");
            }
        }
    });
  }
});
}

Can anybody identify the problem with this script, or perhaps help me identify why the tokens being set aren't valid JWT tokens? The tokens are sent by an Android Application using the AWS Cognito SDK.

EDIT: Upon further investigation, the token retrieved from event.authorizationToken is of the following format (the [VALUE] blocks are to hide potentially sensitive information):

AWS4-HMAC-SHA256 Credential=[VALUE1]/20170329/us-east-1/execute-api/aws4_request,
SignedHeaders=host;x-amz-date;x-amz-security-token,
Signature=[VALUE2]


问:
how to Show/Hide button C# ASP.Net <No Panel>
I have below code

```<code><div class="modal‐footer">
<div class="row">
  <div class="col-md-6" runat="server" id="d1">
    <asp:Button runat="server" ID="UpdateBtn" OnClick="UpdateBtn_Click" CssClass="btn btn-info btn-block invisible" Text="Update" />
  </div>
  <div class="col-md-6" runat="server" id="d2">
    <asp:Button runat="server" ID="SubmitBtn"  OnClick="SubmmitBtn_Click" CssClass="btn btn-success btn-block" Text="Submit" />
  </div>
  <div class="col-md-6" runat="server" id="d3">
    <asp:Button runat="server" ID="ApproveBtn" OnClick="ApproveBtn_Click" CssClass="btn btn-success btn-block" Text="Approve" />
  </div>
  <div class="col-md-6" runat="server" id="d4">
    <asp:Button runat="server" ID="RejectBtn" OnClick="RejectBtn_Click" CssClass="btn btn-danger btn-block" Text="Reject" />
  </div>
</div>
</div>
</code>```

I need to show only Update Button, under condition. Example,

```<code>if a=="Pending"; only UpdateBtn will be shown.
</code>```

Currently I cannot work with Panel (Even it is success, because my function will be corrupted if i use panel)

Please do help me on this. Ive read lot of forum and tried many approaches but failed.

This is how i declare the (aa) in the back code : public string rfcStatus

this is back code:

```<code>namespace AA.Search
{
public partial class Default : System.Web.UI.Page
{
    private string _searchText;
    public string aa;
    public string poaQa = "No";
    SearchMgt search = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (User.Identity.IsAuthenticated)
            {
                if (Request.QueryString["idno"] != null)
                {
                    _searchText = Request.QueryString["idno"];
                    SearchText.InnerHtml = _searchText;
                    aa = "Pending"
                    BindData();
                }
            }
            else
            {
                Response.Redirect("~/AccessDenied.aspx");
            }
        }
    }
</code>```

答:
Best way to do this is in simple way is ternary operator

```<code>  <asp:Button runat="server" ID="UpdateBtn" OnClick="UpdateBtn_Click"
    CssClass="btn btn-info btn-block invisible" Text="Update"
      visible=" <%= aa == 'Pending' ? "true" : "false"; %> "/>
</code>```

OR
Try this ,code behind file

```<code>  public bool IsUpdateBtnVisible{get;set;}
    if( aa = "Pending")
     {
       IsUpdateBtnVisible=true;
     }
    else
      {
        IsUpdateBtnVisible=false;
      }
</code>```

ASPX page:

```<code><asp:Button runat="server" ID="UpdateBtn" OnClick="UpdateBtn_Click"
  CssClass="btn btn-info btn-block invisible" Text="Update"
   visible="<%# IsUpdateBtnVisible %>"/>
</code>```

Body:
I have below code

    <asp:Button runat="server" ID="UpdateBtn" OnClick="UpdateBtn_Click" CssClass="btn btn-info btn-block invisible" Text="Update" />

    <asp:Button runat="server" ID="SubmitBtn"  OnClick="SubmmitBtn_Click" CssClass="btn btn-success btn-block" Text="Submit" />

    <asp:Button runat="server" ID="ApproveBtn" OnClick="ApproveBtn_Click" CssClass="btn btn-success btn-block" Text="Approve" />

    <asp:Button runat="server" ID="RejectBtn" OnClick="RejectBtn_Click" CssClass="btn btn-danger btn-block" Text="Reject" />

I need to show only Update Button, under condition. Example,

if a=="Pending"; only UpdateBtn will be shown.

Currently I cannot work with Panel (Even it is success, because my function will be corrupted if i use panel)

Please do help me on this. Ive read lot of forum and tried many approaches but failed.

This is how i declare the (aa) in the back code : public string rfcStatus

this is back code:

namespace AA.Search
{
public partial class Default : System.Web.UI.Page
{
    private string _searchText;
    public string aa;
    public string poaQa = "No";
    SearchMgt search = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (User.Identity.IsAuthenticated)
            {
                if (Request.QueryString["idno"] != null)
                {
                    _searchText = Request.QueryString["idno"];
                    SearchText.InnerHtml = _searchText;
                    aa = "Pending"
                    BindData();
                }
            }
            else
            {
                Response.Redirect("~/AccessDenied.aspx");
            }
        }
    }

Body:
Best way to do this is in simple way is ternary operator

  <asp:Button runat="server" ID="UpdateBtn" OnClick="UpdateBtn_Click"
    CssClass="btn btn-info btn-block invisible" Text="Update"
      visible=" <%= aa == 'Pending' ? "true" : "false"; %> "/>

OR
Try this ,code behind file

  public bool IsUpdateBtnVisible{get;set;}
    if( aa = "Pending")
     {
       IsUpdateBtnVisible=true;
     }
    else
      {
        IsUpdateBtnVisible=false;
      }

ASPX page:

<asp:Button runat="server" ID="UpdateBtn" OnClick="UpdateBtn_Click"
  CssClass="btn btn-info btn-block invisible" Text="Update"
   visible="<%# IsUpdateBtnVisible %>"/>


问:
First occurrence in numpy logics
Let's say I have a numpy.ndarray:

```<code>a = np.array([0,4,10,0,11,10])
</code>```

I compared this with 10.

```<code>a >= 10
# array([False, False,  True, False,  True,  True], dtype=bool)
</code>```

I would like to have a single True, i.e. True only at the first occurrence.

I would like to apply this to a given axis in n-D numpy.ndarray.(say, 1000*1000*10)

```<code>a_2d = np.array([[0,4,10],[0,11,10]])
#if axis == 1: array([[False, False, True], [False, True, False]])
</code>```

What I have done:

As for a 1-D array, I managed to do it by using this.

```<code>b=np.zeros(a.size)
b[np.argmax(a>=10)]=True
#b=array([ 0.,  0.,  1.,  0.,  0.,  0.])
</code>```

However, I have no idea how to apply this to a large n-D array.

答:
If you enumerate over the argmax, you can update your zeros array.

Code:

```<code>a = np.array([[0, 4, 10], [0, 11, 10]])
print(a)

b = np.zeros(a.shape)
for i, j in enumerate(np.argmax(a >= 10, axis=1)):
    b[i, j] = 1
print(b)
</code>```

Results:

```<code>[[ 0  4 10]
 [ 0 11 10]]

[[ 0.  0.  1.]
 [ 0.  1.  0.]]
</code>```

Using advanced indexing:

```<code>c = np.zeros(a.shape)
c[list(range(a.shape[0])), np.argmax(a >= 10, axis=1)] = 1
</code>```

Title: First occurrence in numpy logics

Body:
Let's say I have a numpy.ndarray:

a = np.array([0,4,10,0,11,10])

I compared this with 10.

a >= 10
# array([False, False,  True, False,  True,  True], dtype=bool)

I would like to have a single True, i.e. True only at the first occurrence.

I would like to apply this to a given axis in n-D numpy.ndarray.(say, 1000*1000*10)

a_2d = np.array([[0,4,10],[0,11,10]])
#if axis == 1: array([[False, False, True], [False, True, False]])

What I have done:

As for a 1-D array, I managed to do it by using this.

b=np.zeros(a.size)
b[np.argmax(a>=10)]=True
#b=array([ 0.,  0.,  1.,  0.,  0.,  0.])

However, I have no idea how to apply this to a large n-D array.

Body:
If you enumerate over the argmax, you can update your zeros array.

Code:

a = np.array([[0, 4, 10], [0, 11, 10]])
print(a)

b = np.zeros(a.shape)
for i, j in enumerate(np.argmax(a >= 10, axis=1)):
    b[i, j] = 1
print(b)

Results:

[[ 0  4 10]
 [ 0 11 10]]

[[ 0.  0.  1.]
 [ 0.  1.  0.]]

Using advanced indexing:

c = np.zeros(a.shape)
c[list(range(a.shape[0])), np.argmax(a >= 10, axis=1)] = 1


问:
Vertically connected images with line - CSS HTML
can anyone please suggest a method for creating a div portion like in the image. The height should depend on the outer div. I need to use this as a separator between two divs with text on its left and right. Each circled image should come next to the related heading

答:
try this, may be this will help u, it is fully responsive too

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="robots" content="noindex">

    <title>Timeline (responsive) - Bootsnipp.com</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">

Timeline

Mussum ipsum cacilds

 11 hours ago via Twitter

Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo. Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.

Mussum ipsum cacilds

Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo. Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.

Suco de cevadiss, é um leite divinis, qui tem lupuliz, matis, aguis e fermentis. Interagi no mé, cursus quis, vehicula ac nisi. Aenean vel dui dui. Nullam leo erat, aliquet quis tempus a, posuere ut mi. Ut scelerisque neque et turpis posuere pulvinar pellentesque nibh ullamcorper. Pharetra in mattis molestie, volutpat elementum justo. Aenean ut ante turpis. Pellentesque laoreet mé vel lectus scelerisque interdum cursus velit auctor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ac mauris lectus, non scelerisque augue. Aenean justo massa.

Mussum ipsum cacilds

Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo. Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.

Mussum ipsum cacilds

Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo. Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.

Mussum ipsum cacilds

Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo. Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.

                <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown">

                </button>

Action

Another action

Something else here

Separated link

Mussum ipsum cacilds

Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo. Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.

Mussum ipsum cacilds

Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo. Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.

```

Body:
try this, may be this will help u, it is fully responsive too

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="robots" content="noindex">

    <title>Timeline (responsive) - Bootsnipp.com</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
    <style type="text/css">
    .timeline {
    list-style: none;
    padding: 20px 0 20px;
    position: relative;
}

    .timeline:before {
        top: 0;
        bottom: 0;
        position: absolute;
        content: " ";
        width: 3px;
        background-color: #eeeeee;
        left: 50%;
        margin-left: -1.5px;
    }

    .timeline > li {
        margin-bottom: 20px;
        position: relative;
    }

        .timeline > li:before,
        .timeline > li:after {
            content: " ";
            display: table;
        }

        .timeline > li:after {
            clear: both;
        }

        .timeline > li:before,
        .timeline > li:after {
            content: " ";
            display: table;
        }

        .timeline > li:after {
            clear: both;
        }

        .timeline > li > .timeline-panel {
            width: 46%;
            float: left;
            border: 1px solid #d4d4d4;
            border-radius: 2px;
            padding: 20px;
            position: relative;
            -webkit-box-shadow: 0 1px 6px rgba(0, 0, 0, 0.175);
            box-shadow: 0 1px 6px rgba(0, 0, 0, 0.175);
        }

            .timeline > li > .timeline-panel:before {
                position: absolute;
                top: 26px;
                right: -15px;
                display: inline-block;
                border-top: 15px solid transparent;
                border-left: 15px solid #ccc;
                border-right: 0 solid #ccc;
                border-bottom: 15px solid transparent;
                content: " ";
            }

            .timeline > li > .timeline-panel:after {
                position: absolute;
                top: 27px;
                right: -14px;
                display: inline-block;
                border-top: 14px solid transparent;
                border-left: 14px solid #fff;
                border-right: 0 solid #fff;
                border-bottom: 14px solid transparent;
                content: " ";
            }

        .timeline > li > .timeline-badge {
            color: #fff;
            width: 50px;
            height: 50px;
            line-height: 50px;
            font-size: 1.4em;
            text-align: center;
            position: absolute;
            top: 16px;
            left: 50%;
            margin-left: -25px;
            background-color: #999999;
            z-index: 100;
            border-top-right-radius: 50%;
            border-top-left-radius: 50%;
            border-bottom-right-radius: 50%;
            border-bottom-left-radius: 50%;
        }

        .timeline > li.timeline-inverted > .timeline-panel {
            float: right;
        }

            .timeline > li.timeline-inverted > .timeline-panel:before {
                border-left-width: 0;
                border-right-width: 15px;
                left: -15px;
                right: auto;
            }

            .timeline > li.timeline-inverted > .timeline-panel:after {
                border-left-width: 0;
                border-right-width: 14px;
                left: -14px;
                right: auto;
            }

.timeline-badge.primary {
    background-color: #2e6da4 !important;
}

.timeline-badge.success {
    background-color: #3f903f !important;
}

.timeline-badge.warning {
    background-color: #f0ad4e !important;
}

.timeline-badge.danger {
    background-color: #d9534f !important;
}

.timeline-badge.info {
    background-color: #5bc0de !important;
}

.timeline-title {
    margin-top: 0;
    color: inherit;
}

.timeline-body > p,
.timeline-body > ul {
    margin-bottom: 0;
}

    .timeline-body > p + p {
        margin-top: 5px;
    }

@media (max-width: 767px) {
    ul.timeline:before {
        left: 40px;
    }

    ul.timeline > li > .timeline-panel {
        width: calc(100% - 90px);
        width: -moz-calc(100% - 90px);
        width: -webkit-calc(100% - 90px);
    }

    ul.timeline > li > .timeline-badge {
        left: 15px;
        margin-left: 0;
        top: 16px;
    }

    ul.timeline > li > .timeline-panel {
        float: right;
    }

        ul.timeline > li > .timeline-panel:before {
            border-left-width: 0;
            border-right-width: 15px;
            left: -15px;
            right: auto;
        }

        ul.timeline > li > .timeline-panel:after {
            border-left-width: 0;
            border-right-width: 14px;
            left: -14px;
            right: auto;
        }
}
    </style>
    <script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
    <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
    <script type="text/javascript">
        window.alert = function(){};
        var defaultCSS = document.getElementById('bootstrap-css');
        function changeCSS(css){
            if(css) $('head > link').filter(':first').replaceWith('<link rel="stylesheet" href="'+ css +'" type="text/css" />');
            else $('head > link').filter(':first').replaceWith(defaultCSS);
        }
        $( document ).ready(function() {
          var iframe_height = parseInt($('html').height());
          window.parent.postMessage( iframe_height, 'http://bootsnipp.com');
        });
    </script>
</head>
<body>
 <div class="container">
    <div class="page-header">
        <h1 id="timeline">Timeline</h1>
    </div>
    <ul class="timeline">
        <li>
          <div class="timeline-badge"><i class="glyphicon glyphicon-check"></i></div>
          <div class="timeline-panel">
            <div class="timeline-heading">
              <h4 class="timeline-title">Mussum ipsum cacilds</h4>
              <p><small class="text-muted"><i class="glyphicon glyphicon-time"></i> 11 hours ago via Twitter</small></p>
            </div>
            <div class="timeline-body">
              <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo. Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>
            </div>
          </div>
        </li>
        <li class="timeline-inverted">
          <div class="timeline-badge warning"><i class="glyphicon glyphicon-credit-card"></i></div>
          <div class="timeline-panel">
            <div class="timeline-heading">
              <h4 class="timeline-title">Mussum ipsum cacilds</h4>
            </div>
            <div class="timeline-body">
              <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo. Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>
              <p>Suco de cevadiss, é um leite divinis, qui tem lupuliz, matis, aguis e fermentis. Interagi no mé, cursus quis, vehicula ac nisi. Aenean vel dui dui. Nullam leo erat, aliquet quis tempus a, posuere ut mi. Ut scelerisque neque et turpis posuere pulvinar pellentesque nibh ullamcorper. Pharetra in mattis molestie, volutpat elementum justo. Aenean ut ante turpis. Pellentesque laoreet mé vel lectus scelerisque interdum cursus velit auctor. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ac mauris lectus, non scelerisque augue. Aenean justo massa.</p>
            </div>
          </div>
        </li>
        <li>
          <div class="timeline-badge danger"><i class="glyphicon glyphicon-credit-card"></i></div>
          <div class="timeline-panel">
            <div class="timeline-heading">
              <h4 class="timeline-title">Mussum ipsum cacilds</h4>
            </div>
            <div class="timeline-body">
              <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo. Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>
            </div>
          </div>
        </li>
        <li class="timeline-inverted">
          <div class="timeline-panel">
            <div class="timeline-heading">
              <h4 class="timeline-title">Mussum ipsum cacilds</h4>
            </div>
            <div class="timeline-body">
              <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo. Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>
            </div>
          </div>
        </li>
        <li>
          <div class="timeline-badge info"><i class="glyphicon glyphicon-floppy-disk"></i></div>
          <div class="timeline-panel">
            <div class="timeline-heading">
              <h4 class="timeline-title">Mussum ipsum cacilds</h4>
            </div>
            <div class="timeline-body">
              <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo. Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>
              <hr>
              <div class="btn-group">
                <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown">
                  <i class="glyphicon glyphicon-cog"></i> <span class="caret"></span>
                </button>
                <ul class="dropdown-menu" role="menu">
                  <li><a href="#">Action</a></li>
                  <li><a href="#">Another action</a></li>
                  <li><a href="#">Something else here</a></li>
                  <li class="divider"></li>
                  <li><a href="#">Separated link</a></li>
                </ul>
              </div>
            </div>
          </div>
        </li>
        <li>
          <div class="timeline-panel">
            <div class="timeline-heading">
              <h4 class="timeline-title">Mussum ipsum cacilds</h4>
            </div>
            <div class="timeline-body">
              <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo. Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>
            </div>
          </div>
        </li>
        <li class="timeline-inverted">
          <div class="timeline-badge success"><i class="glyphicon glyphicon-thumbs-up"></i></div>
          <div class="timeline-panel">
            <div class="timeline-heading">
              <h4 class="timeline-title">Mussum ipsum cacilds</h4>
            </div>
            <div class="timeline-body">
              <p>Mussum ipsum cacilds, vidis litro abertis. Consetis adipiscings elitis. Pra lá , depois divoltis porris, paradis. Paisis, filhis, espiritis santis. Mé faiz elementum girarzis, nisi eros vermeio, in elementis mé pra quem é amistosis quis leo. Manduma pindureta quium dia nois paga. Sapien in monti palavris qui num significa nadis i pareci latim. Interessantiss quisso pudia ce receita de bolis, mais bolis eu num gostis.</p>
            </div>
          </div>
        </li>
    </ul>
</div>
 <script type="text/javascript">

 </script>
</body>
</html>


问:
Glassfish4 and Eclipse Neon Cannot bridge runtimes
I am trying to use glassfish4 with eclipse-neon but when i try to add server it gives me following error. I am new to eclispe so i don't know much about it Screenshot of error</p>

答: You need to add GlassFish into your runtime first before you create GlassFish server, go eclipse window menu -> preference:


问:
Check internet connection (iOS 10)
For iOS 9 I was using Reachability public class to check wether the device is connected to the internet or not. I converted my Swift 2 code to Swift 3, and the Reachability doesn't work anymore. Can someone tell me how to check the internet connection on iOS 10? Thanks!
Here's the code snippet:</p>

```<code>open class Reachability {
    class func isConnectedToNetwork() -> Bool {
        var zeroAddress = sockaddr_in()
        zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
        zeroAddress.sin_family = sa_family_t(AF_INET)
        let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
            SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
        }
        var flags = SCNetworkReachabilityFlags()
        if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
            return false
        }
        let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
        let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
        return (isReachable && !needsConnection)
    }
}
</code>```

答:
step 1 : create a swift file in your project. i created "ConnectionCheck.swift"

step 2 : add this code in your "ConnectionCheck.swift" file and "import SystemConfiguration" file to your "ConnectionCheck.swift" and "ViewController.swift"

```<code>import Foundation
import SystemConfiguration
public class ConnectionCheck {

class func isConnectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
    zeroAddress.sin_family = sa_family_t(AF_INET)

    guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
            SCNetworkReachabilityCreateWithAddress(nil, $0)
        }
    }) else {
        return false
    }

    var flags: SCNetworkReachabilityFlags = []
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
        return false
    }

    let isReachable = flags.contains(.reachable)
    let needsConnection = flags.contains(.connectionRequired)

    return (isReachable && !needsConnection)
}
</code>```

}

step 3 : Now in "ViewController.swift" use this code to check Network Reachability

```<code>if ConnectionCheck.isConnectedToNetwork() {
        print("Connected")
    }
    else{
        print("disConnected")
    }
</code>```

Title: Check internet connection (iOS 10)

Body:
For iOS 9 I was using Reachability public class to check wether the device is connected to the internet or not. I converted my Swift 2 code to Swift 3, and the Reachability doesn't work anymore. Can someone tell me how to check the internet connection on iOS 10? Thanks!
Here's the code snippet:

open class Reachability {
    class func isConnectedToNetwork() -> Bool {
        var zeroAddress = sockaddr_in()
        zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
        zeroAddress.sin_family = sa_family_t(AF_INET)
        let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
            SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
        }
        var flags = SCNetworkReachabilityFlags()
        if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
            return false
        }
        let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
        let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
        return (isReachable && !needsConnection)
    }
}

Body:
step 1 : create a swift file in your project. i created "ConnectionCheck.swift"

step 2 : add this code in your "ConnectionCheck.swift" file and "import SystemConfiguration" file to your "ConnectionCheck.swift" and "ViewController.swift"

import Foundation
import SystemConfiguration
public class ConnectionCheck {

class func isConnectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
    zeroAddress.sin_family = sa_family_t(AF_INET)

    guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
            SCNetworkReachabilityCreateWithAddress(nil, $0)
        }
    }) else {
        return false
    }

    var flags: SCNetworkReachabilityFlags = []
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
        return false
    }

    let isReachable = flags.contains(.reachable)
    let needsConnection = flags.contains(.connectionRequired)

    return (isReachable && !needsConnection)
}

}

step 3 : Now in "ViewController.swift" use this code to check Network Reachability

if ConnectionCheck.isConnectedToNetwork() {
        print("Connected")
    }
    else{
        print("disConnected")
    }


问:
What is the different between 'click' and 'on' in jquery
I have a button in a datatable. I  have a class attached to it . All the rows of the data table has this button field with different field id and same class.I just want to print the id of the button on its click.

```<code> '<button class="link" id="field1">'+field1+'</button>';

 '<button class="link" id="field2">'+field2+'</button>';
</code>```

When i make the call using $(".link").click(function(){ console.log(this.id)}; it does nothing.

But when i make the call using $(document).on('click','.link',function(){
console.log(this.id)} it worked . So i want to know the difference why the second one works and the first one doesn't work . Here this Difference between .on('click') vs .click() question says that both are functionally same, So what might be the reason in this case .

答:
Read the jquery on api you will find your answer.

and I am sure your button element are not present at the time of html render,

Body:
I have a button in a datatable. I  have a class attached to it . All the rows of the data table has this button field with different field id and same class.I just want to print the id of the button on its click.

 '<button class="link" id="field1">'+field1+'</button>';

 '<button class="link" id="field2">'+field2+'</button>';

When i make the call using $(".link").click(function(){ console.log(this.id)}; it does nothing.

But when i make the call using $(document).on('click','.link',function(){
console.log(this.id)} it worked . So i want to know the difference why the second one works and the first one doesn't work . Here this Difference between .on('click') vs .click() question says that both are functionally same, So what might be the reason in this case .


问:
How do I parse this json response object?
I have a json response of the following type:

```<code>[{
  cat_name : value
  post : [{
          title:value
          image:value
          content:value
         },
         {
          title:value
          image:value
          content:value
         },
         {
          title:value
          image:value
          content:value
         }]
 },{
  cat_name : value
  post : [{
          title:value
          image:value
          content:value
         },
         {
          title:value
          image:value
          content:value
         }]
 },
{
 cat_name : value
 post : [{
         title:value
         image:value
         content:value
         }]
}]
</code>```

and so on...

I've tried the following -

Stored the response object in an array(responseArray). Implemented first for loop from 0 till responseArray.count, stored the value for post in an array (postArray). Inside the first loop I implemented the second loop from 0 till postArray.count and returned the value for count of postarray.count.

EDIT - ADDED THE FOR LOOP

```<code>for (int i = 0; i < responseArrayList.count; i++) {

    postArrayList = [[responseArrayList objectAtIndex:i] valueForKey:@"post"];

    for (int j = 0; j < postArrayList.count; j++) {

        return postArrayList.count;

    }
}
</code>```

It gives a warning that the second loop wont be incremented and would only run once.

How do I set the return value for numberOfRowsInSection ?

答:
i suggest to write code like this...</p>

```<code>NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

     self.myarray=dict[@"result”][@“post”];

//store the value in newObject

[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

        NSLog(@"%@ my object is ",obj);
        myobject  *object = [[myobject alloc]init];
        object.name = obj.productName;
        object.image = obj.productimage;

        [_myarray addObject:object];

    }];
</code>```

Body:
I have a json response of the following type:

[{
  cat_name : value
  post : [{
          title:value
          image:value
          content:value
         },
         {
          title:value
          image:value
          content:value
         },
         {
          title:value
          image:value
          content:value
         }]
 },{
  cat_name : value
  post : [{
          title:value
          image:value
          content:value
         },
         {
          title:value
          image:value
          content:value
         }]
 },
{
 cat_name : value
 post : [{
         title:value
         image:value
         content:value
         }]
}]

and so on...

I've tried the following -

Stored the response object in an array(responseArray). Implemented first for loop from 0 till responseArray.count, stored the value for post in an array (postArray). Inside the first loop I implemented the second loop from 0 till postArray.count and returned the value for count of postarray.count.

EDIT - ADDED THE FOR LOOP

for (int i = 0; i < responseArrayList.count; i++) {

    postArrayList = [[responseArrayList objectAtIndex:i] valueForKey:@"post"];

    for (int j = 0; j < postArrayList.count; j++) {

        return postArrayList.count;

    }
}

It gives a warning that the second loop wont be incremented and would only run once.

How do I set the return value for numberOfRowsInSection ?

Body:
i suggest to write code like this...

NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

     self.myarray=dict[@"result”][@“post”];

//store the value in newObject

[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

        NSLog(@"%@ my object is ",obj);
        myobject  *object = [[myobject alloc]init];
        object.name = obj.productName;
        object.image = obj.productimage;

        [_myarray addObject:object];

    }];


问:
Android Mediaplayer doesnt throw IO exception If file not available at the link
I am starting mediaplayer with a URL. The URL suppose to link to a video/Audio  . But i have deleted the video/audio file from the location, hence i would like to expect a IOException id there is nothing available at that link.

But i am not getting the IO exception. Instead mediaplayer itself try to go to the linkl 10 times and finally throw the error on onErrorListner.
follwings are the logs printed while mediaPlayer is preparing.

Note: - my url is not for local storaged file!! its for server side file.

```<code> E/NuCachedSource2: source returned error -1, 10 retries left
 E/NuCachedSource2: source returned error -1, 9 retries left
 E/NuCachedSource2: source returned error -1, 8 retries left
 E/NuCachedSource2: source returned error -1, 7 retries left
 E/NuCachedSource2: source returned error -1, 6 retries left
 E/NuCachedSource2: source returned error -1, 5 retries left
 E/NuCachedSource2: source returned error -1, 4 retries left
 E/NuCachedSource2: source returned error -1, 3 retries left
 E/NuCachedSource2: source returned error -1, 2 retries left
 E/NuCachedSource2: source returned error -1, 1 retries left
 E/NuCachedSource2: source returned error -1, 0 retries left
 E/GenericSource: Failed to init from data source!
</code>```

I do not want to wait so long that mediaplayer try to reconnect with the same URL 10 time. I want the IOException or error immediately on the very first time.

following is my code. Kindly help!!

```<code>  mMediaPlayer = new MediaPlayer();
  mMediaPlayer.setDataSource(getContext(), Uri.parse(url));
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlayer.setLooping(false);
            mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                    OnErrorReceive("Something is wrong with media player states");

                    return false;
                }
            });
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
    enter code here
               strong text     mMediaPlayer.start();

                }
            });
            mMediaPlayer.prepareAsync();
</code>```

答:
If you are playing with remote media resources, I'd recommend other mediaPlayer implementation like google/ExoPlayer2.

The retry count of Android default player is 10. There is no error handling on HTTP 404 response.

```<code>struct NuCachedSource2 : public DataSource {

...
enum {
    kMaxNumRetries = 10,
};
</code>```

google/ExoPlayer2 has 2. But you can change if you want. my commit in github

```<code>      if (retryAction == DONT_RETRY_FATAL) {
        fatalError = currentError;
      } else if (retryAction != DONT_RETRY) { // DONT_RETRY = 2
        errorCount = retryAction == RETRY_RESET_ERROR_COUNT ? 1 : errorCount + 1;
        start(getRetryDelayMillis());
      }
</code>```

Body:
I am starting mediaplayer with a URL. The URL suppose to link to a video/Audio  . But i have deleted the video/audio file from the location, hence i would like to expect a IOException id there is nothing available at that link.

But i am not getting the IO exception. Instead mediaplayer itself try to go to the linkl 10 times and finally throw the error on onErrorListner.
follwings are the logs printed while mediaPlayer is preparing.

Note: - my url is not for local storaged file!! its for server side file.

 E/NuCachedSource2: source returned error -1, 10 retries left
 E/NuCachedSource2: source returned error -1, 9 retries left
 E/NuCachedSource2: source returned error -1, 8 retries left
 E/NuCachedSource2: source returned error -1, 7 retries left
 E/NuCachedSource2: source returned error -1, 6 retries left
 E/NuCachedSource2: source returned error -1, 5 retries left
 E/NuCachedSource2: source returned error -1, 4 retries left
 E/NuCachedSource2: source returned error -1, 3 retries left
 E/NuCachedSource2: source returned error -1, 2 retries left
 E/NuCachedSource2: source returned error -1, 1 retries left
 E/NuCachedSource2: source returned error -1, 0 retries left
 E/GenericSource: Failed to init from data source!

I do not want to wait so long that mediaplayer try to reconnect with the same URL 10 time. I want the IOException or error immediately on the very first time.

following is my code. Kindly help!!

  mMediaPlayer = new MediaPlayer();
  mMediaPlayer.setDataSource(getContext(), Uri.parse(url));
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlayer.setLooping(false);
            mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                    OnErrorReceive("Something is wrong with media player states");

                    return false;
                }
            });
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
    enter code here
               strong text     mMediaPlayer.start();

                }
            });
            mMediaPlayer.prepareAsync();

Body:
If you are playing with remote media resources, I'd recommend other mediaPlayer implementation like google/ExoPlayer2.

The retry count of Android default player is 10. There is no error handling on HTTP 404 response.

struct NuCachedSource2 : public DataSource {

...
enum {
    kMaxNumRetries = 10,
};

google/ExoPlayer2 has 2. But you can change if you want. my commit in github

      if (retryAction == DONT_RETRY_FATAL) {
        fatalError = currentError;
      } else if (retryAction != DONT_RETRY) { // DONT_RETRY = 2
        errorCount = retryAction == RETRY_RESET_ERROR_COUNT ? 1 : errorCount + 1;
        start(getRetryDelayMillis());
      }


问:
Matlab: confusion in generating binary numbers with a specific probability distribution
I want to obtain an array of binary numbers of length say N=10 where the probability of 0 = 0.6 and probability of 1's is 0.4. But, during validating if actually the probability is correct, I am getting incorrect probability values. So, symbols is an array of 0/1 integers generated. Then I am checking if the probability is correct or not using p_1 = sum(symbols==1)/length(symbols) .Where am I going wrong?

```<code>    N =10;
    p_0 = 0.6;% probability of zeros
  *for n = 1:N
         xr=rand;
         if xr<p_0
             symbols(n)=1;
         else
             symbols(n)=0;
         end
end

        p_1 = sum(symbols==1)/length(symbols)
        p_0 = 1-p_1*
</code>```

答:
I think your confusion lies in understanding probability and not in Matlab. You are using the built-in function rand, which generates uniformly distributed values between 0..1. When you test the hypothesis that the values are less than some threshold, you generate a new distribution. The code is correct.

observations = rand(N, 1) > p_0

produces a distribution of 1s and 0s as you state. As you increase N you will find that the empirical results,

p_1 = sum(observations == 1)

consistently approaches your expected value of 0.4

Body:
I want to obtain an array of binary numbers of length say N=10 where the probability of 0 = 0.6 and probability of 1's is 0.4. But, during validating if actually the probability is correct, I am getting incorrect probability values. So, symbols is an array of 0/1 integers generated. Then I am checking if the probability is correct or not using p_1 = sum(symbols==1)/length(symbols) .Where am I going wrong?

    N =10;
    p_0 = 0.6;% probability of zeros
  *for n = 1:N
         xr=rand;
         if xr<p_0
             symbols(n)=1;
         else
             symbols(n)=0;
         end
end

        p_1 = sum(symbols==1)/length(symbols)
        p_0 = 1-p_1*


问:
Merge default options containing object with JSON Object
I need to merge these two objects to get below output using JS. Thanks in advance and its ok to use jquery library if needed

var defaultOptions = {
        count:3
    };

    var JSON = {
      one:{
        title:"something",
        count:15
      },
      two:{
        title:"another"
      }
    }

    // expecting

    var JSON = {
      one:{
        title:"something",
        count:15
      },
      two:{
        title:"another",
        count:3
      }
    }```

答:
You can use $.extend to merge objects.

```<code>    for (var key in JSON) {
       if (!JSON[key]['count']){
          $.extend(JSON[key], defaultOptions);
       }
    }
</code>```

Update: Loop through the object and check for count object

Body:
You can use $.extend to merge objects.

    for (var key in JSON) {
       if (!JSON[key]['count']){
          $.extend(JSON[key], defaultOptions);
       }
    }

Update: Loop through the object and check for count object


问:
Javascript - create text file on website
So I have a web page, and I would like to programaticly create a text file (lets say it has the words 'hello, I am a text file' in it) on a new directory on my website. The program will be in another directory on the website.

e.g.
https://www.example.com/txtbuild.html is trying to programaticly make https://www.example.com/texts/hi.txt

Is there a way to do this with HTML/Javascript?

EDIT:
I am on Github

答:
The short answer to your question is no.

The long answer is that you have the following alternatives:

Use a form on the Browser end, send the data back to the server, and then use a server-side language such as PHP to receive and save the data. No JavaScript required, but you do need server-side programming.

You can make the process more immediate by using JavaScript on the browser end to send data back to the server. This is called Ajax. You will still need server side processing, though.

Note that it is probably a very bad idea to simple accept user data and save it directly. There are two things you should consider in your development:

Always filter the incoming data against the possibility of receiving and accepting carefully crafted malicious data.

Consider storing the data in a database. Apart from being easier to manage (you don’t have to worry about filenames, for example), they can do less damage there.


问:
File size increase for pngquant output when using PIL
If I compress and image with pngquant, and then read and write out with PIL, I see file size increase significantly (sometimes by up to 2x). Anyone have any tips here? I suspect it may have to do with some PIL flags, but not familiar enough with it.</p>

答:
and then read and write out with PIL, I see file size increase significantly (sometimes by up to 2x)

Since PNG is lossless and therefore does not introduce artifacts that might be problematic with other encoders, I see only three real possibilities:

you are saving with a different bit depth (e.g. input 8 bits, output 24 bits)

you are saving with added alpha information

the palette gets heavily reordered (this shouldn't either save or lose more than a few percent, but without seeing the actual image, if 2x is an exceptional case and the rule is closer to 1.2x, it is within the realm of possibility)

For very small files, non-image chunks might be part of the problem if PIL re-adds some data that pngquant removed. Grab some PNG diagnostic tool capable of dumping list and size of all chunks (PLTE, tEXT etc.) and see where the actual increase takes place (Quick google link).

zLib could also be to blame (e.g. if memory serves, advpng uses a tricked-up zlib to increase performance), but not with those numbers, unless we're talking small enough files that even a few bytes might be significant.


问:
How to validate the grid table value in protractor?
In protractor, I want to verify whether added value is displaying in the grid.
How do I validate it?

The grid looks like this:

答:
Try it at your end and let me know it works:

```<code>var a  = element(by.xpath("//div[contains(text(), 'test_protractor')]")).getText().then(function(msg){
  console.log(msg)
  expect(msg).toEqual("test_protractor")
})
</code>```

If there are multiple and you want to get only first row then

```<code>var a  = element.all(by.xpath("//div[contains(text(), 'test_protractor')]")).get(1).getText().then(function(msg){
  console.log(msg)
  expect(msg).toEqual("test_protractor")
})
</code>```

Body:
Try it at your end and let me know it works:

var a  = element(by.xpath("//div[contains(text(), 'test_protractor')]")).getText().then(function(msg){
  console.log(msg)
  expect(msg).toEqual("test_protractor")
})

If there are multiple and you want to get only first row then

var a  = element.all(by.xpath("//div[contains(text(), 'test_protractor')]")).get(1).getText().then(function(msg){
  console.log(msg)
  expect(msg).toEqual("test_protractor")
})