问:
Maven: hibernate-entitymanager together with javaee-api break my unit tests
I'm having the two dependencies javaee-api and hibernate-entitymanager in my pom. But they don't work very well together: as soon as I add javaee-api, all my unit tests break due to java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/validation/Validation. Without javaee-api, everything works fine. Why is that?

(this question has been edited in order to fit the problem ;))

答:
Maven Dependencies have no order , but the provide the concept of scopes.

So what you need to do is, use the scopes to build the right set of dependencies for:

compile time

runtime in the server: (use for example provided for dependencies that are needed at compiletime, but will be provided by the server, so your Application does/must not contain them

test time: use the test scope to add dependencies that are only needed for testing (junit for example)

In your special case it looks like that javax.validation interface libary is not aviable in the tests. May they are not incuded in javaee-api. If this is the case, then add:

```<code>     <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.0.0.GA</version>
        <scope>test</scope>
    </dependency>
</code>```

But be careful, your explanation, about what is included in the server, and the described behaviour sounds strange to me. - I recommend to double check what the server provides and what javaee-api relay includes. But may I am wrong, and javax.validation  is only needed for test explicit

The reason why the problem only occoures when javaee-api is included, could be, that javax validation sometimes is only turned on, when a implementation is aviable in the classpath.

The order of dependency matter in some cases. The "problem" is that if a libary/dependency is referenced in two places (direct and inderect) and the version of both references to the same library differers, Maven has to decide which version to use.

The first and most important criterium is the depth of the reference in the dependency tree. If you reference the library directly in your project POM, then this will be dominate all other. If the library is refered directly by a libary that is refered direcly by you, then this will dominate all other where is one more indirection.

But in case where are two references (to the same library in different versions) in the same depth of the dependency tree, the first one will win. (more details).

First of all,

Body:
Maven Dependencies have no order , but the provide the concept of scopes.

So what you need to do is, use the scopes to build the right set of dependencies for:

compile time

runtime in the server: (use for example provided for dependencies that are needed at compiletime, but will be provided by the server, so your Application does/must not contain them

test time: use the test scope to add dependencies that are only needed for testing (junit for example)

In your special case it looks like that javax.validation interface libary is not aviable in the tests. May they are not incuded in javaee-api. If this is the case, then add:

     <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.0.0.GA</version>
        <scope>test</scope>
    </dependency>

But be careful, your explanation, about what is included in the server, and the described behaviour sounds strange to me. - I recommend to double check what the server provides and what javaee-api relay includes. But may I am wrong, and javax.validation  is only needed for test explicit

The reason why the problem only occoures when javaee-api is included, could be, that javax validation sometimes is only turned on, when a implementation is aviable in the classpath.

The order of dependency matter in some cases. The "problem" is that if a libary/dependency is referenced in two places (direct and inderect) and the version of both references to the same library differers, Maven has to decide which version to use.

The first and most important criterium is the depth of the reference in the dependency tree. If you reference the library directly in your project POM, then this will be dominate all other. If the library is refered directly by a libary that is refered direcly by you, then this will dominate all other where is one more indirection.

But in case where are two references (to the same library in different versions) in the same depth of the dependency tree, the first one will win. (more details).

First of all,


来源: stackexchange

问:
How to get the SID of the current machine?
I know how to get the SID for the current user. Conceptually the answer is:

Use OpenThreadToken (or OpenProcessToken) to get the security TOKEN of the running user

use GetTokenInformation to get the TOKEN_USER structure

and then TOKEN_USER.Sid is the Sid

So in pseudocode:

```<code>String GetCurrentUserSid()
{
   // Get the calling thread's access token.
   TOKEN hToken;
   if (!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, true, out hToken)
   {
       if (GetLastError() != ERROR_NO_TOKEN)
          RaiseLastWin32Error();

       // No thread token exists, try again against the process token
       if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, out hToken)
          RaiseLastWin32Error();
   }
   try
   {
      // Obtain the size of the user information in the token.
      DWORD cbReturned;
      GetTokenInformation(hToken, TokenUser, nil, 0, out cbReturned);

      //Allocate memory and try again for real
      TOKEN_USER* tiUser = GetMemory(cbReturned);
      if (!GetTokenInformation(hToken, TokenUser, tiUser, cbReturned, out cbReturned))
      RaiseLastWin32Error();
   }
   finally
   {
      CloseHandle(hToken);
   }

   //Convert the structure to a string
   return SidToString(tiUser.User.Sid);
}
</code>```

But how to do it for the current machine?

```<code>String GetCurrentMachineSid()
{
   // TODO: Ask Stackoverflow
}
</code>```

Bonus Reading

The Machine SID Duplication Myth (and Why Sysprep Matters)

Machine SIDs and Domain SIDs

How to find SID of computer

答:
You can see the machine SID on your computer by running Sysinternals
  PsGetSid with no parameters

so i simply look under debugger how PsGetSid do this.

it get SID from POLICY_ACCOUNT_DOMAIN_INFO - DomainSid : Pointer to the SID of the account domain

code can be next

```<code>LSA_HANDLE PolicyHandle;

LSA_OBJECT_ATTRIBUTES ObjectAttributes = { sizeof(ObjectAttributes) };

NTSTATUS status = LsaOpenPolicy(0, &ObjectAttributes, POLICY_VIEW_LOCAL_INFORMATION, &PolicyHandle);

if (0 <= status)
{
    POLICY_ACCOUNT_DOMAIN_INFO* ppadi;

    status = LsaQueryInformationPolicy(PolicyHandle, PolicyAccountDomainInformation, (void**)&ppadi);

    if (0 <= status)
    {
        PWSTR szSid;
        BOOL b = ConvertSidToStringSidW(ppadi->DomainSid, &szSid);
        LsaFreeMemory(ppadi);

        if (b)
        {
            DbgPrint("%S\n", szSid);
            LocalFree(szSid);
        }
    }

    LsaClose(PolicyHandle);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I know how to get the SID for the current user. Conceptually the answer is:

Use OpenThreadToken (or OpenProcessToken) to get the security TOKEN of the running user

use GetTokenInformation to get the TOKEN_USER structure

and then TOKEN_USER.Sid is the Sid

So in pseudocode:

String GetCurrentUserSid()
{
   // Get the calling thread's access token.
   TOKEN hToken;
   if (!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, true, out hToken)
   {
       if (GetLastError() != ERROR_NO_TOKEN)
          RaiseLastWin32Error();

       // No thread token exists, try again against the process token
       if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, out hToken)
          RaiseLastWin32Error();
   }
   try
   {
      // Obtain the size of the user information in the token.
      DWORD cbReturned;
      GetTokenInformation(hToken, TokenUser, nil, 0, out cbReturned);

      //Allocate memory and try again for real
      TOKEN_USER* tiUser = GetMemory(cbReturned);
      if (!GetTokenInformation(hToken, TokenUser, tiUser, cbReturned, out cbReturned))
      RaiseLastWin32Error();
   }
   finally
   {
      CloseHandle(hToken);
   }

   //Convert the structure to a string
   return SidToString(tiUser.User.Sid);
}

But how to do it for the current machine?

String GetCurrentMachineSid()
{
   // TODO: Ask Stackoverflow
}

Bonus Reading

The Machine SID Duplication Myth (and Why Sysprep Matters)

Machine SIDs and Domain SIDs

How to find SID of computer

Body:
You can see the machine SID on your computer by running Sysinternals
  PsGetSid with no parameters

so i simply look under debugger how PsGetSid do this.

it get SID from POLICY_ACCOUNT_DOMAIN_INFO - DomainSid : Pointer to the SID of the account domain

code can be next

LSA_HANDLE PolicyHandle;

LSA_OBJECT_ATTRIBUTES ObjectAttributes = { sizeof(ObjectAttributes) };

NTSTATUS status = LsaOpenPolicy(0, &ObjectAttributes, POLICY_VIEW_LOCAL_INFORMATION, &PolicyHandle);

if (0 <= status)
{
    POLICY_ACCOUNT_DOMAIN_INFO* ppadi;

    status = LsaQueryInformationPolicy(PolicyHandle, PolicyAccountDomainInformation, (void**)&ppadi);

    if (0 <= status)
    {
        PWSTR szSid;
        BOOL b = ConvertSidToStringSidW(ppadi->DomainSid, &szSid);
        LsaFreeMemory(ppadi);

        if (b)
        {
            DbgPrint("%S\n", szSid);
            LocalFree(szSid);
        }
    }

    LsaClose(PolicyHandle);
}


问:
Read json from argument instead of stdin using jq
Say I have JSON like so:

```<code>export connection_info = ` echo '{
  "values": [
    {"host":"xxx", "port": 3939},
    {"host":"yyy", "port": 7373}
  ]
}'  | jq -c `
</code>```

And I want to read it like this:

```<code>#!/usr/bin/env bash

echo "$connection_info" | jq -r '.values[]' |

  while read item; do

     timeout 10 telnet `jq -r "$item"` 9200 || {
        echo "Could not connect to host: $host port: $port"
     }
  done;
</code>```

how can parse the host and port from the item? Something like this:

I could probably do:

```<code>host=`echo "$item" | jq -r '.host'`
port=`echo "$item" | jq -r '.port'`

timeout 10 telnet "$host" "$port" 9200
</code>```

but is there a way to do it without using stdin?

答:
Yes.  Also, there's no need to export connection_info.

For example:

```<code>#!/bin/bash

connection_info='{
  "values": [
    {"host":"xxx", "port": 3939},
    {"host":"yyy", "port": 7373}
  ]
}'

jq -n --argjson ci "$connection_info" -cr '$ci | .values[] | "\(.host) \(.port)"' |
while read -r host port ; do
     timeout 10 telnet "$host" "$port" ||
        echo "Could not connect to host: $host port: $port"
done;
</code>```

Using stdin

For reference, your script could also be tweaked as follows:

```<code>#!/bin/bash

connection_info='{
  "values": [
    {"host":"xxx", "port": 3939},
    {"host":"yyy", "port": 7373}
  ]
}'

echo "$connection_info" | jq -cr '.values[] | "\(.host) \(.port)"' |
while read -r host port ; do
     timeout 10 telnet "$host" "$port" ||
        echo "Could not connect to host: $host port: $port"
done;
</code>```

Body:
Say I have JSON like so:

export connection_info = ` echo '{
  "values": [
    {"host":"xxx", "port": 3939},
    {"host":"yyy", "port": 7373}
  ]
}'  | jq -c `

And I want to read it like this:

#!/usr/bin/env bash

echo "$connection_info" | jq -r '.values[]' |

  while read item; do

     timeout 10 telnet `jq -r "$item"` 9200 || {
        echo "Could not connect to host: $host port: $port"
     }
  done;

how can parse the host and port from the item? Something like this:

I could probably do:

host=`echo "$item" | jq -r '.host'`
port=`echo "$item" | jq -r '.port'`

timeout 10 telnet "$host" "$port" 9200

but is there a way to do it without using stdin?

Body:
Yes.  Also, there's no need to export connection_info.

For example:

#!/bin/bash

connection_info='{
  "values": [
    {"host":"xxx", "port": 3939},
    {"host":"yyy", "port": 7373}
  ]
}'

jq -n --argjson ci "$connection_info" -cr '$ci | .values[] | "\(.host) \(.port)"' |
while read -r host port ; do
     timeout 10 telnet "$host" "$port" ||
        echo "Could not connect to host: $host port: $port"
done;

Using stdin

For reference, your script could also be tweaked as follows:

#!/bin/bash

