答:
To solve your problem I would replace your current for loop with a while loop

Moreover, I see a lot of unacessary things in your code, I will try to list them :

Why do you use so many "while True"?

Why don't you just use exit()    function to exit instead of using a
variable?

Is all the if part    really necessary, can't you just print the
number?

Here's my proposal:

```<code>import random
remaining_dices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()

while True:
    remaining_dices=int(input("How many dices to throw? (1-5) "))
    if remaining_dices<1 or remaining_dices>5:
        print("Wrong input, try again")
        break
    dicesArray = list()
    while remaining_dices>0:
        dice_value = random.randint(1, 6)
        dicesArray.append(dice_value)
        print(dice_value)
        total += dice_value
        remaining_dices -= 1
        if(dice_value == 6):
            total-=6
            remaining_dices +=2
            print("You rolled a 6, rolling two new dices")
        else:
            print("You rolled a " + str(dice_value) + ", the total is : " +str(total))

    restart=(input("Do you want to restart press Enter, to quit press 9. "))
    if restart=="9":
        exit()
    else:
        print()
</code>```

Title: Dice rolling program with counter

Body:
I'm new to programming and I have a task that I can't figure out on my own.

The task is to make a program that let's you decide how many dices to throw, 1 to 5, with checking if you make a wrong input.
After every roll the number of the die will show and the total so far.
If the die rolls a 6 then it is not included in the total and you get to more rolls. This is where I'm stuck. I want my program to restart the loop if the die turns a 6 and just ad 2 rolls to the sumDices and continue the loop, but I can't get it to work.

here is my code:

import random
numDices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
exit=False
reset=False
while True:
    while True:
        numDices=int(input("How many dices to throw? (1-5) "))
        if numDices<1 or numDices>5:
            print("Wrong input, try again")
            break
        while True:
            if reset==True:
                break
            for i in range(numDices):
                dicesArray = list(range(numDices))
                dicesArray[i] = random.randint(1, 6)
                print(dicesArray[i])
                total += dicesArray[i]
                if dicesArray[i] == 1:
                    print("You rolled a one, the total is: ",str(total))
                elif dicesArray[i] == 2:
                    print("You rolled a two, the total is: ",str(total))
                elif dicesArray[i] == 3:
                    print("You rolled a three, the total is: ",str(total))
                elif dicesArray[i] == 4:
                    print("You rolled a four, the total is: ",str(total))
                elif dicesArray[i] == 5:
                    print("You rolled a five, the total is: ",str(total))
                elif dicesArray[i] == 6:
                    total-=6
                    numDices+=2
                    print("You rolled a six, rolling two new dices")
                    reset=True
        print("The total sum is",str(total),"with",numDices,"number of rolls.")
        print()
        restart=(input("Do you want to restart press Enter, to quit press 9. "))
        if restart=="9":
            exit=True
            break
        else:
            print()
            break
    if exit==True:
        break

Body:
To solve your problem I would replace your current for loop with a while loop

Moreover, I see a lot of unacessary things in your code, I will try to list them :

Why do you use so many "while True"?

Why don't you just use exit()    function to exit instead of using a
variable?

Is all the if part    really necessary, can't you just print the
number?

Here's my proposal:

import random
remaining_dices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()

while True:
    remaining_dices=int(input("How many dices to throw? (1-5) "))
    if remaining_dices<1 or remaining_dices>5:
        print("Wrong input, try again")
        break
    dicesArray = list()
    while remaining_dices>0:
        dice_value = random.randint(1, 6)
        dicesArray.append(dice_value)
        print(dice_value)
        total += dice_value
        remaining_dices -= 1
        if(dice_value == 6):
            total-=6
            remaining_dices +=2
            print("You rolled a 6, rolling two new dices")
        else:
            print("You rolled a " + str(dice_value) + ", the total is : " +str(total))

    restart=(input("Do you want to restart press Enter, to quit press 9. "))
    if restart=="9":
        exit()
    else:
        print()


来源: stackexchange

问:
how to make json web service in asp.net?
I m making web service for the first time. and i need to make that using json in c#. I m not getting how to code the methods that fetch data from database
Any suggessions.</p>

答:
You can use the below code to return the JSON serialized string: </p>

```<code>    [WebMethod(Description = "Your Description")]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string FunctionName()
    {
        // Return JSON data
        JavaScriptSerializer js = new JavaScriptSerializer();
        string retJSON = js.Serialize(Object);
        return retJSON;

    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can use the below code to return the JSON serialized string:

    [WebMethod(Description = "Your Description")]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string FunctionName()
    {
        // Return JSON data
        JavaScriptSerializer js = new JavaScriptSerializer();
        string retJSON = js.Serialize(Object);
        return retJSON;

    }


问:
Loss and learning rate scaling strategies for Tensorflow distributed training when using TF Estimator
For those who don't want to read the whole story:

TL; DR: When using TF Estimator, do we have to scale learning rate by the factor by which we increase batch size (I know this is the right way, I am not sure if TF handles this internally)? Similarly, do we have to scale per example loss by global batch size (batch_size_per_replica * number of replicas)?

Documentation on Tensorflow distributed learning is confusing. I need clarification on below points.

It is now understood that if you increase the batch size by a factor of k then you need to increase the learning rate by k (see this and this paper). However, Tensoflow official page on distributed learning makes no clarifying comment about this. They do mention here that learning rate needs to be adjusted. Do they handle the learning rate scaling by themselves? To make matters more complicated, the behavior is different in Keras and tf.Estimator (see next point). Any suggestions on should I increase the LR by a factor of K or not when I am using tf.Estimator?

It is widely accepted that the per example loss should be scaled by global_batch_size = batch_size_per_replica * number of replicas. Tensorflow mentions it here but then when illustrating how to achieve this with a tf.Estimator, they either forget or the scaling by global_batch_size is not required. See here, in the code snippet, loss is defined as follows.

```<code>loss = tf.reduce_sum(loss) * (1. / BATCH_SIZE)
</code>```

and BATCH_SIZE to the best of my understanding is defined above as per replica batch size.

To complicate things further, the scaling is handled automatically if you are using Keras (for reasons I will never understand, it would have been better to keep everything consistent).

答:
The learning rate is not automatically scaled by the global step. As you said, they even suggest that you might need to adjust the learning rate, but then again only in some cases, so that's not the default. I suggest that you do increase the learning rate manually.

If we take a look at a simple tf.Estimator, the tf.estimator.DNNClassifier (link),  the default loss_reduction is losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE. If we got to that Reduction (found here), we see that it's a policy for how to combine losses form indiviual samples together. On a single machine, we would just use tf.reduce_mean, but you can't use that in a distributed setting (as mentioned in the next link). The Reduction leads us to here, which shows you 1) an implementation of how you would implement the global step and 2) explains why. As they are telling you you should implement this yourself, this implies it's not handled by tf.Estimator. Also note that yo can find some explanations on the Reduction page they state the differences bewteen Keras and Estimators about these params.

ContentLicense: CC BY-SA 4.0

Body:
For those who don't want to read the whole story:

TL; DR: When using TF Estimator, do we have to scale learning rate by the factor by which we increase batch size (I know this is the right way, I am not sure if TF handles this internally)? Similarly, do we have to scale per example loss by global batch size (batch_size_per_replica * number of replicas)?

Documentation on Tensorflow distributed learning is confusing. I need clarification on below points.

It is now understood that if you increase the batch size by a factor of k then you need to increase the learning rate by k (see this and this paper). However, Tensoflow official page on distributed learning makes no clarifying comment about this. They do mention here that learning rate needs to be adjusted. Do they handle the learning rate scaling by themselves? To make matters more complicated, the behavior is different in Keras and tf.Estimator (see next point). Any suggestions on should I increase the LR by a factor of K or not when I am using tf.Estimator?

It is widely accepted that the per example loss should be scaled by global_batch_size = batch_size_per_replica * number of replicas. Tensorflow mentions it here but then when illustrating how to achieve this with a tf.Estimator, they either forget or the scaling by global_batch_size is not required. See here, in the code snippet, loss is defined as follows.

loss = tf.reduce_sum(loss) * (1. / BATCH_SIZE)

and BATCH_SIZE to the best of my understanding is defined above as per replica batch size.

To complicate things further, the scaling is handled automatically if you are using Keras (for reasons I will never understand, it would have been better to keep everything consistent).


问:
Extending Qt plugin
I have a question about c++ plugins in Qt5 with QML UI.

Lets say we have application A and application B. Both using plugin C which is written in c++ to draw some QQuickItems in qml.

Both application working fine. Now I have to extend the plugin with some more options (nothing to draw, but based on the data already available in plugin C) which - and thats the problem - should be only available in application B.

Why? The extra options needing some includes from other libraries which should be not added to application A. So application A should run with the basic plugin and application should run with the extended plugin.

My question is what is the best/common way to achieve this?

I just thought about it a little bit and got some (in my opion not very good) solutions/ideas:

Writing a plugin D which can do the extended options. So application A can run with plugin C and application runs with plugins C and D. The disadvantage is that the 2 plugins needs to communicate heavily (plugin D needs the data of C) via qml. I think thats not very nice, may there be a better way to do the data transfer between two plugins?

Writing 2 plugins where plugin C is the basic one and plugin D has the content of plugin C plus the extended options. Well that should of course work but I will have to maintenance the code twice. That's definitely not nice.

I thought about some conditional includes to just include the extended options if corresponding flags are set. I do not have any experience with that. But could this be possible?

答:
I think the best way for you to proceed is your third option. You can add a init function to your plugin.

```<code>class PluginC : public plugininterface {

    Q_OBJECT

    Q_PLUGIN_METADATA(IID "plugininterface")
    Q_INTERFACES(plugininterface)

public:
    /* Init the plugin */
    void init( bool extended );

    ...
    ...
    ...

private:
    bool m_extended;
};
</code>```

Rest of the plugin can be built just as usual, with all the features you want. In your application A, you can init your plugin with extended = false, and application B, you can init your plugin with extended = true

Title: Extending Qt plugin

Body:
I think the best way for you to proceed is your third option. You can add a init function to your plugin.

class PluginC : public plugininterface {

    Q_OBJECT

    Q_PLUGIN_METADATA(IID "plugininterface")
    Q_INTERFACES(plugininterface)

public:
    /* Init the plugin */
    void init( bool extended );

    ...
    ...
    ...

private:
    bool m_extended;
};

Rest of the plugin can be built just as usual, with all the features you want. In your application A, you can init your plugin with extended = false, and application B, you can init your plugin with extended = true


问:
How to insert arrays into objects that are inside an array? For ng2-charts / Charts.js
Let's say I have 2 arrays:

```<code>var array1 = [1,1,1];
var array2 = [2,2,2];
</code>```

How do I create the parent array with the 2 objects shown below?

(I'm trying to insert the given arrays above into a parent array with 2 objects, but I also still need to create the objects so that they include the keys shown.  This is to comply with the ng2-charts ChartDataSets type.)

```<code>// below is what I'm trying to accomplish, but I only have the 2 arrays above so far
[
  { data : array1, label: 'some label1' },
  { data : array2, label: 'some label2' },
]
</code>```

答:
let arr1 = [1, 1, 1];
let arr2 = [2, 2, 2];
let reqArray = [arr1, arr2].map((ele, ind) => {
  return {
    data: ele,
    label: `some label${ind+1}`
  }
});
console.log(reqArray)```

