问:
Angular OnPush: an updated Input string won't update the template
There is a parent component with default changeDetection and two child components with onPush change detection strategy. While the input variable is being updated, the template will not update. I can't used async pipes in the ChildBComponent as it is a global UI component for the project and refactoring is not an option. How do I go about this?

parent.ts

```<code>@Component({
   selector: 'parent',
   template: `
   <div>
     <child-a>
        <child-b [label]="firstLabel"></child-b>
        <child-b [label]="secondLabel"></child-b>
        <child-b label="Just a plain label"></child-b>
     </child-a>
   </div>`
})
export class ParentComponent implements OnInit {

   public ngOnInit(): void {
      this.httpService.loadData()
        .subscribe(data => {
           this.someValue = 1;
           this.otherValue = 2;
        });
   }

   // getters to explicitly trigger change detection
   public get firstLabel(): string {
     return `Something ${ this.someValue || '?'}`;
   }

   public get secondLabel(): string {
     return `Different ${ this.otherValue || '?'}`;
   }
}
</code>```

child-a.ts

```<code>@Component({
   selector: 'child-a',
   template: `
      <div>Layout wrapper</div>
      <ng-content></ng-content>`,
   changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildBComponent implements AfterContentInit {
}
</code>```

child-b.ts

```<code>@Component({
   selector: 'child-b',
   template: '<div>{{ label }}</div>',
   changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildBComponent implements AfterViewInit, OnDestroy {
   @Input public label: string;
}
</code>```

I tried converting @Input into getter/setter - to no avail. When debugging, the changes are coming through, but the template will only update if I click on the component itself. Throwing in a markForCheck() didn't help either.

And idea is helpful.

Edit: Added StackBlitz. Please use a wide preview to see the issue; miraculously it works properly when mobile view elements are shown.

答:
The problem is not with Change Detection, and the label values are correctly reflected in html. The change in countA and countB values do get reflected in HTML, it's just the CSS that gives the impression as if the html is not updated.

In fieldtabs.component.html you have logic to display tabs via
 and you also have <ng-content>.

The problem is when the device has max width of 767.98px, the
 element is not shown as a result of below CSS:

@media (max-width: 767.98px) {
  .fieldtabs--tabs-container {
      display:none
  }
}
```
<p>whereas the <code><fieldtab></code> i.e the Content Children are only visible when device max width is <code>767.98px</code>. Below is the CSS responsible for the same:</p>
<pre class="lang-css prettyprint-override"><code>.fieldtabs-l {
  display: none
}

@media (max-width: 767.98px) {
  .fieldtabs-l {
      display:flex;
      align-items: center
  }
}
</code>```

The fieldtab template html responsible for displaying label has the above class:

<div *ngIf="!invisible" class="fieldtabs-l fieldtab--accord"
```

So when device max width is 767.98px:

The {{ label }} interpolation present within your OnPush Content child fieldtab template is visible

The {{ tab.label }} interpolation present within your OnPush fieldtabs template is not visible

When width is greater than 767.98px, the opposite happens i.e {{ tab.label}} is what you see on the screen, which doesn't get updated as the tabs are being constructed within ngAfterContentInit and the method won't be called again when countA and countB get assigned new values.

Body:
There is a parent component with default changeDetection and two child components with onPush change detection strategy. While the input variable is being updated, the template will not update. I can't used async pipes in the ChildBComponent as it is a global UI component for the project and refactoring is not an option. How do I go about this?

parent.ts

@Component({
   selector: 'parent',
   template: `

     <child-a>
        <child-b [label]="firstLabel"></child-b>
        <child-b [label]="secondLabel"></child-b>
        <child-b label="Just a plain label"></child-b>
     </child-a>

`
})
export class ParentComponent implements OnInit {

   public ngOnInit(): void {
      this.httpService.loadData()
        .subscribe(data => {
           this.someValue = 1;
           this.otherValue = 2;
        });
   }

   // getters to explicitly trigger change detection
   public get firstLabel(): string {
     return `Something ${ this.someValue || '?'}`;
   }

   public get secondLabel(): string {
     return `Different ${ this.otherValue || '?'}`;
   }
}

child-a.ts

@Component({
   selector: 'child-a',
   template: `

Layout wrapper

      <ng-content></ng-content>`,
   changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildBComponent implements AfterContentInit {
}

child-b.ts

@Component({
   selector: 'child-b',
   template: '
{{ label }}
',
   changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildBComponent implements AfterViewInit, OnDestroy {
   @Input public label: string;
}

I tried converting @Input into getter/setter - to no avail. When debugging, the changes are coming through, but the template will only update if I click on the component itself. Throwing in a markForCheck() didn't help either.

And idea is helpful.

Edit: Added StackBlitz. Please use a wide preview to see the issue; miraculously it works properly when mobile view elements are shown.

Body:
The problem is not with Change Detection, and the label values are correctly reflected in html. The change in countA and countB values do get reflected in HTML, it's just the CSS that gives the impression as if the html is not updated.

In fieldtabs.component.html you have logic to display tabs via <ul> and you also have <ng-content>.

The problem is when the device has max width of 767.98px, the <ul *ngIf="!vertical" class="fieldtabs--tabs-container"> element is not shown as a result of below CSS:

@media (max-width: 767.98px) {
  .fieldtabs--tabs-container {
      display:none
  }
}

whereas the <fieldtab> i.e the Content Children are only visible when device max width is 767.98px. Below is the CSS responsible for the same:

.fieldtabs-l {
  display: none
}

@media (max-width: 767.98px) {
  .fieldtabs-l {
      display:flex;
      align-items: center
  }
}

The fieldtab template html responsible for displaying label has the above class:

<div *ngIf="!invisible" class="fieldtabs-l fieldtab--accord"

So when device max width is 767.98px:

The {{ label }} interpolation present within your OnPush Content child fieldtab template is visible

The {{ tab.label }} interpolation present within your OnPush fieldtabs template is not visible

When width is greater than 767.98px, the opposite happens i.e {{ tab.label}} is what you see on the screen, which doesn't get updated as the tabs are being constructed within ngAfterContentInit and the method won't be called again when countA and countB get assigned new values.


来源: stackexchange

问:
Determine time of event in R
Wondering what the most effective way to determine event time in R is. Other answers seemed to not have grouping by ID, and that's a big chunk of what I need.

My data looks something like this:

```<code>time = rep(c(1:5),2)
id = c(rep(1,5),rep(2,5))
event = c(0,0,0,1,1,0,1,1,1,1)

df = data.frame(cbind(time,id,event))
df
   time id event
1     1  1     0
2     2  1     0
3     3  1     0
4     4  1     1
5     5  1     1
6     1  2     0
7     2  2     1
8     3  2     1
9     4  2     1
10    5  2     1
>
</code>```

Where "event" is binary observation (death of individual in experiment), and (should) remain 1 once it is first observed.

I need to determine the first time of event == 1, for each id number, and generate a vector of the id number and time first observed where event =1.

I originally was going to sloppily subset the data where event =1, and then just pick the minimum value of the week for each id, but that gets even sloppier when grouping by ID. Then I tried some aggregating but also struggled to do it across the ID grouping. I know tidyverse has some options but I'm a n00b.

I'm sure there's a very straightforward way to do this. Thanks!

答:
```<code># set as data.table
setDT(df)

# find 1st death event. Fetch row
x <-
df[event == 1
   ][, xx := 1:.N, id
   ][xx == 1
     ][, xx := NULL]

x
   time id event
1:    4  1     1
2:    2  2     1
</code>```

ContentLicense: CC BY-SA 4.0

Title: Determine time of event in R

Body:
Wondering what the most effective way to determine event time in R is. Other answers seemed to not have grouping by ID, and that's a big chunk of what I need.

My data looks something like this:

time = rep(c(1:5),2)
id = c(rep(1,5),rep(2,5))
event = c(0,0,0,1,1,0,1,1,1,1)

df = data.frame(cbind(time,id,event))
df
   time id event
1     1  1     0
2     2  1     0
3     3  1     0
4     4  1     1
5     5  1     1
6     1  2     0
7     2  2     1
8     3  2     1
9     4  2     1
10    5  2     1
>

Where "event" is binary observation (death of individual in experiment), and (should) remain 1 once it is first observed.

I need to determine the first time of event == 1, for each id number, and generate a vector of the id number and time first observed where event =1.

I originally was going to sloppily subset the data where event =1, and then just pick the minimum value of the week for each id, but that gets even sloppier when grouping by ID. Then I tried some aggregating but also struggled to do it across the ID grouping. I know tidyverse has some options but I'm a n00b.

I'm sure there's a very straightforward way to do this. Thanks!


问:
SQL query is returning most recent duplicates, but not non-duplicates
I have an MySQL table (MySQL 5.7) with the following columns: id (key), email, percentage, file_name. The table logs when students (identified by email) complete certain activities.

I need to return a list that has a row for each file_name that the student has completed. If they have completed a file_name more than once I want to return the most recent attempt, based on the auto-incrementing id. I've used a few answers on here to create the following query. The file_name string matches are to isolate particular activity types and levels:

```<code>SELECT id,
       file_name,
       percentage
FROM users t1
WHERE email IN ('name@student.com')
AND file_name LIKE ('%IL%')
AND file_name LIKE ('%B2%')
AND id = (  SELECT MAX(id)
            FROM users t2
            WHERE t2.file_name = t1.file_name
         )
GROUP BY file_name, percentage, id
ORDER BY id;
</code>```

This query successfully returns the most recent instance of any duplicated filenames, but doesn't return any non-duplicates. So, if a student has completed 8 file_names once, but has repeated 1 file_name twice, this query only returns one row, the most recent duplicate. It should return the 8 single activity rows, plus the most recent duplicate.

I've got it running here and it works as expected - returning the non duplicates and the most recent duplicate, so I don't understand why it's not working on the database itself.

I can successfully do this using a CTE, but I'm not in control of the database and so can't upgrade to allow CTEs.

答:
The big rock problem is that the correlated subquery is getting the most recent id for a file_name for any email, not just email that matches from the outer query.  Also the GROUP BY on the outer query seems to be unnecessary.

Keeping with the same correlated subquery pattern, we can do something like this:

```<code>SELECT t1.id
     , t1.email
     , t1.file_name
     , t1.percentage
  FROM users t1
 WHERE t1.email IN ('name@student.com')
   AND t1.file_name LIKE ('%IL%')
   AND t1.file_name LIKE ('%B2%')
   AND t1.id = ( -- most recent id for (email,file_name)
                 SELECT MAX(t2.id)
                   FROM users t2
                  WHERE t2.email     = t1.email
                    AND t2.file_name = t1.file_name
               )
 ORDER BY t1.id