connection_info='{
  "values": [
    {"host":"xxx", "port": 3939},
    {"host":"yyy", "port": 7373}
  ]
}'

echo "$connection_info" | jq -cr '.values[] | "\(.host) \(.port)"' |
while read -r host port ; do
     timeout 10 telnet "$host" "$port" ||
        echo "Could not connect to host: $host port: $port"
done;


问:
How to turn a dict value that's a list into a tuple to then invert the dict
My assignment requires to create a dictionary with a list of values for each key. Then, it provides an invert function and asks to modify the function so that every item in the list is a new key. My understanding is this.
a={'a':['2','3','4'], 'b':['1','5','6']}
b={'2':'a', '3':'a','4':'a','1':'b','5':'b','6':'b'}

I created a test dictionary with tuples instead of lists and I was able to invert them but I don't know how to turn the lists in the dictionary into tuples and then into individual items that would correspond to the same value.
I watched youtube tutorials and tried googling it (including stack overflow) but cannot get how to complete it.
At this point, I don't even know anything - I would definitely appreciate any explanation as I feel completely confused.

```<code>
def invert_dict(d):
     inverse = dict()
     for key in d:
          val = d[key]
          if val not in inverse:
               inverse[val] = [key]
          else:
               inverse[val].append(key)
     return inverse

#my initial dictionary
work_contacts={'Lauren' : '617-111-2222', 'Sana' : '781-234-1212', 'Kelly': '845-234-1515', 'Jose' : '946-999-3210', 'Sabrina' : '617-222-5656', 'Shirika' : '410-231-9090', 'Rachel': '823-432-2121'}

c=invert_dict(work_contacts)
c
{'617-111-2222': ['Lauren'], '781-234-1212': ['Sana'], '845-234-1515': ['Kelly'], '946-999-3210': ['Jose'], '617-222-5656': ['Sabrina'], '410-231-9090': ['Shirika'], '823-432-2121': ['Rachel']}
c['617-111-2222'] #calling the first key
['Lauren']

#the dictionary for the assignment
work_contacts={'Lauren' : ['617-111-2222', 'lauren@company.org'], 'Sana' : ['781-234-1212', 'sana@company.org'], 'Kelly': ['845-234-1515', 'kelly@company.org'], 'Jose' : ['946-999-3210', 'jose@company.org'], 'Sabrina' : ['617-222-5656', 'sabrina@company.org'], 'Shirika' : ['410-231-9090', 'shirika@comoany.org'], 'Rachel': ['823-432-2121', 'rachel@company.org']}

#the error comes back like this
invert_dict(work_contacts)
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    invert_dict(work_contacts)
  File "<pyshell#2>", line 5, in invert_dict
    if val not in inverse:
TypeError: unhashable type: 'list'

#I tried to turn the lists into tuples
def l_t(s):
    final = []
    for k, v in test.items():
        if v in final:
            final.append(k)
        final = tuple(final)
    return s

l_t(work_contacts)
{'Lauren': ['617-111-2222', 'lauren@company.org'], 'Sana': ['781-234-1212', 'sana@company.org'], 'Kelly': ['845-234-1515', 'kelly@company.org'], 'Jose': ['946-999-3210', 'jose@company.org'], 'Sabrina': ['617-222-5656', 'sabrina@company.org'], 'Shirika': ['410-231-9090', 'shirika@comoany.org'], 'Rachel': ['823-432-2121', 'rachel@company.org']}

def l_t(s):
    p=s
    final = []
    for k, v in test.items():
        if v in final:
            final.append(k)
        final = tuple(final)
    return p

l_t(work_contacts)
{'Lauren': ['617-111-2222', 'lauren@company.org'], 'Sana': ['781-234-1212', 'sana@company.org'], 'Kelly': ['845-234-1515', 'kelly@company.org'], 'Jose': ['946-999-3210', 'jose@company.org'], 'Sabrina': ['617-222-5656', 'sabrina@company.org'], 'Shirika': ['410-231-9090', 'shirika@comoany.org'], 'Rachel': ['823-432-2121', 'rachel@company.org']}

`def l_t(s):
    p=s
    final = []
    for k, v in p.items():
        if v in final:
            final.append(k)
        final = tuple(final)
    return p

l_t(work_contacts)
{'Lauren': ['617-111-2222', 'lauren@company.org'], 'Sana': ['781-234-1212', 'sana@company.org'], 'Kelly': ['845-234-1515', 'kelly@company.org'], 'Jose': ['946-999-3210', 'jose@company.org'], 'Sabrina': ['617-222-5656', 'sabrina@company.org'], 'Shirika': ['410-231-9090', 'shirika@comoany.org'], 'Rachel': ['823-432-2121', 'rachel@company.org']}

#I then tried to tuple the values
tuple(work_contacts.values())
(['617-111-2222', 'lauren@company.org'], ['781-234-1212', 'sana@company.org'], ['845-234-1515', 'kelly@company.org'], ['946-999-3210', 'jose@company.org'], ['617-222-5656', 'sabrina@company.org'], ['410-231-9090', 'shirika@comoany.org'], ['823-432-2121', 'rachel@company.org'])

#I have generated much more code with error messages, as below
b=invert_dict(test)
b
{(2, 'al', 3): ['a'], ('we', 'as', 4): ['blue']}

b[2]
Traceback (most recent call last):
  File "<pyshell#145>", line 1, in <module>
    b[2]
KeyError: 2
b(2)
Traceback (most recent call last):
  File "<pyshell#146>", line 1, in <module>
    b(2)
TypeError: 'dict' object is not callable
b(2, 'al', 3)
Traceback (most recent call last):
  File "<pyshell#147>", line 1, in <module>
    b(2, 'al', 3)
TypeError: 'dict' object is not callable
b[1]
Traceback (most recent call last):
  File "<pyshell#148>", line 1, in <module>
    b[1]
KeyError: 1```
```

答:
It is not clear to me what you want to solve.

However if you are trying to convert the following

```<code>{'a': [2, 3, 5], 'b': [7,11]} => {2: ['a'], 3: ['a'], 5: ['a'], 7: ['b'], 11: ['b']}
</code>```

Then you could use the following

```<code>{v1: [k] for k, v in original_dict.items() for v1 in v}
</code>```

some extra words
to invert the dictionary I iterate through the original dictionary as per the

```<code>for k, v in original_dict.items() => ('a', [2, 3, 5]), ('b', [7,11])
</code>```

the second step is to iterate through the values, v

```<code>[m for k in [[1,2], [3,4]] for m in k] => [1,2,3,4]
</code>```

This step also shows how list comprehension works - where we can iterate through nested lists.

you have all the tools now to see how you can use the same logic for creating the dictionary.

Body:
My assignment requires to create a dictionary with a list of values for each key. Then, it provides an invert function and asks to modify the function so that every item in the list is a new key. My understanding is this.
a={'a':['2','3','4'], 'b':['1','5','6']}
b={'2':'a', '3':'a','4':'a','1':'b','5':'b','6':'b'}

I created a test dictionary with tuples instead of lists and I was able to invert them but I don't know how to turn the lists in the dictionary into tuples and then into individual items that would correspond to the same value.
I watched youtube tutorials and tried googling it (including stack overflow) but cannot get how to complete it.
At this point, I don't even know anything - I would definitely appreciate any explanation as I feel completely confused.

def invert_dict(d):
     inverse = dict()
     for key in d:
          val = d[key]
          if val not in inverse:
               inverse[val] = [key]
          else:
               inverse[val].append(key)
     return inverse

#my initial dictionary
work_contacts={'Lauren' : '617-111-2222', 'Sana' : '781-234-1212', 'Kelly': '845-234-1515', 'Jose' : '946-999-3210', 'Sabrina' : '617-222-5656', 'Shirika' : '410-231-9090', 'Rachel': '823-432-2121'}

c=invert_dict(work_contacts)
c
{'617-111-2222': ['Lauren'], '781-234-1212': ['Sana'], '845-234-1515': ['Kelly'], '946-999-3210': ['Jose'], '617-222-5656': ['Sabrina'], '410-231-9090': ['Shirika'], '823-432-2121': ['Rachel']}
c['617-111-2222'] #calling the first key
['Lauren']

#the dictionary for the assignment
work_contacts={'Lauren' : ['617-111-2222', 'lauren@company.org'], 'Sana' : ['781-234-1212', 'sana@company.org'], 'Kelly': ['845-234-1515', 'kelly@company.org'], 'Jose' : ['946-999-3210', 'jose@company.org'], 'Sabrina' : ['617-222-5656', 'sabrina@company.org'], 'Shirika' : ['410-231-9090', 'shirika@comoany.org'], 'Rachel': ['823-432-2121', 'rachel@company.org']}

#the error comes back like this
invert_dict(work_contacts)
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    invert_dict(work_contacts)
  File "<pyshell#2>", line 5, in invert_dict
    if val not in inverse:
TypeError: unhashable type: 'list'

#I tried to turn the lists into tuples
def l_t(s):
    final = []
    for k, v in test.items():
        if v in final:
            final.append(k)
        final = tuple(final)
    return s

l_t(work_contacts)
{'Lauren': ['617-111-2222', 'lauren@company.org'], 'Sana': ['781-234-1212', 'sana@company.org'], 'Kelly': ['845-234-1515', 'kelly@company.org'], 'Jose': ['946-999-3210', 'jose@company.org'], 'Sabrina': ['617-222-5656', 'sabrina@company.org'], 'Shirika': ['410-231-9090', 'shirika@comoany.org'], 'Rachel': ['823-432-2121', 'rachel@company.org']}

def l_t(s):
    p=s
    final = []
    for k, v in test.items():
        if v in final:
            final.append(k)
        final = tuple(final)
    return p

l_t(work_contacts)
{'Lauren': ['617-111-2222', 'lauren@company.org'], 'Sana': ['781-234-1212', 'sana@company.org'], 'Kelly': ['845-234-1515', 'kelly@company.org'], 'Jose': ['946-999-3210', 'jose@company.org'], 'Sabrina': ['617-222-5656', 'sabrina@company.org'], 'Shirika': ['410-231-9090', 'shirika@comoany.org'], 'Rachel': ['823-432-2121', 'rachel@company.org']}

`def l_t(s):
    p=s
    final = []
    for k, v in p.items():
        if v in final:
            final.append(k)
        final = tuple(final)
    return p

l_t(work_contacts)
{'Lauren': ['617-111-2222', 'lauren@company.org'], 'Sana': ['781-234-1212', 'sana@company.org'], 'Kelly': ['845-234-1515', 'kelly@company.org'], 'Jose': ['946-999-3210', 'jose@company.org'], 'Sabrina': ['617-222-5656', 'sabrina@company.org'], 'Shirika': ['410-231-9090', 'shirika@comoany.org'], 'Rachel': ['823-432-2121', 'rachel@company.org']}

#I then tried to tuple the values
tuple(work_contacts.values())
(['617-111-2222', 'lauren@company.org'], ['781-234-1212', 'sana@company.org'], ['845-234-1515', 'kelly@company.org'], ['946-999-3210', 'jose@company.org'], ['617-222-5656', 'sabrina@company.org'], ['410-231-9090', 'shirika@comoany.org'], ['823-432-2121', 'rachel@company.org'])

#I have generated much more code with error messages, as below
b=invert_dict(test)
b
{(2, 'al', 3): ['a'], ('we', 'as', 4): ['blue']}

b[2]
Traceback (most recent call last):
  File "<pyshell#145>", line 1, in <module>
    b[2]
KeyError: 2
b(2)
Traceback (most recent call last):
  File "<pyshell#146>", line 1, in <module>
    b(2)
TypeError: 'dict' object is not callable
b(2, 'al', 3)
Traceback (most recent call last):
  File "<pyshell#147>", line 1, in <module>
    b(2, 'al', 3)
TypeError: 'dict' object is not callable
b[1]
Traceback (most recent call last):
  File "<pyshell#148>", line 1, in <module>
    b[1]
KeyError: 1```

