答:
You should replace each space with different random elements of the array. replacingOccurrences method replaces all ranges at once. Get the range of space one by one and replace with unique random elements

```<code>let randomArray:[String] = ["a","b","c","d"]
var passedSentence = "This is a long text"
var start = passedSentence.startIndex
while let range = passedSentence[start...].rangeOfCharacter(from: .whitespaces),
    let random1 = randomArray.randomElement(),
    let random2 = randomArray.randomElement()  {
    let replacementString = " \(random1) \(random2) "
    passedSentence.replaceSubrange(range, with: " \(random1) \(random2) ")
    start = passedSentence.index(range.upperBound, offsetBy: replacementString.count)
}
print(passedSentence)
</code>```

To get the random element from an array don't use randomArray[Int.random(in: 0...103)]. You can use randomElement()

Title: How can I individually replace each occurence of a string?

Body:
You should replace each space with different random elements of the array. replacingOccurrences method replaces all ranges at once. Get the range of space one by one and replace with unique random elements

let randomArray:[String] = ["a","b","c","d"]
var passedSentence = "This is a long text"
var start = passedSentence.startIndex
while let range = passedSentence[start...].rangeOfCharacter(from: .whitespaces),
    let random1 = randomArray.randomElement(),
    let random2 = randomArray.randomElement()  {
    let replacementString = " \(random1) \(random2) "
    passedSentence.replaceSubrange(range, with: " \(random1) \(random2) ")
    start = passedSentence.index(range.upperBound, offsetBy: replacementString.count)
}
print(passedSentence)

To get the random element from an array don't use randomArray[Int.random(in: 0...103)]. You can use randomElement()


来源: stackexchange

问:
Keep getting "identifier expected" and "; expected" error messages
I am trying to make a high score system for my game in unity and am not really sure on how to do that, but I tried this code nonetheless and I keep receiving error messages.

I have tried to search up these errors but since I am quite new to unity and coding in general none of the solutions there make sense to me.

```<code>public Transform player;
public Text scoreText;
public Text highScore;

// Update is called once per frame
void Update()
{
    scoreText.text = player.position.z.ToString("0");
    scoreText = scoreText.int.Parse;

    if (scoreText > PlayerPrefs.GetInt("High Score", 0)) ;
    {
        PlayerPrefs.SetInt("High Score", scoreText);
        highScore.text = scoreText.ToString;
    }
</code>```

These are the error messages that show up

Assets\Score.cs(15,31): error CS1001: Identifier expected

Assets\Score.cs(15,31): error CS1002: ; expected

答:
What you have presently won't work. It would be nice  if you could learn the basics syntax of C# to possibly avoid problems like this.

Text is a class and scoreText in this case is an instance of the Text class. You can't just do this:

```<code>scoreText = scoreText.int.Parse;
</code>```

