问:
Timed input in python 3 for Mac and Windows
I need a timed input for python 3 on both Mac and Windows which, if the user runs out of time, automatically chooses one of the options. Every other answer for a question I've seen only terminates after user presses 'Enter'. I need it to terminate regardless of any 'Enter' pressed or not.

For example, in my chess program, if no input is given after 5 seconds, I need it to automatically choose "Q". Also if the input is not in ["Q", "R", "B", "N"] then I also need it to choose "Q".

The following code doesn't work. It'll ask for the input then wait forever; the timer doesn't work at all.

```<code>def countdown():
    global timer
    timer = 5
    for x in range(timer):
        timer -= 1
        time.sleep(1)

countdownThread = threading.Thread(target=countdown)
countdownThread.start()

while timer > 0:
    promotedPiece = input("Promote to Q, R, B or N? >  ").upper()
    if timer == 0:
        break

if timer == 0:
    if promotedPiece not in ["Q", "R", "B", "N"]:  # If not valid input, choose Queen
        promotedPiece = "Q"
        print("Queen auto selected")
</code>```

答:
As managing input in different environments is quite different, it is a good idea to use a module where someone else has taken care of it. pynput does what you want. Be careful as it has some caveats.

Here is the implementation of timeout_input and timeout_getchar functions that are good enough for general use. In your case, timeout_getchar should be a perfect match:

from pynput import keyboard
from time import monotonic

def timeout_input(timeout:float, prompt:str='', echo=True, None_on_timeout=False):
    """Read string with timeout.

    Reads keypresses until enter is pressed or timeout occurs. On enter,
    returns the characters read. On timeout the return value depends on the
    None_on_timeout parameter.

    Parameters
    ----------
    timeout : float
        Timeout in seconds
    prompt : str
        Prompt to print
    echo : bool
        If True, echo keys to screen as they are pressed
    None_on_timeout : bool
        If this parameter is True and timeout is reached, None is returned.
        Otherwise a (possibly empty) str of characters read so far is returned

    Returns
    -------
    str or None
        Characters read

    Observations
    ------------
    Requires pynput. All caveats of pynput apply to this function. As it
    records keypresses some differences with plain input behavior are expected.
    """
    rv = []
    print(prompt, end='')
    with keyboard.Events() as events:
        while timeout > 0:
            start_time = monotonic()
            event = events.get(timeout)
            if event is not None:
                if isinstance(event, keyboard.Events.Press):
                    try:
                        if isinstance(event.key.char, str):
                            if echo:
                                print(event.key.char, end='')
                            rv.append(event.key.char)
                    except AttributeError:
                        if event.key == keyboard.Key.enter:
                            return ''.join(rv)
            timeout -= monotonic() - start_time
    return None if None_on_timeout else ''.join(rv)

def timeout_getchar(timeout:float, prompt:str=''):
    """Read a single char with timeout.

    On timeout the return value is None

    Parameters
    ----------
    timeout : float
        Timeout in seconds
    prompt : str
        Prompt to print

    Returns
    -------
    str or None
        Character read

    Observations
    ------------
    Requires pynput. All caveats of pynput apply to this function. As it
    records keypresses some differences with plain input behavior are expected
    """
    print(prompt, end='')
    with keyboard.Events() as events:
        while timeout > 0:
            start_time = monotonic()
            event = events.get(timeout)
            if event is not None:
                if isinstance(event, keyboard.Events.Press):
                    try:
                        if isinstance(event.key.char, str):
                            return event.key.char
                    except AttributeError:
                        pass
            timeout -= monotonic() - start_time
    return None

promotedPiece = timeout_getchar(5, "Promote to Q, R, B or N? >  ")
print()
if promotedPiece is None:
    print("You took too long. I choose Q for you")
    promotedPiece = 'Q'
promotedPiece = promotedPiece.upper()
if promotedPiece not in ["Q", "R", "B", "N"]:  # If not valid input, choose Queen
    print(f"I said Q, R, B or N. You can not choose {promotedPiece}. I choose Q for you")
    promotedPiece = 'Q'
print("selection = ", promotedPiece)
```

Body:
I need a timed input for python 3 on both Mac and Windows which, if the user runs out of time, automatically chooses one of the options. Every other answer for a question I've seen only terminates after user presses 'Enter'. I need it to terminate regardless of any 'Enter' pressed or not.

For example, in my chess program, if no input is given after 5 seconds, I need it to automatically choose "Q". Also if the input is not in ["Q", "R", "B", "N"] then I also need it to choose "Q".

The following code doesn't work. It'll ask for the input then wait forever; the timer doesn't work at all.

def countdown():
    global timer
    timer = 5
    for x in range(timer):
        timer -= 1
        time.sleep(1)

countdownThread = threading.Thread(target=countdown)
countdownThread.start()

while timer > 0:
    promotedPiece = input("Promote to Q, R, B or N? >  ").upper()
    if timer == 0:
        break

if timer == 0:
    if promotedPiece not in ["Q", "R", "B", "N"]:  # If not valid input, choose Queen
        promotedPiece = "Q"
        print("Queen auto selected")


来源: stackexchange

问:
Editing the git commit message in GitHub
Is there any way of online editing the commit message in GitHub.com, after submission?

From the command line, one can do

```<code>git commit --amend -m "New commit message"
</code>```

as correctly suggested in the following question:

How to modify existing, unpushed commit messages?

Trying git pull and then git push has worked (without any other commit having interfered in the mean time).

But can it be done via the GitHub website?

答:
For Visual Studio users:

You are able to modify the commit message from the commit tab by clicking Unpushed Commit (1) and the View Outgoing/Incoming option (2).
Then, once comment is modified (3), 'Amend Message' option (4) is enabled and changes are performed automatically in the commit.

Tested on VS 2019

ContentLicense: CC BY-SA 4.0

Body:
Is there any way of online editing the commit message in GitHub.com, after submission?

From the command line, one can do

git commit --amend -m "New commit message"

as correctly suggested in the following question:

How to modify existing, unpushed commit messages?

Trying git pull and then git push has worked (without any other commit having interfered in the mean time).

But can it be done via the GitHub website?


问:
How to merge multiple H.264 streams into a single H.264 stream
I encode camera images with several parallel H.264 baseline I-frame only encoder cores in FPGA (more parallel cores are required to get the encoding done fast enough without external memory). I use an opensource encoder. On simulator I use 352x288 yuv420 input image and I slice it to 2 horizontal halves.

The decoder is on another embedded device and I can decode the separated slices correctly. But, instead of several decoded video sequences, I would need to have just one vido sequence (with the whole image) from one H.264 byte stream. It is preferred to merge the H.264 streams on the FPGA (instead of doing this by post processing the decoded slice video sequences on the embedded host).

So, the input image data looks like this:

```<code>    .--.-----.--.--.-----.--.
    |MB|     |MB|MB|     |MB|
    | 0| ... |10|11| ... |21|
    |--.     '--|--'     '--|
    |MB|        |           |
    |22|        |           |
    |--'        |           |
    |   Slice   |   Slice   |
    |     0     |     1     |
    '-----------'----------'
</code>```

And the encoder's block diagram is this (just one encoder core shown, without merging):

```<code>                                 YUV420 MacroBlocks (16*16 pixel)
                                         |       |
                                  chroma |       | luma
                                         |       |
                      .----------------.-------. |
                      |                | |     | |
                      |                v v     v v
                 reconstruct      intra8x8cc  intra4x4 ---> header
                      ^                |        |             |
                      |                v        v             |
                inv.transform        coretransform            |
                      ^                |     |                |
                      |                |     v                |
                  dequantise           | dctransform          |
                   ^       ^           |     |                |
                   |       |           v     v                |
        inv.dc.transform <-'---------- quantise               |
                                           |                  |
                                           v                  |
                                         buffer               |
                                           |                  |
                                           v                  |
                                          cavlc               |
                                           |                  |
                                           v                  |
                                         tobytes <------------'
                                           |
                                           v
                                         H.264 byte stream