Body:
It is not clear to me what you want to solve.

However if you are trying to convert the following

{'a': [2, 3, 5], 'b': [7,11]} => {2: ['a'], 3: ['a'], 5: ['a'], 7: ['b'], 11: ['b']}

Then you could use the following

{v1: [k] for k, v in original_dict.items() for v1 in v}

some extra words
to invert the dictionary I iterate through the original dictionary as per the

for k, v in original_dict.items() => ('a', [2, 3, 5]), ('b', [7,11])

the second step is to iterate through the values, v

[m for k in [[1,2], [3,4]] for m in k] => [1,2,3,4]

This step also shows how list comprehension works - where we can iterate through nested lists.

you have all the tools now to see how you can use the same logic for creating the dictionary.


问:
The second time the JQuery Ajax is fired the data does not bind in vuejs2, although the data update in Vue object
So I`m trying to bind a value to a HTML input type="checkbox" element by using vuejs2 v-model, by calling a JQuery Ajax 'get' function. The value binds correctly the first time, but afterwards it does nothing, It also deselect the input type="checkbox".

```<code>...<input type="checkbox" id="notification" class="custom-control-input" v-model="checked"  />...

... <button class="btn btn-primary" type="button" onclick="getSettings()">Update</button>...

<script>
     function getSettings()
                {
                    $.ajax({
                        type: "GET",
                        url: "../../handler/getSettings.ashx",
                        contentType: "application/json; charset=utf-8",
                        data: {

                        },
                        async:false,
                        success: function (result) {

                            var app = new Vue({
                                el: '#notification',
                                data: {
                                    checked: result.Notification
                                }
                            });

                            console.log(app.checked);
                        },
                        error: function (err) {

                        }
                    });
                };
</script>
</code>```

I expect the  to be selected, but if I rerun (for the second time and onward) the code (by calling getSettings()) the input type="checkbox" deselect and stays deselected. I can confirm that the code get executed, due to the fact that the console log return a 'true'.

答:
So it looks like every request you send - you build a new VueJS object which destroys all the data you saved. Vue is super powerful, and allows you to declare methods within the object itself. As seen below.

Vue objects also have life cycle events! Which allows you to put things like "mounted" in the Vue object. Mounted is called when the Vue object is attached to the html page.

Take a look at the rework below, and the docs. after.

```

I haven't tested this. But it should work.

I suggest looking at:
https://v2.vuejs.org/v2/guide/
Scroll down a bit you and will see a few examples involving methods.

Body:
So I`m trying to bind a value to a HTML input type="checkbox" element by using vuejs2 v-model, by calling a JQuery Ajax 'get' function. The value binds correctly the first time, but afterwards it does nothing, It also deselect the input type="checkbox".

...<input type="checkbox" id="notification" class="custom-control-input" v-model="checked"  />...

... <button class="btn btn-primary" type="button" onclick="getSettings()">Update</button>...

I expect the  to be selected, but if I rerun (for the second time and onward) the code (by calling getSettings()) the input type="checkbox" deselect and stays deselected. I can confirm that the code get executed, due to the fact that the console log return a 'true'.

Body:
So it looks like every request you send - you build a new VueJS object which destroys all the data you saved. Vue is super powerful, and allows you to declare methods within the object itself. As seen below.

Vue objects also have life cycle events! Which allows you to put things like "mounted" in the Vue object. Mounted is called when the Vue object is attached to the html page.

Take a look at the rework below, and the docs. after.

<script>
var app = new Vue({
  el: '#notification',
  data: {
    checked: false
  },
  methods:{
    getSettings(){
      $.ajax({
              type: "GET",
              url: "../../handler/getSettings.ashx",
              contentType: "application/json; charset=utf-8",
                        data: {},
                        async:false,
                        success: function (result) {
                            this.checked = result.Notification;
                            console.log(app.checked);
                        },
                        error: function (err) {

                        }
                    });
    }
  },
  mounted(){
    this.getSettings();
  }
});
</script

I haven't tested this. But it should work.

I suggest looking at:
https://v2.vuejs.org/v2/guide/
Scroll down a bit you and will see a few examples involving methods.


问:
Writing the results in html file by passing the values in java - any help would be greatly appreciated
Placed the reports have overrided all the resultsi would like to print in a table with results but when i printed it overriding the results and it is printing only one line

am passing the values form other class file to print the results

i have tried using Buffered  writer for writing the code

public void createTestSummaryHTMLTable(String sample,String samp[le,String sample,String passedText,String status) throws IOException {

    File file=new File("C:\\AutomationResults\\Forms\\",foldername);
    if(!file.exists()){
        file.mkdir();}

    final String FILE_PATH =(file+"/"+formname);

    //final String FILE_PATH = "C:\\AutomationResults\\Forms\\"+formname;
    final String FILE_EXTENSION = "html";
    DateFormat df = new SimpleDateFormat("yyyyMMdd"); // add S if you need milliseconds
    String filename = FILE_PATH + "_"+ df.format(new Date()) + "." + FILE_EXTENSION;

    File file2 = new File(filename);

    // if file doesnt exists, then create it
    if (!file2.exists()) {
        file2.createNewFile();
    }
    BufferedWriter html = new BufferedWriter(new FileWriter(file2));
    html.write("
");
    html.write("<title>Automation Summary report </title>");
    html.write("
");
    html.write("Batch report heading");
    html.write(""+new Date().toString()+"");
    html.write("
");
    addlabel1(html,"Test Step Name");
    addlabel1(html,"Test Step Description");
    addlabel1(html,"Status");
    addlabel1(html,"Screenshot");
    html.write("
");

    html.write("
");
    html.newLine();
    addlabel(html,sample);

    addlabel(html,sample);

    String status1 = "Passed";
    if (status1.equals(status))
    {
        html.write(""+status+"	");
    } else {
        html.write(""+status+"	");
    }

    addlabel(html,"Screenshot");

    html.write("
");
    html.write("
");
    html.close();
}
```

答:
You can try adding a boolean parameter to FileWriter that helps to specify whether it should append to or override the existing content. If you pass true, it would open the file for writing in append mode.

Please change this line:

```<code>BufferedWriter html = new BufferedWriter(new FileWriter(file2));
</code>```

To this:

```<code>BufferedWriter html = new BufferedWriter(new FileWriter(file2, true));
</code>```

Body:
You can try adding a boolean parameter to FileWriter that helps to specify whether it should append to or override the existing content. If you pass true, it would open the file for writing in append mode.

Please change this line:

BufferedWriter html = new BufferedWriter(new FileWriter(file2));

To this:

BufferedWriter html = new BufferedWriter(new FileWriter(file2, true));


问:
Effective-Date-Range One-Hot-Encode groupby
Starting with this sample data...

```<code>import pandas as pd

start_data = {"person_id": [1, 1, 1, 1, 2], "nid": [1, 2, 3, 4, 1],
              "beg": ["Jan 1 2018", "Jan 5 2018", "Jan 10 2018", "Feb 5 2018", "Jan 25 2018"],
              "end": ["Feb 1 2018", "Mar 4 2018", "", "Oct 18 2018", "Nov 10 2018"]}
df = pd.DataFrame(start_data)
df["beg"] = pd.to_datetime(df["beg"])
df["end"] = pd.to_datetime(df["end"])
</code>```

Starting point:

```<code>   person_id  nid        beg        end
0          1    1 2018-01-01 2018-02-01
1          1    2 2018-01-05 2018-03-04
2          1    3 2018-01-10        NaT
3          1    4 2018-02-05 2018-10-18
4          2    1 2018-01-25 2018-11-10
</code>```

Goal output:

```<code>person_id date       1 2 3 4
        1 2018-01-01 1 0 0 0
        1 2018-01-05 1 1 0 0
        1 2018-01-10 1 1 1 0
        1 2018-02-01 0 1 1 0
        1 2018-02-05 0 1 1 1
        1 2018-03-04 0 0 1 1
        1 2018-10-18 0 0 1 0
        2 2018-01-25 1 0 0 0
        2 2018-11-10 0 0 0 0
</code>```

I am trying to tie all active nid's to the associated person_id This will then be joined to another dataframe based on the latest date less than a dated activity column. And finally this will be part of the input into a predictive model.

Doing something like pd.get_dummies(df["nid"]) get's this output:

```<code>   1  2  3  4
0  1  0  0  0
1  0  1  0  0
2  0  0  1  0
3  0  0  0  1
4  1  0  0  0
</code>```

So this needs to be moved to a different index representing effective date, grouped by person_id, and then aggregated to match the goal output.

Special bonus to anyone who can come up with an approach that would properly leverage Dask. This is what we are using for other parts of the pipeline due to the scalability. This may be a pipe-dream but I thought I would send it out to see what comes back.

答:
Similar to @WenYoBen's approach, a little different in broadcasting and return:

```<code>def onehot(group):
    pid, g = group

    ends = g.end.fillna(g.end.max())
    begs = g.beg

    days = pd.concat((ends,begs)).sort_values().unique()

    ret = pd.DataFrame((days[:,None] < ends.values) & (days[:,None]>= begs.values),
                    columns= g.nid)
    ret['persion_id'] = pid
    return ret

new_df = pd.concat([onehot(group) for group in df.groupby('person_id')], sort=False)
new_df.fillna(0).astype(int)
</code>```

Output:

```<code>    1   2   3   4   persion_id
0   1   0   0   0   1
1   1   1   0   0   1
2   1   1   1   0   1
3   0   1   1   0   1
4   0   1   1   1   1
5   0   0   1   1   1
6   0   0   0   0   1
0   1   0   0   0   2
1   0   0   0   0   2
</code>```

Body:
Starting with this sample data...

import pandas as pd

start_data = {"person_id": [1, 1, 1, 1, 2], "nid": [1, 2, 3, 4, 1],
              "beg": ["Jan 1 2018", "Jan 5 2018", "Jan 10 2018", "Feb 5 2018", "Jan 25 2018"],
              "end": ["Feb 1 2018", "Mar 4 2018", "", "Oct 18 2018", "Nov 10 2018"]}
df = pd.DataFrame(start_data)
df["beg"] = pd.to_datetime(df["beg"])
df["end"] = pd.to_datetime(df["end"])

Starting point:

   person_id  nid        beg        end
0          1    1 2018-01-01 2018-02-01
1          1    2 2018-01-05 2018-03-04
2          1    3 2018-01-10        NaT
3          1    4 2018-02-05 2018-10-18
4          2    1 2018-01-25 2018-11-10

Goal output:

person_id date       1 2 3 4
        1 2018-01-01 1 0 0 0
        1 2018-01-05 1 1 0 0
        1 2018-01-10 1 1 1 0
        1 2018-02-01 0 1 1 0
        1 2018-02-05 0 1 1 1
        1 2018-03-04 0 0 1 1
        1 2018-10-18 0 0 1 0
        2 2018-01-25 1 0 0 0
        2 2018-11-10 0 0 0 0

I am trying to tie all active nid's to the associated person_id This will then be joined to another dataframe based on the latest date less than a dated activity column. And finally this will be part of the input into a predictive model.