Body:
Let's say I have 2 arrays:

var array1 = [1,1,1];
var array2 = [2,2,2];

How do I create the parent array with the 2 objects shown below?

(I'm trying to insert the given arrays above into a parent array with 2 objects, but I also still need to create the objects so that they include the keys shown.  This is to comply with the ng2-charts ChartDataSets type.)

// below is what I'm trying to accomplish, but I only have the 2 arrays above so far
[
  { data : array1, label: 'some label1' },
  { data : array2, label: 'some label2' },
]


问:
Why does the other player never gets its turn in my Last Stone Game (Nim) implementation?
```<code>package HomePlace;

import java.util.Random;

import java.util.Scanner;

public class LastStone {
    public static boolean isValidEntry(int left, int User) {
        if (left > 0 && User < 4 && left >= User) {
            return true;
        } else {
            System.out.print("Invalid entry!!");
            return false;
        }
    }

    public static int userMove(int left) {
        Scanner input = new Scanner(System.in);
        System.out.print("There are " + left + " stones. How many would you like? ");
        int User = input.nextInt();
        return User;
    }

    public static int computerMove(int left) {
        int cpuStones;
        cpuStones = generateStones();
        System.out.print("There are " + left + "stones. The computer takes" + cpuStones + " stones");
        return cpuStones;
    }

    public static int generateStones() {
        Random sr = new Random();
        int gstones = sr.nextInt(2) + 1;
        return gstones;
    }

    public static void playLastStone(int UserOrCpu) {
        Scanner input = new Scanner(System.in);
        if (UserOrCpu % 2 == 1) {
            System.out.println("The Computer beats the User!");
        } else {
            System.out.println("The User beats the Computer!");
        }
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Random r = new Random();
        int left = r.nextInt(16) + 15;
        int UserOrCpu = 1, User = 1, temp;
        while (true) {
            if (UserOrCpu % 2 == 1) {
                User = userMove(left);
                if (isValidEntry(left, User)) {
                    if (left == User) {
                        playLastStone(UserOrCpu);
                        break;
                    }
                    left -= User;
                } else {
                    continue;
                }
            } else {
                computerMove(left);
                temp = computerMove(left);
                if (left <= temp) {
                    playLastStone(UserOrCpu);
                    break;
                } else {
                    left -= temp;
                }
            }
        }
        UserOrCpu += 1;
    }
}
</code>```

My computer player cpu never takes its turn in my implementation of the Last Stone game or Nim.

I found similar questions but none helped with solving my problem.

I debugged my code line by line but couldn't figure out why my second } else { in my main method is never executed?

```<code>                    left -= User;
                } else {
                    continue;
                }
            } else { // why is it never executed?
</code>```

答:
In your given code, your main method actually reduces itself to

```<code>    public static void main(String[] args) {
        Random r = new Random();
        int left = r.nextInt(16) + 15;
        int userOrCpu = 1, user;
        while (true) {
            user = userMove(left);
            if (isValidEntry(left, user)) {
                if (left == user) {
                    playLastStone(userOrCpu);
                    break;
                }
                left -= user;
            }
        }
    }
</code>```

And so it's now clear that your computer player cpu never gets its turn.

The problem is that your UserOrCpu += 1; assignment isn't in the right scope, and so doesn't have any effect.

The "fixed" main method should look like this

```<code>    public static void main(String[] args) {
        Random r = new Random();
        int left = r.nextInt(16) + 15;
        int UserOrCpu = 1, User = 1, temp;
        while (true) {
            if (UserOrCpu % 2 == 1) {
                User = userMove(left);
                if (isValidEntry(left, User)) {
                    if (left == User) {
                        playLastStone(UserOrCpu);
                        break;

                    }
                    left -= User;
                } else {
                    continue;
                }
            } else {
                computerMove(left);
                temp = computerMove(left); // executes computer move a 2nd time?
                if (left <= temp) {
                    playLastStone(UserOrCpu);
                    break;

                } else {
                    left -= temp;
                }
            }
            UserOrCpu += 1;
        }
    }
</code>```

Hint: Get yourself an IDE (like IntelliJ) for writing code. Such a code editor will indicate "obvious" problems with your code immediately.

Body:
package HomePlace;

import java.util.Random;

import java.util.Scanner;

public class LastStone {
    public static boolean isValidEntry(int left, int User) {
        if (left > 0 && User < 4 && left >= User) {
            return true;
        } else {
            System.out.print("Invalid entry!!");
            return false;
        }
    }

    public static int userMove(int left) {
        Scanner input = new Scanner(System.in);
        System.out.print("There are " + left + " stones. How many would you like? ");
        int User = input.nextInt();
        return User;
    }

    public static int computerMove(int left) {
        int cpuStones;
        cpuStones = generateStones();
        System.out.print("There are " + left + "stones. The computer takes" + cpuStones + " stones");
        return cpuStones;
    }

    public static int generateStones() {
        Random sr = new Random();
        int gstones = sr.nextInt(2) + 1;
        return gstones;
    }

    public static void playLastStone(int UserOrCpu) {
        Scanner input = new Scanner(System.in);
        if (UserOrCpu % 2 == 1) {
            System.out.println("The Computer beats the User!");
        } else {
            System.out.println("The User beats the Computer!");
        }
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        Random r = new Random();
        int left = r.nextInt(16) + 15;
        int UserOrCpu = 1, User = 1, temp;
        while (true) {
            if (UserOrCpu % 2 == 1) {
                User = userMove(left);
                if (isValidEntry(left, User)) {
                    if (left == User) {
                        playLastStone(UserOrCpu);
                        break;
                    }
                    left -= User;
                } else {
                    continue;
                }
            } else {
                computerMove(left);
                temp = computerMove(left);
                if (left <= temp) {
                    playLastStone(UserOrCpu);
                    break;
                } else {
                    left -= temp;
                }
            }
        }
        UserOrCpu += 1;
    }
}

My computer player cpu never takes its turn in my implementation of the Last Stone game or Nim.

I found similar questions but none helped with solving my problem.

I debugged my code line by line but couldn't figure out why my second } else { in my main method is never executed?

                    left -= User;
                } else {
                    continue;
                }
            } else { // why is it never executed?

Body:
In your given code, your main method actually reduces itself to

    public static void main(String[] args) {
        Random r = new Random();
        int left = r.nextInt(16) + 15;
        int userOrCpu = 1, user;
        while (true) {
            user = userMove(left);
            if (isValidEntry(left, user)) {
                if (left == user) {
                    playLastStone(userOrCpu);
                    break;
                }
                left -= user;
            }
        }
    }

And so it's now clear that your computer player cpu never gets its turn.

The problem is that your UserOrCpu += 1; assignment isn't in the right scope, and so doesn't have any effect.

The "fixed" main method should look like this

    public static void main(String[] args) {
        Random r = new Random();
        int left = r.nextInt(16) + 15;
        int UserOrCpu = 1, User = 1, temp;
        while (true) {
            if (UserOrCpu % 2 == 1) {
                User = userMove(left);
                if (isValidEntry(left, User)) {
                    if (left == User) {
                        playLastStone(UserOrCpu);
                        break;

                    }
                    left -= User;
                } else {
                    continue;
                }
            } else {
                computerMove(left);
                temp = computerMove(left); // executes computer move a 2nd time?
                if (left <= temp) {
                    playLastStone(UserOrCpu);
                    break;

                } else {
                    left -= temp;
                }
            }
            UserOrCpu += 1;
        }
    }

Hint: Get yourself an IDE (like IntelliJ) for writing code. Such a code editor will indicate "obvious" problems with your code immediately.


问:
How to use KeyboardAvoidingView with FlatList?
I have a FlatList component with an Input inside each row. When I select the input I want it to scroll up above the keyboard.

My code:

```<code>return (
  <KeyboardAvoidingView behavior='padding' style={{ flex: 1 }} >
    <FlatList
      style={{ flex: 1, backgroundColor: '#fff' }}
      data={ds}
      renderItem={({ item }) => <ListItem data={item} />}
      ListFooterComponent={this.renderButton}
    />
  </KeyboardAvoidingView>
);
</code>```

In this scenario, the FlatList is never loaded. When I delete flex:1 from both components, FlatList renders properly but selecting an Input does not make it scroll up

答:
For anyone on a similar path as mine. I was not able to use KeyboardAvoidingView because it depends on ScrollView which conflicts with Flatlist. I couldn't used the header and footer option in Flatlist as I'm using it as a generated thing in a search selection box so it has to be contained.

For me there is a difference in how Android and iOS calculate absolute position. Android considers the bottom to be the top of the keyboard and iOS it is the bottom of the screen when the keyboard is showing.

It turns out to be not that difficult to just put a View around the content you want to remain above the keyboard and just dynamically set the height of it on iOS. This isn't even really necessary on Android as it follows the keyboard if the View is position: absolute and bottom: 0.

This heavily borrows from here: https://stackoverflow.com/a/60682069/438322
Thanks to Kevin Amiranoff

Here's a basic example using hooks.

```<code>function YourComponent(props){
  const onKeyboardWillShow = e => {
    setKeyboardHeight(e.endCoordinates.height);
  };

  const onKeyboardWillHide = () => {
    setKeyboardHeight(0);
  };

  useEffect(() => {
    // These listeners on ios are a little more snappy but not available on Android
    // If you want to use this on Android use keyboardDidShow/Hide
    if (Platform.OS === 'ios') {
      Keyboard.addListener('keyboardWillShow', onKeyboardWillShow);
      Keyboard.addListener('keyboardWillHide', onKeyboardWillHide);
    }

    return () => {
      if (Platform.OS === 'ios') {
        Keyboard.removeListener('keyboardWillShow', onKeyboardWillShow);
        Keyboard.removeListener('keyboardWillHide', onKeyboardWillHide);
      }
    };
  }, []);

  const buttonHeight = 50;

  return(
    <View>
      <Content bla={'bla'}/>

      <View style={{
        height: Platform.OS === 'ios'
          ? keyboardHeight + buttonHeight : buttonHeight,
        position: 'absolute',
        bottom: 0
      }}>
      {/* Keep this button above the keyboard */}
      <Button style={{ height: buttonHeight }}/>
</View
    </View>
  )
}
</code>```

Body:
I have a FlatList component with an Input inside each row. When I select the input I want it to scroll up above the keyboard.

My code:

return (
  <KeyboardAvoidingView behavior='padding' style={{ flex: 1 }} >
    <FlatList
      style={{ flex: 1, backgroundColor: '#fff' }}
      data={ds}
      renderItem={({ item }) => <ListItem data={item} />}
      ListFooterComponent={this.renderButton}
    />
  </KeyboardAvoidingView>
);

In this scenario, the FlatList is never loaded. When I delete flex:1 from both components, FlatList renders properly but selecting an Input does not make it scroll up

Body:
For anyone on a similar path as mine. I was not able to use KeyboardAvoidingView because it depends on ScrollView which conflicts with Flatlist. I couldn't used the header and footer option in Flatlist as I'm using it as a generated thing in a search selection box so it has to be contained.

For me there is a difference in how Android and iOS calculate absolute position. Android considers the bottom to be the top of the keyboard and iOS it is the bottom of the screen when the keyboard is showing.

It turns out to be not that difficult to just put a View around the content you want to remain above the keyboard and just dynamically set the height of it on iOS. This isn't even really necessary on Android as it follows the keyboard if the View is position: absolute and bottom: 0.

This heavily borrows from here: https://stackoverflow.com/a/60682069/438322
Thanks to Kevin Amiranoff

Here's a basic example using hooks.

function YourComponent(props){
  const onKeyboardWillShow = e => {
    setKeyboardHeight(e.endCoordinates.height);
  };

  const onKeyboardWillHide = () => {
    setKeyboardHeight(0);
  };

  useEffect(() => {
    // These listeners on ios are a little more snappy but not available on Android
    // If you want to use this on Android use keyboardDidShow/Hide
    if (Platform.OS === 'ios') {
      Keyboard.addListener('keyboardWillShow', onKeyboardWillShow);
      Keyboard.addListener('keyboardWillHide', onKeyboardWillHide);
    }

    return () => {
      if (Platform.OS === 'ios') {
        Keyboard.removeListener('keyboardWillShow', onKeyboardWillShow);
        Keyboard.removeListener('keyboardWillHide', onKeyboardWillHide);
      }
    };
  }, []);

  const buttonHeight = 50;

  return(
    <View>
      <Content bla={'bla'}/>

      <View style={{
        height: Platform.OS === 'ios'
          ? keyboardHeight + buttonHeight : buttonHeight,
        position: 'absolute',
        bottom: 0
      }}>
      {/* Keep this button above the keyboard */}
      <Button style={{ height: buttonHeight }}/>
</View
    </View>
  )
}


问:
Is WCF MessageBuffer.CreateMessage thread safe?
http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.messagebuffer(v=vs.85).aspx is somewhat vague when it says that "Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe."

As a general rule, it seems like instance members do not have the thread-safe guarantee.

However, I'm guessing that some instance member methods are reentrant and thread-safe and others are not.

MessageBuffer.CreateMessage is an instance method.
Has anyone confirmed whether this specific method is reentrant (or whether callers need to implement locking around calls to the method) ?

答:
I don't think until explicity specified, instance methods are always non thread safe. You can look at this method through reflector to confirm.

Also why are you concern about thread safety of this method? What is your usage scenario?


问:
Dice rolling program with counter
I'm new to programming and I have a task that I can't figure out on my own.

The task is to make a program that let's you decide how many dices to throw, 1 to 5, with checking if you make a wrong input.
After every roll the number of the die will show and the total so far.
If the die rolls a 6 then it is not included in the total and you get to more rolls. This is where I'm stuck. I want my program to restart the loop if the die turns a 6 and just ad 2 rolls to the sumDices and continue the loop, but I can't get it to work.

here is my code:

```<code>import random
numDices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
exit=False
reset=False
while True:
    while True:
        numDices=int(input("How many dices to throw? (1-5) "))
        if numDices<1 or numDices>5:
            print("Wrong input, try again")
            break
        while True:
            if reset==True:
                break
            for i in range(numDices):
                dicesArray = list(range(numDices))
                dicesArray[i] = random.randint(1, 6)
                print(dicesArray[i])
                total += dicesArray[i]
                if dicesArray[i] == 1:
                    print("You rolled a one, the total is: ",str(total))
                elif dicesArray[i] == 2:
                    print("You rolled a two, the total is: ",str(total))
                elif dicesArray[i] == 3:
                    print("You rolled a three, the total is: ",str(total))
                elif dicesArray[i] == 4:
                    print("You rolled a four, the total is: ",str(total))
                elif dicesArray[i] == 5:
                    print("You rolled a five, the total is: ",str(total))
                elif dicesArray[i] == 6:
                    total-=6
                    numDices+=2
                    print("You rolled a six, rolling two new dices")
                    reset=True
        print("The total sum is",str(total),"with",numDices,"number of rolls.")
        print()
        restart=(input("Do you want to restart press Enter, to quit press 9. "))
        if restart=="9":
            exit=True
            break
        else:
            print()
            break
    if exit==True:
        break
</code>```

答:
```<code>for i in range(numDices):
</code>```

Your for loop limits the number of iterations as soon as range(numDices) is evaluated/executed.  When you attempt to increase the number of iterations with numDices+=2 it does not have any effect because range(numDices) is only evaluated once.

If you want to be able to change the number of iterations, use another while loop and use i as a counter.  Something like.

```<code>i = 0
while i <= numDices:
    ...
    ...
    if ...:
        ...
    elif ...:
    ...
    i += 1
</code>```

Then in the suite for elif dicesArray[i] == 6: the statement numDices += 2 will effectively increase the number of iterations.

I see another problem that you haven't mentioned. You start with a fixed length list based on the original value of numDices and you use i as an index for that list.

```<code>dicesArray = list(range(numDices))`
...
dicesArray[i]
...
</code>```

If i can potentially be greater than the original numDices (greater than len(dicesArray)) you will eventually get an IndexError.  You should probably start with an empty list and append to it. To get the most recent dice roll use  dicesArray[-1] instead of dicesArray[i].

```<code>...
dicesArray = []
i = 0
while i <= numDices:
    dicesArray.append(random.randint(1, 6))
    total += dicesArray[-1]
    if dicesArray[-1] == 1:
        ...
    ...
</code>```

6.3.2. Subscriptions

Title: Dice rolling program with counter

Body:
for i in range(numDices):

Your for loop limits the number of iterations as soon as range(numDices) is evaluated/executed.  When you attempt to increase the number of iterations with numDices+=2 it does not have any effect because range(numDices) is only evaluated once.

If you want to be able to change the number of iterations, use another while loop and use i as a counter.  Something like.

i = 0
while i <= numDices:
    ...
    ...
    if ...:
        ...
    elif ...:
    ...
    i += 1

Then in the suite for elif dicesArray[i] == 6: the statement numDices += 2 will effectively increase the number of iterations.

I see another problem that you haven't mentioned. You start with a fixed length list based on the original value of numDices and you use i as an index for that list.

dicesArray = list(range(numDices))`
...
dicesArray[i]
...

If i can potentially be greater than the original numDices (greater than len(dicesArray)) you will eventually get an IndexError.  You should probably start with an empty list and append to it. To get the most recent dice roll use  dicesArray[-1] instead of dicesArray[i].

...
dicesArray = []
i = 0
while i <= numDices:
    dicesArray.append(random.randint(1, 6))
    total += dicesArray[-1]
    if dicesArray[-1] == 1:
        ...
    ...

6.3.2. Subscriptions


问:
JavaScript Object is not recognized after defined using WebPack Encore in Symfony 4
I am trying to include BootstrapDialog in a Symfony 4 project using WebPack Encore.

First, I copied the Bootstrap Dialog JS file to the JS folder where all other JS files reside.

Second, I have done this in app.js file:

```<code>require('./bootstrap-dialog');

global.$ = global.jQuery = $;

alert(BootstrapDialog);
</code>```

Third I have added this inside bootstrap dialog JS file.

```<code>alert(BootstrapDialog);
</code>```

Notice the alert in app.js and the alert in the bootstrap dialog js file.

The alert in the bootstrap dialog js file shows the BootstrapDialog function body, however, the alert in app.js caused this to be displayed in browser console window:

```<code> ReferenceError: BootstrapDialog is not defined
</code>```

How can I make BootstrapDialog function to be accesible from outside its own JS file?

Regards
Jaime

答:
You can use bootbox (http://bootboxjs.com/)

In app.js or other, you write
bootbox = require('bootbox');

That's all

You can use it :

bootbox.alert("Your message here…")

bootbox.confirm("Are you sure?", function(result){
/* your callback code */
})

...

Body:
I am trying to include BootstrapDialog in a Symfony 4 project using WebPack Encore.

First, I copied the Bootstrap Dialog JS file to the JS folder where all other JS files reside.

Second, I have done this in app.js file:

require('./bootstrap-dialog');

global.$ = global.jQuery = $;

alert(BootstrapDialog);

Third I have added this inside bootstrap dialog JS file.

alert(BootstrapDialog);

Notice the alert in app.js and the alert in the bootstrap dialog js file.

The alert in the bootstrap dialog js file shows the BootstrapDialog function body, however, the alert in app.js caused this to be displayed in browser console window:

 ReferenceError: BootstrapDialog is not defined

How can I make BootstrapDialog function to be accesible from outside its own JS file?

Regards
Jaime


问:
Javascript XMLHTTPREQUEST Post sending GET on localhost
I am trying to POST Form data using pure javascript XMLHTTPREQUEST library.  My javascript function first gets all the html form data and cleans it as well as check that it is the right format before sticking it in an Object.
 Then the normal request library is used to send the JSON.stringify(Object) with the right headers.  The problem is I am testing it on my Apache localhost  and it does not send the data to the designated php file.  It only concatenates the data to my Url header as a GET request.

```<code>        let reqObj = new XMLHttpRequest();
        var elem = document.getElementById(msgContan);
        //add event listener for request
        reqObj.addEventListener("progress", function(eve) {
            if (eve.lengthComputable) {
                //show progress on download using view
                jsView.elementShowMover(elem, strPos,endPos,moveMs);
                document.getElementById(msgElemnt).innerText = Math.round(eve.loaded/eve.total * 100) + "% Complete";
            }
        });
        reqObj.addEventListener("load", function(eve) {
            if (reqObj.status >= 200 && reqObj.status < 300) {
                //elem.style.display = "none";
                console.log('Completed');
            }
        });
        reqObj.addEventListener("error", function(eve) {
            document.getElementById(msgElemnt).innerText = "Failed to post data.";
        });
        reqObj.addEventListener("abort", function(eve) {
            document.getElementById(msgElemnt).innerText = "Data post was cancelled.";
        });
        //set timeout @ 30 seconds
        reqObj.timeout = 30000;
        //open network request
        reqObj.open('POST', 'localhost/myprojects/pages/app/web_app/getter.php');
        //set http-headers
        reqObj.setRequestHeader('Content-Type', 'application/json');
        //send the request
        reqObj.send(JSON.stringify(answ.jObj));

</code>```

Can someone help to give me a clue why that would happen and how do you test a POST request on a localhost?

答:
@epascarello gave the right diagnoses to solve my question.  Therefore I am posting it.

The concatenated data to my URL and constant GET request sent, even though POST was requested, is due to me

not cancelling the form submission.

To cancel form submission depends on how the XmlHttpRequest object is called.  In my case I called the function with an onclick event bound to a html <button>.

The button had no type attribute set which meant it defaulted to submit.

I changed the button attribute to type='button' which cancelled the form submission.

My second problem of not executing the php file or completing the request within the set javascript load event function was due to the XmlHttpRequest .send property's second parameter not set as a relative path.  My incorrect path therefore showed a

network request

404 Not Found with Request URL:http://localhost/myprojects/pages/localhost/myprojects/pages/app/web_app/getter.php.

By changing my absolute path to a relative path the POST request was completed.

Body:
I am trying to POST Form data using pure javascript XMLHTTPREQUEST library.  My javascript function first gets all the html form data and cleans it as well as check that it is the right format before sticking it in an Object.
 Then the normal request library is used to send the JSON.stringify(Object) with the right headers.  The problem is I am testing it on my Apache localhost  and it does not send the data to the designated php file.  It only concatenates the data to my Url header as a GET request.

        let reqObj = new XMLHttpRequest();
        var elem = document.getElementById(msgContan);
        //add event listener for request
        reqObj.addEventListener("progress", function(eve) {
            if (eve.lengthComputable) {
                //show progress on download using view
                jsView.elementShowMover(elem, strPos,endPos,moveMs);
                document.getElementById(msgElemnt).innerText = Math.round(eve.loaded/eve.total * 100) + "% Complete";
            }
        });
        reqObj.addEventListener("load", function(eve) {
            if (reqObj.status >= 200 && reqObj.status < 300) {
                //elem.style.display = "none";
                console.log('Completed');
            }
        });
        reqObj.addEventListener("error", function(eve) {
            document.getElementById(msgElemnt).innerText = "Failed to post data.";
        });
        reqObj.addEventListener("abort", function(eve) {
            document.getElementById(msgElemnt).innerText = "Data post was cancelled.";
        });
        //set timeout @ 30 seconds
        reqObj.timeout = 30000;
        //open network request
        reqObj.open('POST', 'localhost/myprojects/pages/app/web_app/getter.php');
        //set http-headers
        reqObj.setRequestHeader('Content-Type', 'application/json');
        //send the request
        reqObj.send(JSON.stringify(answ.jObj));

Can someone help to give me a clue why that would happen and how do you test a POST request on a localhost?


问:
Why does fseek from SEEK_CUR use random character for space?
Having this:

```<code>int main (void) {

    FILE *fp = fopen("txt2", "r+");

    rewind(fp);
    fprintf(fp, "ab");
    fseek(fp,1L,SEEK_CUR); //trying to change offset to 1,2,3,...
    fprintf(fp, "cd");
    rewind(fp);

    for(int c;(c=getc(fp))!=EOF;)
        putchar(c);

    fclose(fp);

    return 0;
}
</code>```

I want to know, If fseek from current position offsets forward with spaces or some garbage. I will gives output with ^ in places, where should be space.

```<code>fseek(fp,0L,SEEK_CUR)
->  abcd //yes, that is what I expect

fseek(fp,1L,SEEK_CUR)
-> abccd //not space -> 'c' char instead
     ^

fseek(fp,2L,SEEK_CUR)
-> abcdcd //'cd' are in addition (random chars?)
     ^^

fseek(fp,3L,SEEK_CUR)
-> abcdccd //'cdc' no it is probably not "random", they repeat
     ^^^

fseek(fp,100000000000L,SEEK_CUR)
-> abcdcdcdcdcdcdcdcdcd

fseek(fp,1000000000000000000000000L,SEEK_CUR0
->warning: integer constant is too large for its type
fseek(fp,1000000000000000000000000L,SEEK_CUR);
</code>```

What is going on with fseek moving? They are pattern on which the "moved char" will be made? In this case according to the next printf chars? (cd). I do not really understand this behaviour and how to move by spaces with fseek? I only know to use rewind before and after every writing in order to perform correct read (in for loop), but that does not explain the behaviour. Can someone give a hint?

答:
Aha, I see what's going on. It's not using spaces, it's using NUL bytes, which is much more in line with expectations but not showing up in your output.

In your sample code that shows the output, change it to:

```<code>    for(int c; (c = getc(fp)) != EOF;)
    {
        if (c == 0) c = '.';  // ADD ME
        putchar(c);
    }
</code>```

Now it will show a dot every time there's a NUL byte, which represents the hole you seeked past.

Starting with an empty txt2 file and a seek offset of 2, it shows:

```<code>ab..cd
</code>```

Because you weren't seeing the NUL bytes on your terminal, it made it look like things were all shifted around, and it had me scratching my head for a minute.

EDIT: your post would be a lot clearer if you would show the contents of the txt2 file before-and-after, because these changes are cumulative and impossible to follow when the NUL bytes enter the game.

This should do the trick:

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

static void showfile(FILE *fp, const char *which)
{
    // using | characters to show the start and end of the buffer
    // in case there are trailing blanks involved.
    printf("File %s: |");
    for (int c; (c = getc(fp)) !=EOF;)
    {
        if (c == 0) c = '.';
        putchar(c);
    }
    printf("|\n");
}

int main (void) {

    FILE *fp = fopen("txt2", "r+");

    long offset = 3L;  //trying to change offset to 1,2,3,...
    printf("Running with offset = %ld\n", offset);

    showfile(fp, "before");

    rewind(fp);
    fprintf(fp, "ab");
    fseek(fp, offset, SEEK_CUR);
    fprintf(fp, "cd");
    rewind(fp);

    showfile(fp, "after ");

    fclose(fp);

    return 0;
}
</code>```

Then running it:

```<code>Running with offset = 2
File before: ||
File after : |ab..cd|

// rerun with previous file
Running with offset = 3
File before: |ab..cd|
File after : |ab..ccd|
</code>```

Body:
Having this:

int main (void) {

    FILE *fp = fopen("txt2", "r+");

    rewind(fp);
    fprintf(fp, "ab");
    fseek(fp,1L,SEEK_CUR); //trying to change offset to 1,2,3,...
    fprintf(fp, "cd");
    rewind(fp);

    for(int c;(c=getc(fp))!=EOF;)
        putchar(c);

    fclose(fp);

    return 0;
}

I want to know, If fseek from current position offsets forward with spaces or some garbage. I will gives output with ^ in places, where should be space.

fseek(fp,0L,SEEK_CUR)
->  abcd //yes, that is what I expect

fseek(fp,1L,SEEK_CUR)
-> abccd //not space -> 'c' char instead
     ^

fseek(fp,2L,SEEK_CUR)
-> abcdcd //'cd' are in addition (random chars?)
     ^^

fseek(fp,3L,SEEK_CUR)
-> abcdccd //'cdc' no it is probably not "random", they repeat
     ^^^

fseek(fp,100000000000L,SEEK_CUR)
-> abcdcdcdcdcdcdcdcdcd

fseek(fp,1000000000000000000000000L,SEEK_CUR0
->warning: integer constant is too large for its type
fseek(fp,1000000000000000000000000L,SEEK_CUR);

What is going on with fseek moving? They are pattern on which the "moved char" will be made? In this case according to the next printf chars? (cd). I do not really understand this behaviour and how to move by spaces with fseek? I only know to use rewind before and after every writing in order to perform correct read (in for loop), but that does not explain the behaviour. Can someone give a hint?

Body:
Aha, I see what's going on. It's not using spaces, it's using NUL bytes, which is much more in line with expectations but not showing up in your output.

In your sample code that shows the output, change it to:

    for(int c; (c = getc(fp)) != EOF;)
    {
        if (c == 0) c = '.';  // ADD ME
        putchar(c);
    }

Now it will show a dot every time there's a NUL byte, which represents the hole you seeked past.

Starting with an empty txt2 file and a seek offset of 2, it shows:

ab..cd

Because you weren't seeing the NUL bytes on your terminal, it made it look like things were all shifted around, and it had me scratching my head for a minute.

EDIT: your post would be a lot clearer if you would show the contents of the txt2 file before-and-after, because these changes are cumulative and impossible to follow when the NUL bytes enter the game.

This should do the trick:

#include <stdio.h>

static void showfile(FILE *fp, const char *which)
{
    // using | characters to show the start and end of the buffer
    // in case there are trailing blanks involved.
    printf("File %s: |");
    for (int c; (c = getc(fp)) !=EOF;)
    {
        if (c == 0) c = '.';
        putchar(c);
    }
    printf("|\n");
}

int main (void) {

    FILE *fp = fopen("txt2", "r+");

    long offset = 3L;  //trying to change offset to 1,2,3,...
    printf("Running with offset = %ld\n", offset);

    showfile(fp, "before");

    rewind(fp);
    fprintf(fp, "ab");
    fseek(fp, offset, SEEK_CUR);
    fprintf(fp, "cd");
    rewind(fp);

    showfile(fp, "after ");

    fclose(fp);

    return 0;
}

Then running it:

Running with offset = 2
File before: ||
File after : |ab..cd|

// rerun with previous file
Running with offset = 3
File before: |ab..cd|
File after : |ab..ccd|


问:
Simple censor function does not work in python
I have created a function that takes a text and a word to censor in the text. It should return the text but with the censor word replaced with ****.
But it does not censor the word.

```<code>def censor(text,word):
  if word in text:
    word="*"*len(word)
  return text
</code>```

What's wrong with the code?

答:
You are not making any changes to the string 'text'. The example code below should give you the desired output.</p>

```<code>def censor(text,word):
  if word in text:
    text= text.replace(word,"*"*len(word))
  return text

</code>```

Body:
I have created a function that takes a text and a word to censor in the text. It should return the text but with the censor word replaced with ****.
But it does not censor the word.

def censor(text,word):
  if word in text:
    word="*"*len(word)
  return text

What's wrong with the code?

Body:
You are not making any changes to the string 'text'. The example code below should give you the desired output.

def censor(text,word):
  if word in text:
    text= text.replace(word,"*"*len(word))
  return text


问:
Cannot create Maven project in Netbeans
I'm trying to create a Maven project in Netbeans (for the first time),
Every time i try to create a project, i get this error message:

------------------------------------------------------------------------ BUILD FAILURE
  ------------------------------------------------------------------------ Total time: 0.095s Finished at: Thu Jul 03 12:07:01 CEST 2014 Final
  Memory: 4M/112M
  ------------------------------------------------------------------------ No goals have been specified for this build. You must specify a valid
  lifecycle phase or a goal in the format : or
  :[:]:.
  Available lifecycle phases are: validate, initialize,
  generate-sources, process-sources, generate-resources,
  process-resources, compile, process-classes, generate-test-sources,
  process-test-sources, generate-test-resources, process-test-resources,
  test-compile, process-test-classes, test, prepare-package, package,
  pre-integration-test, integration-test, post-integration-test, verify,
  install, deploy, pre-site, site, post-site, site-deploy, pre-clean,
  clean, post-clean. -> [Help 1]

To see the full stack trace of the errors, re-run Maven with the -e
  switch. Re-run Maven using the -X switch to enable full debug logging.

For more information about the errors and possible solutions, please
  read the following articles: [Help 1]
  http://cwiki.apache.org/confluence/display/MAVEN/NoGoalSpecifiedException
  The system cannot find the path specified.

and i the project folder/files aren't created.

I'm using the Netbeans 8 IDE and download the full one (that contain J2EE and stuff), does that mean i have Maven installed by default, or i have to download and install it separately?

答: If you are using Windows 10 Pro and stack configuring the proxy setting in settings, try deactivating proxy in settings>Networks&Internet>proxy>Authomatic detect settings(off)

Title: Cannot create Maven project in Netbeans


问:
When considering git vs svn for work projects, is Mercurial best of both worlds?
Lately I've been searching for the best source control technologies for my work projects. I've been a subversion user for a while, but heard more and more about git. So I checked it out, and I very much liked the fact that it allows you to easily put your projects under source control, even offline, when you don't have access to a server.
However in multiple programmer environments (for instance at work) the idea of a central server still has its benefits.
That's when I came across Mercurial, this seems to me to be the best of both worlds, since you can just put your project under source control offline, you can pull push to other people if they put up a webserver, but you can also use a central server to push to and pull from..
Combine that with the fact that something like bitbucket.com gives you the chance to start a private free repository online..

So am I right in my thinking, or are there some important subtleties with these source control systems in a work environment that I fail to grasp?

答:
To answer your question, I believe so.

I use mercurial for all my mercurial, git and subversion repository access.  I use a mercurial extension called hg-git http://hg-git.github.com/ to work with git repositories; mainly on github.  Mercurial has a few ways to work with subverion, but ultimately I have converted those svn repos and not needed to do anything more.

As far mercurial alone being great, it is.  But mostly it's great because dvcs is great.  If you can, use them both (git, hg) for a while and try to best understand them.  You can't go wrong with choosing git or hg.


问:
Dependency Injection into an ILogger object
I have a Server side Blazor application where I am implementing an ILogger object to catch unhandled application errors and log them.  You can see how I did that in my answer here:
Processing unhandled exceptions in ASP.NET Core 3.1

What I would like to do is to use dependency injection to pass objects into my ILogger object so it can get more information to log about the exception.  But I am not able to figure out how to do that.  I tried adding DI objects to the constructor of the ExceptionLoggerProvider and ExceptionLogger objects, but I couldn't get that to work.  Can someone provide an example of how to do that?

For example, I have a LoginAccount DI class I created which tracks the logged in user which I setup like this which I would like to be injected into my ILogger object.

```<code>services.AddScoped<LoginAccount>();
</code>```

答:
If I understood your requirement correctly, you can implement something like this-

Add Host.CreateDefaultBuilder(args) in Program.cs

```<code>using Microsoft.Extensions.Logging;

        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
</code>```

If you are implementing in Model class, you can call something like this-

```<code>private readonly ILogger<RegisterModel> _logger;

public class YourModel : PageModel
{
    private readonly ILogger<YourModel> _logger;

    public YourModel(ILogger<YourModel> logger)
    {
        _logger = logger;
    }
}
</code>```

And you can call like this inside your Action/methods to log info. You can pass exception/event object as well.

```<code>_logger.LogInformation("Log your info here.");
</code>```

If you are implementing in Controller, you can use something like -

```<code>public class YourController : Controller
{
    private readonly ILogger<YourController> _logger;

    public YourController(ILogger<YourController> logger)
    {
        _logger = logger;
    }
 }
</code>```

And similar way you can call like this inside your Controller Actions to log info-

```<code>_logger.LogInformation("Log your info here");
</code>```

To override the default set of logging providers added by Host.CreateDefaultBuilder, call ClearProviders and add the required logging providers. For example, the following code in Program.cs:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureLogging(logging =>
        {
            logging.ClearProviders();
            logging.AddConsole();  //you can pass any third party logging provider here
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });```

For further info, see the docs.

Body:
I have a Server side Blazor application where I am implementing an ILogger object to catch unhandled application errors and log them.  You can see how I did that in my answer here:
Processing unhandled exceptions in ASP.NET Core 3.1

What I would like to do is to use dependency injection to pass objects into my ILogger object so it can get more information to log about the exception.  But I am not able to figure out how to do that.  I tried adding DI objects to the constructor of the ExceptionLoggerProvider and ExceptionLogger objects, but I couldn't get that to work.  Can someone provide an example of how to do that?

For example, I have a LoginAccount DI class I created which tracks the logged in user which I setup like this which I would like to be injected into my ILogger object.

services.AddScoped<LoginAccount>();

Body:
If I understood your requirement correctly, you can implement something like this-

Add Host.CreateDefaultBuilder(args) in Program.cs

using Microsoft.Extensions.Logging;

        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });

