问:
How to convert from a Hybris enumtype to a Java Calendar?
In Hybris, I created an enumeration of days of week.

Here is my code:

```<code>public enum DaysOfWeek implements HybrisEnumValue
{
    SUNDAY("SUNDAY"),
    MONDAY("MONDAY"),
    TUESDAY("TUESDAY"),
    WEDNESDAY("WEDNESDAY"),
    THURSDAY("THURSDAY"),
    FRIDAY("FRIDAY"),
    SATURDAY("SATURDAY");
}
</code>```

How can I convert this enumeration to a Calendar in Java, so as I can compare between Hybris enumeration and Java Calendar values?

答:
java.time

I recommend that you use java.time, the modern Java date and time API, for your date work. It already has a built-in DayOfWeek enum similar to yours (only begins with MONDAY in agreement with the international standard). Which class to use instead of the old Calendar depends on your exact requirements. For example, for a day without time of day use LocalDate. For a date and time in a specific time zone use ZonedDateTime. Here’s an example of code using LocalDate:

```<code>    DayOfWeek givenDow = DayOfWeek.TUESDAY; // java.time DayOfWeek
    LocalDate date = LocalDate.of(2020, Month.JUNE, 2);
    DayOfWeek dowOfDate = date.getDayOfWeek();
    if (dowOfDate.equals(givenDow)) {
        System.out.println("Yes, it’s a Tuesday");
    } else {
        System.out.println("No, it’s a " + dowOfDate);
    }
</code>```

Output is:

Yes, it’s a Tuesday

I did think about whether you wanted a comparison to tell you whether the date was before or after Tuesday, but since Tuesdays come every week, I didn’t find it very meaningful for most purposes. Let me know if it is for yours.

It’s always the question whether you want to use equals() or == for comparing enum values. Both work since the compuiler ensure that each enum constant is a singleton. On Stack Overflow I tend to use equals() because it’s generally recommended for comparing objects for equality, and someone using == between non-enum objects risks an unpleasant surprise. The project standard where I work says to use == for comparing enum values.

If you’ve got a GregorianCalendar object from a legacy API that you cannot afford to upgrade to java.time just now, you may convert to ZonedDateTime and get its day of week as a java.time enum constant:

```<code>    GregorianCalendar oldfashionedCalendar
            = new GregorianCalendar(2020, Calendar.JUNE, 3);

    DayOfWeek dowOfCalendar = oldfashionedCalendar.toZonedDateTime().getDayOfWeek();
</code>```

The rest is as before. The Calendar that you have got is by far most likely a GregorianCalendar, and if so, you may cast it to one.

Converting to Calendar

I don’t know what sense it makes, but of course a DayOfWeek value can be converted to an old-fashioned Calendar. We need to decide what we want all the other Calendar fields to be. Here’s an example:

```<code>    DayOfWeek givenDow = DayOfWeek.TUESDAY;

    ZonedDateTime startOfDay = LocalDate.EPOCH
            .with(givenDow)
            .atStartOfDay(ZoneId.systemDefault());
    Calendar oldfashionedCalendar = GregorianCalendar.from(startOfDay);

    System.out.println(oldfashionedCalendar.getTime());
</code>```

Tue Dec 30 00:00:00 CET 1969

So we’ve got a Tuesday as requested.

Using your Hybris enum

If you insist on using your own enum, we can convert that too. To convert to a java.time enum we need to take into account that your enum has Sunday first while java.time has got it last:

```<code>    DaysOfWeek givenDow = DaysOfWeek.TUESDAY; // Your Hybris DaysOfWeek

    DayOfWeek javaDow;
    if (givenDow.equals(DaysOfWeek.SUNDAY)) {
        javaDow = DayOfWeek.SUNDAY;
    } else {
        // The ordinal of Hybris DaysOfWeek for Monday through Saturday are 1 through 6,
        // which agrees with Java DayOfWeek numbering
        javaDow = DayOfWeek.of(givenDow.ordinal());
    }
    System.out.println("As java.time DayOfWeek: " + javaDow);
</code>```

As java.time DayOfWeek: TUESDAY

To convert it to something that you can meaningfully compare with a Calendar we need to add 1 to the ordinal because Calendar numbers the days from 1. Sunday poses no problem, it comes first in both DaysOfWeek and Calendar.

```<code>    int givenCalendarDow = givenDow.ordinal() + 1;
    GregorianCalendar oldfashionedCalendar
            = new GregorianCalendar(2020, Calendar.JUNE, 9);
    int dowOfCalendar = oldfashionedCalendar.get(Calendar.DAY_OF_WEEK);
    if (dowOfCalendar == givenCalendarDow) {
        System.out.println("Yes, it’s a Tuesday");
    } else {
        System.out.println("No, it’s a " + dowOfCalendar);
    }
</code>```

Yes, it’s a Tuesday

Link

Oracle tutorial: Date Time explaining how to use java.time.

Body:
In Hybris, I created an enumeration of days of week.

Here is my code:

public enum DaysOfWeek implements HybrisEnumValue
{
    SUNDAY("SUNDAY"),
    MONDAY("MONDAY"),
    TUESDAY("TUESDAY"),
    WEDNESDAY("WEDNESDAY"),
    THURSDAY("THURSDAY"),
    FRIDAY("FRIDAY"),
    SATURDAY("SATURDAY");
}

How can I convert this enumeration to a Calendar in Java, so as I can compare between Hybris enumeration and Java Calendar values?

Body:
java.time

I recommend that you use java.time, the modern Java date and time API, for your date work. It already has a built-in DayOfWeek enum similar to yours (only begins with MONDAY in agreement with the international standard). Which class to use instead of the old Calendar depends on your exact requirements. For example, for a day without time of day use LocalDate. For a date and time in a specific time zone use ZonedDateTime. Here’s an example of code using LocalDate:

    DayOfWeek givenDow = DayOfWeek.TUESDAY; // java.time DayOfWeek
    LocalDate date = LocalDate.of(2020, Month.JUNE, 2);
    DayOfWeek dowOfDate = date.getDayOfWeek();
    if (dowOfDate.equals(givenDow)) {
        System.out.println("Yes, it’s a Tuesday");
    } else {
        System.out.println("No, it’s a " + dowOfDate);
    }

Output is:

Yes, it’s a Tuesday

I did think about whether you wanted a comparison to tell you whether the date was before or after Tuesday, but since Tuesdays come every week, I didn’t find it very meaningful for most purposes. Let me know if it is for yours.

It’s always the question whether you want to use equals() or == for comparing enum values. Both work since the compuiler ensure that each enum constant is a singleton. On Stack Overflow I tend to use equals() because it’s generally recommended for comparing objects for equality, and someone using == between non-enum objects risks an unpleasant surprise. The project standard where I work says to use == for comparing enum values.

If you’ve got a GregorianCalendar object from a legacy API that you cannot afford to upgrade to java.time just now, you may convert to ZonedDateTime and get its day of week as a java.time enum constant:

    GregorianCalendar oldfashionedCalendar
            = new GregorianCalendar(2020, Calendar.JUNE, 3);

    DayOfWeek dowOfCalendar = oldfashionedCalendar.toZonedDateTime().getDayOfWeek();

The rest is as before. The Calendar that you have got is by far most likely a GregorianCalendar, and if so, you may cast it to one.

Converting to Calendar

I don’t know what sense it makes, but of course a DayOfWeek value can be converted to an old-fashioned Calendar. We need to decide what we want all the other Calendar fields to be. Here’s an example:

    DayOfWeek givenDow = DayOfWeek.TUESDAY;

    ZonedDateTime startOfDay = LocalDate.EPOCH
            .with(givenDow)
            .atStartOfDay(ZoneId.systemDefault());
    Calendar oldfashionedCalendar = GregorianCalendar.from(startOfDay);

    System.out.println(oldfashionedCalendar.getTime());

Tue Dec 30 00:00:00 CET 1969

So we’ve got a Tuesday as requested.

Using your Hybris enum

If you insist on using your own enum, we can convert that too. To convert to a java.time enum we need to take into account that your enum has Sunday first while java.time has got it last:

    DaysOfWeek givenDow = DaysOfWeek.TUESDAY; // Your Hybris DaysOfWeek

    DayOfWeek javaDow;
    if (givenDow.equals(DaysOfWeek.SUNDAY)) {
        javaDow = DayOfWeek.SUNDAY;
    } else {
        // The ordinal of Hybris DaysOfWeek for Monday through Saturday are 1 through 6,
        // which agrees with Java DayOfWeek numbering
        javaDow = DayOfWeek.of(givenDow.ordinal());
    }
    System.out.println("As java.time DayOfWeek: " + javaDow);

As java.time DayOfWeek: TUESDAY

To convert it to something that you can meaningfully compare with a Calendar we need to add 1 to the ordinal because Calendar numbers the days from 1. Sunday poses no problem, it comes first in both DaysOfWeek and Calendar.

    int givenCalendarDow = givenDow.ordinal() + 1;
    GregorianCalendar oldfashionedCalendar
            = new GregorianCalendar(2020, Calendar.JUNE, 9);
    int dowOfCalendar = oldfashionedCalendar.get(Calendar.DAY_OF_WEEK);
    if (dowOfCalendar == givenCalendarDow) {
        System.out.println("Yes, it’s a Tuesday");
    } else {
        System.out.println("No, it’s a " + dowOfCalendar);
    }

Yes, it’s a Tuesday

Link

Oracle tutorial: Date Time explaining how to use java.time.


来源: stackexchange

问:
How to create timer in c++
Two independent timers with two different time periods running simultaneously.
Using SetWaitableTimer.

```<code>SetWaitableTimer(mhandle, &liDueTime, 0, onCallFunc, this, TRUE);
</code>```

What iperiod indicate?

答:
After the first timer expiry at lpDueTime, the timer will go off every lPeriod milliseconds unless

lPeriod is zero. Zero means the timer goes off only once, or

lPeriod is less than zero. SetWaitableTimer fails if given a negative period.

For more details see Documentation.

ContentLicense: CC BY-SA 4.0

Title: How to create timer in c++

Body:
Two independent timers with two different time periods running simultaneously.
Using SetWaitableTimer.

SetWaitableTimer(mhandle, &liDueTime, 0, onCallFunc, this, TRUE);

What iperiod indicate?


问:
Write a code that Calculates the average number of non-zero ratings per individual in our data set
So I've written my code below but I am having a hard time getting the code to not include the number of zeros. It runs but unfortunately not the way I want it to. Can anyone shed some light?

the variable movies is basically a list of movies we were given  The code will be right if an average of 21.4 is the output.

```<code>all_ratings =[
[5,5,4,4,3,1,2,3,4,4,4,3,4,0,0,0,1,2,3,4,4,4,1,4,0,0,0,1,2,5],
[5,0,1,2,3,1,2,3,4,4,4,5,4,2,1,0,1,2,0,5,0,4,1,4,2,0,0,1,0,5],
[5,2,3,4,4,0,0,0,4,5,0,3,0,0,0,3,4,0,1,4,4,4,0,4,0,3,0,1,2,5],
[5,0,4,0,0,4,2,3,0,0,4,0,3,0,1,0,1,2,3,0,2,0,1,0,0,0,4,0,1,5],
[5,4,3,2,1,1,2,3,4,3,4,3,4,0,3,0,1,2,4,4,4,4,1,4,0,0,0,1,2,5],
]

total=[]
average=[]

for index in range (len(all_ratings)):
    total+=[sum(all_ratings[index])]

for index in range(len(all_ratings)):
    average = average + [total[index]/30]

for index in range(len(movies)):
    print(average)
</code>```