Doing something like pd.get_dummies(df["nid"]) get's this output:

   1  2  3  4
0  1  0  0  0
1  0  1  0  0
2  0  0  1  0
3  0  0  0  1
4  1  0  0  0

So this needs to be moved to a different index representing effective date, grouped by person_id, and then aggregated to match the goal output.

Special bonus to anyone who can come up with an approach that would properly leverage Dask. This is what we are using for other parts of the pipeline due to the scalability. This may be a pipe-dream but I thought I would send it out to see what comes back.

Body:
Similar to @WenYoBen's approach, a little different in broadcasting and return:

def onehot(group):
    pid, g = group

    ends = g.end.fillna(g.end.max())
    begs = g.beg

    days = pd.concat((ends,begs)).sort_values().unique()

    ret = pd.DataFrame((days[:,None] < ends.values) & (days[:,None]>= begs.values),
                    columns= g.nid)
    ret['persion_id'] = pid
    return ret

new_df = pd.concat([onehot(group) for group in df.groupby('person_id')], sort=False)
new_df.fillna(0).astype(int)

Output:

    1   2   3   4   persion_id
0   1   0   0   0   1
1   1   1   0   0   1
2   1   1   1   0   1
3   0   1   1   0   1
4   0   1   1   1   1
5   0   0   1   1   1
6   0   0   0   0   1
0   1   0   0   0   2
1   0   0   0   0   2


问:
Apache Rewrite with Multiple Parameters
I need to rewrite the following types of URLs:

http://www.gocruise.co.uk/fusion/detailline3.pl?lineid=13&sid=6924&ccid=Fred+Olsen

into:

http://www.gocruise.co.uk/fred-olsen

using an Apache RewriteRule. I have been trying to get to grips with these rewrites as quick as i can but have run out of time. Any help will be much appreciated.

(the main bit im struggling with is how to manage the multiple parameters)

答:
You probably want it the other way round: A request of /fred-olsen comes in, and you want to redirect the user to the longer URL. This is pretty simple:

```<code># in the Server Configuration or VHost Configuration:
RewriteRule ^/fred-olsen$ /fusion/detailline3.pl?lineid=13&sid=6924&ccid=Fred+Olsen [R=301,L]
</code>```

or:

```<code># in the .htaccess file of the DocumentRoot
RewriteRule ^fred-olsen$ fusion/detailline3.pl?lineid=13&sid=6924&ccid=Fred+Olsen [R=301,L]
</code>```

ContentLicense: CC BY-SA 3.0

Title: Apache Rewrite with Multiple Parameters

Body:
You probably want it the other way round: A request of /fred-olsen comes in, and you want to redirect the user to the longer URL. This is pretty simple:

# in the Server Configuration or VHost Configuration:
RewriteRule ^/fred-olsen$ /fusion/detailline3.pl?lineid=13&sid=6924&ccid=Fred+Olsen [R=301,L]

or:

# in the .htaccess file of the DocumentRoot
RewriteRule ^fred-olsen$ fusion/detailline3.pl?lineid=13&sid=6924&ccid=Fred+Olsen [R=301,L]


问:
Using library functions in chef resources
I have created a chef cookbook "lcd_web_source" with the following directory structure.

The content of my helpers.rb is shown below

```<code>module Lcd_web_source
  module Helpers

def platform_package_httpd
  case node['platform']
  when 'centos' then 'httpd'
  when 'ubuntu' then 'apache2'
  end
end
def platform_service_httpd
  case node['platform']
  when 'centos' then 'httpd'
  when 'ubuntu' then 'apache2'
  end
end

end
end

Chef::Recipe.include(Lcd_web_source::Helpers)
Chef::Resource.include(Lcd_web_source::Helpers)
</code>```

the content of the resource file "hello.rb" is as follow

```<code>include Lcd_web_source::Helpers
resource_name :hello_httpd
property :greeting, :kind_of => String

default_action :create
action :create do

  package platform_package_httpd

  service platform_service_httpd do
    action [:enable, :start]
  end

  template '/var/www/html/index.html' do
    source 'index.html.erb'
    owner 'apache'
    group 'apache'
    variables(
      greeting_scope: node['greeting_scope'],
      greeting: new_resource.greeting,
      fqdn: node['fqdn']
    )
  end
end
</code>```

and my recipe default.rb looks as

```<code>package platform_package_httpd
hello_httpd 'greet world' do
    greeting "Hello"
    action :create
end
</code>```

When this recipe runs, the first statement

```<code>package platform_package_httpd
</code>```

runs fine, which means the recipe is able to find library functions.

But the second statement fails with the following error

```<code>NameError: undefined local variable or method `platform_package_httpd' for #<#<Class:0x0000000004326f00>:0x0000000004244268>
</code>```

In short custom, the resource is not able to locate the functions defined in the library.
Help me understand as to why this is happening.

答:
This example looks to be from a Linux Academy course. I had to use the action_class within the Custom Resource DSL. Using the action_class block I was able to use the method i created within the libraries/helper.rb

Change your hello.rb to include the action_class block

```<code>action_class do
  include Lcd_web_source::Helpers
end

resource_name :hello_httpd
property :greeting, :kind_of => String

default_action :create
action :create do

  package platform_package_httpd

</code>```

Reference:
https://docs.chef.io/custom_resources.html#custom-resource-dsl

Body:
I have created a chef cookbook "lcd_web_source" with the following directory structure.

The content of my helpers.rb is shown below

module Lcd_web_source
  module Helpers

def platform_package_httpd
  case node['platform']
  when 'centos' then 'httpd'
  when 'ubuntu' then 'apache2'
  end
end
def platform_service_httpd
  case node['platform']
  when 'centos' then 'httpd'
  when 'ubuntu' then 'apache2'
  end
end

end
end

Chef::Recipe.include(Lcd_web_source::Helpers)
Chef::Resource.include(Lcd_web_source::Helpers)

the content of the resource file "hello.rb" is as follow

include Lcd_web_source::Helpers
resource_name :hello_httpd
property :greeting, :kind_of => String

default_action :create
action :create do

  package platform_package_httpd

  service platform_service_httpd do
    action [:enable, :start]
  end

  template '/var/www/html/index.html' do
    source 'index.html.erb'
    owner 'apache'
    group 'apache'
    variables(
      greeting_scope: node['greeting_scope'],
      greeting: new_resource.greeting,
      fqdn: node['fqdn']
    )
  end
end

and my recipe default.rb looks as

package platform_package_httpd
hello_httpd 'greet world' do
    greeting "Hello"
    action :create
end

When this recipe runs, the first statement

package platform_package_httpd

runs fine, which means the recipe is able to find library functions.

But the second statement fails with the following error

NameError: undefined local variable or method `platform_package_httpd' for #<#<Class:0x0000000004326f00>:0x0000000004244268>

In short custom, the resource is not able to locate the functions defined in the library.
Help me understand as to why this is happening.

Body:
This example looks to be from a Linux Academy course. I had to use the action_class within the Custom Resource DSL. Using the action_class block I was able to use the method i created within the libraries/helper.rb

Change your hello.rb to include the action_class block

action_class do
  include Lcd_web_source::Helpers
end

resource_name :hello_httpd
property :greeting, :kind_of => String

default_action :create
action :create do

  package platform_package_httpd

Reference:
https://docs.chef.io/custom_resources.html#custom-resource-dsl


问:
Error reading file extracted from tesseract using fopen PHP
I'm using fopen in PHP to open a file extracted from tesseract OCR. The returned text contains <<<<<<, fopen reads till it finds the first < character then stops.

File returned from OCR:

```<code>P<dsdasdasd<<dasd<adsda<dsada<<<<<<<<<<ec<
dasdasdsdasdasdasdasd<<<<<<<<<<<<<<06

£ y
</code>```

The echo from fopen:

```<code>P
</code>```

If I view source, I found rest text in red color.

Code I used:

```<code><?php
file_put_contents("tmpFile.jpg",file_get_contents("1.jpg"));
$cmd = "tesseract tmpFile.jpg ee ";
exec($cmd);
$myfile = fopen("ee.txt", "r") or die("Unable to open file!");
$data= fread($myfile,100000000);
fclose($myfile);
echo $data;
?>
</code>```

I paste the text in question and it also hidden.

Screenshot while I typing question and the text hidden in question:

Screen-shot from output and viewsource:

答:
As far as I can see, the issue has nothing to do with tesseract or your input text file.

fopen reads till it finds the first < character then stops

I don't think that's true. Why would you see the rest of the source in "view source", then? fopen reads the whole file but the issue is with displaying that information in your browser.

You want to display characters which are reserved for HTML tags - in this case a < ("less than" symbol). That's why you get red text in "view source" since the browser doesn't know how to interpret the HTML code.

As a first workaround, just put a <textarea> tag around your <?php to view the data:

```<code><textarea><?php
/* ...
your regular code here
... */
?></textarea>
</code>```

The next step should be to encode those special characters before you give them to echo. Have a look at htmlspecialchars
or htmlentities.

You might also find useful information on the topic at:

Print less-than and greater-than symbols in PHP

How to display HTML tags as plain text

Body:
I'm using fopen in PHP to open a file extracted from tesseract OCR. The returned text contains <<<<<<, fopen reads till it finds the first < character then stops.

File returned from OCR:

P<dsdasdasd<<dasd<adsda<dsada<<<<<<<<<<ec<
dasdasdsdasdasdasdasd<<<<<<<<<<<<<<06

£ y

The echo from fopen:

P

If I view source, I found rest text in red color.

Code I used:

<?php
file_put_contents("tmpFile.jpg",file_get_contents("1.jpg"));
$cmd = "tesseract tmpFile.jpg ee ";
exec($cmd);
$myfile = fopen("ee.txt", "r") or die("Unable to open file!");
$data= fread($myfile,100000000);
fclose($myfile);
echo $data;
?>

I paste the text in question and it also hidden.

Screenshot while I typing question and the text hidden in question:

Screen-shot from output and viewsource:

Body:
As far as I can see, the issue has nothing to do with tesseract or your input text file.

fopen reads till it finds the first < character then stops

I don't think that's true. Why would you see the rest of the source in "view source", then? fopen reads the whole file but the issue is with displaying that information in your browser.

You want to display characters which are reserved for HTML tags - in this case a < ("less than" symbol). That's why you get red text in "view source" since the browser doesn't know how to interpret the HTML code.

As a first workaround, just put a <textarea> tag around your <?php to view the data:

<textarea><?php
/* ...
your regular code here
... */
?></textarea>

The next step should be to encode those special characters before you give them to echo. Have a look at htmlspecialchars
or htmlentities.

You might also find useful information on the topic at:

Print less-than and greater-than symbols in PHP

How to display HTML tags as plain text


问:
shred multiple xml elements into multiple columns
I am trying to shred this xml column into multiple xml columns but it seems to be in the wrong format.

Here is my data from using xml path()

```<code><claim id="1111111">
  <InsHistDB>2</InsHistDB>
  <ClaimHistID>111111</ClaimHistID>
  <PatID>00000001</PatID>
  <ProcedureData>
    <row proc_logid="0000009" proc_logdb="1000000" createdate="2000-09-21T00:00:00" pldate="2000-09-21T00:00:00" adacode="D0120" />
    <row proc_logid="1211557" proc_logdb="1000010" createdate="2015-09-21T00:00:00" pldate="2015-09-21T00:00:00" adacode="D0220" />
    <row proc_logid="1211558" proc_logdb="1000010" createdate="2015-09-21T00:00:00" pldate="2015-09-21T00:00:00" adacode="D0230" />
    <row proc_logid="1211556" proc_logdb="1000010" createdate="2015-09-21T00:00:00" pldate="2015-09-21T00:00:00" adacode="D0272" />
  </ProcedureData>
</claim>
</code>```