</code>```

With large sets, the correlated subquery pattern can can eat our lunch, and our lunchbox, even with appropriate indexes available, because that subquery will get re-executed for every row processed by the outer query (every row that isnt earlier excluded by another predicate)

I tend to rewrite the query to avoid the correlated subquery, and measure and compare performance and compare plans (EXPLAIN PLAN output.)

We could use an inline view (a "derived table" in the MySQL parlance) to get the most recent id, and then join back to the original table to get the columns associated with that id

```<code>SELECT t1.id
     , t1.email
     , t1.file_name
     , t1.percentage
  -- , t2.*
 FROM ( -- most recent id for (email,file_name)
        SELECT MAX(t2.id) AS _most_recent_id
             , t2.email
             , t2.file_name
          FROM users t2
         WHERE t2.email IN ('name@student.com')
           AND t2.file_name LIKE ('%IL%')
           AND t3.file_name LIKE ('%B2%')
         GROUP
            BY t2.email
             , t2.file_name
      ) t3
 JOIN users t1
   ON t1.id = t3._most_recent_id
ORDER
   BY t1.id
</code>```

NOTES: We can get the inline view query (the SELECT aliased as t3) tested and working before we incorporate that as a derived table in the outer SELECT.

In this example, its not strictly necessary for t3 (the inline view query) to return columns t2.email or t2.file_name.  But it does make it easier to verify the results, that we are getting the highest id for a given email and file_name.  (We can use the returned values in another simpler statement SELECT * FROM users WHERE email = ? AND file_name = ? to get the entire set of rows we picked a max id from.

Body:
I have an MySQL table (MySQL 5.7) with the following columns: id (key), email, percentage, file_name. The table logs when students (identified by email) complete certain activities.

I need to return a list that has a row for each file_name that the student has completed. If they have completed a file_name more than once I want to return the most recent attempt, based on the auto-incrementing id. I've used a few answers on here to create the following query. The file_name string matches are to isolate particular activity types and levels:

SELECT id,
       file_name,
       percentage
FROM users t1
WHERE email IN ('name@student.com')
AND file_name LIKE ('%IL%')
AND file_name LIKE ('%B2%')
AND id = (  SELECT MAX(id)
            FROM users t2
            WHERE t2.file_name = t1.file_name
         )
GROUP BY file_name, percentage, id
ORDER BY id;

This query successfully returns the most recent instance of any duplicated filenames, but doesn't return any non-duplicates. So, if a student has completed 8 file_names once, but has repeated 1 file_name twice, this query only returns one row, the most recent duplicate. It should return the 8 single activity rows, plus the most recent duplicate.

I've got it running here and it works as expected - returning the non duplicates and the most recent duplicate, so I don't understand why it's not working on the database itself.

I can successfully do this using a CTE, but I'm not in control of the database and so can't upgrade to allow CTEs.

Body:
The big rock problem is that the correlated subquery is getting the most recent id for a file_name for any email, not just email that matches from the outer query.  Also the GROUP BY on the outer query seems to be unnecessary.

Keeping with the same correlated subquery pattern, we can do something like this:

SELECT t1.id
     , t1.email
     , t1.file_name
     , t1.percentage
  FROM users t1
 WHERE t1.email IN ('name@student.com')
   AND t1.file_name LIKE ('%IL%')
   AND t1.file_name LIKE ('%B2%')
   AND t1.id = ( -- most recent id for (email,file_name)
                 SELECT MAX(t2.id)
                   FROM users t2
                  WHERE t2.email     = t1.email
                    AND t2.file_name = t1.file_name
               )
 ORDER BY t1.id

With large sets, the correlated subquery pattern can can eat our lunch, and our lunchbox, even with appropriate indexes available, because that subquery will get re-executed for every row processed by the outer query (every row that isnt earlier excluded by another predicate)

I tend to rewrite the query to avoid the correlated subquery, and measure and compare performance and compare plans (EXPLAIN PLAN output.)

We could use an inline view (a "derived table" in the MySQL parlance) to get the most recent id, and then join back to the original table to get the columns associated with that id

SELECT t1.id
     , t1.email
     , t1.file_name
     , t1.percentage
  -- , t2.*
 FROM ( -- most recent id for (email,file_name)
        SELECT MAX(t2.id) AS _most_recent_id
             , t2.email
             , t2.file_name
          FROM users t2
         WHERE t2.email IN ('name@student.com')
           AND t2.file_name LIKE ('%IL%')
           AND t3.file_name LIKE ('%B2%')
         GROUP
            BY t2.email
             , t2.file_name
      ) t3
 JOIN users t1
   ON t1.id = t3._most_recent_id
ORDER
   BY t1.id

NOTES: We can get the inline view query (the SELECT aliased as t3) tested and working before we incorporate that as a derived table in the outer SELECT.

In this example, its not strictly necessary for t3 (the inline view query) to return columns t2.email or t2.file_name.  But it does make it easier to verify the results, that we are getting the highest id for a given email and file_name.  (We can use the returned values in another simpler statement SELECT * FROM users WHERE email = ? AND file_name = ? to get the entire set of rows we picked a max id from.


问:
How to set up continuous integration for Unity on Linux
I would like to create a system for building a Unity project each time it is changed with git. I would like to use Semaphore or Shippable because of the free plan options. However, I don't know how to set up a system to automatically build a Unity project on Linux. Online, I can find documentation on how to do it for Mac with TravisCI, but this is not an option for me. How could I install Unity onto Ubuntu from the command line and then use the CLI build a project from a git repo? Thanks!</p>

答:
You can use Github or Gitlab pipelines. Every change, submit your code using git and they will build your game automatically.

Use https://game.ci/ workflow. They have a quite complete set of scripts and configurations.


问:
NuGet 6 not available on Azure Pipeline
I try to update my pipeline from NET 5 to NET 6. It immediately bombed out at nuget restore saying that the used version does not support NET 6. When going to advanced settings for the NuGet tool installer therer is an i icon showing all available versions (links to https://dist.nuget.org/tools.json). That link shows 6.0.0-preview.3. If I set this and run the pipeline I get an error that latest version is 5.11.

I did add a task BEFORE to install net SDK 6 which succeeds (Successfully installed .NET Core sdk version 6.0.100-preview.3.21202.5.
Creating global tool path and pre-pending to PATH.)

So why can't it find the nuget 6 ?

答:
Try updating the vm image defined in the yml file.
I was getting error with windows latest but allowed for nuget restore and project/solution builds.

pool:
vmImage: 'windows-2022'

Title: NuGet 6 not available on Azure Pipeline


问:
How set cookies in dev tools in Google Chrome 98 version?
after update google chrome up to 98 version, I can't set cookies

it looks like a red stripe and after the refresh, it disappears. Even you fill all fields, it disappears.

Maybe any know how it disables the feature?
This feature describes in their blog, but I can't find how to fix it

答: Using a plugin like 'EditThisCookie' also works for now.


问:
How to add tabs at bottom
I have a tabhost which contains three tabs, connected with three activities. All three tabs are in the upper side. How can I make these three tabs at the bottom?

I found this, but there are still some problems.

This is my tabhost XML file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1" />
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0"/>
    </LinearLayout>
</TabHost>
</code>```

In my TabActivity class, I have following code:

```<code>setContentView(R.layout.tabs);

TabHost mTabHost = (TabHost)findViewById(android.R.id.tabhost);

mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("TAB 1").setContent(new Intent(AndroisTabViewActivity.this,TabActivity1.class)));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("TAB 2").setContent(new Intent(AndroisTabViewActivity.this,TabActivity1.class)));
mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator("TAB 3").setContent(new Intent(AndroisTabViewActivity.this,TabActivity1.class)));

mTabHost.setCurrentTab(0);
</code>```

There is one activity named TabActivity1 which I have also included in Manifest file. But it is showing the error:

Can't get the activity TabActivity1.

答:
I assume you want to show "Tab" at bottom of the window, just try this:

```<code><RelativeLayout
    android:layout_width="match_parent"
    android:id="@+id/linearLayout1"
    android:layout_height="match_parent">

    <TabWidget
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@android:id/tabs"
        android:layout_alignParentBottom="true">
    </TabWidget>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@android:id/tabcontent">
    </FrameLayout>
</RelativeLayout>
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to add tabs at bottom

Body:
I have a tabhost which contains three tabs, connected with three activities. All three tabs are in the upper side. How can I make these three tabs at the bottom?

I found this, but there are still some problems.

This is my tabhost XML file:

<?xml version="1.0" encoding="UTF-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1" />
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0"/>
    </LinearLayout>
</TabHost>

In my TabActivity class, I have following code:

setContentView(R.layout.tabs);

TabHost mTabHost = (TabHost)findViewById(android.R.id.tabhost);

mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("TAB 1").setContent(new Intent(AndroisTabViewActivity.this,TabActivity1.class)));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("TAB 2").setContent(new Intent(AndroisTabViewActivity.this,TabActivity1.class)));
mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator("TAB 3").setContent(new Intent(AndroisTabViewActivity.this,TabActivity1.class)));

mTabHost.setCurrentTab(0);

There is one activity named TabActivity1 which I have also included in Manifest file. But it is showing the error:

Can't get the activity TabActivity1.

Body:
I assume you want to show "Tab" at bottom of the window, just try this:

<RelativeLayout
    android:layout_width="match_parent"
    android:id="@+id/linearLayout1"
    android:layout_height="match_parent">

    <TabWidget
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@android:id/tabs"
        android:layout_alignParentBottom="true">
    </TabWidget>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@android:id/tabcontent">
    </FrameLayout>
</RelativeLayout>


问:
Django template regorup
I want to regroup this on the basis of ingredients.
this is my sample result which I want
Just like the below picture as there is more than one certificate so I am showing them in one row.

Ingredient_name, all the stop_name associated with that ingredient,
all  the stop_longitude associated with that ingredient and so on in one table row.

Right now its showing like this and you can see that the ingredient name is repeating .

model

```<code>class SupplyChainStops(models.Model):
    ingredient = models.ForeignKey(Ingredients, null=True, on_delete=models.CASCADE)

    stop_name = models.CharField(max_length=1024, null=True, blank=True)
    stop_longitude = models.CharField(max_length=500, null=True, blank=True)
    stop_latitude = models.CharField(max_length=500, null=True, blank=True)
    is_supplier = models.BooleanField(default=False, blank=True, null=True)

    def __str__(self):
        return f'{self.stop_name}'
</code>```

query

```<code>items = SupplyChainStops.objects.all()
</code>```

template

```<code>        {% for item in items %}
            <tr class="text-black">
                <td>{{ item.ingredient }}</td>
                <td>{{ item.stop_name }}
                <td>{{ item.stop_longitude }}
                <td>{{ item.stop_latitude }}
</code>```

This is my DB structure

This is my desired output

答:
You can set the related_name for ForeignKey field.

```<code>class SupplyChainStops(models.Model):
    ingredient = models.ForeignKey(Ingredients, null=True, on_delete=models.CASCADE, related_name="supply_chain_stops")