</code>```

The encoded h264 data from a singel core (parsed with H264Naked, see parse.txt, ref.yuv420 and ref.264) contains 3 NAL-s: in the first one there is a Sequence Parameter Set, in the second a Picture Parameter Set and in the third a Coded slice of an IDR picture. The SPS and PPS headers are static and these are generated on the host. The IDR header is generated by the encoder on the FPGA. Currently I use a constant Quantization Parameter (i.e. VBR, but it is planned to implement CBR, with variable QP later).

To get the encoded streams merged, I have removed the IDR header from the slices (except from slice 0) in the header block. Then I buffer the output of CAVLC blocks from each encoder for a whole MB row (this is the encoded MB data, MB headers can be identified from the output of header block). Then from this buffer I drive all the CAVLC data to a new instance of tobytes block in this sequence:

CAVLC data of one MB row from slice 0

CAVLC data of one MB row from slice 1

the above is repeated till the end of the frame.

When I decode this merged H.264 stream, then I get the following error with ffmpeg (see merged_tobytes.264 and ffplay_error.txt):

```<code>[h264 @ 0x7f5f0c00ac00] dquant out of range (-112) at 13 1B f=0/0
[h264 @ 0x7f5f0c00ac00] error while decoding MB 13 1
[h264 @ 0x7f5f0c00ac00] concealing 396 DC, 396 AC, 396 MV errors in I frame
</code>```

With JM reference decoder I get this error (jm_dec_error.txt):

```<code>mb_qp_delta is out of range (-112)
illegal chroma intra pred mode!
</code>```

I think the problem is that the decoder does not know about the slices and expects neighboring MB data from other slice which are not available in the encoded data. I have checked the Macroblock prediction syntax in the standard (chapter 7.3.5.1), but I do not see how should I correct this (I have very little knowledge about H.264). On the encoder side, I see that intra4x4 and intra8x8cc are using neighboring MB prediction and pixel data from the top and left MB neighbors when those are available (we have no top MB neighbors in the first MB row and we have no left MB neighbor at first MB of each MB row, in each slice).

I have also tried to use FMO and declared slice groups (slice_group_map_type=2) as described here, but FMO and slice groups are not supported by typical H.264 decoders (see ffmpeg issue, I think it is used only in broadcast equipments). In fact, I had also got error from JM reference decoder even when I have declared the slice groups (see merged_tobytes_with_slice_grops.264 and jm_dec_slice_groups_error.txt):

```<code>warning: Intra_8x8_Horizontal prediction mode not allowed at mb 0
illegal chroma intra pred mode!
</code>```

Any help is appreciated.

Reference photo is taken from here.

PS: if someone can advise a deblocker which could be used with this FPGA core, that would be also nice.

答:
You can't just interleave slice data like that. From a decoder's point of view, each slice is supposed to be a complete and independent decoding unit, so a decoder can parse and decode multiple slices at the same time using different slice decoding instances (e.g. threads).

Slices are also supposed to be contiguous in scan-order. So, in your example, you'd want to cut the image horizontally (in two slices on top of each other) rather than vertically, and then append the second slice after the first - and fixing up the header(s) to signal the correct frame height. This should decode correctly. To do this for more slices, just cut the individual slices smaller. But they should always be contiguous in scan-order.

Body:
I encode camera images with several parallel H.264 baseline I-frame only encoder cores in FPGA (more parallel cores are required to get the encoding done fast enough without external memory). I use an opensource encoder. On simulator I use 352x288 yuv420 input image and I slice it to 2 horizontal halves.

The decoder is on another embedded device and I can decode the separated slices correctly. But, instead of several decoded video sequences, I would need to have just one vido sequence (with the whole image) from one H.264 byte stream. It is preferred to merge the H.264 streams on the FPGA (instead of doing this by post processing the decoded slice video sequences on the embedded host).

So, the input image data looks like this:

    .--.-----.--.--.-----.--.
    |MB|     |MB|MB|     |MB|
    | 0| ... |10|11| ... |21|
    |--.     '--|--'     '--|
    |MB|        |           |
    |22|        |           |
    |--'        |           |
    |   Slice   |   Slice   |
    |     0     |     1     |
    '-----------'----------'

And the encoder's block diagram is this (just one encoder core shown, without merging):

                                 YUV420 MacroBlocks (16*16 pixel)
                                         |       |
                                  chroma |       | luma
                                         |       |
                      .----------------.-------. |
                      |                | |     | |
                      |                v v     v v
                 reconstruct      intra8x8cc  intra4x4 ---> header
                      ^                |        |             |
                      |                v        v             |
                inv.transform        coretransform            |
                      ^                |     |                |
                      |                |     v                |
                  dequantise           | dctransform          |
                   ^       ^           |     |                |
                   |       |           v     v                |
        inv.dc.transform <-'---------- quantise               |
                                           |                  |
                                           v                  |
                                         buffer               |
                                           |                  |
                                           v                  |
                                          cavlc               |
                                           |                  |
                                           v                  |
                                         tobytes <------------'
                                           |
                                           v
                                         H.264 byte stream

The encoded h264 data from a singel core (parsed with H264Naked, see parse.txt, ref.yuv420 and ref.264) contains 3 NAL-s: in the first one there is a Sequence Parameter Set, in the second a Picture Parameter Set and in the third a Coded slice of an IDR picture. The SPS and PPS headers are static and these are generated on the host. The IDR header is generated by the encoder on the FPGA. Currently I use a constant Quantization Parameter (i.e. VBR, but it is planned to implement CBR, with variable QP later).

To get the encoded streams merged, I have removed the IDR header from the slices (except from slice 0) in the header block. Then I buffer the output of CAVLC blocks from each encoder for a whole MB row (this is the encoded MB data, MB headers can be identified from the output of header block). Then from this buffer I drive all the CAVLC data to a new instance of tobytes block in this sequence:

CAVLC data of one MB row from slice 0

CAVLC data of one MB row from slice 1

the above is repeated till the end of the frame.

When I decode this merged H.264 stream, then I get the following error with ffmpeg (see merged_tobytes.264 and ffplay_error.txt):

[h264 @ 0x7f5f0c00ac00] dquant out of range (-112) at 13 1B f=0/0
[h264 @ 0x7f5f0c00ac00] error while decoding MB 13 1
[h264 @ 0x7f5f0c00ac00] concealing 396 DC, 396 AC, 396 MV errors in I frame

With JM reference decoder I get this error (jm_dec_error.txt):

mb_qp_delta is out of range (-112)
illegal chroma intra pred mode!

I think the problem is that the decoder does not know about the slices and expects neighboring MB data from other slice which are not available in the encoded data. I have checked the Macroblock prediction syntax in the standard (chapter 7.3.5.1), but I do not see how should I correct this (I have very little knowledge about H.264). On the encoder side, I see that intra4x4 and intra8x8cc are using neighboring MB prediction and pixel data from the top and left MB neighbors when those are available (we have no top MB neighbors in the first MB row and we have no left MB neighbor at first MB of each MB row, in each slice).

I have also tried to use FMO and declared slice groups (slice_group_map_type=2) as described here, but FMO and slice groups are not supported by typical H.264 decoders (see ffmpeg issue, I think it is used only in broadcast equipments). In fact, I had also got error from JM reference decoder even when I have declared the slice groups (see merged_tobytes_with_slice_grops.264 and jm_dec_slice_groups_error.txt):

warning: Intra_8x8_Horizontal prediction mode not allowed at mb 0
illegal chroma intra pred mode!

Any help is appreciated.

Reference photo is taken from here.

PS: if someone can advise a deblocker which could be used with this FPGA core, that would be also nice.


问:
Getting this error "AttributeError: 'music' object has no attribute 'music_queue'" when trying to do anything with my list
```<code>class music(commands.Cog):
 def init(self, client):
   self.client = client
   self.music_queue = []

cog_ext.cog_slash(name='play', description='play music')
 async def play(self,ctx,song):

   self.music_queue.append(song)

   print(self.music_queue)
</code>```
```<code>AttributeError: 'music' object has no attribute 'music_queue'
</code>```

答:
Firstly, this isn't a discord.py related question as it doesn't support slash commands. Secondly, it's supposed to be @cog_ext.cog_slash(name='play', description='play music'). Thirdly, the indentation makes it so that the decorator (and thus the command) wouldn't be a part of the class.

class Music(commands.Cog):

    def __init__(self, client):
        self.client=client
        self.music_queue=[]

    @cog_ext.cog_slash(
        name="play",
        description="plays a song (probably)"
    )
    async def play(self, ctx, song):
        self.music_queue.append(song)
        return
```

Body:
class music(commands.Cog):
 def init(self, client):
   self.client = client
   self.music_queue = []

cog_ext.cog_slash(name='play', description='play music')
 async def play(self,ctx,song):

   self.music_queue.append(song)

   print(self.music_queue)

AttributeError: 'music' object has no attribute 'music_queue'


问:
MongoParseError: options poolsize, usenewurlparse are not supported
I get the error "MongoParseError: options poolsize, usenewurlparse are not supported" when I run "nodemon server".

Here the code for setting up the mongodb connection:

```<code>import app from "./server.js"
import mongodb from "mongodb"
import dotenv from "dotenv"

dotenv.config()
const MongoClient = mongodb.MongoClient

const port = process.env.PORT || 8000

MongoClient.connect(
  process.env.RESTREVIEWS_DB_URI,
  {
    poolSize: 50,
    wtimeout: 2500,
    useNewUrlParse: true,
    }
  )
  .catch(err => {

    console.error(err.stack)
    process.exit(1)
  })
  .then(async client => {

    app.listen(port, () => {
      console.log(`listening on port ${port}`)
    })
  })
</code>```

答:
I had the same issue and this is how I managed, in your code , replace

```<code> {
    poolSize: 50,
    wtimeout: 2500,
    useNewUrlParse: true,
    }
</code>```

with

```<code>{

  maxPoolSize: 50,
  wtimeoutMS: 2500,
  useNewUrlParser: true,
}
</code>```

Body:
I get the error "MongoParseError: options poolsize, usenewurlparse are not supported" when I run "nodemon server".

Here the code for setting up the mongodb connection:

import app from "./server.js"
import mongodb from "mongodb"
import dotenv from "dotenv"

dotenv.config()
const MongoClient = mongodb.MongoClient

const port = process.env.PORT || 8000

MongoClient.connect(
  process.env.RESTREVIEWS_DB_URI,
  {
    poolSize: 50,
    wtimeout: 2500,
    useNewUrlParse: true,
    }
  )
  .catch(err => {

    console.error(err.stack)
    process.exit(1)
  })
  .then(async client => {

    app.listen(port, () => {
      console.log(`listening on port ${port}`)
    })
  })

Body:
I had the same issue and this is how I managed, in your code , replace

 {
    poolSize: 50,
    wtimeout: 2500,
    useNewUrlParse: true,
    }

with

{

  maxPoolSize: 50,
  wtimeoutMS: 2500,
  useNewUrlParser: true,
}


问:
How to modify values in delimiter text file in unix
I have a huge file with delimited value with '~' example

abc~poi~123~jijda~123~abc

Requirement is to replace the values at 3rd occurrence (which is 123 in our case) to be replaced with 111.

I used the below command

awk -F '~' -v OFS='~' '$3 == "123" {$3 = "111"} 1 ' file.txt > Newfile.txt

this works for manually created file but when it the file was created using utf-8 encoding it doesn't work. Can some one help on this. Thanks!

答:
Your awk code with some changes:

```<code>awk -F'~' -v OFS='~' '{$3=111} 1' file
abc~poi~111~jijda~123~abc
</code>```

we assign to $3 the 111 value.

Body:
Your awk code with some changes:

awk -F'~' -v OFS='~' '{$3=111} 1' file
abc~poi~111~jijda~123~abc

we assign to $3 the 111 value.


问:
How to get a variable value from sh file and pass it in shell script?
I have a sh file which fetches the username and password. i want to pass this as a parameter to another shell script. How do i do that

```<code>fetch_credentials.sh
export user=test
export pass=test123

bash
./fetch_credentials.sh
echo "userName : "$user
echo "password : "$pass
</code>```

i'm presently getting null values when i execute the same.

答:
You need to source your first file, as:

$ cat > fetch_credentials.sh
export user=test
export pass=test123

$ source fetch_credentials.sh

$ echo "userName: $user, password: $pass"
userName: test, password: test123
```

Note that source is an alias for . so you can also use . fetch_credentials.sh.

Body:
I have a sh file which fetches the username and password. i want to pass this as a parameter to another shell script. How do i do that

fetch_credentials.sh
export user=test
export pass=test123

bash
./fetch_credentials.sh
echo "userName : "$user
echo "password : "$pass

i'm presently getting null values when i execute the same.

Body:
You need to source your first file, as:

$ cat > fetch_credentials.sh
export user=test
export pass=test123

$ source fetch_credentials.sh

$ echo "userName: $user, password: $pass"
userName: test, password: test123

Note that source is an alias for . so you can also use . fetch_credentials.sh.


问:
Neo4j: Could someone "translate" this code snippet for me?
I'm sorry if I don't follow best practice here, but I just can't understand (and therefore of course also not recreate in a new version of Neo4j) whatever this snippet is supposed to do :(

Out of interest, I started my journey in Neo4j and concluded the intro classes and wanted to recreate some projects to become more fluent with this interesting technology.
But I can't wrap my head around this exercise from the "What's cooking" example:

```<code>// Construct lists of node ids of ingredients,
// grouped by node ids of recipes
MATCH (r:Recipe)-[:CONTAINS_INGREDIENT]->(ingredient)
WITH {item:id(r), categories: collect(id(ingredient))} as userData
WITH collect(userData) as data
CALL algo.similarity.jaccard.stream(data)
YIELD item1, item2, count1, count2, intersection, similarity

