问:
What Nuget Package do I need for WinApplication.GetSecurityStrategy().RegisterXPOAdapterProviders();?
I created a new Winforms Xaf Xpo standard security project with 21.2/5
Then I changed the framework of each project to be 4.7.2
Then I ran the upgrade wizard.
Then I tried to convert the project files to use Nuget with Package References.
However I get the following build errors

```<code>Severity    Code    Description Project File    Line    Suppression State
Error   CS1061  'SecurityStrategy' does not contain a definition for 'RegisterXPOAdapterProviders' and no accessible extension method 'RegisterXPOAdapterProviders' accepting a first argument of type 'SecurityStrategy' could be found (are you missing a using directive or an assembly reference?)  DXXpo.Win   C:\Users\kirst\source\repos\DXXpo\DXXpo.Win\Program.cs  33  Active
Error   CS0246  The type or namespace name 'SecuredObjectSpaceProvider' could not be found (are you missing a using directive or an assembly reference?)    DXXpo.Win   C:\Users\kirst\source\repos\DXXpo\DXXpo.Win\WinApplication.cs   20  Active
</code>```

I tried drilling into another new project and I can see that RegisterXPOAdapterProviders has namespace DevExpress.ExpressApp.Security
I already have that installed as a NugetPackage.
I tried installing DevExpress.ExpressApp.Security.Xpo but I get a message
Severity    Code    Description Project File    Line    Suppression State

```<code>Error   NU1101  Unable to find package DevExpress.ExpressApp.Persistent.Base. No packages exist with this id in source(s): DevExpressMy, nuget.org, SBDCommonFeed@Local DXXpo.Win   C:\Users\kirst\source\repos\DXXpo\DXXpo.Win\DXXpo.Win.csproj    1
</code>```

There are no packages starting with DevExpress.ExpressApp.Persistent in the feed.

The docs are here

This question is possibly related.

答: I managed to resolve this issue by including the package DevExpress.ExpressApp.Security.Xpo</p>

Body:
I created a new Winforms Xaf Xpo standard security project with 21.2/5
Then I changed the framework of each project to be 4.7.2
Then I ran the upgrade wizard.
Then I tried to convert the project files to use Nuget with Package References.
However I get the following build errors

Severity    Code    Description Project File    Line    Suppression State
Error   CS1061  'SecurityStrategy' does not contain a definition for 'RegisterXPOAdapterProviders' and no accessible extension method 'RegisterXPOAdapterProviders' accepting a first argument of type 'SecurityStrategy' could be found (are you missing a using directive or an assembly reference?)  DXXpo.Win   C:\Users\kirst\source\repos\DXXpo\DXXpo.Win\Program.cs  33  Active
Error   CS0246  The type or namespace name 'SecuredObjectSpaceProvider' could not be found (are you missing a using directive or an assembly reference?)    DXXpo.Win   C:\Users\kirst\source\repos\DXXpo\DXXpo.Win\WinApplication.cs   20  Active

I tried drilling into another new project and I can see that RegisterXPOAdapterProviders has namespace DevExpress.ExpressApp.Security
I already have that installed as a NugetPackage.
I tried installing DevExpress.ExpressApp.Security.Xpo but I get a message
Severity    Code    Description Project File    Line    Suppression State

Error   NU1101  Unable to find package DevExpress.ExpressApp.Persistent.Base. No packages exist with this id in source(s): DevExpressMy, nuget.org, SBDCommonFeed@Local DXXpo.Win   C:\Users\kirst\source\repos\DXXpo\DXXpo.Win\DXXpo.Win.csproj    1

There are no packages starting with DevExpress.ExpressApp.Persistent in the feed.

The docs are here

This question is possibly related.


来源: stackexchange

问:
I am trying to keep the objects of csv files into a linked list to search for the tshirts But I am getting cannot infer type arguments for linked list
My program is to implement a standalone product search program in Java that lists matching
products for a user who is looking for T-shirts. I am given 3 CSV files. I am trying to keep
the objects of CSV files into a LinkedList to search for the T-shirts but I am getting cannot
infer type arguments for LinkedList.
Here is my code in which I am trying to store objects of CSV file into LinkedList.

package com.example.Mavenassignmentone;

import java.io.*;
import java.util.*;

public class FindTshirt {
    List<ShirtModel> shirtlist = new LinkedList<ShirtModel>();
    LinkedList<String> list;
    showTshirt sh = new showTshirt();

    public void find(String filename, String COLOUR, String GENDER_RECOMMENDATION, String SIZE)
            throws FileNotFoundException {
        Scanner sc = new Scanner(new File(filename));
        while (sc.hasNext()) {
            String sentence = sc.nextLine().toString();
            if (!sentence.isEmpty()) {
                StringTokenizer token = new StringTokenizer(sentence, "|");
                list = new LinkedList<>(sentence.length());
                while (token.hasMoreTokens()) {
                    list.add(token.nextToken());
                }
                if (list.get(1).equals(COLOUR) && list.get(2).equals(GENDER_RECOMMENDATION)
                        && list.get(3).equals(SIZE)) {
                    ShirtModel model = new ShirtModel(list.get(0), list.get(1), list.get(2),
                            list.get(3), list.get(4), Integer.parseInt(list.get(5)),
                            Float.parseFloat(list.get(6)), list.get(7));
                    shirtlist.add(model);
                }
            }
        }
    }

    public void updateView(int choiceCode) {
        if (choiceCode == 1) {
            Collections.sort(shirtlist, new Comparator<ShirtModel>() {
                @Override
                public int compare(ShirtModel o1, ShirtModel o2) {
                    return o1.getPrice() - o2.getPrice();
                }
            });
        }
        else if (choiceCode == 2) {
            Collections.sort(shirtlist, new Comparator<ShirtModel>() {
                public int compare(ShirtModel o1, ShirtModel o2) {
                    return (int) (o1.getRating() - o2.getRating());
                }
            });
        }

        else {
            System.out.println("Wrong Choice.");
            return;
        }
        sh.viewtshirt(shirtlist);
    }
}
```
<p>This line of code is giving error:</p>
<pre class="lang-java prettyprint-override"><code>list=new LinkedList<>(sentence.length());
</code>```

Error is

cannot infer type arguments

答:
Your problem is in this line of your code.

list = new LinkedList<>(sentence.length());
```
<p>There is no constructor of class LinkedList that takes an <code>int</code> parameter.<br />
The line should be:</p>
<pre class="lang-java prettyprint-override"><code>list = new LinkedList<>();
</code>```

For the sake of completeness, here is your code with the correction. There is one change and it is marked with the comment CHANGE HERE.

package com.example.Mavenassignmentone;

import java.io.*;
import java.util.*;

public class FindTshirt {
    List<ShirtModel> shirtlist = new LinkedList<ShirtModel>();
    LinkedList<String> list;
    showTshirt sh = new showTshirt();

    public void find(String filename, String COLOUR, String GENDER_RECOMMENDATION, String SIZE)
            throws FileNotFoundException {
        Scanner sc = new Scanner(new File(filename));
        while (sc.hasNext()) {
            String sentence = sc.nextLine().toString();
            if (!sentence.isEmpty()) {
                StringTokenizer token = new StringTokenizer(sentence, "|");
                list = new LinkedList<>(); // CHANGE HERE
                while (token.hasMoreTokens()) {
                    list.add(token.nextToken());
                }
                if (list.get(1).equals(COLOUR) && list.get(2).equals(GENDER_RECOMMENDATION)
                        && list.get(3).equals(SIZE)) {
                    ShirtModel model = new ShirtModel(list.get(0), list.get(1), list.get(2),
                            list.get(3), list.get(4), Integer.parseInt(list.get(5)),
                            Float.parseFloat(list.get(6)), list.get(7));
                    shirtlist.add(model);
                }
            }
        }
    }

    public void updateView(int choiceCode) {
        if (choiceCode == 1) {
            Collections.sort(shirtlist, new Comparator<ShirtModel>() {
                @Override
                public int compare(ShirtModel o1, ShirtModel o2) {
                    return o1.getPrice() - o2.getPrice();
                }
            });
        }
        else if (choiceCode == 2) {
            Collections.sort(shirtlist, new Comparator<ShirtModel>() {
                public int compare(ShirtModel o1, ShirtModel o2) {
                    return (int) (o1.getRating() - o2.getRating());
                }
            });
        }

        else {
            System.out.println("Wrong Choice.");
            return;
        }
        sh.viewtshirt(shirtlist);
    }
}
```

Note that this solves the compiler error you are getting however I did not check whether the code executes correctly since you did not post a reproducible example because your code is missing classes ShirtModel and showTshirt.

ContentLicense: CC BY-SA 4.0

Body:
My program is to implement a standalone product search program in Java that lists matching
products for a user who is looking for T-shirts. I am given 3 CSV files. I am trying to keep
the objects of CSV files into a LinkedList to search for the T-shirts but I am getting cannot
infer type arguments for LinkedList.
Here is my code in which I am trying to store objects of CSV file into LinkedList.

package com.example.Mavenassignmentone;

import java.io.*;
import java.util.*;

public class FindTshirt {
    List<ShirtModel> shirtlist = new LinkedList<ShirtModel>();
    LinkedList<String> list;
    showTshirt sh = new showTshirt();

    public void find(String filename, String COLOUR, String GENDER_RECOMMENDATION, String SIZE)
            throws FileNotFoundException {
        Scanner sc = new Scanner(new File(filename));
        while (sc.hasNext()) {
            String sentence = sc.nextLine().toString();
            if (!sentence.isEmpty()) {
                StringTokenizer token = new StringTokenizer(sentence, "|");
                list = new LinkedList<>(sentence.length());
                while (token.hasMoreTokens()) {
                    list.add(token.nextToken());
                }
                if (list.get(1).equals(COLOUR) && list.get(2).equals(GENDER_RECOMMENDATION)
                        && list.get(3).equals(SIZE)) {
                    ShirtModel model = new ShirtModel(list.get(0), list.get(1), list.get(2),
                            list.get(3), list.get(4), Integer.parseInt(list.get(5)),
                            Float.parseFloat(list.get(6)), list.get(7));
                    shirtlist.add(model);
                }
            }
        }
    }

    public void updateView(int choiceCode) {
        if (choiceCode == 1) {
            Collections.sort(shirtlist, new Comparator<ShirtModel>() {
                @Override
                public int compare(ShirtModel o1, ShirtModel o2) {
                    return o1.getPrice() - o2.getPrice();
                }
            });
        }
        else if (choiceCode == 2) {
            Collections.sort(shirtlist, new Comparator<ShirtModel>() {
                public int compare(ShirtModel o1, ShirtModel o2) {
                    return (int) (o1.getRating() - o2.getRating());
                }
            });
        }

        else {
            System.out.println("Wrong Choice.");
            return;
        }
        sh.viewtshirt(shirtlist);
    }
}

This line of code is giving error:

list=new LinkedList<>(sentence.length());

Error is

cannot infer type arguments

Body:
Your problem is in this line of your code.

list = new LinkedList<>(sentence.length());

There is no constructor of class LinkedList that takes an int parameter.

The line should be:

list = new LinkedList<>();

For the sake of completeness, here is your code with the correction. There is one change and it is marked with the comment CHANGE HERE.

package com.example.Mavenassignmentone;

import java.io.*;
import java.util.*;

public class FindTshirt {
    List<ShirtModel> shirtlist = new LinkedList<ShirtModel>();
    LinkedList<String> list;
    showTshirt sh = new showTshirt();

    public void find(String filename, String COLOUR, String GENDER_RECOMMENDATION, String SIZE)
            throws FileNotFoundException {
        Scanner sc = new Scanner(new File(filename));
        while (sc.hasNext()) {
            String sentence = sc.nextLine().toString();
            if (!sentence.isEmpty()) {
                StringTokenizer token = new StringTokenizer(sentence, "|");
                list = new LinkedList<>(); // CHANGE HERE
                while (token.hasMoreTokens()) {
                    list.add(token.nextToken());
                }
                if (list.get(1).equals(COLOUR) && list.get(2).equals(GENDER_RECOMMENDATION)
                        && list.get(3).equals(SIZE)) {
                    ShirtModel model = new ShirtModel(list.get(0), list.get(1), list.get(2),
                            list.get(3), list.get(4), Integer.parseInt(list.get(5)),
                            Float.parseFloat(list.get(6)), list.get(7));
                    shirtlist.add(model);
                }
            }
        }
    }

    public void updateView(int choiceCode) {
        if (choiceCode == 1) {
            Collections.sort(shirtlist, new Comparator<ShirtModel>() {
                @Override
                public int compare(ShirtModel o1, ShirtModel o2) {
                    return o1.getPrice() - o2.getPrice();
                }
            });
        }
        else if (choiceCode == 2) {
            Collections.sort(shirtlist, new Comparator<ShirtModel>() {
                public int compare(ShirtModel o1, ShirtModel o2) {
                    return (int) (o1.getRating() - o2.getRating());
                }
            });
        }

        else {
            System.out.println("Wrong Choice.");
            return;
        }
        sh.viewtshirt(shirtlist);
    }
}

Note that this solves the compiler error you are getting however I did not check whether the code executes correctly since you did not post a reproducible example because your code is missing classes ShirtModel and showTshirt.


问:
FileNotFoundError when creating a binary read only file in Python
I'm creating an FTP client and am attempting to download from and upload files to an FTP server.

Downloading the files work fine as I have no issues creating a write only binary file, that does not initially exist on my local computer:

```<code>if cmnd1[0] == 'get':
    f1 = open('newDownloadText.txt', 'wb')
    ftp_cl.retrbinary("RETR " + cmnd1[1], f1.write, 1024)
    f1.close()
    ftp_cl.quit()
    break