</code>```

in view:

```<code>each_row = []
ing_ids = []
sup = SupplyChainStops.objects.all()
for each_sup in sup:
    ing_ids.append(each_sup.ingredient.id)
ing_ids = list(set(ing_ids))
sch = []
for each_ing_id in ing_ids:
    sch.append(SupplyChainStops.objects.filter(ingredient__id= each_ing_id).last())

for each in sch:
    stop_names_list = []
    stop_longitude_list = []
    stop_latitude_list = []
    mi_list = each.ingredient.supply_chain_stops.all()
    for each_mi in mi_list:
        stop_names_list.append(each_mi.stop_name)
        stop_longitude_list.append(each_mi.stop_longitude)
        stop_latitude_list.append(each_mi.stop_latitude)
    row_list = [each.ingredient, stop_names_list, stop_longitude_list, stop_latitude_list]
    each_row.append(row_list)
context = {
"items": each_row
}
</code>```

in template:

```<code>{% for item in items %}
    <tr class="text-black">
        <td>{{ item.0 }}</td>
        <td>{{ item.1|join:", " }}</td>
        <td>{{ item.2|join:", " }}</td>
        <td>{{ item.3|join:", " }}</td>
    </tr>
{% endfor %}
</code>```

Title: Django template regorup

Body:
I want to regroup this on the basis of ingredients.
this is my sample result which I want
Just like the below picture as there is more than one certificate so I am showing them in one row.

Ingredient_name, all the stop_name associated with that ingredient,
all  the stop_longitude associated with that ingredient and so on in one table row.

Right now its showing like this and you can see that the ingredient name is repeating .

model

class SupplyChainStops(models.Model):
    ingredient = models.ForeignKey(Ingredients, null=True, on_delete=models.CASCADE)

    stop_name = models.CharField(max_length=1024, null=True, blank=True)
    stop_longitude = models.CharField(max_length=500, null=True, blank=True)
    stop_latitude = models.CharField(max_length=500, null=True, blank=True)
    is_supplier = models.BooleanField(default=False, blank=True, null=True)

    def __str__(self):
        return f'{self.stop_name}'

query

items = SupplyChainStops.objects.all()

template

        {% for item in items %}

                {{ item.ingredient }}
                {{ item.stop_name }}
                {{ item.stop_longitude }}
                {{ item.stop_latitude }}

This is my DB structure

This is my desired output

Body:
You can set the related_name for ForeignKey field.

class SupplyChainStops(models.Model):
    ingredient = models.ForeignKey(Ingredients, null=True, on_delete=models.CASCADE, related_name="supply_chain_stops")

in view:

each_row = []
ing_ids = []
sup = SupplyChainStops.objects.all()
for each_sup in sup:
    ing_ids.append(each_sup.ingredient.id)
ing_ids = list(set(ing_ids))
sch = []
for each_ing_id in ing_ids:
    sch.append(SupplyChainStops.objects.filter(ingredient__id= each_ing_id).last())

for each in sch:
    stop_names_list = []
    stop_longitude_list = []
    stop_latitude_list = []
    mi_list = each.ingredient.supply_chain_stops.all()
    for each_mi in mi_list:
        stop_names_list.append(each_mi.stop_name)
        stop_longitude_list.append(each_mi.stop_longitude)
        stop_latitude_list.append(each_mi.stop_latitude)
    row_list = [each.ingredient, stop_names_list, stop_longitude_list, stop_latitude_list]
    each_row.append(row_list)
context = {
"items": each_row
}

in template:

{% for item in items %}
    <tr class="text-black">
        <td>{{ item.0 }}</td>
        <td>{{ item.1|join:", " }}</td>
        <td>{{ item.2|join:", " }}</td>
        <td>{{ item.3|join:", " }}</td>
    </tr>
{% endfor %}


问:
yarn start-https failed with error Command failed with exit code 1
I am working on a project that I downloaded, but having trouble setting up and getting the enviroment started.
After yarn install, yarn build, and then yarn start-https, I get this error message:

```<code>Error: error:0909006C:PEM routines:get_name:no start line
    at node:internal/tls/secure-context:65:13
    at Array.forEach (<anonymous>)
    at setCerts (node:internal/tls/secure-context:63:3)
    at configSecureContext (node:internal/tls/secure-context:152:5)
    at Object.createSecureContext (node:_tls_common:116:3)
    at Server.setSecureContext (node:_tls_wrap:1344:27)
    at Server (node:_tls_wrap:1203:8)
    at new Server (node:https:69:3)
    at Object.createServer (node:https:105:10)
    at Server.createServer (.../node_modules/webpack-dev-server/lib/Server.js:677:35)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
</code>```

I am have followed the set for the readMe file... and I tried googling each line of error message but nothing had helped solved this issue of exiting out.

I feel, that I must be missing something... somthing that was not documented in the readme file...

Any help would be greatly appreciated.

答: This error showing that you have a problem around ssl settings, you have to prepare self-signed SSL Certificate.</p>

Body:
I am working on a project that I downloaded, but having trouble setting up and getting the enviroment started.
After yarn install, yarn build, and then yarn start-https, I get this error message:

Error: error:0909006C:PEM routines:get_name:no start line
    at node:internal/tls/secure-context:65:13
    at Array.forEach (<anonymous>)
    at setCerts (node:internal/tls/secure-context:63:3)
    at configSecureContext (node:internal/tls/secure-context:152:5)
    at Object.createSecureContext (node:_tls_common:116:3)
    at Server.setSecureContext (node:_tls_wrap:1344:27)
    at Server (node:_tls_wrap:1203:8)
    at new Server (node:https:69:3)
    at Object.createServer (node:https:105:10)
    at Server.createServer (.../node_modules/webpack-dev-server/lib/Server.js:677:35)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

I am have followed the set for the readMe file... and I tried googling each line of error message but nothing had helped solved this issue of exiting out.

I feel, that I must be missing something... somthing that was not documented in the readme file...

Any help would be greatly appreciated.


问:
how to map multiple png texture in ThreeJS
Im working with Three.js particles , and trying to map multiple png textures, (my png images are juste différent colors stars to create a sky full of stars)
my code looks like this :

```<code>const loader = new THREE.TextureLoader();
const cross = loader.load ('./cross1.png');
const cross2 = loader.load ('./cross3.png');
.
.
.
const particlesMaterial = new THREE.PointsMaterial({
    size: 0.02,
    map: cross,
    transparent: true
})

// Mesh
const sphere = new THREE.Points(geometry,material)
const particlesMesh = new THREE.Points(particlesGeometry, particlesMaterial)

scene.add(sphere, particlesMesh)
</code>```

it works fine with only maping one elmement "cross" .
my question is, how can i MAP multiple images to get like a random mix  please ?
something like :

```<code>const particlesMaterial = new THREE.PointsMaterial({
    size: 0.02,
    map: cross, cross2, cross3
    transparent: true
})
</code>```

THANKS !

答:
If you are looking to make stars with multiple colors I would just create 3 instances of points mesh with each one containing their respective textures.

const particlesMaterial = new THREE.PointsMaterial({
    size: 0.02,
    map: cross,
    transparent: true
})
const particlesMaterial2 = new THREE.PointsMaterial({
    size: 0.02,
    map: cross2,
    transparent: true
})
const particlesMaterial3 = new THREE.PointsMaterial({
    size: 0.02,
    map: cross3,
    transparent: true
})

const particlesMesh = new THREE.Points(particlesGeometry, particlesMaterial)
const particlesMesh2 = new THREE.Points(particlesGeometry, particlesMaterial2)
const particlesMesh3 = new THREE.Points(particlesGeometry, particlesMaterial3)

scene.add(particlesMesh, particlesMesh2, particlesMesh3)
```

this works as long as your point coordinates are randomized

Body:
Im working with Three.js particles , and trying to map multiple png textures, (my png images are juste différent colors stars to create a sky full of stars)
my code looks like this :

const loader = new THREE.TextureLoader();
const cross = loader.load ('./cross1.png');
const cross2 = loader.load ('./cross3.png');
.
.
.
const particlesMaterial = new THREE.PointsMaterial({
    size: 0.02,
    map: cross,
    transparent: true
})

// Mesh
const sphere = new THREE.Points(geometry,material)
const particlesMesh = new THREE.Points(particlesGeometry, particlesMaterial)

scene.add(sphere, particlesMesh)

it works fine with only maping one elmement "cross" .
my question is, how can i MAP multiple images to get like a random mix  please ?
something like :

const particlesMaterial = new THREE.PointsMaterial({
    size: 0.02,
    map: cross, cross2, cross3
    transparent: true
})

THANKS !

Body:
If you are looking to make stars with multiple colors I would just create 3 instances of points mesh with each one containing their respective textures.

const particlesMaterial = new THREE.PointsMaterial({
    size: 0.02,
    map: cross,
    transparent: true
})
const particlesMaterial2 = new THREE.PointsMaterial({
    size: 0.02,
    map: cross2,
    transparent: true
})
const particlesMaterial3 = new THREE.PointsMaterial({
    size: 0.02,
    map: cross3,
    transparent: true
})

const particlesMesh = new THREE.Points(particlesGeometry, particlesMaterial)
const particlesMesh2 = new THREE.Points(particlesGeometry, particlesMaterial2)
const particlesMesh3 = new THREE.Points(particlesGeometry, particlesMaterial3)

scene.add(particlesMesh, particlesMesh2, particlesMesh3)

this works as long as your point coordinates are randomized


问:
JPanel Obscures BufferedImage
I'm having trouble finding out why the following problem happens: In a program that uses "extends Frame" to create a window, I can use BufferedImage to draw to the graphics context of the Frame (not JFrame), and it looks just fine. However, the moment I declare a JPanel, all of the text drawn by BufferedImage becomes obscured (not completely, but semi-transparent and hard to read), even if I don't add the JPanel to the JFrame.

Here's a simplified version of the code:

```<code>import java.awt.*;
import java.awt.event.*;
import javax.swing.Timer;
import java.awt.image.*;
import javax.swing.*;

public class MyProgram extends Frame {

    static Frame f;
    static Timer timer;

    public static void main(String[] args) {

        f = new Frame();
        f.setSize(400, 200);
        f.setResizable(false);
        f.setVisible(true);

        f.addKeyListener(new KeyAdapter() {

        public void keyPressed(KeyEvent e) {

            drawScreen();
        }
    });

    drawScreen();
}

public static void drawScreen() {

    BufferedImage off_i = new BufferedImage(f.getWidth(), f.getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics g = off_i.createGraphics();

    g.setColor(new Color(50, 50, 50));
    g.drawString("Hit any key; why does this text change?", 15, f.getHeight() - 10);

    Graphics off_g = f.getGraphics();
    off_g.drawImage(off_i, 0, 0, null);

    JPanel panel = new JPanel();
    }
}
</code>```