Unless of course, scoreText.int.Parse (doesn't work though) returns a Text.

I think what you're trying to do is to get the player's position and convert to int, so you could save the value using PlayerPrefs.

You can simply create an int variable.

```<code>private int _score;
</code>```

Then use like this:

```<code>_score=int.Parse(scoreText.text);
</code>```

You can the save using PlayerPrefs.

```<code>PlayerPrefs.SetInt("High Score", _score);
</code>```

I hope this helps.

There is also an error on this line:

```<code>highScore.text = scoreText.ToString;
</code>```

Should be :

```<code>highScore.text = scoreText.ToString();
</code>```

Because ToString() is a method.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to make a high score system for my game in unity and am not really sure on how to do that, but I tried this code nonetheless and I keep receiving error messages.

I have tried to search up these errors but since I am quite new to unity and coding in general none of the solutions there make sense to me.

public Transform player;
public Text scoreText;
public Text highScore;

// Update is called once per frame
void Update()
{
    scoreText.text = player.position.z.ToString("0");
    scoreText = scoreText.int.Parse;

    if (scoreText > PlayerPrefs.GetInt("High Score", 0)) ;
    {
        PlayerPrefs.SetInt("High Score", scoreText);
        highScore.text = scoreText.ToString;
    }

These are the error messages that show up

Assets\Score.cs(15,31): error CS1001: Identifier expected

Assets\Score.cs(15,31): error CS1002: ; expected

Body:
What you have presently won't work. It would be nice  if you could learn the basics syntax of C# to possibly avoid problems like this.

Text is a class and scoreText in this case is an instance of the Text class. You can't just do this:

scoreText = scoreText.int.Parse;

Unless of course, scoreText.int.Parse (doesn't work though) returns a Text.

I think what you're trying to do is to get the player's position and convert to int, so you could save the value using PlayerPrefs.

You can simply create an int variable.

private int _score;

Then use like this:

_score=int.Parse(scoreText.text);

You can the save using PlayerPrefs.

PlayerPrefs.SetInt("High Score", _score);

I hope this helps.

There is also an error on this line:

highScore.text = scoreText.ToString;

Should be :

highScore.text = scoreText.ToString();

Because ToString() is a method.


问:
Make a login into dbo for a database in SQL Server
I am attempting to migrate from SQL Server 2005 to SQL Server 2008. Both of these database instances are hosted on 3rd party shared servers that I do not have full permissions to. They are using mixed mode authentication.

I am running into trouble setting up the new database the same way the old one was set up. Specifically, the new web-based control panel doesn't allow a dbo to be specified when creating a new database and then when using Red Gate SQL Compare to sync up the schemas I am having problems because some objects (that don't explicitly specify dbo in the script) are being created with the prefix of the user account rather dbo.

I have poured over the documentation trying to find a way to force my login "user1" as dbo to the "db1" database. I came to the conclusion that the script should look like this:

```<code>ALTER AUTHORIZATION ON DATABASE::db1 TO user1
</code>```

Before running this script, the login "user1" already exists, but is not a user for database "db1". Note I had to submit this script to the support of my hosting company in order to run it. According to the hosting company the statement successfully executes, however when I compare the databases using SQL Compare the user "user1" has not been physically added to the database like it was under SQL Server 2005. When trying to add it using the script:

```<code>CREATE USER [user1] FOR LOGIN [user1] WITH DEFAULT_SCHEMA=[dbo]
</code>```

I get the error message:

```<code>"The login already has an account under a different username"
</code>```

I have tried dropping all of the other users from the database, but the error message still persists - which I find odd.

While I could just fix the scripts by explicitly specifying dbo, this would inevitably be a time bomb waiting to go off because if any new script were introduced that didn't explicitly specify dbo there would be a failure during synchronization. Since some of the scripts are from 3rd parties, this is not a good solution.

So my questions: Is there another statement that I need to run in order to add "user1" to the database as a user that is dbo? Is there anything that has changed in the implementation between SQL Server 2005 and SQL Server 2008 R2 that could cause these inconsistencies?

I am unfortunately not able to test to find an answer to the second one because I don't have another SQL Server 2008 database to test with and I don't have full access to do anything I want on this one.

The old database was created through a control panel which forced dbo to be specified and the new one doesn't allow dbo to be specified when creating a database.

答:
From what i have gathered the following should suffice.

```<code>ALTER USER [user1] WITH DEFAULT_SCHEMA=[dbo]
</code>```

The create wasnt working as it already existed.

ContentLicense: CC BY-SA 3.0

Body:
I am attempting to migrate from SQL Server 2005 to SQL Server 2008. Both of these database instances are hosted on 3rd party shared servers that I do not have full permissions to. They are using mixed mode authentication.

I am running into trouble setting up the new database the same way the old one was set up. Specifically, the new web-based control panel doesn't allow a dbo to be specified when creating a new database and then when using Red Gate SQL Compare to sync up the schemas I am having problems because some objects (that don't explicitly specify dbo in the script) are being created with the prefix of the user account rather dbo.

I have poured over the documentation trying to find a way to force my login "user1" as dbo to the "db1" database. I came to the conclusion that the script should look like this:

ALTER AUTHORIZATION ON DATABASE::db1 TO user1

Before running this script, the login "user1" already exists, but is not a user for database "db1". Note I had to submit this script to the support of my hosting company in order to run it. According to the hosting company the statement successfully executes, however when I compare the databases using SQL Compare the user "user1" has not been physically added to the database like it was under SQL Server 2005. When trying to add it using the script:

CREATE USER [user1] FOR LOGIN [user1] WITH DEFAULT_SCHEMA=[dbo]

I get the error message:

"The login already has an account under a different username"

I have tried dropping all of the other users from the database, but the error message still persists - which I find odd.

While I could just fix the scripts by explicitly specifying dbo, this would inevitably be a time bomb waiting to go off because if any new script were introduced that didn't explicitly specify dbo there would be a failure during synchronization. Since some of the scripts are from 3rd parties, this is not a good solution.

So my questions: Is there another statement that I need to run in order to add "user1" to the database as a user that is dbo? Is there anything that has changed in the implementation between SQL Server 2005 and SQL Server 2008 R2 that could cause these inconsistencies?

I am unfortunately not able to test to find an answer to the second one because I don't have another SQL Server 2008 database to test with and I don't have full access to do anything I want on this one.

The old database was created through a control panel which forced dbo to be specified and the new one doesn't allow dbo to be specified when creating a database.

Body:
From what i have gathered the following should suffice.

ALTER USER [user1] WITH DEFAULT_SCHEMA=[dbo]

The create wasnt working as it already existed.


问:
How to create Toast in Flutter
Can I create something similar to Toasts in Flutter?

Just a tiny notification window that is not directly in the face of the user and does not lock or fade the view behind it.

答:
I would like to provide an alternative solution to use package flushbar.

As the package said: Use this package if you need more customization when notifying your user. For Android developers, it is made to substitute toasts and snackbars.

Another suggestion to use flushbar is How can I show a snackbar after navigator.pop(context) in Flutter?

You can also set flushbarPosition to TOP or BOTTOM:

```<code>    Flushbar(
      title: "Hey Ninja",
      message: "Lorem Ipsum is simply dummy text of the printing and typesetting industry",
      flushbarPosition: FlushbarPosition.TOP,
      flushbarStyle: FlushbarStyle.FLOATING,
      reverseAnimationCurve: Curves.decelerate,
      forwardAnimationCurve: Curves.elasticOut,
      backgroundColor: Colors.red,
      boxShadows: [BoxShadow(color: Colors.blue[800], offset: Offset(0.0, 2.0), blurRadius: 3.0)],
      backgroundGradient: LinearGradient(colors: [Colors.blueGrey, Colors.black]),
      isDismissible: false,
      duration: Duration(seconds: 4),
      icon: Icon(
        Icons.check,
        color: Colors.greenAccent,
      ),
      mainButton: FlatButton(
        onPressed: () {},
        child: Text(
          "CLAP",
          style: TextStyle(color: Colors.amber),
        ),
      ),
      showProgressIndicator: true,
      progressIndicatorBackgroundColor: Colors.blueGrey,
      titleText: Text(
        "Hello Hero",
        style: TextStyle(
            fontWeight: FontWeight.bold, fontSize: 20.0, color: Colors.yellow[600], fontFamily: "ShadowsIntoLightTwo"),
      ),
      messageText: Text(
        "You killed that giant monster in the city. Congratulations!",
        style: TextStyle(fontSize: 18.0, color: Colors.green, fontFamily: "ShadowsIntoLightTwo"),
      ),
    )..show(context);
</code>```

Title: How to create Toast in Flutter

Body:
I would like to provide an alternative solution to use package flushbar.

As the package said: Use this package if you need more customization when notifying your user. For Android developers, it is made to substitute toasts and snackbars.

Another suggestion to use flushbar is How can I show a snackbar after navigator.pop(context) in Flutter?

You can also set flushbarPosition to TOP or BOTTOM:

    Flushbar(
      title: "Hey Ninja",
      message: "Lorem Ipsum is simply dummy text of the printing and typesetting industry",
      flushbarPosition: FlushbarPosition.TOP,
      flushbarStyle: FlushbarStyle.FLOATING,
      reverseAnimationCurve: Curves.decelerate,
      forwardAnimationCurve: Curves.elasticOut,
      backgroundColor: Colors.red,
      boxShadows: [BoxShadow(color: Colors.blue[800], offset: Offset(0.0, 2.0), blurRadius: 3.0)],
      backgroundGradient: LinearGradient(colors: [Colors.blueGrey, Colors.black]),
      isDismissible: false,
      duration: Duration(seconds: 4),
      icon: Icon(
        Icons.check,
        color: Colors.greenAccent,
      ),
      mainButton: FlatButton(
        onPressed: () {},
        child: Text(
          "CLAP",
          style: TextStyle(color: Colors.amber),
        ),
      ),
      showProgressIndicator: true,
      progressIndicatorBackgroundColor: Colors.blueGrey,
      titleText: Text(
        "Hello Hero",
        style: TextStyle(
            fontWeight: FontWeight.bold, fontSize: 20.0, color: Colors.yellow[600], fontFamily: "ShadowsIntoLightTwo"),
      ),
      messageText: Text(
        "You killed that giant monster in the city. Congratulations!",
        style: TextStyle(fontSize: 18.0, color: Colors.green, fontFamily: "ShadowsIntoLightTwo"),
      ),
    )..show(context);


问:
z3 returns unknown when asserting division of 0 by 0 is 1
I was trying out examples from the article Z3: a tutorial. There is an example demonstrating that all functions are total, including "div":

```<code>(push)
(assert (= 1 (div 0 0)))
(check-sat)
;sat (pop)
</code>```

I noticed that z3 version 4.8.5 returns different results depending on whether one uses "push" or not.

With the code below, z3 returns unknown:

```<code>(get-info :version)
;(push)
(assert (= 1 (div 0 0)))
(check-sat)
</code>```

The output from z3 is:

```<code>(:version "4.8.5 - build hashcode 8c085f1a1850")
unknown
</code>```

In contrast, with the code below, z3 returns sat:

```<code>(get-info :version)
(push)
(assert (= 1 (div 0 0)))
(check-sat)
(get-model)
</code>```

The output from z3 is:

```<code>(:version "4.8.5 - build hashcode 8c085f1a1850")
sat
(model
)
</code>```

In the rise4fun tutorial, it says that "The command push creates a new scope by saving the current stack size", it seems that the usage of "push" should not cause different results here since there is only one assertion?

答:
Strictly speaking unknown and sat are not contradictory: The solver is allowed to bail out at any moment and say unknown. For instance, this sort of behavior can happen if you explicitly use tactics.

But you're absolutely correct that it's bizarre push is causing this discrepancy. Please file a ticket at the z3 github issues site: https://github.com/Z3Prover/z3/issues and let us know what you find out!

Body:
I was trying out examples from the article Z3: a tutorial. There is an example demonstrating that all functions are total, including "div":

(push)
(assert (= 1 (div 0 0)))
(check-sat)
;sat (pop)

I noticed that z3 version 4.8.5 returns different results depending on whether one uses "push" or not.

With the code below, z3 returns unknown:

(get-info :version)
;(push)
(assert (= 1 (div 0 0)))
(check-sat)

The output from z3 is:

(:version "4.8.5 - build hashcode 8c085f1a1850")
unknown

In contrast, with the code below, z3 returns sat:

(get-info :version)
(push)
(assert (= 1 (div 0 0)))
(check-sat)
(get-model)

The output from z3 is:

(:version "4.8.5 - build hashcode 8c085f1a1850")
sat
(model
)

In the rise4fun tutorial, it says that "The command push creates a new scope by saving the current stack size", it seems that the usage of "push" should not cause different results here since there is only one assertion?


问:
How to customize object equality for JavaScript Set
New ES 6 (Harmony) introduces new Set object. Identity algorithm used by Set is similar to === operator and so not much suitable for comparing objects:

var set = new Set();
set.add({a:1});
set.add({a:1});
console.log([...set.values()]); // Array [ Object, Object ]
```

How to customize equality for Set objects in order to do deep object comparison? Is there anything like Java equals(Object)?

答:
As the top answer mentions, customizing equality is problematic for mutable objects. The good news is (and I'm surprised no one has mentioned this yet) there's a very popular library called immutable-js that provides a rich set of immutable types which provide the deep value equality semantics you're looking for.

Here's your example using immutable-js:

const { Map, Set } = require('immutable');
var set = new Set();
set = set.add(Map({a:1}));
set = set.add(Map({a:1}));
console.log([...set.values()]); // [Map {"a" => 1}]
```

Body:
New ES 6 (Harmony) introduces new Set object. Identity algorithm used by Set is similar to === operator and so not much suitable for comparing objects:

var set = new Set();
set.add({a:1});
set.add({a:1});
console.log([...set.values()]); // Array [ Object, Object ]

How to customize equality for Set objects in order to do deep object comparison? Is there anything like Java equals(Object)?


问:
How to access a specific field from Cloud FireStore Firebase in Swift
Here is my data structure:

I have an ios app that is attempting to access data from Cloud Firestore. I have been successful in retrieving full documents and querying for documents. However I need to access specific fields from specific documents. How would I make a call that retrieves me just the value of one field from Firestore in swift? Any Help would be appreciated.

答:
There is actually a way, use this sample code provided by Firebase itself</p>

```<code>let docRef = db.collection("cities").document("SF")

docRef.getDocument { (document, error) in
    if let document = document, document.exists {
        let property = document.get('fieldname')
        print("Document data: \(dataDescription)")
    } else {
        print("Document does not exist")
    }
}
</code>```

Body:
There is actually a way, use this sample code provided by Firebase itself

let docRef = db.collection("cities").document("SF")

docRef.getDocument { (document, error) in
    if let document = document, document.exists {
        let property = document.get('fieldname')
        print("Document data: \(dataDescription)")
    } else {
        print("Document does not exist")
    }
}


问:
alert box in asp.net web application
how can i use an alert box in asp.net web application without using javascript with Yes/NO option, much like messagebox in desktop (windows) application.

Thanks

答: Simple, you can't.  That message box object is only for WinForms Development.</p>

Title: alert box in asp.net web application


问:
Generating all possible permutations of a list recursively
I'm trying to recursively generate all items in a list recursively. I've seen a few solutions to similar questions to this, but I haven't been able to get my code to work. Could someone point out how I can fix my code?

This is open to all S/O'ers, not just Java people.

(Also I should note that it crashes with a SO exception).

Sample input:

```<code>[1, 2, 3]
</code>```

Output:

```<code>[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
</code>```

//allPossibleItems is an AL of all items

//this is called with generatePerm(null, new ArrayList<Item>);

private void generatePerm(Item i, ArrayList<Item> a) {
    if (i != null) { a.add(i); }
    if (a.size() == DESIRED_SIZE) {
        permutations.add(a);
        return;
    }
    for (int j = 0; j < allPossibleItems.size(); j++) {
        if (allPossibleItems.get(j) != i)
            generatePerm(allPossibleItems.get(j), a);
    }
}
```

答:
You can keep the start fixed and then keep swapping. It is one of the easiest approaches to understand.

public class PermutationListRecursion {
    private Set<List<Integer>> permList = new HashSet<>();

    public static void main(String[] args) {
        PermutationListRecursion pt = new PermutationListRecursion();
        Integer[] nums = {1, 2, 3};
        pt.permute(nums);
        System.out.println(pt.permList);
    }

    public void permute(Integer[] nums) {
        permutation(0, nums.length - 1, nums);
    }

    public void permutation(int start, int end, Integer[] nums) {
        if (start == end) {
            permList.add(new ArrayList<Integer>(Arrays.asList(nums)));
        }
        for (int i = start; i <= end; i++) {
            permList.add(swap(nums, start, i));
            permutation(start + 1, end, nums);
            permList.add(swap(nums, start, i));
        }
    }

    private List<Integer> swap(Integer[] arr, int a, int b) {
        if (a == b) {
            return new ArrayList<>(Arrays.asList(arr));
        }
        Integer temp = arr[b];
        arr[b] = arr[a];
        arr[a] = temp;
        return new ArrayList<>(Arrays.asList(arr));
    }
}
```

Body:
I'm trying to recursively generate all items in a list recursively. I've seen a few solutions to similar questions to this, but I haven't been able to get my code to work. Could someone point out how I can fix my code?

This is open to all S/O'ers, not just Java people.

(Also I should note that it crashes with a SO exception).

Sample input:

[1, 2, 3]

Output:

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]