答:
define

```<code>def mean(l):
    return sum(l)/len(l)
</code>```

and now

```<code>[mean([y for y in x if y > 0]) for x in allratings]
</code>```

Body:
So I've written my code below but I am having a hard time getting the code to not include the number of zeros. It runs but unfortunately not the way I want it to. Can anyone shed some light?

the variable movies is basically a list of movies we were given  The code will be right if an average of 21.4 is the output.

all_ratings =[
[5,5,4,4,3,1,2,3,4,4,4,3,4,0,0,0,1,2,3,4,4,4,1,4,0,0,0,1,2,5],
[5,0,1,2,3,1,2,3,4,4,4,5,4,2,1,0,1,2,0,5,0,4,1,4,2,0,0,1,0,5],
[5,2,3,4,4,0,0,0,4,5,0,3,0,0,0,3,4,0,1,4,4,4,0,4,0,3,0,1,2,5],
[5,0,4,0,0,4,2,3,0,0,4,0,3,0,1,0,1,2,3,0,2,0,1,0,0,0,4,0,1,5],
[5,4,3,2,1,1,2,3,4,3,4,3,4,0,3,0,1,2,4,4,4,4,1,4,0,0,0,1,2,5],
]

total=[]
average=[]

for index in range (len(all_ratings)):
    total+=[sum(all_ratings[index])]

for index in range(len(all_ratings)):
    average = average + [total[index]/30]

for index in range(len(movies)):
    print(average)

Body:
define

def mean(l):
    return sum(l)/len(l)

and now

[mean([y for y in x if y > 0]) for x in allratings]


问:
Elasticsearch : "failed to get node info for {IP}" and "noNodeAvailableException" in service log
I am facing an issue which i wasn't earlier.

I am attaching logs of my service and elasticSearch (2.4.4):

```<code>2020-05-30 06:29:44.576  INFO 24787 --- [generic][T#287]] org.elasticsearch.client.transport       : [Shatter] failed to get node info for {#transport#-1}{172.17.0.1}{172.17.0.1:9300}, disc
onnecting...

org.elasticsearch.transport.ReceiveTimeoutTransportException: [][172.17.0.1:9300][cluster:monitor/nodes/liveness] request_id [10242] timed out after [5000ms]
        at org.elasticsearch.transport.TransportService$TimeoutHandler.run(TransportService.java:698) ~[elasticsearch-2.4.4.jar!/:2.4.4]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_242]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_242]
        at java.lang.Thread.run(Thread.java:748) [na:1.8.0_242]
</code>```

ElasticSearch Logs:

```<code>[2020-05-30 06:29:46,784][INFO ][monitor.jvm              ] [Tempo] [gc][old][230125][41498] duration [8.2s], collections [1]/[9s], total [8.2s]/[10.7h], memory [473.2mb]->[426.1mb]/[494.9mb], all_pools {[young] [131.8mb]->[84.7mb]/[136.5mb]}{[survivor] [0b]->[0b]/[17mb]}{[old] [341.3mb]->[341.3mb]/[341.3mb]}
[2020-05-30 06:33:47,782][INFO ][monitor.jvm              ] [Tempo] [gc][old][230340][41540] duration [7s], collections [1]/[7.8s], total [7s]/[10.7h], memory [493.3mb]->[425mb]/[494.9mb], all_pools {[young] [136.5mb]->[83.6mb]/[136.5mb]}{[survivor] [15.4mb]->[0b]/[17mb]}{[old] [341.3mb]->[341.3mb]/[341.3mb]}
[2020-05-30 06:37:59,384][INFO ][monitor.jvm              ] [Tempo] [gc][old][230569][41582] duration [6.9s], collections [1]/[7.2s], total [6.9s]/[10.7h], memory [494.8mb]->[424.7mb]/[494.9mb], all_pools {[young] [136.5mb]->[83.4mb]/[136.5mb]}{[survivor] [16.9mb]->[0b]/[17mb]}{[old] [341.3mb]->[341.3mb]/[341.3mb]}
</code>```

i am not facing the issue in my Development environment however when i deploy on EC2 i am getting this. Adding further when i do a restart of elastic. It works absolutely fine with no issues but after 10-15 mins or less depending on the amount for search queries or insertion queries, the error message appears.

Also, my storage space on the instance is 74% consumed 94G out of 120G.
can it be because of memory ?
I am pretty much sure my res-client code is fine as its working in production now for a long time.
Can it be a Port issue ? I am using docker container for elastic.

Any help will be appreciated.

_cat/fielddata?v

_cat/nodes?v

答:
I think your heap size for elasticsearch is very low. my best guess is with increasing the heap size the problem will be solved.
To ask why this has happened now, I think it's because the volume of data has increased over time.

my second guess is about high load. It seems that you have too many request to elasticsearch recently. you can check the size of queue request via /_cat/thread_pool?v.
you have two solution for this situation. first decrease the request. second add a node and add replica.

Body:
I am facing an issue which i wasn't earlier.

I am attaching logs of my service and elasticSearch (2.4.4):

2020-05-30 06:29:44.576  INFO 24787 --- [generic][T#287]] org.elasticsearch.client.transport       : [Shatter] failed to get node info for {#transport#-1}{172.17.0.1}{172.17.0.1:9300}, disc
onnecting...

org.elasticsearch.transport.ReceiveTimeoutTransportException: [][172.17.0.1:9300][cluster:monitor/nodes/liveness] request_id [10242] timed out after [5000ms]
        at org.elasticsearch.transport.TransportService$TimeoutHandler.run(TransportService.java:698) ~[elasticsearch-2.4.4.jar!/:2.4.4]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_242]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_242]
        at java.lang.Thread.run(Thread.java:748) [na:1.8.0_242]

ElasticSearch Logs:

[2020-05-30 06:29:46,784][INFO ][monitor.jvm              ] [Tempo] [gc][old][230125][41498] duration [8.2s], collections [1]/[9s], total [8.2s]/[10.7h], memory [473.2mb]->[426.1mb]/[494.9mb], all_pools {[young] [131.8mb]->[84.7mb]/[136.5mb]}{[survivor] [0b]->[0b]/[17mb]}{[old] [341.3mb]->[341.3mb]/[341.3mb]}
[2020-05-30 06:33:47,782][INFO ][monitor.jvm              ] [Tempo] [gc][old][230340][41540] duration [7s], collections [1]/[7.8s], total [7s]/[10.7h], memory [493.3mb]->[425mb]/[494.9mb], all_pools {[young] [136.5mb]->[83.6mb]/[136.5mb]}{[survivor] [15.4mb]->[0b]/[17mb]}{[old] [341.3mb]->[341.3mb]/[341.3mb]}
[2020-05-30 06:37:59,384][INFO ][monitor.jvm              ] [Tempo] [gc][old][230569][41582] duration [6.9s], collections [1]/[7.2s], total [6.9s]/[10.7h], memory [494.8mb]->[424.7mb]/[494.9mb], all_pools {[young] [136.5mb]->[83.4mb]/[136.5mb]}{[survivor] [16.9mb]->[0b]/[17mb]}{[old] [341.3mb]->[341.3mb]/[341.3mb]}

i am not facing the issue in my Development environment however when i deploy on EC2 i am getting this. Adding further when i do a restart of elastic. It works absolutely fine with no issues but after 10-15 mins or less depending on the amount for search queries or insertion queries, the error message appears.

Also, my storage space on the instance is 74% consumed 94G out of 120G.
can it be because of memory ?
I am pretty much sure my res-client code is fine as its working in production now for a long time.
Can it be a Port issue ? I am using docker container for elastic.

Any help will be appreciated.

_cat/fielddata?v

_cat/nodes?v


问:
Python : How to call csv files from the directory based on the list of items?
I have a list of items and I want to call only those csv files from the directory whose names are similar to the items in the list. I am doing something like below but its reading all the files from the directory. Please suggest.</p>

```<code>x_list = [ a,b,c,d]
files in directory = [a.csv, b.csv, c.csv, d.csv, e.csv, f.csv]

for files in os.listdir(dir + 'folder\\'):
    file_name = files[:files.find('.')]
    if file_name in x_list:
        print(file_name)
</code>```

答:
You can use regular expressions for which you'll need the re module.

```<code>import re
print(*(file for file in os.listdir() if re.match(r".*\.csv", file) and file[:-4] in x), sep='\n')

</code>```

You can also use the filter function:

```<code>print(*filter(lambda file:  re.match(r".*\.csv", file) and file[:-4] in x, os.listdir(), sep='\n')
</code>```

Body:
I have a list of items and I want to call only those csv files from the directory whose names are similar to the items in the list. I am doing something like below but its reading all the files from the directory. Please suggest.

x_list = [ a,b,c,d]
files in directory = [a.csv, b.csv, c.csv, d.csv, e.csv, f.csv]

for files in os.listdir(dir + 'folder\\'):
    file_name = files[:files.find('.')]
    if file_name in x_list:
        print(file_name)

Body:
You can use regular expressions for which you'll need the re module.

import re
print(*(file for file in os.listdir() if re.match(r".*\.csv", file) and file[:-4] in x), sep='\n')

You can also use the filter function:

print(*filter(lambda file:  re.match(r".*\.csv", file) and file[:-4] in x, os.listdir(), sep='\n')


问:
Cannot resolve symbol 'HasRequired' Entity Framework Core
I'm trying to connect two tables by means of code in C# with Entity Framework Core.

The classes are:

```<code>public class roll
{
    [key]
    public int rollId { get; set; }

    public List<pieces> pieces { get; set; }
}

public class pieces
{
    [Key]
    public int pieceId { get; set; }
    public int quantity { get; set; }
    public decimal price { get; set; }
}
</code>```

In my DbContext, I have the following method:

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<roll>()
                .HasRequired(m => m.quantity)
                .WithMany(m => m.pieces)
                .HasForeignKey(m => m.pieceId);

    base.OnModelCreating(modelBuilder);
}
</code>```

HasRequired turns red and gives this message:

EntityTypeBuilder does not contain a definition for HasRequired.

The project has added a reference to Microsoft.EntityFrameworkCore.Relational.
I have recompiled the solution, closed and opened visual studio and I cannot solve that HasRequired stops being red

What is wrong with my code?

答:
You should change your code for .net core EF, they just removed HasRequired and replace it with HasOne for one-to-one relationship and HasMany for one-to-many relations. You Can Also add .IsRequired() for required relations. Good Luck.

```<code>modelBuilder.Entity<roll>()
            .HasOne(m => m.quantity).IsRequired()
            .WithMany(m => m.pieces)
            .HasForeignKey(m => m.pieceId);