// Look up nodes by node id
WITH algo.asNode(item1) AS from,
     algo.asNode(item2) AS to,
     similarity, intersection
RETURN from.name, from.id, to.name, to.id, intersection, similarity
ORDER BY similarity DESC
LIMIT 20
</code>```

when I try to update the outdated algo.similarity.jaccard() with gds.nodeSimilarity.stream as well as algo.asNode() with gds.asNode(), I still fail after the YIELD statement where the console tells me, that it just doesn't find item1 (and therefore will also not find item2).

EDIT: I'm running with Neo4j version 4.2.5 and GDS 1.5.2

I hope someone could help me to understand what's gone wrong!

BR,
Dan

答:
You are correct that your example is from the older algorithms library, not the current GDS library. Here's a breakdown of what the example code is doing.

Start by matching recipes with the ingredients they contain.

```<code>// Construct lists of node ids of ingredients,
// grouped by node ids of recipes
MATCH (r:Recipe)-[:CONTAINS_INGREDIENT]->(ingredient)
</code>```

At this point, we have a tall result set consisting pairs of r nodes for recipes and ingredient nodes for ingredients.

```<code>WITH {item:id(r), categories: collect(id(ingredient))} as userData
</code>```

Now we have transformed the results so that we have one map per recipe. The map has two key-value pairs. The item key points to the recipe node's id. The categories key points to a list of all of the ids for the ingredient nodes.

```<code>WITH collect(userData) as data
</code>```

We transform the results again from many rows with one map per row to a single row. This row contains a list called data that holds all the maps. This is the format that algo.similarity.jaccard.stream expects as input. Now we can call the algorithm.

```<code>CALL algo.similarity.jaccard.stream(data)
YIELD item1, item2, count1, count2, intersection, similarity
</code>```

The algorithm outputs item1 and item2. These are Neo4j's internal node ids. Those ids have no meaning outside of Neo4j, so we want to convert them back into nodes by calling algo.asNode

```<code>// Look up nodes by node id
WITH algo.asNode(item1) AS from,
     algo.asNode(item2) AS to,
     similarity, intersection
</code>```

Now we can return the node properties that are interesting to us.

```<code>RETURN from.name, from.id, to.name, to.id, intersection, similarity
ORDER BY similarity DESC
LIMIT 20
</code>```

To do something similar in the current Graph Data Science library, you can use the Node Similarity algorithm. Instead of expecting a list of maps, the GDS algorithm accepts an in-memory graph projection as input. Create an in-memory graph called recipe-graph that contains the Recipe and Ingredient nodes and the CONTAINS_INGREDIENT relationships.

```<code>CALL gds.graph.create('recipe-graph', ["Recipe", "Ingredient"], 'CONTAINS_INGREDIENT')
</code>```

Then, pass that graph to the nodeSimilarity algorithm.

```<code>CALL gds.nodeSimilarity.stream('recipe-graph')
 YIELD node1, node2, similarity
 WITH gds.util.asNode(node1) AS r1,
    gds.util.asNode(node2) AS r2, similarity
 WHERE r1:Recipe and r1:Recipe
 RETURN r1.name as recipe1, r2.name as recipe2, similarity
 ORDER BY similarity DESCENDING, r1.name, r2.name
 LIMIT 20
</code>```

Finally, drop the in-memory graph you created.

```<code>CALL gds.graph.drop('recipe-graph')
</code>```

If you don't want to create and drop a named graph, it's also possible to call the algorithm on an anonymous graph.

Body:
I'm sorry if I don't follow best practice here, but I just can't understand (and therefore of course also not recreate in a new version of Neo4j) whatever this snippet is supposed to do :(

Out of interest, I started my journey in Neo4j and concluded the intro classes and wanted to recreate some projects to become more fluent with this interesting technology.
But I can't wrap my head around this exercise from the "What's cooking" example:

// Construct lists of node ids of ingredients,
// grouped by node ids of recipes
MATCH (r:Recipe)-[:CONTAINS_INGREDIENT]->(ingredient)
WITH {item:id(r), categories: collect(id(ingredient))} as userData
WITH collect(userData) as data
CALL algo.similarity.jaccard.stream(data)
YIELD item1, item2, count1, count2, intersection, similarity

// Look up nodes by node id
WITH algo.asNode(item1) AS from,
     algo.asNode(item2) AS to,
     similarity, intersection
RETURN from.name, from.id, to.name, to.id, intersection, similarity
ORDER BY similarity DESC
LIMIT 20

when I try to update the outdated algo.similarity.jaccard() with gds.nodeSimilarity.stream as well as algo.asNode() with gds.asNode(), I still fail after the YIELD statement where the console tells me, that it just doesn't find item1 (and therefore will also not find item2).

EDIT: I'm running with Neo4j version 4.2.5 and GDS 1.5.2

I hope someone could help me to understand what's gone wrong!

BR,
Dan

Body:
You are correct that your example is from the older algorithms library, not the current GDS library. Here's a breakdown of what the example code is doing.

Start by matching recipes with the ingredients they contain.

// Construct lists of node ids of ingredients,
// grouped by node ids of recipes
MATCH (r:Recipe)-[:CONTAINS_INGREDIENT]->(ingredient)

At this point, we have a tall result set consisting pairs of r nodes for recipes and ingredient nodes for ingredients.

WITH {item:id(r), categories: collect(id(ingredient))} as userData

Now we have transformed the results so that we have one map per recipe. The map has two key-value pairs. The item key points to the recipe node's id. The categories key points to a list of all of the ids for the ingredient nodes.

WITH collect(userData) as data

We transform the results again from many rows with one map per row to a single row. This row contains a list called data that holds all the maps. This is the format that algo.similarity.jaccard.stream expects as input. Now we can call the algorithm.

CALL algo.similarity.jaccard.stream(data)
YIELD item1, item2, count1, count2, intersection, similarity

The algorithm outputs item1 and item2. These are Neo4j's internal node ids. Those ids have no meaning outside of Neo4j, so we want to convert them back into nodes by calling algo.asNode

// Look up nodes by node id
WITH algo.asNode(item1) AS from,
     algo.asNode(item2) AS to,
     similarity, intersection

Now we can return the node properties that are interesting to us.

RETURN from.name, from.id, to.name, to.id, intersection, similarity
ORDER BY similarity DESC
LIMIT 20

To do something similar in the current Graph Data Science library, you can use the Node Similarity algorithm. Instead of expecting a list of maps, the GDS algorithm accepts an in-memory graph projection as input. Create an in-memory graph called recipe-graph that contains the Recipe and Ingredient nodes and the CONTAINS_INGREDIENT relationships.

CALL gds.graph.create('recipe-graph', ["Recipe", "Ingredient"], 'CONTAINS_INGREDIENT')

Then, pass that graph to the nodeSimilarity algorithm.

CALL gds.nodeSimilarity.stream('recipe-graph')
 YIELD node1, node2, similarity
 WITH gds.util.asNode(node1) AS r1,
    gds.util.asNode(node2) AS r2, similarity
 WHERE r1:Recipe and r1:Recipe
 RETURN r1.name as recipe1, r2.name as recipe2, similarity
 ORDER BY similarity DESCENDING, r1.name, r2.name
 LIMIT 20

Finally, drop the in-memory graph you created.

CALL gds.graph.drop('recipe-graph')

If you don't want to create and drop a named graph, it's also possible to call the algorithm on an anonymous graph.


问:
Make a nicer looking dropdown filter label with DataTables DT in R
I'm trying to make a datatable for a shiny dashboard that will have a dropdown filter on a column. I actually have it working, but the appearance is what I'd call subpar.

Here is my simple example

```<code>library(DT)
mytable <- data.frame(Col1 = as.factor(LETTERS[1:3]))
datatable(mytable, filter = "top")
</code>```

When I have the dropdown active, the filter text input looks nice:

However, when I click away, it does not look as nice:

Is there any way to keep that nice looking A with an x in a bubble (sorry I'm sure there's a better term for that), or at least get rid of the bracket and quotation marks? I know that if the column values are characters rather than factors, I can get a nicer looking text input, but them I lose the dropdown functionality (related to this question Factor dropdown filter in DT::datatable in shiny dashboards not working), which I need.

```<code>mytable <- data.frame(Col1 = LETTERS[1:3], stringsAsFactors = FALSE)
datatable(mytable, filter = "top")
</code>```

I'd be happy with a cell dropdown like the one in this post Edit datatable in Shiny with dropdown selection for factor variables, but I need to filter the table, not edit it.

Version info:

R version 3.5.3

DT_0.20

答:
I know how to do that but with the dropdowns in the footer, I don't know how to put them at the top. The code uses the JavaScript library select2.

library(shiny)
library(DT)

dat <- iris

sketch <- htmltools::tags$table(
  tableHeader(c("",names(dat))),
  tableFooter(rep("", 1+ncol(dat)))
)

js <- c(
  "function(){",
  "  this.api().columns().every(function(i){",
  "    var column = this;",
  "    var select = $('<select multiple=\"multiple\"><option value=\"\"></option></select>')",
  "      .appendTo( $(column.footer()).empty() )",
  "      .on('change', function(){",
  "        var vals = $('option:selected', this).map(function(index,element){",
  "          return $.fn.dataTable.util.escapeRegex($(element).val());",
  "        }).toArray().join('|');",
  "        column.search(vals.length > 0 ? '^('+vals+')$' : '', true, false).draw();",
  "      });",
  "    var data = column.data();",
  "    if(i == 0){",
  "      data.each(function(d, j){",
  "        select.append('<option value=\"'+d+'\">'+d+'</option>');",
  "      });",
  "    }else{",
  "      data.unique().sort().each(function(d, j){",
  "        select.append('<option value=\"'+d+'\">'+d+'</option>');",
  "      });",
  "    }",
  "    select.select2({width: '100%', closeOnSelect: false});",
  "  });",
  "}")

ui <- fluidPage(
  tags$head(
    tags$link(rel = "stylesheet", href = "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css"),
    tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js")
  ),
  br(),
  DTOutput("dtable")
)

server <- function(input, output, session){
  output[["dtable"]] <- renderDT({
    datatable(
      dat, container=sketch,
      options = list(
        initComplete = JS(js),
        columnDefs = list(
          list(targets = "_all", className = "dt-center")
        )
      )
    )
  }, server = FALSE)
}

shinyApp(ui, server)
```
<p><img src="https://i.stack.imgur.com/UK9JC.gif" alt="enter image description here" /></p>
<hr />
<h1>Edit</h1>
<p>To have the filters at the top:</p>
<pre class="lang-r prettyprint-override"><code>library(shiny)
library(DT)
library(htmltools)

