问:
How do I get my leap year Java program to keep looping?
I'm trying to finish my final assignment for my intro to programming class and I can't figure out how to keep the program looping until the user inputs 0 to exit. My teacher wanted this exact format, so I'm not allowed to condense the code to make it simpler. We've only been coding with Java for roughly 4 weeks throughout the whole 16-week semester (I don't understand it either) so I'm not very familiar with how to use and understand Java.

Where my program is at currently, is that it takes the input, determines if it's a leap year, outputs the correct string, and then exits. My checkValidYear method outputs the string "Enter 0 if you'd like to exit." but doesn't allow further input. I need some guidance on where/how to loop the program and stop it from ending.

Too sum it up, I need assistance on changing my program from exiting when given an input, to looping the program for more inputs until the user inputs 0.

This is my main file.

```<code>/**
 * Main class of the Java program.
 */
import java.util.Scanner;

public class FinalProject {

    public static void main(String[] args) {

        int usersYear;

        //set up the scanner
        Scanner inputReader = new Scanner(System.in);

        //Create leap year instance
        LeapYear inputYear = new LeapYear();

    do {
        System.out.println("Enter a year which I will test if it is a leap year. Input 0  to stop");

        int i = inputReader.nextInt();
        inputYear.setYear(i);
       }

         while(inputYear.checkValidYear().equals("invalid"));
        inputReader.close();
        System.out.println(inputYear.getOutput());

       // create a loop to which sees if the user wants to stop
        //   in the loop:
        //     use the setYear() method to set the year inside the object
        //     use the CheckforLeapYear() method to do all the testing. DO NOT SEND YEAR because it was    already set using setYear()
        //     use the getOutput() to get the message you print - is it a leap year or not.
        //     get the next year from the user

    } //end main method
} //end Main class

</code>```

This is my LeapYear file where the methods are kept.

```<code>/**
 LeapYear class determines if a year is a leap year
**/
class LeapYear {
    /**Declarations**/
    /*
    * 1. Create a private year variable that is an integer
    * 2. Create a getter and setter method for the field variable
    * 3. Create a default constructor.Do not set any variables
    **/
  private int year;

  public LeapYear(){

  }

  // Getter
     public int getYear() {
        return year;
  }

  // Setter
     public void setYear(int newYear) {
        year = newYear;
  }

    /*
    * This method should call all the checkIfYearDivisibleby4(), checkIfYearNotDivisibleby100(), and checkIfYearDivisibleby400()
    * @return int year
    **/
    public boolean checkForLeapYear(){
        boolean result = false;
        //add code here
      result= checkIfYearDivisibleby4()||
        checkIfYearNotDivisibleby100()||
        checkIfYearDivisibleby400();

        return result;
    }

    /*
    * This method should return true if year is divisible by 4
    * @return int year
    **/
    private boolean checkIfYearDivisibleby4(){
        boolean result = false;
            //add code here
            result = year%4==0;
            return result;
    }

    /*
    * This method should return true if year is NOT divisible by 100
    * @return int year
    **/
    private boolean checkIfYearNotDivisibleby100(){
        boolean result = false;
        //add code here
        result = year%100==0;
        return result;

    }

    /*
    * This method should return true if year is divisible by 400
    * @return int year
    **/
    private boolean checkIfYearDivisibleby400(){
        boolean result = false;
        //add code here
        result = year%400==0;
        return result;

    }

    /*
    * This method calls the checkForLeapYear()
    * if the checkForLeapYear() returns true return a string that states it is a leap year
    * otherwise, return a string that states it is not a leap year
    * @return int year
    **/

      public String getOutput(){
      String output= "";
      if (checkForLeapYear())
      {
          output = "This is a leap year";
      }
      else
      {
          output = "This is not a leap year";
      }
      return output;
    }

    public String checkValidYear(){
        System.out.println("Enter 0 if you'd like to exit.");
        String result = "valid";
        if(year==0)
        result = "invalid";
        return result;

    }

}
</code>```

This is what the output looks like:

Enter a year which I will test if it is a leap year. Input 0  to stop
2023
Enter 0 if you'd like to exit.
This is not a leap year

Body:
I'm trying to finish my final assignment for my intro to programming class and I can't figure out how to keep the program looping until the user inputs 0 to exit. My teacher wanted this exact format, so I'm not allowed to condense the code to make it simpler. We've only been coding with Java for roughly 4 weeks throughout the whole 16-week semester (I don't understand it either) so I'm not very familiar with how to use and understand Java.

Where my program is at currently, is that it takes the input, determines if it's a leap year, outputs the correct string, and then exits. My checkValidYear method outputs the string "Enter 0 if you'd like to exit." but doesn't allow further input. I need some guidance on where/how to loop the program and stop it from ending.

Too sum it up, I need assistance on changing my program from exiting when given an input, to looping the program for more inputs until the user inputs 0.

This is my main file.

/**
 * Main class of the Java program.
 */
import java.util.Scanner;

public class FinalProject {

    public static void main(String[] args) {

        int usersYear;

        //set up the scanner
        Scanner inputReader = new Scanner(System.in);

        //Create leap year instance
        LeapYear inputYear = new LeapYear();

    do {
        System.out.println("Enter a year which I will test if it is a leap year. Input 0  to stop");

        int i = inputReader.nextInt();
        inputYear.setYear(i);
       }

         while(inputYear.checkValidYear().equals("invalid"));
        inputReader.close();
        System.out.println(inputYear.getOutput());

       // create a loop to which sees if the user wants to stop
        //   in the loop:
        //     use the setYear() method to set the year inside the object
        //     use the CheckforLeapYear() method to do all the testing. DO NOT SEND YEAR because it was    already set using setYear()
        //     use the getOutput() to get the message you print - is it a leap year or not.
        //     get the next year from the user

    } //end main method
} //end Main class

This is my LeapYear file where the methods are kept.

/**
 LeapYear class determines if a year is a leap year
**/
class LeapYear {
    /**Declarations**/
    /*
    * 1. Create a private year variable that is an integer
    * 2. Create a getter and setter method for the field variable
    * 3. Create a default constructor.Do not set any variables
    **/
  private int year;

  public LeapYear(){

  }

  // Getter
     public int getYear() {
        return year;
  }

  // Setter
     public void setYear(int newYear) {
        year = newYear;
  }

    /*
    * This method should call all the checkIfYearDivisibleby4(), checkIfYearNotDivisibleby100(), and checkIfYearDivisibleby400()
    * @return int year
    **/
    public boolean checkForLeapYear(){
        boolean result = false;
        //add code here
      result= checkIfYearDivisibleby4()||
        checkIfYearNotDivisibleby100()||
        checkIfYearDivisibleby400();

        return result;
    }

    /*
    * This method should return true if year is divisible by 4
    * @return int year
    **/
    private boolean checkIfYearDivisibleby4(){
        boolean result = false;
            //add code here
            result = year%4==0;
            return result;
    }

    /*
    * This method should return true if year is NOT divisible by 100
    * @return int year
    **/
    private boolean checkIfYearNotDivisibleby100(){
        boolean result = false;
        //add code here
        result = year%100==0;
        return result;

    }

    /*
    * This method should return true if year is divisible by 400
    * @return int year
    **/
    private boolean checkIfYearDivisibleby400(){
        boolean result = false;
        //add code here
        result = year%400==0;
        return result;

    }

    /*
    * This method calls the checkForLeapYear()
    * if the checkForLeapYear() returns true return a string that states it is a leap year
    * otherwise, return a string that states it is not a leap year
    * @return int year
    **/

      public String getOutput(){
      String output= "";
      if (checkForLeapYear())
      {
          output = "This is a leap year";
      }
      else
      {
          output = "This is not a leap year";
      }
      return output;
    }

    public String checkValidYear(){
        System.out.println("Enter 0 if you'd like to exit.");
        String result = "valid";
        if(year==0)
        result = "invalid";
        return result;

    }

}

This is what the output looks like:

Enter a year which I will test if it is a leap year. Input 0  to stop
2023
Enter 0 if you'd like to exit.
This is not a leap year


来源: stackexchange

问:
Cor() function giving me and error that the standard deviation is zero
I am trying to run a correlation matrix on a data frame using the following code:

```<code>data <- raybio %>% select(4:20, 23:112)
data <- as.matrix(data)
mydata.cor <- cor(data, method = "pearson", use = "complete.obs")
</code>```

I keep getting the following error:

```<code>Warning message:
In cor(data, method = "pearson", use = "complete.obs") :
  the standard deviation is zero
</code>```

Any suggestions?

ContentLicense: CC BY-SA 4.0

Body:
I am trying to run a correlation matrix on a data frame using the following code:

data <- raybio %>% select(4:20, 23:112)
data <- as.matrix(data)
mydata.cor <- cor(data, method = "pearson", use = "complete.obs")

I keep getting the following error:

Warning message:
In cor(data, method = "pearson", use = "complete.obs") :
  the standard deviation is zero

Any suggestions?


问:
How to use Typescript on Vee-Validate setFieldValue
I'm using the setFieldValue function to manually set values in my form.  When I use the function I get a typescript error.

```<code>const { handleSubmit, setFieldValue, setFieldError, values, resetForm } = useForm();

setFieldValue('myField', 'some value');
    TS Error:  Argument of type 'string' is not assignable to parameter of type 'never'.ts(2345)
</code>```

I can get rid of the error by changing the arguments to:

```<code>setFieldValue('myField' as never, 'some value' as never);
    //  No error on this
</code>```

I'm sure that this is not proper form though.  What is the correct way to type this function so that I don't get a TS Error?

Using Vue 3.2 and Vee-Validate 4.6.

Body:
I'm using the setFieldValue function to manually set values in my form.  When I use the function I get a typescript error.

const { handleSubmit, setFieldValue, setFieldError, values, resetForm } = useForm();

setFieldValue('myField', 'some value');
    TS Error:  Argument of type 'string' is not assignable to parameter of type 'never'.ts(2345)

I can get rid of the error by changing the arguments to:

setFieldValue('myField' as never, 'some value' as never);
    //  No error on this

I'm sure that this is not proper form though.  What is the correct way to type this function so that I don't get a TS Error?

Using Vue 3.2 and Vee-Validate 4.6.


问:
503 service unavailable next.js in cpanel
I want to deploy next.js in cpanel but everytime throw 503 service unavailable error. How can i solve?

I am using next.js version 13.0.6

//server js

```<code>const { createServer } = require("http");
const { parse } = require("url");
const next = require("next");

const dev = process.env.NODE_ENV !== "production";
const hostname = "localhost";
const port = process.env.PORT || 3000;
// when using middleware `hostname` and `port` must be provided below
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  createServer(async (req, res) => {
    try {
      // Be sure to pass `true` as the second argument to `url.parse`.
      // This tells it to parse the query portion of the URL.
      const parsedUrl = parse(req.url, true);
      const { pathname, query } = parsedUrl;

      if (pathname === "/a") {
        await app.render(req, res, "/a", query);
      } else if (pathname === "/b") {
        await app.render(req, res, "/b", query);
      } else {
        await handle(req, res, parsedUrl);
      }
    } catch (err) {
      console.error("Error occurred handling", req.url, err);
      res.statusCode = 500;
      res.end("internal server error");
    }
  }).listen(port, (err) => {
    if (err) throw err;
    console.log(`> Ready on http://${hostname}:${port}`);
  });
});
</code>```

I am tried to fix server js but every time throw error. As usual Node server js files are work so well but next server.js files are throw error. Can anyone help me.

Body:
I want to deploy next.js in cpanel but everytime throw 503 service unavailable error. How can i solve?

I am using next.js version 13.0.6

//server js

const { createServer } = require("http");
const { parse } = require("url");
const next = require("next");

const dev = process.env.NODE_ENV !== "production";
const hostname = "localhost";
const port = process.env.PORT || 3000;
// when using middleware `hostname` and `port` must be provided below
const app = next({ dev, hostname, port });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  createServer(async (req, res) => {
    try {
      // Be sure to pass `true` as the second argument to `url.parse`.
      // This tells it to parse the query portion of the URL.
      const parsedUrl = parse(req.url, true);
      const { pathname, query } = parsedUrl;

      if (pathname === "/a") {
        await app.render(req, res, "/a", query);
      } else if (pathname === "/b") {
        await app.render(req, res, "/b", query);
      } else {
        await handle(req, res, parsedUrl);
      }
    } catch (err) {
      console.error("Error occurred handling", req.url, err);
      res.statusCode = 500;
      res.end("internal server error");
    }
  }).listen(port, (err) => {
    if (err) throw err;
    console.log(`> Ready on http://${hostname}:${port}`);
  });
});