</code>```

You can find complete documentation here : Documentation link

Body:
I'm trying to connect two tables by means of code in C# with Entity Framework Core.

The classes are:

public class roll
{
    [key]
    public int rollId { get; set; }

    public List<pieces> pieces { get; set; }
}

public class pieces
{
    [Key]
    public int pieceId { get; set; }
    public int quantity { get; set; }
    public decimal price { get; set; }
}

In my DbContext, I have the following method:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<roll>()
                .HasRequired(m => m.quantity)
                .WithMany(m => m.pieces)
                .HasForeignKey(m => m.pieceId);

    base.OnModelCreating(modelBuilder);
}

HasRequired turns red and gives this message:

EntityTypeBuilder does not contain a definition for HasRequired.

The project has added a reference to Microsoft.EntityFrameworkCore.Relational.
I have recompiled the solution, closed and opened visual studio and I cannot solve that HasRequired stops being red

What is wrong with my code?

Body:
You should change your code for .net core EF, they just removed HasRequired and replace it with HasOne for one-to-one relationship and HasMany for one-to-many relations. You Can Also add .IsRequired() for required relations. Good Luck.

modelBuilder.Entity<roll>()
            .HasOne(m => m.quantity).IsRequired()
            .WithMany(m => m.pieces)
            .HasForeignKey(m => m.pieceId);

You can find complete documentation here : Documentation link


问:
How to deal with quotes around an argument in a function?
I have a function I am trying to make in R that looks like this:

```<code>diff_abund <- function(Data, Rank, Taxa) {
subset_taxa(Data, Rank == Taxa)
}

da= diff_abund(frbc1_02, Phylum, "Acidobacteria")
</code>```

And I get the error:

```<code>Error in eval(e, x, parent.frame()) : object 'Rank' not found
</code>```

The problem appears to be with the Rank == Taxa part. If I remove that from the function like so:

```<code>diff_abund <- function(Data) {

subset_taxa(Data, Phylum == "Acidobacteria")

}
da= diff_abund(frbc1_02)
</code>```

The function works normally. The dataset is an S4 object that only works in the package phyloseq. "Rank" is basically a group of vectors ranging from Kingdom down to Species. Not sure what you would call that. Any reason this could be happening?
Thank you,
Sam

答:
First thing: whenever you post, provide a reproducible example: either with sample data you create; or with a small part of your own data (using dput()). Otherwise, we're limited in how we can help.

Generally speaking, quotations would go outside of the function. If year was supposed to be character, and I had some function where I wanted to add year to a dataset I'd write

```<code>
    random.fun <- function(dat, yr){
    dat%>%
    mutate(yr = year)
    }

</code>```

and then I'd create a variable and call that function, assigning it to the variable.

```<code>
    df <- random.fun(dataset, "2007")
</code>```

There are other problems with your code, and again, it's hard to help without knowing what you really want to do. But below, it doesn't look as though subset_taxa is a meaningful function.

```<code>
    diff_abund <- function(Data,Rank,Taxa) {

    FTaxa=subset_taxa(Data, Rank == "Taxa")

    }
    diff_abund(frbc1_02, Phylum, "Acidobacteria")

</code>```

Generally, I prefer writing with dplyr

```<code>    library(tidyverse)

    diff_abund <- function(data, rank, taxa){
    data%>%
    filter(rank==taxa)
    }

    newdf <- diff_abund(df, phylum, "taxa")

</code>```

Body:
I have a function I am trying to make in R that looks like this:

diff_abund <- function(Data, Rank, Taxa) {
subset_taxa(Data, Rank == Taxa)
}

da= diff_abund(frbc1_02, Phylum, "Acidobacteria")

And I get the error:

Error in eval(e, x, parent.frame()) : object 'Rank' not found

The problem appears to be with the Rank == Taxa part. If I remove that from the function like so:

diff_abund <- function(Data) {

subset_taxa(Data, Phylum == "Acidobacteria")

}
da= diff_abund(frbc1_02)

The function works normally. The dataset is an S4 object that only works in the package phyloseq. "Rank" is basically a group of vectors ranging from Kingdom down to Species. Not sure what you would call that. Any reason this could be happening?
Thank you,
Sam

Body:
First thing: whenever you post, provide a reproducible example: either with sample data you create; or with a small part of your own data (using dput()). Otherwise, we're limited in how we can help.

Generally speaking, quotations would go outside of the function. If year was supposed to be character, and I had some function where I wanted to add year to a dataset I'd write

    random.fun <- function(dat, yr){
    dat%>%
    mutate(yr = year)
    }

and then I'd create a variable and call that function, assigning it to the variable.

    df <- random.fun(dataset, "2007")

There are other problems with your code, and again, it's hard to help without knowing what you really want to do. But below, it doesn't look as though subset_taxa is a meaningful function.

    diff_abund <- function(Data,Rank,Taxa) {

    FTaxa=subset_taxa(Data, Rank == "Taxa")

    }
    diff_abund(frbc1_02, Phylum, "Acidobacteria")

Generally, I prefer writing with dplyr

    library(tidyverse)

    diff_abund <- function(data, rank, taxa){
    data%>%
    filter(rank==taxa)
    }

    newdf <- diff_abund(df, phylum, "taxa")


问:
by instance() showing red line in android studio after updating android studio 4 in kotlin
by instance() showing red line after updating android studio 4

private val factory: SelectHospitalViewModelFactory by instance()

答:
step 1-
Setting-> Kotlin Compiler"  »

step 2-
could you please disable new type inference in IDE by unchecking checkbox "Enable new type inference algorithm..." in Preferences -> Kotlin Compiler


答:
From official doc : "The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell, although results are returned in arbitrary order."

import glob
dirPath = "/home/.../"
pattern = dirPath + '*.csv'

for file_path in glob.glob(pattern):
    print(file_path)
```

Title: Python : How to call csv files from the directory based on the list of items?


问:
Changing position in table so title is always on top in mobile view
I've made some changes and progress hence the new question (this way it can be simplified). I'm creating a layout where images will alternate positions, left and right on the page with information opposite them (on desktop). I'm using flex for alignment and so the contents of each DIV is centered within it.

My code is as follows…

.site-section-content {
    width: 100%;
}

.site-section-wrap {
  width: 100%;
  display: flex;
  background: pink;
  align-items: center;
  justify-content: center;
  flex-flow: row;
  text-align: center;
  border-style: dashed;
}

@media only screen and (max-width: 900px) {
.site-section-wrap {
  width: 100%;
  display: table;
  background: pink;
  align-items: center;
  justify-content: center;
  text-align: center;
  border-style: dashed;
}
}

.site-section-title-section {
  width: 50%;
  float: right;
}

@media only screen and (max-width: 900px) {
.site-section-title-section {
  width: 100%;
  float: left;
}
}

.site-section-info-section {
  width: 50%;
  float: right;
}