I could maybe understand seeing the problem arise if I had added the JPanel to the JFrame and didn't set any bounds to its visibility, but even creating the JPanel gives that issue, which seems weird to me.

Basically, what I'm trying to do here is take an existing program that I have that runs just fine without JPanel, and I want to add to it a JTextArea so that I can accept copy/paste text for modifying the displaying of the program.

My understanding of Java is kind of spotty, as I learned it mainly by hobby and not formally, but I'm always looking to learn more when I can. Thanks for the help!

Update: I discovered that this problem only happens when the draw function is called again, after the JPanel has been declared, though I still don't understand why it does that or how to get around it.

答:
As an answer to my original question:

It seems that initializing JPanel alongside awt draw() commands causes the text to be antialiased, which makes the text look harder to read, partially obscured, thinner, etc. Although I tried setRenderingHint() with VALUE_TEXT_ANTIALIAS_OFF, it did not solve the problem. But as other posters pointed out it's not best practice to mix the two components.

While this doesn't exactly solve my problem, it does answer the question of what is going on, that being text antialiasing as some result of JPanel (does that sound right?). Ideally I wouldn't want to rewrite all of the code just to add a single JTextArea into an already existing codebase. But perhaps it's good every now and then to revisit old code and revamp it where it may be faulty.

Thanks everyone for the comments, information, and resource links!

Title: JPanel Obscures BufferedImage

Body:
I'm having trouble finding out why the following problem happens: In a program that uses "extends Frame" to create a window, I can use BufferedImage to draw to the graphics context of the Frame (not JFrame), and it looks just fine. However, the moment I declare a JPanel, all of the text drawn by BufferedImage becomes obscured (not completely, but semi-transparent and hard to read), even if I don't add the JPanel to the JFrame.

Here's a simplified version of the code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.Timer;
import java.awt.image.*;
import javax.swing.*;

public class MyProgram extends Frame {

    static Frame f;
    static Timer timer;

    public static void main(String[] args) {

        f = new Frame();
        f.setSize(400, 200);
        f.setResizable(false);
        f.setVisible(true);

        f.addKeyListener(new KeyAdapter() {

        public void keyPressed(KeyEvent e) {

            drawScreen();
        }
    });

    drawScreen();
}

public static void drawScreen() {

    BufferedImage off_i = new BufferedImage(f.getWidth(), f.getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics g = off_i.createGraphics();

    g.setColor(new Color(50, 50, 50));
    g.drawString("Hit any key; why does this text change?", 15, f.getHeight() - 10);

    Graphics off_g = f.getGraphics();
    off_g.drawImage(off_i, 0, 0, null);

    JPanel panel = new JPanel();
    }
}

I could maybe understand seeing the problem arise if I had added the JPanel to the JFrame and didn't set any bounds to its visibility, but even creating the JPanel gives that issue, which seems weird to me.

Basically, what I'm trying to do here is take an existing program that I have that runs just fine without JPanel, and I want to add to it a JTextArea so that I can accept copy/paste text for modifying the displaying of the program.

My understanding of Java is kind of spotty, as I learned it mainly by hobby and not formally, but I'm always looking to learn more when I can. Thanks for the help!

Update: I discovered that this problem only happens when the draw function is called again, after the JPanel has been declared, though I still don't understand why it does that or how to get around it.


问:
Why doesn't nested parameter expansion work correctly in GitLab CI/CD?
Using a bash runner, is there any reason why the following variable expansion shouldn't work?

```<code>variables:
  GIT_BRANCH: "${CI_MERGE_REQUEST_SOURCE_BRANCH_NAME:-${CI_COMMIT_BRANCH:-$CI_DEFAULT_BRANCH}}"

job1:
  script:
    - echo $GIT_BRANCH
</code>```

The job outputs }.

I'm using GitLab Enterprise Edition 14.1.8-ee.

答:
These expansions are done by GitLab CI, not by bash, so they probably simply can't handle nested expansions as robustly as bash can.

They probably think the variable name is everything up to the next }, so CI_MERGE_REQUEST_SOURCE_BRANCH_NAME:-${CI_COMMIT_BRANCH:-$CI_DEFAULT_BRANCH without a closing curly brace. That would explain why there is a leftover } when the dust settles.

Body:
Using a bash runner, is there any reason why the following variable expansion shouldn't work?

variables:
  GIT_BRANCH: "${CI_MERGE_REQUEST_SOURCE_BRANCH_NAME:-${CI_COMMIT_BRANCH:-$CI_DEFAULT_BRANCH}}"

job1:
  script:
    - echo $GIT_BRANCH

The job outputs }.

I'm using GitLab Enterprise Edition 14.1.8-ee.


问:
remove duplicated rows and convert it to list or tuple
I have dataframe as follows (Name is index):

Name
Age
year

Tom
20
2020

Tom
20
2021

Nick
19
2019

Jack
18
2018

my goal is to remove duplicate and convert the column year to tuple or list, like below

Name
Age
year

Tom
20
(2020, 2019)

Nick
19
2019

Jack
18
2018

how can I do that efficiently since my df has more than 800,000 rows

答:
How about a groupby + agg(np.array)?

```<code>>>> df.groupby(['Name', 'Age'], as_index=False)['year'].agg(np.array)
   Name  Age          year
0  Jack   18          2018
1  Nick   19          2019
2   Tom   20  [2020, 2021]
</code>```

If you don't care about the items being strings, you can do this:

```<code>>>> df.assign(year=df['year'].astype(str)).groupby(['Name', 'Age'], as_index=False, sort=False)['year'].agg(list).pipe(lambda x: x.assign(year=x['year'].str.join(', ')))
   Name  Age        year
0   Tom   20  2020, 2021
1  Nick   19        2019
2  Jack   18        2018
</code>```

Body:
How about a groupby + agg(np.array)?

>>> df.groupby(['Name', 'Age'], as_index=False)['year'].agg(np.array)
   Name  Age          year
0  Jack   18          2018
1  Nick   19          2019
2   Tom   20  [2020, 2021]

If you don't care about the items being strings, you can do this:

>>> df.assign(year=df['year'].astype(str)).groupby(['Name', 'Age'], as_index=False, sort=False)['year'].agg(list).pipe(lambda x: x.assign(year=x['year'].str.join(', ')))
   Name  Age        year
0   Tom   20  2020, 2021
1  Nick   19        2019
2  Jack   18        2018


问:
React Native: Can't fetch on onPress={}
My app :

```<code>import { LoginFunction, RegisterFunction } from './authentication/auth'

export default function LoginPage(props) {

  const navigateToRegister = () => {
    props.navigation.navigate("Register")
  }

  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')

  return (
    <View style={styles.container}>

      <View style={styles.input}>
        <Text style={styles.label}>Username</Text>
        <TextInput style={styles.textinput} placeholder='...' onChangeText={(text) => setUsername(text)}/>
      </View>

      <View style={styles.input}>
        <Text style={styles.label}>Password</Text>
        <TextInput style={styles.textinput} placeholder='...' onChangeText={(pw) => setPassword(pw)}/>
      </View>

      <View style={styles.login}>

        // HERE IS I'M TRYING TO RUN FUNCTION
        <TouchableOpacity style={styles.loginbtn} onPress={() => {
          LoginFunction(username, password)
        }}>
        // ----------------------------------

          <Text style={styles.logintext}>Login</Text>
        </TouchableOpacity>
      </View>

      <TouchableOpacity style={styles.btn} onPress={() => navigateToRegister()}>
        <Text style={styles.text}>
          Register Instead
        </Text>
      </TouchableOpacity>

    </View>
  )
}
</code>```

The function in where I imported from :

```<code>import React, { useState, useEffect } from 'react';
export function LoginFunction(username, password) {
  const [data, setData] = useState([])

  fetch('https://some**app**.herokuapp.com/api/users/', {
      method: "GET"
  })
  .then((resp) => resp.json())
  .then((resp) => {
    setData(resp)
  })
  .catch((err) => console.log("ERR: " + err))

  console.log(data)

  alert(username + " " + password)
}
</code>```

I'm trying to make my own authentication system with using rest api. I tried to fetch data from api and make provide user login. But I'm getting an error with this code.

Error : Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

I dealed with this error before but I cannot now. What should I do? What is the wrong?

答:
You should move the const [data, setData] = useState([]) to LoginPage component instead.
The LoginFunction function accepts 3 parameters: (username, password, setData)
You then can use data in the LoginPage.

Title: React Native: Can't fetch on onPress={}

Body:
My app :

import { LoginFunction, RegisterFunction } from './authentication/auth'

export default function LoginPage(props) {

  const navigateToRegister = () => {
    props.navigation.navigate("Register")
  }

  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')

  return (
    <View style={styles.container}>

      <View style={styles.input}>
        <Text style={styles.label}>Username</Text>
        <TextInput style={styles.textinput} placeholder='...' onChangeText={(text) => setUsername(text)}/>
      </View>

      <View style={styles.input}>
        <Text style={styles.label}>Password</Text>
        <TextInput style={styles.textinput} placeholder='...' onChangeText={(pw) => setPassword(pw)}/>
      </View>

      <View style={styles.login}>

        // HERE IS I'M TRYING TO RUN FUNCTION
        <TouchableOpacity style={styles.loginbtn} onPress={() => {
          LoginFunction(username, password)
        }}>
        // ----------------------------------

          <Text style={styles.logintext}>Login</Text>
        </TouchableOpacity>
      </View>

      <TouchableOpacity style={styles.btn} onPress={() => navigateToRegister()}>
        <Text style={styles.text}>
          Register Instead
        </Text>
      </TouchableOpacity>

    </View>
  )
}

The function in where I imported from :

import React, { useState, useEffect } from 'react';
export function LoginFunction(username, password) {
  const [data, setData] = useState([])

  fetch('https://some**app**.herokuapp.com/api/users/', {
      method: "GET"
  })
  .then((resp) => resp.json())
  .then((resp) => {
    setData(resp)
  })
  .catch((err) => console.log("ERR: " + err))

  console.log(data)

  alert(username + " " + password)
}

I'm trying to make my own authentication system with using rest api. I tried to fetch data from api and make provide user login. But I'm getting an error with this code.

Error : Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

I dealed with this error before but I cannot now. What should I do? What is the wrong?


问:
How to reference models in junction model with Sequelize 6 (and 7?) cli generated models
I have a very simple structure for managing permissions where I have a table of users and a table of roles and a many-to-many mapping between them. This is working in the "old" way of setting up Sequelize. But, I'm about to add a bunch more complicated stuff, and am moving to the cli/migration model of defining models. I figured I'd start by getting my existing stuff working the new way.