I am tried to fix server js but every time throw error. As usual Node server js files are work so well but next server.js files are throw error. Can anyone help me.


问:
how to fix Fatal Exception: Resources$NotFoundException: Resource ID #0x20c003b DeviceFormFactor.java line 107 org.chromium.ui.base.DeviceFormFactor.a
Getting this in crashlytics, not getting an idea where the problem would be.

```<code>Fatal Exception: android.content.res.Resources$NotFoundException: Resource ID #0x20c003b
   at android.content.res.ResourcesImpl.getValue(ResourcesImpl.java:264)
   at android.content.res.Resources.getInteger(Resources.java:1201)
   at org.chromium.ui.base.DeviceFormFactor.a(DeviceFormFactor.java:107)
   at R8.onCreateActionMode(R8.java:722)
   at com.android.internal.policy.DecorView$ActionModeCallback2Wrapper.onCreateActionMode(DecorView.java:2840)
   at com.android.internal.policy.DecorView.startActionMode(DecorView.java:1012)
   at com.android.internal.policy.DecorView.startActionModeForChild(DecorView.java:968)

   at android.view.ViewGroup.startActionModeForChild(ViewGroup.java:1033)
   at android.view.View.startActionMode(View.java:7774)
   at org.chromium.content.browser.selection.SelectionPopupControllerImpl.B(SelectionPopupControllerImpl.java:489)
   at di0.a(di0.java:1587)
   at Fl0.i(Fl0.java:259)
   at T6.run(T6.java:454)
   at android.os.Handler.handleCallback(Handler.java:938)
   at android.os.Handler.dispatchMessage(Handler.java:99)
   at android.os.Looper.loop(Looper.java:264)
   at android.app.ActivityThread.main(ActivityThread.java:8312)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:632)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1049)
</code>```

any suggestions on how to fix this?

whats the putpose of org.chromium.content.browser.selection.SelectionPopupControllerImpl class and org.chromium.content.browser.selection.SelectionPopupControllerImpl method?

can we guess what is actually happening or what has triggered this?

Thanks!

Body:
Getting this in crashlytics, not getting an idea where the problem would be.

Fatal Exception: android.content.res.Resources$NotFoundException: Resource ID #0x20c003b
   at android.content.res.ResourcesImpl.getValue(ResourcesImpl.java:264)
   at android.content.res.Resources.getInteger(Resources.java:1201)
   at org.chromium.ui.base.DeviceFormFactor.a(DeviceFormFactor.java:107)
   at R8.onCreateActionMode(R8.java:722)
   at com.android.internal.policy.DecorView$ActionModeCallback2Wrapper.onCreateActionMode(DecorView.java:2840)
   at com.android.internal.policy.DecorView.startActionMode(DecorView.java:1012)
   at com.android.internal.policy.DecorView.startActionModeForChild(DecorView.java:968)

   at android.view.ViewGroup.startActionModeForChild(ViewGroup.java:1033)
   at android.view.View.startActionMode(View.java:7774)
   at org.chromium.content.browser.selection.SelectionPopupControllerImpl.B(SelectionPopupControllerImpl.java:489)
   at di0.a(di0.java:1587)
   at Fl0.i(Fl0.java:259)
   at T6.run(T6.java:454)
   at android.os.Handler.handleCallback(Handler.java:938)
   at android.os.Handler.dispatchMessage(Handler.java:99)
   at android.os.Looper.loop(Looper.java:264)
   at android.app.ActivityThread.main(ActivityThread.java:8312)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:632)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1049)

any suggestions on how to fix this?

whats the putpose of org.chromium.content.browser.selection.SelectionPopupControllerImpl class and org.chromium.content.browser.selection.SelectionPopupControllerImpl method?

can we guess what is actually happening or what has triggered this?

Thanks!


问:
Using spinner inside a Dialog in an Non actvity class
I'm trying to implement a spinner inside a Dialog, it is named UserClassDialog.java(non activity class), as shown below:

```<code>public class UserClassDialog extends AppCompatDialogFragment {
 @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState)  {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.layout_dialog, null);

        Spinner spinner = view.findViewById(R.id.spinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.courses);
}
</code>```

But, of course it would be an error because using "this" would be an error inside a non activity class.  My question is, how can use this spinner in an Non activity class? Is it by using a constructor? If yes, how?

Also this is my code for the mainactivity(named UserClass.class) which calls the dialog box, as shown below:

```<code>public class UserClasses extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_classes);
}
@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater =getMenuInflater();
        inflater.inflate(R.menu.class_menu, menu); //Layout for the dialog
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.add: // the add icon on the class_menu layout to open the dialog
                openDialog();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }

    }

    public void openDialog() {
            UserClassDialog userClassDialog = new UserClassDialog();
            userClassDialog.show(getSupportFragmentManager(), "user class dialog");

    }
</code>```

Body:
I'm trying to implement a spinner inside a Dialog, it is named UserClassDialog.java(non activity class), as shown below:

public class UserClassDialog extends AppCompatDialogFragment {
 @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState)  {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.layout_dialog, null);

        Spinner spinner = view.findViewById(R.id.spinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.courses);
}

But, of course it would be an error because using "this" would be an error inside a non activity class.  My question is, how can use this spinner in an Non activity class? Is it by using a constructor? If yes, how?

Also this is my code for the mainactivity(named UserClass.class) which calls the dialog box, as shown below:

public class UserClasses extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_classes);
}
@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater =getMenuInflater();
        inflater.inflate(R.menu.class_menu, menu); //Layout for the dialog
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.add: // the add icon on the class_menu layout to open the dialog
                openDialog();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }

    }

    public void openDialog() {
            UserClassDialog userClassDialog = new UserClassDialog();
            userClassDialog.show(getSupportFragmentManager(), "user class dialog");

    }


问:
Containerizing .Net 6 Web Api using Docker
I am containerizing the .NET 6 Web API which includes custom NuGet feeds. The docker build is successful but when I do run the docker container it sends an empty response.

Here is my Docker file:

```<code>FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["test.OrganizationService.csproj", "./"]
COPY ./nuget.config .
RUN dotnet restore
COPY . .
RUN dotnet build "test.OrganizationService.csproj" -c Release -o /app

FROM build AS publish
RUN dotnet publish "test.OrganizationService.csproj" -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "test.OrganizationService.dll"]
</code>```

This is the error I am getting:

Using the following documentation for Managing NuGet Credentials in Docker

Managing NuGet Credentials in Docker Scenarios

Body:
I am containerizing the .NET 6 Web API which includes custom NuGet feeds. The docker build is successful but when I do run the docker container it sends an empty response.

Here is my Docker file:

FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["test.OrganizationService.csproj", "./"]
COPY ./nuget.config .
RUN dotnet restore
COPY . .
RUN dotnet build "test.OrganizationService.csproj" -c Release -o /app

FROM build AS publish
RUN dotnet publish "test.OrganizationService.csproj" -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "test.OrganizationService.dll"]

This is the error I am getting:

Using the following documentation for Managing NuGet Credentials in Docker

Managing NuGet Credentials in Docker Scenarios


问:
Finding the deleted files between two commits
I'm currently writing a script in bash to find the deleted files between a pull request and the latest tag of the destination branch of the pull request. My idea is to get the commit id of both the pull request and the commit id of the tag and compare both of them to find the deleted files.

I'm using this command to find the diff between the commits

```<code>GIT_DIFF_RESULT=$(git diff --diff-filter=D --name-only "$commitid_of_latest_tag"..."$BITBUCKET_COMMIT")
</code>```

My repository is in bitbucket and their variable BITBUCKET_COMMIT will give me the commit id of the pull request and commitid_of_latest_tag will me the commit of the latest tag in the branch.

I checked the execution and both the values from the variables are correct but the answer that I get is wrong. If I run it several times it will give me different answers for the same information.

Body:
I'm currently writing a script in bash to find the deleted files between a pull request and the latest tag of the destination branch of the pull request. My idea is to get the commit id of both the pull request and the commit id of the tag and compare both of them to find the deleted files.

I'm using this command to find the diff between the commits

GIT_DIFF_RESULT=$(git diff --diff-filter=D --name-only "$commitid_of_latest_tag"..."$BITBUCKET_COMMIT")

My repository is in bitbucket and their variable BITBUCKET_COMMIT will give me the commit id of the pull request and commitid_of_latest_tag will me the commit of the latest tag in the branch.

I checked the execution and both the values from the variables are correct but the answer that I get is wrong. If I run it several times it will give me different answers for the same information.


问:
read pandas dataframe cell value of list error ValueError: could not convert string to float: '[0,2]'
Have a pandas dataframe and some of the cell values are list. Tried to get  the cell value out but get some errors.

```<code>dd = pd.DataFrame([['apple',[0,2],[3,4],['pear',3,4]],columns = ['product','count1','count2'])
</code>```

Then this dataframe was saved as a csv file and read back for further processing.
Tried to get the cell value out as numbers inside a function

