问:
Azure Function ServiceBusReceivedMessage ApplicatonProperties are empty
I am creating an Azure Function that is a ServiceBus Trigger.

```<code>        [FunctionName("RetryRack")]
    public async Task Run([ServiceBusTrigger("%RackIntegration:topic%", "%RackIntegration:subscription%")] ServiceBusReceivedMessage sbMessage, ILogger log, MessageReceiver messageReceiver)
</code>```

I am using Azure.Messaging.ServiceBus (7.6.0).

I have several custom properties that I sent in the messages when I send them using ServiceBusMessage from the same library. I can see those custom properties in SB Explorer so I kno w they are being set properly.

Now when I receive the message in the function the ApplicationProperties are empty.

Can anyone help me figure out why the custom properties are not being populated when I receive the message when I know they are being set correctly from SB Explorer?

FYI, I set the properties like this when I send the message.

```<code>message.ApplicationProperties.Add("@message.event","eventName");
</code>```

This is the method that I use to send the messages

```<code>        public async Task SendMessage<T>(T messageObject)
    {
        ServiceBusMessage message = new ServiceBusMessage(JsonConvert.SerializeObject(messageObject));
        message.ApplicationProperties.Add(MessageProperties.Event, "RackIntegration");
        message.ApplicationProperties.Add(MessageProperties.Plant, "CNW");

        try
        {
            await sender.SendMessageAsync(message);
        }
        finally
        {
            await sender.DisposeAsync();
            await client.DisposeAsync();
        }

    }
</code>```

Once the servicebus trigger received the message I try to get the custom properties like this

```<code>string prop1 = receivedMessage.ApplicationProperties[MessageProperties.Event].toString();
</code>```

And as I show in the screen print above the ApplicationProperties collection is empty when the message is retrieved by the function trigger.

I wrote a small console app to receive the message manually using ServiceBusProcessor. When I do that the ApplicationProperties are correctly populated.

So it seems that it is an issue with the Function ServiceBus trigger...maybe?

答:
Apparently in order to use the Azure.Messaging.ServiceBus Nuget package you have to update the Microsoft.Azure.WebJobs.Extensions.ServiceBus to 5.x.

When I created the project it installed version 4.1.0 of that package. I updated it to the latest, 5.2.0, and now everything works.

Thanks

Body:
I am creating an Azure Function that is a ServiceBus Trigger.

        [FunctionName("RetryRack")]
    public async Task Run([ServiceBusTrigger("%RackIntegration:topic%", "%RackIntegration:subscription%")] ServiceBusReceivedMessage sbMessage, ILogger log, MessageReceiver messageReceiver)

I am using Azure.Messaging.ServiceBus (7.6.0).

I have several custom properties that I sent in the messages when I send them using ServiceBusMessage from the same library. I can see those custom properties in SB Explorer so I kno w they are being set properly.

Now when I receive the message in the function the ApplicationProperties are empty.

Can anyone help me figure out why the custom properties are not being populated when I receive the message when I know they are being set correctly from SB Explorer?

FYI, I set the properties like this when I send the message.

message.ApplicationProperties.Add("@message.event","eventName");

This is the method that I use to send the messages

        public async Task SendMessage<T>(T messageObject)
    {
        ServiceBusMessage message = new ServiceBusMessage(JsonConvert.SerializeObject(messageObject));
        message.ApplicationProperties.Add(MessageProperties.Event, "RackIntegration");
        message.ApplicationProperties.Add(MessageProperties.Plant, "CNW");

        try
        {
            await sender.SendMessageAsync(message);
        }
        finally
        {
            await sender.DisposeAsync();
            await client.DisposeAsync();
        }

    }

Once the servicebus trigger received the message I try to get the custom properties like this

string prop1 = receivedMessage.ApplicationProperties[MessageProperties.Event].toString();

And as I show in the screen print above the ApplicationProperties collection is empty when the message is retrieved by the function trigger.

I wrote a small console app to receive the message manually using ServiceBusProcessor. When I do that the ApplicationProperties are correctly populated.

So it seems that it is an issue with the Function ServiceBus trigger...maybe?


来源: stackexchange

问:
How to trigger functions in a component of Angular with TinyMce?
Currently I am trying to let the editor of TinyMce trigger a local function when a button of it triggers 'onAction', but it does not accept any variable with 'this.'.

```<code>        onAction: function () {
          alert('Button clicked!');
          if (this.fileUpload) {
            this.fileUpload.nativeElement.click();
          }
          // Cannot use any function or variable with 'this.'
        }
</code>```

While this is not triggering, this is triggering:

```<code>        onAction: this.postMessage()
</code>```

But for some reason, this will trigger every time the component is initialized (and not clicked). The onAction is bonded with a button which supposed to be triggered only on click, but it doesn't work in that way.

答:
This is because you are using function to declare your functions. The scope is now within that function. If you use arrow functions instead it will work.

So it would be:

```<code>onAction: () => {
      alert('Button clicked!');
      if (this.fileUpload) {
        this.fileUpload.nativeElement.click();
      }
    }
</code>```

Note that you'll have to change the function where you create the button as well. Right now you probably have something like this from the TinyMCE documentation:

```<code>setup: function (editor) {
</code>```

You want to change that to an arrow function also:

```<code>setup: (editor) => {
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Currently I am trying to let the editor of TinyMce trigger a local function when a button of it triggers 'onAction', but it does not accept any variable with 'this.'.

        onAction: function () {
          alert('Button clicked!');
          if (this.fileUpload) {
            this.fileUpload.nativeElement.click();
          }
          // Cannot use any function or variable with 'this.'
        }

While this is not triggering, this is triggering:

        onAction: this.postMessage()

But for some reason, this will trigger every time the component is initialized (and not clicked). The onAction is bonded with a button which supposed to be triggered only on click, but it doesn't work in that way.

Body:
This is because you are using function to declare your functions. The scope is now within that function. If you use arrow functions instead it will work.

So it would be:

onAction: () => {
      alert('Button clicked!');
      if (this.fileUpload) {
        this.fileUpload.nativeElement.click();
      }
    }

Note that you'll have to change the function where you create the button as well. Right now you probably have something like this from the TinyMCE documentation:

setup: function (editor) {

You want to change that to an arrow function also:

setup: (editor) => {


问:
Python: whats does comma mean in in [ : ,1 ]
guys I am new to python and learning machine learning.I have trouble understanding what does this line of code mean:-

```<code>y_scores_knn = y_probas_knn[:,1]
</code>```

I didnt get what  ,1 mean inside an array box [] and what it does

答:
Say for example your list is somewhat like this:

```<code>a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
</code>```

if you do this print(a[:,0])

it will return [1, 2, 3]

So basically ':' means that you want to iterate through every item in the x co-ordinate

Body:
guys I am new to python and learning machine learning.I have trouble understanding what does this line of code mean:-

y_scores_knn = y_probas_knn[:,1]

I didnt get what  ,1 mean inside an array box [] and what it does

Body:
Say for example your list is somewhat like this:

a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]

if you do this print(a[:,0])

it will return [1, 2, 3]

So basically ':' means that you want to iterate through every item in the x co-ordinate


问:
Docker container doesn't update when file changes are made on host
I'm using a docker image as my dev environment for a specific version of PHP. I am using PHP for a command line script so every time I make a change to the script I would like it to automatically make changes in the container.

I'm not sure if this is even possible. I assumed it was. I mostly use docker-compose and I can add VOLUMES easily to achieve this, but not in this instance with docker.

My Dockerfile:

```<code>FROM php:7.2-cli
COPY ./app /usr/src/app/
WORKDIR /usr/src/app
ENTRYPOINT [ "php" ]
CMD [ "./index.php" ]
</code>```

I first run:

```<code>docker build -t app .
</code>```

And then

```<code>docker run app
</code>```

Everything works well. But if I change something in index.php I have to run the steps again. Is this expected behaviour or is there any way to have docker watch for changes?

答:
If you are editing a file using vim/sublime outside docker in your host, this is normal, because vim/sublime does not simple "edit" that file, but create a new file. see : https://github.com/moby/moby/issues/15793

solution:

```<code>After some googling, Sublime text has atomic_save instead so Adding "atomic_save": false to user preferences worked (After a restart).
</code>```

if you are using docker-compose, use this command:

```<code>$ docker-compose run --build
</code>```

Body:
I'm using a docker image as my dev environment for a specific version of PHP. I am using PHP for a command line script so every time I make a change to the script I would like it to automatically make changes in the container.

I'm not sure if this is even possible. I assumed it was. I mostly use docker-compose and I can add VOLUMES easily to achieve this, but not in this instance with docker.

My Dockerfile:

FROM php:7.2-cli
COPY ./app /usr/src/app/
WORKDIR /usr/src/app
ENTRYPOINT [ "php" ]
CMD [ "./index.php" ]

I first run:

docker build -t app .

And then

docker run app

Everything works well. But if I change something in index.php I have to run the steps again. Is this expected behaviour or is there any way to have docker watch for changes?

Body:
If you are editing a file using vim/sublime outside docker in your host, this is normal, because vim/sublime does not simple "edit" that file, but create a new file. see : https://github.com/moby/moby/issues/15793

solution:

After some googling, Sublime text has atomic_save instead so Adding "atomic_save": false to user preferences worked (After a restart).

if you are using docker-compose, use this command:

$ docker-compose run --build


问:
filter not muting video ffmpeg-python
Idk why but when I apply this filter the video is still output with sound. I am not sure of the syntax required to apply filter, so help would be appreciated. Only necessary portion of the code is shown, as im pretty sure this is just a syntax error. I am attempting to mute the clip</p>
```<code>ffmpeg.filter_(i,'volume',0)                                     ##YOU ARE HERE TRYING TO GET FILTERS TO WORK
        ffmpeg.output(i, videoFileName,
                    **{'c:v': 'libx264', 'b:v': targetTotalBitrate, 'pass': 2, 'f' :'mp4'}
                    ).overwrite_output().run()
        print('selected')
</code>```

答:
I doubt the volume filter is meant to be used for muting. If you want no sound, you eliminate an audio stream from your output. The easiest way is to use -an output option.

See FFmpeg Audio Options Documentation

For ffmpeg-python, try

```<code>ffmpeg.output(i, videoFileName,**{'c:v': 'libx264', 'an':None, 'b:v': targetTotalBitrate, 'pass': 2,'f' :'mp4'})
</code>```

Finally, if you continue having an issue with ffmpeg-python, you can give my ffmpegio a try:

```<code>pip install ffmpegio-core
</code>```

(There is ffmpegio package as well, but that one adds NumPy dependency)

from ffmpegio import ffmpegprocess

ffmpegprocess.run_two_pass({
    'inputs' : [('myvideo.mp4',None)], # None can be replaced with an option dict
    'outputs': [(videoFileName, {
        'c:v': 'libx264',
        'an' : None,
        'b:v': targetTotalBitrate,
        'f'  : 'mp4'})]}, overwrite=True)
```