If you are implementing in Model class, you can call something like this-

private readonly ILogger<RegisterModel> _logger;

public class YourModel : PageModel
{
    private readonly ILogger<YourModel> _logger;

    public YourModel(ILogger<YourModel> logger)
    {
        _logger = logger;
    }
}

And you can call like this inside your Action/methods to log info. You can pass exception/event object as well.

_logger.LogInformation("Log your info here.");

If you are implementing in Controller, you can use something like -

public class YourController : Controller
{
    private readonly ILogger<YourController> _logger;

    public YourController(ILogger<YourController> logger)
    {
        _logger = logger;
    }
 }

And similar way you can call like this inside your Controller Actions to log info-

_logger.LogInformation("Log your info here");

To override the default set of logging providers added by Host.CreateDefaultBuilder, call ClearProviders and add the required logging providers. For example, the following code in Program.cs:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureLogging(logging =>
        {
            logging.ClearProviders();
            logging.AddConsole();  //you can pass any third party logging provider here
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

For further info, see the docs.


问:
Ionic Webview not syncing cookies on first launch IOS
Please help!! I’m using Ionic 5 with Angular and Cordova. My app works perfect when testing on browsers and Android devices but when it’s first installed on my device (iphone) through Xcode the cookies are not received or sent properly. My app uses cookie based authentication so when I get my login response it will have a cookie that should be sent with all subsequent requests. However, on the first launch after install I cannot login at all. When I exit and relaunch my app it works perfectly. I believe this is due to the webview not syncing cookies correctly. I have tried all the solutions in this post: https://github.com/Telerik-Verified-Plugins/WKWebView/issues/247 but the plugins are so outdated I can’t get it to work properly.

I have been looking for a solution for weeks and am completely stuck and exhausted at this point. I’m new to Ionic and development in general so any help would be greatly appreciated! I will provide whatever code or screenshots is helpful, just let me know what I should share.

答:
I don't know if you have solved this since it's been 24 days since you asked, but:

I was having a similar issue. I'm using the cordova-plugin-wkwebview-cookie-sync plugin
and even though the cookie was set, the page was loading as it wasn't. All I had to do was
update $('body').append(_return); to $('body').html(_return); and the content showed up
using the cookie.

This is my code:

function loadApp() {
  $.ajax({
    // this url sets the cookie when called
    url: "example.com",
    success: function (_return) {
      if (_return) {
        // the _return value uses the cookie to display custom data
        // I previously used the append() method here
        $("body").html(_return);
      }
    },
  });
}

document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
  wkWebView.injectCookie(
    "www.example.com/index",
    function () {
      // success callback
      loadApp();
    },
    function () {
      // error callback
      //alert('error');
    }
  );
}
```


问:
Postman pre-request to get token doesn't work
At this time I can perform succesfully my Postman request to get my token. I'm using these parameters :

-Basic Authorization in the headers

-and this body
-

Now I would like to get this request as a pre-request script (and use an environment variable for the token).

Here is the script :

```<code>pm.sendRequest({
    url: 'http://localhost:8084/oauth/token',
    method: 'POST',
    header: {
        'Authorization':'Basic Y2xpZW50OnBhc3N3b3Jk',
        'content-type': 'application/x-www-form-urlencoded'
    },
    data:{
        'password':'secret',
        'username':'admin',
        'grant_type':'password'
    }
}, (err, res) => pm.environment.set("token", res.json().access_token));
</code>```

It doesn't work with the response : Full authentication is required to access this resource.

What is wrong?

Thanks

答:
You could change the data section to something like this?

```<code>body:{
   mode:"urlencoded",
   urlencoded:[
      {
         key:"grant_type",
         value:"password"
      },
      {
         key:"username",
         value:"admin"
      },
      {
         key:"password",
         value:"secret"
      }
   ]
}
</code>```

A great resource for pm.sendRequest() examples can be found here

Body:
At this time I can perform succesfully my Postman request to get my token. I'm using these parameters :

-Basic Authorization in the headers

-and this body
-

Now I would like to get this request as a pre-request script (and use an environment variable for the token).

Here is the script :

pm.sendRequest({
    url: 'http://localhost:8084/oauth/token',
    method: 'POST',
    header: {
        'Authorization':'Basic Y2xpZW50OnBhc3N3b3Jk',
        'content-type': 'application/x-www-form-urlencoded'
    },
    data:{
        'password':'secret',
        'username':'admin',
        'grant_type':'password'
    }
}, (err, res) => pm.environment.set("token", res.json().access_token));

It doesn't work with the response : Full authentication is required to access this resource.

What is wrong?

Thanks

Body:
You could change the data section to something like this?

body:{
   mode:"urlencoded",
   urlencoded:[
      {
         key:"grant_type",
         value:"password"
      },
      {
         key:"username",
         value:"admin"
      },
      {
         key:"password",
         value:"secret"
      }
   ]
}

A great resource for pm.sendRequest() examples can be found here


问:
mailchimp3 (Python-mailchimp-api) How to set tags
I tried:

```<code>    client.lists.members.create('1111111', {
        'email_address' : 'frogger116@gmail.com',
        'status'        : 'subscribed',
        "tags": [{'name': 'frogger', 'status' : 'active'}],
    })
</code>```

and get:

```<code>mailchimp3.mailchimpclient.MailChimpError: {
    'type': 'http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/',
    'title': 'Invalid Resource',
    'status': 400,
    'detail': 'Expected argument of type "string", "stdClass" given',
    'instance': '5ae1b966-ed35-49f1-ad32-0a39c3d63593'
}
</code>```

Without the "tags" line the satement works

答:
This works for me (you need hash the email address)</p>

```<code>hash = get_subscriber_hash(email_address)

data = {
        'tags': [
            {'name': 'foo', 'status': 'active'},
            {'name': 'bar', 'status': 'inactive'}
        ]
}

client.lists.members.tags.update(list_id=list_id, subscriber_hash=hash, data=data)
</code>```

Body:
I tried:

    client.lists.members.create('1111111', {
        'email_address' : 'frogger116@gmail.com',
        'status'        : 'subscribed',
        "tags": [{'name': 'frogger', 'status' : 'active'}],
    })

and get:

mailchimp3.mailchimpclient.MailChimpError: {
    'type': 'http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/',
    'title': 'Invalid Resource',
    'status': 400,
    'detail': 'Expected argument of type "string", "stdClass" given',
    'instance': '5ae1b966-ed35-49f1-ad32-0a39c3d63593'
}

Without the "tags" line the satement works

Body:
This works for me (you need hash the email address)

hash = get_subscriber_hash(email_address)

data = {
        'tags': [
            {'name': 'foo', 'status': 'active'},
            {'name': 'bar', 'status': 'inactive'}
        ]
}

client.lists.members.tags.update(list_id=list_id, subscriber_hash=hash, data=data)


问:
Why functions not called during runtime?
I am new to C. I want to design a simple data manager. in the main function, I call the login function and it works fine. Then, I print a statement and call the choosetask function. The cmd waits for me to input the tasknumber. Then the program ends without calling the next functions.  </p>

```<code>int main()
{
  login ();
  printf ("choose a task to perform (write its number to go):\n 1- Insert the data of a new patient.\n 2- Assign a patient to a hospital.\n 3- Load a hospital patients data.\n 4- Delete a patient data.\n 5- Exit.\n\n");
  choosetask ();
  return 0;
}
</code>```

```<code>void choosetask ()
{
    int tasknumber;

    scanf ("%d", tasknumber);

    if (tasknumber == 1)
    {
    newpatient ();
    }

    else if (tasknumber == 2)
    {
    assignpatient ();
    }

    else if (tasknumber == 3)
    {
    loadhospitaldata ();
    }

    else if (tasknumber == 4)
    {
    deletepatient ();
    }

    else if (tasknumber == 5)
    {
        exit(0);
    }

    else
    {
      printf ("Choose a valid task number, please\n");
      choosetask ();
    }
}
</code>```

答:
If you use gcc in command line mode (here with Linux) with following source code:

```<code>$ cat test.c
#include <stdio.h>

int main(int argc, char **argv)
{
    int tasknumber;
    scanf ("%d", tasknumber);
    return 0;
}
</code>```

you get:

```<code>$ gcc -Wall test.c
test.c: In function ‘main’:
test.c:6:5: attention : format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=]
     scanf ("%d", tasknumber);
     ^