dat <- iris

sketch <- tags$table(
  tags$thead(
    tags$tr(
      tags$th(),
      lapply(names(dat), tags$th)
    ),
    tags$tr(
      tags$th(id = "th0"),
      tags$th(id = "th1"),
      tags$th(id = "th2"),
      tags$th(id = "th3"),
      tags$th(id = "th4"),
      tags$th(id = "th5")
    )
  )
)

js <- c(
  "function(){",
  "  this.api().columns().every(function(i){",
  "    var column = this;",
  "    var select = $('<select multiple=\"multiple\"><option value=\"\"></option></select>')",
  "      .appendTo( $('#th'+i).empty() )",
  "      .on('change', function(){",
  "        var vals = $('option:selected', this).map(function(index,element){",
  "          return $.fn.dataTable.util.escapeRegex($(element).val());",
  "        }).toArray().join('|');",
  "        column.search(vals.length > 0 ? '^('+vals+')$' : '', true, false).draw();",
  "      });",
  "    var data = column.data();",
  "    if(i == 0){",
  "      data.each(function(d, j){",
  "        select.append('<option value=\"'+d+'\">'+d+'</option>');",
  "      });",
  "    }else{",
  "      data.unique().sort().each(function(d, j){",
  "        select.append('<option value=\"'+d+'\">'+d+'</option>');",
  "      });",
  "    }",
  "    select.select2({width: '100%', closeOnSelect: false});",
  "  });",
  "}")

ui <- fluidPage(
  tags$head(
    tags$link(rel = "stylesheet", href = "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css"),
    tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js")
  ),
  br(),
  DTOutput("dtable")
)

server <- function(input, output, session){
  output[["dtable"]] <- renderDT({
    datatable(
      dat, container=sketch,
      options = list(
        orderCellsTop = TRUE,
        initComplete = JS(js),
        columnDefs = list(
          list(targets = "_all", className = "dt-center")
        )
      )
    )
  }, server = FALSE)
}

shinyApp(ui, server)
</code>```

Body:
I'm trying to make a datatable for a shiny dashboard that will have a dropdown filter on a column. I actually have it working, but the appearance is what I'd call subpar.

Here is my simple example

library(DT)
mytable <- data.frame(Col1 = as.factor(LETTERS[1:3]))
datatable(mytable, filter = "top")

When I have the dropdown active, the filter text input looks nice:

However, when I click away, it does not look as nice:

Is there any way to keep that nice looking A with an x in a bubble (sorry I'm sure there's a better term for that), or at least get rid of the bracket and quotation marks? I know that if the column values are characters rather than factors, I can get a nicer looking text input, but them I lose the dropdown functionality (related to this question Factor dropdown filter in DT::datatable in shiny dashboards not working), which I need.

mytable <- data.frame(Col1 = LETTERS[1:3], stringsAsFactors = FALSE)
datatable(mytable, filter = "top")

I'd be happy with a cell dropdown like the one in this post Edit datatable in Shiny with dropdown selection for factor variables, but I need to filter the table, not edit it.

Version info:

R version 3.5.3

DT_0.20

Body:
I know how to do that but with the dropdowns in the footer, I don't know how to put them at the top. The code uses the JavaScript library select2.

library(shiny)
library(DT)

dat <- iris

sketch <- htmltools::tags$table(
  tableHeader(c("",names(dat))),
  tableFooter(rep("", 1+ncol(dat)))
)

js <- c(
  "function(){",
  "  this.api().columns().every(function(i){",
  "    var column = this;",
  "    var select = $('<select multiple=\"multiple\"><option value=\"\"></option></select>')",
  "      .appendTo( $(column.footer()).empty() )",
  "      .on('change', function(){",
  "        var vals = $('option:selected', this).map(function(index,element){",
  "          return $.fn.dataTable.util.escapeRegex($(element).val());",
  "        }).toArray().join('|');",
  "        column.search(vals.length > 0 ? '^('+vals+')$' : '', true, false).draw();",
  "      });",
  "    var data = column.data();",
  "    if(i == 0){",
  "      data.each(function(d, j){",
  "        select.append('<option value=\"'+d+'\">'+d+'</option>');",
  "      });",
  "    }else{",
  "      data.unique().sort().each(function(d, j){",
  "        select.append('<option value=\"'+d+'\">'+d+'</option>');",
  "      });",
  "    }",
  "    select.select2({width: '100%', closeOnSelect: false});",
  "  });",
  "}")

ui <- fluidPage(
  tags$head(
    tags$link(rel = "stylesheet", href = "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css"),
    tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js")
  ),
  br(),
  DTOutput("dtable")
)

server <- function(input, output, session){
  output[["dtable"]] <- renderDT({
    datatable(
      dat, container=sketch,
      options = list(
        initComplete = JS(js),
        columnDefs = list(
          list(targets = "_all", className = "dt-center")
        )
      )
    )
  }, server = FALSE)
}

shinyApp(ui, server)

Edit

To have the filters at the top:

library(shiny)
library(DT)
library(htmltools)

dat <- iris

sketch <- tags$table(
  tags$thead(
    tags$tr(
      tags$th(),
      lapply(names(dat), tags$th)
    ),
    tags$tr(
      tags$th(id = "th0"),
      tags$th(id = "th1"),
      tags$th(id = "th2"),
      tags$th(id = "th3"),
      tags$th(id = "th4"),
      tags$th(id = "th5")
    )
  )
)

js <- c(
  "function(){",
  "  this.api().columns().every(function(i){",
  "    var column = this;",
  "    var select = $('<select multiple=\"multiple\"><option value=\"\"></option></select>')",
  "      .appendTo( $('#th'+i).empty() )",
  "      .on('change', function(){",
  "        var vals = $('option:selected', this).map(function(index,element){",
  "          return $.fn.dataTable.util.escapeRegex($(element).val());",
  "        }).toArray().join('|');",
  "        column.search(vals.length > 0 ? '^('+vals+')$' : '', true, false).draw();",
  "      });",
  "    var data = column.data();",
  "    if(i == 0){",
  "      data.each(function(d, j){",
  "        select.append('<option value=\"'+d+'\">'+d+'</option>');",
  "      });",
  "    }else{",
  "      data.unique().sort().each(function(d, j){",
  "        select.append('<option value=\"'+d+'\">'+d+'</option>');",
  "      });",
  "    }",
  "    select.select2({width: '100%', closeOnSelect: false});",
  "  });",
  "}")

ui <- fluidPage(
  tags$head(
    tags$link(rel = "stylesheet", href = "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css"),
    tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js")
  ),
  br(),
  DTOutput("dtable")
)

server <- function(input, output, session){
  output[["dtable"]] <- renderDT({
    datatable(
      dat, container=sketch,
      options = list(
        orderCellsTop = TRUE,
        initComplete = JS(js),
        columnDefs = list(
          list(targets = "_all", className = "dt-center")
        )
      )
    )
  }, server = FALSE)
}

shinyApp(ui, server)


问:
What is the point of salt and hashing if database is accessible?
I just learned the concept of hashing ("Hey! don't forget the salt!") and using salt to make the password secured.

Hashing it is a one way encryption (actually not encryption but hashing) so it cannot be reversed engineered. Salting is prefixing or appending randomly created values to the password before hashing 'coz the problem in hashing (just hashing) is, some genius has provided a hash table of words from the dictionary so that they'll just compare the hash from that dictionary to the user's table from the database to login - W-wait? did I say table from the database? So it means somebody can access the database so we have to use salt? If that so, then why would the hacker recover the password if he already has access to the database? If I were him, I'll just get all the details I want from the database, why would I use the key I've stolen from a house to open the door if I can access the house already through the window?

So, why hash? why salt? I don't understand. Please, somebody help me.

Thanks in advance.

Important Note: I'm not against hashing or salting, I just want to clarify things.

答:
Suppose an attacker somehow gains access to a backup of the database, containing unrecoverable hashed passwords. Then they have all the data that was in there yesterday, which is quite bad. But at least they don't have access to the data that will be in there tomorrow, and they can't delete anything from the real site, deface it, serve malware via its CMS, etc.

Suppose an attacker gets everyone's plaintext passwords, especially if that includes the administrator. Oops.

ContentLicense: CC BY-SA 3.0


问:
How can I dispay the data in django admin panel
I am creating an eCommerce website but I want to know how can I display a product_name or customer_name in the admin panel.

The concept is that if a customer places an order that it will go to the admin panel. So the other details are displaying properly except product_name or customet_name.

As shown in the below image:

models.py

```<code>class Order(models.Model):
        product = models.ForeignKey(Product, on_delete=models.CASCADE)
        customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
        quantity = models.IntegerField(default=1)
        address = models.CharField(max_length=50, default='', blank=True)
        phone = models.CharField(max_length=50, default='', blank=True)
        price = models.IntegerField()
        date = models.DateField(default=datetime.datetime.today)
        status = models.BooleanField(default=False)
</code>```

admin.py

```<code>class AdminOrders(admin.ModelAdmin):
    list_display = ['product', 'customer', 'quantity', 'address', 'phone', 'price', 'date', 'status']
</code>```

答:
Have tried double underscore in order to access the foreign item field  (product__name) and (customer__name).

```<code>class Product(models.Model):
   name= models.CharField(max_length=50, default='', blank=True)
   ....
class Customer(models.Model):
   name= models.CharField(max_length=50, default='', blank=True)
   ....

class AdminOrders(admin.ModelAdmin):
    list_display = ['product__name', 'customer__name', 'quantity', 'address', 'phone', 'price', 'date', 'status']
