text:
Q: Regex for a pattern XXYYZZ I want to validate a string which should follow the pattern XXYYZZ where X, Y, Z can be any letter a-z, A-Z or 0-9.
Example of valid strings:
RRFFKK
BB7733
WWDDMM
5599AA

Not valid:
555677
AABBCD

For now I am splitting the string using the regex (?<=(.))(?!\\1) and iterating over the resulting array and checking if each substring has a length of 2.
String str = "AABBEE";
boolean isValid = checkPattern(str);

public static boolean checkPattern(String str) {
   String splited = str.split("(?<=(.))(?!\\1)");
   for (String s : splited) {
       if (s.length() != 2) {
         return false;
       }
   }
   return true;
}

I would like to replace my way of checking with String#matches and get rid of the loop, but can't come up with a valid regex. Can some one help what to put in someRegex in the below snippet?
public static boolean checkPattern(String str) {
    return str.matches(someRegex);
}

A: Since you know a valid pattern will always be six characters long with three pairs of equal characters which are different from each other, a short series of explicit conditions may be simpler than a regex:
public static boolean checkPattern(String str) {
   return str.length() == 6 &&
          str.charAt(0) == str.chatAt(1) &&
          str.charAt(2) == str.chatAt(3) &&
          str.charAt(4) == str.chatAt(5) &&
          str.charAt(0) != str.charAt(2) &&
          str.charAt(0) != str.charAt(4) &&
          str.charAt(2) != str.charAt(4);
}

A: Would the following work for you?
^(([A-Za-z\d])\2(?!.*\2)){3}$

See the online demo

*

*^ - Start string anchor.

*(- Open 1st capture group.

*

*( - Open 2nd capture group.

*

*[A-Za-z\d] - Any alphanumeric character.

*) - Close 2nd capture group.

*\2 - Match exactly what was just captured.

*(?!.*\2) - Negative lookahead to make sure the same character is not used elsewhere.

*) - Close 1st capture group.

*{3} - Repeat the above three times.

*$ - End string anchor.

A: Well, here's another solution that uses regex and streams in combination.

*

*It breaks up the pattern into groups of two characters.

*keeps the distinct groups.

*and returns true if the count is 3.

String[] data = { "AABBBB", "AABBCC", "AAAAAA","AABBAA", "ABC", "AAABCC",
        "RRABBCCC" };
String pat = "(?:\\G(.)\\1)+";
Pattern pattern = Pattern.compile(pat);

for (String str : data) {
    Matcher m = pattern.matcher(str);
    boolean isValid = m.results().map(MatchResult::group).distinct().count() == 3;
    System.out.printf("%8s  ->  %s%n",
            str, isValid ? "Valid" : "Not Valid");
}

Prints
  AABBBB  ->  Not Valid
  AABBCC  ->  Valid
  AAAAAA  ->  Not Valid
  AABBAA  ->  Not Valid
     ABC  ->  Not Valid
  AAABCC  ->  Not Valid
RRABBCCC  ->  Not Valid

A: You can use
s.matches("(\\p{Alnum})\\1(?!\\1)(\\p{Alnum})\\2(?!\\1|\\2)(\\p{Alnum})\\3")

See the regex demo.
Details

*

*\A - start of string (it is implicit in String#matches) - the start of string

*(\p{Alnum})\1 - an alphanumeric char (captured into Group 1) and an identical char right after

*(?!\1) - the next char cannot be the same as in Group 1

*(\p{Alnum})\2 - an alphanumeric char (captured into Group 2) and an identical char right after

*(?!\1|\2) - the next char cannot be the same as in Group 1 and 2

*(\p{Alnum})\3 - an alphanumeric char (captured into Group 3) and an identical char right after

*\z - (implicit in String#matches) - end of string.

RegexPlanet test results:

A: You can check if a character matches with its following character and also if the count of distinct characters is 3.
Demo:
public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(isValidPattern("RRFFKK"));
        System.out.println(isValidPattern("BBAABB"));
        System.out.println(isValidPattern("555677"));
    }

    static boolean isValidPattern(String str) {
        return str.length() == 6 &&
                str.charAt(0) == str.charAt(1) &&
                str.charAt(2) == str.charAt(3) &&
                str.charAt(4) == str.charAt(5) &&
                str.chars().distinct().count() == 3;
    }
}

Output:
true
false
false

Note: String#chars is available since Java-9.


text:
Q: CSS 'checkbox hack' to set body background color This question is purely hypothetical; I don't intend to use the methods discussed here. The intention is to learn more about CSS selectors.
Consider an HTML page containing a checkbox. If the checkbox is selected, the background of the body element is red. Otherwise it is blue.
Is this possible to achieve using currently usable selectors in CSS?
Here are the constraints:

*

*No javascript anywhere

*No divs overlaying the entire page. It must be the body element's background property.

*No future CSS selectors like :has. Ideally the method should be demonstrable in a Codepen.

A: Here's one way. It satisfies all your conditions, but it does use a pseudo-element so it sort of cheats on the "It must be the body element's background property" requirement since the body's background color is set, but the red color comes from the pseudo element:

input:checked::before {
  content: '';
  position: absolute;
  background: red;
  z-index: -1;
  top:0;
  right:0;
  bottom:0;
  left:0;
}

body {
  margin: 0;
  background: blue;
}
<input type="checkbox">

redpajama_set_name: RedPajamaStackExchange


text:
Q: Local attestation with Intel SGX I'm trying to perform a local attestation between two enclaves created from two different applications.
The provided sample code for Linux here creates 3 different enclaves and then establishes secure connections between them. But those enclaves have all been created by the same application which therefore is aware of all enclave IDs.
If two different applications are creating there own enclave which should communicate with one another, how would the source enclave get to know the ID of the destination enclave? Would that ID have to be transmitted from one application to the enclave on a "general" way (IPC)?
I've tried some simple test by starting a destination enclave and printing its ID: "26ce00000002"
Then I used this ID in the local attestation example to try to connect to this running destination enclave:
uint64_t wrapper(const char *c) {
    errno = 0;
    uint64_t result = strtoull(c, NULL, 16);

    if (errno == EINVAL) {
        cout << "WRONG NUMBER" << endl;
    } else if (errno == ERANGE) {
        cout << "Too big\n";
    }

    return result;
}

uint32_t load_enclaves() {
    uint32_t enclave_temp_no;
    int ret, launch_token_updated;
    sgx_launch_token_t launch_token;

    enclave_temp_no = 0;

    ret = sgx_create_enclave(ENCLAVE1_PATH, SGX_DEBUG_FLAG, &launch_token, &launch_token_updated, &e1_enclave_id, NULL);
    if (ret != SGX_SUCCESS) {
        return ret;
    }
    enclave_temp_no++;
    g_enclave_id_map.insert(std::pair<sgx_enclave_id_t, uint32_t>(e1_enclave_id, enclave_temp_no));

const char *test = "26ce00000002";
e2_enclave_id = wrapper(test);

    enclave_temp_no++;
    g_enclave_id_map.insert(std::pair<sgx_enclave_id_t, uint32_t>(e2_enclave_id, enclave_temp_no));

    return SGX_SUCCESS;
}