@media only screen and (max-width: 900px) {
.site-section-info-section {
  width: 100%;
  float: left;
}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<div class="site-section-content">
   <div class="site-section-wrap">
      <div class="site-section-title-section">
         <img src="https://via.placeholder.com/540x250" width="100%">
      </div>
      <div class="site-section-info-section">
         <h1>IMAGE INFO</h1>
      </div>
   </div>
   <div class="site-section-wrap">
      <div class="site-section-info-section">
         <h1>IMAGE INFO</h1>
      </div>
      <div class="site-section-title-section">
         <img src="https://via.placeholder.com/540x250" width="100%">
      </div>
   </div>
   <div class="site-section-wrap">
      <div class="site-section-title-section">
         <img src="https://via.placeholder.com/540x250" width="100%">
      </div>
      <div class="site-section-info-section">
         <h1>IMAGE INFO</h1>
      </div>
   </div>
   <div class="site-section-wrap">
      <div class="site-section-info-section">
         <h1>IMAGE INFO</h1>
      </div>
      <div class="site-section-title-section">
         <img src="https://via.placeholder.com/540x250" width="100%">
      </div>
   </div>
</div></code>```

For clarity I've added dashed borders which will be removed. You'll notice that the height is the same on desktop for each side but on mobile it's only the height of its contents, this behaviour is fine.

I've swapped around the tags for each alternation but the problem is that the image title and info isn't always above the image on mobile (which it should be).

I've experimented with different float positions to no avail so I'm stuck here.

答:
Just use flex , no need of float for your requirement,

don't repeat the property in media query which you don't need to change

    .site-section-content {
        width: 100%;
    }

    .site-section-wrap {
        width: 100%;
        display: flex;
        background: pink;
        align-items: center;
        justify-content: center;
        flex-flow: row;
        text-align: center;
        border-style: dashed;
    }

    .site-section-title-section {
        width: 50%;
    }
    .site-section-info-section {
        width: 50%;
    }
    .site-section-content .site-section-wrap:nth-child(even){
      flex-direction: row-reverse;
    }

    @media only screen and (max-width: 900px) {
        .site-section-wrap {
            flex-direction: column-reverse !important;
        }
        .site-section-title-section,.site-section-info-section{
            width: 100%;
        }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div class="site-section-content">
        <div class="site-section-wrap">
            <div class="site-section-title-section">
                <img src="https://via.placeholder.com/540x250" width="100%">
            </div>
            <div class="site-section-info-section">
                <h1>IMAGE INFO</h1>
            </div>
        </div>
        <div class="site-section-wrap">
            <div class="site-section-title-section">
                <img src="https://via.placeholder.com/540x250" width="100%">
            </div>
            <div class="site-section-info-section">
                <h1>IMAGE INFO</h1>
            </div>
        </div>
        <div class="site-section-wrap">
            <div class="site-section-title-section">
                <img src="https://via.placeholder.com/540x250" width="100%">
            </div>
            <div class="site-section-info-section">
                <h1>IMAGE INFO</h1>
            </div>
        </div>
        <div class="site-section-wrap">
            <div class="site-section-title-section">
                <img src="https://via.placeholder.com/540x250" width="100%">
            </div>
            <div class="site-section-info-section">
                <h1>IMAGE INFO</h1>
            </div>
        </div>
    </div></code>```

Body:
I've made some changes and progress hence the new question (this way it can be simplified). I'm creating a layout where images will alternate positions, left and right on the page with information opposite them (on desktop). I'm using flex for alignment and so the contents of each DIV is centered within it.

My code is as follows…

.site-section-content {
    width: 100%;
}

.site-section-wrap {
  width: 100%;
  display: flex;
  background: pink;
  align-items: center;
  justify-content: center;
  flex-flow: row;
  text-align: center;
  border-style: dashed;
}

@media only screen and (max-width: 900px) {
.site-section-wrap {
  width: 100%;
  display: table;
  background: pink;
  align-items: center;
  justify-content: center;
  text-align: center;
  border-style: dashed;
}
}

.site-section-title-section {
  width: 50%;
  float: right;
}

@media only screen and (max-width: 900px) {
.site-section-title-section {
  width: 100%;
  float: left;
}
}

.site-section-info-section {
  width: 50%;
  float: right;
}

@media only screen and (max-width: 900px) {
.site-section-info-section {
  width: 100%;
  float: left;
}
}

<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">

IMAGE INFO

IMAGE INFO

IMAGE INFO

IMAGE INFO

For clarity I've added dashed borders which will be removed. You'll notice that the height is the same on desktop for each side but on mobile it's only the height of its contents, this behaviour is fine.

I've swapped around the tags for each alternation but the problem is that the image title and info isn't always above the image on mobile (which it should be).

I've experimented with different float positions to no avail so I'm stuck here.

Body:
Just use flex , no need of float for your requirement,

don't repeat the property in media query which you don't need to change

    .site-section-content {
        width: 100%;
    }

    .site-section-wrap {
        width: 100%;
        display: flex;
        background: pink;
        align-items: center;
        justify-content: center;
        flex-flow: row;
        text-align: center;
        border-style: dashed;
    }

    .site-section-title-section {
        width: 50%;
    }
    .site-section-info-section {
        width: 50%;
    }
    .site-section-content .site-section-wrap:nth-child(even){
      flex-direction: row-reverse;
    }

    @media only screen and (max-width: 900px) {
        .site-section-wrap {
            flex-direction: column-reverse !important;
        }
        .site-section-title-section,.site-section-info-section{
            width: 100%;
        }
    }

    <div class="site-section-content">
        <div class="site-section-wrap">
            <div class="site-section-title-section">
                <img src="https://via.placeholder.com/540x250" width="100%">
            </div>
            <div class="site-section-info-section">
                <h1>IMAGE INFO</h1>
            </div>
        </div>
        <div class="site-section-wrap">
            <div class="site-section-title-section">
                <img src="https://via.placeholder.com/540x250" width="100%">
            </div>
            <div class="site-section-info-section">
                <h1>IMAGE INFO</h1>
            </div>
        </div>
        <div class="site-section-wrap">
            <div class="site-section-title-section">
                <img src="https://via.placeholder.com/540x250" width="100%">
            </div>
            <div class="site-section-info-section">
                <h1>IMAGE INFO</h1>
            </div>
        </div>
        <div class="site-section-wrap">
            <div class="site-section-title-section">
                <img src="https://via.placeholder.com/540x250" width="100%">
            </div>
            <div class="site-section-info-section">
                <h1>IMAGE INFO</h1>
            </div>
        </div>
    </div>


问:
How do I fix a black screen when I delete a Navigation ViewController?
I am attempting to delete a Navigation ViewController from Xcode application. When I delete from the Main.storyboard file, the app screen is black when I run the application(it's not because it is loading). </p>

<p>How can I successfully de-integrate a Navigation ViewController from my Xcode application? </p>

答:
I think there is no initial view controller in your storyboard after you delete the navigationVC

You need to select VC that you what to load first and check IsInitialVC

Body:
I am attempting to delete a Navigation ViewController from Xcode application. When I delete from the Main.storyboard file, the app screen is black when I run the application(it's not because it is loading).

How can I successfully de-integrate a Navigation ViewController from my Xcode application?


问:
Numerical integration with big errors
I'm trying to compute this integral, but the errors seems too high.

I tried changing the precision with mp.mp.dps = 100 and maxdegree= 3000 but without any good results.

Is it possible to compute such an integral ?

```<code>import mpmath as mp
A = 106.829
B = 2546.40
DD = 1000.0
mp.mp.dps = 100

nom = lambda oo, mm: (2 * mm - 1) * mm**( DD * mm) * (
              mp.exp( (2 * mm - 1) * A -  (mm/oo) * B)) /  (mp.gamma(mm) ** DD * oo ** (DD * mm) )

nomRes = mp.quad(nom,[0.5,3.0],[0.5,3.0], error = True, maxdegree= 3000)
</code>```

I got the following error :

```<code>nomRes = (5.2385053e-792,5.1842e-792)
</code>```

This error suggests that I can't trust the value obtained.

答: You are raising things to power DD*mm which is huge. What do you expect to get?

Title: Numerical integration with big errors

Body:
I'm trying to compute this integral, but the errors seems too high.

I tried changing the precision with mp.mp.dps = 100 and maxdegree= 3000 but without any good results.

Is it possible to compute such an integral ?

import mpmath as mp
A = 106.829
B = 2546.40
DD = 1000.0
mp.mp.dps = 100

nom = lambda oo, mm: (2 * mm - 1) * mm**( DD * mm) * (
              mp.exp( (2 * mm - 1) * A -  (mm/oo) * B)) /  (mp.gamma(mm) ** DD * oo ** (DD * mm) )

nomRes = mp.quad(nom,[0.5,3.0],[0.5,3.0], error = True, maxdegree= 3000)

I got the following error :

nomRes = (5.2385053e-792,5.1842e-792)

This error suggests that I can't trust the value obtained.


问:
Does anyone know how to block browser back button?

Possible Duplicate:

  Disable browser's back button

i have one button on page
on that button click event page will redirect on the next page
now i click on the browser back button
but i want to restrict browser back button for some security purpose

does any one know how to block browser back button so that page can not redirect to previous page?

答:
Do not disable expected browser behaviour and you can handle the possiblity at your end, but if you really want to do so,
there is one work around here...

```<code>Just put this javascript on the html section of aspx page above head section.
</code>```

This causes every back to return with
  a forward.

```<code><script type = "text/javascript" >
function disableBackButton()
{
window.history.forward();
}
setTimeout("disableBackButton()", 0);
</script>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Do not disable expected browser behaviour and you can handle the possiblity at your end, but if you really want to do so,
there is one work around here...

Just put this javascript on the html section of aspx page above head section.

This causes every back to return with
  a forward.

<script type = "text/javascript" >
function disableBackButton()
{
window.history.forward();
}
setTimeout("disableBackButton()", 0);
</script>


问:
Couldnt display data from firebase in recyclerview
I am developing an android app which shows the user with the latest jobs from various fields. I want to display the jobs that the user has applied so far in "Your Applications" section.

But the values are not getting retrieved. It displays a blank activity. I have attached the code.

Applications.java

```<code>import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Application;
import android.app.ProgressDialog;
import android.os.Bundle;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

public class Applications extends AppCompatActivity {

    DatabaseReference databaseReference;
    FirebaseDatabase firebaseDatabase;
    RecyclerView recyclerView;
    FirebaseUser user;
    FirebaseAuth mAuth;
    ArrayList<Post> posts;
    MyAdap adap;
    ProgressDialog pd;
    long maxid=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_applications);
        recyclerView = findViewById(R.id.work);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAuth = FirebaseAuth.getInstance();
        user = mAuth.getCurrentUser();
        posts = new ArrayList<>();
        pd= new ProgressDialog(Applications.this);
        pd.setMessage("Loading...");
        pd.show();

        getSupportActionBar().setTitle("Your Applications");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        firebaseDatabase = FirebaseDatabase.getInstance();
        databaseReference = firebaseDatabase.getReference("Job Applications");

        Query query = databaseReference.orderByChild(String.valueOf(maxid+1)).equalTo(user.getUid());
        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot ds: dataSnapshot.getChildren()){
                    Post p = ds.getValue(Post.class);
                    posts.add(p);
                }
                pd.dismiss();
                adap = new MyAdap(Applications.this, posts);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                pd.dismiss();
            }
        });
    }
}
</code>```

Posts.java

```<code>    public class Post {
    private String jobtitle, jobtype, company, location;

    public Post() {
    }

    public Post(String jobtitle, String jobtype, String company, String location) {
        this.jobtitle = jobtitle;
        this.jobtype = jobtype;
        this.company = company;
        this.location = location;
    }

    public String getJobtitle() {
        return jobtitle;
    }

    public void setJobtitle(String jobtitle) {
        this.jobtitle = jobtitle;
    }

    public String getJobtype() {
        return jobtype;
    }

    public void setJobtype(String jobtype) {
        this.jobtype = jobtype;
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    public String getLocation() {
        return location;
    }

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

MyAdap.java

```<code>import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class MyAdap extends RecyclerView.Adapter<MyAdap.ViewHolder> {

    Context cb;
    ArrayList<Post> posts;

    public MyAdap(Context c, ArrayList<Post> applications){
        cb=c;
        posts=applications;
    }
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(cb).inflate(R.layout.post, parent,false));
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.jobTitle.setText(posts.get(position).getJobtitle());
        holder.jobType.setText(posts.get(position).getJobtype());
        holder.location.setText(posts.get(position).getLocation());
        holder.companyName.setText(posts.get(position).getCompany());
    }

    @Override
    public int getItemCount() {
        return posts.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        TextView jobTitle, jobType,companyName,location;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            jobTitle = itemView.findViewById(R.id.jobTitle);
            jobType = itemView.findViewById(R.id.jobType);
            companyName = itemView.findViewById(R.id.companyName);
            location = itemView.findViewById(R.id.location);
        }
    }
}
</code>```

Here is the image of the database.

答: As said by abdul add the adapter to the recycler view and also add the android lifecycle method onStart(); method and in the add adapter.startlisteneing();</p>

Body:
I am developing an android app which shows the user with the latest jobs from various fields. I want to display the jobs that the user has applied so far in "Your Applications" section.

But the values are not getting retrieved. It displays a blank activity. I have attached the code.

Applications.java

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Application;
import android.app.ProgressDialog;
import android.os.Bundle;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

public class Applications extends AppCompatActivity {

    DatabaseReference databaseReference;
    FirebaseDatabase firebaseDatabase;
    RecyclerView recyclerView;
    FirebaseUser user;
    FirebaseAuth mAuth;
    ArrayList<Post> posts;
    MyAdap adap;
    ProgressDialog pd;
    long maxid=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_applications);
        recyclerView = findViewById(R.id.work);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAuth = FirebaseAuth.getInstance();
        user = mAuth.getCurrentUser();
        posts = new ArrayList<>();
        pd= new ProgressDialog(Applications.this);
        pd.setMessage("Loading...");
        pd.show();

        getSupportActionBar().setTitle("Your Applications");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        firebaseDatabase = FirebaseDatabase.getInstance();
        databaseReference = firebaseDatabase.getReference("Job Applications");

        Query query = databaseReference.orderByChild(String.valueOf(maxid+1)).equalTo(user.getUid());
        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot ds: dataSnapshot.getChildren()){
                    Post p = ds.getValue(Post.class);
                    posts.add(p);
                }
                pd.dismiss();
                adap = new MyAdap(Applications.this, posts);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                pd.dismiss();
            }
        });
    }
}

Posts.java

    public class Post {
    private String jobtitle, jobtype, company, location;

    public Post() {
    }

    public Post(String jobtitle, String jobtype, String company, String location) {
        this.jobtitle = jobtitle;
        this.jobtype = jobtype;
        this.company = company;
        this.location = location;
    }

    public String getJobtitle() {
        return jobtitle;
    }

    public void setJobtitle(String jobtitle) {
        this.jobtitle = jobtitle;
    }

    public String getJobtype() {
        return jobtype;
    }

    public void setJobtype(String jobtype) {
        this.jobtype = jobtype;
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

MyAdap.java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class MyAdap extends RecyclerView.Adapter<MyAdap.ViewHolder> {

    Context cb;
    ArrayList<Post> posts;

    public MyAdap(Context c, ArrayList<Post> applications){
        cb=c;
        posts=applications;
    }
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(cb).inflate(R.layout.post, parent,false));
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.jobTitle.setText(posts.get(position).getJobtitle());
        holder.jobType.setText(posts.get(position).getJobtype());
        holder.location.setText(posts.get(position).getLocation());
        holder.companyName.setText(posts.get(position).getCompany());
    }

    @Override
    public int getItemCount() {
        return posts.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        TextView jobTitle, jobType,companyName,location;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            jobTitle = itemView.findViewById(R.id.jobTitle);
            jobType = itemView.findViewById(R.id.jobType);
            companyName = itemView.findViewById(R.id.companyName);
            location = itemView.findViewById(R.id.location);
        }
    }
}

Here is the image of the database.


问:
c++ - error C3646: unknown override specifier
I modified my project and after compiling there pop up some weird error.