</code>```

Body:
I am creating an eCommerce website but I want to know how can I display a product_name or customer_name in the admin panel.

The concept is that if a customer places an order that it will go to the admin panel. So the other details are displaying properly except product_name or customet_name.

As shown in the below image:

models.py

class Order(models.Model):
        product = models.ForeignKey(Product, on_delete=models.CASCADE)
        customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
        quantity = models.IntegerField(default=1)
        address = models.CharField(max_length=50, default='', blank=True)
        phone = models.CharField(max_length=50, default='', blank=True)
        price = models.IntegerField()
        date = models.DateField(default=datetime.datetime.today)
        status = models.BooleanField(default=False)

admin.py

class AdminOrders(admin.ModelAdmin):
    list_display = ['product', 'customer', 'quantity', 'address', 'phone', 'price', 'date', 'status']

Body:
Have tried double underscore in order to access the foreign item field  (product__name) and (customer__name).

class Product(models.Model):
   name= models.CharField(max_length=50, default='', blank=True)
   ....
class Customer(models.Model):
   name= models.CharField(max_length=50, default='', blank=True)
   ....

class AdminOrders(admin.ModelAdmin):
    list_display = ['product__name', 'customer__name', 'quantity', 'address', 'phone', 'price', 'date', 'status']


问:
What does "npm audit fix" exactly do?
npm audit fix is intended to automatically upgrade / fix vulnerabilities in npm packages. However, I haven't found out what it exactly does to fix those vulnerabilities.

I assumed that npm audit fix would upgrade dependencies and dependencies' dependencies to the latest versions that are allowed by the semver-definitions of the packages – effectively the same as rm package-lock.json; npm install. However npm audit fix still performs a lot of changes after lock file removal + reinstall.

What exactly does npm audit fix do? Does it for example install versions of dependencies newer than those allowed by the corresponding package.json (but still semver-compatible)?

答:
In my understanding is not only "upgrading" but sometimes also downgrading in order to install the stable version that fix the issue, sometimes those issues comes in newer versions that maybe have introduced bugs or simply do not match with previous package's API etc.

E.g in my case for example npm install have upgrade react-script to 5.0.0 that has some issue and after have run:

```<code>npm audit fix --force
</code>```

The force flag does : To address all issues (including breaking changes), run: npm audit fix --force

it installed the 3.0.1 with following message:

```<code>npm WARN audit Updating react-scripts to 3.0.1,which is a SemVer major change.
</code>```

So it does the upgrade to the stable version of that package that fix the issue.

On top, though docs state "is running npm install under the hood" but not in the sense of installing newest version of a dependency, but could be useful also to check what happens with npm ci What is the difference between "npm install" and "npm ci"?

Title: What does "npm audit fix" exactly do?

Body:
In my understanding is not only "upgrading" but sometimes also downgrading in order to install the stable version that fix the issue, sometimes those issues comes in newer versions that maybe have introduced bugs or simply do not match with previous package's API etc.

E.g in my case for example npm install have upgrade react-script to 5.0.0 that has some issue and after have run:

npm audit fix --force

The force flag does : To address all issues (including breaking changes), run: npm audit fix --force

it installed the 3.0.1 with following message:

npm WARN audit Updating react-scripts to 3.0.1,which is a SemVer major change.

So it does the upgrade to the stable version of that package that fix the issue.

On top, though docs state "is running npm install under the hood" but not in the sense of installing newest version of a dependency, but could be useful also to check what happens with npm ci What is the difference between "npm install" and "npm ci"?


问:
Python - add functionality to function to access information from previous call
I got a function like below:

```<code>def my_func(some_objects):
    objects_information = []
    for object_ in some_objects:
        object_information = dict()
        object_information['name'] = some_object.name
        object_information['position'] = some_object.position
        object_information['previous_position'] = previous_position or None
        objects_information.append(object_information)
    return objects_information
</code>```

how can I add to that function an option to hold information about the objects position so in the line object_information['previous_position'] I can use the information object_position['position'] from the last call to the function?  If object_information['name'] is the same as in previous call and if it's the first call with that object_name it will place None in previous_position key.

Thank you very much

答:
functionality to function to access information from previous call

To get such feature you might exploit mutable default argument gotcha, consider following example

```<code>def remember(arg, seen=[]):
    seen.append(arg)
    return seen
print(remember(3))
print(remember(5))
print(remember(7))
</code>```

output

```<code>[3]
[3, 5]
[3, 5, 7]
</code>```

Note that this is often trap for python coders unaware of this behavior, so if you decide to use it document it well.

Body:
I got a function like below:

def my_func(some_objects):
    objects_information = []
    for object_ in some_objects:
        object_information = dict()
        object_information['name'] = some_object.name
        object_information['position'] = some_object.position
        object_information['previous_position'] = previous_position or None
        objects_information.append(object_information)
    return objects_information

how can I add to that function an option to hold information about the objects position so in the line object_information['previous_position'] I can use the information object_position['position'] from the last call to the function?  If object_information['name'] is the same as in previous call and if it's the first call with that object_name it will place None in previous_position key.

Thank you very much

Body:
functionality to function to access information from previous call

To get such feature you might exploit mutable default argument gotcha, consider following example

def remember(arg, seen=[]):
    seen.append(arg)
    return seen
print(remember(3))
print(remember(5))
print(remember(7))

output

[3]
[3, 5]
[3, 5, 7]

Note that this is often trap for python coders unaware of this behavior, so if you decide to use it document it well.


问:
my app is not responding when it should be asking for permission
I'm coding an instagram clone and i must request external storage permission but my app doesn't respond when i clicked imageView that ı set onClick method (fotoSec) for taking image from gallery.

```<code>   fun fotoSec (view: View) {

    // Önce izin istenecek. İzin verilirse galeriye gidecek verilmezse uyarı mesajı gösterecek.
    // İzini bir kere verdiyse tekrar istenmeyecek direkt galeriye gidecek.
    if (ContextCompat.checkSelfPermission(this,android.Manifest.permission.READ_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED) {
        //İzin verilmemiş.
        ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE),1)
    } else {
        //İzin verilmiş.
        val galeriIntent = Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(galeriIntent,2)
    }
}

override fun onRequestPermissionsResult(
    requestCode: Int,
    permissions: Array<out String>,
    grantResults: IntArray
) {
    if (requestCode==1) {
        if(grantResults.size>0 &&grantResults[0]== PackageManager.PERMISSION_GRANTED) {

            val galeriIntent = Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            startActivityForResult(galeriIntent,2)
        }
    }

    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

    if ( requestCode==2 &&  resultCode== Activity.RESULT_OK && data!=null) {
        secilenGorsel=data.data

        if (secilenGorsel!=null) {

            if (Build.VERSION.SDK_INT>= 28) {
                val source = ImageDecoder.createSource(this.contentResolver,secilenGorsel!!)
                secilenBitmap=ImageDecoder.decodeBitmap(source)
                image!!.setImageBitmap(secilenBitmap)

            }else {
                secilenBitmap= MediaStore.Images.Media.getBitmap(this.contentResolver,secilenGorsel)

                image!!.setImageBitmap(secilenBitmap)
            }

        }
    }

    super.onActivityResult(requestCode, resultCode, data)
}
</code>```

And there is no exceptions in logcat.
In addition I'm a beginner, sorry my faults.

Thanks in advance.

答: make sure that you have added the same permission in AndroidManifest.xml like below.

Body:
I'm coding an instagram clone and i must request external storage permission but my app doesn't respond when i clicked imageView that ı set onClick method (fotoSec) for taking image from gallery.

   fun fotoSec (view: View) {

    // Önce izin istenecek. İzin verilirse galeriye gidecek verilmezse uyarı mesajı gösterecek.
    // İzini bir kere verdiyse tekrar istenmeyecek direkt galeriye gidecek.
    if (ContextCompat.checkSelfPermission(this,android.Manifest.permission.READ_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED) {
        //İzin verilmemiş.
        ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE),1)
    } else {
        //İzin verilmiş.
        val galeriIntent = Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(galeriIntent,2)
    }
}

override fun onRequestPermissionsResult(
    requestCode: Int,
    permissions: Array<out String>,
    grantResults: IntArray
) {
    if (requestCode==1) {
        if(grantResults.size>0 &&grantResults[0]== PackageManager.PERMISSION_GRANTED) {

            val galeriIntent = Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            startActivityForResult(galeriIntent,2)
        }
    }

    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

    if ( requestCode==2 &&  resultCode== Activity.RESULT_OK && data!=null) {
        secilenGorsel=data.data

        if (secilenGorsel!=null) {

            if (Build.VERSION.SDK_INT>= 28) {
                val source = ImageDecoder.createSource(this.contentResolver,secilenGorsel!!)
                secilenBitmap=ImageDecoder.decodeBitmap(source)
                image!!.setImageBitmap(secilenBitmap)

            }else {
                secilenBitmap= MediaStore.Images.Media.getBitmap(this.contentResolver,secilenGorsel)

                image!!.setImageBitmap(secilenBitmap)
            }

        }
    }

    super.onActivityResult(requestCode, resultCode, data)
}

And there is no exceptions in logcat.
In addition I'm a beginner, sorry my faults.

Thanks in advance.


问:
How can I add text to a Google Docs document via Docs API?
I'm trying to add text to an existing Google Docs file via Google Docs API and I'm using Golang for this. I followed steps in https://developers.google.com/docs/api/quickstart/go I can reach but I don't know how can I edit this file?

I found how to add text to file here is related part of my code :

```<code>b := &docs.BatchUpdateDocumentRequest{
        Requests: []*docs.Request{
            {
                InsertText: &docs.InsertTextRequest{
                    Text: "texttoadd",
                    Location: &docs.Location{
                        Index: md.Body.Content[len(md.Body.Content)-1].EndIndex - 1,
                    },
                },
            },
        },
    }
    _, err = srv.Documents.BatchUpdate("your_document_id", b).Do()
    if err != nil {
        fmt.Println(err)
    }
</code>```

答:
this answer is a bit late:

the go api is now available here:

regarding the specifics of your code, it should work. I added a step for step approach below. You have to create the structures first and then assign their pointers to the Request structure.

The long way code:

```<code>var batchreqs docs.BatchUpdateDocumentRequest

var instxtreq docs.InsertTextRequest

var txtloc docs.Location

var breq docs.Request

txtloc.Index = {your index}

txtloc.SegmentID = "" // a bit superfluous

instxtreq.Location = &txtloc

instxtreq.Text = "your new text"

breq.InsertText =&instxtreq

var breqarray [1](*docs.Request)

breqarray[0].InsertText = instxtreq

breqslice = breqarray[:]

 batchreqs.Request = &breqslice

// now you can do the BatchUpdate

 _, err = srv.Documents.BatchUpdate("your_document_id", &batchreqs).Do()