//allPossibleItems is an AL of all items

//this is called with generatePerm(null, new ArrayList<Item>);

private void generatePerm(Item i, ArrayList<Item> a) {
    if (i != null) { a.add(i); }
    if (a.size() == DESIRED_SIZE) {
        permutations.add(a);
        return;
    }
    for (int j = 0; j < allPossibleItems.size(); j++) {
        if (allPossibleItems.get(j) != i)
            generatePerm(allPossibleItems.get(j), a);
    }
}


问:
Binary operator '*' cannot be applied to operands of type 'Float' and 'Double'
I am implementing AudioVisualizer and I am trying to calculate time of audio but I am getting below error

Binary operator '*' cannot be applied to operands of type 'Float' and 'Double'

Here is my code:

```<code> var lowPassReslts: Double = 0.0
 var lowPassReslts1: Double = 0.0

 let ALPHA: Float = 1.05

 let averagePowerForChannel = pow(10, (0.05 * audioPlayer.averagePower(forChannel: 0)))
 lowPassReslts = ALPHA * averagePowerForChannel + (1.0 - ALPHA) * lowPassReslts //HERE i am getting error which i mention above

 let averagePowerForChannel1 = pow(10, (0.05 * audioPlayer.averagePower(forChannel: 1)))
 lowPassReslts1 = ALPHA * averagePowerForChannel1 + (1.0 - ALPHA) * lowPassReslts1 //HERE i am getting error
</code>```

This above code have converted from Objective-C. This code works perfect in Objective-C but it is not working in Swift. Can anyone please tell me how to solve this error?

答:
```<code>    var lowPassReslts: Double = 0.0
    var lowPassReslts1: Double = 0.0

    let ALPHA: Float = 1.05

    let averagePowerForChannel = pow(10, (0.05 * audioPlayer.averagePower(forChannel: 0)))
    lowPassReslts = Double(ALPHA * Float(averagePowerForChannel) + (1.0 - ALPHA) * Float(lowPassReslts))

    let averagePowerForChannel1 = pow(10, (0.05 * audioPlayer.averagePower(forChannel: 1)))
    lowPassReslts1 = Double(ALPHA * Float(averagePowerForChannel1) + (1.0 - ALPHA) * Float(lowPassReslts1))
</code>```

Body:
I am implementing AudioVisualizer and I am trying to calculate time of audio but I am getting below error

Binary operator '*' cannot be applied to operands of type 'Float' and 'Double'

Here is my code:

 var lowPassReslts: Double = 0.0
 var lowPassReslts1: Double = 0.0

 let ALPHA: Float = 1.05

 let averagePowerForChannel = pow(10, (0.05 * audioPlayer.averagePower(forChannel: 0)))
 lowPassReslts = ALPHA * averagePowerForChannel + (1.0 - ALPHA) * lowPassReslts //HERE i am getting error which i mention above

 let averagePowerForChannel1 = pow(10, (0.05 * audioPlayer.averagePower(forChannel: 1)))
 lowPassReslts1 = ALPHA * averagePowerForChannel1 + (1.0 - ALPHA) * lowPassReslts1 //HERE i am getting error

This above code have converted from Objective-C. This code works perfect in Objective-C but it is not working in Swift. Can anyone please tell me how to solve this error?


问:
AttributeError at /files/
when I am going to implement tag field I am getting following error

AttributeError: Got AttributeError when attempting to get a value for field tags on serializer CategorySerializers.
  The serializer field might be named incorrectly and not match any attribute or key on the Category instance.
  Original exception text was: 'Category' object has no attribute 'tags'.

models.py

```<code>class Category(models.Model):
    name = models.CharField(max_length=100)

class Tag(models.Model):
    tag_name = models.CharField(max_length=30)

class FileUp(models.Model):
    name = models.ForeignKey(Category, on_delete=models.CASCADE)
    file = models.FileField(upload_to='path')
    tags = models.ManyToManyField(Tag)

    def __str__(self):
        return self.name.name
</code>```

serializers.py

```<code> class TagSerializers(serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = ['tag_name']

class FileSerializers(serializers.ModelSerializer):
    class Meta:
        model = FileUp
        fields = ['file']

class CategorySerializers(serializers.HyperlinkedModelSerializer):
    files = FileSerializers(source='file_set', many=True, read_only=True)
    tags = TagSerializers(many=True)

    class Meta:
        model = Category
        fields = ['id', 'name', 'files', 'tags']
        read_only_fields = ['tags']

def create(self, validated_data):
    files_data = self.context.get('view').request.FILES
    name = Category.objects.create(name=validated_data.get('name'))

    for file_data in files_data.values():
        FileUp.objects.create(name=name, file=file_data)

    return name
</code>```

here is what I tried, I have put Tag in Category model but when I am going to add files I cannot add tags to it or select tags in the admin panel. But, If I add Tag to FileUp I am getting error above shown. How can I apply to Tag to FileUp? any help please?

答:
Use SerializerMethodField parameter,

```<code>class CategorySerializers(serializers.HyperlinkedModelSerializer):
    files = FileSerializers(source='file_set', many=True, read_only=True)
    <b>tags = serializers.SerializerMethodField()

    def get_tags(self, category):
        return TagSerializers(Tag.objects.filter(fileup__name__categories=category), many=True).data</b>

    class Meta:
        model = Category
        fields = ['id', 'name', 'files', 'tags']
        read_only_fields = ['tags']</code>```

Title: AttributeError at /files/

Body:
when I am going to implement tag field I am getting following error

AttributeError: Got AttributeError when attempting to get a value for field tags on serializer CategorySerializers.
  The serializer field might be named incorrectly and not match any attribute or key on the Category instance.
  Original exception text was: 'Category' object has no attribute 'tags'.

models.py

class Category(models.Model):
    name = models.CharField(max_length=100)

class Tag(models.Model):
    tag_name = models.CharField(max_length=30)

class FileUp(models.Model):
    name = models.ForeignKey(Category, on_delete=models.CASCADE)
    file = models.FileField(upload_to='path')
    tags = models.ManyToManyField(Tag)

    def __str__(self):
        return self.name.name