```<code>#ifndef BART_RAY_TRACER_MESH_H
#define BART_RAY_TRACER_MESH_H

#include <vector>
#include "assert.h"
#include "vec3f.h"

class Triangle;

class Mesh {
public:
    uint32_t nverts;
    bool _is_static;
    vec3f *verts;
    vec3f *_verts_world;
    Material material;
    // 2 error occurs at the line below
    Matrix4x4 _trans_local_to_world; // '_trans_local_to_world': unknown override specifier & missing type specifier - int assumed. Note: C++ does not support default-int
    Matrix4x4 _trans_local_to_world_inv;
    TransformHierarchy *_trans_hierarchy;

    std::vector<Triangle* > triangles;
    // ...
};
#endif
</code>```

When I change the order of the declaration a little bit, the error always occurs the line after Material material, but with different message:

```<code>#ifndef BART_RAY_TRACER_MESH_H
#define BART_RAY_TRACER_MESH_H

#include <vector>
#include "assert.h"
#include "vec3f.h"

class Triangle;

class Mesh {
public:
    uint32_t nverts;
    bool _is_static;
    vec3f *verts;
    vec3f *_verts_world;
    Material material;
    // 2 error occurs at the line below
    TransformHierarchy *_trans_hierarchy; // error C2143: syntax error: missing ';' before '*' & error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
    Matrix4x4 _trans_local_to_world;
    Matrix4x4 _trans_local_to_world_inv;

    std::vector<Triangle* > triangles;
    // ...
};
#endif
</code>```

I've searched for similar questions on SO but none seems useful.
I've checked my vec3f, Triangle class definition in case there are missing semicolons but I can't find any.

Can any one help?

答:
In my case, it was found that a header file had the following directives for a class [ie, myComboBoxData]

```<code>#ifndef __COMBOBOXDATA__
#define __COMBOBOXDATA__
// ...
class myComboBoxData
{
    // ...
}
#endif
</code>```

As another class below tried to use myComboBoxData class

```<code>class TypeDlg : public CDialog
{
    myComboBoxData cbRow,cbCol;
    // ...
}
</code>```

the error message popped up as above:

"error C3646: 'cbRow': unknown override specifier".

Solution:

The problem was the directive name (__COMBOBOXDATA__) was already used by OTHER header.

Thus, make sure to use some other name like (__myCOMBOBOXDATA__).

Body:
I modified my project and after compiling there pop up some weird error.

#ifndef BART_RAY_TRACER_MESH_H
#define BART_RAY_TRACER_MESH_H

#include <vector>
#include "assert.h"
#include "vec3f.h"

class Triangle;

class Mesh {
public:
    uint32_t nverts;
    bool _is_static;
    vec3f *verts;
    vec3f *_verts_world;
    Material material;
    // 2 error occurs at the line below
    Matrix4x4 _trans_local_to_world; // '_trans_local_to_world': unknown override specifier & missing type specifier - int assumed. Note: C++ does not support default-int
    Matrix4x4 _trans_local_to_world_inv;
    TransformHierarchy *_trans_hierarchy;

    std::vector<Triangle* > triangles;
    // ...
};
#endif

When I change the order of the declaration a little bit, the error always occurs the line after Material material, but with different message:

#ifndef BART_RAY_TRACER_MESH_H
#define BART_RAY_TRACER_MESH_H

#include <vector>
#include "assert.h"
#include "vec3f.h"

class Triangle;

class Mesh {
public:
    uint32_t nverts;
    bool _is_static;
    vec3f *verts;
    vec3f *_verts_world;
    Material material;
    // 2 error occurs at the line below
    TransformHierarchy *_trans_hierarchy; // error C2143: syntax error: missing ';' before '*' & error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
    Matrix4x4 _trans_local_to_world;
    Matrix4x4 _trans_local_to_world_inv;

    std::vector<Triangle* > triangles;
    // ...
};
#endif

I've searched for similar questions on SO but none seems useful.
I've checked my vec3f, Triangle class definition in case there are missing semicolons but I can't find any.

Can any one help?

Body:
In my case, it was found that a header file had the following directives for a class [ie, myComboBoxData]

#ifndef __COMBOBOXDATA__
#define __COMBOBOXDATA__
// ...
class myComboBoxData
{
    // ...
}
#endif

As another class below tried to use myComboBoxData class

class TypeDlg : public CDialog
{
    myComboBoxData cbRow,cbCol;
    // ...
}

the error message popped up as above:

"error C3646: 'cbRow': unknown override specifier".

Solution:

The problem was the directive name (__COMBOBOXDATA__) was already used by OTHER header.

Thus, make sure to use some other name like (__myCOMBOBOXDATA__).


问:
Algorithm for finding the SumKSmallest
Can anyone help me solve this question in pseudocode?
Consider the function SumKSmallest(A[0..n − 1], k) that returns the sum of the k smallest elements in an unsorted integer array A of size n. For example, given the array A =[6,-6,3,2,1,2,0,4,3,5] and k =3, the function should return -5.
a. Write an algorithm in pseudocode for SumKSmallest using the brute force paradigm. Indicate and justify (within a few sentences) the time complexity of your algorithm.b. Write another algorithm in pseudocode for SumKSmalleast using the transform & conquer paradigm. Your algorithm should strictly run in O(n log n) time. Justify the time complexity of your algorithm. c. Explain with details, how we could implement another SumKSmalleast that strictly runs in less than O(n log n) time, considering k<

答:
Brute force
O(n^2) You got it right.

Second Approach:
Sort the array and sum the first k numbers to get the sum of the smallest K numbers. O(nlog(n)) Merge Sort.

Third Approach:
Heap: Take the first K elements and Max-heapify it. Now iterate over remaining elements taking them one by one and comparing it with the root of max-heap (arr[0]), if (arr[0] > element) remove arr[0] from the heap and add an element into heap. At last, you will be left with K smallest numbers of the array.
O(k + (n-k)log(k))

Read about Min-heap and Max-heap

Title: Algorithm for finding the SumKSmallest

Body:
<p>Can anyone help me solve this question in pseudocode?
Consider the function SumKSmallest(A[0..n − 1], k) that returns the sum of the k smallest elements in an unsorted integer array A of size n. For example, given the array A =[6,-6,3,2,1,2,0,4,3,5] and k =3, the function should return -5.
a. Write an algorithm in pseudocode for SumKSmallest using the brute force paradigm. Indicate and justify (within a few sentences) the time complexity of your algorithm.b. Write another algorithm in pseudocode for SumKSmalleast using the transform & conquer paradigm. Your algorithm should strictly run in O(n log n) time. Justify the time complexity of your algorithm. c. Explain with details, how we could implement another SumKSmalleast that strictly runs in less than O(n log n) time, considering k<


问:
Union intersected nested lists in python
I am looking for an efficient way to union intersected nested lists.
Ex:

```<code>input: [[1,2,3], [5,3,7],[8,9]]
output: [[1,2,3,5,7],[8,9]]
</code>```

Note: assume more than three nested lists

Current implementation:
Loop over each nested list --> loop over all lists --> if there is an intersection, union and delete old list -- do that until no intersection.

答: Ok. So I thought of something else: this problem reduces to finding the connected components in a (particular bipartite) graph: You have two types of vertices: 1. sublists 2. elements of those sublists. There is an edge from a sublist to an element iff that sublist contains that element. There are well known and efficient algorithms for finding the connect components of a graph, so I will not reiterate them here.</p>

Body:
I am looking for an efficient way to union intersected nested lists.
Ex:

input: [[1,2,3], [5,3,7],[8,9]]
output: [[1,2,3,5,7],[8,9]]

Note: assume more than three nested lists

Current implementation:
Loop over each nested list --> loop over all lists --> if there is an intersection, union and delete old list -- do that until no intersection.


问:
php asynchronous cURL request
I am developing a website with PHP and sending requests with cURL.

I have a website, that does some calculations, that I need to get a response from. I am sending requests via cURL Currently what I'm doing is to send a request, wait 10 sec and send it again (max 3 times), if no "good" response is received. If all request fail, I flag them for "manual fix".

The thing is I want to send a request with 30 sec timeout, and on the 10th second, if no response is received, to send another one with 20 sec timeout, on the 20th second to send last one with 10 sec timeout. Is such thing possible?