As I understand things, there's no way to pass association information to the CLI during the generate phase, so you have to manually go back and add the associations. Moreover, when using this method instead of sync, you also have to create a separate migration file for the junction table. This can be facilitated by the generate command, but again needs to be manually configured.

I have all of that "done", such that db:migrate works; however, I'm running into errors when I try to actually use it in Node.

Here are the (modified) files in ./models:

role.js:

```<code>'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Role extends Model {
    static associate(models) {
      models.Role.belongsToMany(models.User, {
        through: models.UserRole
      })
    }
  }
  Role.init({
    name: DataTypes.STRING
  }, {
    sequelize,
    modelName: 'Role',
  });
  return Role;
};
</code>```

user.js:

```<code>'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class User extends Model {
    static associate(models) {
      models.User.belongsToMany(models.Role, {
        through: models.UserRole
      })
    }
  }
  User.init({
    username: DataTypes.STRING,
    email: DataTypes.STRING,
    password: DataTypes.STRING
  }, {
    sequelize,
    modelName: 'User',
  });
  return User;
};
</code>```

userrole.js:

```<code>'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class UserRole extends Model {
    static associate(models) {
      // define association here
    }
  }
  UserRole.init({
    userId: {
      type: DataTypes.INTEGER,
      references: {
        model: User, // <--- this is the complaint
        key: 'id'
      }
    },
    roleId: {
      type: DataTypes.INTEGER,
      references: {
        model: Role,
        key: 'id'
      }
    }
  }, {
    sequelize,
    modelName: 'UserRole',
  });
  return UserRole;
};
</code>```

These are all read in with the autogenerated index.js.

When I spin things up with nodemon, it complains

```<code>userrole.js:20
        model: User,
               ^

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

I tried modifying that line to model: models.User, but then it complains ReferenceError: models is not defined.

I'm sure I'm missing something quite simple here, but, how do I get those references into the model file for the junction table?

FWIW, this is with

```<code>sequelize@6.16.0
node v14.17.3
</code>```

and I have it using sqlite as the dialect in the development environment.

答:
It's better to remove references option and define all links in associate:

static associate(models) {
       UserRole.belongsTo(models.User, { foreignKey: 'userId' });
       UserRole.belongsTo(models.Role, { foreignKey: 'roleId' });
    }
```

Body:
I have a very simple structure for managing permissions where I have a table of users and a table of roles and a many-to-many mapping between them. This is working in the "old" way of setting up Sequelize. But, I'm about to add a bunch more complicated stuff, and am moving to the cli/migration model of defining models. I figured I'd start by getting my existing stuff working the new way.

As I understand things, there's no way to pass association information to the CLI during the generate phase, so you have to manually go back and add the associations. Moreover, when using this method instead of sync, you also have to create a separate migration file for the junction table. This can be facilitated by the generate command, but again needs to be manually configured.

I have all of that "done", such that db:migrate works; however, I'm running into errors when I try to actually use it in Node.

Here are the (modified) files in ./models:

role.js:

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Role extends Model {
    static associate(models) {
      models.Role.belongsToMany(models.User, {
        through: models.UserRole
      })
    }
  }
  Role.init({
    name: DataTypes.STRING
  }, {
    sequelize,
    modelName: 'Role',
  });
  return Role;
};

user.js:

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class User extends Model {
    static associate(models) {
      models.User.belongsToMany(models.Role, {
        through: models.UserRole
      })
    }
  }
  User.init({
    username: DataTypes.STRING,
    email: DataTypes.STRING,
    password: DataTypes.STRING
  }, {
    sequelize,
    modelName: 'User',
  });
  return User;
};

userrole.js:

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class UserRole extends Model {
    static associate(models) {
      // define association here
    }
  }
  UserRole.init({
    userId: {
      type: DataTypes.INTEGER,
      references: {
        model: User, // <--- this is the complaint
        key: 'id'
      }
    },
    roleId: {
      type: DataTypes.INTEGER,
      references: {
        model: Role,
        key: 'id'
      }
    }
  }, {
    sequelize,
    modelName: 'UserRole',
  });
  return UserRole;
};

These are all read in with the autogenerated index.js.

When I spin things up with nodemon, it complains

userrole.js:20
        model: User,
               ^

ReferenceError: User is not defined

I tried modifying that line to model: models.User, but then it complains ReferenceError: models is not defined.

I'm sure I'm missing something quite simple here, but, how do I get those references into the model file for the junction table?

FWIW, this is with

sequelize@6.16.0
node v14.17.3

and I have it using sqlite as the dialect in the development environment.


问:
How to pass an SVG file from a views function to a template?
Within my views.py file I have a function that when called via a request, generates an .svg file. I then want this function to render the template and display said .svg file.

Code I have so far (simplified):

views:

def home(request):
    # ---------------------------------------
    # generate test.svg file and save to a buffer
    # ---------------------------------------

    svg_data = open("buffer/test.svg", "rb").read()

    data = {
        'image': svg_data
        }

    return render(request, 'blog/home.html', data)
```

<p>template:</p>

<pre class="lang-html prettyprint-override"><code>{% extends "blog/base.html" %}
{% block content %}
<svg>
    {{ image }}
</svg>
{% endblock content %}
</code>```

Unfortunately when I attempt to access the {{ image }} tag within the template, it displays nothing. So I ask, is there a way that I can load an .svg file in my views function and have it displayed within my template?

答:
I came across a same problem where when I had passed the svg as text to the django template, and it simply displayed the text as opposed to rendering it. The error turned out to be due to the svg text itself being rendered as a string.

If you check your HTML console you should be able to see that the svg text will be stringified.

The easiest way I solved it is with the safe filter, e.g.,

```<code>{{ svg_data|safe}}
</code>```

In the case of the OP it should have worked with

```<code>{{ image|safe }}
</code>```

Body:
Within my views.py file I have a function that when called via a request, generates an .svg file. I then want this function to render the template and display said .svg file.

Code I have so far (simplified):

views:

def home(request):
    # ---------------------------------------
    # generate test.svg file and save to a buffer
    # ---------------------------------------

    svg_data = open("buffer/test.svg", "rb").read()

    data = {
        'image': svg_data
        }

    return render(request, 'blog/home.html', data)

template:

{% extends "blog/base.html" %}
{% block content %}
<svg>
    {{ image }}
</svg>
{% endblock content %}

Unfortunately when I attempt to access the {{ image }} tag within the template, it displays nothing. So I ask, is there a way that I can load an .svg file in my views function and have it displayed within my template?

Body:
I came across a same problem where when I had passed the svg as text to the django template, and it simply displayed the text as opposed to rendering it. The error turned out to be due to the svg text itself being rendered as a string.

If you check your HTML console you should be able to see that the svg text will be stringified.

The easiest way I solved it is with the safe filter, e.g.,

{{ svg_data|safe}}

In the case of the OP it should have worked with

{{ image|safe }}


问:
Printing Armstrong Numbers from a Range in a For Loop as an Array *Python*
I'm trying to print armstrong values from a specified range in an array style format.
My current code is as below:

```<code>def main():

#Low and high set the bounds for the loop
low = 100

high = 499

#start the for loop for num in the range initialized
for num in range(low, high +1):

    #gets the exponent for each number
    ind_num = len(str(num))

    #initializes the addition of each number
    add = 0

    # sets x equal to num so we can check if the number is armstrong or not
    x = num

    #calculates the armstrong
    while x > 0:
        digit = x % 10

        add += digit ** ind_num

        x //= 10

    if num ==  add:

       print(num)

if __name__ == "__main__":
    main()
</code>```

The output comes out to be:

```<code>153
370
371
407
</code>```

and I want it to be:  [153, 370, 371, 407]
I'm probably thinking too hard on how to make the integers that come out of the for loop arrange as an array, but so far changing them to strings and appending them with a separate defined array variable did not work.

答:
This is as simple as adding the items to a list and then printing the list.

At the start of your main() function add in a variable output = []. Then in your if statement if num == add:, instead of calling print do output.append(num). Then at the end of your main() function print the list, print(output).

Body:
I'm trying to print armstrong values from a specified range in an array style format.
My current code is as below:

def main():

#Low and high set the bounds for the loop
low = 100

high = 499

#start the for loop for num in the range initialized
for num in range(low, high +1):

    #gets the exponent for each number
    ind_num = len(str(num))

    #initializes the addition of each number
    add = 0

    # sets x equal to num so we can check if the number is armstrong or not
    x = num

    #calculates the armstrong
    while x > 0:
        digit = x % 10

        add += digit ** ind_num

        x //= 10

    if num ==  add:

       print(num)

if __name__ == "__main__":
    main()

The output comes out to be:

153
370
371
407

and I want it to be:  [153, 370, 371, 407]
I'm probably thinking too hard on how to make the integers that come out of the for loop arrange as an array, but so far changing them to strings and appending them with a separate defined array variable did not work.


答:
Gitlab variables can not perform bash operations as you try here.

Gitlab understands ${VARIABLE_NAME}

In your case

```<code>${CI_MERGE_REQUEST_SOURCE_BRANCH_NAME:-${CI_COMMIT_BRANCH:-$CI_DEFAULT_BRANCH}}
</code>```

Gitlab tries to find the variable CI_MERGE_REQUEST_SOURCE_BRANCH_NAME:-${CI_COMMIT_BRANCH:-$CI_DEFAULT_BRANCH}

But this variable doesn't exist, so it only outputs }

Title: Why doesn't nested parameter expansion work correctly in GitLab CI/CD?

Body:
Gitlab variables can not perform bash operations as you try here.

Gitlab understands ${VARIABLE_NAME}

In your case

${CI_MERGE_REQUEST_SOURCE_BRANCH_NAME:-${CI_COMMIT_BRANCH:-$CI_DEFAULT_BRANCH}}

Gitlab tries to find the variable CI_MERGE_REQUEST_SOURCE_BRANCH_NAME:-${CI_COMMIT_BRANCH:-$CI_DEFAULT_BRANCH}

But this variable doesn't exist, so it only outputs }


问:
Attach sameplerate or dmix ALSA plugin to OSS device
I have an application in an embedded system that has a application which is OSS based.  Unfortunately, this application is at a fixed sample rate (8K), but I need it to be at 48K.  Furthermore, I can't change the application.

I'm researching sample rate conversion plugins, such as dmix or libsamplerate, but I don't see how to use that with OSS.

Can somebody please point me in the right direction?  Can I configure ALSA in such a way as to convert the OSS interface from 8K->48K in/out of the system?

TIA

Mike

答: What you want is the alsa-oss package which provides a tool you can use to run a program and redirect it's OSS sound output into ALSA where all the normal ALSA tools are available.


问:
setting up elasticSearch with Postgresql
where do I find a howto to set up elasticSearch using Postgres?