serializers.py

 class TagSerializers(serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = ['tag_name']

class FileSerializers(serializers.ModelSerializer):
    class Meta:
        model = FileUp
        fields = ['file']

class CategorySerializers(serializers.HyperlinkedModelSerializer):
    files = FileSerializers(source='file_set', many=True, read_only=True)
    tags = TagSerializers(many=True)

    class Meta:
        model = Category
        fields = ['id', 'name', 'files', 'tags']
        read_only_fields = ['tags']

def create(self, validated_data):
    files_data = self.context.get('view').request.FILES
    name = Category.objects.create(name=validated_data.get('name'))

    for file_data in files_data.values():
        FileUp.objects.create(name=name, file=file_data)

    return name

here is what I tried, I have put Tag in Category model but when I am going to add files I cannot add tags to it or select tags in the admin panel. But, If I add Tag to FileUp I am getting error above shown. How can I apply to Tag to FileUp? any help please?

Body:
Use SerializerMethodField parameter,

class CategorySerializers(serializers.HyperlinkedModelSerializer):
    files = FileSerializers(source='file_set', many=True, read_only=True)
    tags = serializers.SerializerMethodField()

    def get_tags(self, category):
        return TagSerializers(Tag.objects.filter(fileup__name__categories=category), many=True).data

    class Meta:
        model = Category
        fields = ['id', 'name', 'files', 'tags']
        read_only_fields = ['tags']


问:
macOS deprecated APIs
The company I work for has developed a program and the last time the code was touched was 2 years ago. Now the program needs to become notarized so I was asked to take care of the program.

I ported the code to latest Xcode (10.2.1) and latest macOS. But Xcode warns me about the deprecation of a few API calls:

/Users/rowelz/Documents/Develop/Code/ThinPrint/in GIT/myProject/osx-client/src/com.myProject.bootstrap/EZPBootstrapper.m:116:51: 'SMJobCopyDictionary' is deprecated: first deprecated in macOS 10.10

NSDictionary *plist = (__bridge NSDictionary *) SMJobCopyDictionary(
      kSMDomainSystemLaunchd, (__bridge CFStringRef) (label));

/Users/rowelz/Documents/Develop/Code/ThinPrint/in GIT/myProject/osx-client/src/com.myProject.bootstrap/EZPBootstrapper.m:193:21: 'SMJobRemove' is deprecated: first deprecated in macOS 10.10

result = (BOOL) SMJobRemove(kSMDomainSystemLaunchd,
        (__bridge CFStringRef) label, self->_authRef, FALSE, &cfError);

/Users/rowelz/Documents/Develop/Code/ThinPrint/in GIT/myProject/osx-client/src/com.myProject.bootstrap/EZPAppDelegate.m:193:15: 'SMJobSubmit' is deprecated: first deprecated in macOS 10.10

submitted = SMJobSubmit(kSMDomainUserLaunchd, (__bridge CFDictionaryRef)(plist), NULL, &cfError);

/Users/rowelz/Documents/Develop/Code/ThinPrint/in GIT/ezeep/osx-client/src/com.myProject.bootstrap/EZPAppDelegate.m:214:13: 'SMJobRemove' is deprecated: first deprecated in macOS 10.10

removed = SMJobRemove(kSMDomainUserLaunchd, (__bridge CFStringRef)kEzeepServiceNameUpdaterBstrap, NULL, false, NULL);

My Supervisor in this project gave the following boundary conditions:

Program should work during the next one year only. After that It will be replaced by another program of our house.

During this year it should work without limitations, crashes and so on.

I would prefer not to make any changes to the code, since the warnings regarding SMJobCopyDictionary, SMJobRemove and SMJobSubmit means that there is a big change to do - the whole program has to be written anew. And this would be a big effort for a one year life-span.

My Question:
I would like to write a little tool that checks for the availability of these API calls. I will then execute this tool on every beta of macOS until the final release of macOS 10.15. Of course if  that tool shows a problem I will then rewrite the "now defective" program.

Would that be sufficient to detect a problem with the existence of the API? And what function can I use to detect the availability without actually calling them trying to install a launchd binary? I guess the above APIs are CoreFoundation ?

Thanks in advance for you help.

I found this here at stack overflow and it seems to work:

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

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
@autoreleasepool {

    BOOL notFound = NO;

    void *lib = dlopen("/System/Library/Frameworks/ServiceManagement.framework/Versions/A/ServiceManagement", RTLD_LAZY);

    if(lib == NULL)
    {
        printf("Library not found. (/System/Library/Frameworks/ServiceManagement.framework/Versions/A/ServiceManagement).\n");
        exit(1);
    }

    void *function1 = dlsym(lib, "SMJobCopyDictionary");

    if(function1 == NULL)
    {
        printf("Function not found: SMJobCopyDictionary\n");
        notFound = YES;
    }

    // .... and so on

    dlclose(lib);

    if(notFound)
    {
        exit(1);
    }

    printf("Ok, all functions found.\n");
}
return 0;
</code>```

}

will that be sufficient to show a call to a deprecated and removed API?

答:
This is speculation, but I feel confident in it: Apple will not remove these APIs from 10.15. Deprecating APIs is done regularly, but actually removing them breaks existing applications and is done very rarely.

It is possible (though unlikely I think) that they will remove the headers from the 10.15 SDK, in which case you will need to keep building against the 10.14 SDK (using Xcode 10).

And if the 10.15 SDK still contains the headers, the situation is the same as it is now and you won't have any problems.

Title: macOS deprecated APIs

Body:
The company I work for has developed a program and the last time the code was touched was 2 years ago. Now the program needs to become notarized so I was asked to take care of the program.

I ported the code to latest Xcode (10.2.1) and latest macOS. But Xcode warns me about the deprecation of a few API calls:

/Users/rowelz/Documents/Develop/Code/ThinPrint/in GIT/myProject/osx-client/src/com.myProject.bootstrap/EZPBootstrapper.m:116:51: 'SMJobCopyDictionary' is deprecated: first deprecated in macOS 10.10

NSDictionary *plist = (__bridge NSDictionary *) SMJobCopyDictionary(
      kSMDomainSystemLaunchd, (__bridge CFStringRef) (label));

/Users/rowelz/Documents/Develop/Code/ThinPrint/in GIT/myProject/osx-client/src/com.myProject.bootstrap/EZPBootstrapper.m:193:21: 'SMJobRemove' is deprecated: first deprecated in macOS 10.10

result = (BOOL) SMJobRemove(kSMDomainSystemLaunchd,
        (__bridge CFStringRef) label, self->_authRef, FALSE, &cfError);

/Users/rowelz/Documents/Develop/Code/ThinPrint/in GIT/myProject/osx-client/src/com.myProject.bootstrap/EZPAppDelegate.m:193:15: 'SMJobSubmit' is deprecated: first deprecated in macOS 10.10

submitted = SMJobSubmit(kSMDomainUserLaunchd, (__bridge CFDictionaryRef)(plist), NULL, &cfError);

/Users/rowelz/Documents/Develop/Code/ThinPrint/in GIT/ezeep/osx-client/src/com.myProject.bootstrap/EZPAppDelegate.m:214:13: 'SMJobRemove' is deprecated: first deprecated in macOS 10.10

removed = SMJobRemove(kSMDomainUserLaunchd, (__bridge CFStringRef)kEzeepServiceNameUpdaterBstrap, NULL, false, NULL);

My Supervisor in this project gave the following boundary conditions:

Program should work during the next one year only. After that It will be replaced by another program of our house.

During this year it should work without limitations, crashes and so on.

I would prefer not to make any changes to the code, since the warnings regarding SMJobCopyDictionary, SMJobRemove and SMJobSubmit means that there is a big change to do - the whole program has to be written anew. And this would be a big effort for a one year life-span.

My Question:
I would like to write a little tool that checks for the availability of these API calls. I will then execute this tool on every beta of macOS until the final release of macOS 10.15. Of course if  that tool shows a problem I will then rewrite the "now defective" program.

Would that be sufficient to detect a problem with the existence of the API? And what function can I use to detect the availability without actually calling them trying to install a launchd binary? I guess the above APIs are CoreFoundation ?

Thanks in advance for you help.

I found this here at stack overflow and it seems to work:

#include <dlfcn.h>

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
@autoreleasepool {

    BOOL notFound = NO;

    void *lib = dlopen("/System/Library/Frameworks/ServiceManagement.framework/Versions/A/ServiceManagement", RTLD_LAZY);

    if(lib == NULL)
    {
        printf("Library not found. (/System/Library/Frameworks/ServiceManagement.framework/Versions/A/ServiceManagement).\n");
        exit(1);
    }

    void *function1 = dlsym(lib, "SMJobCopyDictionary");

    if(function1 == NULL)
    {
        printf("Function not found: SMJobCopyDictionary\n");
        notFound = YES;
    }

    // .... and so on

    dlclose(lib);

    if(notFound)
    {
        exit(1);
    }

    printf("Ok, all functions found.\n");
}
return 0;

}

will that be sufficient to show a call to a deprecated and removed API?


问:
Casting char array to uint8_t
I have a function definition like this in an Arduino library:

```<code>bool RHReliableDatagram::sendtoWait(uint8_t * buf, uint8_t len, uint8_t address)
</code>```

When I use:

```<code>uint8_t timePacket[] = "time\n";
sendtoWait(timePacket, sizeof(timePacket), SERVER_ADDRESS)
</code>```

I get a perfectly fine string with "time" at the other end (SERVER_ADDRESS) in pyserial's readline() function which is decoded perfectly using utf-8 encoding.

Now I need to send some bytes using the same sendtoWait() function. I first define a char array of 60 bytes

```<code>char packetBuff[60] = "";
</code>```

Then I get every byte and cast it as a char

```<code>char value = (char)flash.readByte(dumpCounter++);
</code>```

Then put each value in the char array like this:

```<code>packetBuff[charNo] = value;
</code>```

After I find a new line character I try to send the char array again using the sendtoWait() function:

```<code>if (value == '\n') {
    Serial.println(packetBuff);
    uint8_t buff[charNo];
    for (int i = 0; i < charNo; i++) {
        buff[i] = packetBuff[i];
    }
    sendtoWait(buff, charNo, SERVER_ADDRESS))
charNo++;
</code>```

But although Serial.println(packetBuff) shows the proper characters e.g. something like "1559105487\n" (unix timestamp), buff array is just not working correctly and shows random characters something like a semi-colon, random single digit numbers etc.

How do I properly cast the char array and send it properly using the sendtoWait() function like "time\n" was sent?

EDIT:
Full code:

```<code>  int charNo = 0;
  char packetBuff[60] = "";
  if (dumpCounter != 0) {
    dumpCounter--;
  }
  while(dumpCounter < currentFlashLoc) {
    char value = (char)flash.readByte(dumpCounter++);
    packetBuff[charNo] = value;
    if (value == '\n') {
      Serial.println(packetBuff);
      uint8_t buff[charNo];
      for (int i = 0; i < charNo; i++) {
        buff[i] = packetBuff[i];
      }
      if (manager.sendtoWait(buff, charNo, SERVER_ADDRESS)) {
        // packet sent successfully
      }
      charNo = -1;
    }
    charNo++;
  }
</code>```

答:
Casting the char array like this:

```<code>sendtoWait((uint8_t*)packetBuff, sizeof(packetBuff), SERVER_ADDRESS)
</code>```

works correctly. buff is not required.

Title: Casting char array to uint8_t

Body:
I have a function definition like this in an Arduino library:

bool RHReliableDatagram::sendtoWait(uint8_t * buf, uint8_t len, uint8_t address)

When I use:

uint8_t timePacket[] = "time\n";
sendtoWait(timePacket, sizeof(timePacket), SERVER_ADDRESS)

I get a perfectly fine string with "time" at the other end (SERVER_ADDRESS) in pyserial's readline() function which is decoded perfectly using utf-8 encoding.

Now I need to send some bytes using the same sendtoWait() function. I first define a char array of 60 bytes

char packetBuff[60] = "";

Then I get every byte and cast it as a char

char value = (char)flash.readByte(dumpCounter++);

Then put each value in the char array like this:

packetBuff[charNo] = value;

After I find a new line character I try to send the char array again using the sendtoWait() function:

if (value == '\n') {
    Serial.println(packetBuff);
    uint8_t buff[charNo];
    for (int i = 0; i < charNo; i++) {
        buff[i] = packetBuff[i];
    }
    sendtoWait(buff, charNo, SERVER_ADDRESS))
charNo++;

But although Serial.println(packetBuff) shows the proper characters e.g. something like "1559105487\n" (unix timestamp), buff array is just not working correctly and shows random characters something like a semi-colon, random single digit numbers etc.

How do I properly cast the char array and send it properly using the sendtoWait() function like "time\n" was sent?

EDIT:
Full code:

  int charNo = 0;
  char packetBuff[60] = "";
  if (dumpCounter != 0) {
    dumpCounter--;
  }
  while(dumpCounter < currentFlashLoc) {
    char value = (char)flash.readByte(dumpCounter++);
    packetBuff[charNo] = value;
    if (value == '\n') {
      Serial.println(packetBuff);
      uint8_t buff[charNo];
      for (int i = 0; i < charNo; i++) {
        buff[i] = packetBuff[i];
      }
      if (manager.sendtoWait(buff, charNo, SERVER_ADDRESS)) {
        // packet sent successfully
      }
      charNo = -1;
    }
    charNo++;
  }

Body:
Casting the char array like this:

sendtoWait((uint8_t*)packetBuff, sizeof(packetBuff), SERVER_ADDRESS)

works correctly. buff is not required.


问:
Connecting to an API using Power Bi
I am trying to connect to an API using Power BI. I am doing this by clicking on the Get Data then choosing Web, typing the URL address of the site. It comes with the list of API links created when I drill to any of them I cannot see anything. Is this the correct way of doing it? Many Thanks for your help</p>

答:
For querying REST APIs, that's the correct way of doing it yes. But in your case, it might be an issue with the API itself or that you need more details in the query? It's hard to troubleshoot without vieweing the API documentations.

If you then press on Advanced, you can then include further details for your request if needed.

I will include some screenshots below of how to choose the Web connector.

Title: Connecting to an API using Power Bi


问:
How to update Progressbar in android while downloading and inserting JSON data in SQLite?
The background or thread operation of downloading and inserting JSON data into database works fine but as I also want to update my ProgressBar when the data insertion operation keeps updating. My problem is, it starts with Zero percent and dismisses when the whole operation is completed without any update in percentage value.

Sync Fragment:

```<code>String value; //defined globally

private class JsonParse extends AsyncTask<String, String, String> {

    Context mcontext;
    private ProgressDialog progressDialog;

    public JsonParse(Context context) {
        this.mcontext = context;
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        progressDialog = new ProgressDialog(mcontext);

        progressDialog.setTitle("Downloading"); // Setting Title
        progressDialog.setMessage("Please wait"); // Setting Message
        progressDialog.setIndeterminate(false);
        progressDialog.setMax(100);
        progressDialog.setCancelable(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, mcontext.getString(R.string.cancel_btn), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

        String choice = params[0];
        final String url = BASE_URL + "" + VERSION + "" + METHOD + "";

        StringRequest request = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        Log.i("response", url + "response:" + response);

                        try {
                            JSONObject object = new JSONObject(response);
                            JSONArray jsonArray = object.getJSONArray(METHOD + "");

                            long counter = 0;
                            int size = jsonArray.length();

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

                                final JSONObject jsonObject = jsonArray.getJSONObject(i);

                                counter++;
                                int percent = (int) ((counter * 100) / size);
                                value = percent + "";

                                onProgressUpdate(value);

                                Log.i("view_", "size: " + size + " " + "counter: " + counter + " " + "percent: " + percent + "%");

                                switch (choice) {

                                    case "deaths":

                                        String id_d = jsonObject.getString("id");
                                        String family_id = jsonObject.getString("family_id");
                                        String death_one_year = jsonObject.getString("death_one_year");
                                        String no_of_deaths = jsonObject.getString("no_of_death");
                                        String cause = jsonObject.getString("cause");
                                        String cause_other = jsonObject.getString("cause_other");
                                        String ward_id_d = jsonObject.getString("ward_id");
                                        String has_error_d = jsonObject.getString("has_error");
                                        String updated_by_d = jsonObject.getString("updated_by");
                                        String updated_at_d = jsonObject.getString("updated_at");
                                        String created_at = jsonObject.getString("created_at");
                                        String uuid_d = jsonObject.getString("uuid");

                                        dbHelper.SyncDeath(Integer.parseInt(id_d), family_id, death_one_year, no_of_deaths, cause, cause_other,
                                                ward_id_d, has_error_d, updated_by_d, updated_at_d, created_at, uuid_d);

                                        death_txt.setTextColor(getResources().getColor(R.color.colorPrimary));
                                        death_txt.setText(R.string.synced);

                                        break;
                                }
                            }
                            return;

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        progressDialog.dismiss();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                Toast.makeText(getContext(), "Server Error, Please Try Again!!", Toast.LENGTH_SHORT).show();
            }
        });

        requestQueue.add(request);

        publishProgress(value);

        Log.i("view_percent_value", value); // Getting null value

        /*for (int i = 0; i <= 100; i++){
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            publishProgress(String.valueOf(i));
        }*/

        return null;
    }

    @Override
    protected void onProgressUpdate(String... values) {

        progressDialog.setProgress(Integer.parseInt(values[0]));
        value = values[0]; // Tried to update this "value" i.e. set globally but can't update

        Log.i("view_values", values[0] + "");
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {

    }
}
</code>```

The above-commented code:

```<code> /*for (int i = 0; i <= 100; i++){
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            publishProgress(String.valueOf(i));
        }*/