```<code>ss = dd[dd['product']=='apple'].copy()
count1 = ss['count1'].values[0]
count2 = ss['count2'].values[0]
if isinstance(count1,list):
   print('it's list')
   count1 = [int(float(i)) for i in count1]
else:
   print('it's not list')
   count1 = int(float(i))
</code>```

but got errors

```<code>ValueError: could not convert string to float: '[0,2]'
</code>```

here count1 value is '[0,2]' which is string.
How could I avoid such error?

Body:
Have a pandas dataframe and some of the cell values are list. Tried to get  the cell value out but get some errors.

dd = pd.DataFrame([['apple',[0,2],[3,4],['pear',3,4]],columns = ['product','count1','count2'])

Then this dataframe was saved as a csv file and read back for further processing.
Tried to get the cell value out as numbers inside a function

ss = dd[dd['product']=='apple'].copy()
count1 = ss['count1'].values[0]
count2 = ss['count2'].values[0]
if isinstance(count1,list):
   print('it's list')
   count1 = [int(float(i)) for i in count1]
else:
   print('it's not list')
   count1 = int(float(i))

but got errors

ValueError: could not convert string to float: '[0,2]'

here count1 value is '[0,2]' which is string.
How could I avoid such error?


问:
Getting Genebank info automatically in a python script
Is there a method in Biopython where I can get the entire genebank file just by inputting the accession number of the protein? From what I'm seeing, I would have to have the gb file locally, or scrape it from the genebank website. Is there a biopython method that does this for me?

I'm pretty new to programming so any help is appreciated, thanks.

I tried looking at the biopython documentation, but they all are reading a local gb file.


问:
im getting infinite loop for my user and gender's relationship,advice?
I am trying to mix two objects together via one to many relationship.just by running the application i get an infinite loop between the processor trying to get the user then gender then user and so on.I have tried looking around but no other page has solutions that applied to my issue or upon trying to fix it worked.

error

```<code>    Hibernate: select gender0_.id as id1_18_, gender0_.gender as gender2_18_ from gender gender0_
2022-12-08 22:23:48.371 TRACE 11832 --- [nio-8080-exec-3] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_18_] : [BIGINT]) - [1]
2022-12-08 22:23:48.371 TRACE 11832 --- [nio-8080-exec-3] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([gender2_18_] : [VARCHAR]) - [male]
2022-12-08 22:23:48.371 TRACE 11832 --- [nio-8080-exec-3] org.hibernate.type.CollectionType        : Created collection wrapper: [com.example.realtyKing.Account.GeneralUser.Model.Gender.users#1]
2022-12-08 22:23:48.372 DEBUG 11832 --- [nio-8080-exec-3] org.hibernate.SQL                        : select users0_.gender_id as gender_11_27_0_, users0_.id as id1_27_0_, users0_.id as id1_27_1_, users0_.dob as dob2_27_1_, users0_.email as email3_27_1_, users0_.email_config as email_co4_27_1_, users0_.first_name as first_na5_27_1_, users0_.gender_id as gender_11_27_1_, users0_.is_active as is_activ6_27_1_, users0_.last_name as last_nam7_27_1_, users0_.middle_name as middle_n8_27_1_, users0_.password as password9_27_1_, users0_.phone_number as phone_n10_27_1_, employee1_.id as id1_10_2_, employee1_.address as address2_10_2_, employee1_.company_id as company_5_10_2_, employee1_.date_of_termination as date_of_3_10_2_, employee1_.department_id as departme6_10_2_, employee1_.status as status4_10_2_, employee1_.user_id as user_id7_10_2_, employeege2_.id as id1_15_3_, employeege2_.area_id as area_id2_15_3_, employeege2_.city_id as city_id3_15_3_, employeege2_.employee_id as employee4_15_3_, employment3_.id as id1_16_4_, employment3_.brokage_share as brokage_2_16_4_, employment3_.employee_id as employee6_16_4_, employment3_.employee_end_date as employee3_16_4_, employment3_.employee_start_date as employee4_16_4_, employment3_.hourly_pay as hourly_p5_16_4_ from user users0_ left outer join employee employee1_ on users0_.id=employee1_.user_id left outer join employee_geographic_data employeege2_ on employee1_.id=employeege2_.employee_id left outer join employment_term employment3_ on employee1_.id=employment3_.employee_id where users0_.gender_id=?
Hibernate: select users0_.gender_id as gender_11_27_0_, users0_.id as id1_27_0_, users0_.id as id1_27_1_, users0_.dob as dob2_27_1_, users0_.email as email3_27_1_, users0_.email_config as email_co4_27_1_, users0_.first_name as first_na5_27_1_, users0_.gender_id as gender_11_27_1_, users0_.is_active as is_activ6_27_1_, users0_.last_name as last_nam7_27_1_, users0_.middle_name as middle_n8_27_1_, users0_.password as password9_27_1_, users0_.phone_number as phone_n10_27_1_, employee1_.id as id1_10_2_, employee1_.address as address2_10_2_, employee1_.company_id as company_5_10_2_, employee1_.date_of_termination as date_of_3_10_2_, employee1_.department_id as departme6_10_2_, employee1_.status as status4_10_2_, employee1_.user_id as user_id7_10_2_, employeege2_.id as id1_15_3_, employeege2_.area_id as area_id2_15_3_, employeege2_.city_id as city_id3_15_3_, employeege2_.employee_id as employee4_15_3_, employment3_.id as id1_16_4_, employment3_.brokage_share as brokage_2_16_4_, employment3_.employee_id as employee6_16_4_, employment3_.employee_end_date as employee3_16_4_, employment3_.employee_start_date as employee4_16_4_, employment3_.hourly_pay as hourly_p5_16_4_ from user users0_ left outer join employee employee1_ on users0_.id=employee1_.user_id left outer join employee_geographic_data employeege2_ on employee1_.id=employeege2_.employee_id left outer join employment_term employment3_ on employee1_.id=employment3_.employee_id where users0_.gender_id=?
2022-12-08 22:23:48.372 TRACE 11832 --- [nio-8080-exec-3] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [BIGINT] - [1]
2022-12-08 22:23:48.377 DEBUG 11832 --- [nio-8080-exec-8] org.hibernate.SQL                        : select gender0_.id as id1_18_, gender0_.gender as gender2_18_ from gender gender0_
</code>```

my objects

```<code>package com.example.realtyKing.Account.GeneralUser.Model;
import com.example.realtyKing.Account.Employee.Model.Employee;
import com.example.realtyKing.Transaction.Model.Payroll;
import com.fasterxml.jackson.annotation.*;
import com.voodoodyne.jackson.jsog.JSOGGenerator;
import lombok.*;

import javax.persistence.*;
import java.sql.Date;
import java.util.*;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIdentityInfo(generator= JSOGGenerator.class)
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "user", uniqueConstraints = @UniqueConstraint(columnNames = "email"))
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "first_name", nullable = false)
    private String firstName;
    @Column(name = "middle_name")
    private String middleName;
    @Column(name = "last_name", nullable = false)
    private String lastName;
    @Column(nullable = false)
    private Date dob;
    @Column(name = "phone_number", nullable = false)
    private String phoneNumber;

    @Column(nullable = false)
    private String email;

    @Column(nullable = false)
    private String password;
    @Column(nullable = false)
    private Boolean isActive;

    @Column(name = "email_config")
    private String emailConfig;

    @OneToOne(mappedBy = "user")
    private Employee employee;

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(
            name = "user_role",
            joinColumns = @JoinColumn(
                    name = "user_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(
                    name = "role_id", referencedColumnName = "id"))

    private Collection < Role > roles;

    @JsonBackReference
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "gender_id")
    private Gender gender;

    @OneToMany(fetch=FetchType.LAZY, mappedBy="user")
    private Set<Payroll> payrolls;

    public User(String firstName, String lastName, Date dob, String phoneNumber, String email,
                String password, Collection < Role > roles, Gender gender)
    {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        this.dob = dob;
        this.phoneNumber=phoneNumber;
        this.email = email;
        this.password = password;
        this.roles = roles;
        this.gender=gender;
    }

}
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIdentityInfo(generator= JSOGGenerator.class)

@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "gender")

public class Gender {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(nullable = false)
    private String gender;

    @JsonManagedReference
    @OneToMany(fetch=FetchType.LAZY, mappedBy="gender")
    private Set<User> users;

}
</code>```

im researching into it but for some reason even when terminated and restarted the program goes to the gender controller.on the one with no extra path the base get.

```<code>@CrossOrigin(origins = {"http://localhost:3000"})
@RestController
@RequestMapping("/gender")
public class GenderController {
    @Autowired
    GenderRepository genderRepository;
    @Autowired
    AccountValidator accountValidator;
    @GetMapping
    public ArrayList<Gender> getGenders(){
        try{
            return new ArrayList<>(genderRepository.findAll());
        }
        catch(NullPointerException e){
            return new ArrayList<Gender>();
        }
    }
    @GetMapping("/{id}")
    public Gender getGender(@PathVariable Long id) {
        try{
            return genderRepository.findById(id).get();
        }
        catch(NullPointerException e){
            return new Gender();
        }
    }
    @PostMapping("/update")
    public String postGender(@RequestBody Gender gender, Errors errors) throws URISyntaxException {
        accountValidator.genderExistPass(gender.getId(),errors);
        String message="";
        try{
            message=errors.getFieldError("genderError").getDefaultMessage();
        }
        catch(NullPointerException e){

        }
        if(!errors.hasErrors()){
            genderRepository.save(gender);
        }
        return message;
    }
    @DeleteMapping("/{id}")
    public ResponseEntity deleteGender(@PathVariable Long id) {
        genderRepository.deleteById(id);
        return ResponseEntity.ok().build();
    }
}
</code>```

Body:
I am trying to mix two objects together via one to many relationship.just by running the application i get an infinite loop between the processor trying to get the user then gender then user and so on.I have tried looking around but no other page has solutions that applied to my issue or upon trying to fix it worked.

error

    Hibernate: select gender0_.id as id1_18_, gender0_.gender as gender2_18_ from gender gender0_
2022-12-08 22:23:48.371 TRACE 11832 --- [nio-8080-exec-3] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([id1_18_] : [BIGINT]) - [1]
2022-12-08 22:23:48.371 TRACE 11832 --- [nio-8080-exec-3] o.h.type.descriptor.sql.BasicExtractor   : extracted value ([gender2_18_] : [VARCHAR]) - [male]
2022-12-08 22:23:48.371 TRACE 11832 --- [nio-8080-exec-3] org.hibernate.type.CollectionType        : Created collection wrapper: [com.example.realtyKing.Account.GeneralUser.Model.Gender.users#1]
2022-12-08 22:23:48.372 DEBUG 11832 --- [nio-8080-exec-3] org.hibernate.SQL                        : select users0_.gender_id as gender_11_27_0_, users0_.id as id1_27_0_, users0_.id as id1_27_1_, users0_.dob as dob2_27_1_, users0_.email as email3_27_1_, users0_.email_config as email_co4_27_1_, users0_.first_name as first_na5_27_1_, users0_.gender_id as gender_11_27_1_, users0_.is_active as is_activ6_27_1_, users0_.last_name as last_nam7_27_1_, users0_.middle_name as middle_n8_27_1_, users0_.password as password9_27_1_, users0_.phone_number as phone_n10_27_1_, employee1_.id as id1_10_2_, employee1_.address as address2_10_2_, employee1_.company_id as company_5_10_2_, employee1_.date_of_termination as date_of_3_10_2_, employee1_.department_id as departme6_10_2_, employee1_.status as status4_10_2_, employee1_.user_id as user_id7_10_2_, employeege2_.id as id1_15_3_, employeege2_.area_id as area_id2_15_3_, employeege2_.city_id as city_id3_15_3_, employeege2_.employee_id as employee4_15_3_, employment3_.id as id1_16_4_, employment3_.brokage_share as brokage_2_16_4_, employment3_.employee_id as employee6_16_4_, employment3_.employee_end_date as employee3_16_4_, employment3_.employee_start_date as employee4_16_4_, employment3_.hourly_pay as hourly_p5_16_4_ from user users0_ left outer join employee employee1_ on users0_.id=employee1_.user_id left outer join employee_geographic_data employeege2_ on employee1_.id=employeege2_.employee_id left outer join employment_term employment3_ on employee1_.id=employment3_.employee_id where users0_.gender_id=?
Hibernate: select users0_.gender_id as gender_11_27_0_, users0_.id as id1_27_0_, users0_.id as id1_27_1_, users0_.dob as dob2_27_1_, users0_.email as email3_27_1_, users0_.email_config as email_co4_27_1_, users0_.first_name as first_na5_27_1_, users0_.gender_id as gender_11_27_1_, users0_.is_active as is_activ6_27_1_, users0_.last_name as last_nam7_27_1_, users0_.middle_name as middle_n8_27_1_, users0_.password as password9_27_1_, users0_.phone_number as phone_n10_27_1_, employee1_.id as id1_10_2_, employee1_.address as address2_10_2_, employee1_.company_id as company_5_10_2_, employee1_.date_of_termination as date_of_3_10_2_, employee1_.department_id as departme6_10_2_, employee1_.status as status4_10_2_, employee1_.user_id as user_id7_10_2_, employeege2_.id as id1_15_3_, employeege2_.area_id as area_id2_15_3_, employeege2_.city_id as city_id3_15_3_, employeege2_.employee_id as employee4_15_3_, employment3_.id as id1_16_4_, employment3_.brokage_share as brokage_2_16_4_, employment3_.employee_id as employee6_16_4_, employment3_.employee_end_date as employee3_16_4_, employment3_.employee_start_date as employee4_16_4_, employment3_.hourly_pay as hourly_p5_16_4_ from user users0_ left outer join employee employee1_ on users0_.id=employee1_.user_id left outer join employee_geographic_data employeege2_ on employee1_.id=employeege2_.employee_id left outer join employment_term employment3_ on employee1_.id=employment3_.employee_id where users0_.gender_id=?
2022-12-08 22:23:48.372 TRACE 11832 --- [nio-8080-exec-3] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [BIGINT] - [1]
2022-12-08 22:23:48.377 DEBUG 11832 --- [nio-8080-exec-8] org.hibernate.SQL                        : select gender0_.id as id1_18_, gender0_.gender as gender2_18_ from gender gender0_

my objects

package com.example.realtyKing.Account.GeneralUser.Model;
import com.example.realtyKing.Account.Employee.Model.Employee;
import com.example.realtyKing.Transaction.Model.Payroll;
import com.fasterxml.jackson.annotation.*;
import com.voodoodyne.jackson.jsog.JSOGGenerator;
import lombok.*;

import javax.persistence.*;
import java.sql.Date;
import java.util.*;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIdentityInfo(generator= JSOGGenerator.class)
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "user", uniqueConstraints = @UniqueConstraint(columnNames = "email"))
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "first_name", nullable = false)
    private String firstName;
    @Column(name = "middle_name")
    private String middleName;
    @Column(name = "last_name", nullable = false)
    private String lastName;
    @Column(nullable = false)
    private Date dob;
    @Column(name = "phone_number", nullable = false)
    private String phoneNumber;

    @Column(nullable = false)
    private String email;

    @Column(nullable = false)
    private String password;
    @Column(nullable = false)
    private Boolean isActive;

    @Column(name = "email_config")
    private String emailConfig;

    @OneToOne(mappedBy = "user")
    private Employee employee;

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(
            name = "user_role",
            joinColumns = @JoinColumn(
                    name = "user_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(
                    name = "role_id", referencedColumnName = "id"))

    private Collection < Role > roles;

    @JsonBackReference
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "gender_id")
    private Gender gender;

    @OneToMany(fetch=FetchType.LAZY, mappedBy="user")
    private Set<Payroll> payrolls;

    public User(String firstName, String lastName, Date dob, String phoneNumber, String email,
                String password, Collection < Role > roles, Gender gender)
    {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        this.dob = dob;
        this.phoneNumber=phoneNumber;
        this.email = email;
        this.password = password;
        this.roles = roles;
        this.gender=gender;
    }

}
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIdentityInfo(generator= JSOGGenerator.class)