The select statement is currently this

```<code>SELECT TOP (1000)  [ClaimID] as '@id'
      ,[InsHistDB]
      ,[ClaimHistID]
      ,[PatID]
   -- ,[ProcedureData].value('declare namespace ns= "ProcedureData"; (/ns:ProcedureData/ns:row[1])','nvarchar(50)') as pp
     ,[ProcedureData]
     --,[ProcedureData].query('proc_logid').value('.','varchar(50)') as 'proc_1'
  FROM [Mine].[dbo].[claim]
  where claimid=1111111

 FOR XML PATH('claim')
</code>```

What I am wanting to do is divide out the {Proc_Log_id} into different columns so the row should read.

```<code>Claim ID         INSHISTDB       CLaimHistID       PATID      Proc_Id1      Proc_ID2      ProcID3   procID4
 11111              2               1111111      000000001     0000009    1211557        1211558      1211556
</code>```

Is this possible or am i just spinning my wheels? Also this will be for multiple patid's so the query without the where clause is expected. Also I believe there can be up to 10 proc_logids per xml data point. I am fine with null values, as i plan to pivot and normalize this data.

Thanks for reading.

答:
The syntax to select the 3rd node is column.value('(/foo/bar)[3]','varchar(25)').

You are right to consider other options. The 'query' or 'nodes' functions in particular are better suited as they could return the values as a second result set or a new XML document.

Body:
I am trying to shred this xml column into multiple xml columns but it seems to be in the wrong format.

Here is my data from using xml path()

<claim id="1111111">
  <InsHistDB>2</InsHistDB>
  <ClaimHistID>111111</ClaimHistID>
  <PatID>00000001</PatID>
  <ProcedureData>
    <row proc_logid="0000009" proc_logdb="1000000" createdate="2000-09-21T00:00:00" pldate="2000-09-21T00:00:00" adacode="D0120" />
    <row proc_logid="1211557" proc_logdb="1000010" createdate="2015-09-21T00:00:00" pldate="2015-09-21T00:00:00" adacode="D0220" />
    <row proc_logid="1211558" proc_logdb="1000010" createdate="2015-09-21T00:00:00" pldate="2015-09-21T00:00:00" adacode="D0230" />
    <row proc_logid="1211556" proc_logdb="1000010" createdate="2015-09-21T00:00:00" pldate="2015-09-21T00:00:00" adacode="D0272" />
  </ProcedureData>
</claim>

The select statement is currently this

SELECT TOP (1000)  [ClaimID] as '@id'
      ,[InsHistDB]
      ,[ClaimHistID]
      ,[PatID]
   -- ,[ProcedureData].value('declare namespace ns= "ProcedureData"; (/ns:ProcedureData/ns:row[1])','nvarchar(50)') as pp
     ,[ProcedureData]
     --,[ProcedureData].query('proc_logid').value('.','varchar(50)') as 'proc_1'
  FROM [Mine].[dbo].[claim]
  where claimid=1111111

 FOR XML PATH('claim')

What I am wanting to do is divide out the {Proc_Log_id} into different columns so the row should read.

Claim ID         INSHISTDB       CLaimHistID       PATID      Proc_Id1      Proc_ID2      ProcID3   procID4
 11111              2               1111111      000000001     0000009    1211557        1211558      1211556

Is this possible or am i just spinning my wheels? Also this will be for multiple patid's so the query without the where clause is expected. Also I believe there can be up to 10 proc_logids per xml data point. I am fine with null values, as i plan to pivot and normalize this data.

Thanks for reading.


问:
Python 'utf-8' codec stop message with IIS log
With the following python code

```<code>import csv
log_file = open('190415190514.txt', 'r')
all_data = csv.reader(log_file, delimiter=' ')
data = []
for row in all_data:
    data.append(row)
</code>```

to read a big file containing

```<code>2019-04-15 00:00:46 192.168.168.29 GET / - 443 - 192.168.168.80 Mozilla/5.0+(compatible;+PRTG+Network+Monitor+(www.paessler.com);+Windows) - 200 0 0 0
</code>```

I get this error

```<code> File "main.py", line 5, in <module>
   for row in datareader:
 File "/usr/lib/python3.6/codecs.py", line 321, in decode
   (result, consumed) = self._buffer_decode(data, self.errors, final)
 UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 1284: invalid start byte
</code>```

I think there is no problem with the data file since it is a IIS log file. If there is any encoding issue, how can I locate that line? I am also not sure if my problem is the same this one.

答:
Since you opened the file as 'r' instead of 'rb', python is trying to decode it as utf-8.   The contents of the file are apparently not valid utf-8, so you're getting an erorr.   You can find the line number of the offending line like this:

with open('190415190514.txt', 'rb') as f:
    for i, line in enumerate(f):
        try:
            line.decode('utf-8')
        except UnicodeDecodeError as e:
            print (f'{e} at line {i+1}')
```

You probably should be passing errors or encoding to open.  see: https://docs.python.org/3/library/functions.html#open

Body:
With the following python code

import csv
log_file = open('190415190514.txt', 'r')
all_data = csv.reader(log_file, delimiter=' ')
data = []
for row in all_data:
    data.append(row)

to read a big file containing

2019-04-15 00:00:46 192.168.168.29 GET / - 443 - 192.168.168.80 Mozilla/5.0+(compatible;+PRTG+Network+Monitor+(www.paessler.com);+Windows) - 200 0 0 0

I get this error

 File "main.py", line 5, in <module>
   for row in datareader:
 File "/usr/lib/python3.6/codecs.py", line 321, in decode
   (result, consumed) = self._buffer_decode(data, self.errors, final)
 UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 1284: invalid start byte

I think there is no problem with the data file since it is a IIS log file. If there is any encoding issue, how can I locate that line? I am also not sure if my problem is the same this one.

Body:
Since you opened the file as 'r' instead of 'rb', python is trying to decode it as utf-8.   The contents of the file are apparently not valid utf-8, so you're getting an erorr.   You can find the line number of the offending line like this:

with open('190415190514.txt', 'rb') as f:
    for i, line in enumerate(f):
        try:
            line.decode('utf-8')
        except UnicodeDecodeError as e:
            print (f'{e} at line {i+1}')

You probably should be passing errors or encoding to open.  see: https://docs.python.org/3/library/functions.html#open


问:
How to get an MD5 checksum in PowerShell
I would like to calculate an MD5 checksum of some content. How do I do this in PowerShell?</p>

答:
As stated in the accepted answer, Get-FileHash is easy to use with files, but it is also possible to use it with strings:

```<code>$s = "asdf"
Get-FileHash -InputStream ([System.IO.MemoryStream]::New([System.Text.Encoding]::ASCII.GetBytes($s)))
</code>```

Body:
As stated in the accepted answer, Get-FileHash is easy to use with files, but it is also possible to use it with strings:

$s = "asdf"
Get-FileHash -InputStream ([System.IO.MemoryStream]::New([System.Text.Encoding]::ASCII.GetBytes($s)))


问:
Check for differences between RDF models with non-deterministic (UUID-based) URIs?
A college and I are individually instantiating electronic health records into triples.  We'd like to compare our sets of 10k to 100k triples to see if they have the same shapes.

As a policy, I create URIs based on UUIDs, so nothing semantic is embedded in them.  I'd like to stick with this policy, as my college and I are really trying to holistically compare existing workflows.

I know how to compare two RDF files in TopBraid Composer, but I don't think it will be useful if we have the same data patterns but different URIs.  I store my triples in Ontotext GraphDB but am glad to use any other tool.

For example, the triples about person ...fe54977c174a and person ...4bcdc1c8abf9 should be considered equivalent, but ...fe54977c174a and ...ae00dc86b3bb should not.  Is this feasible?

I would prefer not to spot-check with hand-crafted SPARQL ASK statements.

```<code>@prefix ns0: <http://example.com/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

<http://example.com/4f79ea05-2358-4f43-a335-fe54977c174a>
  a <http://example.com/Person> ;
  ns0:gender ns0:Male ;
  ns0:participatesIn ns0:5d2dfc7b-994c-4933-b787-f7971dae397c .

ns0:5d2dfc7b-994c-4933-b787-f7971dae397c
  a ns0:HealthCareEncounter ;
  ns0:startDate "2019-05-01"^^xsd:date ;
  ns0:hasOutput ns0:a129ca96-c6d2-4a07-a4eb-4cf9ce23a314 .

ns0:a129ca96-c6d2-4a07-a4eb-4cf9ce23a314
  a ns0:Diagnosis ;
  ns0:mentions ns0:Headache .
</code>```

has the same shape as this (despite the different URIs):

```<code>@prefix ns0: <http://example.com/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

<http://example.com/a740d254-084c-4621-b06d-4bcdc1c8abf9>
  a <http://example.com/Person> ;
  ns0:gender ns0:Male ;
  ns0:participatesIn ns0:060d2091-b4f7-406d-ab0d-75b39b400823 .

ns0:060d2091-b4f7-406d-ab0d-75b39b400823
  a ns0:HealthCareEncounter ;
  ns0:startDate "2019-05-01"^^xsd:date ;
  ns0:hasOutput ns0:bc549711-ed9d-4db6-8cf9-d43022903ef7 .

ns0:bc549711-ed9d-4db6-8cf9-d43022903ef7
  a ns0:Diagnosis ;
  ns0:mentions ns0:Headache .

</code>```

but this is structurally different (due to the different gender and diagnosis mention):

```<code>@prefix ns0: <http://example.com/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

<http://example.com/aa3a977a-999a-4c5c-9524-ae00dc86b3bb>
  a <http://example.com/Person> ;
  ns0:gender ns0:Female ;
  ns0:participatesIn ns0:b31a62a5-337a-454d-a637-85aefef26684 .

ns0:b31a62a5-337a-454d-a637-85aefef26684
  a ns0:HealthCareEncounter ;
  ns0:startDate "2019-05-01"^^xsd:date ;
  ns0:hasOutput ns0:6566d543-773e-4649-b589-66eb3d0f3165 .

ns0:6566d543-773e-4649-b589-66eb3d0f3165
  a ns0:Diagnosis ;
  ns0:mentions ns0:Nausea .