</code>```

helps me update ProgressBar but it is not updating in Realtime. In my case, the parameter passed in publishprogress(); i.e. "value" which is defined globally is not getting updated value from the loop. As I guess, it may be the case using for-loop inside try-catch but I can't find the way how to pass that value to publishprogress(); method.

The Log view:

```<code>Log.i("view_", "size: " + size + " " + "counter: " + counter + " " + "percent: " + percent + "%");
</code>```

is updating the percentage value in real-time. Like this:

Please help me to figure out this problem. I'm stuck with this problem from couple of weeks. Thank you in advance!!

答:
Trying setting value of your progress in onProgressUpdate() function.

Follow this link for reference:
android how to work with asynctasks progressdialog

Body:
The background or thread operation of downloading and inserting JSON data into database works fine but as I also want to update my ProgressBar when the data insertion operation keeps updating. My problem is, it starts with Zero percent and dismisses when the whole operation is completed without any update in percentage value.

Sync Fragment:

String value; //defined globally

private class JsonParse extends AsyncTask<String, String, String> {

    Context mcontext;
    private ProgressDialog progressDialog;

    public JsonParse(Context context) {
        this.mcontext = context;
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        progressDialog = new ProgressDialog(mcontext);

        progressDialog.setTitle("Downloading"); // Setting Title
        progressDialog.setMessage("Please wait"); // Setting Message
        progressDialog.setIndeterminate(false);
        progressDialog.setMax(100);
        progressDialog.setCancelable(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, mcontext.getString(R.string.cancel_btn), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

        String choice = params[0];
        final String url = BASE_URL + "" + VERSION + "" + METHOD + "";

        StringRequest request = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        Log.i("response", url + "response:" + response);

                        try {
                            JSONObject object = new JSONObject(response);
                            JSONArray jsonArray = object.getJSONArray(METHOD + "");

                            long counter = 0;
                            int size = jsonArray.length();

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

                                final JSONObject jsonObject = jsonArray.getJSONObject(i);

                                counter++;
                                int percent = (int) ((counter * 100) / size);
                                value = percent + "";

                                onProgressUpdate(value);

                                Log.i("view_", "size: " + size + " " + "counter: " + counter + " " + "percent: " + percent + "%");

                                switch (choice) {

                                    case "deaths":

                                        String id_d = jsonObject.getString("id");
                                        String family_id = jsonObject.getString("family_id");
                                        String death_one_year = jsonObject.getString("death_one_year");
                                        String no_of_deaths = jsonObject.getString("no_of_death");
                                        String cause = jsonObject.getString("cause");
                                        String cause_other = jsonObject.getString("cause_other");
                                        String ward_id_d = jsonObject.getString("ward_id");
                                        String has_error_d = jsonObject.getString("has_error");
                                        String updated_by_d = jsonObject.getString("updated_by");
                                        String updated_at_d = jsonObject.getString("updated_at");
                                        String created_at = jsonObject.getString("created_at");
                                        String uuid_d = jsonObject.getString("uuid");

                                        dbHelper.SyncDeath(Integer.parseInt(id_d), family_id, death_one_year, no_of_deaths, cause, cause_other,
                                                ward_id_d, has_error_d, updated_by_d, updated_at_d, created_at, uuid_d);

                                        death_txt.setTextColor(getResources().getColor(R.color.colorPrimary));
                                        death_txt.setText(R.string.synced);

                                        break;
                                }
                            }
                            return;

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        progressDialog.dismiss();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                Toast.makeText(getContext(), "Server Error, Please Try Again!!", Toast.LENGTH_SHORT).show();
            }
        });

        requestQueue.add(request);

        publishProgress(value);

        Log.i("view_percent_value", value); // Getting null value

        /*for (int i = 0; i <= 100; i++){
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            publishProgress(String.valueOf(i));
        }*/

        return null;
    }

    @Override
    protected void onProgressUpdate(String... values) {

        progressDialog.setProgress(Integer.parseInt(values[0]));
        value = values[0]; // Tried to update this "value" i.e. set globally but can't update

        Log.i("view_values", values[0] + "");
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {

    }
}

The above-commented code:

 /*for (int i = 0; i <= 100; i++){
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            publishProgress(String.valueOf(i));
        }*/

helps me update ProgressBar but it is not updating in Realtime. In my case, the parameter passed in publishprogress(); i.e. "value" which is defined globally is not getting updated value from the loop. As I guess, it may be the case using for-loop inside try-catch but I can't find the way how to pass that value to publishprogress(); method.

The Log view:

Log.i("view_", "size: " + size + " " + "counter: " + counter + " " + "percent: " + percent + "%");

is updating the percentage value in real-time. Like this:

Please help me to figure out this problem. I'm stuck with this problem from couple of weeks. Thank you in advance!!


问:
How to select the maximum quarter from the result set?
I have a list of period for each quarter for many years, I need to select the maximum period from the result.

Say for example, the actual data would be like this;

```<code>**period description**
2014 Q2
2014 Q1
2018 Q3
2016 Q1
2017 Q4
2018 Q4
</code>```

Here I need to fetch only the latest quarter in the given data..i.e. we need to get 2018 Q4.

I tried :

```<code>select substring  (perioddescription, 1, 4)
</code>```

but I've a string in between them so any help would be much appreciated.thanks in advacne

答:
You can try below -</p>

```<code>select top 1 * from tablename
order by cast(left(perioddescription,4) as int) desc,cast(right(perioddescription,1) as int) desc
</code>```

Body:
I have a list of period for each quarter for many years, I need to select the maximum period from the result.

Say for example, the actual data would be like this;

**period description**
2014 Q2
2014 Q1
2018 Q3
2016 Q1
2017 Q4
2018 Q4

Here I need to fetch only the latest quarter in the given data..i.e. we need to get 2018 Q4.

I tried :

select substring  (perioddescription, 1, 4)

but I've a string in between them so any help would be much appreciated.thanks in advacne

Body:
You can try below -

select top 1 * from tablename
order by cast(left(perioddescription,4) as int) desc,cast(right(perioddescription,1) as int) desc


问:
How to remove top status bar black background
I'd like to create a TRUE fullscreen activity, but there is always a black status bar on screen top. Android 9.0.

I've tried almost all I can find with Google and existing Apps with similar jobs. Manifest, code, style, AS sample fullscreen activity, all were tried.

styles.xml:

```