test.c:6:11: attention : ‘tasknumber’ is used uninitialized in this function [-Wuninitialized]
     scanf ("%d", tasknumber);
           ^
</code>```

If you fix your source code:

```<code>$ cat test.c
#include <stdio.h>

int main(int argc, char **argv)
{
    int tasknumber;
    scanf ("%d", &tasknumber);
    return 0;
}
</code>```

you get no more warnings:

```<code>$ gcc -Wall test.c
$
</code>```

Note: this is just an example to get a first level of warnings. You can also use other gcc options like-pedantic to get more warnings or -std=c11 to check with respect to C11 standard.

Body:
I am new to C. I want to design a simple data manager. in the main function, I call the login function and it works fine. Then, I print a statement and call the choosetask function. The cmd waits for me to input the tasknumber. Then the program ends without calling the next functions.

int main()
{
  login ();
  printf ("choose a task to perform (write its number to go):\n 1- Insert the data of a new patient.\n 2- Assign a patient to a hospital.\n 3- Load a hospital patients data.\n 4- Delete a patient data.\n 5- Exit.\n\n");
  choosetask ();
  return 0;
}

void choosetask ()
{
    int tasknumber;

    scanf ("%d", tasknumber);

    if (tasknumber == 1)
    {
    newpatient ();
    }

    else if (tasknumber == 2)
    {
    assignpatient ();
    }

    else if (tasknumber == 3)
    {
    loadhospitaldata ();
    }

    else if (tasknumber == 4)
    {
    deletepatient ();
    }

    else if (tasknumber == 5)
    {
        exit(0);
    }

    else
    {
      printf ("Choose a valid task number, please\n");
      choosetask ();
    }
}

Body:
If you use gcc in command line mode (here with Linux) with following source code:

$ cat test.c
#include <stdio.h>

int main(int argc, char **argv)
{
    int tasknumber;
    scanf ("%d", tasknumber);
    return 0;
}

you get:

$ gcc -Wall test.c
test.c: In function ‘main’:
test.c:6:5: attention : format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=]
     scanf ("%d", tasknumber);
     ^
test.c:6:11: attention : ‘tasknumber’ is used uninitialized in this function [-Wuninitialized]
     scanf ("%d", tasknumber);
           ^

If you fix your source code:

$ cat test.c
#include <stdio.h>

int main(int argc, char **argv)
{
    int tasknumber;
    scanf ("%d", &tasknumber);
    return 0;
}

you get no more warnings:

$ gcc -Wall test.c
$

Note: this is just an example to get a first level of warnings. You can also use other gcc options like-pedantic to get more warnings or -std=c11 to check with respect to C11 standard.


问:
How to get the remote/peer IP address from an SSL/ssl_st structure in C?
The things I have previously tried are getting the socket fd from SSL_get_wfd and then passing it to getpeername. I also looked the the BIO object/functions but without any luck. Attempted to look at the openSSL implementation in /usr/include/openssl but then again with no luck.

Does anyone know how to get the remote IP address (and port) to which an openSSL socket is connected?

Some context:

```<code>socket fd: 64 // the file descriptor doesn't look incorrect (to me)
after getaddress, socklen: 28 // the length of the plausible address also looks correct
sockaddr ptr: 0x7b0b0fcac0, val: 0x0 // the pointer is empty despite being allocated :(
</code>```

edit: the documentation I based my work on:
https://docs.huihoo.com/doxygen/openssl/1.0.1c/structssl__st.html

答:
Frida has nice features related to Sockets.

        var address = Socket.peerAddress(fd);
        // Assert address not null
        console.log(fd, address.ip + ':' + address.port);
```