My field sizes will be about 350mb, yes, MB, each in size.  I have a
text output of all of the US Code and all decisions from all the courts,
the Statutes at Large, pretty much everything you would find in a library,
and I need to be able to do full text searches and return the exact point
in the field to the app to return the exact page in PDF form.  Postgres
can easily handle the datastore, but I've never used elasticSearch and
have no idea of how it integrates into the indexing, etc.

答:
Its possible to insert/update/delete postgres data in elasticsearch without middle ware other than the pgsql_http extension.  Using triggers you can get a pretty much real-time index update.

You can also query elasticsearch and use the results within postgres to do joins etc with other tables/data in your database.

See the elasticsearch examples: https://github.com/sysadminmike/pgsql-http_examples

ContentLicense: CC BY-SA 2.5


问:
In what library is dgesvd_?
I'm trying to use the function dgesvd_() in a code and just can't find the library I have to include in order to the compiler to detect it!

I've only discovered some LAPACK or something like that but couldn't see includes or relevant information anywhere.

答: dgesvd computes the singular value decomposition (SVD) of a real matrix. It is a part of LAPACK. LAPACK is not really a library but an interface for numerical algebra functions. The standard implementation is the one provided by Netlib LAPACK. However, the Intel MKL also implement this (more efficiently than the one of Netlib). LAPACKE is a C interface of the FORTRAN one provided by the Netlib implementation. It provides a header than can be used for C project to call LAPACK functions (linked at runtime). You could use it in your C project as long as you link a LAPACK-compatible library.

Title: In what library is dgesvd_?


问:
Accessing equal earth projection with sf
I'm a little confused why I'm not able to iplement the equal earth projection using sf in R, or how to diagnose why this is.

When I check my crs options with sf_proj_info("proj") it appears as an option.

But if whenever I try to implement it with st_crs("+proj=eqearth") or st_crs("eqearth") I'm told that it is an invalid crs.

Am I misunderstanding whether this is an available option? implementing it incorrectly for transforming/projecting? Or all of the above?

Just trying to display the whole earth without grossly distorting areas near the poles...

答:
It works for me using sp, give or take some warnings:

```<code>> library(sf)
Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1; sf_use_s2() is TRUE
> library(sp)
> library(rnaturalearth)
> coast = ne_coastline(returnclass="sp")
>
> coast_eq = spTransform(coast, "+proj=eqearth")
Warning messages:
1: In spTransform(xSP, CRSobj, ...) :
  NULL source CRS comment, falling back to PROJ string
2: In wkt(obj) : CRS object has no comment
> plot(coast_eq)
</code>```

And one glitchy coordinate that has popped over to the wrong side of the -180 line:

You could then convert this to an sf class with coast_sf = st_as_sf(coast_eq).

But I don't understand the root cause yet...

Body:
It works for me using sp, give or take some warnings:

> library(sf)
Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1; sf_use_s2() is TRUE
> library(sp)
> library(rnaturalearth)
> coast = ne_coastline(returnclass="sp")
>
> coast_eq = spTransform(coast, "+proj=eqearth")
Warning messages:
1: In spTransform(xSP, CRSobj, ...) :
  NULL source CRS comment, falling back to PROJ string
2: In wkt(obj) : CRS object has no comment
> plot(coast_eq)

And one glitchy coordinate that has popped over to the wrong side of the -180 line:

You could then convert this to an sf class with coast_sf = st_as_sf(coast_eq).

But I don't understand the root cause yet...


问:
Angular way of doing javascript getById code
I'm working on a migration project from AngularJS to Angular8

where I came across this code

```<code>// get the pattern from SVG document and set the stroke color
 var patternElt = $scope.svgDocument.find("#striped");
 patternElt.css("fill", color);
 // apply the striped class to the element
 element.css("fill", "url(#striped)");
 $(zoneClassSelector, element).css("fill", "url(#striped)");
</code>```

what the above code does is when an element is clicked, it gets a pattern element from an svg file (below) and adds a fill color to it, and then applies it on the clicked DOM element :

```<code><defs>
    <pattern id="striped"
        width="8" height="8"
        patternUnits="userSpaceOnUse"
        patternTransform="rotate(45)">
        <rect width="4" height="8" transform="translate(0,0)"></rect>
    </pattern>
</defs>
</code>```

In my case in Typescript code I have the following

```<code>click($event: MouseEvent) {

let clickedEl = $event.target;
// check if clicked element is not an svg element
if (clickedEl instanceof SVGPolygonElement || clickedEl instanceof SVGPathElement || clickedEl instanceof SVGGElement) {
  this.renderer.setAttribute(clickedEl, "style", "fill:url(#striped);");
}
</code>```

}

Note: the SVG file is loaded with its path (no SVG xml in the component view to reference)

How could I get the striped  pattern element using Typscript to add a fill color to it before pass it to the renderer setAttribute

答:
You can try using document.querySelector()

public fillColor(): void {
  const rectElement: SVGRectElement = document.querySelector('#striped') as SVGRectElement;
  rectElement.style.fill = 'red';
}
```
<pre class="lang-html prettyprint-override"><code><svg (click)="fillColor()">
  <defs>
    <pattern id="Pattern" width=".25" height=".25">
      <rect x="0" y="0" id="striped" width="50" height="50" />
    </pattern>
  </defs>
  <rect fill="url(#Pattern)" width="200" height="200" />
</svg>
</code>```

Body:
I'm working on a migration project from AngularJS to Angular8

where I came across this code

// get the pattern from SVG document and set the stroke color
 var patternElt = $scope.svgDocument.find("#striped");
 patternElt.css("fill", color);
 // apply the striped class to the element
 element.css("fill", "url(#striped)");
 $(zoneClassSelector, element).css("fill", "url(#striped)");

what the above code does is when an element is clicked, it gets a pattern element from an svg file (below) and adds a fill color to it, and then applies it on the clicked DOM element :

<defs>
    <pattern id="striped"
        width="8" height="8"
        patternUnits="userSpaceOnUse"
        patternTransform="rotate(45)">
        <rect width="4" height="8" transform="translate(0,0)"></rect>
    </pattern>
</defs>

In my case in Typescript code I have the following

click($event: MouseEvent) {

let clickedEl = $event.target;
// check if clicked element is not an svg element
if (clickedEl instanceof SVGPolygonElement || clickedEl instanceof SVGPathElement || clickedEl instanceof SVGGElement) {
  this.renderer.setAttribute(clickedEl, "style", "fill:url(#striped);");
}

}

Note: the SVG file is loaded with its path (no SVG xml in the component view to reference)

How could I get the striped  pattern element using Typscript to add a fill color to it before pass it to the renderer setAttribute

Body:
You can try using document.querySelector()

public fillColor(): void {
  const rectElement: SVGRectElement = document.querySelector('#striped') as SVGRectElement;
  rectElement.style.fill = 'red';
}

<svg (click)="fillColor()">
  <defs>
    <pattern id="Pattern" width=".25" height=".25">
      <rect x="0" y="0" id="striped" width="50" height="50" />
    </pattern>
  </defs>
  <rect fill="url(#Pattern)" width="200" height="200" />
</svg>


问:
Flutter: wasm streaming compile failed: TypeError: Could not download wasm module
I'm building a Flutter web app. Everything was working fine until randomly I did a hot restart and then I began getting this error.

wasm streaming compile failed: TypeError: Could not download wasm module

Tried 2 things

Reverted the code back to a known working state (from git source control) and I still get this error.

Created NEW Flutter project from Android studio using New Flutter project options. Still did not work.

Any ideas? I tried to update Chrome and this did not help.

答: I lived in a remote area where no broadband is available so I use wireless network through sim card. The operator network is disturbing ,I can browse website sometimes and some times bit laggy on the other hand my flutter project work on emulator but I can not run it web. I changed the operator network and get a good quality of internet connection than The issue gone. What I think some module in web need to build good internet connection. I don't know this answer is helpful or not but this is how I solve my issue</p>


问:
How to test a date is later/greater than another in jest?
I understand that JavaScript allows for basic comparison between dates e.g.,

```<code>const dateOne = new Date();
const dateTwo = new Date();

return dateTwo > dateOne;
</code>```

I can see there is a .toBeGreaterThan() expectation in Jest, but this is only for numbers or big ints. Is there something available for dates to compare one is later than another?

答: Just use date.getTime(), that'll return the date in unix milliseconds.

Body:
I understand that JavaScript allows for basic comparison between dates e.g.,

const dateOne = new Date();
const dateTwo = new Date();

return dateTwo > dateOne;

I can see there is a .toBeGreaterThan() expectation in Jest, but this is only for numbers or big ints. Is there something available for dates to compare one is later than another?


问:
Webpack can't resolve asset/resource?
I am trying to load an image in a project using webpack

```<code>asset
  resource
    image.png
src
  components
    global
      module
        module.js
</code>```

In my js file, I have this line

import image from '../../../../asset/resource/image.png'
```
<p>And in my webpack.config.js:</p>
<pre class="lang-js prettyprint-override"><code>module.exports = {
  // snip
  module: {
    rules: [
      // snip
      {
        test: /\.png$/i,
        use: 'asset/resource'
      }
    ]
  },
  // snip
}
</code>```

But on start, webpack throw an error:

ERROR in ./src/components/global/module/module.riot 1:0-86
Module not found: Error: Can't resolve 'asset/resource' in '/path/to/my/project'
resolve 'asset/resource' in '/path/to/my/project'
  Parsed request is a module
  using description file: /path/to/my/project/package.json (relative path: .)
    resolve as module
      looking for modules in /path/to/my/project/node_modules
        /path/to/my/project/node_modules/asset doesn't exist
      /path/to/my/node_modules doesn't exist or is not a directory
      /path/to/node_modules doesn't exist or is not a directory
      /path/node_modules doesn't exist or is not a directory
      /node_modules doesn't exist or is not a directory
 @ ./src/components/global/ sync [a-zA-Z0-9-]+\.riot ./module/module.riot
 @ ./src/register-global-components.js 4:32-100
 @ ./src/index.js 4:0-67 7:0-24

webpack 5.66.0 compiled with 1 error in 3616 ms
```

So it looks like webpack doesn't find it's own built in package ? The doc s quite clear about t being built in and I don't see the difference with their example.

答:
Regarding your provided snippet, it looks like it should be type: 'asset/resource' instead of use: 'asset/resource.

```<code>module.exports = {
  // snip
  module: {
    rules: [
      // snip
      {
        test: /\.png$/i,
        // use: 'asset/resource'
        type: 'asset/resource'
      }
    ]
  },
  // snip
}
</code>```

Here's the documentation example:

```<code> const path = require('path');

 module.exports = {
   entry: './src/index.js',
   output: {
     filename: 'bundle.js',
     path: path.resolve(__dirname, 'dist'),
   },
   module: {
     rules: [
       {
         test: /\.css$/i,
         use: ['style-loader', 'css-loader'],
       },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource', // EXAMPLE HERE
      },
     ],
   },
 };