<p>Manifest:</p>

<pre class="lang-xml prettyprint-override"><code><activity android:name=".ScreenActivity" android:theme="@style/AppThemeA" />
</code>```

Layout:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/rootLayout"
        android:fitsSystemWindows="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>
```

<p>Kotlin (commented lines are tried and failed):</p>

```class ScreenActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        //setTheme(R.style.AppThemeDetector)
        super.onCreate(savedInstanceState)

        //window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
        //window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
        //window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_FULLSCREEN

        /*
        window.decorView.systemUiVisibility = (
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        or View.SYSTEM_UI_FLAG_FULLSCREEN
                )*/

        setContentView(R.layout.activity_screen_detector)
        ...
    }
}
```

The expected result:

What I actually got:

[[[[ Solution ]]]]

Found what caused this. You should set the App to FullScreen App in Settings -> Display.

https://www.gottabemobile.com/how-to-enable-full-screen-apps-on-galaxy-s10

So fixed. Thanks for all your help.

答:
In addition to your code you just need adding this code before your setContentView in your activity </p>

```<code>this.requestWindowFeature(Window.FEATURE_NO_TITLE);
</code>```

Body:
I'd like to create a TRUE fullscreen activity, but there is always a black status bar on screen top. Android 9.0.

I've tried almost all I can find with Google and existing Apps with similar jobs. Manifest, code, style, AS sample fullscreen activity, all were tried.

styles.xml:

Manifest:

<activity android:name=".ScreenActivity" android:theme="@style/AppThemeA" />

Layout:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/rootLayout"
        android:fitsSystemWindows="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Kotlin (commented lines are tried and failed):

class ScreenActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        //setTheme(R.style.AppThemeDetector)
        super.onCreate(savedInstanceState)

        //window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
        //window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)
        //window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_FULLSCREEN

        /*
        window.decorView.systemUiVisibility = (
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        or View.SYSTEM_UI_FLAG_FULLSCREEN
                )*/

        setContentView(R.layout.activity_screen_detector)
        ...
    }
}

The expected result:

What I actually got:

[[[[ Solution ]]]]

Found what caused this. You should set the App to FullScreen App in Settings -> Display.

https://www.gottabemobile.com/how-to-enable-full-screen-apps-on-galaxy-s10

So fixed. Thanks for all your help.

Body:
In addition to your code you just need adding this code before your setContentView in your activity

this.requestWindowFeature(Window.FEATURE_NO_TITLE);


问:
ASP.NET MVC3 IAuthorisationfilter Ninject Dependency
Currently I am trying to set up dependency injection and override the authorisation attribute. I have tried to follow a few examples although I always seem to get errors.

Global.asax

```<code>public class MvcApplication : Ninject.Web.Mvc.NinjectHttpApplication
{
    private class MyModule : NinjectModule
    {
        public override void Load()
        {
            this.BindFilter<SageAdminAuthorizationFilter>(FilterScope.Controller, 0);
            Bind<IAuthentication>().To<CustomAuthenticationService>();
        }
    }

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default",
            "{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }

    protected override void OnApplicationStarted()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

    protected override IKernel CreateKernel()
    {
        var modules = new INinjectModule[] {
        new MyModule()
    };
        var kernel = new StandardKernel(modules);

        return kernel;
    }
}
</code>```

Authentication Filter

```<code>public class CustomAuthenticationService : IAuthentication
{
    public void SignIn(string claimedIdentifier, bool createPersistentCookie)
    {
        //Write Sign in code here
        FormsAuthentication.SetAuthCookie(claimedIdentifier, createPersistentCookie);
    }

    public void SignOut()
    {
        FormsAuthentication.SignOut();
    }

    public bool Authorize(HttpContextBase httpContext)
    {
        //Check here if the user can administer the  admin
        return false;
    }
}

//The Authorization attribute on a controller
public class CustomAdminAuthorizationFilter : IAuthorizationFilter
{
    private readonly IAuthentication _authentication;

    public SageAdminAuthorizationFilter(IAuthentication authentication)
    {
        _authentication = authentication;
    }

    public void OnAuthorization(AuthorizationContext filterContext)
    {
        _authentication.Authorize(filterContext.HttpContext);
    }
}
</code>```

I always receive

Sequence contains no elements.

Any help would appreciated.

Update:
I am still receiving the same error.

The call stack is as follows

Locating source for 'c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectHttpApplication.cs'. Checksum: MD5 {3d e3 7f 86 44 70 db 0 3c 6f e0 97 fb 1e 12 13}
The file 'c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectHttpApplication.cs' does not exist.
Looking in script documents for 'c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectHttpApplication.cs'...
Looking in the projects for 'c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectHttpApplication.cs'.
The file was not found in a project.
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\crt\src\'...
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\atlmfc\src\mfc\'...
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\atlmfc\src\atl\'...
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\atlmfc\include\'...
The debug source files settings for the active solution indicate that the debugger will not ask the user to find the file: c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectHttpApplication.cs.
The debugger could not locate the source file 'c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectHttpApplication.cs'.

I have installed Ninject and Ninject.MVC3 from Nuget. It looks although it is trying to find the files to debug. Would anyone be able to give me any information to why this is happening.

I also receive this error

[InvalidOperationException: Sequence contains no elements]
   System.Linq.Enumerable.Single(IEnumerable1 source) +320
   Ninject.Web.Mvc.Bootstrapper.Initialize(Func1 createKernelCallback) in c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\Bootstrapper.cs:67
   Ninject.Web.Mvc.NinjectHttpApplication.Application_Start() in c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectHttpApplication.cs:65

答:
Action filters should be registered using the following syntax:

```<code>public override void Load()
{
    BindFilter<CustomAdminAuthorizationFilter>(FilterScope.Controller, 0);
    Bind<IAuthentication>().To<CustomAuthenticationService>();
}
</code>```

You can also apply the filter conditionally.

Remark: can't see any relation with the NinjectDependencyResolver class you are showing in your question. That's already built into ninject.mvc3 and you shouldn't be writing it manually.

Body:
Currently I am trying to set up dependency injection and override the authorisation attribute. I have tried to follow a few examples although I always seem to get errors.

Global.asax

public class MvcApplication : Ninject.Web.Mvc.NinjectHttpApplication
{
    private class MyModule : NinjectModule
    {
        public override void Load()
        {
            this.BindFilter<SageAdminAuthorizationFilter>(FilterScope.Controller, 0);
            Bind<IAuthentication>().To<CustomAuthenticationService>();
        }
    }

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default",
            "{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }

    protected override void OnApplicationStarted()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

    protected override IKernel CreateKernel()
    {
        var modules = new INinjectModule[] {
        new MyModule()
    };
        var kernel = new StandardKernel(modules);

        return kernel;
    }
}

Authentication Filter

public class CustomAuthenticationService : IAuthentication
{
    public void SignIn(string claimedIdentifier, bool createPersistentCookie)
    {
        //Write Sign in code here
        FormsAuthentication.SetAuthCookie(claimedIdentifier, createPersistentCookie);
    }

    public void SignOut()
    {
        FormsAuthentication.SignOut();
    }

    public bool Authorize(HttpContextBase httpContext)
    {
        //Check here if the user can administer the  admin
        return false;
    }
}

//The Authorization attribute on a controller
public class CustomAdminAuthorizationFilter : IAuthorizationFilter
{
    private readonly IAuthentication _authentication;

    public SageAdminAuthorizationFilter(IAuthentication authentication)
    {
        _authentication = authentication;
    }

    public void OnAuthorization(AuthorizationContext filterContext)
    {
        _authentication.Authorize(filterContext.HttpContext);
    }
}

I always receive

Sequence contains no elements.

Any help would appreciated.

Update:
I am still receiving the same error.

The call stack is as follows