Title: filter not muting video ffmpeg-python

Body:
Idk why but when I apply this filter the video is still output with sound. I am not sure of the syntax required to apply filter, so help would be appreciated. Only necessary portion of the code is shown, as im pretty sure this is just a syntax error. I am attempting to mute the clip

ffmpeg.filter_(i,'volume',0)                                     ##YOU ARE HERE TRYING TO GET FILTERS TO WORK
        ffmpeg.output(i, videoFileName,
                    **{'c:v': 'libx264', 'b:v': targetTotalBitrate, 'pass': 2, 'f' :'mp4'}
                    ).overwrite_output().run()
        print('selected')

Body:
I doubt the volume filter is meant to be used for muting. If you want no sound, you eliminate an audio stream from your output. The easiest way is to use -an output option.

See FFmpeg Audio Options Documentation

For ffmpeg-python, try

ffmpeg.output(i, videoFileName,**{'c:v': 'libx264', 'an':None, 'b:v': targetTotalBitrate, 'pass': 2,'f' :'mp4'})

Finally, if you continue having an issue with ffmpeg-python, you can give my ffmpegio a try:

pip install ffmpegio-core

(There is ffmpegio package as well, but that one adds NumPy dependency)

from ffmpegio import ffmpegprocess

ffmpegprocess.run_two_pass({
    'inputs' : [('myvideo.mp4',None)], # None can be replaced with an option dict
    'outputs': [(videoFileName, {
        'c:v': 'libx264',
        'an' : None,
        'b:v': targetTotalBitrate,
        'f'  : 'mp4'})]}, overwrite=True)


问:
How to call a function from a different class
I am trying to call the following hideOverlay function from a separate class

```<code>  hideOverlay() {
    overlayEntry?.remove();
    overlayEntry = null;

    if (overlayEntry != null) {
      overlayEntry.remove();
      overlayEntry = null;
    }
  }
</code>```

In a separate class, I have imported the file containing the function and attempted to call the file by using.

```<code>hideOverlay();
</code>```