</code>```

However, I am unable to upload files to the server as I cannot successfully create a new read only binary file:

```<code>elif cmnd1[0] == 'put':
    f2 = open('newUploadTest.txt', 'rb')
    ftp_cl.storbinary("STOR " + cmnd1[1], f2)
    f2.close()
    ftp_cl.quit()
    break
</code>```

My code fails when I attempt to create 'newUploadTest.txt'

```<code>Traceback (most recent call last):
  File "client.py", line 29, in <module>
    f2 = open('newUploadTest.txt', 'rb')
FileNotFoundError: [Errno 2] No such file or directory: 'newUploadTest.txt'
</code>```

I have seen other posts on stackoverflow with individuals creating a new read only binary files without issues using 'rb' as a parameter, not sure why mine fails every time.

答:
Code:

File must be created before reading, whereas write mode creates the file.

creating a new read only binary files

'rb' mode does not Create read only binary, but it reads a binary file which already exists.

'rb' mode opens a binary file which already exists in a read only mode. It is not creating any file.

```<code>from os.path import isfile
if my_condition:
    file = 'newUploadTest.txt'
    # Check if the file exists
    if isfile(file):
        # open binary file
        f2 = open(file, 'rb')
        # do something...
        f2.close()
    else:
        print("File doesn't exists")
</code>```

Body:
I'm creating an FTP client and am attempting to download from and upload files to an FTP server.

Downloading the files work fine as I have no issues creating a write only binary file, that does not initially exist on my local computer:

if cmnd1[0] == 'get':
    f1 = open('newDownloadText.txt', 'wb')
    ftp_cl.retrbinary("RETR " + cmnd1[1], f1.write, 1024)
    f1.close()
    ftp_cl.quit()
    break

However, I am unable to upload files to the server as I cannot successfully create a new read only binary file:

elif cmnd1[0] == 'put':
    f2 = open('newUploadTest.txt', 'rb')
    ftp_cl.storbinary("STOR " + cmnd1[1], f2)
    f2.close()
    ftp_cl.quit()
    break

My code fails when I attempt to create 'newUploadTest.txt'

Traceback (most recent call last):
  File "client.py", line 29, in <module>
    f2 = open('newUploadTest.txt', 'rb')
FileNotFoundError: [Errno 2] No such file or directory: 'newUploadTest.txt'

I have seen other posts on stackoverflow with individuals creating a new read only binary files without issues using 'rb' as a parameter, not sure why mine fails every time.

Body:
Code:

File must be created before reading, whereas write mode creates the file.

creating a new read only binary files

'rb' mode does not Create read only binary, but it reads a binary file which already exists.

'rb' mode opens a binary file which already exists in a read only mode. It is not creating any file.

from os.path import isfile
if my_condition:
    file = 'newUploadTest.txt'
    # Check if the file exists
    if isfile(file):
        # open binary file
        f2 = open(file, 'rb')
        # do something...
        f2.close()
    else:
        print("File doesn't exists")


问:
Can you move multiple images with 1 timer?
So I'm creating a simple game in Delphi where timers are used to move images(the moving algorithm completed), but it would be better to move all images with a certain name (ie. they all start with "img") at the same time using 1 timer. Is this possible? The images all move in a straight line at them same speed and are created dynamically at random intervals, cant create a timer for each one. Here is the timers code:

```<code>if ((imgLandmine.Left + imgLandmine.Width) <= 0) then
  begin
    imgLandmine.Left := iFormWidth - imgLandmine.Width;
  end
  else
  begin
    imgLandmine.Left := imgLandmine.Left - iMineSpeed;
  end;
</code>```

how to replace "imgLandmine" with an alternative that includes every landmine image currently in use.

this is the code for the dynamic image:

```<code>imgLandmine := TImage.Create(frmTank);
  imgLandmine.Parent := frmTank;

  imgLandmine.Picture.LoadFromFile('Landmine.png');
  imgLandmine.Visible := True;
  imgLandmine.BringToFront;
  imgLandmine.Stretch := True;
  imgLandmine.Width := 60;
  imgLandmine.Height := 30;
  imgLandmine.Left := iFormWidth - imgLandmine.Width;
  imgLandmine.Top := pnlGrass.Top - imgLandmine.Height;
</code>```

答:
Can you move multiple images with one timer? Of course you can. You just need a mechanism to iterate over them.

Since you are using components one bad way would be to iterate through all Controls of your frmTank and check if their name starts with img. But this is bad approach as you would be iterating through all controls that are on your form and doing lots of string comparisons.

The good way of doing this would be to create a list or an array that would contain references to your images so you can easily loop thought them.

Since you are new in coding i would recommend using List at this time so you don't have to deal with additional code that would be required to manage dynamic array allocation when adding items and resizing and reordering of items in an array when removing items.

So you should create yourself a List to store references to the mines

```<code>procedure TForm3.FormCreate(Sender: TObject);
begin
  //Create a list for storing references to your LandMine images
  LandMines := TList.Create;
end;
</code>```

Then while you are creating the LandMines you also add them to the said list

```<code>  imgLandmine := TImage.Create(frmTank);
  //Add your LandMine image to the list
  LandMines.Add(imgLandMine);
</code>```

And finally in your OnTimer event you can then loop through all the LandMines using

```<code>procedure TForm3.Timer1Timer(Sender: TObject);
var I: Integer;
    //Just local TImage variable to store reference to current landmine we will be
    //working with for easier code readability
    LandMine: TImage;
begin
  //Loop through the LandMines list
  //NOTE: Since list is 0 based you should pay attention that your loop does not
  //exceed list bounds. So always use List.Count-1 end loop position
  for I := 0 to LandMines.Count-1 do
  begin
    //Retrieve reference to specific landmine image from the list and set the
    //local LandMine variable to it for easier code readability
    LandMine := TImage(LandMines[I]);
    //Update the landmine position
    LandMine.Left := Landmine.Left - iMineSpeed;
    //Check to see if the LandMine is out of viewable area so it can be destroyed
    //
    //Checking mine position after moving it to new position saves the need to use
    //if..else if clause that you used in your code example which can improve in
    //code readability
    if (LandMine.Left + LandMine.Width) < 0 then //Destroy landmine
  end;