</code>```

Title: Webpack can't resolve asset/resource?

Body:
I am trying to load an image in a project using webpack

asset
  resource
    image.png
src
  components
    global
      module
        module.js

In my js file, I have this line

import image from '../../../../asset/resource/image.png'

And in my webpack.config.js:

module.exports = {
  // snip
  module: {
    rules: [
      // snip
      {
        test: /\.png$/i,
        use: 'asset/resource'
      }
    ]
  },
  // snip
}

But on start, webpack throw an error:

ERROR in ./src/components/global/module/module.riot 1:0-86
Module not found: Error: Can't resolve 'asset/resource' in '/path/to/my/project'
resolve 'asset/resource' in '/path/to/my/project'
  Parsed request is a module
  using description file: /path/to/my/project/package.json (relative path: .)
    resolve as module
      looking for modules in /path/to/my/project/node_modules
        /path/to/my/project/node_modules/asset doesn't exist
      /path/to/my/node_modules doesn't exist or is not a directory
      /path/to/node_modules doesn't exist or is not a directory
      /path/node_modules doesn't exist or is not a directory
      /node_modules doesn't exist or is not a directory
 @ ./src/components/global/ sync [a-zA-Z0-9-]+\.riot ./module/module.riot
 @ ./src/register-global-components.js 4:32-100
 @ ./src/index.js 4:0-67 7:0-24

webpack 5.66.0 compiled with 1 error in 3616 ms

So it looks like webpack doesn't find it's own built in package ? The doc s quite clear about t being built in and I don't see the difference with their example.

Body:
Regarding your provided snippet, it looks like it should be type: 'asset/resource' instead of use: 'asset/resource.

module.exports = {
  // snip
  module: {
    rules: [
      // snip
      {
        test: /\.png$/i,
        // use: 'asset/resource'
        type: 'asset/resource'
      }
    ]
  },
  // snip
}

Here's the documentation example:

 const path = require('path');

 module.exports = {
   entry: './src/index.js',
   output: {
     filename: 'bundle.js',
     path: path.resolve(__dirname, 'dist'),
   },
   module: {
     rules: [
       {
         test: /\.css$/i,
         use: ['style-loader', 'css-loader'],
       },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource', // EXAMPLE HERE
      },
     ],
   },
 };


问:
How can I use a SystemAssigned identity when pulling an image from Azure Container Registry into Azure Container Instances?
I want to create a container (or container group) in Azure Container Instances, pulling the image(s) from Azure Container Registry - but with using a SystemAssigned identity. With that I want to avoid using ACR login credentials, a service principal or a UserAssigned identity.

When I run this script (Azure CLI in PowerShell) ...

```<code>$LOC = "westeurope"
$RG = "myresourcegroup"
$ACRNAME = "myacr"

az configure --defaults location=$LOC group=$RG

$acr = az acr show -n $ACRNAME -o json | ConvertFrom-Json -Depth 10

az container create --name app1 --image $($acr.loginServer+"/app1") `
    --assign-identity --role acrpull --scope $acr.id `
    --debug
</code>```

... ACI does not seem to recognize that it should be already authorized for ACR and shows this prompt:

```<code>Image registry username:
</code>```

Azure CLI version: 2.14.0

Does this make sense? Is the ACI managed identity supported for ACR?

答: From Jan 2022 on managed identity is supported on Azure Container Instance to access Azure Container Registry: https://learn.microsoft.com/en-us/azure/container-instances/using-azure-container-registry-mi</p>

Body:
I want to create a container (or container group) in Azure Container Instances, pulling the image(s) from Azure Container Registry - but with using a SystemAssigned identity. With that I want to avoid using ACR login credentials, a service principal or a UserAssigned identity.

When I run this script (Azure CLI in PowerShell) ...

$LOC = "westeurope"
$RG = "myresourcegroup"
$ACRNAME = "myacr"

az configure --defaults location=$LOC group=$RG

$acr = az acr show -n $ACRNAME -o json | ConvertFrom-Json -Depth 10

az container create --name app1 --image $($acr.loginServer+"/app1") `
    --assign-identity --role acrpull --scope $acr.id `
    --debug

... ACI does not seem to recognize that it should be already authorized for ACR and shows this prompt:

Image registry username:

Azure CLI version: 2.14.0

Does this make sense? Is the ACI managed identity supported for ACR?


问:
The width of dropdown is changing based on selected item in Antd React
The width of the dropdown is changing based on dropdown list.

```<code>let drop = ['Abhiram', 'Bhanu', 'Dhanunjay Ram']
    let menu = (
        <Menu onClick={this.handleMenuClick}>
            { drop && (
                drop.map((item, i) => {
                    return (
                        <Menu.Item key={i} icon={<UserOutlined />}>{item}</Menu.Item>
                    )
                })
            )}
        </Menu>
      );
<div>
     <Dropdown overlay={menu} trigger={['click']}>
        <Button> Abhiram </Button>
      </Dropdown>