// the batch reqs must be a pointer to an existing batchupdaterequest structure
</code>```

Body:
I'm trying to add text to an existing Google Docs file via Google Docs API and I'm using Golang for this. I followed steps in https://developers.google.com/docs/api/quickstart/go I can reach but I don't know how can I edit this file?

I found how to add text to file here is related part of my code :

b := &docs.BatchUpdateDocumentRequest{
        Requests: []*docs.Request{
            {
                InsertText: &docs.InsertTextRequest{
                    Text: "texttoadd",
                    Location: &docs.Location{
                        Index: md.Body.Content[len(md.Body.Content)-1].EndIndex - 1,
                    },
                },
            },
        },
    }
    _, err = srv.Documents.BatchUpdate("your_document_id", b).Do()
    if err != nil {
        fmt.Println(err)
    }

Body:
this answer is a bit late:

the go api is now available here:

regarding the specifics of your code, it should work. I added a step for step approach below. You have to create the structures first and then assign their pointers to the Request structure.

The long way code:

var batchreqs docs.BatchUpdateDocumentRequest

var instxtreq docs.InsertTextRequest

var txtloc docs.Location

var breq docs.Request

txtloc.Index = {your index}

txtloc.SegmentID = "" // a bit superfluous

instxtreq.Location = &txtloc

instxtreq.Text = "your new text"

breq.InsertText =&instxtreq

var breqarray [1](*docs.Request)

breqarray[0].InsertText = instxtreq

breqslice = breqarray[:]

 batchreqs.Request = &breqslice

// now you can do the BatchUpdate

 _, err = srv.Documents.BatchUpdate("your_document_id", &batchreqs).Do()

// the batch reqs must be a pointer to an existing batchupdaterequest structure


问:
How can i deal with an error that shows 'lateinit property binding has not been initialized' while trying to display a list in a RecyclerView
I'm new to Android development and I'm trying to display a list of todo on my RecyclerView but it is throwing an error that says 'lateinit property binding has not been initialized' I think the error is from here :

 override fun onBindViewHolder(holder: TodoViewHolder, position: Int) {

        holder.itemView.apply {
            binding.txtTitle.text = todos[position].title
            binding.cbTodo.isChecked = todos[position].isChecked
        }
```
<p>Because that's the line of code in my Adapter the logcat is highlighting while I checked for error.  Please I need help in solving this error , my app crashes whenever I tried entering this Activity.</p>
<p><strong>my Adapter</strong></p>
<pre class="lang-kotlin prettyprint-override"><code>class TodoAdapter(var todos : List<Todo>) : RecyclerView.Adapter<TodoAdapter.TodoViewHolder>()
{
    inner class TodoViewHolder(itemView:View) : RecyclerView.ViewHolder(itemView)
    private lateinit var binding:ItemTodoBinding

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TodoViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_todo,parent,false)
        return TodoViewHolder(view)
    }

    override fun onBindViewHolder(holder: TodoViewHolder, position: Int) {
        holder.itemView.apply {
            binding.txtTitle.text = todos[position].title
            binding.cbTodo.isChecked = todos[position].isChecked
        }
    }

    override fun getItemCount(): Int {
        return  todos.size
    }
}
</code>```

My Class

data class Todo (
    val title :String,
    var  isChecked : Boolean
        )
```
<p><strong>My Activity.kt</strong></p>
<pre class="lang-kotlin prettyprint-override"><code>class NextAftertoolbar : AppCompatActivity() {
        binding = ActivityNextAftertoolbarBinding.inflate(layoutInflater)
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        supportActionBar?.hide()

        var todolist = mutableListOf(
            Todo("Follow Android devs",false),
            Todo(" Learn ",false),
            Todo("Build",false),
            Todo("Land a role",false),
        )

        val adapter = TodoAdapter(todolist)
        binding.rvTodo.adapter = adapter
        binding.rvTodo.layoutManager=LinearLayoutManager(this)

        binding.btnTodo.setOnClickListener {
            val title  = binding.etTodo.text.toString()
            val todo = Todo(title,false)
            todolist.add(todo)
            adapter.notifyItemInserted(todolist.size-1)
        }
    }
}
</code>```

答:
As answered earlier, you should inflate and provide binding to your ViewHolder.

Here full working code.

```<code>class TodoAdapter(var todos: List<Todo>) :
    RecyclerView.Adapter<TodoAdapter.TodoViewHolder>() {

    inner class TodoViewHolder(val binding: ItemTodoBinding) :
        RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): TodoViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        val binding = ItemTodoBinding.inflate(inflater, parent, false)
        return TodoViewHolder(binding)
    }

    override fun onBindViewHolder(
        holder: TodoViewHolder,
        position: Int
    ) {
        holder.apply {
            binding.txtTitle.text = todos[position].title
            binding.cbTodo.isChecked = todos[position].isChecked
        }
    }

    override fun getItemCount(): Int {
        return todos.size
    }

}
</code>```

Body:
I'm new to Android development and I'm trying to display a list of todo on my RecyclerView but it is throwing an error that says 'lateinit property binding has not been initialized' I think the error is from here :

 override fun onBindViewHolder(holder: TodoViewHolder, position: Int) {

        holder.itemView.apply {
            binding.txtTitle.text = todos[position].title
            binding.cbTodo.isChecked = todos[position].isChecked
        }

Because that's the line of code in my Adapter the logcat is highlighting while I checked for error.  Please I need help in solving this error , my app crashes whenever I tried entering this Activity.

my Adapter

class TodoAdapter(var todos : List<Todo>) : RecyclerView.Adapter<TodoAdapter.TodoViewHolder>()
{
    inner class TodoViewHolder(itemView:View) : RecyclerView.ViewHolder(itemView)
    private lateinit var binding:ItemTodoBinding

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TodoViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_todo,parent,false)
        return TodoViewHolder(view)
    }

    override fun onBindViewHolder(holder: TodoViewHolder, position: Int) {
        holder.itemView.apply {
            binding.txtTitle.text = todos[position].title
            binding.cbTodo.isChecked = todos[position].isChecked
        }
    }

    override fun getItemCount(): Int {
        return  todos.size
    }
}

My Class

data class Todo (
    val title :String,
    var  isChecked : Boolean
        )

My Activity.kt

class NextAftertoolbar : AppCompatActivity() {
        binding = ActivityNextAftertoolbarBinding.inflate(layoutInflater)
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        supportActionBar?.hide()

        var todolist = mutableListOf(
            Todo("Follow Android devs",false),
            Todo(" Learn ",false),
            Todo("Build",false),
            Todo("Land a role",false),
        )

        val adapter = TodoAdapter(todolist)
        binding.rvTodo.adapter = adapter
        binding.rvTodo.layoutManager=LinearLayoutManager(this)

        binding.btnTodo.setOnClickListener {
            val title  = binding.etTodo.text.toString()
            val todo = Todo(title,false)
            todolist.add(todo)
            adapter.notifyItemInserted(todolist.size-1)
        }
    }
}

Body:
As answered earlier, you should inflate and provide binding to your ViewHolder.

Here full working code.

class TodoAdapter(var todos: List<Todo>) :
    RecyclerView.Adapter<TodoAdapter.TodoViewHolder>() {

    inner class TodoViewHolder(val binding: ItemTodoBinding) :
        RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): TodoViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        val binding = ItemTodoBinding.inflate(inflater, parent, false)
        return TodoViewHolder(binding)
    }

    override fun onBindViewHolder(
        holder: TodoViewHolder,
        position: Int
    ) {
        holder.apply {
            binding.txtTitle.text = todos[position].title
            binding.cbTodo.isChecked = todos[position].isChecked
        }
    }

    override fun getItemCount(): Int {
        return todos.size
    }

}


问:
angular json array - duplicate table creation problem
I have a code structure as below, the data comes as an array, but more than one table is formed. I think I'm doing something wrong on the HTML side. Is there any way to fix this

When I try to import the data in the Material Demands Details from the json into a table, it creates more than one table

```<code>      <li *ngFor="let item of materialsDetails" >
        <ol *ngFor="let subItem of item.materialDemandDetails">
          <table mat-table [dataSource]="materialsDetails" class="mat-elevation-z8">

            <!-- Id Column -->
            <ng-container matColumnDef="id">
              <th mat-header-cell *matHeaderCellDef> Id </th>
              <td mat-cell *matCellDef="let element"> {{subItem.id}}</td>
            </ng-container>

            <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
            <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
          </table>
        </ol>
      </li>
</code>```

I've been trying for hours but I couldn't find where I made a mistake on the html side.

i have json data like below and i want to get array inside a nested data and pass it to table

Json

```<code>[
 {
 "description": "Ram .",
 "createdUserId": "12345",
 "createdUserName": "demo user",
 "status": "idle",
 "companyId": 2,
 "materialDemandId": 0,
 "materialDemandDetails": [
     {
         "stockName": "Ram 12 gb products",
         "totalDemand": 2,
         "materialDemandId": 1,
         "productId": 2,
         "id": 1,
         "createdDate": "2022-02-08T14:29:11.1763481",
         "updatedDate": "2022-02-08T11:28:42.409",
         "totalCount": 0,
         "companyId": 0
     },
     {
         "stockName": "Ram 12 gb",
         "totalDemand": 2,
         "materialDemandId": 1,
         "productId": 1,
         "id": 3,
         "createdDate": "2022-02-08T14:32:09.7305862",
         "updatedDate": "2022-02-08T11:28:42.409",
         "totalCount": 0,
         "companyId": 0
     }
 ],
 "id": 1,
 "createdDate": "2022-02-08T14:28:33.0658772",
 "updatedDate": "2022-02-08T11:27:46.939",
 "totalCount": 0
 }
]
</code>```

答:
```<code>  <table mat-table [dataSource]="materialDemandDetailsNew" class="mat-elevation-z8">

    <!-- Id Column -->
    <ng-container matColumnDef="id">
      <th mat-header-cell *matHeaderCellDef> Id </th>
      <td mat-cell *matCellDef="let element"> {{subItem.id}}</td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>