</code>```

答:
Eclipse Rdf4j (bundled with GraphDB) contains a  graph isomorphism utility: Models.isomorphic. By default it only does blank node to blank node mappings. So you have two options:

do a replace of each IRI in your graphs with a (dictionary-mapped) blank node. This should be fairly easy to do with a HashMap and a bit of looping or streaming-magic.

have a look at the code for the Models utility and adapt the bit where it does blank node mapping to do IRI mapping instead.

Body:
A college and I are individually instantiating electronic health records into triples.  We'd like to compare our sets of 10k to 100k triples to see if they have the same shapes.

As a policy, I create URIs based on UUIDs, so nothing semantic is embedded in them.  I'd like to stick with this policy, as my college and I are really trying to holistically compare existing workflows.

I know how to compare two RDF files in TopBraid Composer, but I don't think it will be useful if we have the same data patterns but different URIs.  I store my triples in Ontotext GraphDB but am glad to use any other tool.

For example, the triples about person ...fe54977c174a and person ...4bcdc1c8abf9 should be considered equivalent, but ...fe54977c174a and ...ae00dc86b3bb should not.  Is this feasible?

I would prefer not to spot-check with hand-crafted SPARQL ASK statements.

@prefix ns0: <http://example.com/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

<http://example.com/4f79ea05-2358-4f43-a335-fe54977c174a>
  a <http://example.com/Person> ;
  ns0:gender ns0:Male ;
  ns0:participatesIn ns0:5d2dfc7b-994c-4933-b787-f7971dae397c .

ns0:5d2dfc7b-994c-4933-b787-f7971dae397c
  a ns0:HealthCareEncounter ;
  ns0:startDate "2019-05-01"^^xsd:date ;
  ns0:hasOutput ns0:a129ca96-c6d2-4a07-a4eb-4cf9ce23a314 .

ns0:a129ca96-c6d2-4a07-a4eb-4cf9ce23a314
  a ns0:Diagnosis ;
  ns0:mentions ns0:Headache .

has the same shape as this (despite the different URIs):

@prefix ns0: <http://example.com/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

<http://example.com/a740d254-084c-4621-b06d-4bcdc1c8abf9>
  a <http://example.com/Person> ;
  ns0:gender ns0:Male ;
  ns0:participatesIn ns0:060d2091-b4f7-406d-ab0d-75b39b400823 .

ns0:060d2091-b4f7-406d-ab0d-75b39b400823
  a ns0:HealthCareEncounter ;
  ns0:startDate "2019-05-01"^^xsd:date ;
  ns0:hasOutput ns0:bc549711-ed9d-4db6-8cf9-d43022903ef7 .

ns0:bc549711-ed9d-4db6-8cf9-d43022903ef7
  a ns0:Diagnosis ;
  ns0:mentions ns0:Headache .

but this is structurally different (due to the different gender and diagnosis mention):

@prefix ns0: <http://example.com/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .

<http://example.com/aa3a977a-999a-4c5c-9524-ae00dc86b3bb>
  a <http://example.com/Person> ;
  ns0:gender ns0:Female ;
  ns0:participatesIn ns0:b31a62a5-337a-454d-a637-85aefef26684 .

ns0:b31a62a5-337a-454d-a637-85aefef26684
  a ns0:HealthCareEncounter ;
  ns0:startDate "2019-05-01"^^xsd:date ;
  ns0:hasOutput ns0:6566d543-773e-4649-b589-66eb3d0f3165 .

ns0:6566d543-773e-4649-b589-66eb3d0f3165
  a ns0:Diagnosis ;
  ns0:mentions ns0:Nausea .


问:
Why is AWS denying permission when IAM is set to allow all?
I'm trying to run a script that creates tables in DynamoDB. The first table is created just fine but the 2nd table runs into a permission problem, which seems to be IAM related.

This is a python security tool that requires an initial setup and part of that is creating two DynamoDB tables. I'm able to create the first table just fine but run into issues with the 2nd table.

The user role has wide open AWS permissions so I don't see how this is an issue.

Python3.7.3 if the version is necessary.

```<code>Traceback (most recent call last):
  File "argos_config_setup.py", line 28, in check_account_table
    response = client.describe_table(TableName=argos_account_table)
  File "/Users/generic_user/.virtualenvs/myvenv/lib/python3.7/site-packages/botocore/client.py", line 357, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/Users/generic_user/.virtualenvs/myvenv/lib/python3.7/site-packages/botocore/client.py", line 661, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.errorfactory.ResourceNotFoundException: An error occurred (ResourceNotFoundException) when calling the DescribeTable operation: Requested resource not found: Table: argos_accounts not found

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "argos_config_setup.py", line 240, in <module>
    check_account_table()
  File "argos_config_setup.py", line 34, in check_account_table
    create_account_table(argos_account_table)
  File "argos_config_setup.py", line 103, in create_account_table
    for accounts_itr in account_iterator:
  File "/Users/generic_user/.virtualenvs/myvenv/lib/python3.7/site-packages/botocore/paginate.py", line 255, in __iter__
    response = self._make_request(current_kwargs)
  File "/Users/generic_user/.virtualenvs/myvenv/lib/python3.7/site-packages/botocore/paginate.py", line 332, in _make_request
    return self._method(**current_kwargs)
  File "/Users/generic_user/.virtualenvs/myvenv/lib/python3.7/site-packages/botocore/client.py", line 357, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/Users/generic_user/.virtualenvs/myvenv/lib/python3.7/site-packages/botocore/client.py", line 661, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.errorfactory.AccessDeniedException: An error occurred (AccessDeniedException) when calling the ListAccounts operation: You don't have permissions to access this resource.
</code>```

AWS JSON POLICY

```<code>    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "*",
            "Resource": "*"
        }
    ]
}
</code>```

A 2nd dynamoDB table is supposed to be created.

Below is the create_account_table function

```<code>    org_client = boto3.client('organizations')
    paginator = org_client.get_paginator('list_accounts')
    account_iterator = paginator.paginate()
    accounts = []
    for accounts_itr in account_iterator:
        for account in accounts_itr['Accounts']:
            accounts.append({'id': account['Id'], 'name': account['Name'], 'email': account['Email'],
                             'environment': ''})
    dynamodb_client = boto3.client('dynamodb')
    dynamodb_client.create_table(
        AttributeDefinitions=[
            {
                "AttributeName": "id",
                "AttributeType": "S"
            }
        ],
        TableName=argos_account_table,
        KeySchema=[
            {
                "AttributeName": "id",
                "KeyType": "HASH"
            }
        ],
        BillingMode='PAY_PER_REQUEST'
    )

    dynamodb_resource = boto3.resource('dynamodb')
    table = dynamodb_resource.Table(argos_account_table)
    with table.batch_writer() as batch:
        for account in accounts:
            batch.put_item(
                Item={
                    'id': account['id'],
                    'name': account['name'],
                    'email': account['email'],
                    'environment': account['environment'],
                }
)
</code>```

答:
Without seeing how you are creating the tables I can only tell you two things:

The first error you encountered is because you are trying describe a table that can't be found (404 error)

While trying to handle the unfound table error it appears your code tried a ListAccounts call which depends on the AWS Organization settings you have. It appears your user doesn't have ListAccounts permission either.

Could you post a the snippet of how you are trying to create the tables, because here we can only see you make a describeTable call instead of a createTable.

Body:
I'm trying to run a script that creates tables in DynamoDB. The first table is created just fine but the 2nd table runs into a permission problem, which seems to be IAM related.

This is a python security tool that requires an initial setup and part of that is creating two DynamoDB tables. I'm able to create the first table just fine but run into issues with the 2nd table.

The user role has wide open AWS permissions so I don't see how this is an issue.

Python3.7.3 if the version is necessary.

Traceback (most recent call last):
  File "argos_config_setup.py", line 28, in check_account_table
    response = client.describe_table(TableName=argos_account_table)
  File "/Users/generic_user/.virtualenvs/myvenv/lib/python3.7/site-packages/botocore/client.py", line 357, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/Users/generic_user/.virtualenvs/myvenv/lib/python3.7/site-packages/botocore/client.py", line 661, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.errorfactory.ResourceNotFoundException: An error occurred (ResourceNotFoundException) when calling the DescribeTable operation: Requested resource not found: Table: argos_accounts not found

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "argos_config_setup.py", line 240, in <module>
    check_account_table()
  File "argos_config_setup.py", line 34, in check_account_table
    create_account_table(argos_account_table)
  File "argos_config_setup.py", line 103, in create_account_table
    for accounts_itr in account_iterator:
  File "/Users/generic_user/.virtualenvs/myvenv/lib/python3.7/site-packages/botocore/paginate.py", line 255, in __iter__
    response = self._make_request(current_kwargs)
  File "/Users/generic_user/.virtualenvs/myvenv/lib/python3.7/site-packages/botocore/paginate.py", line 332, in _make_request
    return self._method(**current_kwargs)
  File "/Users/generic_user/.virtualenvs/myvenv/lib/python3.7/site-packages/botocore/client.py", line 357, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/Users/generic_user/.virtualenvs/myvenv/lib/python3.7/site-packages/botocore/client.py", line 661, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.errorfactory.AccessDeniedException: An error occurred (AccessDeniedException) when calling the ListAccounts operation: You don't have permissions to access this resource.

AWS JSON POLICY

    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "*",
            "Resource": "*"
        }
    ]
}

A 2nd dynamoDB table is supposed to be created.

Below is the create_account_table function

    org_client = boto3.client('organizations')
    paginator = org_client.get_paginator('list_accounts')
    account_iterator = paginator.paginate()
    accounts = []
    for accounts_itr in account_iterator:
        for account in accounts_itr['Accounts']:
            accounts.append({'id': account['Id'], 'name': account['Name'], 'email': account['Email'],
                             'environment': ''})
    dynamodb_client = boto3.client('dynamodb')
    dynamodb_client.create_table(
        AttributeDefinitions=[
            {
                "AttributeName": "id",
                "AttributeType": "S"
            }
        ],
        TableName=argos_account_table,
        KeySchema=[
            {
                "AttributeName": "id",
                "KeyType": "HASH"
            }
        ],
        BillingMode='PAY_PER_REQUEST'
    )

    dynamodb_resource = boto3.resource('dynamodb')
    table = dynamodb_resource.Table(argos_account_table)
    with table.batch_writer() as batch:
        for account in accounts:
            batch.put_item(
                Item={
                    'id': account['id'],
                    'name': account['name'],
                    'email': account['email'],
                    'environment': account['environment'],
                }
)


问:
Counting particular words
I'm working on a function that can count the number of words (including contractions like couldn't) in a list having exactly five letters.

I searched the internet for a similar issue but came up empty-handed.

```<code>def word_count(wlist):
    """ This function counts the number of words (including contractions like couldn't) in a list w/ exactly 5
        letters."""
    w = 0
    for word in x:
        w += 1 if len(word) == 5 else 0
    return w

x = ["adsfe", "as", "jkiejjl", "jsengd'e", "jjies"]
print(word_count(x))
</code>```

I'd like this function to count the number of words (including contractions like couldn't) in a list w/ exactly five letters. Any feedback is appreciated.

答:
```<code>>>> def word5(wlist):
...     return len([word for word in wlist if len(word)==5])
...
>>> word5(["adsfe", "as", "jkiejjl", "jseke", "jjies"])
3
>>>
</code>```

Title: Counting particular words

Body:
I'm working on a function that can count the number of words (including contractions like couldn't) in a list having exactly five letters.

I searched the internet for a similar issue but came up empty-handed.

def word_count(wlist):
    """ This function counts the number of words (including contractions like couldn't) in a list w/ exactly 5
        letters."""
    w = 0
    for word in x:
        w += 1 if len(word) == 5 else 0
    return w

x = ["adsfe", "as", "jkiejjl", "jsengd'e", "jjies"]
print(word_count(x))

I'd like this function to count the number of words (including contractions like couldn't) in a list w/ exactly five letters. Any feedback is appreciated.


问:
How to have a radio checked on page load
I have a donation page using Liquid Shopify. I CANNOT change name="donation[amount_option]" (I do not have access to that file) so I need code that allows this to stay.

I want to have $250 automatically checked on load

My code

document.querySelector('input[name="donation[amount_option]"][value=250]').checked = true;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="radio-inline donation-v2-amounts padbottommore">
  <span>
    <input id="donation_amount_25" type="radio" name="donation[amount_option]" class="donation_amount_option" value="25">
    <label for="donation_amount_25" class="radio">$25</label>
  </span>

  <span>
    <input id="donation_amount_250" type="radio" name="donation[amount_option]" class="donation_amount_option" value="250">
    <label for="donation_amount_250" class="radio">$250</label>
  </span>

  <span>
    <input id="donation_amount_1000" type="radio" name="donation[amount_option]" class="donation_amount_option" value="1000">
    <label for="donation_amount_1000" class="radio">$1,000</label>
  </span>
</div></code>```