Locating source for 'c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectHttpApplication.cs'. Checksum: MD5 {3d e3 7f 86 44 70 db 0 3c 6f e0 97 fb 1e 12 13}
The file 'c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectHttpApplication.cs' does not exist.
Looking in script documents for 'c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectHttpApplication.cs'...
Looking in the projects for 'c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectHttpApplication.cs'.
The file was not found in a project.
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\crt\src\'...
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\atlmfc\src\mfc\'...
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\atlmfc\src\atl\'...
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\atlmfc\include\'...
The debug source files settings for the active solution indicate that the debugger will not ask the user to find the file: c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectHttpApplication.cs.
The debugger could not locate the source file 'c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectHttpApplication.cs'.

I have installed Ninject and Ninject.MVC3 from Nuget. It looks although it is trying to find the files to debug. Would anyone be able to give me any information to why this is happening.

I also receive this error

[InvalidOperationException: Sequence contains no elements]
   System.Linq.Enumerable.Single(IEnumerable1 source) +320
   Ninject.Web.Mvc.Bootstrapper.Initialize(Func1 createKernelCallback) in c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\Bootstrapper.cs:67
   Ninject.Web.Mvc.NinjectHttpApplication.Application_Start() in c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectHttpApplication.cs:65

Body:
Action filters should be registered using the following syntax:

public override void Load()
{
    BindFilter<CustomAdminAuthorizationFilter>(FilterScope.Controller, 0);
    Bind<IAuthentication>().To<CustomAuthenticationService>();
}

You can also apply the filter conditionally.

Remark: can't see any relation with the NinjectDependencyResolver class you are showing in your question. That's already built into ninject.mvc3 and you shouldn't be writing it manually.


问:
Is it possible to make SQL query into .exe file?
I would like to know if it's possible to make SQL queries into .exe files so that when you run the .exe file, it runs the query.

If not, is there a way to automatically run a query when certain table's value is updated?

答:
Is there a way to automatically run a query when a certain table's value is updated? Yes in SQL Server You can use the triggers. Inside the trigger you can write a query which you need to execute when a table get updated

Try SQL jobs to run a particular query at a particular time.


问:
Ajax form submit twice or once but missing last value no submit button
It may seems to be asked a few time, yet I can't find a solution.

```<code><form id="foo">
    <div class="g1">
     <input type="radio" data-next="2" name="op1[]" value="1">
     <input type="radio" data-next="2" name="op1[]" value="2">
     <input type="radio" data-next="2" name="op1[]" value="3">
    </div>
    <div class="g2">
     <input type="radio" data-next="3" name="op2[]" value="1">
     <input type="radio" data-next="3" name="op2[]" value="5">
     <input type="radio" data-next="3" name="op2[]" value="3">
    </div>
    <div class="g3">
     <input type="radio" data-send="1" name="op3[]" value="6">
     <input type="radio" data-send="1" name="op3[]" value="5">
     <input type="radio" data-send="1" name="op3[]" value="3">
    </div>
 </form>
</code>```

That is a basic of my actual code but same concept, g2 and g3 are hidden, when a user select one option from g1 it shows the next block, user selects from g2 and it shows g3...

When user select one option from the group g3 it submit the form via ajax.

The problem is that it submits the form twice the first time only send options 1 and 2, and the second time it send's the whole form.

if I use event.preventDefault(); it only submit the form once which is what I want the problem is that is not sending the value of op3

```<code>$('[data-send]').on('click', function(e) {
 e.preventDefault();
var formdata = $('form#foo').serialize();
// next is a regular ajax, post, dataType: 'json'... etc
})
</code>```

So, by using event.preventDefault(); it doesn't send my last radio value and if I don't, it submits the form twice, if I use return false;, result is the same as preventDefault();,

答:
$('[data-send]') will not be rcognisable, so add class to g3 radio buttons and use that class for click

Code:-

```<code>$('.submit-form').on('click', function(e) {
   e.preventDefault();
   var formdata = $('form#foo').serialize();
})
</code>```

Working snippet:-