<p>View Sockets activity;</p>

<pre class="lang-js prettyprint-override"><code>Process
  .getModuleByName({ linux: 'libc.so', darwin: 'libSystem.B.dylib', windows: 'ws2_32.dll' }[Process.platform])
  .enumerateExports().filter(ex => ex.type === 'function' && ['connect', 'recv', 'send', 'read', 'write'].some(prefix => ex.name.indexOf(prefix) === 0))
  .forEach(ex => {
    Interceptor.attach(ex.address, {
      onEnter: function (args) {
        var fd = args[0].toInt32();
        if (Socket.type(fd) !== 'tcp')
          return;
        var address = Socket.peerAddress(fd);
        if (address === null)
          return;
        console.log(fd, ex.name, address.ip + ':' + address.port);
      }
    })
  })
</code>```

Output example

```<code>$ frida -Uf com.example.app -l script.js --no-pause
[Android Model-X::com.example.app]->
117 write 5.0.2.1:5242
117 read 5.0.2.1:5242
135 write 5.0.2.1:4244
135 read 5.0.2.1:4244
135 read 5.0.2.1:4244
</code>```

Body:
The things I have previously tried are getting the socket fd from SSL_get_wfd and then passing it to getpeername. I also looked the the BIO object/functions but without any luck. Attempted to look at the openSSL implementation in /usr/include/openssl but then again with no luck.

Does anyone know how to get the remote IP address (and port) to which an openSSL socket is connected?

Some context:

socket fd: 64 // the file descriptor doesn't look incorrect (to me)
after getaddress, socklen: 28 // the length of the plausible address also looks correct
sockaddr ptr: 0x7b0b0fcac0, val: 0x0 // the pointer is empty despite being allocated :(

edit: the documentation I based my work on:
https://docs.huihoo.com/doxygen/openssl/1.0.1c/structssl__st.html

Body:
Frida has nice features related to Sockets.

        var address = Socket.peerAddress(fd);
        // Assert address not null
        console.log(fd, address.ip + ':' + address.port);

View Sockets activity;

Process
  .getModuleByName({ linux: 'libc.so', darwin: 'libSystem.B.dylib', windows: 'ws2_32.dll' }[Process.platform])
  .enumerateExports().filter(ex => ex.type === 'function' && ['connect', 'recv', 'send', 'read', 'write'].some(prefix => ex.name.indexOf(prefix) === 0))
  .forEach(ex => {
    Interceptor.attach(ex.address, {
      onEnter: function (args) {
        var fd = args[0].toInt32();
        if (Socket.type(fd) !== 'tcp')
          return;
        var address = Socket.peerAddress(fd);
        if (address === null)
          return;
        console.log(fd, ex.name, address.ip + ':' + address.port);
      }
    })
  })

Output example

$ frida -Uf com.example.app -l script.js --no-pause
[Android Model-X::com.example.app]->
117 write 5.0.2.1:5242
117 read 5.0.2.1:5242
135 write 5.0.2.1:4244
135 read 5.0.2.1:4244
135 read 5.0.2.1:4244


问:
How to create a file with content and download it with THYMELEAF
I'm working on a spring boot project with thymeleaf and I need to create a file and put some lines on it then send it for the user to download it.

@PostMapping("/filegenerator")
public String createFile(@ModelAttribute("page") Page page, Model model) {
    List<String> lines = new ArrayList<String>();

    //Some code ..........

    lines.forEach(l->{
        System.out.println(l);
    });

    //Here I need to create a file with the List of lines

    //And also put some code to download it

    return "filegenerator";
}
```