答:
If you need a pure js alternative (in addition to the answer above). You can select by value:

document.querySelector('input[value="250"]').checked = true;

EDIT:

In case it isn't clear, you can use any valid selector such as the id, i.e.:

document.querySelector('#donation_amount_25').checked = true;.

Body:
I have a donation page using Liquid Shopify. I CANNOT change name="donation[amount_option]" (I do not have access to that file) so I need code that allows this to stay.

I want to have $250 automatically checked on load

My code

document.querySelector('input[name="donation[amount_option]"][value=250]').checked = true;

    <input id="donation_amount_25" type="radio" name="donation[amount_option]" class="donation_amount_option" value="25">
    $25

    <input id="donation_amount_250" type="radio" name="donation[amount_option]" class="donation_amount_option" value="250">
    $250

    <input id="donation_amount_1000" type="radio" name="donation[amount_option]" class="donation_amount_option" value="1000">
    $1,000


问:
How to set the 'web.config' file to show the full error message (.NET Core 2.1)
I hosted my ASP.NET Core app on IIS (using the publish-in- folder method). I tried to create my own web.config file to see detailed error messages on the client side. So I added file web.config:

<configuration>
    <system.web>
        <customErrors mode="Off" />
    </system.web>
    <system.webServer>
        <httpErrors errorMode="Detailed" />
    </system.webServer>
</configuration>
```

After I restarted IIS, nothing happened. Clients still got the default error:

Can I somehow get additional information about errors using file web.config?

答:
You can configure it in your Startup.cs file. By default, it shows the Developer Exception Page only in development mode:

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Home/Error");
}
```

If you replace this part just with app.UseDeveloperExceptionPage(); it will always show the detailed error message.

You can read more about it here:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-2.1

Body:
I hosted my ASP.NET Core app on IIS (using the publish-in- folder method). I tried to create my own web.config file to see detailed error messages on the client side. So I added file web.config:

<configuration>
    <system.web>
        <customErrors mode="Off" />
    </system.web>
    <system.webServer>
        <httpErrors errorMode="Detailed" />
    </system.webServer>
</configuration>

After I restarted IIS, nothing happened. Clients still got the default error:

Can I somehow get additional information about errors using file web.config?

Body:
You can configure it in your Startup.cs file. By default, it shows the Developer Exception Page only in development mode:

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Home/Error");
}

If you replace this part just with app.UseDeveloperExceptionPage(); it will always show the detailed error message.

You can read more about it here:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-2.1


问:
How can I append packets in Java?
I have a simple client/server system build with Netty and I send data using packets.
A Packet in my case has two methods to write and read from a BytBuf.
For example a packet which contains strings gets the bytes from a string and writs them to a ByteBuf, which then is sent, or it reads the bytes from the ByteBuf and creates the message.
Here's the code snippet from my packet interface:

```<code>import io.netty.buffer.ByteBuf;

public abstract class Packet {

    public abstract void read(ByteBuf byteBuf);

    public abstract void write(ByteBuf byteBuf);
}
</code>```

First, when a packet is received, I want to check if there is a packet attached, and then I want to access or read it.

The problem is the instantiation of the packet when it is received. I could append a second packet to another and store it in a local variable of the first packet, but it is gone when i use Class.newInstance() to recreate the packet on the server-side.

Also the ByteBuf from Netty is not able to read or write own classes as far as i know...

My only idea is to send multiple packages, can i avoid that?

EDIT

Definition of the packet system i use.

Because of the not well explained packet system i shortly tell what it does:

A packet in my case wrappes around the ByteBuf. In Netty the only way to send data is to write it on a ByteBuf in form of bytes. An example for a String based packet would be:

```<code>package com.sxf.protocol.chat.util.packets;

import io.netty.buffer.ByteBuf;

public class MessagePacket extends Packet {

    private String msg;

    public MessagePacket() {}

    public MessagePacket(String message) {
        this.msg = message;
    }

    @Override
    public void read(ByteBuf byteBuf) {
        byte[] msgBytes = new byte[byteBuf.readInt()];
        byteBuf.readBytes(msgBytes);

        msg = new String(msgBytes);
    }

    @Override
    public void write(ByteBuf byteBuf) {
        byte[] msgBytes = msg.getBytes();

        byteBuf.writeInt(msgBytes.length);
        byteBuf.writeBytes(msgBytes);
    }

    public String getMsg() {
        return msg;
    }
}
</code>```

When you create the Packet you have to add the message in the form of a String. In the process of encoding i call write() and pass the ByteBuf which is sent through the pipeline. The message is then formed to bytes and written to the ByteBuf.

The same happens at the decoding, just the other way around.

I hope it gets clear so.

答:
I found an easy way is to have a packet attached to another is by adding a variable and a few methods to the class like this:

```<code>package com.sxf.protocol.chat.util.packets;

import io.netty.buffer.ByteBuf;

public abstract class Packet {

    private Packet attached;

    public abstract void read(ByteBuf byteBuf);

    public abstract void write(ByteBuf byteBuf);

    public final boolean isLinked() {
        return attached != null;
    }

    public final void append(Packet packet) {
        attached = packet;
    }

    public final Packet getAttached() {
        if (isLinked()) {
            return attached;
        }

        throw new NullPointerException("unsafe access to getAttached");
    }
}
</code>```

With append() are you able to add a packet and store the passed packet.
isLinked() return wether a packet was attached or not.
getAttached() return the appended packet.

In the encoder you check if a packet is added and if so just recall the encode-method with the added packet. Like this:

```<code>    if (packet.isLinked()) {
            out.writeBoolean(true);
            encode(ctx, packet.getAttached(), out);
    } else {
            out.writeBoolean(false);
    }
</code>```

Same for the decoder and your custom ChannelInboundHandler.

Title: How can I append packets in Java?

Body:
I have a simple client/server system build with Netty and I send data using packets.
A Packet in my case has two methods to write and read from a BytBuf.
For example a packet which contains strings gets the bytes from a string and writs them to a ByteBuf, which then is sent, or it reads the bytes from the ByteBuf and creates the message.
Here's the code snippet from my packet interface:

import io.netty.buffer.ByteBuf;

public abstract class Packet {

    public abstract void read(ByteBuf byteBuf);

    public abstract void write(ByteBuf byteBuf);
}

First, when a packet is received, I want to check if there is a packet attached, and then I want to access or read it.

The problem is the instantiation of the packet when it is received. I could append a second packet to another and store it in a local variable of the first packet, but it is gone when i use Class.newInstance() to recreate the packet on the server-side.

Also the ByteBuf from Netty is not able to read or write own classes as far as i know...

My only idea is to send multiple packages, can i avoid that?

EDIT

Definition of the packet system i use.

Because of the not well explained packet system i shortly tell what it does:

A packet in my case wrappes around the ByteBuf. In Netty the only way to send data is to write it on a ByteBuf in form of bytes. An example for a String based packet would be:

package com.sxf.protocol.chat.util.packets;

import io.netty.buffer.ByteBuf;

public class MessagePacket extends Packet {

    private String msg;

    public MessagePacket() {}

    public MessagePacket(String message) {
        this.msg = message;
    }

    @Override
    public void read(ByteBuf byteBuf) {
        byte[] msgBytes = new byte[byteBuf.readInt()];
        byteBuf.readBytes(msgBytes);

        msg = new String(msgBytes);
    }

    @Override
    public void write(ByteBuf byteBuf) {
        byte[] msgBytes = msg.getBytes();

        byteBuf.writeInt(msgBytes.length);
        byteBuf.writeBytes(msgBytes);
    }

    public String getMsg() {
        return msg;
    }
}

When you create the Packet you have to add the message in the form of a String. In the process of encoding i call write() and pass the ByteBuf which is sent through the pipeline. The message is then formed to bytes and written to the ByteBuf.

The same happens at the decoding, just the other way around.

I hope it gets clear so.

Body:
I found an easy way is to have a packet attached to another is by adding a variable and a few methods to the class like this:

package com.sxf.protocol.chat.util.packets;

import io.netty.buffer.ByteBuf;

public abstract class Packet {

    private Packet attached;

    public abstract void read(ByteBuf byteBuf);

    public abstract void write(ByteBuf byteBuf);

    public final boolean isLinked() {
        return attached != null;
    }

    public final void append(Packet packet) {
        attached = packet;
    }

    public final Packet getAttached() {
        if (isLinked()) {
            return attached;
        }

        throw new NullPointerException("unsafe access to getAttached");
    }
}

With append() are you able to add a packet and store the passed packet.
isLinked() return wether a packet was attached or not.
getAttached() return the appended packet.

In the encoder you check if a packet is added and if so just recall the encode-method with the added packet. Like this:

    if (packet.isLinked()) {
            out.writeBoolean(true);
            encode(ctx, packet.getAttached(), out);
    } else {
            out.writeBoolean(false);
    }

Same for the decoder and your custom ChannelInboundHandler.


问:
In Django, how can I prevent a "Save with update_fields did not affect any rows." error?
I'm using Django and Python 3.7.  I have this code

```<code>article = get_article(id)
...
article.label = label
article.save(update_fields=["label"])
</code>```

Sometimes I get the following error on my "save" line ...

```<code>    raise DatabaseError("Save with update_fields did not affect any rows.")
django.db.utils.DatabaseError: Save with update_fields did not affect any rows.
</code>```

Evidently, in the "..." another thread may be deleting my article.  Is there another way to rewrite my "article.save(...)" statement such that if the object no longer exists I can ignore any error being thrown?

答:
This is hacky, but you could override _do_update in your model and simply return True. Django itself does something kind of hacky on line 893 of _do_update to suppress the same exception when update_fields contains column names that do not appear in the model.

The return value from _do_update triggers the exception you are seeing from this block

I tested the override below and it seemed to work. I feel somewhat dirty for overriding a private-ish method, but I think I will get over it.

def _do_update(self, base_qs, using, pk_val, values, update_fields, forced_update):
    updated = super(Article, self)._do_update(base_qs, using, pk_val, values, update_fields, forced_update)
    if not updated and Article.objects.filter(id=pk_val).count() == 0:
        return True
    return updated
```

<p>This solution could be genericized and moved to a mixin base class if you need to handle this for more than one model.</p>

<p>I used this django management command to test</p>

<pre class="lang-py prettyprint-override"><code>from django.core.management.base import BaseCommand
from foo.models import Article

class Command(BaseCommand):
    def handle(self, *args, **kwargs):
        Article.objects.update_or_create(id=1, defaults=dict(label='zulu'))

        print('Testing _do_update hack')
        article1 = Article.objects.get(id=1)
        article1.label = 'yankee'
        article2 = Article.objects.get(id=1)
        article2.delete()

        article1.save(update_fields=['label'])
        print('Done. No exception raised')
</code>```

Body:
I'm using Django and Python 3.7.  I have this code

article = get_article(id)
...
article.label = label
article.save(update_fields=["label"])

Sometimes I get the following error on my "save" line ...

    raise DatabaseError("Save with update_fields did not affect any rows.")
django.db.utils.DatabaseError: Save with update_fields did not affect any rows.

Evidently, in the "..." another thread may be deleting my article.  Is there another way to rewrite my "article.save(...)" statement such that if the object no longer exists I can ignore any error being thrown?