int main(int argc, char **argv) {
    uint32_t ret_status;
    sgx_status_t status;

    if(load_enclaves() != SGX_SUCCESS) {
        printf("\nLoad Enclave Failure");
    }

    printf("\nAvaliable Enclaves");
    printf("\nEnclave1 - EnclaveID %lx",e1_enclave_id);
    printf("\nEnclave2 - EnclaveID %lx",e2_enclave_id);

    do {
        //Test Create session between Enclave1(Source) and Enclave2(Destination)
        status = Enclave1_test_create_session(e1_enclave_id, &ret_status, e1_enclave_id, e2_enclave_id);
        if (status!=SGX_SUCCESS)
        {
            printf("Enclave1_test_create_session Ecall failed: Error status code is %x", status);
            print_error_message(status);
            break;
        }
        else
        {
            if(ret_status==0)
            {
                printf("\n\nSecure Channel Establishment between Source (E1) and Destination (E2) Enclaves successful !!!");
            }
            else
            {
                printf("\nSession establishment and key exchange failure between Source (E1) and Destination (E2): Error return status is %x\n", ret_status);
                break;
            }
        }

When executing the local attestation program with the source enclave I receive a "SGX_ERROR_INVALID_ENCLAVE_ID" error? This error is not thrown by the local attestation example program but comes from somewhere in the SGX libraries and I don't know why since the destination enclave is still running, therefore the ID should exist!?

A: We do not need a secure connection to exchange the enclave id's. The Application can store the enclave id in a registry or on the disc along with the enclave names which can be retrieved by corresponding application to obtain the id of the required enclave. Then the  application initiates a session between the  source enclave and the destination enclave by doing an ECALL into the source enclave, passing in  the enclave id of the destination enclave. Upon receiving the enclave id of the destination enclave,  the source enclave does an OCALL into the core untrusted code which then does an ECALL into the  destination enclave to exchange the messages required to establish a session using ECDH Key  Exchange protocol.


text:
Q: Windows Workflow Foundation Repeat an Activity Every X minutes What is the best way to repeat a code activity every 2 minutes until a certain condition is met?
Say I have the following code activity that checks a database to see that a batch of reports has been completed.
public sealed class CheckReportsAreComplete : CodeActivity
{
    public InArgument<int> ReportBatchId{ get; set; }
    public OutArgument<bool> HaveReportsCompleted{ get; set; }

    protected override void Execute(CodeActivityContext context)
    {
        bool haveCompleted = ReportService.HaveReportsCompleted((context.GetValue(this.ReportBatchId));

        HaveReportsCompleted.Set(context, haveCompleted);
    }
}

I need this code activity to run every 2 minutes and continue processing when the OutArgument HaveReportsCompleted has been set to true. Should I just use Timer.Sleep in the code or is that bad practice?
I'd assume I'd need a combination of a while/do while with a delay and condition?

A: Heres the solution I came up with:


text:
Q: Is there anyway to collaborate on a Google Document in realtime using VIM? I want to use the VIM keyboard commands to edit a Google Document.  Preferably I'd like to use my .vimrc file and have changes I make reflected in real time (or at least on save).  I want to do this for a technical coding interview.
So far I've tried using GoogleCL which only pushes/receives changes on quitting VIM (which is too slow). And I've tried the Vimium Chrome plugin but that seems to be just for navigation not text editing.  I however may be overlooking a feature of one of these.
I'm using OSX and Chrome, Safari or Firefox.

A: You can:

*

*sync your google docs then edit normally

*use vim-anywhere plugin

*use GoogleCL inside au FileWrite

*use some library to quickly create your own thing, for instance google-drive-ruby (see short example on its page).

To collaborate and see changes real time you could for instance use ruby library to upload/dowload changes every now and then. If you always overwrite your original file even as you edit it, you can diff external changes to see what the other users did.


text:
Q: Figure reference problem I am using LaTeX with the help of TeXnicCenter. I try to add figure reference in my text but it did not work out.  Here is what I am doing.
Code:
Figure~\ref{fig:abc} shows the execution ............

\begin{figure}[H]
\centering
  \includegraphics[height=8cm]{Path/abc.png}
  \caption{abc}
  \label{fig:abc}
\end{figure}

then it shows as

Figure ?? shows the execution of...


text:
Q: Openssl Renegotiation Fails I am trying to connect an openssl client to a server. I'm using the following command:
    openssl s_client -cipher "AES256" -connect 15.213.94.8:6433 -msg
The Output is:
CONNECTED(00000003)
>>> TLS 1.2 Handshake [length 00ce], ClientHello
01 00 00 ca 03 03 f1 77 45 36 0d 10 84 27 a3 11
04 81 07 78 84 39 46 a2 de 44 53 8b b9 01 fd 57
14 d9 fe 67 61 ab 00 00 34 c0 30 c0 2c c0 28 c0
24 c0 14 c0 0a 00 a3 00 9f 00 6b 00 6a 00 39 00
38 c0 19 00 a7 00 6d 00 3a c0 32 c0 2e c0 2a c0
26 c0 0f c0 05 00 9d 00 3d 00 35 00 ff 01 00 00
6d 00 0b 00 04 03 00 01 02 00 0a 00 34 00 32 00
0e 00 0d 00 19 00 0b 00 0c 00 18 00 09 00 0a 00
16 00 17 00 08 00 06 00 07 00 14 00 15 00 04 00
05 00 12 00 13 00 01 00 02 00 03 00 0f 00 10 00
11 00 23 00 00 00 0d 00 20 00 1e 06 01 06 02 06
03 05 01 05 02 05 03 04 01 04 02 04 03 03 01 03
02 03 03 02 01 02 02 02 03 00 0f 00 01 01
<<< TLS 1.2 Handshake [length 0051], ServerHello
02 00 00 4d 03 03 5a ce f7 9f 32 15 3b 2b 7e 75
8d 02 6f ff e9 d1 44 e4 6f 05 cd 1c ec 70 0c 7c
d2 05 d2 b5 27 f5 20 6a 45 e2 43 62 20 e9 48 0e
aa fc 7e 2e c4 5b c6 0a 6d dd 7d b6 71 7d 05 a0
4c 60 09 61 1d 24 69 00 6b 00 00 05 ff 01 00 01
00
<<< TLS 1.2 Handshake [length 033f], Certificate
0b 00 03 3b 00 03 38 00 03 35 30 82 03 31 30 82
02 9a a0 03 02 01 02 02 04 5a cc 5e 97 30 0d 06
09 2a 86 48 86 f7 0d 01 01 05 05 00 30 81 dc 31
10 30 0e 06 03 55 04 0a 13 07 6e 73 73 74 73 31
34 31 34 30 32 06 03 55 04 0b 13 2b 47 65 6e 65
72 61 74 65 64 20 54 75 65 20 41 70 72 20 31 30
20 31 32 3a 31 39 3a 35 36 20 55 54 43 2b 2d 35
3a 2d 20 32 30 31 38 31 23 30 21 06 03 55 04 0b
13 1a 4e 6f 20 41 73 73 75 72 61 6e 63 65 20 2d
20 53 65 6c 66 2d 53 69 67 6e 65 64 31 3c 30 3a
06 03 55 04 0b 13 33 54 65 73 74 69 6e 67 20 4f
6e 6c 79 20 2d 20 44 6f 20 4e 6f 74 20 54 72 75
73 74 20 66 6f 72 20 53 65 63 75 72 65 20 54 72
61 6e 73 61 63 74 69 6f 6e 73 31 2f 30 2d 06 03
55 04 03 13 26 53 65 63 75 72 65 20 54 72 61 6e
73 70 6f 72 74 20 42 6f 6f 74 73 74 72 61 70 20
43 65 72 74 69 66 69 63 61 74 65 30 1e 17 0d 31
38 30 34 31 30 30 36 34 39 35 39 5a 17 0d 31 38
30 37 30 39 30 36 34 39 35 39 5a 30 81 dc 31 10
30 0e 06 03 55 04 0a 13 07 6e 73 73 74 73 31 34
31 34 30 32 06 03 55 04 0b 13 2b 47 65 6e 65 72
61 74 65 64 20 54 75 65 20 41 70 72 20 31 30 20
31 32 3a 31 39 3a 35 36 20 55 54 43 2b 2d 35 3a
2d 20 32 30 31 38 31 23 30 21 06 03 55 04 0b 13
1a 4e 6f 20 41 73 73 75 72 61 6e 63 65 20 2d 20
53 65 6c 66 2d 53 69 67 6e 65 64 31 3c 30 3a 06
03 55 04 0b 13 33 54 65 73 74 69 6e 67 20 4f 6e
6c 79 20 2d 20 44 6f 20 4e 6f 74 20 54 72 75 73
74 20 66 6f 72 20 53 65 63 75 72 65 20 54 72 61
6e 73 61 63 74 69 6f 6e 73 31 2f 30 2d 06 03 55
04 03 13 26 53 65 63 75 72 65 20 54 72 61 6e 73
70 6f 72 74 20 42 6f 6f 74 73 74 72 61 70 20 43
65 72 74 69 66 69 63 61 74 65 30 81 9f 30 0d 06
09 2a 86 48 86 f7 0d 01 01 01 05 00 03 81 8d 00
30 81 89 02 81 81 00 a0 80 77 3c 87 c4 f2 a0 23
ea 3c c2 03 90 e5 1f 07 2b da e0 3a 54 4f 54 b1
1b 99 07 e3 31 e8 fc ea c0 2c 1b 3b b1 2c b2 81
dc 52 4f 01 6c 86 72 26 e9 2f e5 51 e9 88 5f c5
da 74 1e 9c b2 f1 29 ce b2 b9 b3 af 1a 64 ce 47
df 5b 6b 0c b1 ad 2d 05 9e bf 97 42 a9 26 e9 92
f7 6c 15 23 bd fa 94 2f e6 54 2e 27 d3 dd ef 92
7e 3a 21 55 98 db 65 63 6c 3f ca a1 3b d7 e6 5e
09 77 0d 40 dc ad 5f 02 03 01 00 01 30 0d 06 09
2a 86 48 86 f7 0d 01 01 05 05 00 03 81 81 00 6e
18 05 ad 39 bc 64 47 b6 50 56 c2 6e da 4a db a4
f9 10 9a 86 63 4f 99 b5 36 93 7b 7a 59 78 b2 21
d7 50 a1 18 cc 08 81 a4 13 8e ce d5 03 13 0b 53
97 76 80 6b b2 3f e2 15 ad ca b4 ac fa 49 a5 70
e2 d8 5a 3e 43 eb 3d 28 7e 27 47 a7 df 27 e2 5a
29 1a 6a ba ef 32 56 fe 0f f5 00 dc fe 6c af fb
df c7 fe 0c b2 93 d9 99 6e 03 ae f7 9b cc 43 6f
7c 85 d8 65 11 96 fc a1 4b ee 25 d4 e6 0a 8c
depth=0 O = nssts99, OU = "Generated Tue Apr 10 12:19:56 UTC+-5:- 2018", OU = No Assurance - Self-Signed, OU = Testing Only - Do Not Trust for Secure Transactions, CN = Secure Transport Bootstrap Certificate
verify error:num=18:self signed certificate
verify return:1
depth=0 O = nssts99, OU = "Generated Tue Apr 10 12:19:56 UTC+-5:- 2018", OU = No Assurance - Self-Signed, OU = Testing Only - Do Not Trust for Secure Transactions, CN = Secure Transport Bootstrap Certificate
verify return:1
<<< TLS 1.2 Handshake [length 020e], ServerKeyExchange
0c 00 02 0a 00 80 84 cd 7a 4d c7 91 c6 75 30 c3
05 c9 d9 04 d4 4c 20 a5 52 e2 52 0e f1 7d 0c 3c
6a 98 75 91 ac 51 17 a5 45 1a 58 90 8e af 2b ac
29 f9 bd 39 33 a1 bd b2 cc 91 5b d6 49 19 98 fa
d4 b7 e7 7e 58 35 6c 83 fc 4b 63 e6 e9 96 aa 83
2b 44 f4 be fa dc c0 31 fa 61 58 49 bf 2f bc f5
82 b0 ab 8f b2 1d b4 87 a2 6e 3b e6 15 ef 5b fc
77 29 88 a7 5f fa 0d 9f 91 9e 25 33 21 c4 fa d6
5a 2b e9 dc 1f 17 00 80 42 93 80 8f 55 ab e4 1b
71 a2 d2 ec 93 5b 37 c5 71 36 cc 4f ab 06 d8 8f
63 48 23 2f f3 d6 34 e0 d5 f7 7a e6 f8 2e 0b 94
12 0b 4f d7 62 1c 9d 33 83 c5 cd 7c b0 c8 24 76
19 be a5 50 12 c7 77 e6 a8 85 53 18 36 e4 4d 4b
27 0b 0a 73 4a b6 33 8b 47 9c 94 d3 be b2 02 35
72 b0 15 62 26 b6 04 8e 73 2e eb e4 39 ea 14 8f
cd f8 28 16 74 20 02 30 cc 26 5f 16 c7 f2 92 7f
6d e0 cd 31 aa 60 93 d6 00 80 84 af 04 c2 f5 45
6c c6 a0 87 89 cd b3 dd 68 79 fe 4f ba c5 e2 db
0e 32 12 36 14 e9 e6 a3 ca 3f 87 bf 6a 89 32 f3
68 14 50 b1 b0 50 3f 3a ee 79 72 53 c7 3c 2c 5b
86 0e 2d e6 c3 15 d4 03 8a 6b 1f 03 05 89 88 9a
0a d9 ea 4c 3c 7a c7 8f af 40 b2 c8 a3 fe b2 db
43 e7 0e b3 4b b9 43 03 f6 97 46 33 57 ec fe 64
de f2 3b 60 b8 09 7e 5d 02 b0 51 21 4e 05 22 08
f6 ee 0d 27 2e 47 89 6a 9f e5 06 01 00 80 53 af
c7 d1 d3 63 d3 19 5f 3e a6 10 47 4c c5 dc 36 f8
7e 4d d0 a3 ce 1b 42 a8 cc 54 01 ac fc 95 85 3e
75 11 6d 2f 9a a0 67 65 e9 3e f2 f6 c2 00 91 4b
48 9d 8c 83 4b d7 a7 37 83 29 10 5d 2d f5 d8 4e
28 23 8e 7a e8 b6 23 75 3b 57 8d 3a 69 62 8a db
69 86 a4 79 5e 2c d0 0a e6 41 7c b4 38 a4 11 6e
f1 10 93 06 ae 23 3c 32 8f 9d 7b 19 25 44 1c cb
91 ea c5 89 a6 58 c8 bf c8 f0 ee 94 cd ce
<<< TLS 1.2 Handshake [length 0004], ServerHelloDone
0e 00 00 00
>>> TLS 1.2 Handshake [length 0086], ClientKeyExchange
10 00 00 82 00 80 10 95 d8 9b 00 89 95 f2 b6 2e
a5 98 00 88 fa 1b 42 5c ac 75 33 42 1c 0f 32 e7
d6 c7 95 81 07 e0 23 e5 bf d2 99 4a f6 16 81 31
95 64 59 c0 2f b8 52 08 16 e2 45 08 0a df 65 25
b5 5d 2d 7e e6 bb 46 d3 29 a5 74 1a d9 d1 99 57
c0 ea af d4 2f 22 14 5b 8a fa f6 b9 32 15 fe 32
2b b7 a1 82 b8 08 b6 9b 3d e2 7b 33 71 89 f2 48
7e 4d 82 24 e4 14 96 86 d5 db 0c c1 55 03 6a ff
bc 16 58 f1 b6 bc
>>> TLS 1.2 ChangeCipherSpec [length 0001]
01
>>> TLS 1.2 Handshake [length 0010], Finished
14 00 00 0c 52 16 05 75 ee db 9a 44 dc cc 6c bf
<<< TLS 1.2 ChangeCipherSpec [length 0001]
01
<<< TLS 1.2 Handshake [length 0010], Finished
14 00 00 0c 70 6b 32 0a 7e d5 ae 05 64 8b 88 ac---
Certificate chain
0 s:/O=nssts99/OU=Generated Tue Apr 10 12:19:56 UTC+-5:-2018/OU=No Assurance
Self-Signed/OU=Testing Only - Do Not Trust for Secure Transactions/CN=Secure
i:/O=nssts99/OU=Generated Tue Apr 10 12:19:56 UTC+-5:- 2018/OU=No Assurance
Self-Signed/OU=Testing Only - Do Not Trust for Secure Transactions/CN=Secure
---
Server certificate
-----BEGIN CERTIFICATE-----
MIIDMTCCApqgAwIBAgIEWsxelzANBgkqhkiG9w0BAQUFADCB3DEQMA4GA1UEChMH
bnNzdHMxNDE0MDIGA1UECxMrR2VuZXJhdGVkIFR1ZSBBcHIgMTAgMTI6MTk6NTYg
VVRDKy01Oi0gMjAxODEjMCEGA1UECxMaTm8gQXNzdXJhbmNlIC0gU2VsZi1TaWdu
bmNlIC0gU2VsZi1TaWduZWQxPDA6BgNVBAsTM1Rlc3RpbmcgT25seSAtIERvIE5v
dCBUcnVzdCBmb3IgU2VjdXJlIFRyYW5zYWN0aW9uczEvMC0GA1UEAxMmU2VjdXJl
l0KpJumS92wVI736lC/mVC4n093vkn46IVWY22VjbD/KoTvX5l4Jdw1A3K1fAgMB
AAEwDQYJKoZIhvcNAQEFBQADgYEAbhgFrTm8ZEe2UFbCbtpK26T5EJqGY0+ZtTaT
e3pZeLIh11ChGMwIgaQTjs7VAxMLU5d2gGuyP+IVrcq0rPpJpXDi2Fo+Q+s9KH4n
R6ffJ+JaKRpquu8yVv4P9QDc/myv+9/H/gyyk9mZbgOu95vMQ298hdhlEZb8oUvu
JdTmCow=
-----END CERTIFICATE-----
subject=/O=nssts14/OU=Generated Tue Apr 10 12:19:56 UTC+-5:- 2018/OU=No
Assurance - Self-Signed/OU=Testing Only - Do Not Trust for Secure    Transactions/CN=Secure
issuer=/O=nssts14/OU=Generated Tue Apr 10 12:19:56 UTC+-5:- 2018/OU=No   Assurance - Self-Signed/OU=Testing Only - Do Not Trust for Secure  Transactions/CN=Secure

No client certificate CA names sent

SSL handshake has read 1569 bytes and written 441 bytes

New, TLSv1/SSLv3, Cipher is DHE-RSA-AES256-SHA256
Server public key is 1024 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
SSL-Session:
      Protocol  : TLSv1.2
      Cipher    : DHE-RSA-AES256-SHA256
      Session-ID: 6A45E2436220E9480EAAFC7E2EC45BC60A6DDD7DB6717D05A04C6009611D2469
      Session-ID-ctx:
      Master-Key:
3DDDE131C8480BC508F529263A14648AE2F6DFE9D3687AB6A9E5803D77E9FFF7
3C81B2BB836E1FAB4987EE67D0B238A0
      Key-Arg   : None
      PSK identity: None
      PSK identity hint: None
      SRP username: None
      Start Time: 1523513247
      Timeout   : 300 (sec)
      Verify return code: 18 (self signed certificate)
-------------------------------------------------

Above,it says Renegotiation Is Supported. Now when I give R as input for "Renegotiation" I get the following output:
R
RENEGOTIATING
>>> TLS 1.2 Handshake [length 00dd], ClientHello
    01 00 00 d9 03 03 5b 61 2b 1f e8 81 a3 04 04 3b
    d1 d0 b5 f6 11 6f 2c 73 72 ac 04 62 8d 84 a9 e5
    fb bf 8e 2d 0e cb 00 00 32 c0 30 c0 2c c0 28 c0
    24 c0 14 c0 0a 00 a3 00 9f 00 6b 00 6a 00 39 00
    38 c0 19 00 a7 00 6d 00 3a c0 32 c0 2e c0 2a c0
    26 c0 0f c0 05 00 9d 00 3d 00 35 01 00 00 7e ff
    01 00 0d 0c 52 16 05 75 ee db 9a 44 dc cc 6c bf
    00 0b 00 04 03 00 01 02 00 0a 00 34 00 32 00 0e
    00 0d 00 19 00 0b 00 0c 00 18 00 09 00 0a 00 16
    00 17 00 08 00 06 00 07 00 14 00 15 00 04 00 05
    00 12 00 13 00 01 00 02 00 03 00 0f 00 10 00 11
    00 23 00 00 00 0d 00 20 00 1e 06 01 06 02 06 03
    05 01 05 02 05 03 04 01 04 02 04 03 03 01 03 02
    03 03 02 01 02 02 02 03 00 0f 00 01 01
<<< TLS 1.2 Alert [length 0002], warning close_notify
    01 00
1825587648:error:1409E0E5:SSL routines:SSL3_WRITE_BYTES:ssl handshake
failure:/home/ravi/101jssl-h01/openssl-1.0.1j/ssl/s3_pkt.c:615:

Why is it giving a ssl3_write_bytes error and handshake failure?

A: From the log it is obvious that server does not deal the first message "TLS 1.2 Handshake [length 00dd], ClientHello" properly and does not send the ServerHello message, so it sends an alert which notifies the close of connection to client. The client receives the alert message, and calls ssl3_write_bytes to deal this message. And current status is still in TLS renegotiation. So the handshake function will be called, and give out an error as received message is not expected. This is very clear in code
int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
{
const unsigned char *buf=buf_;
unsigned int n,nw;
int i,tot;

s->rwstate=SSL_NOTHING;
OPENSSL_assert(s->s3->wnum <= INT_MAX);
tot=s->s3->wnum;
s->s3->wnum=0;

if (SSL_in_init(s) && !s->in_handshake)
    {
    i=s->handshake_func(s);
    if (i < 0) return(i);
    if (i == 0)
        {
        SSLerr(SSL_F_SSL3_WRITE_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
        return -1;
        }
     }
 ......


text:
Q: Objective-C singleton implementation I am trying to figure out the best implementation of a singleton
this is the latest I got.
This is the .m file implementation, anything wrong with it:
#import "Foo.h"

static Foo *object = nil;

@implementation Foo

+ (Foo*)sharedObject {
   return [[Foo alloc] init];
}

- (id)init {
    static dispatch_once_t once;
    dispatch_once(&once, ^{
       object = [super init];
    });

  return object;
}

@end

and to use it I can do:
[Foo sharedObject]

or
[[Foo alloc] init]

And both will return the same object.

A: According to the your Foo class. No any different when you call both two methods.
But I think better if you can change your Foo singleton method as follows
+ (id) sharedObject {
    static Foo *sharedobj = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedobj = [[self alloc] init];
    });
    return sharedobj;
}

- (id)init {
  if (self = [super init]) {
      someProperty = [[NSString alloc] initWithString:@"Default Property Value"];
  }
  return self;
}

Lets assume you want to create new instance. But it will not create using alloc method because you are overriding init method.


text:
Q: Angular PWA no lee Manifest Estoy instalando una aplicación angular pwa en iis en windows server, estoy instalando la web app como una sub aplicacion de un sitio web. Al generar la app uso el código ng build --prod --base-href "/test-pwa/"y todo funciona bien el problema es que no me lee el manifest, aparece el típico problema "Error línea 1...." que básicamente no encuentra el archivo pero esta la etiqueta link en el html.
Como información adicional, service worker se registra y hasta puedo hacer push notifications, pero para la instalación me falla el manifest.
En archivo angular.json esta como corresponde:
projects: {
   ...
   architect: {
      ...
      build: {
         options: {
            ...
            assets: [
               "src/manifest.webmanifest"
            ]
         }
      ...
      }
   }
   ...
}

A: Solución encontrada, IIS no me deja descargar archivos webmanifest, creo que me hubiese ahorrado problemas si usaba manifest.json, dejo un link a la solución
Add MIME Type webmanifest to IIS


text:
Q: Connecting to PostgreSQL from a Virtual Machine I have MacOS Capitain as my OS in which I have Postgres, and I have Windows 8 running on VMWare Fusion, in which I have QlikSence, now QlikSence needs to connect to Postgres through a wizard which I filled like follows:
        Host Name: my IP address
        Port: 5432
        database: mydatabse
        Username: myuserName
        password: myPassword

I'm sure that database, username and password are correct, however the connection fails. Any help please, is there any setup or configuration on Postgres?
Update: Error msg:

Error Message :Please check the values for username , host and other
properties .Description: Access credentials are not valid for this
connection


text:
Q: Серверная часть android приложения Разрабатываю приложение на Android Cordova (html,css,java script) впервые. Вся база хранится прямо в приложении (json).
До меня дошло, что json масивы немало весят и хорошо бы их загружать с сервера. Эм, "с сервера" - более ничего умного я не смог придумать. Посоветуйте какие-нибудь технологии и ключевые слова, куда мне рыть дабы реализовать загрузку с json массивов(или с бдшек) в андроид приложение.

A: Если хочется именно JavaScript решения, то Node.js конечно же! подключаешь к любой базе на выбор - например MongoDB, где запросы тоже можно делать с помощью JavaScript.
Наружу соответственно вываливаешь некий API, который тебе позволит принимать все эти данные в твое приложение.

A: Можно и на самом устройстве разместить базу sqlite.


text:
Q: .htaccess isn't working on 1&1 hosting and is working on local It gives 500 Internal Server Error. I'm wondering why this code isn't working since it fine in local. I think it has something to do with 1and1 hosting.  Here is my .htaccess file:
Options -Indexes

<IfModule mod_rewrite.c>
RewriteEngine on

RewriteCond %{REQUEST_URI} !^public
RewriteRule ^(.*)$ frontend/web/$1 [L]
</IfModule>

# Deny accessing below extensions
<Files ~ "(.json|.lock|.git)">
Order allow,deny
Deny from all
</Files>

# Deny accessing dot files
RewriteRule (^\.|/\.) - [F]

How can solve the problem?


text:
Q: Is the set of all definable subsets of the natural numbers recursively enumerable? I asked myself similar questions before, for example "Are the definable real numbers countable"? It seemed to me that the set of all explicitly and unambiguously definable objects is "countable", because we could write down the text defining a specific object in the English language. (Or use the English language to define a formal language appropriate to write down the definition.) But English isn't unambiguous, and the meaning of "countable" depends on the used set theory.
Right now I'm thinking about second order logic. Assuming that the natural numbers exist and are well defined seems unproblematic to me. However, the question which subsets of the natural numbers (should we assume to) exist has no good answer. If we say that "all" subsets exist, we run into all sorts of set theoretic questions. If we resort to axiomatic set theory for these questions, we end up with the fact that the natural numbers can't be defined up to isomorphism. The alternative seems to be to assume that only the definable subsets of the natural numbers exist. But my guess is that this won't work out either, i.e. that the "set of all definable subsets of the natural numbers" turns out to be a very strange beast. But if it is a strange beast, I guess it won't be recursively enumerable.
Question
Assuming the Church-Turing thesis (or a suitable analogue for definability, or some other sufficiently solid foundation), what can be said about the "set of all definable subsets of the natural numbers"? Is it well defined and recursively enumerable?
Edit It has been pointed out that my use of "recursively enumerable" is ambiguous without further clarifications, especially that I have to specify how a definable subset of the natural numbers is expected to be encoded as a natural number. Given a natural number, take its binary representation and interpret it as a document in the "OpenDocument" format (ODF). Assume that we can efficiently decide whether the document is valid ODF and whether its content is written sufficiently clear and tries to define a subset of the natural numbers. Let's call this a well formed definition. Assume further that each definable subset has at least one well formed definition which can be recognized to succeed in defining a subset of the natural numbers. Now the question is whether there exists a recursively enumerable subset $S$ of the natural numbers such that each number in $S$ corresponds to a well formed definition which succeeds, and that for each definable subset the set $S$ contains a corresponding definition.

A: The question is somewhat ambiguous about exactly how the sets would be enumerated. The natural way to read it in computability theory is the following, which is the usual sense in which a sequence of sets can be r.e.:

Is there a computable double enumeration $\{ n_{i,j} : i,j \in \omega\}$ such that for each definable set $S \subseteq \omega$ there is an $i_0$ such that $S = \{ n_{i_0,j} : j \in \omega\}$.

The answer to that is certainly "no", because if it was true then every definable set would be r.e., which is not the case.

A: A short answer would be that the concept of "recursively enumerable" is only defined for subsets of some countable universe, where that universe has a ("reasonable") encoding as finite strings of symbols that can be input or output by a Turing machine. In your case the set of "subsets of $\mathbb N$ that are definable" (whatever exactly that means) doesn't satisfy that condition, becuase the natural universe to use would be $\mathcal P(\mathbb N)$, which is not countable.
So it doesn't even make sense to ask whether your set is r.e.
One could attempt to broaden the definitions by imagining a non-deterministic Turing machine that writes an infinite sequence of 0s and 1s to a write-only output tape, where that sequence can be interpreted as a subset of $\mathbb N$. One could then declare that some $A\subseteq 2^{\mathbb N}$ is "recursively enumerable"-ish iff it is the set of possible outputs of some non-deterministic machine.
However, though this can be argued to generalize the ordinary concept of recursive enumerability, it wouldn't be the ordinary concept of recursive enumerability.

A: As long as every "definable" number may be defined using a finite string in some finite alphabet you may sort those strings by length and enumerate numbers using this sort.


text:
Q: VNC Server does not display application GUI I run a VNC Server on an ubuntu 18.04 linux desktop, and connect it using my Windows 10 PC, It was working just fine until I rebooted my server, now none of the applications open GUI, Clicking on "Open terminal here" does nothing, same for Applications while opening chrome. I am using Xfce as my OS

A: I would seriously recommend you look for a file in your home directory which logs the X-related errors. Either .xsession-errors or something in the .vnc folder.


text:
Q: Remotely Set-Printer Options I'm working on a script to set the different printer settings (share, publish, duplex, etc...) with PowerShell. In my environment, I have a different account for server access versus my workstation. So I'm trying to pass those elevated permissions to the server to create the printer and select all the different options, as well as set the permissions.
Using Credential Manager, and creating a new CimSession in the call to create the printer, it works without fail from my workstation. But when it comes to setting the printer options it's not passing the server, or printer, name to the call.
So, here are the calls that create the new printer port and printer:
Add-PrinterPort -Name $IP -ComputerName $Server -PrinterHostAddress $IP -CimSession $Remote -ErrorAction SilentlyContinue

Add-Printer -ComputerName $Server -Name $Printer -PortName $IP -Driver $Driver -Location $Loc -Comment $Comment -CimSession $Remote

That all works as expected. Here is what I'm using to set the options (which fails because access is denied):
Set-Printer -ComputerName "$Server" "$Printer" -Shared:$true -ShareName "$Printer" -Published:$true -PermissionSDDL 'G:SYD:(A;;SWRC;;;AC)(A;OIIO;RPWPSDRCWDWO;;;AC)(A;;SWRC;;;S-1-15-3-1024-155201139-2658482041-3127973164-329287231-3865880861-1938685643-461067658-1087000218)(A;OIIO;RPWPSDRCWDWO;;;S-1-15-3-1024-150205139-2658482041-3872973164-329287231-3865880861-1938685643-461067658-1087000218)(A;;LCSWSDRCWDWO;;;S-1-5-21-1275210071-1425521274-6549912557-618529)(A;OIIO;RPWPSDRCWDWO;;;S-1-5-21-1276648271-1425521274-6549912557-618529)(A;;LCSWSDRCWDWO;;;S-1-5-21-1275210071-1422146274-6549912557-485967)(A;OIIO;RPWPSDRCWDWO;;;S-1-5-21-1194558071-1425521274-6549912557-485967)(A;OIIO;GA;;;CO)(A;;SWRC;;;WD)(A;CIIO;GX;;;WD)(A;;LCSWSDRCWDWO;;;BA)(A;OICIIO;GA;;;BA)'

Since there isn't a way to specify credentials in the Set-Printer command, I started using Invoke-Command. FYI, I really don't understand the details of the Invoke-Command, which is likely my trouble. As in:
$Para = @{
    ComputerName = $Server
    ScriptBlock = {
        Set-Printer -ComputerName $Args[1] $Args[0] $Args[2] $Args[3] $Args[4] -PermissionSDDL 'G:SYD:(A;;SWRC;;;AC)(A;OIIO;RPWPSDRCWDWO;;;AC)(A;;SWRC;;;S-1-15-3-1024-4044835139-2658482041-3127973164-329287231-3865880861-1938685643-461067658-1087000422)(A;OIIO;RPWPSDRCWDWO;;;S-1-15-3-1024-4044835139-2658482041-3127973164-329287231-3865880861-1938685643-461067658-1087000422)(A;;LCSWSDRCWDWO;;;S-1-5-21-1275210071-1425521274-1177238915-348522)(A;OIIO;RPWPSDRCWDWO;;;S-1-5-21-1275210071-1425521274-1177238915-348522)(A;;LCSWSDRCWDWO;;;S-1-5-21-1275210071-1425521274-1177238915-285055)(A;OIIO;RPWPSDRCWDWO;;;S-1-5-21-1275210071-1425521274-1177238915-285055)(A;OIIO;GA;;;CO)(A;;SWRC;;;WD)(A;CIIO;GX;;;WD)(A;;LCSWSDRCWDWO;;;BA)(A;OICIIO;GA;;;BA)'
        }#End ScriptBlock
    ArgumentList = "$Printer", "$Server", "-Shared:$true", "-ShareName $Printer", "-Published:$true"
}
Invoke-Command @Para

This fails miserably.
Can someone help point me in the right direction on this?

A: I think your problem is how you're setting up the remote call.  These are still cmdlets and how you're passing the arguments doesn't make any sense.  I think this is what you're trying to accomplish:
$icParms = @{
    ComputerName = $Server
    ScriptBlock  = {
        $spParms = @{
            Name           = $using:Printer
            ComputerName   = $using:Server
            Shared         = $true
            ShareName      = $using:Printer
            Published      = $true
            PermissionSDDL = 'G:SYD:(A;;SWRC;;;AC)(A;OIIO;RPWPSDRCWDWO;;;AC)(A;;SWRC;;;S-1-15-3-1024-4044835139-2658482041-3127973164-329287231-3865880861-1938685643-461067658-1087000422)(A;OIIO;RPWPSDRCWDWO;;;S-1-15-3-1024-4044835139-2658482041-3127973164-329287231-3865880861-1938685643-461067658-1087000422)(A;;LCSWSDRCWDWO;;;S-1-5-21-1275210071-1425521274-1177238915-348522)(A;OIIO;RPWPSDRCWDWO;;;S-1-5-21-1275210071-1425521274-1177238915-348522)(A;;LCSWSDRCWDWO;;;S-1-5-21-1275210071-1425521274-1177238915-285055)(A;OIIO;RPWPSDRCWDWO;;;S-1-5-21-1275210071-1425521274-1177238915-285055)(A;OIIO;GA;;;CO)(A;;SWRC;;;WD)(A;CIIO;GX;;;WD)(A;;LCSWSDRCWDWO;;;BA)(A;OICIIO;GA;;;BA)'
        }
        Set-Printer @spParms
    }
}
Invoke-Command @icParms

See the about_Remote_Variables topic.


text:
Q: Generate custom documentation (based on SQL table) I'm currently using a software with its own command-line interface, accepting its own commands with parameters, but these commands are documented in several places and files, so I can't simply run doxygen on it, and its not possible to add documentation to these files now.
Dumping everything in one text document seems a bit annoying to use, so my first idea is to generate a table, SQL for example, and add the documentation there, with several columns, such as command and its description, arguments and description of them, example command, execution time, etc., and add some kind of GUI to easily display the commands.
Are there already solutions for this, especially easy to maintenance ones?
Or is it better to have a different approach for this, such as html based Helpfiles?

A: you could build one yourself or use some third party tools like REDGATE SQLdoc..
below is one example of how documentation is generated for one sample table as HTML,PDF as well


text:
Q: Bigger file for narrower screenshot of web page? I was trying to archive a web page, and made a screenshot of it which I then saved as heic, but I ran into this weird phenomenon: When I tried a narrower window the image became bigger, and apparently the original png too?
This is my screenshot for a full-sized browser window:
PNG 2,1 MB 6016×3336 HEIC 796 KB 6016×3336.
This is my screenshot for a narrower browser window
PNG 2,4 MB 1532×3408 HEIC 1,1 MB 1532×3408.
How does this make sense? I would love to know.
Web page from the screenshot

A: PNG encoders filter your image on a line-by-line before compressing them. They can look at a line of pixels and determine if each pixel is heavily based on the line above, or the previous pixel to the left or some more complicated combination of these. They then choose the optimal filter for the line and store it in the output file for the decoder.
As a result, repetitive lines which are largely identical to the line above, or unchanging across the width of the image, are compressed extremely well.
That's what you have in your wider image - there are vast areas of pure white on left and right and they compress very well so although the pixel dimensions are larger, the compression is more effective.


text:
Q: How to get all parents/children categories of a custom taxonomy in WordPress I'm working on a custom WordPress theme and I want to show all the taxonomies list
So, for example, if I  want this structure:

*

*Parent Category 1

*

*Child Category 1

*Child Category 2

*Child Category 3

1.1 - Grand Child Category 1

*Parent Category 2

*

*Child Category 4

*Child Category 5

2.1. - Grand Child Category 2

can you guys please help me to solve this puzzle

A: To create this structure, maybe going with a helper array is the solution. This is not a 100% solution it will just give you start up and you can go from here since figuring it out all alone will be more helpful.
$all_terms = array();
$taxonomy = 'category';
$parent_args = [
    'taxonomy'     => $taxonomy,
    'parent'        => 0,
    'hide_empty'    => false
];
$parent_terms = get_terms( $parent_args );

foreach ( $parent_terms as $parent_term ) {
   $all_terms[ $parent_term->term_id ] = get_all_term_children( $parent_term, $taxonomy );
}

function get_all_term_children( $term, $taxonomy ){
    if ( is_wp_error( get_term_children( $term->term_id, $taxonomy ) ) ) {
        return;
    }

    return get_term_children( $term->term_id, $taxonomy );
}

A: Try this function: replace "taxonomy_name" with your taxonomy.
wp_list_categories( array('taxonomy' => 'taxonomy_name', 'title_li' => "") );

Output:

Note: I have used WP 4.9.8


text:
Q: show that $f\in C^{l}(\mathbb{T})$. given $\sum_n |\hat f(n)||n|^{l} <\infty$ Show that if $f \in\ C(\mathbb{T})$ and further $\sum_n |\hat f(n)||n|^{l} <\infty$ for some positive integer $l$.
show that $f\in C^{l}(\mathbb{T})$.
Hint is given differentiation under integral .
but i could  not get the hint. please help. thanks in advanced

A: Here is how I understand the hint:
The Fourier series of $f$ is $$f(x) = \sum_n \hat f(n) e^{-2\pi i n x}$$
Now if you use derivative on the right hand side you have $\sum_n  (-2\pi i n )\hat f(n)  e^{2\pi i n x}$ which is, by assumption converge to $f'(x)$ (This is not that trivial, but it's true).
Now do the same with the $l$'th derivative.


text:
Q: Confused with C pointers  #include<stdio.h>

// Function to swap two values but does not work
void swapDoesNotWork (int *ptrX, int *ptrY);

// Function to swap two values and works fine
void swap (int *ptrX, int *ptrY);

void swap (int *px, int *py) {
 int temp;
 temp = *px;
 *px = *py;
 *py = temp;
}

void swapDoesNotWork (int *px, int *py) {
 printf("\n\n");
 int temp;
 temp = *px;
 px = py;
 py = &temp;
}

int main() {
 int x = 5;
 int y = 10;
 swapDoesNotWork(&x, &y);
 printf("++++++++++++++++++\n");
 printf("pre x:%d\n", x);
 printf("pre y:%d\n", y);
 printf("\n");
 printf("After calling swapDoesNotWork(&x, &y)...\n");
 printf("post x:%d\n", x);
 printf("post y:%d\n", y);
 printf("++++++++++++++++++\n\n");
 x = 5;
 y = 10;
 printf("= = = = = = = = =\n\n");
 printf("pre x:%d\n", x);
 printf("pre y:%d\n", y);
 swap(&x, &y);

 printf("\n");
 printf("After calling swap(&x, &y)...\n");
 printf("post x:%d\n", x);
 printf("post y:%d\n", y);
 printf("= = = = = = = = =\n\n");
 return 0;

The output of the above program when compiled and executed is:
infi@linux% ./swap_test.o

++++++++++++++++++
pre x:5
pre y:10

After calling swapDoesNotWork(&x, &y)...
post x:5
post y:10
++++++++++++++++++

= = = = = = = = =
= = = = = = = = =
pre x:5
pre y:10

After calling swap(&x, &y)...
post x:10
post y:5

As can be seen, the swapDoesNotWork function does not seem to change the values as is the case with the swap function.
I am new to C language, coming from mostly scripting background. Can someone help me why swapDoesNotWork functon is not changing the values?

A: Here are all the modifications performed by swapDoesNotWork:
 temp = ...
 px = ...
 py = ...

All of these are assignments to local variables. Local variables are destroyed when the function returns, so swapDoesNotWork has no lasting effects. It only changes variables that are about to stop existing anyway.
On the other hand, swap contains these lines:
 *px = ...
 *py = ...

These are assignments to locations pointed to by px and py, respectively. Even though px and py are local variables themselves, they can point to variables outside of the current function (in this case the function is called as swap(&x, &y), so they point to the x and y variables in main).

A: With what you are doing you just cancelled the whole point of using pointers.
What you are doing is basically the same as this:
temp = a;
a = b;
b = temp;

which means that you are acting on a copy of the original variables. So what you do although it is changing the values of the pointers (if you try a printf inside the function the results should be correct) after the function is finished the results disappear. In order for that function to work you would have to pass as an argument a double pointer. Hope I helped


text:
Q: Getting rid of the commas from a CSV file? I have the following code where I take values from a csv file and put them into an ArrayList so that I can use them to plug into a math equation.
    public class Example1
{
public static void main(String[] args) throws InvalidFormatException, IOException{
    ArrayList arr=new ArrayList();
File f=new File("C:\\java\\marchcalllast.csv");
Scanner in=new Scanner(f);
while(in.hasNext())
{
arr.add(in.next());
}
System.out.println("Data From ArrayList");
int size = arr.size();
System.out.println(arr);
System.out.println(size);

for (int i = 0; i < arr.size(); i++){
  String item = (String) arr.get(i);
System.out.println("Item " + i + " : " + item);
}

The output gives me
Item 0 : 15.9,

Item 1 : 13.7,

Item 2 : 12.35,

Item 3 : 10,

Item 4 : 8.45,

Item 5 : 7.15,

Item 6 : 6,

Item 7 : 5.1,

Item 8 : 4.3,

Item 9 : 3.55,

I want to get rid of the comma after these values to use them to insert into a mathematical equation. Is there any way to do that? Also since those values are strings, can I use them for math equations?

A: You can use a delimiter to split by ,. It will also ignore the comma after splitting the String.
Scanner s = new Scanner(input).useDelimiter(",");

Or you try to use this to remove the commas
item.replace(",","");

A: You can use String.split to split a line of text into an array of Strings.  For example:
Part 1: Getting String values between the commas

String line = "13.7, 12.35, 10, 8.45";
String[] elements = line.split(",");
// elements = "13.7", " 12.35", " 10", " 8.45"
To make sure you're just getting the number (and not any spaces), you can tweak the regex to something like this:
line.split("\\s*,\\s*")
Part 2: Converting Strings to Doubles for Mathematical Calculations
Your numbers look like they are decimal numbers.  So you can use Double.valueOf() to convert them to Doubles.
Double.valueOf("1.2")

A: Provider your Scanner with a delimiter (http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#useDelimiter(java.lang.String)) so it will get rid of the commas by itself.
Scanner in = new Scanner(f).useDelimiter(",");


text:
Q: Parsing through text with incorrect attribute definition While trying to parse an html document as XML (added xml start at the beginning) I've ran into a problem with attribute inside tags.

Jun 4, 2013
453.22
454.43
447.39
449.31
10,454,600
449.31

While normally it wouldn't matter (since my xslt code doesn't actually reference it), I am getting an error :
ERROR:  'Attribute name "nowrap" associated with an element type "td" must be followed by the ' = ' character.'
ERROR:  'com.sun.org.apache.xml.internal.utils.WrappedRuntimeException: Attribute name "nowrap" associated with an element type "td" must be followed by the ' = ' character.'

So i was wondering if there's a way to make it suppress / ignore those errors. (Looking for a way of doing it that doesn't involve a separate parse through that would remove all nowrap first.)
(For reference, xml : http://pastebin.com/TLD4bZkq , xslt : http://pastebin.com/dPzDzeAX )

A: The data you're trying to process isn't XML, so the XML parser is right to produce an error.
Depending on what XSLT processor you're using and how you call it you might be able to use an HTML parser instead of an XML parser to parse your HTML into a DOM tree which you then pass to the XSLT processor, rather than having the processor parse the file itself.
But remember that XSLT expects namespace-well-formed XML and if the parser's output doesn't conform to this then you will have problems. For example, in Java (which is what I'm most familiar with), for a DOM Document to be usable by XSLT it must have been produced by a namespace-aware parser even if the document in question doesn't actually use any namespaces.


text:
Q: Como fazer duas chamadas do Retrofit em cadeia com RxJava? Faço uma chamada para recuperar alguns dados e a segunda chamada - que deveria ser feita dentro da primeira - utiliza um dos campos da chamada anterior.
val restApi = retrofit.create(RestAPI::class.java)
testAPI.searchDoc("language", "title_query")
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe { p0 ->
             /** É aqui onde eu quero recuperar os dados de p0 e com eles fazer
                 a segunda chamada. **/
            }
        }

Como que eu utilizo um dos campos da primeira chamada para fazer a segunda? Estou utilizando Kotlin e trabalhando com o RxJava.
Pergunta resumida: Como eu utilizo os dados recuperados na primeira chamada para fazer a segunda dentro do RxAndroid?

A: Acredito que no seu caso é melhor fazer dentro da chain, e não no subscribe. Utilize o operador flatMap:
val restApi = retrofit.create(RestAPI::class.java)
restApi.searchDoc("language", "title_query")
    .flatMap { restApi.doSomethingWithDoc(it.field) }
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe { p0 ->

    }

Se você precisa do valor original, pode usar a função mapeadora e retornar um Pair (ou qualquer outra coisa):
restApi.searchDoc("language", "title_query")
    .flatMap({ restApi.doSomethingWithDoc(it.field) }, { doc, smt -> Pair(doc, smt) }, false)
    .subscribe { pair ->
    }


text: Q: Подвисает шторка в Navigation Drawer В приложении есть только один фрагмент и он выполнен правильно, но на многих моих приложениях при свайпе что бы вызвать меню навигации на этом моменте см.рис. подвисает


text:
Q: 20px gap between top of ImageView and bottom of status bar after returning from iAd animation I am using IB to place a UIImageView (top) ADBannerView (bottom) and within the same View. When running in the Simulator, if I click on the ad, after dismissing the ad screen, the UIImageView is pushed 20px down, leaving a gap between the status bar and UIImageView.
I've tried playing with all of the AutoResizing settings in the Inspector with no luck. Strangely, other objects, like UITextViews that are superimposed over the UIImageView also shift, but respond to AutoResizing settings such that after setting the struts appropriately, the UITextViews stay in place after returning from the ad animation. ??
This issue seems to be similar to My view is displaying y=-20 dispite its frame set to y=0. After rotation it snaps back to y=0. However, adding
self.view.frame = [[UIScreen mainScreen] applicationFrame];

to viewDidLoad is unsuccessful. (I think that's probably because in 3022773 the subview is created programmatically, whereas here its part of the nib)
Also, this post iAd left white blank screen after closed implies that my parent View (the view holding both UIImageView & ADBannerView) must be a "fullscreen view", but I can't figure out how that applies when using IB. (I don't see ANY settings in Inspector that allow me to tell XCode that the parent View should have that property)
Any ideas out there?
Much appreciated!


text:
Q: req body is always empty on post express js I am trying to get req.body on POST method using ExpressJS
But I can always get empty json object ({}).
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.post("/", (req, res) => {
  console.log(req.body) // {}
  res.send(200, req.body);  // {}
});

Who can help me?
I am using :
"body-parser": "^1.19.0",
"express": "^4.17.1",

A: What does your submit form look like? You need to make sure a POST request hits the "/" route.
You can try manually with Postman to see if it goes through.

A: I changed 'content-type' as 'X-www-form-url-encoded' on Postman.
And then i can show the correct body. Thanks.


text:
Q: Exporting lists to files I am trying to write a program which will generate a list of objects and then exports it in a separate file and clears its memory. As an example I tried the following
Do[{Subscript[l, p] = Table[Subscript[l, p, i], {i, 10}];
  Export["\!\(\*SubscriptBox[\"l\", \"p\"]\).mnaz",
   Compress[Subscript[l, p]], "String"]; Clear[Subscript[l, p]]}, {p,
  1, 3}]

Of course, the above is just a sample (and my actual list(s) are more bulky (actually they are list of matrices)), but I hope it explains the spirit. I wanted to export each list separately so that I can get separate files like l_1.mnaz, l_2.mnaz etc., which I can import again by using the same type of code.
Motivation: I need to actually generate a huge list of data. However whatever I do, my system goes out of memory after 5000 loops, which itself takes a lot of time. One reason is that, I need to modify the list at each loop.  It seems 1000 loops takes a  reasonable time. Hence I am trying to break the loop into smaller chunks, export the data, and clear the memory for the next loop. Clear[Subscript[l, p]] is used for that purpose.

A: Try this:
Do[
 l[p] = Table[Subscript[l, p, i], {i, 10}];
 Export["l_" <> ToString[p] <> ".mnaz", Compress@ l[p], "String"];
 l[p] =.
 , {p, 1, 3}
]

I replaced Subscript[l, p] with l[p].  Frankly I don't see a reason to not simply use temp = Table[ . . . but I am trying to keep to the spirit of your example.


text:
Q: What is the best way to manage sessions in Node.js? I'm learning Node.js, and I was wondering what is the best way to handle sessions.
It occurs to me that there are two main options: express-session, or cookie-session.
I did some research, and I've found that express-session is not the best way, since it stores all session information on the server, making it less scalable, but lots of tutorials were recommending it.
So, I am a little confused.

A: These two options are not comparable as they don't have the same functionality.
If you just want to set up a "volatile" session, with no need to store/verify any information server side, you can use cookie based session. This is just an improvement for the user experience (remember choices, preferences...)
On the other hand, if you need to keep some record about that user (authentication, history...), you will need to use a server side session, and a database. Any client side data (like cookie) could be modified by the user.
Note that the last option is not less scalable, it depends on the storage method, MemoryStore by default in express-session package, according to the documentation.
This package is powered by express team, so I guess it is robust enough for a production usage.


text:
Q: Laravel websockt not connecting on live server ubuntu? I am trying to use laravel websockt on ubuntu server. it is working fine on localhost but on ubuntu server when i try to connect it is not working.
In console I am receiving this error
WebSocket connection to 'ws://domain.xyz:6001/app/91407296bd1107c7321?protocol=7&client=js&version=7.0.3&flash=false' failed:

I almost have given all all port permission in my inbound rule of ec2

Don't know Why it is not still working
Any idea?

A: It was required to enable ufw firewall I followed this article
https://www.digitalocean.com/community/tutorials/how-to-set-up-a-firewall-with-ufw-on-ubuntu-18-04
also, make sure you js settings is according to this
new Pusher('1', {

            cluster: 'ap2'
            , forceTLS: false
            , wsHost: window.location.hostname,
            wsPort: 6001,
            wssPort:6001,
           disableStats: true,
        });


text:
Q: How to export a table into the open office spreadsheet (.ods file) through C#.net? I want to create a .ods file throught C#.net and also want to export tables,images into it.
Is there any solution for that?

A: All OpenDocument's is just a couple of XML-files, that are packed into zip-archive and named with different file extensions. It's hard, but possible to write this documents with just only standard XMLWriter/ZipFile classes. Format specifications are open to anyone.
But there are many packages that simplifies and abstracts this process. Take look on Aspose.Words for .NET and AODL NuGet package's at least.


text:
Q: Filter companies that have at least 3 specific products I have an excel pivot table (and a table dataset behind) that has the structure like the one below. How can I filter/show only companies (Col A) with Products (Col B) 1 AND 2 AND 3? Sounds like something easy but can't find a way to do that. No problem by achieving this using Power Query (available in Power BI or Excel).
A1: Company 1 | B1: Product 1
A2: Company 1 | B2: Product 2
A3: Company 1 | B3: Product 3
A4: Company 1 | B4: Product 4
A5: Company 2 | B5: Product 1
A6: Company 3 | B6: Product 1
A7: Company 4 | B7: Product 1
A8: Company 4 | B8: Product 2
A9: Company 4 | B9: Product 3
A10: Company 4 | B9: Product 4
A11: Company 4 | B9: Product 5

A: Here's an approach using Power Query.
Starting with this brought into Power Query from the table in Excel:

I then group on Company (Transform > Group By):

Then I add a new custom column (Add Column > Custom Column) to flag whether each company has the 3 products included in its associated grouped table's Product column:

Then I filter out the FALSE entries from the new custom column (use button at top right of Custom column):

Then I expand the Products column from the embedded table in the AllData column (use button at top right of AllData column).

Then I remove the Custom column:

Here's the M code:
let
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Company", type text}, {"Product", type text}}),
#"Grouped Rows" = Table.Group(#"Changed Type", {"Company"}, {{"AllData", each _, type table}}),
#"Added Custom" = Table.AddColumn(#"Grouped Rows", "Custom", each List.ContainsAll([AllData][Product], {"Product 1","Product 2","Product 3"})),
#"Filtered Rows" = Table.SelectRows(#"Added Custom", each ([Custom] = true)),
#"Expanded AllData" = Table.ExpandTableColumn(#"Filtered Rows", "AllData", {"Product"}, {"Product"}),
#"Removed Columns" = Table.RemoveColumns(#"Expanded AllData",{"Custom"})
in
#"Removed Columns"

A: Basically, you'll need to do a couple of things to do this entirely in Excel:

*

*Add a new table that lists the products, with a column indicating whether that product is included/flagged:

*Update your company/product table to have 2 helper columns: One to VLOOKUP whether the product is flagged, and one to indicate whether a company has all 3 flagged products:

*

*The first helper column would use a formula like =VLOOKUP([@Product],tProducts,2,FALSE).

*The second helper column would use a formula like =COUNTIFS([Company],[@Company],[Product Flagged],TRUE)>=3.

Rows with a TRUE in Column D have 1 each of Products 1, 2, and 3 (unless you have rows with duplicate company/product combinations, where it gets a bit trickier):
In your pivot table, you can filter by this helper column:


text:
Q: C# Possible to override a return type on derived classes? class base{
    ....
    public string name();
    ....
}

class deriveda : base{
    ....
    public override string name();
    ....
}

class derivedb : base{
    ....
    public override string name();
    ....
}

class derivedc : base{
    ....
    public override foo name();
    ....
}

In most of my derived classes it's consistent but one of them I want to return a custom class type, is this possible?

A: Short answer is no.
Think of it, how will you use it later?
base b = new derivedc ()

And then? what will be the return type of b.name() ? string? foo?
You can however use generics to control it (although i'm not sure if it'll fit your use case):
class base<T>{
    ....
    public virtual T name();
    ....
}

class deriveda : base<string>{
    ....
    public override string name();
    ....
}

class derivedb : base<string>{
    ....
    public override string name();
    ....
}

class derivedc : base<foo>{
    ....
    public override foo name();
    ....
}

A: In c# 9, yes this should be possible, as long as the new type satisfies the covariance rules, in particular a more derived reference-type. It'll just work.

A: No, this is not possible. As pointed out by others, the compiler cannot distinguish between functions that differ only in return type (as return type is not part of the function signature).
One workaround (that might not work in your case) is to have your return type be a subclass of the base class functions's return type, as described here. However, foo cannot derive from string, because string is a sealed class. The closest you can get to deriving from predefined types like string is to define a string extension method as illustrated here.
Ofir's answer is probably your best choice, but this might give you other ideas.


text:
Q: JSTL foreach on a Map with custom Objects I've got a Map object in my session with a UDO (User Defined Object) as a key and a list of that same object as value. I'm trying to iterate through this map using jstl and printing it as navbar, but apparently it's like the jstl code is not going through pieces of code as if the variables were not correctly set. The problem is that the navbar doesn't get printed at all, and specifically it doesn't even get into the "include subMenu.jsp" part.
Edit: Apparently the problem is with the c:if that just doesn't let the code get in the if clause although the "menu" attribute in that specific moment isn't null! So probably I'm writing the if clause wrong... but where and how?
This is my code:

            <c:forEach items="${sessionScope.menuNav}" var="menu">
                <c:if test="${menu.key != null}">
                    <c:if test="${menu.value != null}">

<c:out value="${menu.key.getTitle()}"></c:out>

                                <c:set var="subMenu" value="${menu.value}" scope="request"/>
                                <jsp:include page="subMenu.jsp"/>

                    </c:if>
                </c:if>
            </c:forEach>

This is the subMenu.jsp
<c:forEach items="${subMenu}" var="subMenu">
    <c:if test="${subMenu.subMenu == null}">

<c:out value="${subMenu.getTitle()}"></c:out>

    </c:if>
    <c:if test="${subMenu.subMenu != null}">

<c:out value="${subMenu.getTitle()}"></c:out>

                <c:set var="subMenu" value="${subMenu.getSubMenu()}" scope="request"/>
                <jsp:include page="subMenu.jsp"/>

    </c:if>
</c:forEach>

I perfectly manage to put the mapObejct in session.  I know because I've run through every single step in debug mode.  But I still don't get what part I'm getting wrong. The object is conventionally built (with correctly named getters and setters etc.).  This is what I see in debug mode:

The attribute of the session is correctly loaded... I've tried to look for some solutions around but nothing that really helped me... What am I getting wrong?
Edit: This is my Map definition:
Map<InvoiceModel, List<InvoiceModel>> menuMap =
        new HashMap<InvoiceModel, List<InvoiceModel>>();

This is my InvoiceModel Object:
public class InvoiceModel {

    private String title;
    private String page;
    private List<String> roles;
    private List<InvoiceModel> subMenu;

    //Getters and setters
}


text:
Q: Converting data having unix timestamps randomly in data of one column of Oracle Eg: One row in one column contains below data.I need to convert the unix timestamps to actual datetime in oracle.Please provide sql query to convert.
NOTE: {EOT} is special character End of Transmission.
{ETX} is special character End of Text.
1550226213{EOT}Bharath
testtest{ETX}1550226559{EOT}LakshmanUpdate to Current Summary: {EOT}Under Investigation{EOT}
suresh{ETX}1550227918S{EOT}itaUpdate to Current Summary: {EOT}Outage restored- Under Observation
{ETX}1550301176{EOT}Rama

A: Assuming that the times are all at the start of each line within the string then you can use a recursive subquery-factoring clause to iterate over each sub-string line within the string and regular expressions to find each time at the start of that line and then all you need to do is add the offset interval to the epoch the time is being measured from (i.e. 1970-01-01):
Oracle Setup:
CREATE TABLE test_data ( id, value ) AS
SELECT 1, '1550226213Bharath
1550226559LakshmanUpdate to Current Summary: Under Investigation
1550227918SitaUpdate to Current Summary: Outage restored- Under Observation
1550301176Rama' FROM DUAL UNION ALL
SELECT 2, '0ABC' FROM DUAL UNION ALL
SELECT 3, NULL FROM DUAL UNION ALL
SELECT 4, '1234567890A
1234567891B
1234567892C' FROM DUAL;

Query:
WITH lines ( id, value, unix_time, description, line_no, total_lines ) AS (
  SELECT id,
         value,
         TO_NUMBER( REGEXP_SUBSTR( value, '^\d+', 1, 1, 'm' ) ),
         REGEXP_SUBSTR( value, '^\d+(.*)$', 1, 1, 'm', 1 ),
         1,
         COALESCE( REGEXP_COUNT( value, '^\d+', 1, 'm' ), 0 )
  FROM   test_data
UNION ALL
  SELECT id,
         value,
         TO_NUMBER( REGEXP_SUBSTR( value, '^\d+', 1, line_no + 1, 'm' ) ),
         REGEXP_SUBSTR( value, '^\d+(.*)$', 1, line_no + 1, 'm', 1 ),
         line_no + 1,
         total_lines
  FROM   lines
  WHERE  line_no < total_lines
)
SELECT id,
       DATE '1970-01-01' + unix_time * INTERVAL '1' SECOND AS time,
       description
FROM   lines
ORDER BY id, line_no;

Output:

ID | TIME                | DESCRIPTION
-: | :------------------ | :----------------------------------------------------------------
 1 | 2019-02-15 10:23:33 | Bharath
 1 | 2019-02-15 10:29:19 | LakshmanUpdate to Current Summary: Under Investigation
 1 | 2019-02-15 10:51:58 | SitaUpdate to Current Summary: Outage restored- Under Observation
 1 | 2019-02-16 07:12:56 | Rama
 2 | 1970-01-01 00:00:00 | ABC
 3 | null                | null
 4 | 2009-02-13 23:31:30 | A
 4 | 2009-02-13 23:31:31 | B
 4 | 2009-02-13 23:31:32 | C

db<>fiddle here

Update:
Oracle Setup:
CREATE TABLE test_data ( id, value ) AS
SELECT 1, '1550226213{EOT}Bharath
testtest{ETX}1550226559{EOT}LakshmanUpdate to Current Summary: {EOT}Under Investigation{EOT}
suresh{ETX}1550227918{EOT}itaUpdate to Current Summary: {EOT}Outage restored- Under Observation
{ETX}1550301176{EOT}Rama' FROM DUAL UNION ALL
SELECT 2, '0{EOT}ABC' FROM DUAL UNION ALL
SELECT 3, NULL FROM DUAL UNION ALL
SELECT 4, '1234567890{EOT}A{ETX}1234567891{EOT}B{ETX}1234567892{EOT}C' FROM DUAL;

Query:
WITH lines ( id, value, line, line_no, total_lines ) AS (
  SELECT id,
         value,
         REGEXP_SUBSTR( value, '(.+?)(\{ETX\}|$)', 1, 1, 'n', 1 ),
         1,
         COALESCE( REGEXP_COUNT( value, '(.+?)(\{ETX\}|$)', 1, 'n' ), 0 )
  FROM   test_data
UNION ALL
  SELECT id,
         value,
         REGEXP_SUBSTR( value, '(.+?)(\{ETX\}|$)', 1, line_no + 1, 'n', 1 ),
         line_no + 1,
         total_lines
  FROM   lines
  WHERE  line_no < total_lines
)
SELECT id,
       DATE '1970-01-01' + TO_NUMBER( REGEXP_SUBSTR( line, '^(\d+)(\{EOT\}|$)', 1, 1, 'n', 1 ) ) * INTERVAL '1' SECOND AS time,
       REGEXP_SUBSTR( line, '^(\d+)\{EOT\}(.*)$', 1, 1, 'n', 2 ) AS description
FROM   lines
ORDER BY id, line_no;

Output:

ID | TIME                | DESCRIPTION
-: | :------------------ | :-------------------------------------------------------------------------
 1 | 2019-02-15 10:23:33 | Bharath
testtest
 1 | 2019-02-15 10:29:19 | LakshmanUpdate to Current Summary: {EOT}Under Investigation{EOT}
suresh
 1 | 2019-02-15 10:51:58 | itaUpdate to Current Summary: {EOT}Outage restored- Under Observation

 1 | 2019-02-16 07:12:56 | Rama
 2 | 1970-01-01 00:00:00 | ABC
 3 | null                | null
 4 | 2009-02-13 23:31:30 | A
 4 | 2009-02-13 23:31:31 | B
 4 | 2009-02-13 23:31:32 | C

db<>fiddle here


text:
Q: Prove that $A_n$ is the only subgroup of $S_n$ with index 2. For the $n=3$ and $n \geq 5$, $A_n$ is simple, and suppose for a contradiction $H\leq S_n$ has index 2 and $H\neq A_n$, then since $H\cap A_n \unlhd A_n$ and $A_n$ is simple, $H \cap A_n$ must be trivial.
Since $H$ has order equal to that of $A_n$ and $|A_n|>3$, there must exist at least two non-identity elements in $H$. Let $h_1 \neq h_2 \in H$ be non-identity elements of $H$. Then $h_1$ and $h_2$ must be odd permutations, hence $h_1 h_2 \neq h_1^2$. But the product of two odd permutations is even, so $h_1h_2 \in A_n$, so $h_1h_2 \in H\cap A_n = 1$, so $h_1h_2=h_1^2=1$, which is a contradiction.
Therefore $A_n$ is the only subgroup of $S_n$ with index 2 for $n=3$ and $n\geq 5$.
Also note that $A_1$ and $A_2$ are trivial, so we only have to prove the case for $A_4$. But then I'm stuck.

A: An index $2$ subgroup of $S_n$ contains all elements of order $3$,
and those generate $A_n$ for all $n$ (proof by induction).


text:
Q: cakephp 2.4 replace textarea with editable div I am new to CakePHP. I have simple posts table, I want to add a syntax highlighter to actions('add','edit')
add.ctp code:

Create a Post

<?php
    echo $this->Form->create('Post',array('noValidate'));
    echo $this->Form->input('title');

    //echo $this->Form->input('content');

    echo '
';
    echo 'Content';
    echo '

';
    echo '
';

    echo $this->Form->end('Save');
?>

I will dynamically append pre tag to this editable div as highlighter, but how do I replace textarea(content) with div? Currently on adding post it only inserts title but not the content.

A: If you want to send the content of the div at the same time as the form, you can use a textarea like this :
$this->Form->textarea('content');

http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#form-element-specific-methods
But at page init you hide it and only show the div.
Then with javascript you fill the textarea with the content of your div before the onsubmit event.


text:
Q: how check multiple shiro permissions in database table? I have roles_perms table as follow
id || username || role_name || perms_name
1      root         admin      page:show:*;folder:show:*
2      user1        editor     page:show:editorpage,page1;folder:show:folder45,folder55

but following line of code does not returns expected result.
// for user with role "admin"

System.out.println("Test 1 :"+SecurityUtils.getSubject().isPermitted("page:show:*")); // false
System.out.println("Test 2 :"+SecurityUtils.getSubject().isPermitted("page:show:*;folder:show:*")); // true

output:

Test1 :false
Test2 :true

// for user with role "editor"

System.out.println("Test 3 :"+SecurityUtils.getSubject().isPermitted("page:show:page1")); // false
System.out.println("Test 4 :"+SecurityUtils.getSubject().isPermitted("page:show:page1;folder:show:folder55")); // false

 output:
 Test3 :false
 Test4 :false

UPDATE:
shiro.ini file
[main]
ds = org.apache.shiro.jndi.JndiObjectFactory
ds.requiredType   = javax.sql.DataSource
ds.resourceName = jdbc/imgDB
ds.resourceRef = true
jdbcRealm = com.java.realm.MyRealm

# 1000 ms = 1 sec
sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager
securityManager.sessionManager = $sessionManager
securityManager.sessionManager.globalSessionTimeout = 1800000

# password hashing specification
sha256Matcher = org.apache.shiro.authc.credential.HashedCredentialsMatcher
sha256Matcher.hashAlgorithmName = SHA-256
jdbcRealm.credentialsMatcher = $sha256Matcher

jdbcRealm.permissionsLookupEnabled = true
jdbcRealm.authenticationQuery = SELECT password FROM shiro_users WHERE username = ?
jdbcRealm.userRolesQuery = SELECT role_name FROM shiro_user_roles WHERE username = ?
jdbcRealm.permissionsQuery = SELECT perms_name FROM shiro_roles_perms WHERE role_name = ? AND username = ?

jdbcRealm.dataSource = $ds
jdbcRealm.authorizationCachingEnabled = false

# specify login page
authc.loginUrl = /login.jsp

# redirect after successful login
authc.successUrl = /home.jsp

# roles filter: redirect to error page if user does not have access rights
# perms filter: redirect to error page if user does not have permissions
roles.unauthorizedUrl = /accessdenied.jsp
perms.unauthorizedUrl = /accessdenied.jsp

# request parameter with login error information; if not present filter assumes 'shiroLoginFailure'
# authc.failureKeyAttribute = simpleShiroApplicationLoginFailure

[urls]

/login.jsp = authc
/admin/** = authc,roles[admin]
/editor/** = authc

# enable authc filter for all application pages
/ApacheShiroLogin/** = authc

A: Please clarify your question. The title asks about getting values from a database table. However, the post uses the SercurityUtils object. Database table does not equal SecurityUtils.
If you want to select values from a database table. You need to specify what type of database you are using, the schema, etc. Then implement statements to select values from the database.
If you are trying to configure Shiro to use a database, please post you shiro configuration.
Please post your shiro configuration. That might give folks enough information to help you :)
Shiro must be configured to use a database.
Update:
In you Shiro configuration, tou need to add your realm to the security manager:
securityManager.realm = $jdbcRealm

You also need to verify jndi lookups are configured properly.
Also, Please post the context of "but following line of code...". Have you submitted a valid login. If so, how? Where does the "line of code" reside? How is it being invoked??


text:
Q: is componentWillReceiveProps suitable for some instant logic? I'm making a simple login process by react-redux:
there are two redux-connected components called  App
and Login,  and a redux state loggedIn which will be modified to true after an async call.
I hope to check the loggedIn changing in Login::componentWillReceiveProps(by compareing with last value),  then call the router's jump method.
but the problem is the App also connects to the loggedIn state, for displaying some welcome info in header.
so when the loggedIn state change, the App will first know and re-render,  causing the Login child component re-construct and its componentWillReceiveProps won't be called, thus the jump could not be executed.
is it something wrong in my solution?? if considering outside this problem , how could we ensure the child's componentWillReceiveProps running when its parent re-render? is this method suitable for placeing  important logic??


text:
Q: Ошибка компиляции программы через pyinstaller Код работает правильно, путь прописан тоже правильно, любую программу хочу скомпилировать, выводит эту ошибку:
TypeError: an integer is required (got type bytes)

A: Случайно python не 3.8? Если да, то
надо взять Pyinstaller-develop с Github ( ссылка есть на pypi )  и копировать папку PyInstaller из архива в Lib/site-packages/PyInstaller/ . Поможет дожить до следующего релиза :)


text:
Q: How to make a Container widget to an ExpansionPanelList widget in flutter here is my container widget with decorations
Container(
    height: 90,
    width: 150,
    decoration: const BoxDecoration(
      color: Colors.grey,
      borderRadius: BorderRadius.all(Radius.circular(30)),
      boxShadow: [
        BoxShadow(
          color: Colors.black,
          offset: Offset(0.0, 0.0),
          blurRadius: 14.0,
          spreadRadius: -15,
        ), //BoxShadow
      ],
    ),
  );

I need to perform ExpansionPanelList with the same decoration

but when I'm doing this, then this happening

how do I make this inside of the container?
or how do I make the expansion panel widget to this style?
here is my expansion list code
ExpansionPanelList.radio(
        children: taskList
            .map((task) => ExpansionPanelRadio(
                  value: task,
                  headerBuilder: (context, isOpen) =>
                      TaskTile(task: task, taskList: taskList),
                  body: const Text('ss'),
                ))
            .toList());

the TaskTile is task tile widget that contains the widgets inside the expansion panel
how do I implement this?

A: Here it is this looks like you want the expanded list:
import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  static const String _title = 'Expansion Panel List';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: const MyStatefulWidget(),
      ),
    );
  }
}

// stores ExpansionPanel state information
class Item {
  Item({
    required this.id,
    required this.expandedValue,
    required this.headerValue,
    this.checkValue = false,
    this.isExpanded = false,
  });
  int id;
  String expandedValue;
  String headerValue;
  bool isExpanded;
  bool checkValue;
}

List<Item> generateItems(int numberOfItems) {
  return List<Item>.generate(numberOfItems, (int index) {
    return Item(
      id: index,
      headerValue: 'Panel $index',
      expandedValue: 'This is item number $index',
    );
  });
}

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({super.key});

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  final List<Item> _data = generateItems(8);

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Container(
        decoration: const BoxDecoration(
          color: Colors.grey,
          borderRadius: BorderRadius.all(Radius.circular(30)),
          boxShadow: [
            BoxShadow(
              color: Colors.black,
              offset: Offset(0.0, 0.0),
              blurRadius: 14.0,
              spreadRadius: -15,
            ), //BoxShadow
          ],
        ),
        child: _buildPanel(),
      ),
    );
  }

  Widget _buildPanel() {
    return ExpansionPanelList.radio(
      initialOpenPanelValue: 1,
      children: _data.map<ExpansionPanel>((Item item) {
        return ExpansionPanelRadio(
          value: item.id,
          headerBuilder: (BuildContext context, bool isExpanded) {
            return ListTile(
              title: Row(
                children: [
                  GestureDetector(
                    onTap: () {
                      setState(() {
                        // Toggle check value when tapped.
                        item.checkValue = !item.checkValue;
                      });
                    },
                    child: Icon(
                        item.checkValue ? Icons.check_box : Icons.check_box_outline_blank_rounded,
                        color: Colors.lightBlue,
                    ),
                  ),
                  const SizedBox(width: 10),
                  Text(item.headerValue,
                  style: TextStyle(decoration: item.checkValue ? TextDecoration.lineThrough : null),
                  )
                ],
              ),
            );
          },
          body: ListTile(
              title: Text(item.expandedValue),
              subtitle:
              const Text('To delete this panel, tap the trash can icon'),
              trailing: const Icon(Icons.delete),
              onTap: () {
                setState(() {
                  _data.removeWhere((Item currentItem) => item == currentItem);
                });
              }),
          // isExpanded: item.isExpanded,
        );
      }).toList(),
    );
  }
}

If you want to add more items i.e date you can do that by adding it in TaskFile class and for style you can also do that in that class, If you want padding in the Expanded List, then, give the form of the list as you want.

A: i've a simmilar issue before when i was creating a Flutter app, then i realized that is more efficient, using MediaQuery instead giving numbers, i.e.
height:  MediaQuery.of(context).size.height*10,
width:  MediaQuery.of(context).size.width*80,

this is a example, i hope that you can solve this problem.


text:
Q: Given: iptables entry in place; my.cnf properly set up; MySQL user & permissions properly set - but still cannot access MySQL remotely: Suggestions? I would like to access MySQL remotely on an Amazon EC2 CentOS instance (I assume it is CentOS because I use yum to update installed applications and libraries).
I believe that iptables is set properly, that my.cnf is set properly, and that the MySQL user is properly set.
I list all relevant settings in the sections that follow.

Contents of iptables:
# Generated by iptables-save v1.4.18 on Tue Mar  3 18:02:27 2015
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [2620:387248]
[0:0] -A INPUT -i lo -j ACCEPT
[9189:1027277] -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
[216:12376] -A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
[0:0] -A INPUT -s 24.91.66.190/32 -p tcp -i eth0 --dport 3306 -m state --state NEW,ESTABLISHED -j ACCEPT
COMMIT
# Completed on Tue Mar  3 18:02:27 2015

Contents of my.cnf:
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# Settings user and group are ignored when systemd is used.
# If you need to run mysqld under a different user or group,
# customize your systemd unit file for mysqld according to the
# instructions in http://fedoraproject.org/wiki/Systemd

bind-address=0.0.0.0
port=3306

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

Relevant MySQL setup:
mysql> select user, host from mysql.user;
+-------------+--------------+
| user        | host         |
+-------------+--------------+
| root        | 127.0.0.1    |
| dan         | 24.91.66.190 |
| root        | ::1          |
| dan         | localhost    |
| glassbiller | localhost    |
| root        | localhost    |
+-------------+--------------+
6 rows in set (0.00 sec)

and
mysql> select user, host, db, select_priv, insert_priv from mysql.db;
+-------------+--------------+------------------+-------------+-------------+
| user        | host         | db               | select_priv | insert_priv |
+-------------+--------------+------------------+-------------+-------------+
| dan         | 24.91.66.190 | glassbiller_test | Y           | Y           |
| glassbiller | localhost    | glassbiller\_%   | Y           | Y           |
| dan         | localhost    | glassbiller_test | Y           | Y           |
+-------------+--------------+------------------+-------------+-------------+
3 rows in set (0.00 sec)

Details of server and client MySQL tool:
From wget -qO- http://instance-data/latest/meta-data/public-ipv4 (see https://stackoverflow.com/a/7536318/368896) I have confirmed the IP address that I must access from my remote machine, and I am using this.
I have restarted both iptables (sudo service iptables restart) and mysql (sudo service mysqld restart).  In fact, at one point I restarted the server.
The password set for user dan in MySQL is the same for both the 'localhost' and the '24.91.66.190' entries.
I obtained the IP address from which I am trying to access the server (24.91.66.190) via the simple URL http://whatismyip.com, which I typed into Chrome running on my client Windows machine.
I am attempting to access the remote instance from a Windows machine using the program SQLYog.
Of note: When I SSH into this EC2 instance, I use
ssh -i myprivatekey.pem ec2-user@x.x.x.x (i.e, I use a public/private key login, with no password - I'm not sure if this is relevant).  I use a Windows program called 'SecureCRT' to log on to my SSH session - I don't use PuTTy.

When I attempt to access the MySQL database from my Windows machine at the indicated IP (24.91.66.190), with username dan and the password set up for user dan at that IP on MySQL on the remote server, the connection simply times out.
Having investigated both some documentation for both iptables and mysql, as well as reviewing dozens of forum postings on the topic, but without finding any possible clues that I have not already tried, I am now posting this question on ServerFault.
Given that I have undertaken all of the above steps, and still cannot access the MySQL instance remotely, what are suggestions for following steps I might take to track down the problem?

One last detail: In the iptables listing, above, I had changed from INPUT DROP [3;120] to :INPUT ACCEPT [0;0] - in case that made a difference (it did not).  I plan to change it back as soon as this problem is resolved.


text:
Q: Prove Jacobian of $f: \mathbb{R}^{2} \to \mathbb{R}^{2}$ with 3 conditionals over $\mathbb{R}^{2}$ is $I_{2 \times 2}$. If $f: \mathbb{R}^{2} \to \mathbb{R}^{2}$  is given by:
$f(x,y)=
    \begin{cases}
      (x,y-x^{2}) & if & x^{2} \leq y \\
      (x,\frac{y^{2}-x^{2}}{x^{2}}) & if & 0 \leq y \leq x^{2} \\
      -f(-x,-y)   & if & y \leq 0
\end{cases}$
To prove the Jacobian is the identity it must be proved that $df(0,0)=I_{2 \times 2}$. If $
x^{2} \leq y$, then $f(x,y)=(x,y-x^{2})$. So by definition of  Jacobian matrix we got $$df(x,y)=\begin{bmatrix}
1 & 0 \\
-2x & 1
\end{bmatrix}.$$
So  it follows that  $df(0,0)=I_{2 \times 2}$ as required.
The problems begins considering the case where, $(x,y) \in \mathbb{R}^{2}$ are such   $0 \leq y \leq x^{2}$, then $f(x,y)=(x,\frac{y^{2}-x^{2}}{x^{2}})$. Obtaining the following Jacobian matrix:
$$df(x,y)=\begin{bmatrix}
1 & 0 \\
\frac{-2y^{2}}{x^3} & \frac{2y}{x^2}
\end{bmatrix}.$$
But $df(0,0)$ doesnt make sense since $\frac{-2y^{2}}{x^3}$ and $\frac{2y}{x^2}$ doesn make sense evaluated at $(0,0)$.
If $(x,y) \in \mathbb{R}^{2}$ are such $y \leq 0 $, then $f(x,y)=-f(-x,-y)$. And as $-y \geq 0$ we can consider the two cases before. If first case hold $x^{2} \leq y$ we are done and if $0 \leq y \leq x^{2}$ the second case hold. But second case troubles me for what I mentioned before.
Any help in order to finish this proof will be aprecciated. Thanks!


text:
Q: detecting whether some records are excluded from an INSERT INTO operation I have a composite primary key on 2 columns in the table I am INSERTing into. I come from working with SQL Server, and I know that if I attempted to insert a duplicate key value into a PK table, it would throw an error.
My problem is, my code is not throwing this kind of error. Can you look at it and see if it's a problem with the code? Or does Access not throw errors for this kind of violation?
[Edit]
I guess I'm looking for a way to just acknowledge that duplicate records are attempted to be inserted. I want the current functionality to remain (dups are tossed; valid records are inserted). I don't want the entire INSERT to get rolled back.
My code is below.
Function InsertData(Ignore As String)

    ' define file path of CSV to be imported
    Dim CurrentDate As String
    Dim CurrentYear As String

    CurrentDate = Format(Date, "yyyymmdd")
    CurrentYear = Format(Date, "yyyy")

    Dim Exfile As String
    Exfile = iPath + "\" + CurrentYear + "\" + "FileName" + CurrentDate + ".txt"

    'this calls a saved import routine
    DoCmd.RunSavedImportExport "tbl_TEMP"

    'merge data with that already existing in tbl_Perm.
    'the clustered PK on product_ID and As_of_Date prevents dup insertion
    Dim dbs As Database
    Dim errLoop As Error

    Set dbs = OpenDatabase(iPath + "\ExDatabase.mdb")
        dbs.Execute " INSERT INTO tbl_Perm (Col1,Col2,Date_Created) " _
                    & "SELECT ColA + ColB, ColC, Format$(Now(),'Short Date')" _
                    & "FROM tbl_TEMP;"

        ' Trap for errors, checking the Errors collection if necessary.
        On Error GoTo Err_Execute

        'delete temp table
        dbs.Execute "DROP TABLE tbl_TEMP;"

    dbs.Close

Err_Execute:
    ' Notify user of any errors that result from
    ' executing the query.
    If DBEngine.Errors.Count > 0 Then
    For Each errLoop In DBEngine.Errors
    MsgBox "Error number: " & errLoop.Number & vbCr & _
    errLoop.Description
    Next errLoop
    End If
 Resume Next

End Function

A: From the Microsoft DAO Doc (here):

In a Microsoft Access workspace, if you provide a syntactically
  correct SQL statement and have the appropriate permissions, the
  Execute method won't fail — even if not a single row can be modified
  or deleted. Therefore, always use the dbFailOnError option when using
  the Execute method to run an update or delete query. This option
  generates a run-time error and rolls back all successful changes if
  any of the records affected are locked and can't be updated or
  deleted.

So add the dbFailOnError option to your call.

A: If you want to allow the INSERT to proceed and determine whether any duplicates were rejected then you could do something like this
Dim cdb As DAO.Database, qdf As DAO.QueryDef, rst As DAO.Recordset
Dim sqlSelect As String, sourceRecords As Long
Set cdb = CurrentDb
sqlSelect = _
        "SELECT ColA + ColB, ColC, Format$(Now(),'Short Date') " & _
        "FROM tbl_TEMP"
Set rst = cdb.OpenRecordset("SELECT COUNT(*) AS n FROM (" & sqlSelect & ")", dbOpenSnapshot)
sourceRecords = rst!n
rst.Close
Set rst = Nothing
Set qdf = cdb.CreateQueryDef("", _
        "INSERT INTO tbl_Perm (Col1,Col2,Date_Created) " & sqlSelect)
qdf.Execute
If qdf.RecordsAffected < sourceRecords Then
    Debug.Print sourceRecords - qdf.RecordsAffected & " record(s) not inserted"
End If
Set qdf = Nothing
Set cdb = Nothing

A: The line
On Error GoTo Err_Execute

is after you execute your SQL statement. The Err_Execute block will - in this case - be called every time because there is not statement like Exit Function before the label. I am not sure what happens to the errors if you close the connection before evaluating the error collection.


text:
Q: how to visualize 200k rows and 100 columns of data heatmap and pheatmap of R failed to produce a cluster by throwing this error.
Error in vector("double", length) : vector size specified is too large

Does any one know how could I visualize that big matrix ?

A: The hexbin package is designed to efficiently summarize large count 2D displays. Only with more than ten million points does this slow down somewhat on my 3 year-old Mac. (Honest, @James, I did think of this independently.) This is a minor mod to the example in one of its help pages:
 require(hexbin)
 h <- hexbin(rnorm(10000),rnorm(10000))
  plot(h, colramp= function(n){magent(n,beg=15,end=225)})


text:
Q: Post username and password to URL from a sh script I need to create a batch sript to check if Internet is responding. If is responding then do nothing, but if no responding then post usernname and password to a URL. Bellow and example that I want to do, I know that the script is wrong and is for this rason that I am asking for help.
#!/bin/sh
if ping -c 1 8.8.8.8 &> /dev/null
then
 do={/tool fetch http-method=post http-data="username=myuser&&password=mypass" url="https://secure.etecsa.net:8443//LoginServlet" }
else
echo 0
fi

A: ping -c 1 8.8.8.8 &> /dev/null will return 0 if the ping is successful.  0 is FALSE, so the then block will not run.  You need to swap your then and else blocks.  There are other issues with the script, but this should answer you question.

A: You can use curl to post your message:
#!/bin/bash

######################################################################
# Script Configuration
######################################################################
TARGET_URL="https://secure.etecsa.net:8443/LoginServlet"

# Set the internet server to be verified (Change this as needed)
VERIFICATION_SERVER="8.8.8.8"

# Verification Timeout (seconds)
VERIFICATION_TIMEOUT_IN_SECONDS=1

# User Data
data="username=myuser&&password=mypass"

# Checks if internet is reachable
ping -c 1 -W ${VERIFICATION_TIMEOUT_IN_SECONDS} ${VERIFICATION_SERVER} &> /dev/null

if [[ $? -ne 0 ]]; then
  # Internet not detected,
  # post username and password to URL
  curl --insecure -X POST ${TARGET_URL} -d "${data}"
else
  # Internet active
  echo "Internet is active."
fi


text:
Q: Disable QAction if the QTreeView item has no children I have QTreeView populated from database.
I have contextmenu configured as:
ui->treeView->setContextMenuPolicy(Qt::CustomContextMenu);

I have the method to look for a right click to open contextMenu on the item.
void MainWindow::on_treeView_customContextMenuRequested(const QPoint &pos)
{
QModelIndex idx = ui->treeView->indexAt(pos);
if (!idx.isValid())
        {return;}
else{
   QPoint globalPos = ui->treeView->mapToGlobal(pos);
   QAction* selectedItem = contextMenu->exec(globalPos);
    if (selectedItem){
        qDebug () << selectedItem;
    }
}

h.file
QMenu *contextMenu;

How do I check if the selected item from QTreeView is not a parent of any item & it has a parent.
Should I include QTreeView and QStandardItem code here to see or that's irrelevant?

A: The Qt doc. has a dedicated chapter for this topic:
Model/View Programming
which I recommend to get an overview.
Concerning the actual question of OP:

How do I check if the selected item from QTreeView is not a parent of any item & it has a parent.

The QTreeView inherits QAbstractItemView::model() which provides a pointer to the QAbstractItemModel which in turn provides the underlying model data for the rendered tree view items.
Any provided QModelIndex in a view should refer to this model.
The QAbstractItemModel provides a variety of methods to retrieve data concerning visualization and relations of model items. The QTreeView uses this but it should be used as well for any added function.
So, selected item is not parent of any item is turned around into "selected item has no children" for which QAbstractItemModel::hasChildren() is good for:

bool QAbstractItemModel::hasChildren(const QModelIndex &parent = QModelIndex()) const
Returns true if parent has any children; otherwise returns false.
Use rowCount() on the parent to find out the number of children.
Note that it is undefined behavior to report that a particular index hasChildren with this method if the same index has the flag Qt::ItemNeverHasChildren set.
Note: This function can be invoked via the meta-object system and from QML. See Q_INVOKABLE.
See also parent() and index().

and it has a parent can be retrieved using QAbstractItemModel::parent():

QModelIndex QAbstractItemModel::parent(const QModelIndex &index) const
Returns the parent of the model item with the given index. If the item has no parent, an invalid QModelIndex is returned.
A common convention used in models that expose tree data structures is that only items in the first column have children. For that case, when reimplementing this function in a subclass the column of the returned QModelIndex would be 0.
When reimplementing this function in a subclass, be careful to avoid calling QModelIndex member functions, such as QModelIndex::parent(), since indexes belonging to your model will simply call your implementation, leading to infinite recursion.
Note: This function can be invoked via the meta-object system and from QML. See Q_INVOKABLE.
See also createIndex().

Putting this together, OPs function should look like this:
void MainWindow::on_treeView_customContextMenuRequested(const QPoint &pos)
{
    QModelIndex idx = ui->treeView->indexAt(pos);
    if (!idx.isValid()
      || !ui->treeView->model()->hasChildren(idx)
      && !ui->treeView->model()->parent(idx).isValid()) {
      return;
      // bail out -> no context menu for leaf nodes or toplevel nodes
    } else {
       QPoint globalPos = ui->treeView->mapToGlobal(pos);
       QAction* selectedItem = contextMenu->exec(globalPos);
        if (selectedItem) {
            qDebug () << selectedItem;
        }
    }
}

I'm not quite sure whether this matches exactly OPs required behavior. It might be necessary to fix the condition but this should be not that hard.


text:
Q: Why I need to stringify an array of objects, and parse after retrieve it, in React/Redux? I'm not sure if this is the correct way to go, but it's working. I'm not sure either of this is a problem of React/Redux, or just javascript behaviour.
This is my REDUX Actions:
export const getDetectedPersonList = () => {
  return (dispatch, getState) => {
    fetch("http://localhost:8080/detectedPersonsListWS")
          .then(function(response) {
            if (response.status >= 400) {
              throw new Error("Bad response from server");
            }
              return response.json();
            })
            .then(function(detections) {

              var detected = [{"a":1},{"b":2},{"c":3},{"d":4}];

                dispatch({
                  type : GET_DETECTED_PERSON_LIST,
                  payload : JSON.stringify(detected)
                })
             })
        }
    }

And in REACT's presentational component I have:
 componentDidMount() {
  this.props.getDetectedPersonList();
 }

 render() {
    if (typeof this.props.detectedPersonListJson == 'string'){
      console.log(this.props.detectedPersonListJson);
      var json = JSON.parse(this.props.detectedPersonListJson);
      console.log(json); //The array is perfect as created before (detected)
    }

The detected array is obviously mock (in real world I expect a REST response), but ilustrates the question I think, it's not a problem of async action.
My biggest problem is that I'm validating props, before and I was expecting an array, but cannot send the array directly because I receive: [object object] and is interpreted as string by typeof, but it's not... And I get an error doing JSON.parse(detected), if I haven't done JSON.stringify(detected) before.
Makes any sense? Best practices to follow? Thanks so much.


text:
Q: In Java should helper methods be static or instance? I know this question has been answered by others before, but the answer seems to be different depending on the situation.
I see many people saying the class should be instantiated, so that it can be tested and mocked etc... Well here's my code and it looks to me like I could easily unit test it.
WebsiteLogin.java
Is an interface which extends Website.java and contains a void method called login(), it takes three strings, Username, Password and Url.
AccountLogin.java
Is an interface which extends Account and contains getter methods for Username, Password and Url, as well as a setEnabled() method which takes a boolean.
In a seperate class called Login.java I have a method login() which takes WebsiteLogin and AccountLogin. The class only has the one method.
Here's the code
static void login(AccountLoginInformation account, LoginToWebsite website){
        website.login(account.getUsername(), account.getPassord(), account.getUrl());
        account.setEnabled(true);
}

So it logs in and then sets the account to enabled. Now although this method is static, I could still test it works by sending a stubbed LoginToWebsite to it. Am I correct here? So would there be any other reason for not using a static method?
Another question, with Java 8 and default methods in interfaces, could I create an interface called Login.java with the following;
default void login(AccountLoginInformation account, LoginToWebsite website){
        website.login(account.getUsername(), account.getPassord(), account.getUrl());
        account.setEnabled(true);
}

Then in another class implement the Login.java class and just call
login(account, website);

Or is this bad practice?