end;
</code>```

NOTE: instead of destroying your mines after they leave the viewable area you might want to just move them back to the right side changing their height position to some random value.This way you avoid having to constantly create and destroy image components which does have some performance overhead. And to avoid the feeling of mines coming at constant rate just add some random value to their left position when you reallocate them which would mean that they would come with some random delay into viewable are from the right side.

Having all the LandMines in a list will also allow you later to easily loop thought them and check their collision with your tank.

You might also want to create a similar list for your and possibly enemy projectiles. I'm guessing your game would also have these.

PS: If you want your projectiles to have different speeds you could store speed for each projectile using TImage.Tag property which is an inherited property from TComponent and allows you to store simple Integer value. And then when you are updating the position of your projectiles you read speed of each projectile from the mentioned Tag property instead from some global constant.

Heck you could even update the projectile speed in each cycle to simulate air drag affecting them if you want.  Would require some clever math so that speed would not slow down too fast since Tag property is just an integer and not a Floating point value (storing initial speed multiplied by lets us say 100 and then dividing this stored speed by 100 every time to get needed movement speed without the use of Floating point values).

Anyway lists are a good way of grouping objects together into some logical collections. And yes you can have one object in multiple lists if needed since lists don't really store the objects themselves but only references to the said objects.

Just don't forget to remove your objects from the list(s) before destroying them or you will end up with your list referencing the nonexistent objects and thus running into Access Violations when trying to access such objects.

You can remove objects from list by calling List.Delete

This is easy when you are looping through a list since you already have an Index of a current item. But what to do when you don't have an index of an item but only reference to the said item? Then you use List.IndexOf method to retrieve the index of specific object in the list.

Delphi also has a TObjectList which is similar to a TList except that it can also Own the objects that are added to it.

What does this means? This means that if TObjectList is set to own the object and you Delete an object from it it will automatically notify the said object that it needs to be destroyed. But the disadvantage is that only one list can own an object at the same time. So if you are adding your object to multiple list one list may Destroy a specific object without notifying other list that the said object has been destroyed so they would reference to a nonexistent object.

Body:
So I'm creating a simple game in Delphi where timers are used to move images(the moving algorithm completed), but it would be better to move all images with a certain name (ie. they all start with "img") at the same time using 1 timer. Is this possible? The images all move in a straight line at them same speed and are created dynamically at random intervals, cant create a timer for each one. Here is the timers code:

if ((imgLandmine.Left + imgLandmine.Width) <= 0) then
  begin
    imgLandmine.Left := iFormWidth - imgLandmine.Width;
  end
  else
  begin
    imgLandmine.Left := imgLandmine.Left - iMineSpeed;
  end;

how to replace "imgLandmine" with an alternative that includes every landmine image currently in use.

this is the code for the dynamic image:

imgLandmine := TImage.Create(frmTank);
  imgLandmine.Parent := frmTank;

  imgLandmine.Picture.LoadFromFile('Landmine.png');
  imgLandmine.Visible := True;
  imgLandmine.BringToFront;
  imgLandmine.Stretch := True;
  imgLandmine.Width := 60;
  imgLandmine.Height := 30;
  imgLandmine.Left := iFormWidth - imgLandmine.Width;
  imgLandmine.Top := pnlGrass.Top - imgLandmine.Height;

Body:
Can you move multiple images with one timer? Of course you can. You just need a mechanism to iterate over them.

Since you are using components one bad way would be to iterate through all Controls of your frmTank and check if their name starts with img. But this is bad approach as you would be iterating through all controls that are on your form and doing lots of string comparisons.

The good way of doing this would be to create a list or an array that would contain references to your images so you can easily loop thought them.

Since you are new in coding i would recommend using List at this time so you don't have to deal with additional code that would be required to manage dynamic array allocation when adding items and resizing and reordering of items in an array when removing items.

So you should create yourself a List to store references to the mines

procedure TForm3.FormCreate(Sender: TObject);
begin
  //Create a list for storing references to your LandMine images
  LandMines := TList.Create;
end;

Then while you are creating the LandMines you also add them to the said list

  imgLandmine := TImage.Create(frmTank);
  //Add your LandMine image to the list
  LandMines.Add(imgLandMine);

And finally in your OnTimer event you can then loop through all the LandMines using

procedure TForm3.Timer1Timer(Sender: TObject);
var I: Integer;
    //Just local TImage variable to store reference to current landmine we will be
    //working with for easier code readability
    LandMine: TImage;
begin
  //Loop through the LandMines list
  //NOTE: Since list is 0 based you should pay attention that your loop does not
  //exceed list bounds. So always use List.Count-1 end loop position
  for I := 0 to LandMines.Count-1 do
  begin
    //Retrieve reference to specific landmine image from the list and set the
    //local LandMine variable to it for easier code readability
    LandMine := TImage(LandMines[I]);
    //Update the landmine position
    LandMine.Left := Landmine.Left - iMineSpeed;
    //Check to see if the LandMine is out of viewable area so it can be destroyed
    //
    //Checking mine position after moving it to new position saves the need to use
    //if..else if clause that you used in your code example which can improve in
    //code readability
    if (LandMine.Left + LandMine.Width) < 0 then //Destroy landmine
  end;
end;

NOTE: instead of destroying your mines after they leave the viewable area you might want to just move them back to the right side changing their height position to some random value.This way you avoid having to constantly create and destroy image components which does have some performance overhead. And to avoid the feeling of mines coming at constant rate just add some random value to their left position when you reallocate them which would mean that they would come with some random delay into viewable are from the right side.

Having all the LandMines in a list will also allow you later to easily loop thought them and check their collision with your tank.

You might also want to create a similar list for your and possibly enemy projectiles. I'm guessing your game would also have these.

PS: If you want your projectiles to have different speeds you could store speed for each projectile using TImage.Tag property which is an inherited property from TComponent and allows you to store simple Integer value. And then when you are updating the position of your projectiles you read speed of each projectile from the mentioned Tag property instead from some global constant.

Heck you could even update the projectile speed in each cycle to simulate air drag affecting them if you want.  Would require some clever math so that speed would not slow down too fast since Tag property is just an integer and not a Floating point value (storing initial speed multiplied by lets us say 100 and then dividing this stored speed by 100 every time to get needed movement speed without the use of Floating point values).

Anyway lists are a good way of grouping objects together into some logical collections. And yes you can have one object in multiple lists if needed since lists don't really store the objects themselves but only references to the said objects.

Just don't forget to remove your objects from the list(s) before destroying them or you will end up with your list referencing the nonexistent objects and thus running into Access Violations when trying to access such objects.

You can remove objects from list by calling List.Delete

This is easy when you are looping through a list since you already have an Index of a current item. But what to do when you don't have an index of an item but only reference to the said item? Then you use List.IndexOf method to retrieve the index of specific object in the list.

Delphi also has a TObjectList which is similar to a TList except that it can also Own the objects that are added to it.

What does this means? This means that if TObjectList is set to own the object and you Delete an object from it it will automatically notify the said object that it needs to be destroyed. But the disadvantage is that only one list can own an object at the same time. So if you are adding your object to multiple list one list may Destroy a specific object without notifying other list that the said object has been destroyed so they would reference to a nonexistent object.


问:
python how to generate permutations of putting a singular character into a word
No idea how to word this so the title sucks my bad,

Basically, I have a 4 letter word and I want to generate every permutation of putting a dash in it.

So if my word was Cats, I want to get every permutation of it having a dash in it,

Example:

```<code>c-ats
ca-ts
-c-ats
etc,
</code>```

Is anybody able to help me?

答:
Here is a way that does not use itertools. Interpret a binary string as where to place hyphens</p>
```<code>def add_hyphens(str):
    hyphen_words=[]
    a=2**len(str)
    b=2**(len(str)+1)
    for i in range(a,b,1):
        str1=bin(i) #a string  0b1<0's and 1's>
        str2=str1[3:] #take off the 0b and the first '1'
        tmp_s=""
        for j,char1 in enumerate(str):
            if str2[j] == '1':
                tmp_s =tmp_s + '-'
            tmp_s = tmp_s + char1
        hyphen_words.append(tmp_s)
        hyphen_words.append(tmp_s+'-')
    return hyphen_words

print(add_hyphens('cats'))