@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "gender")

public class Gender {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(nullable = false)
    private String gender;

    @JsonManagedReference
    @OneToMany(fetch=FetchType.LAZY, mappedBy="gender")
    private Set<User> users;

}

im researching into it but for some reason even when terminated and restarted the program goes to the gender controller.on the one with no extra path the base get.

@CrossOrigin(origins = {"http://localhost:3000"})
@RestController
@RequestMapping("/gender")
public class GenderController {
    @Autowired
    GenderRepository genderRepository;
    @Autowired
    AccountValidator accountValidator;
    @GetMapping
    public ArrayList<Gender> getGenders(){
        try{
            return new ArrayList<>(genderRepository.findAll());
        }
        catch(NullPointerException e){
            return new ArrayList<Gender>();
        }
    }
    @GetMapping("/{id}")
    public Gender getGender(@PathVariable Long id) {
        try{
            return genderRepository.findById(id).get();
        }
        catch(NullPointerException e){
            return new Gender();
        }
    }
    @PostMapping("/update")
    public String postGender(@RequestBody Gender gender, Errors errors) throws URISyntaxException {
        accountValidator.genderExistPass(gender.getId(),errors);
        String message="";
        try{
            message=errors.getFieldError("genderError").getDefaultMessage();
        }
        catch(NullPointerException e){

        }
        if(!errors.hasErrors()){
            genderRepository.save(gender);
        }
        return message;
    }
    @DeleteMapping("/{id}")
    public ResponseEntity deleteGender(@PathVariable Long id) {
        genderRepository.deleteById(id);
        return ResponseEntity.ok().build();
    }
}


问:
Troubleshooting a Python Code Error: 'Wrong device id!'" - Shelly Cloud API
 I consistently receive the following error: {'isok': False, 'errors': {'wrong_device_id': 'Wrong device id!'}}. I have tried using both HEX and decimal numbers for the "device id" as specified in the app, but the error persists. Additionally, I have attempted to use curl -X POST, but I am unable to even get past the authorization phase there.

# Import the requests module
import requests

# Set the URL for the request
url = "https://********.shelly.cloud/device/relay/control"

# Set the headers for the request
headers = {
    "Authorization": "Bearer ******",
    "Content-Type": "application/json"
}

# Set the data for the request
data = {
    "channel": "0", # The channel to turn off
    "turn": "off", # The desired state (off)
    "id": "*******" # The ID of the device (Tried both, HEX and DEC versions of device ID)
}

# Send the POST request and store the response
response = requests.post(url, headers=headers, json=data)

# Print the response JSON
print(response.json())
```

Tried the same from Shelly API Cloud Documentation with curl.

Body:
 I consistently receive the following error: {'isok': False, 'errors': {'wrong_device_id': 'Wrong device id!'}}. I have tried using both HEX and decimal numbers for the "device id" as specified in the app, but the error persists. Additionally, I have attempted to use curl -X POST, but I am unable to even get past the authorization phase there.

# Import the requests module
import requests

# Set the URL for the request
url = "https://********.shelly.cloud/device/relay/control"

# Set the headers for the request
headers = {
    "Authorization": "Bearer ******",
    "Content-Type": "application/json"
}

# Set the data for the request
data = {
    "channel": "0", # The channel to turn off
    "turn": "off", # The desired state (off)
    "id": "*******" # The ID of the device (Tried both, HEX and DEC versions of device ID)
}

# Send the POST request and store the response
response = requests.post(url, headers=headers, json=data)

# Print the response JSON
print(response.json())

Tried the same from Shelly API Cloud Documentation with curl.


问:
NpgsqlConnection Connection Cannot Be Established
I have a PostgreSQL database in a client PC. I have a system which all the folders are stored in the server. I want to make a connection between my system to the database. These are the parameters.

```<code>
Ip Adress for the server: 192.118.0.xxx
Ip Adress for the client: 192.118.0.yyy
Port used for the database: 5500
User Id for the database: admin
Password for the database: admin123
Database name: dbadmin
</code>```

Here is what I've tried so far. But all of them are not working.

NpgsqlConnection conn = new NpgsqlConnection("Server=192.118.0.xxx,5500;User Id=admin;Password=admin123;Database=dbadmin;")

Error:  Unable to connect to a suitable host

NpgsqlConnection conn = new NpgsqlConnection("Server=192.118.0.xxx,Port:5500;User Id=admin;Password=admin123;Database=dbadmin;")

Error: No connection could be made because the target machine actively refused it.

NpgsqlConnection conn = new NpgsqlConnection("Server=192.118.0.yyy,5500;User Id=admin;Password=admin123;Database=dbadmin;")

Error: Unable to connect to a suitable host

NpgsqlConnection conn = new NpgsqlConnection("Server=192.118.0.yyy;Port=5500;User Id=admin;Password=admin123;Database=dbadmin;Timeout=15;")

Error: Timeout during connection attempt

Body:
I have a PostgreSQL database in a client PC. I have a system which all the folders are stored in the server. I want to make a connection between my system to the database. These are the parameters.

Ip Adress for the server: 192.118.0.xxx
Ip Adress for the client: 192.118.0.yyy
Port used for the database: 5500
User Id for the database: admin
Password for the database: admin123
Database name: dbadmin

Here is what I've tried so far. But all of them are not working.

NpgsqlConnection conn = new NpgsqlConnection("Server=192.118.0.xxx,5500;User Id=admin;Password=admin123;Database=dbadmin;")

Error:  Unable to connect to a suitable host

NpgsqlConnection conn = new NpgsqlConnection("Server=192.118.0.xxx,Port:5500;User Id=admin;Password=admin123;Database=dbadmin;")

Error: No connection could be made because the target machine actively refused it.

NpgsqlConnection conn = new NpgsqlConnection("Server=192.118.0.yyy,5500;User Id=admin;Password=admin123;Database=dbadmin;")

Error: Unable to connect to a suitable host

NpgsqlConnection conn = new NpgsqlConnection("Server=192.118.0.yyy;Port=5500;User Id=admin;Password=admin123;Database=dbadmin;Timeout=15;")

Error: Timeout during connection attempt


问:
How to use custom font for all controls and respecting their own sizes?
I manage to embed my own fonts in a WinForms app. However the solution provided there requires me to:

manually apply to individual control, e.g.

```<code>  private void Form1_Load(object sender, EventArgs e)
  {
      userControl1.Font = myFont;
      button1.Font = myFont;
  }