Body:
This is hacky, but you could override _do_update in your model and simply return True. Django itself does something kind of hacky on line 893 of _do_update to suppress the same exception when update_fields contains column names that do not appear in the model.

The return value from _do_update triggers the exception you are seeing from this block

I tested the override below and it seemed to work. I feel somewhat dirty for overriding a private-ish method, but I think I will get over it.

def _do_update(self, base_qs, using, pk_val, values, update_fields, forced_update):
    updated = super(Article, self)._do_update(base_qs, using, pk_val, values, update_fields, forced_update)
    if not updated and Article.objects.filter(id=pk_val).count() == 0:
        return True
    return updated

This solution could be genericized and moved to a mixin base class if you need to handle this for more than one model.

I used this django management command to test

from django.core.management.base import BaseCommand
from foo.models import Article

class Command(BaseCommand):
    def handle(self, *args, **kwargs):
        Article.objects.update_or_create(id=1, defaults=dict(label='zulu'))

        print('Testing _do_update hack')
        article1 = Article.objects.get(id=1)
        article1.label = 'yankee'
        article2 = Article.objects.get(id=1)
        article2.delete()

        article1.save(update_fields=['label'])
        print('Done. No exception raised')


问:
React adding an element programmatically with a HOC
Is there a way using a High Order Component to add elements programatically to a Component? I was wondering if there was a way using React.createElement to append the component's children? Here is the code that I have so far:

```<code>import React, { Component } from 'react'
import ReactDOM from 'react-dom'

function addAnElement(WrappedComponent) {

  return class Enhancer extends WrappedComponent {

    render() {

      const elementsTree = super.render()

      // Programatically add a child?
      // Update elementTree.props.children somehow?

      return elementsTree
    }
  }
}

class JustSomeText extends Component {
  render() {

    return (
      <div>
        <p>A long time ago, in a galaxy far, far away.</p>
        {/* I want to add an element here? */}
      </div>
    )
  }
}

function App() {

  const ExtendedComponent = addAnElement(JustSomeText)

  return (
    <div className="App">
      <ExtendedComponent />
    </div>
  )
}

export default App

ReactDOM.render(<App />, document.getElementById('root'))
</code>```

I'm also interested in other, more effective ways to achieving the same result.

答:
The simplest way to achieve this (although it does not use HOC) is using the children prop in React.

```<code>class JustSomeText extends Component {
  render() {
    return (
      <div>
        <p>A long time ago, in a galaxy far, far away.</p>
        {this.props.children}
      </div>
    )
  }
}

function App() {
  return (
    <div className="App">
      <JustSomeText>
         <p>more text!</p>
      </JustSomeText>
    </div>
  )
}
</code>```

This will render the following:

```<code><div className="App">
   <div>
      <p>A long time ago, in a galaxy far, far away.</p>
      <p>more text!</p>
   </div>
</div>
</code>```

Refer to this for further detail on children - https://reactjs.org/docs/composition-vs-inheritance.html

Body:
Is there a way using a High Order Component to add elements programatically to a Component? I was wondering if there was a way using React.createElement to append the component's children? Here is the code that I have so far:

import React, { Component } from 'react'
import ReactDOM from 'react-dom'

function addAnElement(WrappedComponent) {

  return class Enhancer extends WrappedComponent {

    render() {

      const elementsTree = super.render()

      // Programatically add a child?
      // Update elementTree.props.children somehow?

      return elementsTree
    }
  }
}

class JustSomeText extends Component {
  render() {

    return (

A long time ago, in a galaxy far, far away.

        {/* I want to add an element here? */}

    )
  }
}

function App() {

  const ExtendedComponent = addAnElement(JustSomeText)

  return (

      <ExtendedComponent />

  )
}

export default App

ReactDOM.render(<App />, document.getElementById('root'))

I'm also interested in other, more effective ways to achieving the same result.

Body:
The simplest way to achieve this (although it does not use HOC) is using the children prop in React.

class JustSomeText extends Component {
  render() {
    return (
      <div>
        <p>A long time ago, in a galaxy far, far away.</p>
        {this.props.children}
      </div>
    )
  }
}

function App() {
  return (
    <div className="App">
      <JustSomeText>
         <p>more text!</p>
      </JustSomeText>
    </div>
  )
}

This will render the following:

<div className="App">
   <div>
      <p>A long time ago, in a galaxy far, far away.</p>
      <p>more text!</p>
   </div>
</div>

Refer to this for further detail on children - https://reactjs.org/docs/composition-vs-inheritance.html


问:
how to access nested json using vue.js in this example?
How would I correctly access the nested json for stage.name in the example below?

You can see in the template I am trying to access stage name.

vue.js

```<code>created() {
    url="http://{{ api_endpoint }}"
    fetch(url)
        .then(response => response.json())
        .then(body => {
            for(i=0; i<body.length; i++){
                this.job_execs.push({
                    'name': JSON.stringify(body[i].job.name),
                    'build_id': JSON.stringify(body[i].build_num),
                    'env': JSON.stringify(body[i].job.env),
                })
            }
    })

template: `
      <li v-for="item in this.job_execs">
        [[ item.build_num ]]
        <li v-if="stage in item.job">
          [[ stage.name ]]
        </li>
      </li>
    </ul>
</code>```

example api

```<code>[
    {
        "build_num": 12,
        "job": {
            "name": "test-job",
            "env": "DEV",
            "tool": {
                "env": "DEV",
            },
            "product": {
                "name": "vuejs"
            },
            "platform": {
                "name": "none"
            },
            "stage": [
                {
                    "name": "stage1"
                },
                {
                    "name": "stage2"
                },
                {
                    "name": "stage3"
                },
            ]
        },
]
</code>```

I am guessing I need to create a new list in the created hook and start pushing the stage names?  But then I will have two lists?  Not sure what is the best way to do this.

答:
If you want to create an
 for each stage it would be:

  [[ stage.name ]]

```

<p>Note <code>v-for</code>, not <code>v-if</code>.</p>

<p>You can think of <code>v-for</code> as being the template equivalent of this:</p>

<pre class="lang-js prettyprint-override"><code>item.job.stage.forEach(stage => {
    // ...
})
</code>```

If you just want the first one then it's:

  [[ item.job.stage[0].name ]]

```

<p>If you did want to pursue the idea of creating a second list then you should do it using a computed property, no need to do anything in a <code>created</code> hook. In that computed property you could reduce down your data into a format that is easier to work with in your template. I'm not sure that's warranted in this case but if your needs are more complex than the example code you've posted then that might be a good way to go rather than writing a convoluted template.</p>

<p><strong>Update:</strong></p>

<p>So in full this would be:</p>

<pre class="lang-html prettyprint-override"><code><ul>
  <li v-for="item in job_execs">
    [[ item.build_num ]]
    <ul>
      <li v-for="stage in item.job.stage">
        [[ stage.name ]]
      </li>
    </ul>
  </li>
</ul>
</code>```

In your JavaScript code there's no need for all that JSON.stringify stuff.

fetch(url)
    .then(response => response.json())
    .then(body => {
        this.job_execs = body
    })
```

<p>If you want something a bit closer to your original code with <code>build_num</code> renamed to <code>build_id</code> then there are several options, such as:</p>

<pre class="lang-js prettyprint-override"><code>fetch(url)
    .then(response => response.json())
    .then(body => {
        for (let i = 0; i < body.length; i++) {
            this.job_execs.push({
                build_id: body[i].build_num,
                job: body[i].job
            })
        }
    })
</code>```

You'd then need to refer to build_num as build_id in your template.

Personally I'd be more inclined to use forEach, for/of or map instead of a straight for loop. e.g.:

fetch(url)
    .then(response => response.json())
    .then(body => {
        this.job_execs = body.map(item => {
            return {
                build_id: item.build_num,
                job: item.job
            }
        })
    })
```

All of this is only necessary if you really need to transform the format of the data though. Otherwise just stick to this.job_execs = body.

Body:
How would I correctly access the nested json for stage.name in the example below?

You can see in the template I am trying to access stage name.

vue.js

created() {
    url="http://{{ api_endpoint }}"
    fetch(url)
        .then(response => response.json())
        .then(body => {
            for(i=0; i<body.length; i++){
                this.job_execs.push({
                    'name': JSON.stringify(body[i].job.name),
                    'build_id': JSON.stringify(body[i].build_num),
                    'env': JSON.stringify(body[i].job.env),
                })
            }
    })

template: `

        [[ item.build_num ]]

          [[ stage.name ]]

example api

[
    {
        "build_num": 12,
        "job": {
            "name": "test-job",
            "env": "DEV",
            "tool": {
                "env": "DEV",
            },
            "product": {
                "name": "vuejs"
            },
            "platform": {
                "name": "none"
            },
            "stage": [
                {
                    "name": "stage1"
                },
                {
                    "name": "stage2"
                },
                {
                    "name": "stage3"
                },
            ]
        },
]

I am guessing I need to create a new list in the created hook and start pushing the stage names?  But then I will have two lists?  Not sure what is the best way to do this.

Body:
If you want to create an <li> for each stage it would be:

<li v-for="stage in item.job.stage">
  [[ stage.name ]]
</li>

Note v-for, not v-if.

You can think of v-for as being the template equivalent of this:

item.job.stage.forEach(stage => {
    // ...
})

If you just want the first one then it's:

<li>
  [[ item.job.stage[0].name ]]
</li>

If you did want to pursue the idea of creating a second list then you should do it using a computed property, no need to do anything in a created hook. In that computed property you could reduce down your data into a format that is easier to work with in your template. I'm not sure that's warranted in this case but if your needs are more complex than the example code you've posted then that might be a good way to go rather than writing a convoluted template.

Update:

So in full this would be:

<ul>
  <li v-for="item in job_execs">
    [[ item.build_num ]]
    <ul>
      <li v-for="stage in item.job.stage">
        [[ stage.name ]]
      </li>
    </ul>
  </li>
</ul>

In your JavaScript code there's no need for all that JSON.stringify stuff.

fetch(url)
    .then(response => response.json())
    .then(body => {
        this.job_execs = body
    })

If you want something a bit closer to your original code with build_num renamed to build_id then there are several options, such as:

fetch(url)
    .then(response => response.json())
    .then(body => {
        for (let i = 0; i < body.length; i++) {
            this.job_execs.push({
                build_id: body[i].build_num,
                job: body[i].job
            })
        }
    })

You'd then need to refer to build_num as build_id in your template.

Personally I'd be more inclined to use forEach, for/of or map instead of a straight for loop. e.g.:

fetch(url)
    .then(response => response.json())
    .then(body => {
        this.job_execs = body.map(item => {
            return {
                build_id: item.build_num,
                job: item.job
            }
        })
    })

All of this is only necessary if you really need to transform the format of the data though. Otherwise just stick to this.job_execs = body.


问:
Set and delete or just overwrite?
I have keys in Redis that after being read once are no longer needed. Should I delete them or just let them sit in the database until I need the key again?
I guess the question is which costs more: unneeded data sitting in the database, or a delete operation?

The set command overwrites if string data already exists at the key specified. So, in a way there is a delete and write command, I could use a get and delete command.
Or I could just call delete after getting a key. My question is should I, or just let the key sit there?

答: If you're only dealing with one key at a time, then overwriting (set) versus deleting (del) both only have a time complexity of O(1) as per the Redis documentation. I'm personally a fan of deleting an entry as soon as I'm finished with it since it is low cost and keeps the storage at a minimum. That being said, both time complexities are low, so overwriting shouldn't be an issue either :)</p>

Title: Set and delete or just overwrite?