['cats', 'cats-', 'cat-s', 'cat-s-', 'ca-ts', 'ca-ts-', 'ca-t-s',
'ca-t-s-', 'c-ats', 'c-ats-', 'c-at-s', 'c-at-s-', 'c-a-ts', 'c-
a-ts-', 'c-a-t-s', 'c-a-t-s-', '-cats', '-cats-', '-cat-s', '-
cat-s-', '-ca-ts', '-ca-ts-', '-ca-t-s', '-ca-t-s-', '-c-ats', '-
c-ats-', '-c-at-s', '-c-at-s-', '-c-a-ts', '-c-a-ts-', '-c-a-t-s', '-c-a-t-s-']
</code>```

Body:
No idea how to word this so the title sucks my bad,

Basically, I have a 4 letter word and I want to generate every permutation of putting a dash in it.

So if my word was Cats, I want to get every permutation of it having a dash in it,

Example:

c-ats
ca-ts
-c-ats
etc,

Is anybody able to help me?

Body:
Here is a way that does not use itertools. Interpret a binary string as where to place hyphens

def add_hyphens(str):
    hyphen_words=[]
    a=2**len(str)
    b=2**(len(str)+1)
    for i in range(a,b,1):
        str1=bin(i) #a string  0b1<0's and 1's>
        str2=str1[3:] #take off the 0b and the first '1'
        tmp_s=""
        for j,char1 in enumerate(str):
            if str2[j] == '1':
                tmp_s =tmp_s + '-'
            tmp_s = tmp_s + char1
        hyphen_words.append(tmp_s)
        hyphen_words.append(tmp_s+'-')
    return hyphen_words

print(add_hyphens('cats'))

['cats', 'cats-', 'cat-s', 'cat-s-', 'ca-ts', 'ca-ts-', 'ca-t-s',
'ca-t-s-', 'c-ats', 'c-ats-', 'c-at-s', 'c-at-s-', 'c-a-ts', 'c-
a-ts-', 'c-a-t-s', 'c-a-t-s-', '-cats', '-cats-', '-cat-s', '-
cat-s-', '-ca-ts', '-ca-ts-', '-ca-t-s', '-ca-t-s-', '-c-ats', '-
c-ats-', '-c-at-s', '-c-at-s-', '-c-a-ts', '-c-a-ts-', '-c-a-t-s', '-c-a-t-s-']


问:
OnPress for React Native Google Places Autocomplete doesn't work due to its parent components
I'm trying to use the react-native-google-places-autocomplete library within my React Native app, but I'm having an issue clicking on the suggested list.  Whenever I click on the Google suggested address, the list disappears and onPress doesn't grab the address. If I use the library in a component by itself without the parent components, it works perfectly fine, but only when I place the component within keyboardavoidingview or KeyboardAwareScrollView, it does not work:

This GooglePlacesInput.js component is just the standard library from the original repository:

       <GooglePlacesAutocomplete
            placeholder='Search'
            minLength={2} // minimum length of text to search
            autoFocus={false}
            returnKeyType={'search'} // Can be left out for default return key https://facebook.github.io/react-native/docs/textinput.html#returnkeytype
            keyboardAppearance={'light'} // Can be left out for default keyboardAppearance https://facebook.github.io/react-native/docs/textinput.html#keyboardappearance
            listViewDisplayed={false}   // true/false/undefined
            fetchDetails={true}
            renderDescription={row => row.description} // custom description render
            onPress={(data, details = null) => { // 'details' is provided when fetchDetails = true
                console.log(data, details);
            }}
            textInputProps={{
                onBlur,
            }}
            getDefaultValue={() => ''}

            query={{
                // available options: https://developers.google.com/places/web-service/autocomplete
                key: googleAPIKeyForAutocomplete,
                language: 'en', // language of the results
                region: "CA",
                // types: '(cities)' // default: 'geocode'
                types: '',
            }}

            styles={{
                listView: {
                    position: 'absolute',
                    top: 60,
                    left: 10,
                    right: 10,
                    backgroundColor: 'white',
                    borderRadius: 5,
                    flex: 1,
                    elevation: 3,
                    zIndex: 100,
                },
                textInputContainer: {
                    backgroundColor: 'transparent',
                    margin: 0,
                    width: '100%',
                    padding: 0,
                    borderTopWidth: 0,
                    borderBottomWidth: 0
                },
                textInput: {
                    backgroundColor: '#F9F5F4',
                    borderRadius: 50,
                    width: "100%",
                    height: height / 15,
                    padding: 20,
                },
                description: {
                    // color: '#ac879a',
                    fontWeight: '300'
                },
                predefinedPlacesDescription: {
                    color: '#1faadb'
                }
            }}

            currentLocation={true} // Will add a 'Current location' button at the top of the predefined places list
            currentLocationLabel="Current location"
            nearbyPlacesAPI='GooglePlacesSearch' // Which API to use: GoogleReverseGeocoding or GooglePlacesSearch
            GoogleReverseGeocodingQuery={{
                // available options for GoogleReverseGeocoding API : https://developers.google.com/maps/documentation/geocoding/intro
            }}
            GooglePlacesSearchQuery={{
                // available options for GooglePlacesSearch API : https://developers.google.com/places/web-service/search
                rankby: 'distance',
                type: 'food'
            }}

            GooglePlacesDetailsQuery={{
                // available options for GooglePlacesDetails API : https://developers.google.com/places/web-service/details
                fields: 'formatted_address',
            }}

            filterReverseGeocodingByTypes={['locality', 'administrative_area_level_3']} // filter the reverse geocoding results by types - ['locality', 'administrative_area_level_3'] if you want to display only cities
            predefinedPlaces={[]}
            enablePoweredByContainer={false}
            debounce={200} // debounce the requests in ms. Set to 0 to remove debounce. By default 0ms.
            renderLeftButton={() => { }}
            renderRightButton={() => { }}
        />
```

<p>I'm using <code>Formik</code> for its parent component <code>Form.js</code>:</p>

<pre class="lang-js prettyprint-override"><code>        <View style={styles.container} >
            <Formik
                initialValues={initialValues}
                onSubmit={(value, action) => submitHandler(value, action)}
                validationSchema={yup.object().shape({
                    address: yup
                        .string()
                        .min(5)
                        .required(),
                })}
            >
                {({
                    values,
                    handleChange,
                    errors,
                    setFieldTouched,
                    touched,
                    isValid,
                    handleSubmit,
                    resetForm,
                    isSubmitting,
                    }) => (
                        <View style={styles.form}>

                            <Animated.View
                                style={[styles.fieldset, addressStyle]}
                                onLayout={e => {
                                    if (addressHeight !== e.nativeEvent.layout.y) {
                                        setAddressHeight(e.nativeEvent.layout.y)
                                    }
                                }}
                            >
                                <Text style={{ marginLeft: 40, marginVertical: 5 }}>
                                    <Text style={{ color: '#FF5D4E' }}>* </Text>
                                    Address
                                    </Text>
                                <View style={styles.autoComplete}>
                                    <GooglePlacesInput
                                        onBlur={() => onBlurProps('address', setFieldTouched)}
                                    />
                                </View>
                            </Animated.View>
                            {touched.address && errors.address &&
                                <Animated.Text style={{ fontSize: 10, color: 'red' }}>{errors.address}</Animated.Text>
                            }
                            <TouchableOpacity
                                disabled={!isValid || loading || isSubmitting}
                                onPress={handleSubmit}
                                style={styles.button}
                            >
                                <Text style={styles.buttonText}>Submit</Text>
                            </TouchableOpacity>
                        </View>
                    )}
            </Formik>
        </View>
</code>```

handleChange still has to be passed, but I want to first figure out the onPress situation first.

And finally, the most parent component:

        <KeyboardAwareScrollView>
            <SafeAreaView style={styles.container} >
                <ScrollView
                    keyboardShouldPersistTaps={'always'}
                    contentContainerStyle={styles.container}
                    style={{ flexGrow: 1 }}
                    showsVerticalScrollIndicator={false}
                    onLayout={e => {
                        if (heightPosition !== e.nativeEvent.layout.y) {
                            setHeightPosition(e.nativeEvent.layout.y)
                        }
                    }}
                >

                    <View style={styles.form}>
                        <Form
                            submitHandler={submitHandler}
                            loading={loading}
                            heightPosition={heightPosition}
                        />
                    </View>
                </ ScrollView>
            </SafeAreaView>
        </KeyboardAwareScrollView>
```

答: If you need to include this component inside a ScrolView or FlatList, remember to apply the keyboardShouldPersistTaps='handled' attribute to all ancestors ScrollView or FlatList as per documentation. Documentation Link

Body:
I'm trying to use the react-native-google-places-autocomplete library within my React Native app, but I'm having an issue clicking on the suggested list.  Whenever I click on the Google suggested address, the list disappears and onPress doesn't grab the address. If I use the library in a component by itself without the parent components, it works perfectly fine, but only when I place the component within keyboardavoidingview or KeyboardAwareScrollView, it does not work:

This GooglePlacesInput.js component is just the standard library from the original repository:

       <GooglePlacesAutocomplete
            placeholder='Search'
            minLength={2} // minimum length of text to search
            autoFocus={false}
            returnKeyType={'search'} // Can be left out for default return key https://facebook.github.io/react-native/docs/textinput.html#returnkeytype
            keyboardAppearance={'light'} // Can be left out for default keyboardAppearance https://facebook.github.io/react-native/docs/textinput.html#keyboardappearance
            listViewDisplayed={false}   // true/false/undefined
            fetchDetails={true}
            renderDescription={row => row.description} // custom description render
            onPress={(data, details = null) => { // 'details' is provided when fetchDetails = true
                console.log(data, details);
            }}
            textInputProps={{
                onBlur,
            }}
            getDefaultValue={() => ''}

            query={{
                // available options: https://developers.google.com/places/web-service/autocomplete
                key: googleAPIKeyForAutocomplete,
                language: 'en', // language of the results
                region: "CA",
                // types: '(cities)' // default: 'geocode'
                types: '',
            }}

            styles={{
                listView: {
                    position: 'absolute',
                    top: 60,
                    left: 10,
                    right: 10,
                    backgroundColor: 'white',
                    borderRadius: 5,
                    flex: 1,
                    elevation: 3,
                    zIndex: 100,
                },
                textInputContainer: {
                    backgroundColor: 'transparent',
                    margin: 0,
                    width: '100%',
                    padding: 0,
                    borderTopWidth: 0,
                    borderBottomWidth: 0
                },
                textInput: {
                    backgroundColor: '#F9F5F4',
                    borderRadius: 50,
                    width: "100%",
                    height: height / 15,
                    padding: 20,
                },
                description: {
                    // color: '#ac879a',
                    fontWeight: '300'
                },
                predefinedPlacesDescription: {
                    color: '#1faadb'
                }
            }}

            currentLocation={true} // Will add a 'Current location' button at the top of the predefined places list
            currentLocationLabel="Current location"
            nearbyPlacesAPI='GooglePlacesSearch' // Which API to use: GoogleReverseGeocoding or GooglePlacesSearch
            GoogleReverseGeocodingQuery={{
                // available options for GoogleReverseGeocoding API : https://developers.google.com/maps/documentation/geocoding/intro
            }}
            GooglePlacesSearchQuery={{
                // available options for GooglePlacesSearch API : https://developers.google.com/places/web-service/search
                rankby: 'distance',
                type: 'food'
            }}

            GooglePlacesDetailsQuery={{
                // available options for GooglePlacesDetails API : https://developers.google.com/places/web-service/details
                fields: 'formatted_address',
            }}

            filterReverseGeocodingByTypes={['locality', 'administrative_area_level_3']} // filter the reverse geocoding results by types - ['locality', 'administrative_area_level_3'] if you want to display only cities
            predefinedPlaces={[]}
            enablePoweredByContainer={false}
            debounce={200} // debounce the requests in ms. Set to 0 to remove debounce. By default 0ms.
            renderLeftButton={() => { }}
            renderRightButton={() => { }}
        />

I'm using Formik for its parent component Form.js:

        <View style={styles.container} >
            <Formik
                initialValues={initialValues}
                onSubmit={(value, action) => submitHandler(value, action)}
                validationSchema={yup.object().shape({
                    address: yup
                        .string()
                        .min(5)
                        .required(),
                })}
            >
                {({
                    values,
                    handleChange,
                    errors,
                    setFieldTouched,
                    touched,
                    isValid,
                    handleSubmit,
                    resetForm,
                    isSubmitting,
                    }) => (
                        <View style={styles.form}>

                            <Animated.View
                                style={[styles.fieldset, addressStyle]}
                                onLayout={e => {
                                    if (addressHeight !== e.nativeEvent.layout.y) {
                                        setAddressHeight(e.nativeEvent.layout.y)
                                    }
                                }}
                            >
                                <Text style={{ marginLeft: 40, marginVertical: 5 }}>
                                    <Text style={{ color: '#FF5D4E' }}>* </Text>
                                    Address
                                    </Text>
                                <View style={styles.autoComplete}>
                                    <GooglePlacesInput
                                        onBlur={() => onBlurProps('address', setFieldTouched)}
                                    />
                                </View>
                            </Animated.View>
                            {touched.address && errors.address &&
                                <Animated.Text style={{ fontSize: 10, color: 'red' }}>{errors.address}</Animated.Text>
                            }
                            <TouchableOpacity
                                disabled={!isValid || loading || isSubmitting}
                                onPress={handleSubmit}
                                style={styles.button}
                            >
                                <Text style={styles.buttonText}>Submit</Text>
                            </TouchableOpacity>
                        </View>
                    )}
            </Formik>
        </View>

handleChange still has to be passed, but I want to first figure out the onPress situation first.

And finally, the most parent component:

        <KeyboardAwareScrollView>
            <SafeAreaView style={styles.container} >
                <ScrollView
                    keyboardShouldPersistTaps={'always'}
                    contentContainerStyle={styles.container}
                    style={{ flexGrow: 1 }}
                    showsVerticalScrollIndicator={false}
                    onLayout={e => {
                        if (heightPosition !== e.nativeEvent.layout.y) {
                            setHeightPosition(e.nativeEvent.layout.y)
                        }
                    }}
                >

                    <View style={styles.form}>
                        <Form
                            submitHandler={submitHandler}
                            loading={loading}
                            heightPosition={heightPosition}
                        />
                    </View>
                </ ScrollView>
            </SafeAreaView>
        </KeyboardAwareScrollView>


问:
Trying to add an already cloned repo as a submodule gives error 'does not have a commit checked out'
Basically I have a repo where I cloned another repo. And now I want to add that sub-repo as a submodule of the parent repo but when I do git submodule add http://sub-repo path-to-sub-repo on the parent repo it gives me this error.

```<code>fatal: '/path-to-sub-repo' does not have a commit checked out
</code>```

I suppose that this means that the sub repo has pending commits but no. Neither the parent repo nor the sub repo have pending commits or untracked files.

This is a similar question but the answer is to make a new repo which is not what I want.

答:
I was using ~ in the path to the sub-repo

```<code>git submodule add https://sub-repo ~/path-to-sub-repo
</code>```

I removed it and now it works fine.

```<code>git submodule add https://sub-repo path-to-sub-repo
</code>```

Body:
Basically I have a repo where I cloned another repo. And now I want to add that sub-repo as a submodule of the parent repo but when I do git submodule add http://sub-repo path-to-sub-repo on the parent repo it gives me this error.

fatal: '/path-to-sub-repo' does not have a commit checked out

I suppose that this means that the sub repo has pending commits but no. Neither the parent repo nor the sub repo have pending commits or untracked files.

This is a similar question but the answer is to make a new repo which is not what I want.

Body:
I was using ~ in the path to the sub-repo

git submodule add https://sub-repo ~/path-to-sub-repo

I removed it and now it works fine.

git submodule add https://sub-repo path-to-sub-repo


问:
how to use flutter ios fcm?
Firebase messaging is being used.
In the case of android, the image comes out well in the notification without any restrictions, but ios does not come out in the notification.

I created and applied UNNOTification Service Extension in xcode.

But it's meaningless.

Even if you look at the contents of https://firebase.google.com/docs/cloud-messaging/android/send-image, it says how to send it from the server, not anything else.

What should I do?

答:
on ios it really needs a little trick, previously I also wanted to display information notifications on android running but in the case of ios it just didn't want to be active, so I used this

https://pub.dev/packages/flutter_local_notifications

Title: how to use flutter ios fcm?


答:
The list is declared as a LinkedList of String via LinkedList<String>list;, but list is initialized as a new linked list with an int as the constructor argument, but the LinkedList constructor that you are using accepts a collection as its constructor, not an int.

This is the reason the compiler cannot infer the type arguments. From the Java type inference doc:

The inference algorithm determines the types of the arguments and, if available, the type that the result is being assigned, or returned. Finally, the inference algorithm tries to find the most specific type that works with all of the arguments.

The easiest fix would be to initialize the list with the empty LinkedList constructor:

list = new LinkedList<>();
```

Title: I am trying to keep the objects of csv files into a linked list to search for the tshirts But I am getting cannot infer type arguments for linked list


问:
HTML to IMAGE using Python
Here is a variable html_str, it is a string that contains html tags and contents in body.
I am created a .html file from this string using the below code in python.

```<code>html_file = open("filename.html", "w")
html_file.write(html_str)
html_file.close()
</code>```

now i got html file named file "filename.html". Now i want to convert that "filename.html" to a image, named filename.jpg with the exact contents of the html file.
please help me.

答:
```<code>from html2image import Html2Image
hti = Html2Image()
with open('./test.html') as f:
    hti.screenshot(f.read(), save_as='out.png')
</code>```

Title: HTML to IMAGE using Python

Body:
Here is a variable html_str, it is a string that contains html tags and contents in body.
I am created a .html file from this string using the below code in python.

html_file = open("filename.html", "w")
html_file.write(html_str)
html_file.close()

now i got html file named file "filename.html". Now i want to convert that "filename.html" to a image, named filename.jpg with the exact contents of the html file.
please help me.


问:
Material UI Menu using routes
I am toying with material-ui. I implemented LeftNav using routes, but I could not find a way to get IconMenu, or Menu working with links or routes. Anyone can point me to a good source / tutorial? The documentation falls short, and both components seem not to support 'menuItems' as property as LeftNav does.</p>

答:
This worked for me with the v5

for external links

```<code><MenuItem
    component={"a"}
    href={"https://example.com"}
>Go here</MenuItem>
</code>```

or internal links

```<code>import { MenuItem } from "@mui/material";
import { Link } from "react-router-dom";
<MenuItem
    component={Link}
    to={"/users/2323"}
>Go here</MenuItem>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Material UI Menu using routes

Body:
This worked for me with the v5

for external links

<MenuItem
    component={"a"}
    href={"https://example.com"}
>Go here</MenuItem>

or internal links

import { MenuItem } from "@mui/material";
import { Link } from "react-router-dom";
<MenuItem
    component={Link}
    to={"/users/2323"}
>Go here</MenuItem>


问:
Firebase auth not successful
I've been trying so make auth with firebase and all went pretty well. But at the moment i tested it, it didn't work. The problem is that the function called createUserWithEmailAndPassowrd is not successful. I think the firebase it's connected to android studio, because the analytics works perfectly. Could you give me a hand please?

Here is the code:

```<code>package com.example.authtest

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.ktx.Firebase

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val etEmail = findViewById<EditText>(R.id.EmailEt)
        val etPwd = findViewById<EditText>(R.id.PasswordEt)
        val registerBtn = findViewById<Button>(R.id.RegisterBtn)
        val logInBtn = findViewById<Button>(R.id.LogInBtn)
        val tvMessage = findViewById<TextView>(R.id.MessageTv)

        val auth = FirebaseAuth.getInstance()

        registerBtn.setOnClickListener {
            if (etEmail.text.isNotEmpty() && etPwd.text.isNotEmpty()) {
                auth.createUserWithEmailAndPassword(etEmail.toString(),etPwd.toString()).addOnCompleteListener {
                    if (it.isSuccessful) {
                        tvMessage.text = "Registered as: " + it.result?.user?.email ?: ""
                    } else {
                        tvMessage.text = "Error registering your account!"
                    }
                }
            }
        }

        logInBtn.setOnClickListener {
            if (etEmail.text.isNotEmpty() && etPwd.text.isNotEmpty()) {
                auth.signInWithEmailAndPassword(etEmail.toString(),etPwd.toString()).addOnCompleteListener {
                    if (it.isSuccessful) {
                        tvMessage.text = "Logged in as: " + it.result?.user?.email ?: ""
                    } else {
                        tvMessage.text = "Incorrect username/password!"
                    }
                }
            }
        }
    }
}
</code>```

Thanks in advance!

答:
Try below code:
createUserWithEmailAndPassword() and signInWithEmailAndPassword() methods require strings as parameter but you are providing editext in these parameters</p>
```<code>registerBtn.setOnClickListener {
        if (etEmail.text.isNotEmpty() && etPwd.text.isNotEmpty()) {
            auth.createUserWithEmailAndPassword(etEmail.text.toString().trim(),etPwd.text.toString().trim()).addOnCompleteListener {
                if (it.isSuccessful) {
                    tvMessage.text = "Registered as: " + it.result?.user?.email ?: ""
                } else {
                    tvMessage.text = "Error registering your account!"
                }
            }
        }
    }

    logInBtn.setOnClickListener {
        if (etEmail.text.isNotEmpty() && etPwd.text.isNotEmpty()) {
            auth.signInWithEmailAndPassword(etEmail.text.toString().trim(),etPwd.text.toString().trim()).addOnCompleteListener {
                if (it.isSuccessful) {
                    tvMessage.text = "Logged in as: " + it.result?.user?.email ?: ""
                } else {
                    tvMessage.text = "Incorrect username/password!"
                }
            }
        }
    }
</code>```

Title: Firebase auth not successful

Body:
I've been trying so make auth with firebase and all went pretty well. But at the moment i tested it, it didn't work. The problem is that the function called createUserWithEmailAndPassowrd is not successful. I think the firebase it's connected to android studio, because the analytics works perfectly. Could you give me a hand please?

Here is the code:

package com.example.authtest

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.ktx.Firebase

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val etEmail = findViewById<EditText>(R.id.EmailEt)
        val etPwd = findViewById<EditText>(R.id.PasswordEt)
        val registerBtn = findViewById<Button>(R.id.RegisterBtn)
        val logInBtn = findViewById<Button>(R.id.LogInBtn)
        val tvMessage = findViewById<TextView>(R.id.MessageTv)

        val auth = FirebaseAuth.getInstance()

        registerBtn.setOnClickListener {
            if (etEmail.text.isNotEmpty() && etPwd.text.isNotEmpty()) {
                auth.createUserWithEmailAndPassword(etEmail.toString(),etPwd.toString()).addOnCompleteListener {
                    if (it.isSuccessful) {
                        tvMessage.text = "Registered as: " + it.result?.user?.email ?: ""
                    } else {
                        tvMessage.text = "Error registering your account!"
                    }
                }
            }
        }

        logInBtn.setOnClickListener {
            if (etEmail.text.isNotEmpty() && etPwd.text.isNotEmpty()) {
                auth.signInWithEmailAndPassword(etEmail.toString(),etPwd.toString()).addOnCompleteListener {
                    if (it.isSuccessful) {
                        tvMessage.text = "Logged in as: " + it.result?.user?.email ?: ""
                    } else {
                        tvMessage.text = "Incorrect username/password!"
                    }
                }
            }
        }
    }
}