</code>```

all of them will have the same size

Is there a way to do this better? Something similar to CSS. I try Form1.Font = myFont; but it throws me Error CS0120:

An object reference is required for the non-static field, method, or property 'Control.Font'

I put it in the constructor of Form1 as well, and it builds successfully, but it doesn't change anything on the display.

Is there a way to fix this?

Body:
I manage to embed my own fonts in a WinForms app. However the solution provided there requires me to:

manually apply to individual control, e.g.

  private void Form1_Load(object sender, EventArgs e)
  {
      userControl1.Font = myFont;
      button1.Font = myFont;
  }

all of them will have the same size

Is there a way to do this better? Something similar to CSS. I try Form1.Font = myFont; but it throws me Error CS0120:

An object reference is required for the non-static field, method, or property 'Control.Font'

I put it in the constructor of Form1 as well, and it builds successfully, but it doesn't change anything on the display.

Is there a way to fix this?


问:
Change payment card icons and disable certain payment methods (WooCommerce Payments)
Issue 1: I would like to hide the American Express and Union Pay icons in my checkout page.

https://i.imgur.com/TZ5jJXF.png

What I tried: I have modified what is shown here (Change payment card icons for WooCommerce Stripe in checkout). However, my code does not seem to work (it messes up my entire checkout page).

```<code>add_filter( 'woocommerce_gateway_icon', 'sort_stripe_payment_icons', 10, 2 );
function sort_stripe_payment_icons( $icons_str, $payment_id ) {
    if ( $payment_id === 'woocommerce_payments' && is_checkout() ) {
        $available_gateways = WC()->payment_gateways->get_available_payment_gateways();
        $woocommerce_payments = $available_gateways['woocommerce_payments'];

        $icons = $woocommerce_payments->payment_icons();

        $icons_str = '';

        if ( 'USD' === get_woocommerce_currency() ) {
         //   $icons_str .= isset( $icons['discover'] ) ? $icons['discover'] : '';
            // $icons_str .= isset( $icons['jcb'] ) ? $icons['jcb'] : '';
            // $icons_str .= isset( $icons['diners'] ) ? $icons['diners'] : '';
           //$icons_str .= isset( $icons['amex'] ) ? $icons['amex'] : '';
       //$icons_str .= isset( $icons['UnionPay'] ) ? $icons['UnionPay'] : '';
        }

        $icons_str .= isset( $icons['mastercard'] ) ? $icons['mastercard'] : '';
        $icons_str .= isset( $icons['visa'] ) ? $icons['visa'] : '';

    }
    return $icons_str;
}
</code>```

Issue 2: I would like to know if there is a way to disable American Express and Union Pay payments in WooCommerce Payments.

What I tried: I have have searched extensively and seems like the only way is to use Stripe Radar to block Amex and UnionPay. However, is there a way to block it through code?

Thanks

Body:
Issue 1: I would like to hide the American Express and Union Pay icons in my checkout page.

https://i.imgur.com/TZ5jJXF.png

What I tried: I have modified what is shown here (Change payment card icons for WooCommerce Stripe in checkout). However, my code does not seem to work (it messes up my entire checkout page).

add_filter( 'woocommerce_gateway_icon', 'sort_stripe_payment_icons', 10, 2 );
function sort_stripe_payment_icons( $icons_str, $payment_id ) {
    if ( $payment_id === 'woocommerce_payments' && is_checkout() ) {
        $available_gateways = WC()->payment_gateways->get_available_payment_gateways();
        $woocommerce_payments = $available_gateways['woocommerce_payments'];

        $icons = $woocommerce_payments->payment_icons();

        $icons_str = '';

        if ( 'USD' === get_woocommerce_currency() ) {
         //   $icons_str .= isset( $icons['discover'] ) ? $icons['discover'] : '';
            // $icons_str .= isset( $icons['jcb'] ) ? $icons['jcb'] : '';
            // $icons_str .= isset( $icons['diners'] ) ? $icons['diners'] : '';
           //$icons_str .= isset( $icons['amex'] ) ? $icons['amex'] : '';
       //$icons_str .= isset( $icons['UnionPay'] ) ? $icons['UnionPay'] : '';
        }

        $icons_str .= isset( $icons['mastercard'] ) ? $icons['mastercard'] : '';
        $icons_str .= isset( $icons['visa'] ) ? $icons['visa'] : '';

    }
    return $icons_str;
}

Issue 2: I would like to know if there is a way to disable American Express and Union Pay payments in WooCommerce Payments.

What I tried: I have have searched extensively and seems like the only way is to use Stripe Radar to block Amex and UnionPay. However, is there a way to block it through code?

Thanks


问:
vscode show the wrong type inference error when using typescript, how to fix that?
In my .ts file, I have some code like that:

```<code>
    **// at first, the store only can be *GlobalStore* type or *null* type.**
    **// now the vscode reference is right.**

    let store = inject(GLOBAL_PROVIDER_KEY, null)

    if (!store) {

        **// then, the store only can be *null* type.**
        **// now the vscode reference is also right.**

        console.log(store);

        **// the `createDefaultStore` function return the `GlobalStore` type**
        **and equal to the store. But vscode inference is GlobalStore | null type!**
        **this is wrong.**

        store = createDefaultStore();

    }
</code>```

It seems like the problem about language-server.

I don't know how to fix the vscode typescript reference or where to find the answer. It is a bug or the config is wrong? Now it report error with red wavy line.

Can I only use store = createDefaultStore() as GlobalStore to solve it?

Body:
In my .ts file, I have some code like that:

    **// at first, the store only can be *GlobalStore* type or *null* type.**
    **// now the vscode reference is right.**

    let store = inject(GLOBAL_PROVIDER_KEY, null)

    if (!store) {

        **// then, the store only can be *null* type.**
        **// now the vscode reference is also right.**

        console.log(store);

        **// the `createDefaultStore` function return the `GlobalStore` type**
        **and equal to the store. But vscode inference is GlobalStore | null type!**
        **this is wrong.**

        store = createDefaultStore();

    }

It seems like the problem about language-server.

I don't know how to fix the vscode typescript reference or where to find the answer. It is a bug or the config is wrong? Now it report error with red wavy line.

Can I only use store = createDefaultStore() as GlobalStore to solve it?


问:
Difference in pytorch BERT model output vs neuron
I converted a pytorch BERT model to neuron. However the embedding or output tensors which is a list of 1024 size is different..i.e the list sizes are same but individual entries differ. Each of the numbers differs around 1-5% with the original pytorch model output. This is the code that I use to neuron compile the pytorch model.</p>
```<code>from transformers import BertTokenizer, BertModel
import torch
import torch_neuron
import os.path
import os
import numpy

tokenizer = BertTokenizer.from_pretrained(modelname, model_max_length=512)
input_str = "The patient's ability is determined based on patients medical parameters, patients history of ability to attend a remote clinician sessions, and physical parameters. Based on identified parameters a patients profile score is calculated to determine patients ability to attend the remote clinician session."
inputs = tokenizer(input_str, padding='max_length', return_tensors="pt")
PATH = './ptmodel/'
fname = 'modelneuron.pt'
kwargs = {'compiler_args':['--fast-math', 'none','--neuroncore-pipeline-cores', '1']}
model = BertModel.from_pretrained(PATH, local_files_only=True, return_dict=False)
neuron_model = torch_neuron.trace(model,
                                    example_inputs = (inputs['input_ids'],inputs['attention_mask'],inputs['token_type_ids']), **kwargs)
neuron_model.save(fname)
</code>```

Body:
I converted a pytorch BERT model to neuron. However the embedding or output tensors which is a list of 1024 size is different..i.e the list sizes are same but individual entries differ. Each of the numbers differs around 1-5% with the original pytorch model output. This is the code that I use to neuron compile the pytorch model.

from transformers import BertTokenizer, BertModel
import torch
import torch_neuron
import os.path
import os
import numpy

tokenizer = BertTokenizer.from_pretrained(modelname, model_max_length=512)
input_str = "The patient's ability is determined based on patients medical parameters, patients history of ability to attend a remote clinician sessions, and physical parameters. Based on identified parameters a patients profile score is calculated to determine patients ability to attend the remote clinician session."
inputs = tokenizer(input_str, padding='max_length', return_tensors="pt")
PATH = './ptmodel/'
fname = 'modelneuron.pt'
kwargs = {'compiler_args':['--fast-math', 'none','--neuroncore-pipeline-cores', '1']}
model = BertModel.from_pretrained(PATH, local_files_only=True, return_dict=False)
neuron_model = torch_neuron.trace(model,
                                    example_inputs = (inputs['input_ids'],inputs['attention_mask'],inputs['token_type_ids']), **kwargs)
neuron_model.save(fname)


问:
pdf button is not showing in datatable in angular 6.9
I used node version v10.16.3 and npm version is 6.9.0. excel, csv button is showing but pdf buttons are not showing

```<code> "styles": [
          "node_modules/bootstrap/dist/css/bootstrap.min.css",
          "src/assets/css/jquery.datetimepicker.css",
          "node_modules/datatables.net-dt/css/jquery.dataTables.css",
          "node modules/datatables.net-buttons-dt/css/buttons.dataTables.css",
          "src/assets/css/style.css"
          ],
"scripts": [
          "node_modules/jquery/dist/jquery.js",
          "node_modules/bootstrap/dist/js/bootstrap.bundle.min.js",
          "src/assets/js/jquery.validate.min.js",
          "src/assets/js/jquery.datetimepicker.full.min.js",
          "node_modules/datatables.net/js/jquery.dataTables.js",
          "node_modules/jszip/dist/jszip.js",
          "node_modules/datatables.net-buttons/js/dataTables.buttons.js",
          "node_modules/datatables.net-buttons/js/buttons.flash.js",
          "node_modules/datatables.net-buttons/js/buttons.html5.js",
          "node_modules/datatables.net-buttons/js/buttons.print.js",
          "node_modules/datatables.net-buttons/js/buttons.colVis.js",
          "src/assets/js/script.js"
          ]