</code>```

And in the component map the whole list into a new variable which you can use in the table

```<code>var materialDemandDetailsNew = [];
materialsDetails.forEach(item => item.materialDemandDetails.forEach(detail => materialDemandDetailsNew.push(detail)))
</code>```

Hope I got the question right

Body:
I have a code structure as below, the data comes as an array, but more than one table is formed. I think I'm doing something wrong on the HTML side. Is there any way to fix this

When I try to import the data in the Material Demands Details from the json into a table, it creates more than one table

            <ng-container matColumnDef="id">
               Id
               {{subItem.id}}
            </ng-container>

I've been trying for hours but I couldn't find where I made a mistake on the html side.

i have json data like below and i want to get array inside a nested data and pass it to table

Json

[
 {
 "description": "Ram .",
 "createdUserId": "12345",
 "createdUserName": "demo user",
 "status": "idle",
 "companyId": 2,
 "materialDemandId": 0,
 "materialDemandDetails": [
     {
         "stockName": "Ram 12 gb products",
         "totalDemand": 2,
         "materialDemandId": 1,
         "productId": 2,
         "id": 1,
         "createdDate": "2022-02-08T14:29:11.1763481",
         "updatedDate": "2022-02-08T11:28:42.409",
         "totalCount": 0,
         "companyId": 0
     },
     {
         "stockName": "Ram 12 gb",
         "totalDemand": 2,
         "materialDemandId": 1,
         "productId": 1,
         "id": 3,
         "createdDate": "2022-02-08T14:32:09.7305862",
         "updatedDate": "2022-02-08T11:28:42.409",
         "totalCount": 0,
         "companyId": 0
     }
 ],
 "id": 1,
 "createdDate": "2022-02-08T14:28:33.0658772",
 "updatedDate": "2022-02-08T11:27:46.939",
 "totalCount": 0
 }
]

Body:
  <table mat-table [dataSource]="materialDemandDetailsNew" class="mat-elevation-z8">

    <!-- Id Column -->
    <ng-container matColumnDef="id">
      <th mat-header-cell *matHeaderCellDef> Id </th>
      <td mat-cell *matCellDef="let element"> {{subItem.id}}</td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>

And in the component map the whole list into a new variable which you can use in the table

var materialDemandDetailsNew = [];
materialsDetails.forEach(item => item.materialDemandDetails.forEach(detail => materialDemandDetailsNew.push(detail)))

Hope I got the question right


问:
Windows Forms - Change Datagrid Cell Value when Button in another Form is clicked
I have a value from Timer Form, which i want to set in a specific Datagridview Cell in the Main Form. When the new value is set, i want to update the Datagrid, so the right value is in shown in the Datagrid.

Thanks for your effort!

答:
Setup an event in Timer form and pass the value, here is a basic example. Adjust to work with your code in regards to your DataGridView and if the value being passed is not a string, change it.

```<code>public partial class TimerForm : Form
{
    public delegate void OnWhatEver(string sender);
    public event OnWhatEver WhatEverHandler;
    public TimerForm()
    {
        InitializeComponent();
    }

    private void WhatEverButton_Click(object sender, EventArgs e)
    {
        WhatEverHandler?.Invoke($"{sender:f}");
    }
}
</code>```

Main Form, one button, one label

```<code>public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
    }

    private void OpenTimerForm_Click(object sender, EventArgs e)
    {
        TimerForm form = new TimerForm();
        form.WhatEverHandler += OnWhatEverEvent;
        form.ShowDialog();
    }

    private void OnWhatEverEvent(string sender)
    {
        label1.Text = sender;
    }
}
</code>```

Body:
Setup an event in Timer form and pass the value, here is a basic example. Adjust to work with your code in regards to your DataGridView and if the value being passed is not a string, change it.

public partial class TimerForm : Form
{
    public delegate void OnWhatEver(string sender);
    public event OnWhatEver WhatEverHandler;
    public TimerForm()
    {
        InitializeComponent();
    }

    private void WhatEverButton_Click(object sender, EventArgs e)
    {
        WhatEverHandler?.Invoke($"{sender:f}");
    }
}

Main Form, one button, one label

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
    }

    private void OpenTimerForm_Click(object sender, EventArgs e)
    {
        TimerForm form = new TimerForm();
        form.WhatEverHandler += OnWhatEverEvent;
        form.ShowDialog();
    }

    private void OnWhatEverEvent(string sender)
    {
        label1.Text = sender;
    }
}


问:
Flutter: How can update the list.generate on delete item?
I want to update the page after deleting a tile. setState is not working... Can u help me?
I can delete it from firebase but not update de view</p>
```<code> Widget build(BuildContext context) {
    final UserProvider userProvider = Provider.of<UserProvider>(context);
    return Scaffold(
...
 children: List.generate(
                  userProvider.getUser.player.length,
                  (index) => SizedBox(
                      child: ListTile(
                    contentPadding: const EdgeInsets.only(
                      right: 5,
                      left: 15,
                      top: 0,
                    ),
                    title: AutoSizeText(
                      userProvider.getUser.bands[index].nameP,
                      style: const TextStyle(letterSpacing: 2.0),
                      maxLines: 1,
                    ),
                    subtitle: Text(userProvider.getUser.bands[index].rol),
                    trailing: IconButton(
                      icon: const Icon(CupertinoIcons.trash),
                      onPressed: () {
                        setState(() {
                          deletePlayer(index, userProvider.getUser.uid);

                        });
</code>```

答:
Don't do setState.
Instead add notifyListeners(); on deletePlayer</p>
```<code>deletePlayer(int index, String uid){
   //code//
   notifyListeners();
}
</code>```

Body:
I want to update the page after deleting a tile. setState is not working... Can u help me?
I can delete it from firebase but not update de view

 Widget build(BuildContext context) {
    final UserProvider userProvider = Provider.of<UserProvider>(context);
    return Scaffold(
...
 children: List.generate(
                  userProvider.getUser.player.length,
                  (index) => SizedBox(
                      child: ListTile(
                    contentPadding: const EdgeInsets.only(
                      right: 5,
                      left: 15,
                      top: 0,
                    ),
                    title: AutoSizeText(
                      userProvider.getUser.bands[index].nameP,
                      style: const TextStyle(letterSpacing: 2.0),
                      maxLines: 1,
                    ),
                    subtitle: Text(userProvider.getUser.bands[index].rol),
                    trailing: IconButton(
                      icon: const Icon(CupertinoIcons.trash),
                      onPressed: () {
                        setState(() {
                          deletePlayer(index, userProvider.getUser.uid);

                        });

Body:
Don't do setState.
Instead add notifyListeners(); on deletePlayer

deletePlayer(int index, String uid){
   //code//
   notifyListeners();
}


答:
```<code>onPressed: () async{
 await deletePlayer(index, userProvider.getUser.uid);
 setState(() {});
}
</code>```

and use notifyListener() in provider

Title: Flutter: How can update the list.generate on delete item?

Body:
onPressed: () async{
 await deletePlayer(index, userProvider.getUser.uid);
 setState(() {});
}

and use notifyListener() in provider


问:
write and save a txt file using spyder
I am trying to write a txt file from Python:

```<code>for i in range(len(X)):
    k+=1
    g.write('CoordinatesX='+str(i)+str(X[i])+'\n')
    g.write('D'+str(k)+'@Sketch'+str(sketch_number)+'=CoordinatesX'+str(k)+'\n')
    k+=1
    g.write('CoordinatesY='+str(i)+str(Y[i])+'\n')
    g.write('D'+str(k)+'@Sketch'+str(sketch_number)+'=CoordinatesY'+str(k)+'\n')
    k+=1
    g.write('CoordinatesZ='+str(i)+str(Z[i])+'\n')
    g.write('D'+str(k)+'@Sketch'+str(sketch_number)+'=CoordinatesZ'+str(k)+'\n')

g.close()
</code>```

I get no error, but then when I go to look for the downloaded file, I don't find it, and nothing was written.
Does someone know what I am doing wrong? Thank you so much already.
cheers!

答:
In Python you can open a file this way:

```<code>file = open('file.txt', 'r+')
file.read() # This will return the content
file.write("This file has just been overwritten")
file.close() # This will close the file
</code>```

A better practice is to use the with/as syntax:

```<code>with open('file.txt', 'r+') as file:
    file.read()
    file.write("This file has just been overwritten")
# The file is automatically closed (saved) after the with block has ended
</code>```

Title: write and save a txt file using spyder

Body:
I am trying to write a txt file from Python:

for i in range(len(X)):
    k+=1
    g.write('CoordinatesX='+str(i)+str(X[i])+'\n')
    g.write('D'+str(k)+'@Sketch'+str(sketch_number)+'=CoordinatesX'+str(k)+'\n')
    k+=1
    g.write('CoordinatesY='+str(i)+str(Y[i])+'\n')
    g.write('D'+str(k)+'@Sketch'+str(sketch_number)+'=CoordinatesY'+str(k)+'\n')
    k+=1
    g.write('CoordinatesZ='+str(i)+str(Z[i])+'\n')
    g.write('D'+str(k)+'@Sketch'+str(sketch_number)+'=CoordinatesZ'+str(k)+'\n')

g.close()

I get no error, but then when I go to look for the downloaded file, I don't find it, and nothing was written.
Does someone know what I am doing wrong? Thank you so much already.
cheers!

Body:
In Python you can open a file this way:

file = open('file.txt', 'r+')
file.read() # This will return the content
file.write("This file has just been overwritten")
file.close() # This will close the file

A better practice is to use the with/as syntax:

with open('file.txt', 'r+') as file:
    file.read()
    file.write("This file has just been overwritten")
# The file is automatically closed (saved) after the with block has ended


问:
WHat is the use the Git Info in YAML Azure container files
We are actually evaluation the deployment of docker image to Azure container instance. For that we are using YAML file as defined in the following link
Yaml file srtucture

In that structure I have notice a section relative to Git repository

What is the use of the entry and in which case scenario we use it ?

Thanks for help
Regards

答:
The version of Docker Images is maintain in Git Repro.

Example : If you will go Docker Hub and search for any images using docker pull imagesName you can directly install the latest images.

In backend Devlopers work on Existing Images and once they update anything on exisiting Image they push it to github with new version.

So Same here in this YAML file we are using Git Repro so any new version of code(images) update by developer or you. Then by continuoues deployment the exisning container wil update with latest images.

For Reference you can take this docker image and in down of this link there is link for Where to file issues in code section you able to see the code of this image.


问:
Ansible Playbook adding the same line multiple times to yml file
I have to add the same line several times in the same file. It must always be inserted after a certain line, which is the same for both locations.

I have tried it with the lineinfile module, but, there, only one line is always added. I have also tried with the replace module, but, then, no line is added at all.

My lineinfile task looks like this:

- name: Add Line
  ansible.builtin.lineinfile:
    path: someyml.yml
    insertbefore: "template:"
    line: "{{ Cluster_API}}"

```
<p>The <code>replace</code> task looks like this:</p>
<pre class="lang-yaml prettyprint-override"><code>- name: Replace
  replace:
    path: someyml.yml
    regexp: '^(template:\n)(?!{{ Cluster_API }})'
    replace: '\1 {{ Cluster_API }}\n'

</code>```

I know how the replace is written it should insert a line after template: but it doesn't even do that.

答:
i have tested with a test file:

```<code>abcdef
template:
toto

123
template:

ssss
template:
toto
</code>```

playbook test:

```<code>- name: "tips3"
  hosts: localhost
  tasks:
    - name: replace 'template:' not followed by toto by 'template:\ntoto'
      replace:
          path: files/test.txt
          regexp: '^(template:)(?!\n{{data}})'
          replace: '\1\n{{data}}'
      vars:
        data: toto
</code>```

result: just only one toto added after the second template

```<code>abcdef
template:
toto

123
template:
toto

ssss
template:
toto
</code>```

Body:
I have to add the same line several times in the same file. It must always be inserted after a certain line, which is the same for both locations.

I have tried it with the lineinfile module, but, there, only one line is always added. I have also tried with the replace module, but, then, no line is added at all.

My lineinfile task looks like this:

- name: Add Line
  ansible.builtin.lineinfile:
    path: someyml.yml
    insertbefore: "template:"
    line: "{{ Cluster_API}}"

The replace task looks like this:

- name: Replace
  replace:
    path: someyml.yml
    regexp: '^(template:\n)(?!{{ Cluster_API }})'
    replace: '\1 {{ Cluster_API }}\n'

I know how the replace is written it should insert a line after template: but it doesn't even do that.

Body:
i have tested with a test file:

abcdef
template:
toto

123
template:

ssss
template:
toto

playbook test:

- name: "tips3"
  hosts: localhost
  tasks:
    - name: replace 'template:' not followed by toto by 'template:\ntoto'
      replace:
          path: files/test.txt
          regexp: '^(template:)(?!\n{{data}})'
          replace: '\1\n{{data}}'
      vars:
        data: toto

result: just only one toto added after the second template

abcdef
template:
toto

123
template:
toto

ssss
template:
toto


问:
collection.find({matchQuery}) in MongoDb is taking too long
I am trying to read some limited records after performing a match query on find() collection in mongoDb.

The query takes forever to process.
In the next line, I try to read elements of the returned collection and that also takes a lot of time to complete.

Please help where I am making a mistake or scope of improvement.

```<code>robot_data = collection.find({"robot_uid": {"$eq":"12345"}},{"_id":0}).sort("_id",1).limit(500)

for a in robot_data :
                print(f"print elements : {a}")
</code>```

Regards,
Aarushi

答:
The answer that worked out for me with everyone's help here was to make the search field robot_uid into an index.

The search is extremely fast now.

Thank you!
Aarushi

Body:
I am trying to read some limited records after performing a match query on find() collection in mongoDb.

The query takes forever to process.
In the next line, I try to read elements of the returned collection and that also takes a lot of time to complete.

Please help where I am making a mistake or scope of improvement.

robot_data = collection.find({"robot_uid": {"$eq":"12345"}},{"_id":0}).sort("_id",1).limit(500)

for a in robot_data :
                print(f"print elements : {a}")

Regards,
Aarushi


问:
Label text color is not changing in bottom navigation bar widget in scaffold, flutter
I used
selectedLabelStyle: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
color: Colors.black,
),

But the text color is still blue. Any idea how to fix it?

答:
The text color can be changed with the selectedItemColor in the BottomNavigationBar
(It will also set the selected Color of the Icon but you have probably overwritten that in the icons)

BottomNavigationBar(
    selectedItemColor:  Colors.black,
    items: ...
)
```


问:
Physics.Raycast not working with a Marching Cubes -generated mesh
What it spits out

My raycast spits out a position way off from what it's supposed to be. I'm trying to place objects procedurally on a procedural mesh. I've been scratching my head at this for a while. Please help.
Sorry for the long script.

The start of the code is just some declares and stuff. GenObjects is run once in FixedUpdate after Start has finished. I'm using a marching cubes library by Scrawk and a noise library by Auburn

    void GenMesh()
    {
        Marching marching = new MarchingCubes();
        marching.Surface = 0.0f;
        voxels = new float[width * height * length];

        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                for (int z = 0; z < length; z++)
                {
                    float fx = x / (width - 1.0f);
                    float fy = y / (height - 1.0f);
                    float fz = z / (length - 1.0f);

                    int idx = x + y * width + z * width * height;

                    float surfaceHeight = noise2.GetNoise(x,z) * amplitude + offset;
                    float currentHeight = Mathf.Clamp(y, surfaceHeight - threshold, surfaceHeight + threshold);
                    float t = Mathf.Abs(currentHeight - surfaceHeight) / threshold;
                    voxels[idx] = Mathf.Lerp(Mathf.Clamp(noise.GetNoise(x,y,z), 0.65f, 1), -1f, t);
                }
            }
        }
        List<Vector3> verts = new List<Vector3>();
        List<int> indices = new List<int>();
        marching.Generate(voxels, width, height, length, verts, indices);
        int maxVertsPerMesh = 30000;
        int numMeshes = verts.Count / maxVertsPerMesh + 1;

        for (int i = 0; i < numMeshes; i++)
        {

            List<Vector3> splitVerts = new List<Vector3>();
            List<int> splitIndices = new List<int>();

            for (int j = 0; j < maxVertsPerMesh; j++)
            {
                int idx = i * maxVertsPerMesh + j;

                if (idx < verts.Count)
                {
                    splitVerts.Add(verts[idx]);
                    splitIndices.Add(j);
                }
            }

            if (splitVerts.Count == 0) continue;

            Mesh mesh = new Mesh();
            mesh.SetVertices(splitVerts);
            mesh.SetTriangles(splitIndices, 0);
            mesh.RecalculateBounds();
            mesh.RecalculateNormals();

            MeshWelder meshWelder = new MeshWelder(mesh);
            meshWelder.Weld();

            GameObject go = new GameObject("Mesh");
            go.layer = LayerMask.NameToLayer("Ground");
            go.transform.parent = transform;
            go.transform.localScale = new Vector3(100f, 100f, 100f);
            go.AddComponent<MeshFilter>();
            go.AddComponent<MeshRenderer>();
            go.AddComponent<MeshCollider>();
            go.GetComponent<Renderer>().material = m_material;
            go.GetComponent<MeshFilter>().mesh = mesh;
            go.GetComponent<MeshCollider>().sharedMesh = mesh;
            go.GetComponent<MeshCollider>().contactOffset = 0f;
            go.transform.localPosition = new Vector3(-width * 100 / 2, -height * 100 / 4, -length * 100 / 2);

            meshes.Add(go);
        }
    }

    void GenObjects(GameObject prefab, float radius, Vector2 sampleRegionSize, Vector2 origin, int seed)
    {
        List<Vector2> points = PoissonDiscSampling.GeneratePoints(radius, sampleRegionSize, seed);
        Physics.queriesHitBackfaces = true;
        foreach (Vector2 point in points)
        {
            RaycastHit hit;
            Vector3 objPos = new Vector3(0,0,0);
            bool validPosFound = false;
            if (Physics.Raycast(new Vector3(point.x + origin.x, 0, point.y + origin.y), Vector3.down, out hit, height * 100, layerMask))
            {
                objPos = hit.point;
                validPosFound = true;
            } else if (Physics.Raycast(new Vector3(point.x + origin.x, 0, point.y + origin.y), Vector3.up, out hit, height * 100, layerMask))
            {
                objPos = hit.point;
                validPosFound = true;
            }
            if (validPosFound)
            {
                GameObject newObject = Instantiate(prefab, objPos, Quaternion.Euler(0, 0, 0));
            }
        }
        Physics.queriesHitBackfaces = false;
    }
}

```

答:
Fixed! My mistake was really stupid. I wasn't assigning the welded mesh, leaving a filthy mesh with lots of empty verts floating about. The raycast was hitting them.

The fixed lines for anyone who cares:

            Mesh mesh = new Mesh();
            Mesh mesh_temp = new Mesh();

            mesh_temp.SetVertices(splitVerts);
            mesh_temp.SetTriangles(splitIndices, 0);
            mesh_temp.RecalculateBounds();
            mesh_temp.RecalculateNormals();

            MeshWelder meshWelder = new MeshWelder();
            meshWelder.customMesh = new CustomMesh();
            meshWelder.customMesh.vertices = splitVerts.ToArray();
            meshWelder.customMesh.triangles = splitIndices.ToArray();
            meshWelder.customMesh.normals = mesh_temp.normals;
            meshWelder.Weld();

            mesh.SetVertices(meshWelder.customMesh.vertices);
            mesh.SetTriangles(meshWelder.customMesh.triangles, 0);
            mesh.SetNormals(meshWelder.customMesh.normals);
            mesh.RecalculateBounds();
```


问:
Do a Nim regex modifier just like Perl one
How is Nim regex PCRE modifier done as in Perl itself is e.g.

```<code>/foobar/i
/ foo bar /x
/foobar.*/s
</code>```

etc ?

Please explain correctly doing such on Nim

Thanks much in advance

答:
I report the excellent answer provided by Hlaftaana to this same question on the forum: https://forum.nim-lang.org/t/8884

With re you supply a set of RegexFlag arguments to the re function, with nre you supply them inside the regex.

Example:

```<code>import re
let reg1 = re("foo bar", {reIgnoreCase, reExtended})
# or
import nre
let reg2 = re"(?ix)foo bar"
</code>```

Body:
How is Nim regex PCRE modifier done as in Perl itself is e.g.

/foobar/i
/ foo bar /x
/foobar.*/s

etc ?

Please explain correctly doing such on Nim

Thanks much in advance

Body:
I report the excellent answer provided by Hlaftaana to this same question on the forum: https://forum.nim-lang.org/t/8884

With re you supply a set of RegexFlag arguments to the re function, with nre you supply them inside the regex.

Example:

import re
let reg1 = re("foo bar", {reIgnoreCase, reExtended})
# or
import nre
let reg2 = re"(?ix)foo bar"


问:
Why the logs are not update?
I have a simple PythonOperator:

```<code>def simple():
    print ("start simple")
    for i in range (10):
        time.sleep(0.7)
        print("hello from simple")
    print ("end simple")
</code>```

When looking on the logs window, I need to refresh the page in order to see new logs.

Is it possible for the logs to be updated automatically?

答:
For Airflow>=2.4.0:

Supprt for logs auto refresh was added to Grid View (See PR)

You can configure the refresh interval by setting auto_refresh_interval
(Note this effect other views as well)

For Airflow<2.4.0:

There is no option for that.
There is an open feature request to add this ability for future Airflow versions: Auto-refresh of logs

You can use browser plugins to get this functionality. Chrome has Easy Auto Refresh (and probably many other plugins in that area)

Title: Why the logs are not update?

Body:
I have a simple PythonOperator:

def simple():
    print ("start simple")
    for i in range (10):
        time.sleep(0.7)
        print("hello from simple")
    print ("end simple")

When looking on the logs window, I need to refresh the page in order to see new logs.

Is it possible for the logs to be updated automatically?