</div>
</code>```

So, here when i select 'Abhiram'. It display Abhiram as selected dropdown and same applies for Bhanu and Dhanunjay Ram. Here, the issue is after selecting the width of dropdown is changing.
I don't want to change the width of dropdown after selecting from list

答:
Try setting the width of the Dropdown component like so:

```<code><Dropdown overlay={menu} trigger={['click']} style={{width: "100px"}}>
</code>```

Body:
The width of the dropdown is changing based on dropdown list.

let drop = ['Abhiram', 'Bhanu', 'Dhanunjay Ram']
    let menu = (
        <Menu onClick={this.handleMenuClick}>
            { drop && (
                drop.map((item, i) => {
                    return (
                        <Menu.Item key={i} icon={<UserOutlined />}>{item}</Menu.Item>
                    )
                })
            )}
        </Menu>
      );

     <Dropdown overlay={menu} trigger={['click']}>
        <Button> Abhiram </Button>
      </Dropdown>

So, here when i select 'Abhiram'. It display Abhiram as selected dropdown and same applies for Bhanu and Dhanunjay Ram. Here, the issue is after selecting the width of dropdown is changing.
I don't want to change the width of dropdown after selecting from list

Body:
Try setting the width of the Dropdown component like so:

<Dropdown overlay={menu} trigger={['click']} style={{width: "100px"}}>


问:
Blank screen after deploying react app on Vercel
My package.json file where I also tried including the previous solutions "homepage"... in this

Any syntax mistakes or references I mistakenly added here in here ? My build was successful but all I could see i a blank page in my deployed site

```<code>{
  "name": "react-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@date-io/date-fns": "^1.3.13",
    "@material-ui/core": "^4.12.2",
    "@material-ui/pickers": "^3.3.10",
    "@reduxjs/toolkit": "^1.6.1",
    "@syncfusion/ej2-react-calendars": "^19.2.55",
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "axios": "^0.21.1",
    "bootstrap": "^5.0.2",
    "framer-motion": "^4.1.17",
    "mdbreact": "^5.1.0",
    "react": "^17.0.2",
    "react-bootstrap": "^2.0.0-beta.4",
    "react-calendar": "^3.4.0",
    "react-datepicker": "^4.1.1",
    "react-dom": "^17.0.2",
    "react-icons": "^4.2.0",
    "react-minimal-side-navigation": "^1.9.2",
    "react-redux": "^7.2.4",
    "react-router-dom": "^5.2.0",
    "react-scripts": "^4.0.3",
    "react-switch": "^6.0.0",
    "rsuite": "^4.10.2",
    "web-vitals": "^1.0.1",
    "homepage": "."
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
</code>```

My App.js file where I imported all my React and Redux Routers..

```<code>import "./App.css";
import Sidebar from "./Components/Sidebar";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import FoodCatalog from "./Components/Pages/FoodCatalog";
import 'bootstrap/dist/css/bootstrap.min.css';
import Promotions from "./Components/Pages/Promotions";
import UserManagement from "./Components/Pages/UserManagement";
import axios from 'axios';
import { Provider } from "react-redux";
import thunk from "redux-thunk";
import { createStore, applyMiddleware, compose } from "redux";
import reducer from './redux/reducers'
import Tickets from "./Components/Pages/Tickets";

function App() {
  return (
    <Provider store={store}>
    <BrowserRouter>
      <div className="App">
        <div>
          <Sidebar />
        </div>

        <div style={{width: '100%',overflow: 'hidden'}}>
          <Switch>
            <Route path="/foodcatalog" component={FoodCatalog } />
            <Route path="/promotions" component={Promotions } />
            <Route path="/usermanagement" component={UserManagement } />
            <Route path="/tickets" component={Tickets } />
          </Switch>

        </div>
      </div>
    </BrowserRouter>
    </Provider>
  );
}

export default App;
</code>```

答:
Specifiying “homepage”

If you’re using create-react-app, you won’t have to deal with Webpack configs. (Which is nice) Instead – ejected or not –  we just have to specify “homepage” in our package.json:

example

The way how create-react-app has it’s webpack configuration set up, this will replace the publicPath with the correct base URL for your app. (If you want to know more about the publicPath setting,  have a look at the Webpack documentation)

Refer this: https://www.andreasreiterer.at/fix-whitescreen-static-react-app/

Body:
My package.json file where I also tried including the previous solutions "homepage"... in this

Any syntax mistakes or references I mistakenly added here in here ? My build was successful but all I could see i a blank page in my deployed site

{
  "name": "react-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@date-io/date-fns": "^1.3.13",
    "@material-ui/core": "^4.12.2",
    "@material-ui/pickers": "^3.3.10",
    "@reduxjs/toolkit": "^1.6.1",
    "@syncfusion/ej2-react-calendars": "^19.2.55",
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "axios": "^0.21.1",
    "bootstrap": "^5.0.2",
    "framer-motion": "^4.1.17",
    "mdbreact": "^5.1.0",
    "react": "^17.0.2",
    "react-bootstrap": "^2.0.0-beta.4",
    "react-calendar": "^3.4.0",
    "react-datepicker": "^4.1.1",
    "react-dom": "^17.0.2",
    "react-icons": "^4.2.0",
    "react-minimal-side-navigation": "^1.9.2",
    "react-redux": "^7.2.4",
    "react-router-dom": "^5.2.0",
    "react-scripts": "^4.0.3",
    "react-switch": "^6.0.0",
    "rsuite": "^4.10.2",
    "web-vitals": "^1.0.1",
    "homepage": "."
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

My App.js file where I imported all my React and Redux Routers..

import "./App.css";
import Sidebar from "./Components/Sidebar";
import { BrowserRouter, Route, Switch } from "react-router-dom";
import FoodCatalog from "./Components/Pages/FoodCatalog";
import 'bootstrap/dist/css/bootstrap.min.css';
import Promotions from "./Components/Pages/Promotions";
import UserManagement from "./Components/Pages/UserManagement";
import axios from 'axios';
import { Provider } from "react-redux";
import thunk from "redux-thunk";
import { createStore, applyMiddleware, compose } from "redux";
import reducer from './redux/reducers'
import Tickets from "./Components/Pages/Tickets";

function App() {
  return (
    <Provider store={store}>
    <BrowserRouter>

          <Sidebar />

          <Switch>
            <Route path="/foodcatalog" component={FoodCatalog } />
            <Route path="/promotions" component={Promotions } />
            <Route path="/usermanagement" component={UserManagement } />
            <Route path="/tickets" component={Tickets } />
          </Switch>

    </BrowserRouter>
    </Provider>
  );
}

export default App;


问:
How to read property of control defined inside style in silverlight.?
I am using NumericUpDown control in my silver-light application. Code is as follows

```<code> <StackPanel Style="{StaticResource StackPanelStyle_LableValue}">
                        <TextBlock Text="{Binding Path=ViewItem.Strength, Source={StaticResource LocalizedStrings }}" Style="{StaticResource TextBlockStyle}" />
                        <inputToolkit:NumericUpDown Style="{StaticResource NumericUpdownStyle_Strength}"
                                                    Value="{Binding RightSpecGlassStrength, Mode=TwoWay, ValidatesOnNotifyDataErrors=True, NotifyOnValidationError=True}"
                                                    TabIndex="5" />
                    </StackPanel>
</code>```

and Style that i bind to NumericUpDown control as follows

```<code> <Style x:Key="NumericUpdownStyle_Strength" TargetType="inputToolkit:NumericUpDown">
    <Setter Property="Width" Value="Auto"></Setter>
    <Setter Property="MinWidth" Value="50"></Setter>
    <Setter Property="Height" Value="20"></Setter>
    <Setter Property="Minimum" Value="-28"></Setter>
    <Setter Property="Maximum" Value="28"></Setter>
    <Setter Property="BorderThickness" Value="0"></Setter>
    <Setter Property="BorderBrush" Value="White"></Setter>
    <Setter Property="DecimalPlaces" Value="2"></Setter>
    <Setter Property="Increment" Value="0.25"></Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="inputToolkit:NumericUpDown">
                <Grid>
                    <VisualStateManager.VisualStateGroups>

                        <VisualStateGroup x:Name="CommonStates">
                            <VisualStateGroup.Transitions>
                                <VisualTransition GeneratedDuration="0"/>
                            </VisualStateGroup.Transitions>
                            <VisualState x:Name="Normal"/>
                            <VisualState x:Name="Disabled">
                                <Storyboard>
                                    <DoubleAnimation Duration="0" Storyboard.TargetName="DisabledVisualElement" Storyboard.TargetProperty="(UIElement.Opacity)" To="1"/>
                                </Storyboard>
                            </VisualState>
                        </VisualStateGroup>
                        <VisualStateGroup x:Name="FocusStates">
                            <VisualState x:Name="Focused">
                                <Storyboard>
                                    <DoubleAnimationUsingKeyFrames Storyboard.TargetName="FocusVisualElement" Storyboard.TargetProperty="Opacity">
                                        <SplineDoubleKeyFrame KeyTime="0" Value="1"/>
                                    </DoubleAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Unfocused"/>
                        </VisualStateGroup>

                        <VisualStateGroup x:Name="ValidationStates">
                            <VisualState x:Name="Valid"/>
                            <VisualState x:Name="InvalidUnfocused">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ValidationErrorElement" Storyboard.TargetProperty="Visibility">
                                        <DiscreteObjectKeyFrame KeyTime="0">
                                            <DiscreteObjectKeyFrame.Value>
                                                <Visibility>Visible</Visibility>
                                            </DiscreteObjectKeyFrame.Value>
                                        </DiscreteObjectKeyFrame>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="InvalidFocused">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ValidationErrorElement" Storyboard.TargetProperty="Visibility">
                                        <DiscreteObjectKeyFrame KeyTime="0">
                                            <DiscreteObjectKeyFrame.Value>
                                                <Visibility>Visible</Visibility>
                                            </DiscreteObjectKeyFrame.Value>
                                        </DiscreteObjectKeyFrame>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="validationTooltip" Storyboard.TargetProperty="IsOpen">
                                        <DiscreteObjectKeyFrame KeyTime="0">
                                            <DiscreteObjectKeyFrame.Value>
                                                <sys:Boolean>True</sys:Boolean>
                                            </DiscreteObjectKeyFrame.Value>
                                        </DiscreteObjectKeyFrame>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                        </VisualStateGroup>

                    </VisualStateManager.VisualStateGroups>
                    <inputToolkit:ButtonSpinner x:Name="Spinner" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" MinWidth="35">
                        <StackPanel Background="White" Orientation="Horizontal" HorizontalAlignment="Right" Width="Auto">
                            <TextBox x:Name="Text"  Style="{StaticResource TextBoxStyle}" TabIndex="0"
                                 BorderThickness="0" FontFamily="{TemplateBinding FontFamily}" FontSize="{TemplateBinding FontSize}" FontStretch="{TemplateBinding FontStretch}" FontStyle="{TemplateBinding FontStyle}" FontWeight="{TemplateBinding FontWeight}" Foreground="{TemplateBinding Foreground}" MinWidth="50" Width="Auto"  AcceptsReturn="False" Text="{TemplateBinding Value}" TextAlignment="Left" TextWrapping="NoWrap"/>
                        </StackPanel>
                    </inputToolkit:ButtonSpinner>
                    <Border x:Name="DisabledVisualElement" IsHitTestVisible="false" Opacity="0" Background="#A5FFFFFF" CornerRadius="2.5,2.5,2.5,2.5"/>
                    <Border x:Name="FocusVisualElement" IsHitTestVisible="False" Opacity="0" BorderBrush="#FF45D6FA" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="1,1,1,1"/>
                    <Border x:Name="ValidationErrorElement" Visibility="Collapsed" BorderBrush="#FFDB000C" BorderThickness="1" CornerRadius="1">
                        <ToolTipService.ToolTip>
                            <ToolTip x:Name="validationTooltip" Height="Auto" Width="Auto" Template="{StaticResource ValidationToolTipTemplate}" DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}" Placement="Right" PlacementTarget="{Binding RelativeSource={RelativeSource TemplatedParent}}">
                                <ToolTip.Triggers>
                                    <EventTrigger RoutedEvent="Canvas.Loaded">
                                        <BeginStoryboard>
                                            <Storyboard>
                                                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="validationTooltip" Storyboard.TargetProperty="IsHitTestVisible">
                                                    <DiscreteObjectKeyFrame KeyTime="0">
                                                        <DiscreteObjectKeyFrame.Value>
                                                            <sys:Boolean>true</sys:Boolean>
                                                        </DiscreteObjectKeyFrame.Value>
                                                    </DiscreteObjectKeyFrame>
                                                </ObjectAnimationUsingKeyFrames>
                                            </Storyboard>
                                        </BeginStoryboard>
                                    </EventTrigger>
                                </ToolTip.Triggers>
                            </ToolTip>
                        </ToolTipService.ToolTip>
                        <Grid Height="12" HorizontalAlignment="Right" Margin="1,-4,-4,0" VerticalAlignment="Top" Width="12" Background="Transparent">
                            <Path Fill="#FFDC000C" Margin="1,3,0,0" Data="M 1,0 L6,0 A 2,2 90 0 1 8,2 L8,7 z"/>
                            <Path Fill="#ffffff" Margin="1,3,0,0" Data="M 0,0 L2,0 L 8,6 L8,8"/>
                        </Grid>
                    </Border>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

I found bug while running appliction build using above code.

To solve that bug I want read value that entered TextBox defined inside <inputToolkit:ButtonSpinner > </inputToolkit:ButtonSpinner >  "Text" defined in the style of  App.xaml  for the NumericUpDown control.

How do i read value from textBox at run time on ValueChainging/ValueChanged/GotFocus/LostFocust or any other event of NumericUpDown control.

答:
I have added LostFocus event to text box that is inside <inputToolkit:ButtonSpinner > </inputToolkit:ButtonSpinner > and there in the event i wrote code to achieve my logic. :)

as follows my TextBox will look like

```<code> <TextBox x:Name="Text"  Style="{StaticResource TextBoxStyle}" TabIndex="{TemplateBinding TabIndex}"
                                     BorderThickness="0" FontFamily="{TemplateBinding FontFamily}" FontSize="{TemplateBinding FontSize}" FontStretch="{TemplateBinding FontStretch}" FontStyle="{TemplateBinding FontStyle}" FontWeight="{TemplateBinding FontWeight}" Foreground="{TemplateBinding Foreground}" MinWidth="50" Width="Auto"  AcceptsReturn="False" Text="{TemplateBinding Value}" TextAlignment="Right" TextWrapping="NoWrap" LostFocus="Text_LostFocus"/>
</code>```

Body:
I am using NumericUpDown control in my silver-light application. Code is as follows

 <StackPanel Style="{StaticResource StackPanelStyle_LableValue}">
                        <TextBlock Text="{Binding Path=ViewItem.Strength, Source={StaticResource LocalizedStrings }}" Style="{StaticResource TextBlockStyle}" />
                        <inputToolkit:NumericUpDown Style="{StaticResource NumericUpdownStyle_Strength}"
                                                    Value="{Binding RightSpecGlassStrength, Mode=TwoWay, ValidatesOnNotifyDataErrors=True, NotifyOnValidationError=True}"
                                                    TabIndex="5" />
                    </StackPanel>

and Style that i bind to NumericUpDown control as follows

I found bug while running appliction build using above code.

To solve that bug I want read value that entered TextBox defined inside <inputToolkit:ButtonSpinner > </inputToolkit:ButtonSpinner >  "Text" defined in the style of  App.xaml  for the NumericUpDown control.

How do i read value from textBox at run time on ValueChainging/ValueChanged/GotFocus/LostFocust or any other event of NumericUpDown control.

Body:
I have added LostFocus event to text box that is inside <inputToolkit:ButtonSpinner > </inputToolkit:ButtonSpinner > and there in the event i wrote code to achieve my logic. :)

as follows my TextBox will look like

 <TextBox x:Name="Text"  Style="{StaticResource TextBoxStyle}" TabIndex="{TemplateBinding TabIndex}"
                                     BorderThickness="0" FontFamily="{TemplateBinding FontFamily}" FontSize="{TemplateBinding FontSize}" FontStretch="{TemplateBinding FontStretch}" FontStyle="{TemplateBinding FontStyle}" FontWeight="{TemplateBinding FontWeight}" Foreground="{TemplateBinding Foreground}" MinWidth="50" Width="Auto"  AcceptsReturn="False" Text="{TemplateBinding Value}" TextAlignment="Right" TextWrapping="NoWrap" LostFocus="Text_LostFocus"/>


答: Just add a width css property in select component :)</p>

Title: The width of dropdown is changing based on selected item in Antd React