</code>```

Body:
I used node version v10.16.3 and npm version is 6.9.0. excel, csv button is showing but pdf buttons are not showing

 "styles": [
          "node_modules/bootstrap/dist/css/bootstrap.min.css",
          "src/assets/css/jquery.datetimepicker.css",
          "node_modules/datatables.net-dt/css/jquery.dataTables.css",
          "node modules/datatables.net-buttons-dt/css/buttons.dataTables.css",
          "src/assets/css/style.css"
          ],
"scripts": [
          "node_modules/jquery/dist/jquery.js",
          "node_modules/bootstrap/dist/js/bootstrap.bundle.min.js",
          "src/assets/js/jquery.validate.min.js",
          "src/assets/js/jquery.datetimepicker.full.min.js",
          "node_modules/datatables.net/js/jquery.dataTables.js",
          "node_modules/jszip/dist/jszip.js",
          "node_modules/datatables.net-buttons/js/dataTables.buttons.js",
          "node_modules/datatables.net-buttons/js/buttons.flash.js",
          "node_modules/datatables.net-buttons/js/buttons.html5.js",
          "node_modules/datatables.net-buttons/js/buttons.print.js",
          "node_modules/datatables.net-buttons/js/buttons.colVis.js",
          "src/assets/js/script.js"
          ]


问:
In Linux, how to do quick remove of USB device, like Windows, without file system impact or corruption?
In Linux, how to do quick remove of USB device, like Windows, without file system impact or corruption?

I know the following:

Lazy unmount will remove the mount reference, on USB device quick remove in Linux, but that does not protect file system, ext4, NTFS, vFat, whatever the USB device file system is, still may have pending writes cached.

Mount with dirsync, sync, flush, none of these seem to work interface to no. 1 above.  Have actually tested this, and you get warnings about running fsck, or chkdsk.

Turning off write cache of device, would seem to make sense to avoid no. 1 and no. 2 above, right?  Is that likely?

Is there a consistent method to disable the write cache before mount is done?  Prefer that this be done via a UDEV add rule, i.e. call script, whatever.

Windows feature as noted above...  Really does imply it is just a write cache/sync removal configuration.


问:
Is there any service I can use for electron app analytics?
Google analytics has deprecated universal analytics feature which is used in electron-google-analytics package. Is there any good way to analyze users in electron app?

What I want to know throuth analytics is user's behavior and which contents is popular in our app.

I've tried to integrate GA with electron but it doesn't work well.


问:
how to prevent my website links to open my android app deeplink
I want to prevent my website links(a tag) to open my android deeplink.

I found the amazon website it wouldn't open the app when I click the link inside, it is always in the browser, but if I add the amazon URL link to my website and click it, it will be opened from the amazon app.

how can I do the same~?


问:
Older datas getting written in Electron app
how are you doing? It is my first experience with Electron.js. I am creating a warehouse app. So it has basic CRUD for products. I am using electron-store as a DB. Whenever I try to edit one product, it changes perfectly, but if I try another product after that, the first product will change as well as the second. So let's say we have three products.

Electron version - 22.0.0

OS - Mac OS

```<code>[
{
 id: "se3",
 name: "Test",
},
{
 id: "j32",
 name: "Yummy",
},
{
 id: "le4",
 name: "Pump",
}
]
</code>```

Let's say I executed changeProduct("j32", {name: "New Yummy"}) function which changes second product, after that if I run changeProduct("le4", {name: "New Pump"}) this will change the j32 product as well. Here is the code

```<code>// This code is from renderer.js
const editProduct = (id) => {
   const editpopup = document.querySelector("#edit");
   editpopup.setAttribute("style", "display: flex;");
   editpopup.querySelector("#close-btn").addEventListener("click", () => {
      editpopup.setAttribute("style", "display: none;");
   });
   editpopup.querySelector("#editProduct").addEventListener("click", () => {
      const name = document.querySelector("#namePopup").value;
      const price = Number(document.querySelector("#pricePopup").value);
      const quantity = Number(document.querySelector("#quantityPopup").value);
      window.api.send("editProduct", { id, name, price, quantity });
      window.api.receive("updateProducts", () => {
         editpopup.setAttribute("style", "display: none;");

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

One thing to note, If I force refresh it is getting fixed, but since I am handling routes with element.setAttributes("style", "display: block;");, it causes returning to the homepage, so the user needs to go to products page again. I don't want this.

```<code>// This is index.js
ipcMain.on("editProduct", function (event, arg) {
   console.log(arg);
   /*
   it returns the updated product body. after the second execution,
   it returns two objects, and after the third three objects etc.
   It must return only one object in every run,
   but it is returning previously updated product objects as well
   */
   let products = store.get("products");
   products = products.map((product) => {
      if (product.id === arg.id) {
         return { ...arg };
      } else {
         return { ...product };
      }
   });
   store.set("products", products);
   mainWindow.webContents.send("updateProducts", store.get("products"));
});

</code>```

I NEED QUICK FIX GUYS, I HAVE VERY LESS TIME.

Body:
how are you doing? It is my first experience with Electron.js. I am creating a warehouse app. So it has basic CRUD for products. I am using electron-store as a DB. Whenever I try to edit one product, it changes perfectly, but if I try another product after that, the first product will change as well as the second. So let's say we have three products.

Electron version - 22.0.0

OS - Mac OS

[
{
 id: "se3",
 name: "Test",
},
{
 id: "j32",
 name: "Yummy",
},
{
 id: "le4",
 name: "Pump",
}
]

Let's say I executed changeProduct("j32", {name: "New Yummy"}) function which changes second product, after that if I run changeProduct("le4", {name: "New Pump"}) this will change the j32 product as well. Here is the code

// This code is from renderer.js
const editProduct = (id) => {
   const editpopup = document.querySelector("#edit");
   editpopup.setAttribute("style", "display: flex;");
   editpopup.querySelector("#close-btn").addEventListener("click", () => {
      editpopup.setAttribute("style", "display: none;");
   });
   editpopup.querySelector("#editProduct").addEventListener("click", () => {
      const name = document.querySelector("#namePopup").value;
      const price = Number(document.querySelector("#pricePopup").value);
      const quantity = Number(document.querySelector("#quantityPopup").value);
      window.api.send("editProduct", { id, name, price, quantity });
      window.api.receive("updateProducts", () => {
         editpopup.setAttribute("style", "display: none;");

      });
   });
};

One thing to note, If I force refresh it is getting fixed, but since I am handling routes with element.setAttributes("style", "display: block;");, it causes returning to the homepage, so the user needs to go to products page again. I don't want this.

// This is index.js
ipcMain.on("editProduct", function (event, arg) {
   console.log(arg);
   /*
   it returns the updated product body. after the second execution,
   it returns two objects, and after the third three objects etc.
   It must return only one object in every run,
   but it is returning previously updated product objects as well
   */
   let products = store.get("products");
   products = products.map((product) => {
      if (product.id === arg.id) {
         return { ...arg };
      } else {
         return { ...product };
      }
   });
   store.set("products", products);
   mainWindow.webContents.send("updateProducts", store.get("products"));
});

I NEED QUICK FIX GUYS, I HAVE VERY LESS TIME.


问:
Set a postgres user for Heroku CI pipeline
so I have Row Level Security installed on my app. For it to work it requires a non-super user to be connected to the database.

In my heroku CI pipline my tests are failling because its connected to the database with a super user.

In the Heroku CI pipeline, Is there a way to connect to the database using a non-super user?

Locally I create the non super user in the postgres console, then add certain privileges, then in my database.yml I go:

```<code>test:
  username: non_super_user
</code>```

So when my tests run it connects to the database using non_super_user user.

I read the Heroku docs and the closest thing I found is this, Heroku CI In-Dyno Databases where I can run some bash commands. But I dont think it will work because even if I create the non super user in postgres called non-super-user, how does heroku know to use that non-super-user each time it connects to the DB while running tests.

```<code>  "environments": {
    "test": {
      "addons": ["heroku-postgresql:in-dyno"],
      "scripts": {
        "test-setup": "./bin/ci/setup", <----- RUN BASH COMMANDS IN setup FILE
      },
</code>```

Body:
so I have Row Level Security installed on my app. For it to work it requires a non-super user to be connected to the database.

In my heroku CI pipline my tests are failling because its connected to the database with a super user.

In the Heroku CI pipeline, Is there a way to connect to the database using a non-super user?

Locally I create the non super user in the postgres console, then add certain privileges, then in my database.yml I go:

test:
  username: non_super_user

So when my tests run it connects to the database using non_super_user user.

I read the Heroku docs and the closest thing I found is this, Heroku CI In-Dyno Databases where I can run some bash commands. But I dont think it will work because even if I create the non super user in postgres called non-super-user, how does heroku know to use that non-super-user each time it connects to the DB while running tests.

  "environments": {
    "test": {
      "addons": ["heroku-postgresql:in-dyno"],
      "scripts": {
        "test-setup": "./bin/ci/setup", <----- RUN BASH COMMANDS IN setup FILE
      },


问:
Oracle 11 connection issues with redhat 8.4
I was able to establish a connection to oracle 11 (which is a dockerised version) from redhat 8.4 with the below connection url - jdbc:oracle:thin:@//localhost:1521/xe

whereas i am not able to connect with the machine ip instead of localhost ?

jdbc:oracle:thin:@//10.xx.xx.xx:1521/xe

Any help is highly appreciated

(The intention of changing from the localhost to machine ip is ,I was faced with "SQL command failed because :IO Error: Got minus one from a read call ", by changing to machine IP solved the issues in ubunutu)


问:
Way to make count from frequency table a variable that can be used in scatterplot?
I am trying to make a scatterplot of a number of publications per month. I created a frequency table to get the count of pub per month and when I try to make a scatterplot it does not acknowledge count as a variable. Is there a way to transform count into a variable or what should I do? I can make a scatterplot by typing out the variable into arrays, this is attached via photo.

Thanks!


问:
Unity enemy alert, Move object outside of the screen to screen boundary, Axis collision
image sample

I'm making a game with enemy alert feature. My problem is how to know the collision point to axis or screen boundary which will be the position I have to put the enemy indicator.
Note: Using only Vector2 or manual mathematical formula WITHOUT using any unity engine.

I tried making the Y to 0 but X is not accurate.

Thank you so much.


问:
how to keep playing audio with discord.py bot
Hey im making music bot everything is working fine when i enter !join in discord chat the bot join voice channel and start playing local .wav file
the thing is i want it to keep playing next audio file randomly without stop
im trying while loop but not working.</p>
```<code>@client.command(pass_context=True)
async def join(ctx):
    if (ctx.author.voice):
        channel = ctx.message.author.voice.channel
        voice = await channel.connect()
        while True:
            mymusic = random.choice(['voice.wav', 'voice1.wav', 'voice2.wav', 'voice3.wav'])
            source = FFmpegPCMAudio(mymusic)
            player = voice.play(source)

    else:
        await ctx.send("You are not in a voice channel")

</code>```

Body:
Hey im making music bot everything is working fine when i enter !join in discord chat the bot join voice channel and start playing local .wav file
the thing is i want it to keep playing next audio file randomly without stop
im trying while loop but not working.

@client.command(pass_context=True)
async def join(ctx):
    if (ctx.author.voice):
        channel = ctx.message.author.voice.channel
        voice = await channel.connect()
        while True:
            mymusic = random.choice(['voice.wav', 'voice1.wav', 'voice2.wav', 'voice3.wav'])
            source = FFmpegPCMAudio(mymusic)
            player = voice.play(source)

    else:
        await ctx.send("You are not in a voice channel")


问:
Spring Data JPA composite primary key using MySQL auto_increment id
Using MySQL, Spring Data JPA composite primary key, column id is a database auto_increment field, column part is database partition base. However, in entity, if I have id annotated as @GeneratedValue(strategy = GenerationType.IDENTITY), when repository.save is called, it throws error as: Can not set java.lang.Long field PK.id to org.hibernate.id.IdentifierGeneratorHelper. Then id has to be annotated as @GeneratedValue(strategy = GenerationType.AUTO), but AUTO + MySQL results in a hibernate_sequence table is needed for geneartion value for id.
So my question is, how to use mysql auto_increment and composite primary key at the same time? Or JPA composite PK has to come with a hibernate_sequence table for id value?

```<code>@Entity
@Getter
@Setter
@ToString
@IdClass(SearchVecPK.class)
@Table(name = "search_vec")
public class SearchVecEntity {

    @Id
    @GeneratedValue // GenerationType.AUTO
    private Long id;

    @Id
    private int part;

    private String appId;
</code>```
```<code>public class SearchVecPK implements Serializable {
    private Long id;
    private int part;
}
</code>```

table:

```<code>CREATE TABLE `search_vec` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `app_id` varchar(255) DEFAULT NULL,
  `part` int(11) NOT NULL,
  PRIMARY KEY (`id`,`part`) USING BTREE,
  UNIQUE KEY `UKqssgibuhvjumx98hexjpw0o3c` (`part`,`user_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=76 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC
/*!50100 PARTITION BY RANGE ( part)
(PARTITION p1 VALUES LESS THAN (1) ENGINE = InnoDB,
 PARTITION p2 VALUES LESS THAN (2) ENGINE = InnoDB)
</code>```
```<code>       SearchVecEntity searchVecEntity = new SearchVecEntity();
       searchVecEntity.setPart(keyPart.getPart());
       searchVecEntity.setGroupId(key); // todo. where should this groupId set? not here.
       SearchVecEntity save = repository.save(searchVecEntity);
</code>```

Body:
Using MySQL, Spring Data JPA composite primary key, column id is a database auto_increment field, column part is database partition base. However, in entity, if I have id annotated as @GeneratedValue(strategy = GenerationType.IDENTITY), when repository.save is called, it throws error as: Can not set java.lang.Long field PK.id to org.hibernate.id.IdentifierGeneratorHelper. Then id has to be annotated as @GeneratedValue(strategy = GenerationType.AUTO), but AUTO + MySQL results in a hibernate_sequence table is needed for geneartion value for id.
So my question is, how to use mysql auto_increment and composite primary key at the same time? Or JPA composite PK has to come with a hibernate_sequence table for id value?

@Entity
@Getter
@Setter
@ToString
@IdClass(SearchVecPK.class)
@Table(name = "search_vec")
public class SearchVecEntity {

    @Id
    @GeneratedValue // GenerationType.AUTO
    private Long id;

    @Id
    private int part;

    private String appId;

public class SearchVecPK implements Serializable {
    private Long id;
    private int part;
}

table:

CREATE TABLE `search_vec` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `app_id` varchar(255) DEFAULT NULL,
  `part` int(11) NOT NULL,
  PRIMARY KEY (`id`,`part`) USING BTREE,
  UNIQUE KEY `UKqssgibuhvjumx98hexjpw0o3c` (`part`,`user_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=76 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC
/*!50100 PARTITION BY RANGE ( part)
(PARTITION p1 VALUES LESS THAN (1) ENGINE = InnoDB,
 PARTITION p2 VALUES LESS THAN (2) ENGINE = InnoDB)

       SearchVecEntity searchVecEntity = new SearchVecEntity();
       searchVecEntity.setPart(keyPart.getPart());
       searchVecEntity.setGroupId(key); // todo. where should this groupId set? not here.
       SearchVecEntity save = repository.save(searchVecEntity);


问:
Hierarchical caching with expiry
Requirements:

We have a list of users.

For every user let us say, there are 2 types of rewards applicable.

For each type there is a list of the rewards that need to be given out to the specific user.

Every reward has a specific expiry, after which that reward, if not delivered, has to be dropped from the list of rewards.

Whenever we get a request, we have to reserve a reward for the user. Users can then claim the rewards later. While claiming, we just search for a reward from the list of rewards reserved for the users and deliver it.

Approach 1
We are thinking to store the data in the following format:

```<code>user_id
    type_1
        reward_1
        reward_2
        reward_3
    type_2
        reward_4
        reward_5
        reward_6
</code>```

Here the number of keys would be limited and data representation is cleaner.

Challenges:

How to expire the reward from the list of rewards. If I am using Redis, then in that case I cannot set a TTL on the rewards as TTL only works for the key, which is user_id in this case.

Also, since we cannot expire the deals automatically, we will first have to remove all the expired rewards from the list, while delivering the reward, and then select one reward from the remaining non-expired rewards.

When we deliver a reward, we have to remove that reward from the list. So every time we deliver a reward, we have to get the list and then push back the updated list, the original list -1 (the reward that was just claimed), to Redis to update the existing data.

All these operations add to the overall latency of the delivery.

Approach 2
Another approach was making the reward a part of the key itself:

```<code>user_id:type_1:reward_1
user_id:type_1:reward_2
user_id:type_1:reward_3
user_id:type_2:reward_4
.
.
</code>```

Here I can set the TTL for each reward.

Challenges:

The number of keys would increase drastically.

While actually delivering the reward, we only know the user and the type and not the actual reward. So we basically have to scan for all the rewards present for the user and the type and then get a list of all the rewards and then deliver one of the available rewards to the user. This increases the latency. The scan complexity is O(N).

What is the best way of structuring such data? How do we work on retrieving and updating the data with minimum latency? How do work on removing the expired records?

Title: Hierarchical caching with expiry

Body:
Requirements:

We have a list of users.

For every user let us say, there are 2 types of rewards applicable.

For each type there is a list of the rewards that need to be given out to the specific user.

Every reward has a specific expiry, after which that reward, if not delivered, has to be dropped from the list of rewards.

Whenever we get a request, we have to reserve a reward for the user. Users can then claim the rewards later. While claiming, we just search for a reward from the list of rewards reserved for the users and deliver it.

Approach 1
We are thinking to store the data in the following format:

user_id
    type_1
        reward_1
        reward_2
        reward_3
    type_2
        reward_4
        reward_5
        reward_6

Here the number of keys would be limited and data representation is cleaner.

Challenges:

How to expire the reward from the list of rewards. If I am using Redis, then in that case I cannot set a TTL on the rewards as TTL only works for the key, which is user_id in this case.

Also, since we cannot expire the deals automatically, we will first have to remove all the expired rewards from the list, while delivering the reward, and then select one reward from the remaining non-expired rewards.

When we deliver a reward, we have to remove that reward from the list. So every time we deliver a reward, we have to get the list and then push back the updated list, the original list -1 (the reward that was just claimed), to Redis to update the existing data.

All these operations add to the overall latency of the delivery.

Approach 2
Another approach was making the reward a part of the key itself:

user_id:type_1:reward_1
user_id:type_1:reward_2
user_id:type_1:reward_3
user_id:type_2:reward_4
.
.

Here I can set the TTL for each reward.

Challenges:

The number of keys would increase drastically.

While actually delivering the reward, we only know the user and the type and not the actual reward. So we basically have to scan for all the rewards present for the user and the type and then get a list of all the rewards and then deliver one of the available rewards to the user. This increases the latency. The scan complexity is O(N).

What is the best way of structuring such data? How do we work on retrieving and updating the data with minimum latency? How do work on removing the expired records?


问:
suggestions are no longer automatic. What should I do to have it automatically converted again?
vscode suggestion doesn't work. Settings are not open. Suddenly, predictive conversion is no longer possible, and the TAB completion function is no longer available.

I opened the settings and fiddled with suggestions, but nothing changed.

I want the suggestion to work as default.

I want the TAB completion function to work as well.


问:
failed to solve: rpc error: code = Unknown desc = failed to solve with frontend dockerfile.v0: failed to read dockerfile
I am Implementing a containerized nextcloud application with a self signed cert using the example docker compose file provided here: https://github.com/nextcloud/docker/blob/master/.examples/docker-compose/with-nginx-proxy/mariadb/apache/docker-compose.yml (also using the provided .env, .conf and Dockerfile provided)

my file structure

```<code>docker-compose.yml
db.env
proxy/uploadsize.conf
proxy/Dockerfile
</code>```

my docker-compose.yml file

```<code>version: '3'

services:
  db:
    image: mariadb:10.5
    command: --transaction-isolation=READ-COMMITTED --binlog-format=ROW
    restart: always
    volumes:
      - db:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=<password>
      - MARIADB_AUTO_UPGRADE=1
      - MARIADB_DISABLE_UPGRADE_BACKUP=1
    env_file:
      - db.env

  redis:
    image: redis:alpine
    restart: always

  app:
    image: nextcloud:apache
    restart: always
    volumes:
      - nextcloud:/var/www/html
    environment:
      - VIRTUAL_HOST=servhostname.local
      - LETSENCRYPT_HOST=servhostname.local
      - LETSENCRYPT_EMAIL=my@example.com
      - MYSQL_HOST=db
      - REDIS_HOST=redis
    env_file:
      - db.env
    depends_on:
      - db
      - redis
    networks:
      - proxy-tier
      - default

  cron:
    image: nextcloud:apache
    restart: always
    volumes:
      - nextcloud:/var/www/html
    entrypoint: /cron.sh
    depends_on:
      - db
      - redis

  proxy:
    build: ./proxy
    restart: always
    ports:
      - 80:80
      - 443:443
    labels:
      com.github.jrcs.letsencrypt_nginx_proxy_companion.nginx_proxy: "true"
    volumes:
      - certs:/etc/nginx/certs:ro
      - vhost.d:/etc/nginx/vhost.d
      - html:/usr/share/nginx/html
      - /var/run/docker.sock:/tmp/docker.sock:ro
    networks:
      - proxy-tier

  letsencrypt-companion:
    image: nginxproxy/acme-companion
    restart: always
    volumes:
      - certs:/etc/nginx/certs
      - acme:/etc/acme.sh
      - vhost.d:/etc/nginx/vhost.d
      - html:/usr/share/nginx/html
      - /var/run/docker.sock:/var/run/docker.sock:ro
    networks:
      - proxy-tier
    depends_on:
      - proxy

# self signed
  omgwtfssl:
    image: paulczar/omgwtfssl
    restart: "no"
    volumes:
      - certs:/certs
    environment:
      - SSL_SUBJECT=servhostname.local
      - CA_SUBJECT=my@example.com
      - SSL_KEY=/certs/servhostname.local.key
      - SSL_CSR=/certs/servhostname.local.csr
      - SSL_CERT=/certs/servhostname.local.crt
    networks:
      - proxy-tier

volumes:
  db:
  nextcloud:
  certs:
  acme:
  vhost.d:
  html:

networks:
  proxy-tier:
</code>```

This works on my Windows Machine, However I want to have this running on a linux Machine. When i run the same docker-compose.yml file in linux (raspbian pi 1GB RAM && ubuntu laptop 6GB RAM) I get the error

failed to solve: rpc error: code = Unknown desc = failed to solve with frontend dockerfile.v0: failed to read dockerfile: open /var/lib/docker/tmp/buildkit-mount218034811/Dockerfile: no such file or directory

before install I did run apt-get update && upgrade

I tried to build the Docker file in the proxy folder

on Windows we get a successful build

on linux we get the following output

$ docker build . [+] Building 0.5s (2/2) FINISHED  => [internal] load
build definition from Dockerfile

0.3s  => => transferring dockerfile: 2B                                                                                0.0s  => [internal] load .dockerignore                                                                                0.4s  => => transferring context: 2B                                                                                0.0s failed to solve with frontend dockerfile.v0: failed to read dockerfile: open
/var/lib/docker/tmp/buildkit-mount789252587/Dockerfile: no such file
or directory

Update

I am able to get the docker-compose file to work by getting rid of the docker file in the proxy folder and doing a bind on the proxy folder with the /etc/nginx/conf.d folder. however if anyone knows why the configuration would not work as it please let me know.

Any help would be appreciated

Body:
I am Implementing a containerized nextcloud application with a self signed cert using the example docker compose file provided here: https://github.com/nextcloud/docker/blob/master/.examples/docker-compose/with-nginx-proxy/mariadb/apache/docker-compose.yml (also using the provided .env, .conf and Dockerfile provided)

my file structure

docker-compose.yml
db.env
proxy/uploadsize.conf
proxy/Dockerfile

my docker-compose.yml file

version: '3'

services:
  db:
    image: mariadb:10.5
    command: --transaction-isolation=READ-COMMITTED --binlog-format=ROW
    restart: always
    volumes:
      - db:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=<password>
      - MARIADB_AUTO_UPGRADE=1
      - MARIADB_DISABLE_UPGRADE_BACKUP=1
    env_file:
      - db.env

  redis:
    image: redis:alpine
    restart: always

  app:
    image: nextcloud:apache
    restart: always
    volumes:
      - nextcloud:/var/www/html
    environment:
      - VIRTUAL_HOST=servhostname.local
      - LETSENCRYPT_HOST=servhostname.local
      - LETSENCRYPT_EMAIL=my@example.com
      - MYSQL_HOST=db
      - REDIS_HOST=redis
    env_file:
      - db.env
    depends_on:
      - db
      - redis
    networks:
      - proxy-tier
      - default

  cron:
    image: nextcloud:apache
    restart: always
    volumes:
      - nextcloud:/var/www/html
    entrypoint: /cron.sh
    depends_on:
      - db
      - redis

  proxy:
    build: ./proxy
    restart: always
    ports:
      - 80:80
      - 443:443
    labels:
      com.github.jrcs.letsencrypt_nginx_proxy_companion.nginx_proxy: "true"
    volumes:
      - certs:/etc/nginx/certs:ro
      - vhost.d:/etc/nginx/vhost.d
      - html:/usr/share/nginx/html
      - /var/run/docker.sock:/tmp/docker.sock:ro
    networks:
      - proxy-tier

  letsencrypt-companion:
    image: nginxproxy/acme-companion
    restart: always
    volumes:
      - certs:/etc/nginx/certs
      - acme:/etc/acme.sh
      - vhost.d:/etc/nginx/vhost.d
      - html:/usr/share/nginx/html
      - /var/run/docker.sock:/var/run/docker.sock:ro
    networks:
      - proxy-tier
    depends_on:
      - proxy

# self signed
  omgwtfssl:
    image: paulczar/omgwtfssl
    restart: "no"
    volumes:
      - certs:/certs
    environment:
      - SSL_SUBJECT=servhostname.local
      - CA_SUBJECT=my@example.com
      - SSL_KEY=/certs/servhostname.local.key
      - SSL_CSR=/certs/servhostname.local.csr
      - SSL_CERT=/certs/servhostname.local.crt
    networks:
      - proxy-tier

volumes:
  db:
  nextcloud:
  certs:
  acme:
  vhost.d:
  html:

networks:
  proxy-tier:

This works on my Windows Machine, However I want to have this running on a linux Machine. When i run the same docker-compose.yml file in linux (raspbian pi 1GB RAM && ubuntu laptop 6GB RAM) I get the error

failed to solve: rpc error: code = Unknown desc = failed to solve with frontend dockerfile.v0: failed to read dockerfile: open /var/lib/docker/tmp/buildkit-mount218034811/Dockerfile: no such file or directory

before install I did run apt-get update && upgrade

I tried to build the Docker file in the proxy folder

on Windows we get a successful build

on linux we get the following output

$ docker build . [+] Building 0.5s (2/2) FINISHED  => [internal] load
build definition from Dockerfile

0.3s  => => transferring dockerfile: 2B                                                                                0.0s  => [internal] load .dockerignore                                                                                0.4s  => => transferring context: 2B                                                                                0.0s failed to solve with frontend dockerfile.v0: failed to read dockerfile: open
/var/lib/docker/tmp/buildkit-mount789252587/Dockerfile: no such file
or directory

Update

I am able to get the docker-compose file to work by getting rid of the docker file in the proxy folder and doing a bind on the proxy folder with the /etc/nginx/conf.d folder. however if anyone knows why the configuration would not work as it please let me know.

Any help would be appreciated


问:
Can not get SSID when change wifi in android
I am having a problem as follows:

I am trying to listen for wifi change status in service. But when I change wifi from A -> B, I can't get the ssid of the network.

I don't know where I am going wrong.

Can anyone help me to solve this problem?

My code is below:

```<code> override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        log("onStartCommand executed with startId: $startId")
        GlobalScope.launch(Dispatchers.IO) {
            while (isServiceStarted) {

                checkNetworkInfo { isConnect ->
                    if (isConnect) {
                        GlobalScope.launch(Dispatchers.IO) {
                            val netInfo = getNetworkSSID(this@NetworkService)
                            log("===========: " + netInfo)
                        }

                    } else {
                        log("============No Connect")
                    }

                }
                delay(1 * 60 * 1000)
            }
        }

        return START_STICKY
    }

     fun getNetworkSSID(context: Context): String {
        val manager = context.applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
        if (manager != null && manager.isWifiEnabled) {
            val wifiInfo: WifiInfo? = manager.connectionInfo
            if (wifiInfo != null) {
                val state: DetailedState =
                    WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState())
                if (state == DetailedState.CONNECTED || state == DetailedState.OBTAINING_IPADDR) {
                    return wifiInfo.getSSID()
                }
            }
        }
        return ""
    }

</code>```
```<code>fun Context.checkNetworkInfo(isConnected: (Boolean) -> Unit) {
    val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        val capabilities =
            connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
        if (capabilities == null) {
            isConnected.invoke(false)
        }
        connectivityManager.registerNetworkCallback(
            NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                .addTransportType(NetworkCapabilities.TRANSPORT_ETHERNET).build(),
            object : ConnectivityManager.NetworkCallback() {

                override fun onAvailable(network: Network) {
                    super.onAvailable(network)
                    isConnected.invoke(true)
                }

                override fun onLost(network: Network) {
                    isConnected.invoke(false)
                }
            })
    } else {
        val networkInfo = connectivityManager.activeNetworkInfo
        isConnected.invoke(networkInfo != null && networkInfo.isConnectedOrConnecting)
    }
}

</code>```

I have granted permission [CHANGE_WIFI_STATE,ACCESS_NETWORK_STATE,ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION]

Thank you.

Body:
I am having a problem as follows:

I am trying to listen for wifi change status in service. But when I change wifi from A -> B, I can't get the ssid of the network.

I don't know where I am going wrong.

Can anyone help me to solve this problem?

My code is below:

 override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        log("onStartCommand executed with startId: $startId")
        GlobalScope.launch(Dispatchers.IO) {
            while (isServiceStarted) {

                checkNetworkInfo { isConnect ->
                    if (isConnect) {
                        GlobalScope.launch(Dispatchers.IO) {
                            val netInfo = getNetworkSSID(this@NetworkService)
                            log("===========: " + netInfo)
                        }

                    } else {
                        log("============No Connect")
                    }

                }
                delay(1 * 60 * 1000)
            }
        }

        return START_STICKY
    }

     fun getNetworkSSID(context: Context): String {
        val manager = context.applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
        if (manager != null && manager.isWifiEnabled) {
            val wifiInfo: WifiInfo? = manager.connectionInfo
            if (wifiInfo != null) {
                val state: DetailedState =
                    WifiInfo.getDetailedStateOf(wifiInfo.getSupplicantState())
                if (state == DetailedState.CONNECTED || state == DetailedState.OBTAINING_IPADDR) {
                    return wifiInfo.getSSID()
                }
            }
        }
        return ""
    }

fun Context.checkNetworkInfo(isConnected: (Boolean) -> Unit) {
    val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        val capabilities =
            connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
        if (capabilities == null) {
            isConnected.invoke(false)
        }
        connectivityManager.registerNetworkCallback(
            NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                .addTransportType(NetworkCapabilities.TRANSPORT_ETHERNET).build(),
            object : ConnectivityManager.NetworkCallback() {

                override fun onAvailable(network: Network) {
                    super.onAvailable(network)
                    isConnected.invoke(true)
                }

                override fun onLost(network: Network) {
                    isConnected.invoke(false)
                }
            })
    } else {
        val networkInfo = connectivityManager.activeNetworkInfo
        isConnected.invoke(networkInfo != null && networkInfo.isConnectedOrConnecting)
    }
}

I have granted permission [CHANGE_WIFI_STATE,ACCESS_NETWORK_STATE,ACCESS_COARSE_LOCATION,ACCESS_FINE_LOCATION]

Thank you.


问:
notification that always stays on the screen without clear notification
how can I push notifications in Android  that always waiting for and that always stay on the screen. In this case clear notification is disabled.
As you see in picture  clear is disabled.

How to make a notification in Android that is always displayed on the screen and How to make a notification that is always displayed on the screen and the app never stops. And always be ready to work.
Thank you