I am a super newbie please advise what I am doing wrong :-(

答:
Put hideOverlay() as a method in a Class, lets call that class 'FirstClass' and from a separate class call an object of the FirstClass class and call that hideOverlay() method like this.</p>
```<code>import 'first_class.dart';

class SecondClass {
 FirstClass firstClass;
//call function like this when needed.
 firstClass.hiveOverlay()
}
</code>```

Body:
I am trying to call the following hideOverlay function from a separate class

  hideOverlay() {
    overlayEntry?.remove();
    overlayEntry = null;

    if (overlayEntry != null) {
      overlayEntry.remove();
      overlayEntry = null;
    }
  }

In a separate class, I have imported the file containing the function and attempted to call the file by using.

hideOverlay();

I am a super newbie please advise what I am doing wrong :-(

Body:
Put hideOverlay() as a method in a Class, lets call that class 'FirstClass' and from a separate class call an object of the FirstClass class and call that hideOverlay() method like this.

import 'first_class.dart';

class SecondClass {
 FirstClass firstClass;
//call function like this when needed.
 firstClass.hiveOverlay()
}


问:
Replace every letter in a string using dictionary values
coders of the internet,

The goal of this assignment was to replace the letters of a sequence with their opposite. 'A' would be 'U', 'C' would be 'G', and vice versa. Here is the string that I came up with so far, but the output is wrong. I can't find a pattern in the output, so I can't reverse-engineer the problem.

```<code>sequence = input('Please enter a sequence: ')
def reverse(sequence):
  dic = { ' A ' : ' U ' , ' G ' : ' C ' , ' C ' : ' G ' , ' U ' : ' A ' }
  for i in range( len ( sequence ) ):
    if sequence[i] in dic.keys():
      sequence = sequence.replace(sequence[i], dic[sequence[i]])
  return sequence
reverse(sequence)
</code>```

Does anyone know how to simply return turn an input (let's just use "GUGU"), and make the code return the output: "CACA"?

答:
Here's my solution.

# Convert input to list format
sequence = list(str(input('Please enter a sequence: ')))

# Define keys
keys = {
    "a": "u",
    "g": "c",
    "c": "g",
    "u": "a"
}

# Create the reverse function
def reverse(sequence: list):
    # Iterate by enumeration and item in sequence list
    for i, letter in enumerate(sequence):
        if letter in keys: # If the letter has a translation
            sequence[i] = keys[letter] # Replace that value
    return ''.join(sequence) # Turn it back into a string

# Pass old list into reverse function
new_sequence = reverse(sequence)
print(new_sequence, type(new_sequence))

# Response: caca <class 'str'>
```

It may contain a few extra steps but clearly outlines how to achieve what you were looking for, step-by-step. The process is essentially:

Convert sequence to list.

Iterate the list and replace values based on keys.

Turn the list back into a string, and return the string.

Body:
coders of the internet,

The goal of this assignment was to replace the letters of a sequence with their opposite. 'A' would be 'U', 'C' would be 'G', and vice versa. Here is the string that I came up with so far, but the output is wrong. I can't find a pattern in the output, so I can't reverse-engineer the problem.

sequence = input('Please enter a sequence: ')
def reverse(sequence):
  dic = { ' A ' : ' U ' , ' G ' : ' C ' , ' C ' : ' G ' , ' U ' : ' A ' }
  for i in range( len ( sequence ) ):
    if sequence[i] in dic.keys():
      sequence = sequence.replace(sequence[i], dic[sequence[i]])
  return sequence
reverse(sequence)

Does anyone know how to simply return turn an input (let's just use "GUGU"), and make the code return the output: "CACA"?

Body:
Here's my solution.

# Convert input to list format
sequence = list(str(input('Please enter a sequence: ')))

# Define keys
keys = {
    "a": "u",
    "g": "c",
    "c": "g",
    "u": "a"
}

# Create the reverse function
def reverse(sequence: list):
    # Iterate by enumeration and item in sequence list
    for i, letter in enumerate(sequence):
        if letter in keys: # If the letter has a translation
            sequence[i] = keys[letter] # Replace that value
    return ''.join(sequence) # Turn it back into a string

# Pass old list into reverse function
new_sequence = reverse(sequence)
print(new_sequence, type(new_sequence))

# Response: caca <class 'str'>

It may contain a few extra steps but clearly outlines how to achieve what you were looking for, step-by-step. The process is essentially:

Convert sequence to list.

Iterate the list and replace values based on keys.

Turn the list back into a string, and return the string.


问:
Checking a parent container for children javascript
Just wondering how you can check an element (i.e. a div container) for elements (i.e. buttons) and if they exist, remove them?

If I append a child to a div, how can I on the next look check for that child or those type of children? i.e. adding;

example = document.getElementById('div');
example.appendChild(aButton);

//loop to look for aButton / button type in example div
```

Cheers

答:
Get the childNodes array, loop through and look for one matching your criteria ( input tag with type button, or possibly a button tag)

```<code>var children = example.childNodes;

for(var i = 0; i<children.length; i++){
    if( children[i].tagName == "INPUT" && children[i].type=='button' ) {
        example.removeChild( children[i] );
        i--; //Decrement counter since we are removing an item from the list
    }
}
</code>```

Example: http://jsfiddle.net/BZMbk/3/

ContentLicense: CC BY-SA 3.0

Body:
Just wondering how you can check an element (i.e. a div container) for elements (i.e. buttons) and if they exist, remove them?

If I append a child to a div, how can I on the next look check for that child or those type of children? i.e. adding;

example = document.getElementById('div');
example.appendChild(aButton);

//loop to look for aButton / button type in example div

Cheers

Body:
Get the childNodes array, loop through and look for one matching your criteria ( input tag with type button, or possibly a button tag)

var children = example.childNodes;

for(var i = 0; i<children.length; i++){
    if( children[i].tagName == "INPUT" && children[i].type=='button' ) {
        example.removeChild( children[i] );
        i--; //Decrement counter since we are removing an item from the list
    }
}

Example: http://jsfiddle.net/BZMbk/3/


问:
TensorFlow 2 tf.function decorator
I have TensorFlow 2.0 and Python 3.7.5.

I have written the following code for performing mini-batch gradient descent which is:

```<code>@tf.function
def train_one_step(model, mask_model, optimizer, x, y):
    '''
    Function to compute one step of gradient descent optimization
    '''
    with tf.GradientTape() as tape:
        # Make predictions using defined model-
        y_pred = model(x)

        # Compute loss-
        loss = loss_fn(y, y_pred)

    # Compute gradients wrt defined loss and weights and biases-
    grads = tape.gradient(loss, model.trainable_variables)

    # type(grads)
    # list

    # List to hold element-wise multiplication between-
    # computed gradient and masks-
    grad_mask_mul = []

    # Perform element-wise multiplication between computed gradients and masks-
    for grad_layer, mask in zip(grads, mask_model.trainable_weights):
        grad_mask_mul.append(tf.math.multiply(grad_layer, mask))

    # Apply computed gradients to model's weights and biases-
    optimizer.apply_gradients(zip(grad_mask_mul, model.trainable_variables))

    # Compute accuracy-
    train_loss(loss)
    train_accuracy(y, y_pred)

    return None
</code>```

In the code, "mask_model" is a mask which is either 0 or 1. The use of "mask_model" is to control which parameters are trained (since, 0 * gradient descent = 0).

My question is, I am using "grad_mask_mul" list variable inside "train_one_step()" TensorFlow decorated function. Can this cause any problems, such as:

ValueError: tf.function-decorated function tried to create variables
  on non-first call.

Or do you guys see some problem of using a list variable inside a tensorflow decorated function?

Thanks!

答:
In case people are still getting the error

ValueError: tf.function-decorated function tried to create variables
on non-first call.

but are unsure what is going on. The tensorflow team has updated the "function" guide around Feb 2021 (see https://github.com/tensorflow/tensorflow/issues/36574):

See the updated guide, particularly, see the "creating tf variables" section: https://www.tensorflow.org/guide/function#creating_tfvariables

Basically, what the OP needs to ensure is:

In the very first call to the function'ized train_step, all tf.Variable's are created once, and no new tf.Variables are ever created in any of the models or optimizers in a subsequent (i.e. non first) call to train_one_step.

Likely, you have sent into train_one_step a new unbuilt version of model or mask_model, and tensorflow is trying to build it (i.e. make new tf.Variable's), but train_one_step was already called before as a tf.function.

The current (updated) guide explains how to address such issues.

Title: TensorFlow 2 tf.function decorator

Body:
I have TensorFlow 2.0 and Python 3.7.5.

I have written the following code for performing mini-batch gradient descent which is:

@tf.function
def train_one_step(model, mask_model, optimizer, x, y):
    '''
    Function to compute one step of gradient descent optimization
    '''
    with tf.GradientTape() as tape:
        # Make predictions using defined model-
        y_pred = model(x)

        # Compute loss-
        loss = loss_fn(y, y_pred)

    # Compute gradients wrt defined loss and weights and biases-
    grads = tape.gradient(loss, model.trainable_variables)

    # type(grads)
    # list

    # List to hold element-wise multiplication between-
    # computed gradient and masks-
    grad_mask_mul = []

    # Perform element-wise multiplication between computed gradients and masks-
    for grad_layer, mask in zip(grads, mask_model.trainable_weights):
        grad_mask_mul.append(tf.math.multiply(grad_layer, mask))

    # Apply computed gradients to model's weights and biases-
    optimizer.apply_gradients(zip(grad_mask_mul, model.trainable_variables))

    # Compute accuracy-
    train_loss(loss)
    train_accuracy(y, y_pred)

    return None

In the code, "mask_model" is a mask which is either 0 or 1. The use of "mask_model" is to control which parameters are trained (since, 0 * gradient descent = 0).

My question is, I am using "grad_mask_mul" list variable inside "train_one_step()" TensorFlow decorated function. Can this cause any problems, such as:

ValueError: tf.function-decorated function tried to create variables
  on non-first call.

Or do you guys see some problem of using a list variable inside a tensorflow decorated function?

Thanks!


问:
Use registerBean() to register multiple beans of same type
I'm reading Spring Start Here (screenshot attached). The author says it's possible to add multiple beans of the same type to the context using context.registerBean(). I tried adding two Parrots to the context using the following code. The print statements are there to verify that there are two calls of context.registerBean(). Initially, I tried adding the beans like so and still only one Parrot was added.

```<code>for (Parrot p : parrots) {
        context.registerBean(Parrot.class, parrotSupplier);
    }
</code>```

I'm confused by the results of running this code, as only one bean is registered.
How can I add multiple beans of the same type using AnnotationConfigApplicationContext.registerBean()?

Results of running main

```<code>Kiki
Kiki
Iteration!
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.event.internalEventListenerFactory
org.springframework.context.event.internalEventListenerProcessor
parrot
projectConfig
</code>```

Main class

```<code>package main;

import config.ProjectConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.Arrays;
import java.util.function.Supplier;

public class Main {
    public static void main(String args[]) {
        var context = new AnnotationConfigApplicationContext(ProjectConfig.class);

        Parrot x = new Parrot();
        x.setName("Kiki");

        Parrot y = new Parrot();
        y.setName("Kiki");

        Parrot[] parrots = new Parrot[]{x,y};

        Iterator<Parrot> parrotIterator = Arrays.asList(parrots).iterator();

        Supplier<Parrot> parrotSupplier = () -> {
        if (parrotIterator.hasNext()) System.out.println("Iteration!");
        return parrotIterator.next();
    };

        for (Parrot p : parrots) {
            System.out.println(p.getName());
            context.registerBean(Parrot.class, parrotSupplier);
        }

        Parrot p = context.getBean(Parrot.class);
        Arrays.asList(context.getBeanDefinitionNames()).stream().sorted().forEach(System.out::println);
    }
}
</code>```

Parrot class

```<code>public class Parrot {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
</code>```

ProjectConfig class

```<code>public class ProjectConfig {
}
</code>```

page 56 of Spring Start Here

答:
You can't register two beans with the same name and the same type, because then there's no way for Spring to distinguish between them.  How would Spring ever know, for example, which one to inject in a particular situation?  You can qualify injections of a particular type by the bean name, but only if beans of the same type have different names.

If you don't supply a name, Spring computes one from the type of the object.  So in your case, you're attempting to register two beans with both the same type and the same name.

I ran your example, and for me it doesn't even run.  I get an error:

```<code>A bean with that name has already been defined and overriding is disabled.
</code>```

There's an overload of registerBean that takes the same two params as the one you're calling, but takes a third name parameter.  I changed your code slightly to use this version and to pass two different names:

```<code>boolean first = true;
for (Parrot p : parrots) {
    System.out.println(p.getName());
    context.registerBean(first? "first" : "second", Parrot.class, parrotSupplier);
    first = false;
}
</code>```

This version of the code works without throwing an error.  I assume that since it refused to do so before, it is now registering both beans.

UPDATE: Reading that error message again, I wondered if maybe you can't register two beans with the same name even if they have different types. It turns out that this is true.  Every Spring bean has to have a unique name.  Since the name is computed from the type of the object if not specified, you can register one bean of any particular type without specifying a name.

Body:
I'm reading Spring Start Here (screenshot attached). The author says it's possible to add multiple beans of the same type to the context using context.registerBean(). I tried adding two Parrots to the context using the following code. The print statements are there to verify that there are two calls of context.registerBean(). Initially, I tried adding the beans like so and still only one Parrot was added.

for (Parrot p : parrots) {
        context.registerBean(Parrot.class, parrotSupplier);
    }

I'm confused by the results of running this code, as only one bean is registered.
How can I add multiple beans of the same type using AnnotationConfigApplicationContext.registerBean()?

Results of running main

Kiki
Kiki
Iteration!
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.event.internalEventListenerFactory
org.springframework.context.event.internalEventListenerProcessor
parrot
projectConfig

Main class

package main;

import config.ProjectConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.Arrays;
import java.util.function.Supplier;

public class Main {
    public static void main(String args[]) {
        var context = new AnnotationConfigApplicationContext(ProjectConfig.class);

        Parrot x = new Parrot();
        x.setName("Kiki");

        Parrot y = new Parrot();
        y.setName("Kiki");

        Parrot[] parrots = new Parrot[]{x,y};

        Iterator<Parrot> parrotIterator = Arrays.asList(parrots).iterator();

        Supplier<Parrot> parrotSupplier = () -> {
        if (parrotIterator.hasNext()) System.out.println("Iteration!");
        return parrotIterator.next();
    };

        for (Parrot p : parrots) {
            System.out.println(p.getName());
            context.registerBean(Parrot.class, parrotSupplier);
        }

        Parrot p = context.getBean(Parrot.class);
        Arrays.asList(context.getBeanDefinitionNames()).stream().sorted().forEach(System.out::println);
    }
}

Parrot class

public class Parrot {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

ProjectConfig class

public class ProjectConfig {
}

page 56 of Spring Start Here

Body:
You can't register two beans with the same name and the same type, because then there's no way for Spring to distinguish between them.  How would Spring ever know, for example, which one to inject in a particular situation?  You can qualify injections of a particular type by the bean name, but only if beans of the same type have different names.

If you don't supply a name, Spring computes one from the type of the object.  So in your case, you're attempting to register two beans with both the same type and the same name.

I ran your example, and for me it doesn't even run.  I get an error:

A bean with that name has already been defined and overriding is disabled.

There's an overload of registerBean that takes the same two params as the one you're calling, but takes a third name parameter.  I changed your code slightly to use this version and to pass two different names:

boolean first = true;
for (Parrot p : parrots) {
    System.out.println(p.getName());
    context.registerBean(first? "first" : "second", Parrot.class, parrotSupplier);
    first = false;
}

This version of the code works without throwing an error.  I assume that since it refused to do so before, it is now registering both beans.

UPDATE: Reading that error message again, I wondered if maybe you can't register two beans with the same name even if they have different types. It turns out that this is true.  Every Spring bean has to have a unique name.  Since the name is computed from the type of the object if not specified, you can register one bean of any particular type without specifying a name.


问:
How do I run a Windows installer and get a succeed/fail value in PowerShell?
I would like to install a set of applications: .NET 4, IIS 7 PowerShell snap-ins, ASP.NET MVC 3, etc. How do I get the applications to install and return a value that determines if the installation was successful or not?</p>

答:
These answers all seem either overly complicated or not complete enough. Running an installer in the PowerShell console has a few problems. An MSI is run in the Windows subsystem, so you can't just invoke them (Invoke-Expression or &). Some people claim to get those commands to work by piping to Out-Null or Out-Host, but I have not observed that to work.

The method that works for me is Start-Process with the silent installation parameters to msiexec.

```<code>$list =
@(
    "/I `"$msi`"",                     # Install this MSI
    "/QN",                             # Quietly, without a UI
    "/L*V `"$ENV:TEMP\$name.log`""     # Verbose output to this log
)

Start-Process -FilePath "msiexec" -ArgumentList $list -Wait
</code>```

You can get the exit code from the Start-Process command and inspect it for pass/fail values. (and here is the exit code reference)

```<code>$p = Start-Process -FilePath "msiexec" -ArgumentList $list -Wait -PassThru

if($p.ExitCode -ne 0)
{
    throw "Installation process returned error code: $($p.ExitCode)"
}
</code>```

Body:
These answers all seem either overly complicated or not complete enough. Running an installer in the PowerShell console has a few problems. An MSI is run in the Windows subsystem, so you can't just invoke them (Invoke-Expression or &). Some people claim to get those commands to work by piping to Out-Null or Out-Host, but I have not observed that to work.

The method that works for me is Start-Process with the silent installation parameters to msiexec.

$list =
@(
    "/I `"$msi`"",                     # Install this MSI
    "/QN",                             # Quietly, without a UI
    "/L*V `"$ENV:TEMP\$name.log`""     # Verbose output to this log
)

Start-Process -FilePath "msiexec" -ArgumentList $list -Wait

You can get the exit code from the Start-Process command and inspect it for pass/fail values. (and here is the exit code reference)

$p = Start-Process -FilePath "msiexec" -ArgumentList $list -Wait -PassThru

if($p.ExitCode -ne 0)
{
    throw "Installation process returned error code: $($p.ExitCode)"
}


问:
How to make a CSS transition loop once?
I am trying to make some text fade to a new colour and then back to it's original colour.

```<code>#sidebar2:target .phonenumber {
    -o-transition:0.7s;
    -ms-transition:0.7s;
    -moz-transition:0.7s;
    -webkit-transition:0.7s;
    transition:0.7s;
    color: yellow;
}
</code>```

Currently it just goes to the new colour and stays like that. How can I adapt this code so that is does what I want? Any help is appreciated!

EDIT:

I am using :target so that when a user clicks on a same page link, the part of the text that I'm linking to is highlighted. I would like the text to fade to a different colour and then back again

答:
8 years late, but there is a "psudo-selector" for visited links: :visited

(It's actually a pseudo class)
Just modify the attributes you want from there. No need for animation and transitions.

Title: How to make a CSS transition loop once?

Body:
I am trying to make some text fade to a new colour and then back to it's original colour.

#sidebar2:target .phonenumber {
    -o-transition:0.7s;
    -ms-transition:0.7s;
    -moz-transition:0.7s;
    -webkit-transition:0.7s;
    transition:0.7s;
    color: yellow;
}

Currently it just goes to the new colour and stays like that. How can I adapt this code so that is does what I want? Any help is appreciated!

EDIT:

I am using :target so that when a user clicks on a same page link, the part of the text that I'm linking to is highlighted. I would like the text to fade to a different colour and then back again


问:
How do I get a random line from a file and send it as a discord bot?
I'm new to python and I'm trying to get a discord bot to send a random line from a text file. So far i have this code, but it wont send when i send the command in the server.</p>
```<code>import os
import discord
import requests
import random

from discord.ext import commands
client = discord.Client()

@client.event
async def on_ready():
  print('online {0.user}'.format(client))

bot = discord.ext.commands.Bot(command_prefix = "$");

@bot.command(name='filetxt')

async def filetxtgetter(ctx):
  lines = open('file.txt').read().splitlines()
  file = random.choice(lines)
  await ctx.send(file)

client.run(os.environ['token'])
</code>```

答:
@bot.command()
async def filetxtgetter(ctx):
    f=open('file.txt')
    lines=f.readlines()

    value = random.choice(lines)
    random_line = (value.removesuffix('\n'))

    await ctx.send(random_line)
```

This should solve your question.

Body:
I'm new to python and I'm trying to get a discord bot to send a random line from a text file. So far i have this code, but it wont send when i send the command in the server.

import os
import discord
import requests
import random

from discord.ext import commands
client = discord.Client()

@client.event
async def on_ready():
  print('online {0.user}'.format(client))

bot = discord.ext.commands.Bot(command_prefix = "$");

@bot.command(name='filetxt')

async def filetxtgetter(ctx):
  lines = open('file.txt').read().splitlines()
  file = random.choice(lines)
  await ctx.send(file)

client.run(os.environ['token'])

Body:
@bot.command()
async def filetxtgetter(ctx):
    f=open('file.txt')
    lines=f.readlines()

    value = random.choice(lines)
    random_line = (value.removesuffix('\n'))

    await ctx.send(random_line)

This should solve your question.


问:
jQuery index on each function
I am curious why I need this index

```<code>$(document).ready(function() {
        $(".divToggle").each(function(index){
            var buttonId = $(this)[0].attributes["id"].value.toString();
            var idParts = buttonId.split('_');
            var uniquePart = idParts[0] + "_" + idParts[1] + "_" + "divContentPanel";
            $(this).click(function() {
                 $("#" + uniquePart).toggle("slow");
            });
        });
    });
</code>```

Why do I need the "[0]" in "var buttonId = $(this)[0]…"  Without it, I get an attributes["id"] is null error..

答:
Use this instead

```<code>var buttonId = this.id;
</code>```

or jQuery way

```<code>var buttonId = $(this).attr("id");
</code>```

Title: jQuery index on each function

Body:
I am curious why I need this index

$(document).ready(function() {
        $(".divToggle").each(function(index){
            var buttonId = $(this)[0].attributes["id"].value.toString();
            var idParts = buttonId.split('_');
            var uniquePart = idParts[0] + "_" + idParts[1] + "_" + "divContentPanel";
            $(this).click(function() {
                 $("#" + uniquePart).toggle("slow");
            });
        });
    });

Why do I need the "[0]" in "var buttonId = $(this)[0]…"  Without it, I get an attributes["id"] is null error..

Body:
Use this instead

var buttonId = this.id;

or jQuery way

var buttonId = $(this).attr("id");


问:
How do i create powershell shortcut that closes automatically
I'm using a shortcut with a powershell command line for shutting down the monitor.
It does what it has to do except automatically close the powershell window after the rule is executed.

How do I change the command line so that the window closes automatically?

This is the command line I'm using:

```<code>    powershell.exe -Command "(Add-Type '[DllImport(\"user32.dll\")]public static extern int SendMessage(int hWnd,int hMsg,int wParam,int lParam);' -Name a -Pas)::SendMessage(-1,0x0112,0xF170,2)"
</code>```

答:
Solution 1: Add '; exit' after the first command, telling PowerShell there is an additional command.

```<code>powershell.exe -Command "(Add-Type '[DllImport(\"user32.dll\")]public static extern int SendMessage(int hWnd,int hMsg,int wParam,int lParam);' -Name a -Pas)::SendMessage(-1,0x0112,0xF170,2)"; exit
</code>```

Solution 2: If the first example does not work you can tell cmd to pass your command into a PowerShell process, if the shortcut is not acting properly.

```<code>C:\Windows\System32\cmd.exe /c powershell.exe -Command "(Add-Type '[DllImport(\"user32.dll\")]public static extern int SendMessage(int hWnd,int hMsg,int wParam,int lParam);' -Name a -Pas)::SendMessage(-1,0x0112,0xF170,2)" & exit
</code>```

Body:
I'm using a shortcut with a powershell command line for shutting down the monitor.
It does what it has to do except automatically close the powershell window after the rule is executed.

How do I change the command line so that the window closes automatically?

This is the command line I'm using:

    powershell.exe -Command "(Add-Type '[DllImport(\"user32.dll\")]public static extern int SendMessage(int hWnd,int hMsg,int wParam,int lParam);' -Name a -Pas)::SendMessage(-1,0x0112,0xF170,2)"

Body:
Solution 1: Add '; exit' after the first command, telling PowerShell there is an additional command.

powershell.exe -Command "(Add-Type '[DllImport(\"user32.dll\")]public static extern int SendMessage(int hWnd,int hMsg,int wParam,int lParam);' -Name a -Pas)::SendMessage(-1,0x0112,0xF170,2)"; exit

Solution 2: If the first example does not work you can tell cmd to pass your command into a PowerShell process, if the shortcut is not acting properly.

C:\Windows\System32\cmd.exe /c powershell.exe -Command "(Add-Type '[DllImport(\"user32.dll\")]public static extern int SendMessage(int hWnd,int hMsg,int wParam,int lParam);' -Name a -Pas)::SendMessage(-1,0x0112,0xF170,2)" & exit


问:
Material-UI Dialog Reusable Component Not Working but no error in the console and app does not crash
This is my reusable component:

```<code>import {
  Dialog,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Divider,
  Button,
  DialogActions,
} from "@mui/material";

const Modal = ({ title, subtitle, children, isOpen, handleClose }) => {
  return (
    <Dialog open={isOpen} onClose={handleClose}>
      <DialogTitle>{title}</DialogTitle>
      <DialogContent>
        <DialogContentText>{subtitle}</DialogContentText>
        <Divider />
        {children}
      </DialogContent>
      <DialogActions>
        <Button onClick={handleClose} color="error">
          Close
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default Modal;
</code>```

Parent component where I use this here:

```<code>const [isOpen, setisOpen] = useState(false);
  const [isOpenDialog, setIsOpenDialog] = useState(false);

  const handleDialogOpen = () => {
    setisOpen(true);
  };

  const handleDialogClose = () => {
    setisOpen(false);
  };

  const handleOpen = () => {
    setIsOpenDialog(true);
  };

  const handleClose = () => {
    setIsOpenDialog(false);
  };

 <Modal
        title="confirmation"
        isOpen={isOpen}
        children={sample}
        handleClose={handleDialogClose}
      />

         <Button
              color="error"
              onClick={
                () => handleDialogOpen}
            >
              Delete
            </Button>
</code>```

It does not show any error in the console and the app does not crash. How can I fix this? Also how can I add a button where the user can say yes since at the moment the modal only have a buttin to close it

答:
There's a lot to unpack here. Here's a solution:

```<code>import {
 Dialog,
 DialogContent,
 DialogContentText,
 DialogTitle,
 Divider,
 Button,
 DialogActions
} from "@mui/material";

const Modal = ({ title, subtitle, children, isOpen, handleClose }) => {
const handleConfirm = () => {
  alert("You Agreed!");
  handleClose();
};
 return (
   <Dialog open={isOpen} onClose={handleClose}>
    <DialogTitle>{title}</DialogTitle>
     <DialogContent>
      <DialogContentText>{subtitle}</DialogContentText>
       <Divider />
        {children}
       </DialogContent>
      <DialogActions>
        <Button onClick={handleClose} color="error">
          Cancel
        </Button>
        <Button onClick={handleConfirm} color="primary">
          Agree
        </Button>
      </DialogActions>
   </Dialog>
  );
};

export default Modal;
</code>```

Here's the parent:

```<code>import Modal from "./modal";
import { useState } from "react";
import { Button } from "@mui/material";

export default function App() {
 const [isOpen, setisOpen] = useState(false);

 const handleOpen = () => {
  setisOpen(true);
 };

 const handleClose = () => {
  setisOpen(false);
 };
   return (
     <div className="App">
     <Modal title="confirmation" isOpen={isOpen} handleClose={handleClose} />
     <Button color="primary" onClick={handleOpen}>
       I Agree
     </Button>
    </div>
 );
}
</code>```

Here's the sandbox:

Body:
This is my reusable component:

import {
  Dialog,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Divider,
  Button,
  DialogActions,
} from "@mui/material";

const Modal = ({ title, subtitle, children, isOpen, handleClose }) => {
  return (
    <Dialog open={isOpen} onClose={handleClose}>
      <DialogTitle>{title}</DialogTitle>
      <DialogContent>
        <DialogContentText>{subtitle}</DialogContentText>
        <Divider />
        {children}
      </DialogContent>
      <DialogActions>
        <Button onClick={handleClose} color="error">
          Close
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default Modal;

Parent component where I use this here:

const [isOpen, setisOpen] = useState(false);
  const [isOpenDialog, setIsOpenDialog] = useState(false);

  const handleDialogOpen = () => {
    setisOpen(true);
  };

  const handleDialogClose = () => {
    setisOpen(false);
  };

  const handleOpen = () => {
    setIsOpenDialog(true);
  };

  const handleClose = () => {
    setIsOpenDialog(false);
  };

 <Modal
        title="confirmation"
        isOpen={isOpen}
        children={sample}
        handleClose={handleDialogClose}
      />

         <Button
              color="error"
              onClick={
                () => handleDialogOpen}
            >
              Delete
            </Button>

It does not show any error in the console and the app does not crash. How can I fix this? Also how can I add a button where the user can say yes since at the moment the modal only have a buttin to close it

Body:
There's a lot to unpack here. Here's a solution:

import {
 Dialog,
 DialogContent,
 DialogContentText,
 DialogTitle,
 Divider,
 Button,
 DialogActions
} from "@mui/material";

const Modal = ({ title, subtitle, children, isOpen, handleClose }) => {
const handleConfirm = () => {
  alert("You Agreed!");
  handleClose();
};
 return (
   <Dialog open={isOpen} onClose={handleClose}>
    <DialogTitle>{title}</DialogTitle>
     <DialogContent>
      <DialogContentText>{subtitle}</DialogContentText>
       <Divider />
        {children}
       </DialogContent>
      <DialogActions>
        <Button onClick={handleClose} color="error">
          Cancel
        </Button>
        <Button onClick={handleConfirm} color="primary">
          Agree
        </Button>
      </DialogActions>
   </Dialog>
  );
};

export default Modal;

Here's the parent:

import Modal from "./modal";
import { useState } from "react";
import { Button } from "@mui/material";

export default function App() {
 const [isOpen, setisOpen] = useState(false);

 const handleOpen = () => {
  setisOpen(true);
 };

 const handleClose = () => {
  setisOpen(false);
 };
   return (
     <div className="App">
     <Modal title="confirmation" isOpen={isOpen} handleClose={handleClose} />
     <Button color="primary" onClick={handleOpen}>
       I Agree
     </Button>
    </div>
 );
}

Here's the sandbox:


问:
Find the number of week rows in a month
Given the start day (Wednesday = 4), and the number of days in a month (31), what is an elegant way to find the number of week rows a calendar of the month would require?

For the current month (startDay = 4, daysInMonth = 31), it would be 5. But if daysInMonth = 33, it would be 6 rows.

This doesn't quite work:

```<code>int numRows = (startDay+daysInMonth)/daysInWeek;
if ((startDay+daysInMonth) % daysInWeek != 0) {
    numRows++;
}
</code>```

答:
Here is a generic way to do it in C#, which works by counting the Saturdays in a month and then adding one if there's any left over days. Since it literally reads a calendar like a human would, there's no strange calendar arithmetic needed. It's all offloaded to the C# DateTime code, we just piggyback off that.

I chose Saturday because most calendars go Sunday (far left) to Saturday (far right). You can just choose a different day if you wish to denote the end of a week.

public static int RowsForMonth(int year, int month)
{
     int days = DateTime.DaysInMonth(year, month);
     int rows = 0;
     int i = 0;
     while(i < days)
     {
          i++;
          DateTime date = new DateTime(year, month, i);
          if (date.DayOfWeek == DayOfWeek.Saturday || i == days)
               rows++;
     }
     return rows;
}
```
```Jan 2022 -> 6
Feb 2022 -> 5
Mar 2022 -> 5
```

Title: Find the number of week rows in a month

Body:
Given the start day (Wednesday = 4), and the number of days in a month (31), what is an elegant way to find the number of week rows a calendar of the month would require?

For the current month (startDay = 4, daysInMonth = 31), it would be 5. But if daysInMonth = 33, it would be 6 rows.

This doesn't quite work:

int numRows = (startDay+daysInMonth)/daysInWeek;
if ((startDay+daysInMonth) % daysInWeek != 0) {
    numRows++;
}

Body:
Here is a generic way to do it in C#, which works by counting the Saturdays in a month and then adding one if there's any left over days. Since it literally reads a calendar like a human would, there's no strange calendar arithmetic needed. It's all offloaded to the C# DateTime code, we just piggyback off that.

I chose Saturday because most calendars go Sunday (far left) to Saturday (far right). You can just choose a different day if you wish to denote the end of a week.

public static int RowsForMonth(int year, int month)
{
     int days = DateTime.DaysInMonth(year, month);
     int rows = 0;
     int i = 0;
     while(i < days)
     {
          i++;
          DateTime date = new DateTime(year, month, i);
          if (date.DayOfWeek == DayOfWeek.Saturday || i == days)
               rows++;
     }
     return rows;
}

Jan 2022 -> 6
Feb 2022 -> 5
Mar 2022 -> 5


问:
How would you solve this tricky SQL problem?
Say you have a table layout like the following:

couses:

```<code>id (INT),
courseName (VARCHAR)
</code>```

instructors:

```<code>id (INT),
courseId(INT),
instructor(VARCHAR)
</code>```

Create a query which will print the all the courses and if one instructor is present display their name, if two instructors are present print both of their names on the row in sorted order, if more than two instructors are present instead of the instructors names display “committee“.

For instance your output would look something like this

```
    courseId    instructor1        instructor2
    0           Edward Yourdon
    1           Edward Dijkstra    Nicholas Wirth
    2           Comittee
```

Note: Taken from a questionnaire on TheDailyWtf. Not a homework question.

答:
What you are looking for is a "Pivot table" or "Cross-tab" report.  They are available using normal SQL:

http://en.wikibooks.org/wiki/MySQL/Pivot_table

There are likely other questions here on SO with more information as well.  Check out the information here, which shows how you might do it in SQL, or in the application logic (through successive queries):

https://stackoverflow.com/search?q=pivot+table

OwnerDisplayName: Click Upvote

ContentLicense: CC BY-SA 2.5

Body:
Say you have a table layout like the following:

couses:

id (INT),
courseName (VARCHAR)

instructors:

id (INT),
courseId(INT),
instructor(VARCHAR)

Create a query which will print the all the courses and if one instructor is present display their name, if two instructors are present print both of their names on the row in sorted order, if more than two instructors are present instead of the instructors names display “committee“.

For instance your output would look something like this

    courseId    instructor1        instructor2
    0           Edward Yourdon
    1           Edward Dijkstra    Nicholas Wirth
    2           Comittee

Note: Taken from a questionnaire on TheDailyWtf. Not a homework question.

OwnerDisplayName: Adam Davis

LastEditorDisplayName: Rich B


问:
std::auto_ptr<T> Usage
I've read a reasonable amount in decent textbooks about the auto_ptr class.  While I understand what it is, and how it gets you around the problem of getting exceptions in places like constructors, I am having trouble figuring out when someone would actually use it.

An auto_ptr can only hold a single type (no array new[] initialization is supported).  It changes ownership when you pass it into functions or try and duplicate it (it's not a reference counting smart pointer).

What is a realistic usage scenario for this class give its limitations?  It seems like most of the textbook examples of its use are reaching because there isn't even a reason to be using a pointer over a stack variable in most of the cases...

Anyway, I'll stop my rant - but if you can provide a short example/description or a link to a good usage scenario for this I'd be grateful.  I just want to know where I should use it in practice in case I come across the situation - I like to practice what I learn so I remember it.

答:
I'll give you a short example for a good usage. Consider this:

```<code>auto_ptr<SomeResource> some_function() {
    auto_ptr<SomeResource> my_ptr = get_the_resource();

    function_that_throws_an_exception();

    return my_ptr;
}
</code>```

The function that raises an exception would normally cause your pointer to be lost, and the object pointed to would not be deleted. With the auto_ptr this can't happen, since it is destroyed when it leaves the frame it was created, if it hasn't been assigned (for example with return).

Title: std::auto_ptr<T> Usage

Body:
I'll give you a short example for a good usage. Consider this:

auto_ptr<SomeResource> some_function() {
    auto_ptr<SomeResource> my_ptr = get_the_resource();

    function_that_throws_an_exception();

    return my_ptr;
}

The function that raises an exception would normally cause your pointer to be lost, and the object pointed to would not be deleted. With the auto_ptr this can't happen, since it is destroyed when it leaves the frame it was created, if it hasn't been assigned (for example with return).


问:
ArrayList vs HashSet
I was working on this problem https://cses.fi/problemset/task/1660, and here's my code:

```<code>import java.util.*;
public class SubarraySumsI {

public static void main(String[] args) {
    Scanner in = new Scanner (System.in);
    int N = in.nextInt();
    int X = in.nextInt();

    ArrayList <Long> prefix = new ArrayList <Long> ();
    int count = 0;
    prefix.add(0l);
    long prefixsum = 0;
    for (int a = 0; a < N; a++) {
        prefixsum += in.nextInt();
        prefix.add(prefixsum);

        if (prefix.contains(prefixsum - X)) {
            count++;
        }
    }

    System.out.println(count);
    in.close();
  }
}
</code>```

I noticed that on a lot of the test cases, it was really slow. However, if I just change prefix from an ArrayList to a HashSet, it suddenly becomes a lot faster.

I'm not that experienced with using Sets and HashSets yet, so can someone explain what the difference is between ArrayList and HashSet?

答:
You can read in here the difference between Set and Array

https://www.geeksforgeeks.org/difference-between-list-set-and-map-in-java/

Title: ArrayList vs HashSet

Body:
I was working on this problem https://cses.fi/problemset/task/1660, and here's my code:

import java.util.*;
public class SubarraySumsI {

public static void main(String[] args) {
    Scanner in = new Scanner (System.in);
    int N = in.nextInt();
    int X = in.nextInt();

    ArrayList <Long> prefix = new ArrayList <Long> ();
    int count = 0;
    prefix.add(0l);
    long prefixsum = 0;
    for (int a = 0; a < N; a++) {
        prefixsum += in.nextInt();
        prefix.add(prefixsum);

        if (prefix.contains(prefixsum - X)) {
            count++;
        }
    }

    System.out.println(count);
    in.close();
  }
}

I noticed that on a lot of the test cases, it was really slow. However, if I just change prefix from an ArrayList to a HashSet, it suddenly becomes a lot faster.

I'm not that experienced with using Sets and HashSets yet, so can someone explain what the difference is between ArrayList and HashSet?


问:
How to resolve circular dependence in the following case?
```<code>#include <iostream>
#include <set>

struct ContainerOfA;

struct StructA
{
  StructA(ContainerOfA* ptr) : m_b_ptr(ptr)
  {}

  void CleanMe()
  {
    m_b_ptr->RemoveStructA(this);
    delete this;
  }

  ContainerOfA* m_b_ptr;
};

struct ContainerOfA
{
  void RemoveStructA(StructA *a_ptr)
  {
    m_set_a.erase(a_ptr);
  }

  void RemoveAllStructA()
  {
    for (auto &iter : m_set_a) {
      delete iter;
    }
  }

  std::set<StructA*> m_set_a;
};

int main()
{
    return 0;
}
</code>```

g++ (GCC) 10.2.1 20210130

```<code>test_me.cpp: In member function ‘void StructA::CleanMe()’:
test_me.cpp:13:12: error: invalid use of incomplete type ‘struct ContainerOfA’
   13 |     m_b_ptr->RemoveStructA(this);
      |            ^~
test_me.cpp:4:8: note: forward declaration of ‘struct ContainerOfA’
    4 | struct ContainerOfA;
      |        ^~~~~~~~~~~~
</code>```

I ran into a circular dependency issue and the sample example is shown above.

Question> Is there a way that I can make it work?

Thank you

答:
Just move the problematic code to a point where the class is defined.

```<code>struct StructA
{
  // ...

  void CleanMe();
  // ...
};

struct ContainerOfA
{
  // ...
};

inline StructA::CleanMe()
{
  m_b_ptr->RemoveA(this);
}
</code>```

By the way, that's a real code smell having an object know what container it's part of.  You should try to architect it so that's not necessary.

Body:
#include <iostream>
#include <set>

struct ContainerOfA;

struct StructA
{
  StructA(ContainerOfA* ptr) : m_b_ptr(ptr)
  {}

  void CleanMe()
  {
    m_b_ptr->RemoveStructA(this);
    delete this;
  }

  ContainerOfA* m_b_ptr;
};

struct ContainerOfA
{
  void RemoveStructA(StructA *a_ptr)
  {
    m_set_a.erase(a_ptr);
  }

  void RemoveAllStructA()
  {
    for (auto &iter : m_set_a) {
      delete iter;
    }
  }

  std::set<StructA*> m_set_a;
};

int main()
{
    return 0;
}

g++ (GCC) 10.2.1 20210130

test_me.cpp: In member function ‘void StructA::CleanMe()’:
test_me.cpp:13:12: error: invalid use of incomplete type ‘struct ContainerOfA’
   13 |     m_b_ptr->RemoveStructA(this);
      |            ^~
test_me.cpp:4:8: note: forward declaration of ‘struct ContainerOfA’
    4 | struct ContainerOfA;
      |        ^~~~~~~~~~~~

I ran into a circular dependency issue and the sample example is shown above.

Question> Is there a way that I can make it work?

Thank you

Body:
Just move the problematic code to a point where the class is defined.

struct StructA
{
  // ...

  void CleanMe();
  // ...
};

struct ContainerOfA
{
  // ...
};

inline StructA::CleanMe()
{
  m_b_ptr->RemoveA(this);
}

By the way, that's a real code smell having an object know what container it's part of.  You should try to architect it so that's not necessary.


问:
How to create a function "my range" In python which works same as built in range function?
How to create a function "my range" In python which works same as built in range?

My attempt:

```<code>def myrange(end, start=1, step=1):
    if step == 1:
        print("(%s,%s)" % (start, end))
    else:
        print("(%s,%s,%s)" % (start, end, step))

b = myrange(10)
print(b)
</code>```

But this does not work when I use for loop, please help how to create such user defined function.

答:
#i created my own range function
def my_range(min='',max='',step=''):</p>
```<code>sonlar=[]

if min!='' and max!='' and step=='':
    while min<max:
        sonlar.append(min)
        min+=1
elif min!='' and max!='' and step!='':

    while min<max:
        sonlar.append(min)
        min+=step
elif min!='' and max=='' and step=='':
    x=0
    while min>x:
        sonlar.append(x)
        x+=1
return sonlar
</code>```

Body:
How to create a function "my range" In python which works same as built in range?

My attempt:

def myrange(end, start=1, step=1):
    if step == 1:
        print("(%s,%s)" % (start, end))
    else:
        print("(%s,%s,%s)" % (start, end, step))

b = myrange(10)
print(b)

But this does not work when I use for loop, please help how to create such user defined function.

Body:
#i created my own range function
def my_range(min='',max='',step=''):

sonlar=[]

if min!='' and max!='' and step=='':
    while min<max:
        sonlar.append(min)
        min+=1
elif min!='' and max!='' and step!='':

    while min<max:
        sonlar.append(min)
        min+=step
elif min!='' and max=='' and step=='':
    x=0
    while min>x:
        sonlar.append(x)
        x+=1
return sonlar


问:
Icon toggle disappears on refresh
I'm trying to toggle between a moon icon and a sun icon on a dark mode project. The original javascript code was simply a button that switched from day mode to dark mode. After some research, I ended up with the following code, which "kinda" works but is sketchy; it switches from day mode to dark mode and the icon toggles from moon to sun BUT, when I come back to the page after setting my preference as dark mode (or refreshing the page in dark mode), the icon disappears.

```<code>const btn = document.querySelector(".btn-mode");
const icon = document.querySelector(".mode");
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");

const currentTheme = localStorage.getItem("theme");
if (currentTheme == "dark") {
  document.body.classList.toggle("dark-theme");
  icon.classList.toggle("fa-sun-o");
} else if (currentTheme == "light") {
  document.body.classList.toggle("light-theme");
  icon.classList.toggle("fa-moon-o");
}

btn.addEventListener("click", function () {
  if (prefersDarkScheme.matches) {
    document.body.classList.toggle("light-theme");
    var theme = document.body.classList.contains("light-theme")
      ? "light"
      : "dark";
    icon.classList.toggle("fa-sun-o");
  } else {
    document.body.classList.toggle("dark-theme");
    var theme = document.body.classList.contains("dark-theme")
      ? "dark"
      : "light";
    icon.classList.toggle("fa-moon-o");
  }
  localStorage.setItem("theme", theme);
});
</code>```

Any idea what I am missing here?

I created a codepen to show the issue

答:
As others have said, you were using a toggle method which was producing inconsistent behaviour.

I refactored the code a bit:

```<code>const btn = document.querySelector(".btn-mode");
const icon = document.querySelector(".mode");
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");

const makeDark = () => {
  document.body.classList.add("dark-theme");
  document.body.classList.remove("light-theme");
  icon.classList.add("fa-moon-o");
  icon.classList.remove("fa-sun-o");
}

const makeLight = () => {
  document.body.classList.remove("dark-theme");
  document.body.classList.add("light-theme");
  icon.classList.remove("fa-moon-o");
  icon.classList.add("fa-sun-o");
}

const setPageThemeTo = (newLightDarkState) => {
  newLightDarkState == "dark" ? makeDark() : makeLight();
}

let currentTheme = localStorage.getItem("theme");

if (!currentTheme) {
  currentTheme = prefersDarkScheme.matches ? 'dark' : 'light';
}

setPageThemeTo(currentTheme);

btn.addEventListener("click", function () {
  currentTheme = currentTheme == "dark" ? "light" : "dark";
  localStorage.setItem("theme", currentTheme);
  setPageThemeTo(currentTheme);
});
</code>```

You could probably DRY it up further! :)

Title: Icon toggle disappears on refresh

Body:
I'm trying to toggle between a moon icon and a sun icon on a dark mode project. The original javascript code was simply a button that switched from day mode to dark mode. After some research, I ended up with the following code, which "kinda" works but is sketchy; it switches from day mode to dark mode and the icon toggles from moon to sun BUT, when I come back to the page after setting my preference as dark mode (or refreshing the page in dark mode), the icon disappears.

const btn = document.querySelector(".btn-mode");
const icon = document.querySelector(".mode");
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");

const currentTheme = localStorage.getItem("theme");
if (currentTheme == "dark") {
  document.body.classList.toggle("dark-theme");
  icon.classList.toggle("fa-sun-o");
} else if (currentTheme == "light") {
  document.body.classList.toggle("light-theme");
  icon.classList.toggle("fa-moon-o");
}

btn.addEventListener("click", function () {
  if (prefersDarkScheme.matches) {
    document.body.classList.toggle("light-theme");
    var theme = document.body.classList.contains("light-theme")
      ? "light"
      : "dark";
    icon.classList.toggle("fa-sun-o");
  } else {
    document.body.classList.toggle("dark-theme");
    var theme = document.body.classList.contains("dark-theme")
      ? "dark"
      : "light";
    icon.classList.toggle("fa-moon-o");
  }
  localStorage.setItem("theme", theme);
});

Any idea what I am missing here?

I created a codepen to show the issue

Body:
As others have said, you were using a toggle method which was producing inconsistent behaviour.

I refactored the code a bit:

const btn = document.querySelector(".btn-mode");
const icon = document.querySelector(".mode");
const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");

const makeDark = () => {
  document.body.classList.add("dark-theme");
  document.body.classList.remove("light-theme");
  icon.classList.add("fa-moon-o");
  icon.classList.remove("fa-sun-o");
}

const makeLight = () => {
  document.body.classList.remove("dark-theme");
  document.body.classList.add("light-theme");
  icon.classList.remove("fa-moon-o");
  icon.classList.add("fa-sun-o");
}

const setPageThemeTo = (newLightDarkState) => {
  newLightDarkState == "dark" ? makeDark() : makeLight();
}

let currentTheme = localStorage.getItem("theme");

if (!currentTheme) {
  currentTheme = prefersDarkScheme.matches ? 'dark' : 'light';
}

setPageThemeTo(currentTheme);

btn.addEventListener("click", function () {
  currentTheme = currentTheme == "dark" ? "light" : "dark";
  localStorage.setItem("theme", currentTheme);
  setPageThemeTo(currentTheme);
});

You could probably DRY it up further! :)


问:
Get AWS Inspector findings report from AWS Inspector in mail
I want to get the AWS Inspector assessment run findings on email.

For that i had configured a SNS topic but the mail i received contains arns(refer pic) :

The json data is non-readable(from pic):

{

"template":"arn:aws:inspector:eu-central-1::target/0-nuQpXxdr/template/0-ZgdD12jw",

"run":"arn:aws:inspector:eu-central-1::target/0-nuQpXxdr/template/0-ZgdD12jw/run/0-xNByk8Qd",

"time":"2022-01-19T12:24:51.348Z",

"finding":"arn:aws:inspector:eu-central-1::target/0-nuQpXxdr/template/0-ZgdD12jw/run/0-xNByk8Qd/finding/0-ZGYFvyQi",

"event":"FINDING_REPORTED",

"target":"arn:aws:inspector:eu-central-1::target/0-nuQpXxdr"

}

REQUIRED: I need a way to get the whole report(pdf/html) or URL of this report and not singular un-readable finding. Is there any way out to do so??

答:
For AWS Inspector Classic:
One way I would do it is by having 2 SNS topics let's call them sns1 and sns2, where sns1 has a lambda function subscribed to it, and sns2 sends emails as notifications.

The lambda function here will receive the JSON, convert it into a readable format and push it sns2.

For AWS Inspector V2 you can get rid of the sns1 topic and replace it with AWS EventBridge for lambda.

Here are some links to help you:

How do I subscribe a Lambda function to an Amazon SNS topic in the same account?

How to Remediate Amazon Inspector Security Findings Automatically

Email notification through SNS and Lambda


问:
How to observe array's new values with combine?
If I have an array:

var arr = [0,1,2]
```
<p>And a Combine publisher for it:</p>
<pre class="lang-swift prettyprint-override"><code>arr.publisher
    .sink { completion in print("Completed with \(completion)")
    } receiveValue: { val in
        print("Received value \(val)")
    }
arr.append(3)
</code>```

Why does it finish right away with:

Received value 0
Received value 1
Received value 2
Completed with finished
```

How can I make Combine execute the code every time I append values to the array?

答:
The publisher method of the array does exactly that - emits every element of the array and then completes, because the array at the time of calling the publisher has a finite number of elements.

If you want to be notified every time the arrays changes (not just when something is appended to it, but on any change) then create a @Published var for the array and attach the observer to it:

```<code>@Published var arr = [1,2,3]

cancellable = $arr
    .sink { completion in print("Completed with \(completion)")
    } receiveValue: { val in
        print("Received value \(val)")
    }

arr.append(4)
</code>```

The output will be:

```<code>Received value [1, 2, 3]
Received value [1, 2, 3, 4]

</code>```

But looks like what you are really looking for is listening to a stream of numbers emitted one at a time. Then define a @Published var of that type and listen to it. You'll get called every time the var changes:

```<code>@Published var value = 1

cancellable = $value
    .sink { completion in print("Completed with \(completion)")
    } receiveValue: { val in
        print("Received value \(val)")
    }

value = 2
value = 3
value = 4
</code>```

The output will be:

```<code>Received value 1
Received value 2
Received value 3
Received value 4

</code>```

Body:
If I have an array:

var arr = [0,1,2]

And a Combine publisher for it:

arr.publisher
    .sink { completion in print("Completed with \(completion)")
    } receiveValue: { val in
        print("Received value \(val)")
    }
arr.append(3)

Why does it finish right away with:

Received value 0
Received value 1
Received value 2
Completed with finished

How can I make Combine execute the code every time I append values to the array?

Body:
The publisher method of the array does exactly that - emits every element of the array and then completes, because the array at the time of calling the publisher has a finite number of elements.

If you want to be notified every time the arrays changes (not just when something is appended to it, but on any change) then create a @Published var for the array and attach the observer to it:

@Published var arr = [1,2,3]

cancellable = $arr
    .sink { completion in print("Completed with \(completion)")
    } receiveValue: { val in
        print("Received value \(val)")
    }

arr.append(4)

The output will be:

Received value [1, 2, 3]
Received value [1, 2, 3, 4]

But looks like what you are really looking for is listening to a stream of numbers emitted one at a time. Then define a @Published var of that type and listen to it. You'll get called every time the var changes:

@Published var value = 1

cancellable = $value
    .sink { completion in print("Completed with \(completion)")
    } receiveValue: { val in
        print("Received value \(val)")
    }

value = 2
value = 3
value = 4

The output will be:

Received value 1
Received value 2
Received value 3
Received value 4


问:
How can I use withRouter in react router v6 for passing props?
Before, you would need to wrap something like this export default withRouter(name of component)  and now it is different in react-router v6.

I have this button where once you clicked this, it will take you to another page including the value inside my tableMeta.rowData[0].
I tried using navigate = useNavigate(), but I do not know how to pass the value of tableMeta.rowData[0]

```<code>   {
      name: "Edit",
      options: {
        customBodyRender: (value, tableMeta, updateValue) => {
          return (
            <Button
              color="success"
               onClick={
            () => navigate("/edit-products")
            // console.log(tableMeta.rowData[0])
          }
            >
              Edit
            </Button>
          );
        },
      },
    },
</code>```

In React-router v6, how can I do this similar to a withRouter before?

答:
It is deprecated. You can recreate it using the hooks version:

```<code>import React from 'react';
import { useLocation, useNavigate, useParams } from 'react-router-dom';

export function withRouter<ComponentProps>(Component: React.FunctionComponent<ComponentProps>) {
    function ComponentWithRouterProp(props: ComponentProps) {
        const location = useLocation();
        const navigate = useNavigate();
        const params = useParams();

        return <Component {...props} router={{ location, navigate, params }} />;
    }

    return ComponentWithRouterProp;
}

</code>```

For more details check this out

Body:
Before, you would need to wrap something like this export default withRouter(name of component)  and now it is different in react-router v6.

I have this button where once you clicked this, it will take you to another page including the value inside my tableMeta.rowData[0].
I tried using navigate = useNavigate(), but I do not know how to pass the value of tableMeta.rowData[0]

   {
      name: "Edit",
      options: {
        customBodyRender: (value, tableMeta, updateValue) => {
          return (
            <Button
              color="success"
               onClick={
            () => navigate("/edit-products")
            // console.log(tableMeta.rowData[0])
          }
            >
              Edit
            </Button>
          );
        },
      },
    },

In React-router v6, how can I do this similar to a withRouter before?

Body:
It is deprecated. You can recreate it using the hooks version:

import React from 'react';
import { useLocation, useNavigate, useParams } from 'react-router-dom';

export function withRouter<ComponentProps>(Component: React.FunctionComponent<ComponentProps>) {
    function ComponentWithRouterProp(props: ComponentProps) {
        const location = useLocation();
        const navigate = useNavigate();
        const params = useParams();

        return <Component {...props} router={{ location, navigate, params }} />;
    }

    return ComponentWithRouterProp;
}

For more details check this out


问:
XML layout android not aligned perfectly in the center
Here is my xml layout code

```<code>    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:id="@+id/titleset"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Orb Runner"
    android:layout_gravity="center"
    android:gravity="center"
    android:layout_marginTop="20dp"
    android:textSize="45sp"
    android:textColor="#FF3366CC"/>

    <TableLayout android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="30dp"
    android:gravity="center"
    android:layout_gravity="center">

    <TableRow android:layout_gravity="center"
    android:gravity="center" android:layout_width="fill_parent">

    <TextView android:id="@+id/newgamebut"
    android:layout_marginRight="5dp"
    android:text="New Game"
    style="@style/Button" android:layout_height="fill_parent" android:layout_width="wrap_content"/>

    <TextView android:id="@+id/newgamebut"
    android:layout_marginLeft="5dp"
    android:text="High Score"
    android:layout_gravity="center"
    style="@style/Button" android:layout_height="fill_parent" android:layout_width="fill_parent"/>

    </TableRow>

    <TableRow android:layout_gravity="center"
    android:gravity="center" android:layout_width="fill_parent">

    <TextView android:id="@+id/newgamebut"
    android:layout_marginRight="5dp"
    android:text="Settings"
    style="@style/Button" android:layout_height="fill_parent" android:layout_width="wrap_content"/>

    <TextView android:id="@+id/newgamebut"
    android:layout_marginLeft="5dp"
    android:text="Instructions"
    android:layout_gravity="center"
    style="@style/Button" android:layout_height="fill_parent" android:layout_width="fill_parent"/>

    </TableRow>

    <TableRow android:layout_gravity="center"
    android:gravity="center" android:layout_width="fill_parent">

    <TextView android:id="@+id/newgamebut"
    android:layout_marginRight="5dp"
    android:text="About"
    style="@style/Button" android:layout_height="fill_parent" android:layout_width="wrap_content"/>

    <TextView android:id="@+id/newgamebut"
    android:layout_marginLeft="5dp"
    android:text="Exit Game"
    android:layout_gravity="center"
    style="@style/Button" android:layout_height="fill_parent" android:layout_width="fill_parent"/>

    </TableRow>

    </TableLayout>
</LinearLayout>
</code>```

What i want to do is to get the instructions textview/button to be completely aligned with the row on top of it currently this is how it looks like.

```<code>| New Game |   | High Scores |
| Settings |  | Instructions |
|   About  |   |  Exit Game  |
</code>```

I want it to look like this

```<code>| New Game |   | High Scores |
| Settings |   | Instructions|
|  About   |   |  Exit Game  |
</code>```

答:
You can use the android:weightSum and android:layout_weight attributes for the textview/button to assign a relative width.

It might sound weird but I would also recommend using android:layout_width="0dp" for your buttons and textviews when using layout_weight.

Body:
Here is my xml layout code

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:id="@+id/titleset"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Orb Runner"
    android:layout_gravity="center"
    android:gravity="center"
    android:layout_marginTop="20dp"
    android:textSize="45sp"
    android:textColor="#FF3366CC"/>

    <TableLayout android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="30dp"
    android:gravity="center"
    android:layout_gravity="center">

    <TableRow android:layout_gravity="center"
    android:gravity="center" android:layout_width="fill_parent">

    <TextView android:id="@+id/newgamebut"
    android:layout_marginRight="5dp"
    android:text="New Game"
    style="@style/Button" android:layout_height="fill_parent" android:layout_width="wrap_content"/>

    <TextView android:id="@+id/newgamebut"
    android:layout_marginLeft="5dp"
    android:text="High Score"
    android:layout_gravity="center"
    style="@style/Button" android:layout_height="fill_parent" android:layout_width="fill_parent"/>

    </TableRow>

    <TableRow android:layout_gravity="center"
    android:gravity="center" android:layout_width="fill_parent">

    <TextView android:id="@+id/newgamebut"
    android:layout_marginRight="5dp"
    android:text="Settings"
    style="@style/Button" android:layout_height="fill_parent" android:layout_width="wrap_content"/>

    <TextView android:id="@+id/newgamebut"
    android:layout_marginLeft="5dp"
    android:text="Instructions"
    android:layout_gravity="center"
    style="@style/Button" android:layout_height="fill_parent" android:layout_width="fill_parent"/>

    </TableRow>

    <TableRow android:layout_gravity="center"
    android:gravity="center" android:layout_width="fill_parent">

    <TextView android:id="@+id/newgamebut"
    android:layout_marginRight="5dp"
    android:text="About"
    style="@style/Button" android:layout_height="fill_parent" android:layout_width="wrap_content"/>

    <TextView android:id="@+id/newgamebut"
    android:layout_marginLeft="5dp"
    android:text="Exit Game"
    android:layout_gravity="center"
    style="@style/Button" android:layout_height="fill_parent" android:layout_width="fill_parent"/>

    </TableRow>

    </TableLayout>
</LinearLayout>

What i want to do is to get the instructions textview/button to be completely aligned with the row on top of it currently this is how it looks like.

| New Game |   | High Scores |
| Settings |  | Instructions |
|   About  |   |  Exit Game  |

I want it to look like this

| New Game |   | High Scores |
| Settings |   | Instructions|
|  About   |   |  Exit Game  |


问:
Why won't the 'react-native -v' command run in my project directory?
When I enter react-native -v in my react-native project directory, all I get is command not found! How do I install this command?

答:
You have to install the react native cli first, globally:

```<code>sudo npm i -g react-native-cli
</code>```

Now you can enter 'react-native -v' at the command line from inside your project directory, and the version info for react native will appear correctly.

You can also see how react native is installed globally on your system (not just for the project) with

```<code>npm view react-native version
</code>```

Body:
You have to install the react native cli first, globally:

sudo npm i -g react-native-cli

Now you can enter 'react-native -v' at the command line from inside your project directory, and the version info for react native will appear correctly.

You can also see how react native is installed globally on your system (not just for the project) with

npm view react-native version


问:
Receive share file intents with Flutter
I searched for a way to make my flutter app receive intents from other apps, but didn't find any.

I want to RECEIVE INTENTS not to send them.

example:

I want to open the Gallery and click on the share button, and choose my flutter app from the menu. and then have my flutter app receive the intent with the picture (and later send it by HTTP request).

Does anyone know how to do it?

答:
It is already answered but wanted to share more details on this,

Here, you can use receive_sharing_intent package. It is null safe & it supports the android & iOS platforms. Using this package you can receive text & multiple media files in open as well as closed applications. So it makes life easier.

For further understanding of how to receive text & multiple media files, you can go through this link. Also there you will get to know how to receive intent in the closed application.

Title: Receive share file intents with Flutter


问:
log4j2 not creating a rolling
I had an application working with log4j1. The configuration I have in the log4j.properties is working fine and it creates the file for log.

I migrate to log4j2 and now the file is not created, even though I follow the documentation. I try all the different solutions here but I can't make it work.

This is my log4j2.xml inside resources in my application

```<code><?xml version="1.0" encoding="UTF-8"?>
<Configuration status="info" name="MyApp" packages="">
<Appenders>
    <RollingFile name="RollingFile" fileName="tmp/app.log"
                 filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
        <PatternLayout>
            <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
        </PatternLayout>
        <Policies>
            <TimeBasedTriggeringPolicy />
            <SizeBasedTriggeringPolicy size="250 MB"/>
        </Policies>
    </RollingFile>
</Appenders>
<Loggers>
    <Root level="info">
        <AppenderRef ref="RollingFile"/>
    </Root>
</Loggers>
</code>```

This is the dependency in my pom.xml

```<code>    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.17.1</version>
    </dependency>
</code>```

I tired changing the path of my file with the full path, changing the folder in case it was permissions problem.

I don't have any error, but when the application runs I don't see any file.
I even print 2 versions of log4j; log4j and log4j2. Log4j creates the file no problem, log4j2 don't

this is my file for log4j

log4j.properties

```<code>log4j.rootLogger=INFO, Appender1,Appender2

log4j.appender.Appender1=org.apache.log4j.RollingFileAppender
log4j.appender.Appender1.File=/tmp/info.log
log4j.appender.Appender1.layout=org.apache.log4j.PatternLayout
log4j.appender.Appender1.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss.SSS} - logger1 - %-5p %c %m%n
log4j.appender.Appender1.Threshold=INFO
log4j.appender.Appender1.maxFileSize=10000KB
log4j.appender.Appender1.MaxBackupIndex=10

log4j.appender.Appender2=org.apache.log4j.RollingFileAppender
log4j.appender.Appender2.File=/tmp/errors.log
log4j.appender.Appender2.layout=org.apache.log4j.PatternLayout
log4j.appender.Appender2.layout.ConversionPattern=%d{dd-mm-YYYY HH:mm:ss.SSS} %-5p %c %m%n
log4j.appender.Appender2.Threshold=ERROR
log4j.appender.Appender2.maxFileSize=10000KB
log4j.appender.Appender2.MaxBackupIndex=10
</code>```

I'm new to this, can anybody help me with this?
what am I'm missing?

let me know if you need more information.

edit: adding the whole pom file in case something is wrong with it:

```<code><?xml version="1.0" encoding="UTF-8"?>
</code>```

4.0.0

org.springframework.boot
spring-boot-starter-parent
2.5.6

com.software
seguros
0.0.1-SNAPSHOT
seguros
Administracion de seguros

<java.version>1.8</java.version>

org.springframework.boot
spring-boot-starter-data-jpa

```<code>    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mindrot</groupId>
        <artifactId>jbcrypt</artifactId>
        <version>0.4</version>
    </dependency>
    <dependency>
        <groupId>com.jfoenix</groupId>
        <artifactId>jfoenix</artifactId>
        <version>8.0.10</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/eu.hansolo.enzo/Enzo -->
    <dependency>
        <groupId>eu.hansolo.enzo</groupId>
        <artifactId>Enzo</artifactId>
        <version>0.3.6</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.17.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.17.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.1.0</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
        <scope>test</scope>
    </dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</code>```

答: You need to remove the 1.2.17 jar and add the log4j-api and log4j-core jars. It will solve the problem.</p>

Title: log4j2 not creating a rolling

Body:
I had an application working with log4j1. The configuration I have in the log4j.properties is working fine and it creates the file for log.

I migrate to log4j2 and now the file is not created, even though I follow the documentation. I try all the different solutions here but I can't make it work.

This is my log4j2.xml inside resources in my application

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="info" name="MyApp" packages="">
<Appenders>
    <RollingFile name="RollingFile" fileName="tmp/app.log"
                 filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
        <PatternLayout>
            <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
        </PatternLayout>
        <Policies>
            <TimeBasedTriggeringPolicy />
            <SizeBasedTriggeringPolicy size="250 MB"/>
        </Policies>
    </RollingFile>
</Appenders>
<Loggers>
    <Root level="info">
        <AppenderRef ref="RollingFile"/>
    </Root>
</Loggers>

This is the dependency in my pom.xml

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.17.1</version>
    </dependency>

I tired changing the path of my file with the full path, changing the folder in case it was permissions problem.

I don't have any error, but when the application runs I don't see any file.
I even print 2 versions of log4j; log4j and log4j2. Log4j creates the file no problem, log4j2 don't

this is my file for log4j

log4j.properties

log4j.rootLogger=INFO, Appender1,Appender2

log4j.appender.Appender1=org.apache.log4j.RollingFileAppender
log4j.appender.Appender1.File=/tmp/info.log
log4j.appender.Appender1.layout=org.apache.log4j.PatternLayout
log4j.appender.Appender1.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss.SSS} - logger1 - %-5p %c %m%n
log4j.appender.Appender1.Threshold=INFO
log4j.appender.Appender1.maxFileSize=10000KB
log4j.appender.Appender1.MaxBackupIndex=10

log4j.appender.Appender2=org.apache.log4j.RollingFileAppender
log4j.appender.Appender2.File=/tmp/errors.log
log4j.appender.Appender2.layout=org.apache.log4j.PatternLayout
log4j.appender.Appender2.layout.ConversionPattern=%d{dd-mm-YYYY HH:mm:ss.SSS} %-5p %c %m%n
log4j.appender.Appender2.Threshold=ERROR
log4j.appender.Appender2.maxFileSize=10000KB
log4j.appender.Appender2.MaxBackupIndex=10

I'm new to this, can anybody help me with this?
what am I'm missing?

let me know if you need more information.

edit: adding the whole pom file in case something is wrong with it:

<?xml version="1.0" encoding="UTF-8"?>

4.0.0

org.springframework.boot
spring-boot-starter-parent
2.5.6

com.software
seguros
0.0.1-SNAPSHOT
seguros
Administracion de seguros

<java.version>1.8</java.version>

org.springframework.boot
spring-boot-starter-data-jpa

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.mindrot</groupId>
        <artifactId>jbcrypt</artifactId>
        <version>0.4</version>
    </dependency>
    <dependency>
        <groupId>com.jfoenix</groupId>
        <artifactId>jfoenix</artifactId>
        <version>8.0.10</version>
    </dependency>

    <dependency>
        <groupId>eu.hansolo.enzo</groupId>
        <artifactId>Enzo</artifactId>
        <version>0.3.6</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.17.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.17.1</version>
    </dependency>

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.1.0</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
        <scope>test</scope>
    </dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>


问:
Through which way should I convert a pointer to a buffer into a string
So I am using the CallNamedPipe function to get some data from a pipe, which is put into response_buffer. However All the methods I have found of turning that response_buffer into a string does not work.

I have tried directly converting it to a string to no avail, as well as other methods

the code in question here is

```<code>std::string word;
        string responses;
        DWORD response_length = 0xffffffff;
        msg = "\"gettrackerpose \" + std::to_string(i) + \" \" + std::to_string(-frameTime - parameters->camLatency)";
        auto msg_cstr = reinterpret_cast<LPVOID>(const_cast<char *>(msg.c_str()));
        int tracker_pose_valid;
        constexpr int BUFFER_SIZE = 512;
        char *response_buffer[BUFFER_SIZE];

        int success = CallNamedPipeA(
            "\\.\\pipe\\ApriltagPipeIn", // pipe name
            msg_cstr,                      // message
            msg.size(),                    // message size
            response_buffer,               // response
            BUFFER_SIZE,                   // response max size
            &response_length,              // response size
            2 * 1000                       // timeout in ms
        );
        //The problem I am having is right here, with trying to convert the buffer to a string
        std::string str(response_buffer, response_buffer + BUFFER_SIZE);

        std::istringstream ret(str);
</code>```

答:
Instead of trying to convert it to a string, just have it one from the start.</p>
```<code>std::string response_buffer{};
response_buffer.resize(BUFFER_SIZE);

int success = CallNamedPipeA(
            "\\.\\pipe\\ApriltagPipeIn", // pipe name
            msg_cstr,                      // message
            msg.size(),                    // message size
            response_buffer.data(),         // response
            BUFFER_SIZE,                   // response max size
            &response_length,              // response size
            2 * 1000                       // timeout in ms
        );

response_buffer.resize(response_length);
</code>```

Body:
So I am using the CallNamedPipe function to get some data from a pipe, which is put into response_buffer. However All the methods I have found of turning that response_buffer into a string does not work.

I have tried directly converting it to a string to no avail, as well as other methods

the code in question here is

std::string word;
        string responses;
        DWORD response_length = 0xffffffff;
        msg = "\"gettrackerpose \" + std::to_string(i) + \" \" + std::to_string(-frameTime - parameters->camLatency)";
        auto msg_cstr = reinterpret_cast<LPVOID>(const_cast<char *>(msg.c_str()));
        int tracker_pose_valid;
        constexpr int BUFFER_SIZE = 512;
        char *response_buffer[BUFFER_SIZE];

        int success = CallNamedPipeA(
            "\\.\\pipe\\ApriltagPipeIn", // pipe name
            msg_cstr,                      // message
            msg.size(),                    // message size
            response_buffer,               // response
            BUFFER_SIZE,                   // response max size
            &response_length,              // response size
            2 * 1000                       // timeout in ms
        );
        //The problem I am having is right here, with trying to convert the buffer to a string
        std::string str(response_buffer, response_buffer + BUFFER_SIZE);

        std::istringstream ret(str);

Body:
Instead of trying to convert it to a string, just have it one from the start.

std::string response_buffer{};
response_buffer.resize(BUFFER_SIZE);

int success = CallNamedPipeA(
            "\\.\\pipe\\ApriltagPipeIn", // pipe name
            msg_cstr,                      // message
            msg.size(),                    // message size
            response_buffer.data(),         // response
            BUFFER_SIZE,                   // response max size
            &response_length,              // response size
            2 * 1000                       // timeout in ms
        );

response_buffer.resize(response_length);