Thanks in advance!

Body:
Try below code:
createUserWithEmailAndPassword() and signInWithEmailAndPassword() methods require strings as parameter but you are providing editext in these parameters

registerBtn.setOnClickListener {
        if (etEmail.text.isNotEmpty() && etPwd.text.isNotEmpty()) {
            auth.createUserWithEmailAndPassword(etEmail.text.toString().trim(),etPwd.text.toString().trim()).addOnCompleteListener {
                if (it.isSuccessful) {
                    tvMessage.text = "Registered as: " + it.result?.user?.email ?: ""
                } else {
                    tvMessage.text = "Error registering your account!"
                }
            }
        }
    }

    logInBtn.setOnClickListener {
        if (etEmail.text.isNotEmpty() && etPwd.text.isNotEmpty()) {
            auth.signInWithEmailAndPassword(etEmail.text.toString().trim(),etPwd.text.toString().trim()).addOnCompleteListener {
                if (it.isSuccessful) {
                    tvMessage.text = "Logged in as: " + it.result?.user?.email ?: ""
                } else {
                    tvMessage.text = "Incorrect username/password!"
                }
            }
        }
    }


问:
How to browse Local host website from Browser
I make hosting for ASP.NET Website on my Local host IIS, and when I browse it by click on Browse from IIS manager it work fine,

But when I browse by write 192.168.1.106:80 in the google chrome browser, it not work
It go to google search.

I want to write 192.168.1.106:80 in browser directly

答:
Two possible solutions:

Prefix the protocol. paste the full url in the browser:

http://192.168.1.106:80
```

There can be multiple application on the same server(ip), so the you must tell the browser which protocol to use. In your daily use of browser you don't see http:// or https:// prefix because they are so widely used that Chrome hides it to save space in address bar. If you copy the url from Chrome, then paste in any editor, you could see the protocol prefix still there.

Check typo

I'm not very clear if you really typed 192.168.1.106:80, if you mistyped some of the characters, browser may not recognize the pattern and so go to search. for example, following two will go to search:

192.168.1.106：80

192.168.1.10a:80

Body:
Two possible solutions:

Prefix the protocol. paste the full url in the browser:

http://192.168.1.106:80

There can be multiple application on the same server(ip), so the you must tell the browser which protocol to use. In your daily use of browser you don't see http:// or https:// prefix because they are so widely used that Chrome hides it to save space in address bar. If you copy the url from Chrome, then paste in any editor, you could see the protocol prefix still there.

Check typo

I'm not very clear if you really typed 192.168.1.106:80, if you mistyped some of the characters, browser may not recognize the pattern and so go to search. for example, following two will go to search:

192.168.1.106：80

192.168.1.10a:80


问:
Detect when user taps out of or saves on DatePicker
I'm trying to fetch some data on a network call when a user selects a time from DatePicker.

I originally tested using .onChange but this fires every time that changes, and not on the final tap off.

DatePicker("Title", selection: $currentDate, displayedComponents: .hourAndMinute)
  .onChange(of: $currentDate) { value in
    print(value)
  }
```
<p>I also tried using the <code>didset{}</code> but that also fired on every change too.</p>
<pre class="lang-swift prettyprint-override"><code>@Published var currentDate: Date = Date() {
  didSet { print(currentDate) }
}
</code>```

What I want to do is once the user selects a time, I fire off some functions. I wanted to not do it every cycle in the wheel.

Is there a way to do this in SwiftUI or UIKit importing into SwiftUI?

Please see attached of what I'm looking at:

答:
You could try rolling your own DatePickerView, such as this approach:

```<code>struct ContentView: View {
    @State private var birthdate = Date()

    var body: some View {
            DatePickerView(date: $birthdate)
    }
}

struct DatePickerView: View {
    @Binding var date: Date
    @State var hasChanged = false

    var body: some View {
        ZStack {
            Color.white.opacity(0.01).ignoresSafeArea()
                .onTapGesture {
                    if hasChanged {
                        print("---> do a network call now with: \(date)")
                        hasChanged = false
                    }
                }
            DatePicker("Birth Date", selection: $date, displayedComponents: .hourAndMinute)
                .pickerStyle(.wheel)
                .onChange(of: date) { val in
                    hasChanged = true
                }
        }
    }
}
</code>```

Body:
I'm trying to fetch some data on a network call when a user selects a time from DatePicker.

I originally tested using .onChange but this fires every time that changes, and not on the final tap off.

DatePicker("Title", selection: $currentDate, displayedComponents: .hourAndMinute)
  .onChange(of: $currentDate) { value in
    print(value)
  }

I also tried using the didset{} but that also fired on every change too.

@Published var currentDate: Date = Date() {
  didSet { print(currentDate) }
}

What I want to do is once the user selects a time, I fire off some functions. I wanted to not do it every cycle in the wheel.

Is there a way to do this in SwiftUI or UIKit importing into SwiftUI?

Please see attached of what I'm looking at:

Body:
You could try rolling your own DatePickerView, such as this approach:

struct ContentView: View {
    @State private var birthdate = Date()

    var body: some View {
            DatePickerView(date: $birthdate)
    }
}

struct DatePickerView: View {
    @Binding var date: Date
    @State var hasChanged = false

    var body: some View {
        ZStack {
            Color.white.opacity(0.01).ignoresSafeArea()
                .onTapGesture {
                    if hasChanged {
                        print("---> do a network call now with: \(date)")
                        hasChanged = false
                    }
                }
            DatePicker("Birth Date", selection: $date, displayedComponents: .hourAndMinute)
                .pickerStyle(.wheel)
                .onChange(of: date) { val in
                    hasChanged = true
                }
        }
    }
}


问:
Landing page URL should be redirected to "/home"
Current landing page URL after login - 'www.website.com'. But I want it to be redirected to "www.website.com/home" upon login. So it has to be redirected to home component.</p>

答: you could simply redirect "/" to "/home"</p>


问:
Receiving error message 'Extension host terminated unexpectedly.' in Visual Studio Code
I have been looking around and I haven't found any answers to my issue.

I keep getting this error "Extension host terminated unexpectedly."    and I have tried removing all of my extensions, reinstalling the program, trying different versions of vscode including the insider versions.

The way I get this isssue isn't from trying to use the debugger or trying to use some sort of extension, as I said before I removed all of them and the error keeps on coming back, it's simply from opening the application. I'm not entirely sure how to continue? I have had to use another editor because the error just doesn't go away. I will just have to wait for another update of Visual Studio Code I assume? I've had the issue since tuesday this week, guessing since the latest update.

Above is the error message I get. It is closed by esc but reappears very shortly after, every time.

When I open developer tools, this is what I find in the console.

Running vscode from command prompt with Code.exe --disable-extensions doesn't help.

Visual Studio Code version:   1.16.1

I appreciate any help.

Linking my github issue on Microsoft/vscode as reference

答: I got same issue and it was because of Color Highlight Extension. I just uninstalled Color Highlight Extension and its working fine and NO ERROR.


问:
React state is always undefined when invoke onClick event
So I have the following code:

```<code>export default function Component() {

  const [list, setList] = useState<JSX.Element[]>();
  const [active, setActive] = useState<JSX.Element>();

  useEffect(()=>{
    let startTab = <li key={"0000-0000-0000-0000"} onClick={() => onClick()}>Star 1</li>;
    let secondTab = <li key={"0001-0000-0000-0000"} onClick={() => onClick()}>Star 2</li>;

    setList(() => [startTab, secondTab]);
    setActive(() => startTab);
  },[])

  const onClick= () =>{
    console.log(list)
  }

  return (
    <div id="BodyMain" className={css["Body-container"]}>
      <div className={css["tab-header"]}>
        { (
          <ul className={css["navs"]}>
            {list?.map(tabItem => tabItem)}
          </ul>)
        }
      </div>
      <div className={css["tab-body"]}>{}</div>
    </div>
  );
}
</code>```

every time I invoke onClick function it just returns undefined!

Nevertheless, 'React Developer Tools' shows that indeed these states have values!!

I am unable to change the state from onClick function because it is always undefined. What did I do wrong? and how can I fix it?

答:
The problem is the way that you use useEffect() hook.
When you dnt have any dependencies, that hook is gonna run once. Hence  setList(() => [startTab, secondTab]); just runs once

If you want to update it whenever you click, you can add a dependency for the useEffect() hook:

```<code>const [list, setList] = useState<JSX.Element[]>();
const [active, setActive] = useState<JSX.Element>();
const [ count, setCount ] = useState (0);

useEffect(()=>{
  let startTab = <li key={"0000-0000-0000-0000"} onClick={() => onClick()}>Star 1</li>;
  let secondTab = <li key={"0001-0000-0000-0000"} onClick={() => onClick()}>Star 2</li>;

  setList(() => [startTab, secondTab]);
  setActive(() => startTab);
},[count])

const onClick= () =>{
  setCount(() => count+1)
  console.log(list)
}
</code>```

I usually use a count variable to capture any change and set it as a useEffect dependency.

Read more at https://reactjs.org/docs/hooks-effect.html

Body:
So I have the following code:

export default function Component() {

  const [list, setList] = useState<JSX.Element[]>();
  const [active, setActive] = useState<JSX.Element>();

  useEffect(()=>{
    let startTab =
 onClick()}>Star 1
;
    let secondTab =
 onClick()}>Star 2
;

    setList(() => [startTab, secondTab]);
    setActive(() => startTab);
  },[])

  const onClick= () =>{
    console.log(list)
  }

  return (

        { (

            {list?.map(tabItem => tabItem)}

)
        }

{}

  );
}

every time I invoke onClick function it just returns undefined!

Nevertheless, 'React Developer Tools' shows that indeed these states have values!!

I am unable to change the state from onClick function because it is always undefined. What did I do wrong? and how can I fix it?

Body:
The problem is the way that you use useEffect() hook.
When you dnt have any dependencies, that hook is gonna run once. Hence  setList(() => [startTab, secondTab]); just runs once

If you want to update it whenever you click, you can add a dependency for the useEffect() hook:

const [list, setList] = useState<JSX.Element[]>();
const [active, setActive] = useState<JSX.Element>();
const [ count, setCount ] = useState (0);

useEffect(()=>{
  let startTab = <li key={"0000-0000-0000-0000"} onClick={() => onClick()}>Star 1</li>;
  let secondTab = <li key={"0001-0000-0000-0000"} onClick={() => onClick()}>Star 2</li>;

  setList(() => [startTab, secondTab]);
  setActive(() => startTab);
},[count])

const onClick= () =>{
  setCount(() => count+1)
  console.log(list)
}

I usually use a count variable to capture any change and set it as a useEffect dependency.

Read more at https://reactjs.org/docs/hooks-effect.html


问:
is it valid to use only digits as URI fragment identifier?
Is a link like this valid?

http://some.server/some/path#123

According to "List of valid characters for the fragment identifier in an URL?" answers, it should be valid. However, APT parser complains that this kind of link is not valid.

These links are generated by JXR and I wonder if JXR should be fixed or is APT parser broken (APT is used by Maven site plugin).

答:
That link is invalid for html/xml documents. Fragment identifiers refer to id or name attributes of tags.

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

http://www.w3.org/TR/html4/types.html#type-name


问:
How do I process numerous files using numerous regex conditions?
I want to process the cna and linear_cna files by reading only lines that do not contain  either Hugo_Symbol or -01.

```<code>import os
import re

class DataProcessing:

    def __init__(self, data):
        self.line = [line.rstrip('\n') for line in data]
        self.data = data

    def read_data(self):
        with open(self.data):
            pass
        return self.line

    def read_cna(self):
        # In cna and linear_cna files, skip lines that either begin with "Hugo_Symbol" or "-01"
        for lines in self.line:
            cna_lines = [lines for l in cna if not re.findall(r"^(Hugo_Symbol|[-01])", l)]
            return cna_lines

...continue...

dp_cna = DataProcessing("data_cna.txt")
dp_linear_cna = DataProcessing("data_linear_cna.txt")

dp_cna.read_data()
dp_linear_cna.read_data()
</code>```

Traceback:

```<code>Traceback (most recent call last):
  File "C:/Users/User/PycharmProjects/testing/main.py", line 24, in <module>
    cna = DataProcessing.read_data("data_cna.txt")
  File "C:/Users/User/PycharmProjects/testing/main.py", line 14, in read_data
    with open(self.data) as f:
AttributeError: 'str' object has no attribute 'data'
</code>```

答:
The right way to use your class consists of two steps.

Step 1: Create an instance of DataProcessing by invoking __init__. You do this by declaring dp = DataProcessing("data_cna.txt"). You can replace dp with any name you want.

Now dp is an instance of DataProcessing. Its data field is set to "DataProcessing". In other words, dp remembers the name of the file.

Step 2: Call read_data on dp. Note that read_data has only one parameter, namely self, which should not be passed as an argument, meaning it takes no arguments. Therefore, the right way to call read_data is just read_data(). To call read_data on dp you do dp.read_data().

Body:
I want to process the cna and linear_cna files by reading only lines that do not contain  either Hugo_Symbol or -01.

import os
import re

class DataProcessing:

    def __init__(self, data):
        self.line = [line.rstrip('\n') for line in data]
        self.data = data

    def read_data(self):
        with open(self.data):
            pass
        return self.line

    def read_cna(self):
        # In cna and linear_cna files, skip lines that either begin with "Hugo_Symbol" or "-01"
        for lines in self.line:
            cna_lines = [lines for l in cna if not re.findall(r"^(Hugo_Symbol|[-01])", l)]
            return cna_lines

...continue...

dp_cna = DataProcessing("data_cna.txt")
dp_linear_cna = DataProcessing("data_linear_cna.txt")

dp_cna.read_data()
dp_linear_cna.read_data()

Traceback:

Traceback (most recent call last):
  File "C:/Users/User/PycharmProjects/testing/main.py", line 24, in <module>
    cna = DataProcessing.read_data("data_cna.txt")
  File "C:/Users/User/PycharmProjects/testing/main.py", line 14, in read_data
    with open(self.data) as f:
AttributeError: 'str' object has no attribute 'data'


问:
Banning user who is replied to (Discord JS)
As title says, I'm trying to write some code that will ban a user if their message is replied to with the word ban. I think the way im getting the id of the original message is wrong but I'm not sure how to implement it otherwise. The error im getting is "TypeError: Cannot read properties of undefined (reading 'id')"</p>
```<code>client.on("messageCreate", (message) => {
    if (message.content == "ban" && message.type == 'REPLY') {
        const member = message.reference.author.id;
        message.guild.members.ban(member).then(console.log)
        .catch(console.error);
}
})
</code>```

答:
Change your current code to:

```<code> const client = new Discord.Client({ intents: [ "GUILDS",
 "GUILD_MESSAGES",
 "GUILD_MEMBERS" ] });

client.on("messageCreate", (message) => {
  if (message.content == "ban" && message.type == 'REPLY') {
     const member = message.author.id;
     message.guild.members.ban(member).then(console.log)
     .catch(console.error);
 }
})
</code>```

To access the Server Members Intent:

Go to discord/developers

In Applications, click your project/bot

Click the BOT section

Scroll down until you see the Privileged Gateway Intents

Find for the Server Members Intent

Enable it

Now try the script again

Body:
As title says, I'm trying to write some code that will ban a user if their message is replied to with the word ban. I think the way im getting the id of the original message is wrong but I'm not sure how to implement it otherwise. The error im getting is "TypeError: Cannot read properties of undefined (reading 'id')"

client.on("messageCreate", (message) => {
    if (message.content == "ban" && message.type == 'REPLY') {
        const member = message.reference.author.id;
        message.guild.members.ban(member).then(console.log)
        .catch(console.error);
}
})

Body:
Change your current code to:

 const client = new Discord.Client({ intents: [ "GUILDS",
 "GUILD_MESSAGES",
 "GUILD_MEMBERS" ] });

client.on("messageCreate", (message) => {
  if (message.content == "ban" && message.type == 'REPLY') {
     const member = message.author.id;
     message.guild.members.ban(member).then(console.log)
     .catch(console.error);
 }
})

To access the Server Members Intent:

Go to discord/developers

In Applications, click your project/bot

Click the BOT section

Scroll down until you see the Privileged Gateway Intents

Find for the Server Members Intent

Enable it

Now try the script again


问:
How do you select portions of a query in aggregate functions by some attribute
Say I have a table Account, and a table Tags. Tags contains all of the random string tags associated with an account. Tags have a TagType field, to indicate what type of tag it is (color, shape, size, etc).

I want to return aggregated lists of tags based on type on a per account basis. I've tried this:

```<code>SELECT a.accountid,
       (SELECT STRING_AGG(t.TagName, ', ') WHERE t.TagType = 'color') AS Colors,
       (SELECT STRING_AGG(t.TagName, ', ') WHERE t.TagType = 'shape') AS Shapes,
       (SELECT STRING_AGG(t.TagName, ', ') WHERE t.TagType = 'size') AS Sizes
FROM dbo.account a
INNER JOIN dbo.tag t ON a.Id = t.AccountId
GROUP BY a.AccountID
</code>```

Ideally, the results would be as such:

```<code>Row - AccountId -     Colors      -     Shapes     -     Sizes
1        10        Red, Blue         Round             NULL
2        11        Green             Rectangular       Small, Medium
etc...
</code>```

However, this results in the following error:

Column 'dbo.tag.TagType' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

If I group by TagType, each account is a separate row for each tag type. The whole point is to get one row per account with different tag types. How can I achieve that?

答:
An alternative to AlwaysLearning's excellent answer is just simple sub-queries e.g.</p>
```<code>SELECT a.AccountId
    , (SELECT STRING_AGG(t.TagName, ', ') FROM dbo.Tag t WHERE t.AccountId = A.AccountId AND t.TagType = 'color' ) AS Colors
    , (SELECT STRING_AGG(t.TagName, ', ') FROM dbo.Tag t WHERE t.AccountId = A.AccountId AND t.TagType = 'shape' ) AS Shapes
    , (SELECT STRING_AGG(t.TagName, ', ') FROM dbo.Tag t WHERE t.AccountId = A.AccountId AND t.TagType = 'size' ) AS Sizes
FROM dbo.Account a;
</code>```

Body:
Say I have a table Account, and a table Tags. Tags contains all of the random string tags associated with an account. Tags have a TagType field, to indicate what type of tag it is (color, shape, size, etc).

I want to return aggregated lists of tags based on type on a per account basis. I've tried this:

SELECT a.accountid,
       (SELECT STRING_AGG(t.TagName, ', ') WHERE t.TagType = 'color') AS Colors,
       (SELECT STRING_AGG(t.TagName, ', ') WHERE t.TagType = 'shape') AS Shapes,
       (SELECT STRING_AGG(t.TagName, ', ') WHERE t.TagType = 'size') AS Sizes
FROM dbo.account a
INNER JOIN dbo.tag t ON a.Id = t.AccountId
GROUP BY a.AccountID

Ideally, the results would be as such:

Row - AccountId -     Colors      -     Shapes     -     Sizes
1        10        Red, Blue         Round             NULL
2        11        Green             Rectangular       Small, Medium
etc...

However, this results in the following error:

Column 'dbo.tag.TagType' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

If I group by TagType, each account is a separate row for each tag type. The whole point is to get one row per account with different tag types. How can I achieve that?

Body:
An alternative to AlwaysLearning's excellent answer is just simple sub-queries e.g.

SELECT a.AccountId
    , (SELECT STRING_AGG(t.TagName, ', ') FROM dbo.Tag t WHERE t.AccountId = A.AccountId AND t.TagType = 'color' ) AS Colors
    , (SELECT STRING_AGG(t.TagName, ', ') FROM dbo.Tag t WHERE t.AccountId = A.AccountId AND t.TagType = 'shape' ) AS Shapes
    , (SELECT STRING_AGG(t.TagName, ', ') FROM dbo.Tag t WHERE t.AccountId = A.AccountId AND t.TagType = 'size' ) AS Sizes
FROM dbo.Account a;


问:
Why expo-location getCurrentPositionAsync heading returns -1 on ios?
The getCurrentPositionAsync function returns the speed and heading values of -1. It says in the document that if location permissions are not open, it can return as -1, but the speed and heading return -1 even though my location permission is open. What is the reason? Thanks in advance.</p>
```<code>const { status } = await Location.getForegroundPermissionsAsync();
const permission = await Location.getBackgroundPermissionsAsync();

if (status === "granted") {
const location = await Location.getCurrentPositionAsync();
}
</code>```
```<code>Object {
  "coords": Object {
    "accuracy": 13.815849315805039,
    "altitude": 108.1436996459961,
    "altitudeAccuracy": 14.495187759399414,
    "heading": -1,
    "latitude": 52.205276,
    "longitude": 0.119167,
    "speed": -1,
  },
  "timestamp": 1639056231575.1208,
}
</code>```

答:
(Expo-Location)

Please Take Permission Before access location.

Below Snippet Code you can try..

```<code>    let { status } = await Location.requestForegroundPermissionsAsync();
  if (status == 'granted') {

    let location = await Location.getCurrentPositionAsync({});
    console.log("Loc ",location);

  }