答:
@Kamil janowski

This is how it looks like now

```<code>@PostMapping("/filegenerator")
public String createFile(@ModelAttribute("page") Page page, Model model,HttpServletResponse response) throws IOException{

    List<String> lines = new ArrayList<String>();
    if(page.getTables().get(0).getName()!="") {
    List<String> output = so.createTable(page.getTables());
    output.forEach(line -> lines.add(line));
    }
    if(page.getInserttables().get(0).getName()!="") {
        List<String> output = so.insert(page.getInserttables());
        output.forEach(line -> lines.add(line));
    }
    if(page.getUpdatetables().get(0).getName()!="") {
        List<String> output = so.update(page.getUpdatetables());
        output.forEach(line -> lines.add(line));
    }

    lines.forEach(l->{
        System.out.println(l);
    });

    InputStream is = new ByteArrayInputStream(lines.stream().collect(Collectors.joining("\n")).getBytes());
    IOUtils.copy(is, response.getOutputStream());
    response.setContentType("application/sql");
    response.setHeader("Content-Disposition", "attachment; filename=\"myquery.sql\"");
    response.flushBuffer();

    model.addAttribute("page", getPage());
    return "filegenerator";
}
</code>```

Body:
@Kamil janowski

This is how it looks like now

@PostMapping("/filegenerator")
public String createFile(@ModelAttribute("page") Page page, Model model,HttpServletResponse response) throws IOException{

    List<String> lines = new ArrayList<String>();
    if(page.getTables().get(0).getName()!="") {
    List<String> output = so.createTable(page.getTables());
    output.forEach(line -> lines.add(line));
    }
    if(page.getInserttables().get(0).getName()!="") {
        List<String> output = so.insert(page.getInserttables());
        output.forEach(line -> lines.add(line));
    }
    if(page.getUpdatetables().get(0).getName()!="") {
        List<String> output = so.update(page.getUpdatetables());
        output.forEach(line -> lines.add(line));
    }

    lines.forEach(l->{
        System.out.println(l);
    });

    InputStream is = new ByteArrayInputStream(lines.stream().collect(Collectors.joining("\n")).getBytes());
    IOUtils.copy(is, response.getOutputStream());
    response.setContentType("application/sql");
    response.setHeader("Content-Disposition", "attachment; filename=\"myquery.sql\"");
    response.flushBuffer();

    model.addAttribute("page", getPage());
    return "filegenerator";
}