$('.submit-form').on('click', function(e) {
   e.preventDefault();
   var formdata = $('form#foo').serialize();
   console.log(formdata);
   //or you can use below too
   //var formdata1 = $('form#foo').serializeArray();
   //console.log(formdata);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="foo">
    <div class="g1">
     <input type="radio" data-next="2" name="op1[]" value="1">
     <input type="radio" data-next="2" name="op1[]" value="2">
     <input type="radio" data-next="2" name="op1[]" value="3">
    </div>
    <div class="g2">
     <input type="radio" data-next="3" name="op2[]" value="1">
     <input type="radio" data-next="3" name="op2[]" value="5">
     <input type="radio" data-next="3" name="op2[]" value="3">
    </div>
    <div class="g3">
     <input type="radio" class="submit-form" data-send="1" name="op3[]" value="6">
     <input type="radio" class="submit-form" data-send="1" name="op3[]" value="5">
     <input type="radio" class="submit-form" data-send="1" name="op3[]" value="3">
    </div>
 </form></code>```

Note:- instead of op1[], op2[],op3[] you can use op[1],op[2],op[3] or best is op[] only. It will make indexes itself. (0=> first div radio buttons,1=>2nd div radio buttons etc)

Body:
It may seems to be asked a few time, yet I can't find a solution.

<form id="foo">

     <input type="radio" data-next="2" name="op1[]" value="1">
     <input type="radio" data-next="2" name="op1[]" value="2">
     <input type="radio" data-next="2" name="op1[]" value="3">

     <input type="radio" data-next="3" name="op2[]" value="1">
     <input type="radio" data-next="3" name="op2[]" value="5">
     <input type="radio" data-next="3" name="op2[]" value="3">

     <input type="radio" data-send="1" name="op3[]" value="6">
     <input type="radio" data-send="1" name="op3[]" value="5">
     <input type="radio" data-send="1" name="op3[]" value="3">

 </form>

That is a basic of my actual code but same concept, g2 and g3 are hidden, when a user select one option from g1 it shows the next block, user selects from g2 and it shows g3...

When user select one option from the group g3 it submit the form via ajax.

The problem is that it submits the form twice the first time only send options 1 and 2, and the second time it send's the whole form.

if I use event.preventDefault(); it only submit the form once which is what I want the problem is that is not sending the value of op3

$('[data-send]').on('click', function(e) {
 e.preventDefault();
var formdata = $('form#foo').serialize();
// next is a regular ajax, post, dataType: 'json'... etc
})

So, by using event.preventDefault(); it doesn't send my last radio value and if I don't, it submits the form twice, if I use return false;, result is the same as preventDefault();,

Body:
$('[data-send]') will not be rcognisable, so add class to g3 radio buttons and use that class for click

Code:-

$('.submit-form').on('click', function(e) {
   e.preventDefault();
   var formdata = $('form#foo').serialize();
})

Working snippet:-

$('.submit-form').on('click', function(e) {
   e.preventDefault();
   var formdata = $('form#foo').serialize();
   console.log(formdata);
   //or you can use below too
   //var formdata1 = $('form#foo').serializeArray();
   //console.log(formdata);
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="foo">
    <div class="g1">
     <input type="radio" data-next="2" name="op1[]" value="1">
     <input type="radio" data-next="2" name="op1[]" value="2">
     <input type="radio" data-next="2" name="op1[]" value="3">
    </div>
    <div class="g2">
     <input type="radio" data-next="3" name="op2[]" value="1">
     <input type="radio" data-next="3" name="op2[]" value="5">
     <input type="radio" data-next="3" name="op2[]" value="3">
    </div>
    <div class="g3">
     <input type="radio" class="submit-form" data-send="1" name="op3[]" value="6">
     <input type="radio" class="submit-form" data-send="1" name="op3[]" value="5">
     <input type="radio" class="submit-form" data-send="1" name="op3[]" value="3">
    </div>
 </form>

Note:- instead of op1[], op2[],op3[] you can use op[1],op[2],op[3] or best is op[] only. It will make indexes itself. (0=> first div radio buttons,1=>2nd div radio buttons etc)


问:
Calling or communicating with docker container on one machine from other application not in docker container and in another machine
I have my docker container in one machine running say Machine A. I have another machine B which consists of a flask server. I would like to call/communicate with the docker container in machine A from my flask server in Machine B. I am not running my flask server inside any docker container. I am actually very new to docker so I am not sure whether we are able to achieve it or not.</p>

答:
You can just directly visit the http service in container from other machine.

E.g.

Container on machineA was this:

```<code>docker run -idt -p 9000:80 nginx
</code>```

Then, you machineB's flask application, you can just use:

```<code>requests.get("http://your_machine_a_ip:9000")
</code>```

to get what you need.

Just remember, for container, you need to expose http port to host, so other machine could visit it.

Body:
You can just directly visit the http service in container from other machine.

E.g.

Container on machineA was this:

docker run -idt -p 9000:80 nginx

Then, you machineB's flask application, you can just use:

requests.get("http://your_machine_a_ip:9000")

to get what you need.

Just remember, for container, you need to expose http port to host, so other machine could visit it.


问:
How to print exponential number "m³" using ESC/POS printer with C#?
I'm trying to print a ticket, and need to print out m³ as unit of measurement using a serial printer. And the following is what I have tried so far:

```<code>if (!printer.IsOpen)
    printer.Open();

printer.WriteLine(string.Format("{0} m{1}", "2.34", Convert.ToChar(0xB3)));

printer.Close();
</code>```

When I tried to debug and view the value using the text visualizer the text is correct which is "2.34 m³". But when it comes to printing, the text changed to "2.34 m?", where the expected output should be "2.34 m³".

I've been trying to figure this out for days. Please help. Thanks.

答:
It seems as if your printer does not support the '³' character natively.
Therefore you need the printer manufacturer's technical manual. There, you must identify a control character sequence for superscript mode and put it in from of a (normal) character '3'. After it, you must switch off superscript mode again.This control codes are printer specific, and you need, therefore you must have this information from the printer manufacturer.

Assuming "Superscript on" is ESC 0x4e and "Superscript off" is ESC 0x4f, then your cde would look like this:

```<code>printer.WriteLine(string.Format("{0} m{1}3{2}", "2.34", "\x1b\x4e", "\x1b\x4f" );
</code>```

Body:
I'm trying to print a ticket, and need to print out m³ as unit of measurement using a serial printer. And the following is what I have tried so far:

if (!printer.IsOpen)
    printer.Open();

printer.WriteLine(string.Format("{0} m{1}", "2.34", Convert.ToChar(0xB3)));

printer.Close();

When I tried to debug and view the value using the text visualizer the text is correct which is "2.34 m³". But when it comes to printing, the text changed to "2.34 m?", where the expected output should be "2.34 m³".

I've been trying to figure this out for days. Please help. Thanks.

Body:
It seems as if your printer does not support the '³' character natively.
Therefore you need the printer manufacturer's technical manual. There, you must identify a control character sequence for superscript mode and put it in from of a (normal) character '3'. After it, you must switch off superscript mode again.This control codes are printer specific, and you need, therefore you must have this information from the printer manufacturer.

Assuming "Superscript on" is ESC 0x4e and "Superscript off" is ESC 0x4f, then your cde would look like this:

printer.WriteLine(string.Format("{0} m{1}3{2}", "2.34", "\x1b\x4e", "\x1b\x4f" );


问:
Android: Google Drive onActivityResult() getting resultCode 0 (RESULT_CANCELED)
I've been scouring the Google documentation and sample code and Stack Overflow for a solution to this, and while I've seen a number of people running into the same symptoms I haven't found anything that helps in my particular case.

Basically I'm trying to do an auth workflow for the Google Drive REST API, and while I get as far as the Google account selection page, when it returns to my calling activity, I'm always seeing a result of RESULT_CANCELED (i.e., 0) instead of RESULT_OK (i.e., -1), no matter what account is selected.

I've checked to make sure that the credentials are set up correctly on the Google developer console — and they were working previously with authentication via the now-defunct CloudRail library. (As far as I can tell, now with Google Sign-In you don't provide any client id, etc.: that's all handled on Google's end when it matches your package name.)

Here is my call for authentication:

```<code>    GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestScopes(new Scope(DriveScopes.DRIVE))
            .build();
    mSignInClient = GoogleSignIn.getClient(activity, signInOptions);
</code>```

And here is the activity's onActivityResult():

```<code>@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    switch (requestCode) {
        case REQUEST_GOOGLE_SIGN_IN:
            if (resultCode == Activity.RESULT_OK && resultData != null) {
                /*** NEVER GET HERE ***/
                handleSignInResult(this, resultData);
            }
            else {
                /*** ALWAYS GET HERE ***/
                Log.e(TAG, String.format("Unable to complete Google sign-in (resultCode: %d)", resultCode));
            }
        }
        break;
    }
    super.onActivityResult(requestCode, resultCode, resultData);
}
</code>```

I'm assuming that this is a case of me doing something obviously dumb and wrong — and was hoping that just typing out the question would help me figure out what it is, but that hasn't happened yet.

答:
First of all most probably it all happens because you add the credential.json from the Google Drive API console.
I suggest you to create a project in Firebase console and add its google.json for validation of authentication.

and in your onActivityResult you can check the error code using following code:

```<code>  @Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if (callbackManager != null) {
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }
    super.onActivityResult(requestCode, resultCode, data);
    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        try {
            // Google Sign In was successful, authenticate with Firebase
            GoogleSignInAccount account = task.getResult(ApiException.class);
            handleSignInResult(account);
        } catch (ApiException e) {
            // Google Sign In failed, update UI appropriately
             System.out.println("errorCode = " + e.getStatusCode());// Print this error code on your console
        }
    }

}
</code>```

if the error code is 12500 then your problem with keys validation and hence you need to create a firebase project and add your machine SHA1 code and then use its google.json file in your app root folder.

Body:
I've been scouring the Google documentation and sample code and Stack Overflow for a solution to this, and while I've seen a number of people running into the same symptoms I haven't found anything that helps in my particular case.

Basically I'm trying to do an auth workflow for the Google Drive REST API, and while I get as far as the Google account selection page, when it returns to my calling activity, I'm always seeing a result of RESULT_CANCELED (i.e., 0) instead of RESULT_OK (i.e., -1), no matter what account is selected.

I've checked to make sure that the credentials are set up correctly on the Google developer console — and they were working previously with authentication via the now-defunct CloudRail library. (As far as I can tell, now with Google Sign-In you don't provide any client id, etc.: that's all handled on Google's end when it matches your package name.)

Here is my call for authentication:

    GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestScopes(new Scope(DriveScopes.DRIVE))
            .build();
    mSignInClient = GoogleSignIn.getClient(activity, signInOptions);

And here is the activity's onActivityResult():

@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    switch (requestCode) {
        case REQUEST_GOOGLE_SIGN_IN:
            if (resultCode == Activity.RESULT_OK && resultData != null) {
                /*** NEVER GET HERE ***/
                handleSignInResult(this, resultData);
            }
            else {
                /*** ALWAYS GET HERE ***/
                Log.e(TAG, String.format("Unable to complete Google sign-in (resultCode: %d)", resultCode));
            }
        }
        break;
    }
    super.onActivityResult(requestCode, resultCode, resultData);
}

I'm assuming that this is a case of me doing something obviously dumb and wrong — and was hoping that just typing out the question would help me figure out what it is, but that hasn't happened yet.

Body:
First of all most probably it all happens because you add the credential.json from the Google Drive API console.
I suggest you to create a project in Firebase console and add its google.json for validation of authentication.

and in your onActivityResult you can check the error code using following code:

  @Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if (callbackManager != null) {
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }
    super.onActivityResult(requestCode, resultCode, data);
    // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        try {
            // Google Sign In was successful, authenticate with Firebase
            GoogleSignInAccount account = task.getResult(ApiException.class);
            handleSignInResult(account);
        } catch (ApiException e) {
            // Google Sign In failed, update UI appropriately
             System.out.println("errorCode = " + e.getStatusCode());// Print this error code on your console
        }
    }

}

if the error code is 12500 then your problem with keys validation and hence you need to create a firebase project and add your machine SHA1 code and then use its google.json file in your app root folder.


问:
How to toogle different modal with different content and change the button as well?
I wanna toggle different models and calculate the results in form individually.

I try to avoid paste too many modal codes and found the sample HERE, however, it use the same ID, so I get stuck!

If you click on

Button A it shows Modal A with Calculate A.

Button B it shows modal B with Calculate B.

Button N it shows modal N with Calculate N.

Is there a way to change the button to another one? or any help?

Much appreciate!

$('#exampleModal').on('show.bs.modal', function(event) {
  var button = $(event.relatedTarget) // Button that triggered the modal
  var recipient = button.data('whatever') // Extract info from data-* attributes
  // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
  // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
  var modal = $(this)
  modal.find('.modal-title').text('Form click on ' + recipient)
  modal.find('.modal-body input').val(recipient)

  $("#buttonA").click(function () {
  var a = $("#amout").val();
  alert("Results: " + a);
 });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="button A">Run button A</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="button B">Run button B</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="button N">Run button ...N</button>

<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Form 1-N</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <form>
          Num: <input id="amout" type="number">
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" id="buttonA">calculate</button>
      </div>
    </div>
  </div>
</div></code>```

答:
The Fastest way is set id for each button you want change and Change innerText of that in your Function.

Html Tag

```<code><button id="AcceptBTN" type="button" class="btn btn-primary">Send message</button>
         ^
         |
        Here
</code>```

jQuery

```<code>$('#exampleModal').on('show.bs.modal', function(event) {
  var button = $(event.relatedTarget) // Button that triggered the modal
  var recipient = button.data('whatever')
 // Extract info from data-* attributes
  // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
  // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.

$('#AcceptBTN')[0].innerText = recipient;   <-----------------Here

  var modal = $(this)
  modal.find('.modal-title').text('New message to ' + recipient)
  modal.find('.modal-body input').val(recipient)
})
</code>```

GoodLuck

Body:
I wanna toggle different models and calculate the results in form individually.

I try to avoid paste too many modal codes and found the sample HERE, however, it use the same ID, so I get stuck!

If you click on

Button A it shows Modal A with Calculate A.

Button B it shows modal B with Calculate B.

Button N it shows modal N with Calculate N.

Is there a way to change the button to another one? or any help?

Much appreciate!

$('#exampleModal').on('show.bs.modal', function(event) {
  var button = $(event.relatedTarget) // Button that triggered the modal
  var recipient = button.data('whatever') // Extract info from data-* attributes
  // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
  // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
  var modal = $(this)
  modal.find('.modal-title').text('Form click on ' + recipient)
  modal.find('.modal-body input').val(recipient)

  $("#buttonA").click(function () {
  var a = $("#amout").val();
  alert("Results: " + a);
 });
})

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="button A">Run button A</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="button B">Run button B</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="button N">Run button ...N</button>

Form 1-N

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        <form>
          Num: <input id="amout" type="number">
        </form>

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" id="buttonA">calculate</button>

Body:
The Fastest way is set id for each button you want change and Change innerText of that in your Function.

Html Tag

<button id="AcceptBTN" type="button" class="btn btn-primary">Send message</button>
         ^
         |
        Here

jQuery

$('#exampleModal').on('show.bs.modal', function(event) {
  var button = $(event.relatedTarget) // Button that triggered the modal
  var recipient = button.data('whatever')
 // Extract info from data-* attributes
  // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
  // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.

$('#AcceptBTN')[0].innerText = recipient;   <-----------------Here

  var modal = $(this)
  modal.find('.modal-title').text('New message to ' + recipient)
  modal.find('.modal-body input').val(recipient)
})

GoodLuck