</code>```

Body:
The getCurrentPositionAsync function returns the speed and heading values of -1. It says in the document that if location permissions are not open, it can return as -1, but the speed and heading return -1 even though my location permission is open. What is the reason? Thanks in advance.

const { status } = await Location.getForegroundPermissionsAsync();
const permission = await Location.getBackgroundPermissionsAsync();

if (status === "granted") {
const location = await Location.getCurrentPositionAsync();
}

Object {
  "coords": Object {
    "accuracy": 13.815849315805039,
    "altitude": 108.1436996459961,
    "altitudeAccuracy": 14.495187759399414,
    "heading": -1,
    "latitude": 52.205276,
    "longitude": 0.119167,
    "speed": -1,
  },
  "timestamp": 1639056231575.1208,
}

Body:
(Expo-Location)

Please Take Permission Before access location.

Below Snippet Code you can try..

    let { status } = await Location.requestForegroundPermissionsAsync();
  if (status == 'granted') {

    let location = await Location.getCurrentPositionAsync({});
    console.log("Loc ",location);

  }


问:
faster way for moving large amounts data in oracle to external database
I have a java program that compares and moves data from a local Oracle database to an external MS SQL data base hosted by an online vendor.

Currently the program connects to the MS SQL database doing a SELECT * FROM myTABLE and putting the results in a two-dimensional array.  A temp table is then created in Oracle and the data is inserted into the temp table using a for loop:

```<code>for (int ii = 0; ii < arr.length(); ii++){
    query = "insert into myTable_temp values "+values_from_array;
    stmt.executeQuery();
}
</code>```

A MINUS statement is used find the differences:

```<code>query = "select * from ora_table minus select * from myTable_temp";
rs = stmt.executeQuery();
</code>```

and the result is then inserted back into the MS SQL table using a insert_into_mssql() method:

```<code>while (rs.next()){
    query = "insert into myTable values "+ values_from_rs
    insert_into_mssql(query);
}
</code>```

This works fine except a table I am using has 220,000 rows.  So it takes a long time to load the array, insert into temp table, run the minus statement, then insert everything back into the mssql table.

Is there a more efficient way to do this? or a way to make this faster?
(a dblink or any direct connection wont work bc of security restrictions)

答: I think it is a good idea to create a dblink.</p>

Body:
I have a java program that compares and moves data from a local Oracle database to an external MS SQL data base hosted by an online vendor.

Currently the program connects to the MS SQL database doing a SELECT * FROM myTABLE and putting the results in a two-dimensional array.  A temp table is then created in Oracle and the data is inserted into the temp table using a for loop:

for (int ii = 0; ii < arr.length(); ii++){
    query = "insert into myTable_temp values "+values_from_array;
    stmt.executeQuery();
}

A MINUS statement is used find the differences:

query = "select * from ora_table minus select * from myTable_temp";
rs = stmt.executeQuery();

and the result is then inserted back into the MS SQL table using a insert_into_mssql() method:

while (rs.next()){
    query = "insert into myTable values "+ values_from_rs
    insert_into_mssql(query);
}

This works fine except a table I am using has 220,000 rows.  So it takes a long time to load the array, insert into temp table, run the minus statement, then insert everything back into the mssql table.

Is there a more efficient way to do this? or a way to make this faster?
(a dblink or any direct connection wont work bc of security restrictions)


问:
kafka server is not getting started showing error
I am new in kafka using c#. It was working fine earlier. But now kafka server is crashing with following error.

```<code>Error :
Error while renaming dir for 46_HAQ-0 in log dir D:\tmp\kafka-logs (kafka.server.LogDirFailureChannel)
java.nio.file.AccessDeniedException: D:\tmp\kafka-logs\46_HAQ-0 -> D:\tmp\kafka-logs\46_HAQ-0.e77858d11274489887d14b1b0407cd44-delete
        at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:89)
        at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103)
        at java.base/sun.nio.fs.WindowsFileCopy.move(WindowsFileCopy.java:395)
        at java.base/sun.nio.fs.WindowsFileSystemProvider.move(WindowsFileSystemProvider.java:288)
        at java.base/java.nio.file.Files.move(Files.java:1421)
        at org.apache.kafka.common.utils.Utils.atomicMoveWithFallback(Utils.java:809)
        at kafka.log.Log.$anonfun$renameDir$2(Log.scala:759)
        at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:12)
        at kafka.log.Log.maybeHandleIOException(Log.scala:1996)
        at kafka.log.Log.renameDir(Log.scala:757)
        at kafka.log.LogManager.asyncDelete(LogManager.scala:842)
        at kafka.cluster.Partition.$anonfun$delete$1(Partition.scala:353)
        at kafka.utils.CoreUtils$.inLock(CoreUtils.scala:251)
        at kafka.utils.CoreUtils$.inWriteLock(CoreUtils.scala:259)
        at kafka.cluster.Partition.delete(Partition.scala:347)
        at kafka.server.ReplicaManager.stopReplica(ReplicaManager.scala:350)
        at kafka.server.ReplicaManager.$anonfun$stopReplicas$2(ReplicaManager.scala:380)
        at scala.collection.Iterator.foreach(Iterator.scala:937)
        at scala.collection.Iterator.foreach$(Iterator.scala:937)
        at scala.collection.AbstractIterator.foreach(Iterator.scala:1425)
        at scala.collection.IterableLike.foreach(IterableLike.scala:70)
        at scala.collection.IterableLike.foreach$(IterableLike.scala:69)
        at scala.collection.AbstractIterable.foreach(Iterable.scala:54)
        at kafka.server.ReplicaManager.stopReplicas(ReplicaManager.scala:378)
        at kafka.server.KafkaApis.handleStopReplicaRequest(KafkaApis.scala:200)
        at kafka.server.KafkaApis.handle(KafkaApis.scala:111)
        at kafka.server.KafkaRequestHandler.run(KafkaRequestHandler.scala:69)
        at java.base/java.lang.Thread.run(Thread.java:834)
        Suppressed: java.nio.file.AccessDeniedException: D:\tmp\kafka-logs\46_HAQ-0 -> D:\tmp\kafka-logs\46_HAQ-0.e77858d11274489887d14b1b0407cd44-delete
                at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:89)
                at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103)
                at java.base/sun.nio.fs.WindowsFileCopy.move(WindowsFileCopy.java:309)
                at java.base/sun.nio.fs.WindowsFileSystemProvider.move(WindowsFileSystemProvider.java:288)
                at java.base/java.nio.file.Files.move(Files.java:1421)
                at org.apache.kafka.common.utils.Utils.atomicMoveWithFallback(Utils.java:806)

stopped moving logs for partitions  because they are in the failed log directory D:\tmp\kafka-logs. (kafka.server.ReplicaManager)
[2019-05-08 08:05:00,598] INFO [ReplicaFetcherManager on broker 0] Removed fetcher for partitions Set() (kafka.server.ReplicaFetcherManager)
[2019-05-08 08:05:00,598] INFO Stopping serving logs in dir D:\tmp\kafka-logs (kafka.log.LogManager)
[2019-05-08 08:05:00,601] INFO [ReplicaAlterLogDirsManager on broker 0] Removed fetcher for partitions Set() (kafka.server.ReplicaAlterLogDirsManager)
[2019-05-08 08:05:00,608] INFO [ReplicaFetcherManager on broker 0] Removed fetcher for partitions Set(46_HAQ-0) (kafka.server.ReplicaFetcherManager)
[2019-05-08 08:05:00,608] INFO [ReplicaAlterLogDirsManager on broker 0] Removed fetcher for partitions Set(46_HAQ-0) (kafka.server.ReplicaAlterLogDirsManager)
[2019-05-08 08:05:00,612] ERROR Shutdown broker because all log dirs in D:\tmp\kafka-logs have failed (kafka.log.LogManager.
</code>```

I have encounter this problem multiple times.

答:
To windows machine please use lower version kafka 2.5.0. Its working fine zookeeper and server both are started.

Thanks

Body:
I am new in kafka using c#. It was working fine earlier. But now kafka server is crashing with following error.

Error :
Error while renaming dir for 46_HAQ-0 in log dir D:\tmp\kafka-logs (kafka.server.LogDirFailureChannel)
java.nio.file.AccessDeniedException: D:\tmp\kafka-logs\46_HAQ-0 -> D:\tmp\kafka-logs\46_HAQ-0.e77858d11274489887d14b1b0407cd44-delete
        at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:89)
        at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103)
        at java.base/sun.nio.fs.WindowsFileCopy.move(WindowsFileCopy.java:395)
        at java.base/sun.nio.fs.WindowsFileSystemProvider.move(WindowsFileSystemProvider.java:288)
        at java.base/java.nio.file.Files.move(Files.java:1421)
        at org.apache.kafka.common.utils.Utils.atomicMoveWithFallback(Utils.java:809)
        at kafka.log.Log.$anonfun$renameDir$2(Log.scala:759)
        at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:12)
        at kafka.log.Log.maybeHandleIOException(Log.scala:1996)
        at kafka.log.Log.renameDir(Log.scala:757)
        at kafka.log.LogManager.asyncDelete(LogManager.scala:842)
        at kafka.cluster.Partition.$anonfun$delete$1(Partition.scala:353)
        at kafka.utils.CoreUtils$.inLock(CoreUtils.scala:251)
        at kafka.utils.CoreUtils$.inWriteLock(CoreUtils.scala:259)
        at kafka.cluster.Partition.delete(Partition.scala:347)
        at kafka.server.ReplicaManager.stopReplica(ReplicaManager.scala:350)
        at kafka.server.ReplicaManager.$anonfun$stopReplicas$2(ReplicaManager.scala:380)
        at scala.collection.Iterator.foreach(Iterator.scala:937)
        at scala.collection.Iterator.foreach$(Iterator.scala:937)
        at scala.collection.AbstractIterator.foreach(Iterator.scala:1425)
        at scala.collection.IterableLike.foreach(IterableLike.scala:70)
        at scala.collection.IterableLike.foreach$(IterableLike.scala:69)
        at scala.collection.AbstractIterable.foreach(Iterable.scala:54)
        at kafka.server.ReplicaManager.stopReplicas(ReplicaManager.scala:378)
        at kafka.server.KafkaApis.handleStopReplicaRequest(KafkaApis.scala:200)
        at kafka.server.KafkaApis.handle(KafkaApis.scala:111)
        at kafka.server.KafkaRequestHandler.run(KafkaRequestHandler.scala:69)
        at java.base/java.lang.Thread.run(Thread.java:834)
        Suppressed: java.nio.file.AccessDeniedException: D:\tmp\kafka-logs\46_HAQ-0 -> D:\tmp\kafka-logs\46_HAQ-0.e77858d11274489887d14b1b0407cd44-delete
                at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:89)
                at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103)
                at java.base/sun.nio.fs.WindowsFileCopy.move(WindowsFileCopy.java:309)
                at java.base/sun.nio.fs.WindowsFileSystemProvider.move(WindowsFileSystemProvider.java:288)
                at java.base/java.nio.file.Files.move(Files.java:1421)
                at org.apache.kafka.common.utils.Utils.atomicMoveWithFallback(Utils.java:806)

stopped moving logs for partitions  because they are in the failed log directory D:\tmp\kafka-logs. (kafka.server.ReplicaManager)
[2019-05-08 08:05:00,598] INFO [ReplicaFetcherManager on broker 0] Removed fetcher for partitions Set() (kafka.server.ReplicaFetcherManager)
[2019-05-08 08:05:00,598] INFO Stopping serving logs in dir D:\tmp\kafka-logs (kafka.log.LogManager)
[2019-05-08 08:05:00,601] INFO [ReplicaAlterLogDirsManager on broker 0] Removed fetcher for partitions Set() (kafka.server.ReplicaAlterLogDirsManager)
[2019-05-08 08:05:00,608] INFO [ReplicaFetcherManager on broker 0] Removed fetcher for partitions Set(46_HAQ-0) (kafka.server.ReplicaFetcherManager)
[2019-05-08 08:05:00,608] INFO [ReplicaAlterLogDirsManager on broker 0] Removed fetcher for partitions Set(46_HAQ-0) (kafka.server.ReplicaAlterLogDirsManager)
[2019-05-08 08:05:00,612] ERROR Shutdown broker because all log dirs in D:\tmp\kafka-logs have failed (kafka.log.LogManager.

I have encounter this problem multiple times.


问:
How could extract context from a p-tag with selected option and also others word have no option to selecte?
I have a p-tag for showing the article which contains two types -
words you don't need to change and words you can select in it. E.G.

```<code>    <div class="context">
        <p v-html="report_data" class="showTxt" id="showTxt" contenteditable="true"></p>
    </div>
</code>```

and I wanna make a window for showing the result which user selected and also include others don't need to change.

**
rr = $('#showTxt option:selected').text()

this way would delect other word don't need to change

r_content = document.getElementById('showTxt').textContent

and this way would show everything include all option

thanks in advance

答:
Your question is not clear to me, but I guess you want to get the text user selected. If so you can use getSelection.

window.getSelection().toString();
```

Body:
I have a p-tag for showing the article which contains two types -
words you don't need to change and words you can select in it. E.G.

and I wanna make a window for showing the result which user selected and also include others don't need to change.

**
rr = $('#showTxt option:selected').text()

this way would delect other word don't need to change

r_content = document.getElementById('showTxt').textContent

and this way would show everything include all option

thanks in advance