问:
Uncaught Dailymotion Auth Required Exception
I'm trying to use the Dailymotion API. I followed every instruction possible but I keep getting errors, although I'm using the changes that people have suggested in other posts ie. DailyMotion Invalid authorization code

The errors I'm getting

Fatal error: Uncaught DailymotionAuthRequiredException in
  /Library/WebServer/Documents/basic/Dailymotion.php:582 Stack trace:

0 /Library/WebServer/Documents/basic/Dailymotion.php(404):
  Dailymotion->getAccessToken()

1 /Library/WebServer/Documents/basic/Dailymotion.php(356):
  Dailymotion->call('GET /file/uploa...', Array)

2 /Library/WebServer/Documents/basic/Dailymotion.php(326):
  Dailymotion->get('/file/upload', Array)

3 /Library/WebServer/Documents/basic/index.php(12):
  Dailymotion->uploadFile(NULL)

4 {main} thrown in /Library/WebServer/Documents/basic/Dailymotion.php
  on line 582

Am I missing something in my php? I've not seen anyone reference the getAccessToken.

```<code><?
include("Dailymotion.php");

$apiKey = "xxxxxxxxxxxxxxx";
$apiSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
$user = "my username";
$pwd = "my password";
$filepath = "Test.mp4";

$api = new Dailymotion();
$api->setGrantType(Dailymotion::GRANT_TYPE_PASSWORD, $apiKey, $apiSecret, array('manage_videos', 'write','delete'), array('username' => $user, 'password' => $pwd));
$url = $api->uploadFile($filepath);
$result = $api->call('video.create', array(
    'url' => $url,
    'title' => $title,
    'description' => $description,
    'private' => 'false',
    'published' => 'true',
));
?>
</code>```

答:
figured out the answer, I kept assuming peoples answers where just as is. I didn't realise I had to put it into another bit to authorise my account.</p>

```<code>
require_once 'Dailymotion.php';
// Account settings
$apiKey        = 'your apikey';
$apiSecret     = 'your secret';
$testUser      = 'your username';
$testPassword  = 'your password';

// Scopes you need to run your tests
$scopes = array(
    'manage_videos',
);
// Dailymotion object instanciation
$api = new Dailymotion();
$api->setGrantType(Dailymotion::GRANT_TYPE_AUTHORIZATION, $apiKey, $apiSecret);

try
{
    // The following line will actually try to authenticate before making the API call.
    // * The SDK takes care of retrying if the access token has expired.
    // * The SDK takes care of storing the access token itself using its `readSession()`
    //   and `storeSession()` methods that are made to be overridden in an extension
    //   of the class if you want a different storage than provided by default.
    $url = $api->uploadFile('Test.mp4');
    $result = $api->call('video.create', array(
    'url' => $url,
    'title' => 'prove this works',
    'description' => 'THis is purely a test',
    'private' => 'false',
    'published' => 'true'
));
    var_dump($result);
}
catch (DailymotionAuthRequiredException $e)
{
    // If the SDK doesn't have any access token stored in memory, it tries to
    // redirect the user to the Dailymotion authorization page for authentication.
    return header('Location: ' . $api->getAuthorizationUrl());
}
catch (DailymotionAuthRefusedException $e)
{

}

?>
</code>```

Body:
I'm trying to use the Dailymotion API. I followed every instruction possible but I keep getting errors, although I'm using the changes that people have suggested in other posts ie. DailyMotion Invalid authorization code

The errors I'm getting

Fatal error: Uncaught DailymotionAuthRequiredException in
  /Library/WebServer/Documents/basic/Dailymotion.php:582 Stack trace:

0 /Library/WebServer/Documents/basic/Dailymotion.php(404):
  Dailymotion->getAccessToken()

1 /Library/WebServer/Documents/basic/Dailymotion.php(356):
  Dailymotion->call('GET /file/uploa...', Array)

2 /Library/WebServer/Documents/basic/Dailymotion.php(326):
  Dailymotion->get('/file/upload', Array)

3 /Library/WebServer/Documents/basic/index.php(12):
  Dailymotion->uploadFile(NULL)

4 {main} thrown in /Library/WebServer/Documents/basic/Dailymotion.php
  on line 582

Am I missing something in my php? I've not seen anyone reference the getAccessToken.

<?
include("Dailymotion.php");

$apiKey = "xxxxxxxxxxxxxxx";
$apiSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
$user = "my username";
$pwd = "my password";
$filepath = "Test.mp4";

$api = new Dailymotion();
$api->setGrantType(Dailymotion::GRANT_TYPE_PASSWORD, $apiKey, $apiSecret, array('manage_videos', 'write','delete'), array('username' => $user, 'password' => $pwd));
$url = $api->uploadFile($filepath);
$result = $api->call('video.create', array(
    'url' => $url,
    'title' => $title,
    'description' => $description,
    'private' => 'false',
    'published' => 'true',
));
?>

Body:
figured out the answer, I kept assuming peoples answers where just as is. I didn't realise I had to put it into another bit to authorise my account.

require_once 'Dailymotion.php';
// Account settings
$apiKey        = 'your apikey';
$apiSecret     = 'your secret';
$testUser      = 'your username';
$testPassword  = 'your password';

// Scopes you need to run your tests
$scopes = array(
    'manage_videos',
);
// Dailymotion object instanciation
$api = new Dailymotion();
$api->setGrantType(Dailymotion::GRANT_TYPE_AUTHORIZATION, $apiKey, $apiSecret);

try
{
    // The following line will actually try to authenticate before making the API call.
    // * The SDK takes care of retrying if the access token has expired.
    // * The SDK takes care of storing the access token itself using its `readSession()`
    //   and `storeSession()` methods that are made to be overridden in an extension
    //   of the class if you want a different storage than provided by default.
    $url = $api->uploadFile('Test.mp4');
    $result = $api->call('video.create', array(
    'url' => $url,
    'title' => 'prove this works',
    'description' => 'THis is purely a test',
    'private' => 'false',
    'published' => 'true'
));
    var_dump($result);
}
catch (DailymotionAuthRequiredException $e)
{
    // If the SDK doesn't have any access token stored in memory, it tries to
    // redirect the user to the Dailymotion authorization page for authentication.
    return header('Location: ' . $api->getAuthorizationUrl());
}
catch (DailymotionAuthRefusedException $e)
{

}

?>


问:
jQuery Tabs UI: change two different data attributes on tab change
I'm able to swap an image in a div on each tab change according to a data attribute in each tab's html. But I also want to change another div for the photographer's credit, and I'm not doing something right, even though it should be easy. jsfiddle here: http://jsfiddle.net/8muBm/56/