Or if my current code remains and I continue to send requests every 10th second with timeout 10 sec each, can I continue to listen to the first one after I send the second (and first and second when I'm sending the third)?

Thank you in advance!

答:
If you want to send multiple curl requests parallely, curl_multi will be helpful as below:

```<code>// create both cURL resources
$ch1 = curl_init();
$ch2 = curl_init();

// set URL and other appropriate options
curl_setopt($ch1, CURLOPT_URL, "http://lxr.php.net/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

//create the multiple cURL handle
$mh = curl_multi_init();

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

//execute the multi handle
do {
    $status = curl_multi_exec($mh, $active);
    if ($active) {
        curl_multi_select($mh);
    }
} while ($active && $status == CURLM_OK);

//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);
</code>```

You can customize this code ex. use loop for creating curl requests etc.

Ref : https://www.php.net/manual/en/function.curl-multi-init.php

Title: php asynchronous cURL request

Body:
If you want to send multiple curl requests parallely, curl_multi will be helpful as below:

// create both cURL resources
$ch1 = curl_init();
$ch2 = curl_init();

// set URL and other appropriate options
curl_setopt($ch1, CURLOPT_URL, "http://lxr.php.net/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

//create the multiple cURL handle
$mh = curl_multi_init();

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

//execute the multi handle
do {
    $status = curl_multi_exec($mh, $active);
    if ($active) {
        curl_multi_select($mh);
    }
} while ($active && $status == CURLM_OK);

//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

You can customize this code ex. use loop for creating curl requests etc.

Ref : https://www.php.net/manual/en/function.curl-multi-init.php


问:
PROC SQL MERGE MISMATCH
ATTACHED SCREENSHOT OF DESIRED OUTPUTthe required condition is
 "SUBJECT in A = SUBJECT in B
and
VISIT in A NE(not equal to) VISIT in B"

I would like to find the exact mismatch and missing VISIT from the below Tables A and B by using Proc SQL procedure, Can anyone help me please?

Table A

```<code>SUBJECT Test    VISIT
1001    ABCB    1
1001    ABCD    2
1001    ABCD    3
1001    ABCD    5
</code>```

Table B

```<code>SUBJECT Test    VISIT1
1001    ABCD    2
1001    ABCD    1
1001    ABCD    4
</code>```

Expected output:

```<code>SUBJECT Test    VISIT   VISIT1
1001    ABCD    3
1001    ABCD    5
1001    ABCD            4
</code>```

VISIT 3 AND 5 IS PRESENT IN DATASET A NOT IN B AND VISIT 4 IS PRESENT IN DATASET2 NOT IN DATASET A , LIKE WISE
CODE FOR DATASET-

```<code>DATA A;
  LENGTH SUBJECT 8 Test $10 visit 8;
  INPUT SUBJECT Test $ visit ;
  DATALINES;
  1001 ABCD 1
  1001 ABCD 2
  1001 ABCD 3
  1001 ABCD 5
;
RUN;

DATA B;
  LENGTH SUBJECT 8 Test $10 visit1 8;
  INPUT SUBJECT Test $ visit1 ;
  DATALINES;
  1001 ABCD 2
  1001 ABCD 1
  1001 ABCD 4
;
RUN;
</code>```

Thanks in advance!

the code i tried is below (but not working as expected)-

```<code>    ****************(VISIT ) in A and not in B****;
proc sql;
create table SS1 as
select distinct a.* FROM
A a where a.visit not in(select s.visit1 from B s WHERE A.SUBJECT = S.SUBJECT );

create  table   INRAVE as
select * from SS1 A
left join
B B
on a.subject=b.SUBJECT  and a.VISIT NE b.VISIT1
where   b.SUBJECT is not  null
;
quit;
****************VISIT in B and not in A****;
proc sql;
create table SS2 as
select distinct a.* from
B a where a.VISIT1 not in(select S.VISIT from A s WHERE A.SUBJECT = S.SUBJECT );

create  table   INVENDOR as
select * from SS2 A
left join
A B
on a.subject=b.SUBJECT  and a.VISIT1 NE b.VISIT
where   b.SUBJECT is not  null
;
quit;

data ALL;;
set inrave invendor;
where subject=subject ;
RUN;
</code>```

答:
Seems you know SQL very well, why not try union all, just like this:

```<code>proc sql noprint;
    create table C as
    select *, 'A' as Source from A
    where catx('@',SUBJECT,Test,visit) not in (
        select distinct catx('@',SUBJECT,Test,visit1) from B
    )
    union all corr
    select *, 'B' as Source from B(rename=VISIT1=VISIT)
    where catx('@',SUBJECT,Test,visit) not in (
        select distinct catx('@',SUBJECT,Test,visit) from A
    )
    ;

    create table D(drop=TmpVISIT Source) as
    select *,
        case when Source = 'B' then . else TmpVISIT end as VISIT,
        case when Source = 'B' then TmpVISIT else . end as VISIT1
    from C(rename=VISIT=TmpVISIT);
quit;
</code>```

I get all obs from dataset A where not repeat in dataset B and do the oppsite with dataset B.

Well, I also get another solution, which is shorter:

```<code>proc sql noprint;
    select catx('@',SUBJECT,Test,visit) into :Ununique separated by '" "' from (
        select * from A union all select * from B(rename=visit1=visit)
    )
    group by SUBJECT, Test, visit
    having count(*) > 1;
quit;

data D;
    set A B;
    if catx('@',SUBJECT,Test,coalesce(visit1,visit)) in ("&Ununique") then delete;
run;
</code>```

Whereas, this method is limited by the max lenth of macro variable.

Title: PROC SQL MERGE MISMATCH

Body:
ATTACHED SCREENSHOT OF DESIRED OUTPUTthe required condition is
 "SUBJECT in A = SUBJECT in B
and
VISIT in A NE(not equal to) VISIT in B"

I would like to find the exact mismatch and missing VISIT from the below Tables A and B by using Proc SQL procedure, Can anyone help me please?

Table A

SUBJECT Test    VISIT
1001    ABCB    1
1001    ABCD    2
1001    ABCD    3
1001    ABCD    5

Table B

SUBJECT Test    VISIT1
1001    ABCD    2
1001    ABCD    1
1001    ABCD    4

Expected output:

SUBJECT Test    VISIT   VISIT1
1001    ABCD    3
1001    ABCD    5
1001    ABCD            4

VISIT 3 AND 5 IS PRESENT IN DATASET A NOT IN B AND VISIT 4 IS PRESENT IN DATASET2 NOT IN DATASET A , LIKE WISE
CODE FOR DATASET-

DATA A;
  LENGTH SUBJECT 8 Test $10 visit 8;
  INPUT SUBJECT Test $ visit ;
  DATALINES;
  1001 ABCD 1
  1001 ABCD 2
  1001 ABCD 3
  1001 ABCD 5
;
RUN;

DATA B;
  LENGTH SUBJECT 8 Test $10 visit1 8;
  INPUT SUBJECT Test $ visit1 ;
  DATALINES;
  1001 ABCD 2
  1001 ABCD 1
  1001 ABCD 4
;
RUN;

Thanks in advance!

the code i tried is below (but not working as expected)-

    ****************(VISIT ) in A and not in B****;
proc sql;
create table SS1 as
select distinct a.* FROM
A a where a.visit not in(select s.visit1 from B s WHERE A.SUBJECT = S.SUBJECT );

create  table   INRAVE as
select * from SS1 A
left join
B B
on a.subject=b.SUBJECT  and a.VISIT NE b.VISIT1
where   b.SUBJECT is not  null
;
quit;
****************VISIT in B and not in A****;
proc sql;
create table SS2 as
select distinct a.* from
B a where a.VISIT1 not in(select S.VISIT from A s WHERE A.SUBJECT = S.SUBJECT );

create  table   INVENDOR as
select * from SS2 A
left join
A B
on a.subject=b.SUBJECT  and a.VISIT1 NE b.VISIT
where   b.SUBJECT is not  null
;
quit;

data ALL;;
set inrave invendor;
where subject=subject ;
RUN;

Body:
Seems you know SQL very well, why not try union all, just like this:

proc sql noprint;
    create table C as
    select *, 'A' as Source from A
    where catx('@',SUBJECT,Test,visit) not in (
        select distinct catx('@',SUBJECT,Test,visit1) from B
    )
    union all corr
    select *, 'B' as Source from B(rename=VISIT1=VISIT)
    where catx('@',SUBJECT,Test,visit) not in (
        select distinct catx('@',SUBJECT,Test,visit) from A
    )
    ;

    create table D(drop=TmpVISIT Source) as
    select *,
        case when Source = 'B' then . else TmpVISIT end as VISIT,
        case when Source = 'B' then TmpVISIT else . end as VISIT1
    from C(rename=VISIT=TmpVISIT);
quit;

I get all obs from dataset A where not repeat in dataset B and do the oppsite with dataset B.

Well, I also get another solution, which is shorter:

proc sql noprint;
    select catx('@',SUBJECT,Test,visit) into :Ununique separated by '" "' from (
        select * from A union all select * from B(rename=visit1=visit)
    )
    group by SUBJECT, Test, visit
    having count(*) > 1;
quit;

data D;
    set A B;
    if catx('@',SUBJECT,Test,coalesce(visit1,visit)) in ("&Ununique") then delete;
run;

Whereas, this method is limited by the max lenth of macro variable.


问:
GCC inline assembly error: asm-specifier for variable '%al' conflicts with asm clobber list
Sorry for so many questions, but I've encountered yet another cryptic error trying to compile the following inline assembly (with -fasm-blocks) which works in MSVC, but apparently not in GCC and wasn't able to deal with it:

```<code>unsigned char testData = 128;

__asm
{
    // ...
    mov al, testData
    mov ah, al // error: asm-specifier for variable '%al' conflicts with asm clobber list
    shl eax, 16
    // ...
};
</code>```

What is this clobber list and what is wrong with it?

I also tried to change optimization level, but it had no effect.

答:
the clobber-list is explained here: http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html, but not in the context of your __asm syntax, with which I'm not familiar. Trying to compile your snippet I get </p>

```<code>jcomeau@intrepid:/tmp$ make test
cc     test.c   -o test
test.c:4: error: expected ‘(’ before ‘{’ token
</code>```

Body:
Sorry for so many questions, but I've encountered yet another cryptic error trying to compile the following inline assembly (with -fasm-blocks) which works in MSVC, but apparently not in GCC and wasn't able to deal with it:

unsigned char testData = 128;

__asm
{
    // ...
    mov al, testData
    mov ah, al // error: asm-specifier for variable '%al' conflicts with asm clobber list
    shl eax, 16
    // ...
};

What is this clobber list and what is wrong with it?

I also tried to change optimization level, but it had no effect.

Body:
the clobber-list is explained here: http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html, but not in the context of your __asm syntax, with which I'm not familiar. Trying to compile your snippet I get

jcomeau@intrepid:/tmp$ make test
cc     test.c   -o test
test.c:4: error: expected ‘(’ before ‘{’ token


问:
Write a code that Calculates the average number of non-zero ratings per individual in our data set
So I've written my code below but I am having a hard time getting the code to not include the number of zeros. It runs but unfortunately not the way I want it to. Can anyone shed some light?

the variable movies is basically a list of movies we were given  The code will be right if an average of 21.4 is the output.

```<code>all_ratings =[
[5,5,4,4,3,1,2,3,4,4,4,3,4,0,0,0,1,2,3,4,4,4,1,4,0,0,0,1,2,5],
[5,0,1,2,3,1,2,3,4,4,4,5,4,2,1,0,1,2,0,5,0,4,1,4,2,0,0,1,0,5],
[5,2,3,4,4,0,0,0,4,5,0,3,0,0,0,3,4,0,1,4,4,4,0,4,0,3,0,1,2,5],
[5,0,4,0,0,4,2,3,0,0,4,0,3,0,1,0,1,2,3,0,2,0,1,0,0,0,4,0,1,5],
[5,4,3,2,1,1,2,3,4,3,4,3,4,0,3,0,1,2,4,4,4,4,1,4,0,0,0,1,2,5],
]

total=[]
average=[]

for index in range (len(all_ratings)):
    total+=[sum(all_ratings[index])]

for index in range(len(all_ratings)):
    average = average + [total[index]/30]

for index in range(len(movies)):
    print(average)
</code>```

Body:
So I've written my code below but I am having a hard time getting the code to not include the number of zeros. It runs but unfortunately not the way I want it to. Can anyone shed some light?

the variable movies is basically a list of movies we were given  The code will be right if an average of 21.4 is the output.

all_ratings =[
[5,5,4,4,3,1,2,3,4,4,4,3,4,0,0,0,1,2,3,4,4,4,1,4,0,0,0,1,2,5],
[5,0,1,2,3,1,2,3,4,4,4,5,4,2,1,0,1,2,0,5,0,4,1,4,2,0,0,1,0,5],
[5,2,3,4,4,0,0,0,4,5,0,3,0,0,0,3,4,0,1,4,4,4,0,4,0,3,0,1,2,5],
[5,0,4,0,0,4,2,3,0,0,4,0,3,0,1,0,1,2,3,0,2,0,1,0,0,0,4,0,1,5],
[5,4,3,2,1,1,2,3,4,3,4,3,4,0,3,0,1,2,4,4,4,4,1,4,0,0,0,1,2,5],
]

total=[]
average=[]

for index in range (len(all_ratings)):
    total+=[sum(all_ratings[index])]

for index in range(len(all_ratings)):
    average = average + [total[index]/30]

for index in range(len(movies)):
    print(average)

Body:
Perhaps this might be a solution.

all_ratings =[
[5,5,4,4,3,1,2,3,4,4,4,3,4,0,0,0,1,2,3,4,4,4,1,4,0,0,0,1,2,5],
[5,0,1,2,3,1,2,3,4,4,4,5,4,2,1,0,1,2,0,5,0,4,1,4,2,0,0,1,0,5],
[5,2,3,4,4,0,0,0,4,5,0,3,0,0,0,3,4,0,1,4,4,4,0,4,0,3,0,1,2,5],
[5,0,4,0,0,4,2,3,0,0,4,0,3,0,1,0,1,2,3,0,2,0,1,0,0,0,4,0,1,5],
[5,4,3,2,1,1,2,3,4,3,4,3,4,0,3,0,1,2,4,4,4,4,1,4,0,0,0,1,2,5],
]

def get_average(vals): # without zero
    counter = 0
    total = 0
    for i in range(len(vals)):
        if (vals[i] != 0):
            counter += 1
        total += vals[i]
    return round(total / counter, 2)

for i in range(len(all_ratings)):
    print(get_average(all_ratings[i]))

Update: I guess 21.4 would be the average number of movies that were rated in each list of ratings. The code below returns 21.4

counter = 0;

for index, item in np.ndenumerate(all_ratings):
    if item != 0:
        counter += 1

print(counter / 5)


问:
Can't use with import in Pytorch
When I import torch, there's a problem like this:

```<code>C: lUsers / ruiha Desktopl flappy_DQL>python flappy.py
Traceback (most recent call last):
File "flappy.py", line 2, in <module>
import torch
File "C: IUsers I rui ha /AppDat a / Local Programs I Python/ Python37 libIsite-packagesI torchl__init__.py", line 81, in <mod
ctypes.CDLL(dll)
File "C: LUsersI ruiha lAppDat a l Local | Programs I Python/ Python37 liblctypesl__init_.py", line 364, in _init_
self._handle = _dlopen(self._name, mode)
OSError: [WinError 126] The specified module could not be found
</code>```

答:
Where are you doing your development? I ask because I see that you are on Windows, where it is much more difficult to manage dll files (compared to Linux). Thus, I would avoid setting up your own bare environment (it would require debugging your OS) and use Anaconda, a Python manager with a focus on scientific computing. Install Anaconda, setup an environment (this is a 'virtual' environment managed by Anaconda), and you will be ready. Simply install torch by

conda install PyTorch -c PyTorch

You can then continue writing your ML app on Jupyter, terminal, etc. by using the Conda runtime to execute your file.

Title: Can't use with import in Pytorch

Body:
When I import torch, there's a problem like this:

C: lUsers / ruiha Desktopl flappy_DQL>python flappy.py
Traceback (most recent call last):
File "flappy.py", line 2, in <module>
import torch
File "C: IUsers I rui ha /AppDat a / Local Programs I Python/ Python37 libIsite-packagesI torchl__init__.py", line 81, in <mod
ctypes.CDLL(dll)
File "C: LUsersI ruiha lAppDat a l Local | Programs I Python/ Python37 liblctypesl__init_.py", line 364, in _init_
self._handle = _dlopen(self._name, mode)
OSError: [WinError 126] The specified module could not be found


问:
Set navigation bar item style in SwiftUI
When adding a navigation bar item with UIKit, you set its style with UIBarButtonItem.style. This is important for a Done button, which is displayed with bold text.

SwitftUI's navigationBarItems(leading:trailing:) takes a View but no style. You could hack a style look-alike by using a bold button in the view, but it won't adjust to future OS style changes (e.g. a font weight other than bold).

How do you set the navigation bar item's style with SwiftUI?

答:
in SwiftUI instead of passing a style you append it to the View component. this will adjust to future OS style changes:</p>

```<code>import SwiftUI
import PlaygroundSupport

struct ContentView: View {
  var body: some View{
    NavigationView {
      Text("blah")
        .navigationBarItems(leading: Text("done button")
          .fontWeight(.medium)
          .bold()
          .foregroundColor(Color.red))
    }
  }
}

PlaygroundPage.current.setLiveView(ContentView())

</code>```

Body:
in SwiftUI instead of passing a style you append it to the View component. this will adjust to future OS style changes:

import SwiftUI
import PlaygroundSupport

struct ContentView: View {
  var body: some View{
    NavigationView {
      Text("blah")
        .navigationBarItems(leading: Text("done button")
          .fontWeight(.medium)
          .bold()
          .foregroundColor(Color.red))
    }
  }
}

PlaygroundPage.current.setLiveView(ContentView())


问:
Unable to create a required list of a given size
```<code>a=[[None]*3]
a=a*3
k=0
for i in range(3):
    for j in range(3):
        a[i][j]=k
        print(a)
        k=k+1
print(a)
</code>```

I want the output to be [[0,1,2],[3,4,5],[6,7,8]]. What I am getting
  is [[6,7,8],[6,7,8],[6,7,8]]

答:
You need to copy each list from a because when using multiple it creates a copy of each list that references to the same list so this way you are getting 3 identical lists that only the last iteration value is in it.

```<code>a=[[],[],[]]
a=[a[:], a[:], a[:]]
k=0
for i in range(3):
    for j in range(3):
        a[i][j]=k
        k+=1
print(a)
</code>```

Output

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

Body:
a=[[None]*3]
a=a*3
k=0
for i in range(3):
    for j in range(3):
        a[i][j]=k
        print(a)
        k=k+1
print(a)

I want the output to be [[0,1,2],[3,4,5],[6,7,8]]. What I am getting
  is [[6,7,8],[6,7,8],[6,7,8]]

Body:
You need to copy each list from a because when using multiple it creates a copy of each list that references to the same list so this way you are getting 3 identical lists that only the last iteration value is in it.

a=[[],[],[]]
a=[a[:], a[:], a[:]]
k=0
for i in range(3):
    for j in range(3):
        a[i][j]=k
        k+=1
print(a)

Output

[[0, 1, 2], [3, 4, 5], [6, 7, 8]]


答:
Mistake is Reference Change of a Variable which impacts every list element.
Go with the following approach.</p>

```<code>n,m = 3, 3
a = [[0] * m for i in range(n)]
k=0
for i in range(3):
    for j in range(3):
        a[i][j]=k
        k=k+1
print(a)
</code>```

Title: Unable to create a required list of a given size

Body:
Mistake is Reference Change of a Variable which impacts every list element.
Go with the following approach.

n,m = 3, 3
a = [[0] * m for i in range(n)]
k=0
for i in range(3):
    for j in range(3):
        a[i][j]=k
        k=k+1
print(a)


问:
Problem in Data display from database using datagridview in vb.net
Im using vb.net windows forms, VS 2019, .net framework 4.7.2 and mysql.

I tried datagridview in a form to display data from my database and its working perfectly fine.

But,

when i tried to use the same procedure, displaying data from the same database using datagridview in a child form (which i call via parent form that docks the child form over a region in parent form), it is not displaying any data, while the query works perfectly fine, its updating the data in database, but the data isn't displaying in this parent-child case.

Tho, the same code works perfectly fine and displays data if its used in a separate form.

I don't know what is the problem actually.

I had to attach more than one picture to explain clearly so i uploaded them and the link is given as:

https://imgur.com/a/6xka1B4

But, i have merged all the snips of the code from different forms as well:

1 The sub-class Custom_LoadDataGrid is called here and working correctly and displaying data in the gridview

```<code> DB.Custom_LoadDataGrid("SELECT item_name as 'NAME', item_price as 'PRICE', quantity as 'QUANTITY', Amount as 'AMOUNT' FROM transaction WHERE client_name ='" + Label11.Text.ToString + "'")
 DB.myConnection.Close()
</code>```

2  The sub Custom_LoadDataGrid which was called above

```<code>Public Sub Custom_LoadDataGrid(ByVal search As String)

    Try
        connString = "server=127.0.0.1;Port=3306;Database=smartcart;Uid=root;Pwd="

        myConnection.ConnectionString = connString
        myConnection.Open()

        sql = search.ToString

        DataAdapter = New MySqlDataAdapter(sql, myConnection)
        Datacmd = New MySqlCommand(sql, myConnection)
        DataAdapter.Fill(DataSet, DbName)
        MaxRows = DataSet.Tables(DbName).Rows.Count

        Dim dt1 As New DataTable
        DataSet.Tables.Add(dt1)
        DataAdapter.Fill(dt1)
        Portal.Guna2DataGridView1.DataSource = dt1.DefaultView
        ReleaseDb()

    Catch ex As Exception
        MsgBox("Something went wrong")
    End Try

End Sub
</code>```

3  i made this sub-class to call child forms and dock in the region somewhere in the parent forms

```<code>Private Sub OpenChildForm(childForm As Form)

    'Open only form'
    If currentChildForm IsNot Nothing Then
        currentChildForm.Close()
    End If
    currentChildForm = childForm
    'end'
    childForm.TopLevel = False
    childForm.FormBorderStyle = FormBorderStyle.None
    childForm.Dock = DockStyle.Fill
    Controls_panel.Controls.Add(childForm)
    Controls_panel.Tag = childForm
    childForm.BringToFront()
    childForm.Show()

End Sub
</code>```

4  here the child form is called

```<code>Private Sub Stock_manag_button_Click(sender As Object, e As EventArgs) Handles Stock_manag_button.Click

    Sub_menu_panel.Hide()
    ActivateButton(sender)
    OpenChildForm(New Stock_management)

End Sub
</code>```

5  This sub-class Custom_Load_DataGrid is called here but is not displaying data in gridview

```<code>    DB.Custom_Load_DataGrid("SELECT * FROM addition_stock ")
    DB.myConnection.Close()
</code>```

'6  the sub-class Custom_Load_DataGrid is exactly same as Custom_LoadDataGrid (but obviously with different variables and relavent form name)
but this is not displaying data in gridview just in this this case of parent-child forms tho this one works fine too when used for seperate
forms.

```<code>Public Sub Custom_Load_DataGrid(ByVal search As String)

    Try
        connString = "server=127.0.0.1;Port=3306;Database=smartcart;Uid=root;Pwd="

        myConnection.ConnectionString = connString
        myConnection.Open()

        sql = search.ToString

        DataAdapter = New MySqlDataAdapter(sql, myConnection)
        Datacmd = New MySqlCommand(sql, myConnection)
        DataAdapter.Fill(DataSet, DbName)
        MaxRows = DataSet.Tables(DbName).Rows.Count
        MsgBox(MaxRows.ToString)
        Dim dt2 As New DataTable
        DataSet.Tables.Add(dt2)
        DataAdapter.Fill(dt2)
        Stock_addition.Guna2DataGridView1.DataSource = dt2.DefaultView
        ReleaseDb()

    Catch ex As Exception
        MsgBox("Something went wrong")
    End Try

End Sub
</code>```

答:
Can I get you to do this, in a new project, as a mini tutorial to make your life easier:

make a new project

Add a Form

Add a DataSet

Open the DataSet, right click in the surface and add a tableadapter

create a connection string to store in the settings: Pick mysql connector (note for this to work you need mysql connector AND ALSO mysql for visual studio https://dev.mysql.com/downloads/windows/visualstudio/ ) and fill in the details to create a database connection string  make sure the test connection succeeds

proceed through the wizard choosing "query that returns rows", "by sql", enter a query of SELECT * FROM addition_stock WHERE ID = @id

write names of FillByID, and GetDataByID

finish

You'll see something that looks like a database table appear, with a thing called addition_stockTableAdapter underneath it

Right click the tableadapter, choose add .. query

add another query that is more relevant to how you will search this table, like maybe SELECT * FROM addition_stock WHERE stock_code = @stockCode

call it FillByStockCode/GetDataByStockCode

always give relevant names to your fill/get data methods

Always make the first query that creates the datatable/tableadapter pair a "select where id =" - it makes things easier later on. Add as many additional queries as you will need

Do the same thing again (Add a tableadapter) this time with a table that is either a parent or a child of addition_stock - it doesn't matter which, I'm just trying to demonstrate something here. Make sure you use a table that has a foreign key in the database, to addition_stock

Once you add your other datatable/tableadapter pair that is related to addition_stock you will see a line connecting the two datatables

Right click this line and choose "show relation labels" to display the name of the relation - it comes from the foreign key in the database

Now we are going to add a convenience method to load child data based on the parent id

Right click your child tableadapter and choose Add Query

add a query of SELECT * FROM tablenamehere WHERE parentidcolumnnamehere = @parentid and call it a suitable FillByXxx - obviously Replace the table name, column name and xxx with real values

save your DataSet and switch to the forms designer

show the Data Sources window (view menu.. other windows)

expand all the nodes of your DataSet - you'll see a parent table and two child tables, one underneath the parent, one not

drag the parent table out of datasources and onto the form - a datagridview with columns will appear, as will a tableadapter, bindingnavigator, DataSet and a bindingsource in the tray at the bottom. The nav has a textbox you can write an id into and a button to press. The datagridview columns are set up appropriately and the grid is bound to the bindingsource. The bindingsource is bound to the DataSet parent table.

run the app, enter an ID in the textbox, click fill, edit the name of something, click save, go use mysql workbench to look in the db. Super; you can download, edit and save db data and you haven't written a single line of code; you're just using the thousands of lines of code visual studio has written for you.

stop the app, go back to the forms designer

drag the child table that is underneath the parent table onto the form. More items appear - a datagridview bound to another bindingsource, another navigator etc. You can delete this second navigator- we won't use it

take a look at the bindingsource of the child table - note that it is NOT bound directly to the DataSet but instead it is bound to the other bindingsource, with a DataMember property that is set to the name of the relation line between the two tables

switch to code view and look at the code of the Fill toolstripmenu that fills the parent record by the id/whatever. If there is any redundant code from the child bindingnavigator, remove it (or comment it out: it could be slightly useful for the next step

under the line of code that fills the parent datatable by id put the following code:

childTableAdapter.ClearBeforeFill = False
yourDatasetName.ChildTableName.Clear()
For Each parentRow in yourDataSetName.YourParentTableName
  childTableAdapter.FillByParentId(yourDataSetName.ChildTableName, parentRow.Id)
Next

Run the app again, enter the parent id, click fill. The parent data and the related child data loads. Great, but the real magic happens when we load multiple parent rows. Go back to code and swap the FillById on the parent tableadapter for the other query you write (if you didn't do one, go back to DataSet, Add a query to the parent table adapter that loads multiple rows, like select * from person where lastname = @lastname so we can enter a last name like smith, of which there are many) so now your code looks like this in the fill:

```<code>parentTableAdapter.FillBySonethingThatGetsMultipleRows(yourDataSetName.ParentTableName, fillByTextboxName.Text)

childTableAdapter.ClearBeforeFill = False
yourDatasetName.ChildTableName.Clear()
For Each parentRow in yourDataSetName.YourParentTableName
  childTableAdapter.FillByParentId(yourDataSetName.ChildTableName, parentRow.Id)
Next
</code>```

You'll note that you get multiple parent rows, you load multiple sets of child rows in the loop, but when you run the app and you choose a different parent in the parent grid the child grid automatically filters to show only the children of the currently selected parent

Body:
Im using vb.net windows forms, VS 2019, .net framework 4.7.2 and mysql.

I tried datagridview in a form to display data from my database and its working perfectly fine.

But,

when i tried to use the same procedure, displaying data from the same database using datagridview in a child form (which i call via parent form that docks the child form over a region in parent form), it is not displaying any data, while the query works perfectly fine, its updating the data in database, but the data isn't displaying in this parent-child case.

Tho, the same code works perfectly fine and displays data if its used in a separate form.

I don't know what is the problem actually.

I had to attach more than one picture to explain clearly so i uploaded them and the link is given as:

https://imgur.com/a/6xka1B4

But, i have merged all the snips of the code from different forms as well:

1 The sub-class Custom_LoadDataGrid is called here and working correctly and displaying data in the gridview

 DB.Custom_LoadDataGrid("SELECT item_name as 'NAME', item_price as 'PRICE', quantity as 'QUANTITY', Amount as 'AMOUNT' FROM transaction WHERE client_name ='" + Label11.Text.ToString + "'")
 DB.myConnection.Close()

2  The sub Custom_LoadDataGrid which was called above

Public Sub Custom_LoadDataGrid(ByVal search As String)

    Try
        connString = "server=127.0.0.1;Port=3306;Database=smartcart;Uid=root;Pwd="

        myConnection.ConnectionString = connString
        myConnection.Open()

        sql = search.ToString

        DataAdapter = New MySqlDataAdapter(sql, myConnection)
        Datacmd = New MySqlCommand(sql, myConnection)
        DataAdapter.Fill(DataSet, DbName)
        MaxRows = DataSet.Tables(DbName).Rows.Count

        Dim dt1 As New DataTable
        DataSet.Tables.Add(dt1)
        DataAdapter.Fill(dt1)
        Portal.Guna2DataGridView1.DataSource = dt1.DefaultView
        ReleaseDb()

    Catch ex As Exception
        MsgBox("Something went wrong")
    End Try

End Sub

3  i made this sub-class to call child forms and dock in the region somewhere in the parent forms

Private Sub OpenChildForm(childForm As Form)

    'Open only form'
    If currentChildForm IsNot Nothing Then
        currentChildForm.Close()
    End If
    currentChildForm = childForm
    'end'
    childForm.TopLevel = False
    childForm.FormBorderStyle = FormBorderStyle.None
    childForm.Dock = DockStyle.Fill
    Controls_panel.Controls.Add(childForm)
    Controls_panel.Tag = childForm
    childForm.BringToFront()
    childForm.Show()

End Sub

4  here the child form is called

Private Sub Stock_manag_button_Click(sender As Object, e As EventArgs) Handles Stock_manag_button.Click

    Sub_menu_panel.Hide()
    ActivateButton(sender)
    OpenChildForm(New Stock_management)

End Sub

5  This sub-class Custom_Load_DataGrid is called here but is not displaying data in gridview

    DB.Custom_Load_DataGrid("SELECT * FROM addition_stock ")
    DB.myConnection.Close()

'6  the sub-class Custom_Load_DataGrid is exactly same as Custom_LoadDataGrid (but obviously with different variables and relavent form name)
but this is not displaying data in gridview just in this this case of parent-child forms tho this one works fine too when used for seperate
forms.

Public Sub Custom_Load_DataGrid(ByVal search As String)

    Try
        connString = "server=127.0.0.1;Port=3306;Database=smartcart;Uid=root;Pwd="

        myConnection.ConnectionString = connString
        myConnection.Open()

        sql = search.ToString

        DataAdapter = New MySqlDataAdapter(sql, myConnection)
        Datacmd = New MySqlCommand(sql, myConnection)
        DataAdapter.Fill(DataSet, DbName)
        MaxRows = DataSet.Tables(DbName).Rows.Count
        MsgBox(MaxRows.ToString)
        Dim dt2 As New DataTable
        DataSet.Tables.Add(dt2)
        DataAdapter.Fill(dt2)
        Stock_addition.Guna2DataGridView1.DataSource = dt2.DefaultView
        ReleaseDb()

    Catch ex As Exception
        MsgBox("Something went wrong")
    End Try

End Sub

Body:
Can I get you to do this, in a new project, as a mini tutorial to make your life easier:

make a new project

Add a Form

Add a DataSet

Open the DataSet, right click in the surface and add a tableadapter

create a connection string to store in the settings: Pick mysql connector (note for this to work you need mysql connector AND ALSO mysql for visual studio https://dev.mysql.com/downloads/windows/visualstudio/ ) and fill in the details to create a database connection string  make sure the test connection succeeds

proceed through the wizard choosing "query that returns rows", "by sql", enter a query of SELECT * FROM addition_stock WHERE ID = @id

write names of FillByID, and GetDataByID

finish

You'll see something that looks like a database table appear, with a thing called addition_stockTableAdapter underneath it

Right click the tableadapter, choose add .. query

add another query that is more relevant to how you will search this table, like maybe SELECT * FROM addition_stock WHERE stock_code = @stockCode

call it FillByStockCode/GetDataByStockCode

always give relevant names to your fill/get data methods

Always make the first query that creates the datatable/tableadapter pair a "select where id =" - it makes things easier later on. Add as many additional queries as you will need

Do the same thing again (Add a tableadapter) this time with a table that is either a parent or a child of addition_stock - it doesn't matter which, I'm just trying to demonstrate something here. Make sure you use a table that has a foreign key in the database, to addition_stock

Once you add your other datatable/tableadapter pair that is related to addition_stock you will see a line connecting the two datatables

Right click this line and choose "show relation labels" to display the name of the relation - it comes from the foreign key in the database

Now we are going to add a convenience method to load child data based on the parent id

Right click your child tableadapter and choose Add Query

add a query of SELECT * FROM tablenamehere WHERE parentidcolumnnamehere = @parentid and call it a suitable FillByXxx - obviously Replace the table name, column name and xxx with real values

save your DataSet and switch to the forms designer

show the Data Sources window (view menu.. other windows)

expand all the nodes of your DataSet - you'll see a parent table and two child tables, one underneath the parent, one not

drag the parent table out of datasources and onto the form - a datagridview with columns will appear, as will a tableadapter, bindingnavigator, DataSet and a bindingsource in the tray at the bottom. The nav has a textbox you can write an id into and a button to press. The datagridview columns are set up appropriately and the grid is bound to the bindingsource. The bindingsource is bound to the DataSet parent table.

run the app, enter an ID in the textbox, click fill, edit the name of something, click save, go use mysql workbench to look in the db. Super; you can download, edit and save db data and you haven't written a single line of code; you're just using the thousands of lines of code visual studio has written for you.

stop the app, go back to the forms designer

drag the child table that is underneath the parent table onto the form. More items appear - a datagridview bound to another bindingsource, another navigator etc. You can delete this second navigator- we won't use it

take a look at the bindingsource of the child table - note that it is NOT bound directly to the DataSet but instead it is bound to the other bindingsource, with a DataMember property that is set to the name of the relation line between the two tables

switch to code view and look at the code of the Fill toolstripmenu that fills the parent record by the id/whatever. If there is any redundant code from the child bindingnavigator, remove it (or comment it out: it could be slightly useful for the next step

under the line of code that fills the parent datatable by id put the following code:

childTableAdapter.ClearBeforeFill = False
yourDatasetName.ChildTableName.Clear()
For Each parentRow in yourDataSetName.YourParentTableName
  childTableAdapter.FillByParentId(yourDataSetName.ChildTableName, parentRow.Id)
Next

Run the app again, enter the parent id, click fill. The parent data and the related child data loads. Great, but the real magic happens when we load multiple parent rows. Go back to code and swap the FillById on the parent tableadapter for the other query you write (if you didn't do one, go back to DataSet, Add a query to the parent table adapter that loads multiple rows, like select * from person where lastname = @lastname so we can enter a last name like smith, of which there are many) so now your code looks like this in the fill:

parentTableAdapter.FillBySonethingThatGetsMultipleRows(yourDataSetName.ParentTableName, fillByTextboxName.Text)

childTableAdapter.ClearBeforeFill = False
yourDatasetName.ChildTableName.Clear()
For Each parentRow in yourDataSetName.YourParentTableName
  childTableAdapter.FillByParentId(yourDataSetName.ChildTableName, parentRow.Id)
Next

You'll note that you get multiple parent rows, you load multiple sets of child rows in the loop, but when you run the app and you choose a different parent in the parent grid the child grid automatically filters to show only the children of the currently selected parent


答: Open the webpage in a popup window rather than normal window. So, that you can restrict the popup window from displaying buttons, menus, status and other features.

Title: Does anyone know how to block browser back button?

Body:
Possible Duplicate:

  Disable browser's back button

i have one button on page
on that button click event page will redirect on the next page
now i click on the browser back button
but i want to restrict browser back button for some security purpose

does any one know how to block browser back button so that page can not redirect to previous page?