```<code>$("#tabs").tabs({
    select: function($event, ui) { /* Extract the image from the active tab: */
        var img = $(ui.panel).data("image");

        /* Animate the header out, set the background css, then animate back in: */

        $("#headerwrapper").animate({
            opacity: 'toggle'
        }, function() {
            $(this).css("background-image", "url(" + img + ")").animate({
                opacity: 'toggle'
            });

            /* credit changer */

            $("#photocredit").text($(this).attr("data-credit"));

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

答:
I think your $(this) is pointing to the div "headerwrapper" tag.

Try:

```<code>$("#tabs").tabs({
    select: function($event, ui) { /* Extract the image from the active tab: */
    var img = $(ui.panel).data("image");

    /* Animate the header out, set the background css, then animate back in: */

    $("#headerwrapper").animate({
        opacity: 'toggle'
        }, function() {
            $(this).css("background-image", "url(" + img + ")").animate({
                opacity: 'toggle'
            });

            /* credit changer */

            $("#photocredit").text($(ui.panel).data("credit"));

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

Body:
I'm able to swap an image in a div on each tab change according to a data attribute in each tab's html. But I also want to change another div for the photographer's credit, and I'm not doing something right, even though it should be easy. jsfiddle here: http://jsfiddle.net/8muBm/56/

$("#tabs").tabs({
    select: function($event, ui) { /* Extract the image from the active tab: */
        var img = $(ui.panel).data("image");

        /* Animate the header out, set the background css, then animate back in: */

        $("#headerwrapper").animate({
            opacity: 'toggle'
        }, function() {
            $(this).css("background-image", "url(" + img + ")").animate({
                opacity: 'toggle'
            });

            /* credit changer */

            $("#photocredit").text($(this).attr("data-credit"));

        });
    }
});

Body:
I think your $(this) is pointing to the div "headerwrapper" tag.

Try:

$("#tabs").tabs({
    select: function($event, ui) { /* Extract the image from the active tab: */
    var img = $(ui.panel).data("image");

    /* Animate the header out, set the background css, then animate back in: */

    $("#headerwrapper").animate({
        opacity: 'toggle'
        }, function() {
            $(this).css("background-image", "url(" + img + ")").animate({
                opacity: 'toggle'
            });

            /* credit changer */

            $("#photocredit").text($(ui.panel).data("credit"));

        });
    }
});


答:
You don't impact on text varible. You should replace your code to

def censor(text,word):
  return text.replace(word, "*" * len(word)) # -> it will replace word to * if word in text else it will do nothing
```

Title: Simple censor function does not work in python

Body:
I have created a function that takes a text and a word to censor in the text. It should return the text but with the censor word replaced with ****.
But it does not censor the word.

def censor(text,word):
  if word in text:
    word="*"*len(word)
  return text

What's wrong with the code?


答:
You need to replace the value in the original text, modifying the iteration variable won't have any effect, try this:

```<code>def censor(text, word):
    return text.replace(word, '*' * len(word))
</code>```

Also it's not necessary to check if the word is in the text, if it's not the replace operation will do nothing.

Body:
You need to replace the value in the original text, modifying the iteration variable won't have any effect, try this:

def censor(text, word):
    return text.replace(word, '*' * len(word))

Also it's not necessary to check if the word is in the text, if it's not the replace operation will do nothing.


问:
Why is parameter to string.indexOf method is an int in Java
I am wondering why the parameter to indexOf method an int , when the description says a char.

public int indexOf(int ch)

```<code>Returns the index within this string of the first occurrence of the specified **character**
</code>```

http://download.oracle.com/javase/1,5.0/docs/api/java/lang/String.html#indexOf%28int%29

```<code>Also, both of these compiles fine:
char c = 'p';
str.indexOf(2147483647);
str.indexOf(c);
</code>```

a]Basically, what I am confused about is int in java is 32bit , while unicode characters are 16 bits .

b]Why not use the character themselves rather than using int . Is this any performance optimization ?. Are chars difficult to represent than int ? How ?

I assume this should be simple reasoning for this and that makes me know about it even more !

Thanks!

答:
The real reason is that indexOf(int) expects a Unicode codepoint, not a 16-bit UTF-16 "character".  Unicode code points are actually up to 21 bits in length.

(The UTF-16 representation of a longer codepoint is actually 2 16-bit "character" values.  These values are known as leading and trailing surrogates; D80016 to DBFF16, and DC0016 to DFFF16 respectively; see Unicode FAQ - UTF-8, UTF-16, UTF-32 & BOM for the gory details.)

If you give indexOf(int) a code point > 65535 it will search for the pair of UTF-16 characters that encode the codepoint.

This is stated by the javadoc (albeit not very clearly), and an examination of the code indicates that this is indeed how the method is implemented.

Why not just use 16-bit characters ?

That's pretty obvious.  If they did that, there wouldn't be an easy way to locate code points greater than 65535 in Strings.  That would be a major problem for people who develop internationalized applications where text may contain such code points.  (A lot of supposedly internationalized applications make the incorrect assumption that a char represents a code point.  Often it doesn't matter, but increasingly often it does.)

But it shouldn't make any difference to you.  The method will still work if your Strings consist of only 16 bit codes ... or, for that matter, of only ASCII codes.

Body:
I am wondering why the parameter to indexOf method an int , when the description says a char.

public int indexOf(int ch)

Returns the index within this string of the first occurrence of the specified **character**

http://download.oracle.com/javase/1,5.0/docs/api/java/lang/String.html#indexOf%28int%29

Also, both of these compiles fine:
char c = 'p';
str.indexOf(2147483647);
str.indexOf(c);

a]Basically, what I am confused about is int in java is 32bit , while unicode characters are 16 bits .

b]Why not use the character themselves rather than using int . Is this any performance optimization ?. Are chars difficult to represent than int ? How ?

I assume this should be simple reasoning for this and that makes me know about it even more !

Thanks!


问:
How often can I rename discord channel's name?
This is not a post about HOW to change channel's name (I know it).

I have an international server using several bots. And we all depend on UTC time (to coordinate through the world). So there was borned a solution to make a time-bot which will show current UTC-time in the dedicated channel nobody can visit. And yes, precision is necessary, even seconds.

I created a voice channel with permissions not to join for @everyone. Everything worked fine, it updated every 1000 ms. Then (after several months of good work) something was broke, it started updating incorrect. I've increased update interval up to 5000 ms and it have started to work fine... until yesterday.

Now it doesn't work anymore. Even if I increase interval much more. It works sometimes I don't really know what the interval is, it's huge and unpredictable.. the time-bot is broken for now and cannot be used anymore in that case.

Is there any restrictions for updating channel name? I can't find any information about this in available documentations.

Client.setInterval(() => {
  const { h, m, s } = getTime();
  channel.edit({ name: `${getClockEmoji({ h, m })} UTC: ${h}-${m}-${s}` }).catch((err) => console.log(err));
}, updateInterval);
```

Providing data is correct, 'cause I send it to console and it updates as good as I need in interval I set. But channel name not updates that often..

Does discord filter too often update requests?

discord.js version is v.12.2.0

答:
This seems to likely be an issue directly related to rate limiting:
https://discord.com/developers/docs/topics/rate-limits

IP addresses that make too many invalid HTTP requests are automatically and temporarily restricted from accessing the Discord API. Currently, this limit is 10,000 per 10 minutes. An invalid request is one that results in 401, 403, or 429 statuses.

For every API request made, we return optional HTTP response headers containing the rate limit encountered during your request.

You should probably decrease the interval by a considerable amount to reduce the risk of the IP being restricted.

Body:
This is not a post about HOW to change channel's name (I know it).

I have an international server using several bots. And we all depend on UTC time (to coordinate through the world). So there was borned a solution to make a time-bot which will show current UTC-time in the dedicated channel nobody can visit. And yes, precision is necessary, even seconds.

I created a voice channel with permissions not to join for @everyone. Everything worked fine, it updated every 1000 ms. Then (after several months of good work) something was broke, it started updating incorrect. I've increased update interval up to 5000 ms and it have started to work fine... until yesterday.

Now it doesn't work anymore. Even if I increase interval much more. It works sometimes I don't really know what the interval is, it's huge and unpredictable.. the time-bot is broken for now and cannot be used anymore in that case.

Is there any restrictions for updating channel name? I can't find any information about this in available documentations.

Client.setInterval(() => {
  const { h, m, s } = getTime();
  channel.edit({ name: `${getClockEmoji({ h, m })} UTC: ${h}-${m}-${s}` }).catch((err) => console.log(err));
}, updateInterval);

Providing data is correct, 'cause I send it to console and it updates as good as I need in interval I set. But channel name not updates that often..

Does discord filter too often update requests?

discord.js version is v.12.2.0


问:
Build React component from string with placeholders
I need to dynamically build a React component based on consistently structured text in an unknown order. How do I replace the placeholder numbers (identified in some consistent way, see below) with corresponding components that consume the placeholder as props?

```<code>const text = "some (1) arbitrary amount of [2] text";

return (
  <div>
    some
    <Component1 var={1} />
    arbitrary amount of
    <Component2 var={2} />
    text
   </div>
)
</code>```

The placement and order of [] and () is not consistent, so that:

```<code>const text = "[2] some arbitrary amount (1) of text";

return (
  <div>
    <Component2 var={2} />
    some arbitrary amount
    <Component1 var={1} />
    of text
   </div>
)
</code>```

答:
Yes possible, you could do something like this</p>

```<code>  const C1 = () => " C1 ";
  const C2 = () => " C2 ";
  const dynamics = { // the ids of these dynamic components that will be used as placeholders
    1: C1,
    2: C2
  };
  const text = "some (1) arbitrary amount of [2] text";
   // you may want to customize this function to suit your needs
  const isDynamic = src => {
    return (
      (src[0] === "(" && src[src.length - 1] === ")") ||
      ("[" && src[src.length - 1] === "]")
    );
  };
  const components = text.split(" ");

// dont forget to add a key to the mapped components, but i will leave this to you, since i dont have all the requirements about the dynamic components, and whether there might be duplicates
  return (
    <div >
      {components.map(comp => {

        if (isDynamic(comp)) {
          const dynamicCompId = parseInt(
            comp
              .split("")
              .filter(x => !Number.isNaN(+x))
              .join("")
          );
          const Dynamic = dynamics[dynamicCompId];
          return <Dynamic   />;
        }
        return comp;
      })}
    </div>
  );
</code>```

Body:
I need to dynamically build a React component based on consistently structured text in an unknown order. How do I replace the placeholder numbers (identified in some consistent way, see below) with corresponding components that consume the placeholder as props?

const text = "some (1) arbitrary amount of [2] text";

return (

    some
    <Component1 var={1} />
    arbitrary amount of
    <Component2 var={2} />
    text

)

The placement and order of [] and () is not consistent, so that:

const text = "[2] some arbitrary amount (1) of text";

return (

    <Component2 var={2} />
    some arbitrary amount
    <Component1 var={1} />
    of text

)

Body:
Yes possible, you could do something like this

  const C1 = () => " C1 ";
  const C2 = () => " C2 ";
  const dynamics = { // the ids of these dynamic components that will be used as placeholders
    1: C1,
    2: C2
  };
  const text = "some (1) arbitrary amount of [2] text";
   // you may want to customize this function to suit your needs
  const isDynamic = src => {
    return (
      (src[0] === "(" && src[src.length - 1] === ")") ||
      ("[" && src[src.length - 1] === "]")
    );
  };
  const components = text.split(" ");

// dont forget to add a key to the mapped components, but i will leave this to you, since i dont have all the requirements about the dynamic components, and whether there might be duplicates
  return (
    <div >
      {components.map(comp => {

        if (isDynamic(comp)) {
          const dynamicCompId = parseInt(
            comp
              .split("")
              .filter(x => !Number.isNaN(+x))
              .join("")
          );
          const Dynamic = dynamics[dynamicCompId];
          return <Dynamic   />;
        }
        return comp;
      })}
    </div>
  );


问:
Header of file compiled by bluespec
I have a file with the .bo extension.
After some researches it seems be built with bluespec which is use with risc-V architecture.
My objective is to reverse this file.

When i do:

```<code>file myfile.bo
myfile.bo: data
</code>```

So, I don't know if it's a good "format" for the file. Or what must be the return of the file command on a .bo file?
What is the basic header file for a verilog file?

Thanks for your help.

答: Verilog is definately not the language format of preference for using other software files except C,C++...I'd suggest to convert the bluespec file into C and then maybe you can get lucky.</p>

Title: Header of file compiled by bluespec

Body:
I have a file with the .bo extension.
After some researches it seems be built with bluespec which is use with risc-V architecture.
My objective is to reverse this file.

When i do:

file myfile.bo
myfile.bo: data

So, I don't know if it's a good "format" for the file. Or what must be the return of the file command on a .bo file?
What is the basic header file for a verilog file?

Thanks for your help.