问:
How to split up a header in angular material table
How to make headers like parent&children in Angular Material?

I wanna have smth like this:

I found only this example:
 https://stackblitz.com/edit/angular-bklajw?file=app%2Ftable-basic-example.html

But I dont need 2 rows of headers.

答:
Welcome to SO, Added 3 header group with col n row span Use below HTMl in  above stack-blitz code to see result

```<code> <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

  <!--- Note that these columns can be defined in any order.
        The actual rendered columns are set as a property on the row definition" -->

  <!-- Position Column -->
  <ng-container matColumnDef="position">
    <th [ngStyle]="{'display': 'none'}" mat-header-cell *matHeaderCellDef [attr.rowspan]="2">  No. </th>
    <td mat-cell *matCellDef="let element"> {{element.position}} </td>
  </ng-container>

  <!-- Name Column -->
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef> Name </th>
    <td mat-cell *matCellDef="let element"> {{element.name}} </td>
  </ng-container>

  <!-- Weight Column -->
  <ng-container matColumnDef="weight">
    <th mat-header-cell *matHeaderCellDef> Weight </th>
    <td mat-cell *matCellDef="let element"> {{element.weight}} </td>
  </ng-container>

  <!-- Symbol Column -->
  <ng-container matColumnDef="symbol">
    <th [attr.rowspan]="2" mat-header-cell *matHeaderCellDef [ngStyle]="{'display': 'none'}"> Symbol </th>
    <td mat-cell *matCellDef="let element"> {{element.symbol}} </td>
  </ng-container>

  <!-- Header row first group -->
  <ng-container matColumnDef="header-row-first-group">
    <th mat-header-cell *matHeaderCellDef
        [style.text-align]="center"
        [attr.rowspan]="2">
      No
    </th>
     </ng-container>
    <ng-container matColumnDef="header-row-sec-group">
     <th mat-header-cell *matHeaderCellDef
        [style.text-align]="center"
        [attr.colspan]="2">
      Name
    </th>
     </ng-container>
    <ng-container matColumnDef="header-row-third-group">
     <th mat-header-cell *matHeaderCellDef
        [style.text-align]="center"
       [attr.rowspan]="2" >
      Role
    </th>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="['header-row-first-group','header-row-sec-group','header-row-third-group']"></tr>
  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</code>```

Body:
Welcome to SO, Added 3 header group with col n row span Use below HTMl in  above stack-blitz code to see result

 <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

  <!--- Note that these columns can be defined in any order.
        The actual rendered columns are set as a property on the row definition" -->

  <!-- Position Column -->
  <ng-container matColumnDef="position">
    <th [ngStyle]="{'display': 'none'}" mat-header-cell *matHeaderCellDef [attr.rowspan]="2">  No. </th>
    <td mat-cell *matCellDef="let element"> {{element.position}} </td>
  </ng-container>

  <!-- Name Column -->
  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef> Name </th>
    <td mat-cell *matCellDef="let element"> {{element.name}} </td>
  </ng-container>

  <!-- Weight Column -->
  <ng-container matColumnDef="weight">
    <th mat-header-cell *matHeaderCellDef> Weight </th>
    <td mat-cell *matCellDef="let element"> {{element.weight}} </td>
  </ng-container>

  <!-- Symbol Column -->
  <ng-container matColumnDef="symbol">
    <th [attr.rowspan]="2" mat-header-cell *matHeaderCellDef [ngStyle]="{'display': 'none'}"> Symbol </th>
    <td mat-cell *matCellDef="let element"> {{element.symbol}} </td>
  </ng-container>

  <!-- Header row first group -->
  <ng-container matColumnDef="header-row-first-group">
    <th mat-header-cell *matHeaderCellDef
        [style.text-align]="center"
        [attr.rowspan]="2">
      No
    </th>
     </ng-container>
    <ng-container matColumnDef="header-row-sec-group">
     <th mat-header-cell *matHeaderCellDef
        [style.text-align]="center"
        [attr.colspan]="2">
      Name
    </th>
     </ng-container>
    <ng-container matColumnDef="header-row-third-group">
     <th mat-header-cell *matHeaderCellDef
        [style.text-align]="center"
       [attr.rowspan]="2" >
      Role
    </th>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="['header-row-first-group','header-row-sec-group','header-row-third-group']"></tr>
  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>


来源: stackexchange

问:
How to change Cursor Icon upon button click on React
How do I change my cursor to be an icon when I click a button and then place that icon down on the second click, and become a regular cursor again? I'm working in React. All I have is that when I button is clicked, the global boolean clicked is turned to true.</p>

答:
Is this useful for what you need?

```<code>const [cursor, setCursor] = useState('crosshair');

  const changeCursor = () => {
    setCursor(prevState => {
      if(prevState === 'crosshair'){
        return 'pointer';
      }
      return 'crosshair';
    });
  }

  return (
    <div className="App" style={{ cursor: cursor }}>

      <h2>Click to change mouse cursor</h2>
      <input  type="button" value="Change cursor"
      onClick={changeCursor}
      style={{ cursor: cursor }}

      />
    </div>
  );
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Is this useful for what you need?

const [cursor, setCursor] = useState('crosshair');

  const changeCursor = () => {
    setCursor(prevState => {
      if(prevState === 'crosshair'){
        return 'pointer';
      }
      return 'crosshair';
    });
  }

  return (
    <div className="App" style={{ cursor: cursor }}>

      <h2>Click to change mouse cursor</h2>
      <input  type="button" value="Change cursor"
      onClick={changeCursor}
      style={{ cursor: cursor }}

      />
    </div>
  );


问:
Pretty Print Distances for iOS
I have two CLLocation objects and I would like the show the distance between them in a nice and pretty format. Like "22 feet", "58 yards", or "2.3 miles"

```<code>CLLocation *location1 = [[CLLocation alloc] initWithLatitude:42.333297 longitude:-71.588858];
CLLocation *location2 = [[CLLocation alloc] initWithLatitude:42.353297 longitude:-71.578858];

float target = [location1 getDistanceFrom:location2];
</code>```

Basically, is there anything in the iOS library that can convert a distance to a pretty string or do I have to do this manually?

答:
```<code>import Foundation

extension Double {
  var prettyDistance: String {
    guard self > -.infinity else { return "?" }

    let formatter = LengthFormatter()
    formatter.numberFormatter.maximumFractionDigits = 2

    if self >= 1000 {
      return formatter.string(fromValue: self / 1000, unit: LengthFormatter.Unit.kilometer)
    } else {
      let value = Double(Int(self))
      return formatter.string(fromValue: value, unit: LengthFormatter.Unit.meter)
    }
  }
}
</code>```

<hr>

```<code>Double(1).prettyDistance // 1 m
Double(10).prettyDistance // 10 m
Double(100).prettyDistance // 100 m
Double(999).prettyDistance // 999 m
Double(1000).prettyDistance // 1 km
Double(1111).prettyDistance // 1.11 km
Double(5555).prettyDistance // 5.56 km
Double(9999).prettyDistance // 10 km
Double(10000).prettyDistance // 10 km
Double(99999).prettyDistance // 100 km
Double(100000).prettyDistance // 100 km
Double(555555).prettyDistance // 555.56 km
Double(999999).prettyDistance // 1,000 km
Double(1000000).prettyDistance // 1,000 km
Double(1234567890).prettyDistance // 1,234,567.89 km
</code>```

ContentLicense: CC BY-SA 3.0

Title: Pretty Print Distances for iOS

Body:
I have two CLLocation objects and I would like the show the distance between them in a nice and pretty format. Like "22 feet", "58 yards", or "2.3 miles"

CLLocation *location1 = [[CLLocation alloc] initWithLatitude:42.333297 longitude:-71.588858];
CLLocation *location2 = [[CLLocation alloc] initWithLatitude:42.353297 longitude:-71.578858];

float target = [location1 getDistanceFrom:location2];

Basically, is there anything in the iOS library that can convert a distance to a pretty string or do I have to do this manually?

Body:
import Foundation

extension Double {
  var prettyDistance: String {
    guard self > -.infinity else { return "?" }

    let formatter = LengthFormatter()
    formatter.numberFormatter.maximumFractionDigits = 2

    if self >= 1000 {
      return formatter.string(fromValue: self / 1000, unit: LengthFormatter.Unit.kilometer)
    } else {
      let value = Double(Int(self))
      return formatter.string(fromValue: value, unit: LengthFormatter.Unit.meter)
    }
  }
}

Double(1).prettyDistance // 1 m
Double(10).prettyDistance // 10 m
Double(100).prettyDistance // 100 m
Double(999).prettyDistance // 999 m
Double(1000).prettyDistance // 1 km
Double(1111).prettyDistance // 1.11 km
Double(5555).prettyDistance // 5.56 km
Double(9999).prettyDistance // 10 km
Double(10000).prettyDistance // 10 km
Double(99999).prettyDistance // 100 km
Double(100000).prettyDistance // 100 km
Double(555555).prettyDistance // 555.56 km
Double(999999).prettyDistance // 1,000 km
Double(1000000).prettyDistance // 1,000 km
Double(1234567890).prettyDistance // 1,234,567.89 km


问:
Is there a dbunit-like framework that doesn't suck for java/scala?
I was thinking of making a new, light-weight database population framework. I absolutely hate dbunit. Before I do, I want to know if someone already did it.

Things i dislike about dbunit:

1) The simplest format to write and get started is deprecated. They want you to use formats that are bloated. Some even require xml schemas. Yeah, whatever.

2) They populate rows not in the order you write them, but in the order tables are defined in the xml file. This is really bad because you can't order your data in such a way that foreign key constraints won't cause problems. This just forces you to go through the hassle of turning them off altogether.

This also wastes time and bloats up your junit base classes to include code to disable the foreign key constraints. You will probably have to test for the database type (hsqldb, etc.) and disable them in database-specific ways. This is way bad.

It could be better if dbunit helped in disabling foreign key constraints as part of their framework automatically, but they don't do this. They do keep track of dialects... so why not use them for this? Ultimately, all of this does is force the programmer to waste time and not get up and testing quickly.

3) XML is a pain to write. I don't need to say more about this. They also offer so many ways to do it, that I think it just complicates matters. Just offer one really solid way and be done with it.

4) When your data gets large, keeping track of the ids and their consistent/correct relationships is a royal pain.

Also, if you don't work on a project for a month, how are you to remember that user_id 1 was an admin, user_id 2 was a business user, user_id 3 was an engineer and user_id 4 was something else? Going back to check this is wasting more time. There should be a meaningful way to retrieve it other than an arbitrary number.

5) It's slow. I've found that unless hsqldb is used, it is painfully slow. It doesn't have to be. There are also numerous ways to mess up its configuration as it is not easy to do "out of the box". There is a hump that you must go through to get it working right. All this does is encourage people to not use it, or be pissed of when they do start to use it.

6) Some values tend to repeat a lot, likes dates. It'd be nice to specify defaults, or even have the framework put defaults in automatically, even without you telling it to put defaults in there. That way you can create objects just with the values you want, and leave the rest off. This sure beats specifying every nook and cranny of a column if it's not required.

7) Probably the most annoying thing is that the first entry must include ALL the values - even null placeholders - or future rows won't pick the columns that you actually specified.

DBunit doesn't have a sensible default for translating [NULL] to a real null value either. You have to manually add it. Tell me, who hasn't done this with dbunit? Everyone has. It shouldn't be like this!

What this means is that if you have a polymorphic object, you must declare all the foreign keys to the joining tables of each subclass in the first row, even though they are null. If you do a table for all subclasses pattern, you still have to specify all the fields on the first row. This is just awful.

Anything out there to satisfy me, or should I become the next framework developer of a much better database testing framework?

答:
Another vote for wrapping DBUnit with a modern library to improve usability and conciseness.  My choice is database-rider, which makes DBUnit a breeze to use and even supports JUnit 5 as demonstrated in the following example:

```<code>@RunWith(JUnitPlatform.class)
@ExtendWith(DBUnitExtension.class)
@DBUnit(cacheConnection = true, cacheTableNames = true)
class TestInstrumentQueryService {

    private ConnectionHolder connHolder = () -> EntityManagerProvider.instance("my-jta-unit").connection();

    @DBRider
    @DataSet("datasets/instrumentIds.yml")
    void testFindInstrumentById() {

        InstrumentQueryService iqs = new InstrumentQueryService(EntityManagerProvider.em());

        Instrument instr = iqs.findInstrumentById(InstrumentIdType.TICKER_BBG, "AAPL");
        assertEquals(100, instr.getId());
    }
}
</code>```

Notice how this allows leveraging (concise) YAML testing data sets seamlessly (YAML not XML, though I'm lead to believe that DBUnit actually supports those natively).

ContentLicense: CC BY-SA 2.5

Body:
Another vote for wrapping DBUnit with a modern library to improve usability and conciseness.  My choice is database-rider, which makes DBUnit a breeze to use and even supports JUnit 5 as demonstrated in the following example:

@RunWith(JUnitPlatform.class)
@ExtendWith(DBUnitExtension.class)
@DBUnit(cacheConnection = true, cacheTableNames = true)
class TestInstrumentQueryService {

    private ConnectionHolder connHolder = () -> EntityManagerProvider.instance("my-jta-unit").connection();

    @DBRider
    @DataSet("datasets/instrumentIds.yml")
    void testFindInstrumentById() {

        InstrumentQueryService iqs = new InstrumentQueryService(EntityManagerProvider.em());

        Instrument instr = iqs.findInstrumentById(InstrumentIdType.TICKER_BBG, "AAPL");
        assertEquals(100, instr.getId());
    }
}

Notice how this allows leveraging (concise) YAML testing data sets seamlessly (YAML not XML, though I'm lead to believe that DBUnit actually supports those natively).


问:
How to question user in forward chainig expert system
I have to create an expert system in the medical field, I decided to use forward chaining starting from a set of facts, and then I have to deduce new information and the final diagnosis also by questioning the user. But how do I interrogate the user?
I suppose I must first start the inferential process to analyze the first facts in the knowledge base, then interrogate the user and restart the inferential process.
I can't understand how to combine these things</p>

答: In forward chaining languages that support the assignment of priorities to rules, it can be as simple as assigning lower priorities to rules that ask questions and designing them so that questions aren't asked about information that's already been deduced.</p>


问:
Chart.js - How to set animation speed?
I'm using Chart.js (documentation), but there doesn't seem to be an option to set the animation speed.

I can't even seem to find an animation speed / time variable in the source code.

How do I go about doing this?

(ps: I'm using Doughnut charts)

EDIT: Changing animationSteps, shows weird artefacts after the animation is complete, for several values (ie: 30 or 75). 60 is working fine. And it doesn't only appear with 100+ values of the chart:

答:
Use the animation object

```<code>options: {
        animation: {
            duration: 2000,
        },
</code>```

I haven't see this documented anywhere, but it's incredibly helpful to not have to set the speed globally for every chart.

I also answered here

Title: Chart.js - How to set animation speed?

Body:
Use the animation object

options: {
        animation: {
            duration: 2000,
        },

I haven't see this documented anywhere, but it's incredibly helpful to not have to set the speed globally for every chart.

I also answered here


问:
Requirement failed: Nothing has been added to this summarizer
I am trying to test that pyspark is running properly on my system, but when I try to call fit on my data I get and error, "Requirement failed: Nothing has been added to this summarizer"

```<code>import findspark
import os
spark_location='/usr/local/spark/'
java8_location= '/usr/lib/jvm/java-8-openjdk-amd64'
os.environ['JAVA_HOME'] = java8_location
findspark.init(spark_home=spark_location)
import pyspark, itertools, string, datetime, math
from pyspark.ml.evaluation import RegressionEvaluator
from pyspark.ml.recommendation import ALS
from pyspark.ml.tuning import CrossValidator, ParamGridBuilder
from pyspark.sql import SparkSession
from pyspark.mllib.evaluation import RegressionMetrics
from pyspark.sql.functions import isnan, isnull, when, count, col

def main():
    spark = pyspark.sql.SparkSession.builder.appName("test").getOrCreate()
    sc = spark.sparkContext
    #data = spark.read.option("inferSchema", True).option("header", True).csv("ml-20m/ratings.csv").drop("timestamp")
    data = spark.read.option("inferSchema", True).option("header", True).csv("ml-20m/ratings_test.csv").drop("timestamp")
    train,test= data.randomSplit([0.8, 0.2])
    print("before als")
    als = ALS(userCol="userId", itemCol="movieId", ratingCol="rating", coldStartStrategy="drop", nonnegative=True)
    print("before param_grid")
    param_grid = ParamGridBuilder().addGrid(als.rank, [12,13,14]).addGrid(als.maxIter, [18,19,20]).addGrid(als.regParam, [.17,.18,.19]).build()

    #################### RMSE ######################
    print("before evaluator")
    evaluator = RegressionEvaluator(metricName="rmse", labelCol="rating", predictionCol="prediction")
    print("before cv")
    cv = CrossValidator(estimator=als, estimatorParamMaps=param_grid, evaluator=evaluator, numFolds=3)
    print("before fit")
    model = cv.fit(train)

    model = model.bestModel
    print("before transform")
    predictions = model.transform(test)
    print("before rmse")
    rmse = evaluator.evaluate(predictions)

    print("RMSE", rmse)
    print("rank", model.rank)
    print("MaxIter", model._java_obj.parent().getMaxIter())
    print("RegParam", model._java_obj.parent().getRegParam())

main()

</code>```

I tested the dataframe to make sure there is no Null or NaN within the dataframe.

答:
Ensure that your train and test set both contain at least 1 instance of the same user id. ALS cannot make predictions on UNSEEN user IDs. Thus, if your data set is very sparse its possible that the set of users in the train set has no overlap with the set of users in the test set.

I had the same error, and that was the cause. The solution was to make both data sets large enough to create an overlap of users.

Body:
I am trying to test that pyspark is running properly on my system, but when I try to call fit on my data I get and error, "Requirement failed: Nothing has been added to this summarizer"

import findspark
import os
spark_location='/usr/local/spark/'
java8_location= '/usr/lib/jvm/java-8-openjdk-amd64'
os.environ['JAVA_HOME'] = java8_location
findspark.init(spark_home=spark_location)
import pyspark, itertools, string, datetime, math
from pyspark.ml.evaluation import RegressionEvaluator
from pyspark.ml.recommendation import ALS
from pyspark.ml.tuning import CrossValidator, ParamGridBuilder
from pyspark.sql import SparkSession
from pyspark.mllib.evaluation import RegressionMetrics
from pyspark.sql.functions import isnan, isnull, when, count, col

def main():
    spark = pyspark.sql.SparkSession.builder.appName("test").getOrCreate()
    sc = spark.sparkContext
    #data = spark.read.option("inferSchema", True).option("header", True).csv("ml-20m/ratings.csv").drop("timestamp")
    data = spark.read.option("inferSchema", True).option("header", True).csv("ml-20m/ratings_test.csv").drop("timestamp")
    train,test= data.randomSplit([0.8, 0.2])
    print("before als")
    als = ALS(userCol="userId", itemCol="movieId", ratingCol="rating", coldStartStrategy="drop", nonnegative=True)
    print("before param_grid")
    param_grid = ParamGridBuilder().addGrid(als.rank, [12,13,14]).addGrid(als.maxIter, [18,19,20]).addGrid(als.regParam, [.17,.18,.19]).build()

    #################### RMSE ######################
    print("before evaluator")
    evaluator = RegressionEvaluator(metricName="rmse", labelCol="rating", predictionCol="prediction")
    print("before cv")
    cv = CrossValidator(estimator=als, estimatorParamMaps=param_grid, evaluator=evaluator, numFolds=3)
    print("before fit")
    model = cv.fit(train)

    model = model.bestModel
    print("before transform")
    predictions = model.transform(test)
    print("before rmse")
    rmse = evaluator.evaluate(predictions)

    print("RMSE", rmse)
    print("rank", model.rank)
    print("MaxIter", model._java_obj.parent().getMaxIter())
    print("RegParam", model._java_obj.parent().getRegParam())

main()

I tested the dataframe to make sure there is no Null or NaN within the dataframe.


问:
Question about model connections in Django
There are two models:

```<code>class Author(models.Model):
    first_name = models.CharField(max_length=150, help_text="Фамилия")
    second_name = models.CharField(blank=True, max_length=150, help_text="Имя")
    third_name = models.CharField(blank=True, max_length=150, help_text="Отчество")

    def __str__(self):
        return '{0} {1} {2}'.format(self.first_name, self.second_name, self.third_name)

    def get_absolute_url(self):
        return reverse('author-detail', args=[str(self.id)])

class Book(models.Model):
    title = models.CharField(max_length=200, help_text="Название книги")
    author = models.ManyToManyField('Author', help_text="Автор")
    year = models.CharField(max_length=4, help_text="Год издания")

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('book-detail', args=[str(self.id)])
</code>```

On the page with information about the book I want to display its author, but what I do does not work:

```<code>  <p><strong>Автор:</strong> {{ book.author }}</p>
</code>```

Also a problem with the author id. This line is broken:

```<code>{{ author.get_absolute_url }}
</code>```

答: You can not access the author this method, because your book model related with author many to mamny relation. If you need really many to many relation you must change your template tag. You can see how to use template tag for many to many relation here</p>

Body:
There are two models:

class Author(models.Model):
    first_name = models.CharField(max_length=150, help_text="Фамилия")
    second_name = models.CharField(blank=True, max_length=150, help_text="Имя")
    third_name = models.CharField(blank=True, max_length=150, help_text="Отчество")

    def __str__(self):
        return '{0} {1} {2}'.format(self.first_name, self.second_name, self.third_name)

    def get_absolute_url(self):
        return reverse('author-detail', args=[str(self.id)])

class Book(models.Model):
    title = models.CharField(max_length=200, help_text="Название книги")
    author = models.ManyToManyField('Author', help_text="Автор")
    year = models.CharField(max_length=4, help_text="Год издания")

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('book-detail', args=[str(self.id)])

On the page with information about the book I want to display its author, but what I do does not work:

Автор: {{ book.author }}

Also a problem with the author id. This line is broken:

{{ author.get_absolute_url }}


问:
NET Core 3.1 - 403 when [Authorize(Roles = "Administrator")]
I'm using Identity Server features, with NET Core 3.1.

What are the requirements in the database when having a role protecting a route?

E.g. [Authorize(Roles = "Administrator")]

I have a user created in AspNetUsers table.

I have a role created in AspNetRoles table. The value for name is Administrator and NormalizedName is ADMINISTRATOR.

I have a row in AspNetUserRoles table with the guid from User and Role.

When hitting this route, I'm getting 403 Forbidden.

Am I missing something?

EDIT 1

The code I'm using add the role is
await userManager.AddToRoleAsync(user, "Administrator");

EDIT 2

Here's the Startup.cs file.

```<code>using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer;
using Microsoft.EntityFrameworkCore;
using SampleApp.Data;
using SampleApp.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SampleApp.Entities;
using AutoMapper;
using System;
using SampleApp.Services;
using SampleApp.Middlewares;

namespace SampleApp
{
    public class Startup
    {
        public IConfiguration _configuration { get; }

        public Startup(IConfiguration configuration)
        {
            _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));

        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped<ISampleAppRepository, SampleAppRepository>();

            var emailConfig = _configuration
                .GetSection("EmailConfiguration")
                .Get<EmailConfiguration>();

            services.AddSingleton(emailConfig);

            services.AddTransient<IPasswordHasher<User>, PasswordHasher<User>>();

            services.AddScoped<IShippingEmailSender, ShippingEmailSender>();

            services.AddDbContext<ApplicationDbContext>(options =>
            {
                options.UseSqlServer(_configuration["connectionStrings:databaseConnectionString"]);
            });

            services.AddDefaultIdentity<User>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddRoles<IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.AddIdentityServer()
                .AddApiAuthorization<User, ApplicationDbContext>();

            services.AddAuthentication()
                .AddIdentityServerJwt();

            services.AddControllersWithViews(setupAction =>
            {
                setupAction.ReturnHttpNotAcceptable = true;

            }).AddXmlDataContractSerializerFormatters();

            services.AddRazorPages();

            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });

            services.AddMvc();

            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            app.UseRouting();

            app.UseMiddleware<TenantDetectionMiddleware>();

            app.UseAuthentication();
            app.UseIdentityServer();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapRazorPages();
            });

            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseReactDevelopmentServer(npmScript: "start");
                }
            });
        }
    }
}

</code>```

答:
I was missing this.

```<code>services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
    options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
    options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
});
</code>```

Thanks to this answer!
https://stackoverflow.com/a/56473365/779975

Body:
I'm using Identity Server features, with NET Core 3.1.

What are the requirements in the database when having a role protecting a route?

E.g. [Authorize(Roles = "Administrator")]

I have a user created in AspNetUsers table.

I have a role created in AspNetRoles table. The value for name is Administrator and NormalizedName is ADMINISTRATOR.

I have a row in AspNetUserRoles table with the guid from User and Role.

When hitting this route, I'm getting 403 Forbidden.

Am I missing something?

EDIT 1

The code I'm using add the role is
await userManager.AddToRoleAsync(user, "Administrator");

EDIT 2

Here's the Startup.cs file.

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer;
using Microsoft.EntityFrameworkCore;
using SampleApp.Data;
using SampleApp.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SampleApp.Entities;
using AutoMapper;
using System;
using SampleApp.Services;
using SampleApp.Middlewares;

namespace SampleApp
{
    public class Startup
    {
        public IConfiguration _configuration { get; }

        public Startup(IConfiguration configuration)
        {
            _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));

        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped<ISampleAppRepository, SampleAppRepository>();

            var emailConfig = _configuration
                .GetSection("EmailConfiguration")
                .Get<EmailConfiguration>();

            services.AddSingleton(emailConfig);

            services.AddTransient<IPasswordHasher<User>, PasswordHasher<User>>();

            services.AddScoped<IShippingEmailSender, ShippingEmailSender>();

            services.AddDbContext<ApplicationDbContext>(options =>
            {
                options.UseSqlServer(_configuration["connectionStrings:databaseConnectionString"]);
            });

            services.AddDefaultIdentity<User>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddRoles<IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.AddIdentityServer()
                .AddApiAuthorization<User, ApplicationDbContext>();

            services.AddAuthentication()
                .AddIdentityServerJwt();

            services.AddControllersWithViews(setupAction =>
            {
                setupAction.ReturnHttpNotAcceptable = true;

            }).AddXmlDataContractSerializerFormatters();

            services.AddRazorPages();

            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });

            services.AddMvc();

            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            app.UseRouting();

            app.UseMiddleware<TenantDetectionMiddleware>();

            app.UseAuthentication();
            app.UseIdentityServer();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapRazorPages();
            });

            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseReactDevelopmentServer(npmScript: "start");
                }
            });
        }
    }
}

Body:
I was missing this.

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
    options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
    options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
});

Thanks to this answer!
https://stackoverflow.com/a/56473365/779975


问:
When running an Async/Await Experiment, operations do not occur in expected order
I have created an experiment (run in XUnit) to test output. I use three methods - the test method, an asynchronous method that calls await, and an inner Task that sleeps for 5 seconds.

```<code>    [Fact]
    public void TestAsyncRunning()
    {
        _testOutput.WriteLine("Beginning Test");
        _testOutput.WriteLine("Calling RunningAsync");

        var t = RunningAsync();

        _testOutput.WriteLine("In outer method, after calling async method");

        t.Wait(); //IOW, Thread.Join();

        _testOutput.WriteLine("Exiting Test");
    }

    private async Task RunningAsync()
    {
        _testOutput.WriteLine("RunningAsync: Enter Method");
        _testOutput.WriteLine("RunningAsync: Calling and awaiting inner running");
        await InnerRunning();
        _testOutput.WriteLine("RunningAsync: Returning");
    }

    private Task InnerRunning()
    {
        _testOutput.WriteLine("InnerRunning: Begin method");
        _testOutput.WriteLine("InnerRunning: Sleeping For 5 seconds");
        var t = Task.Run(() => Thread.Sleep(5000));
        _testOutput.WriteLine("InnerRunning: Wake up and exit");
        return t;
    }
</code>```

In the following output, the lines with the asterisks is where the unexpected order occurs.

The output I expect is

```<code>Beginning Test
Calling RunningAsync
RunningAsync: Enter Method
RunningAsync: Calling and awaiting inner running
InnerRunning: Begin method
InnerRunning: Sleeping For 5 seconds
*In outer method, after calling async method
*InnerRunning: Wake up and exit
RunningAsync: Returning
Exiting Test
</code>```

The output I get is

```<code>Beginning Test
Calling RunningAsync
RunningAsync: Enter Method
RunningAsync: Calling and awaiting inner running
InnerRunning: Begin method
InnerRunning: Sleeping For 5 seconds
*InnerRunning: Wake up and exit
*In outer method, after calling async method
RunningAsync: Returning
Exiting Test
</code>```

It appears that the async method is actually running async but the method it calls is running synchronously. Does this have to do with the TaskScheduler? I am clearly missing something...….

答:
InnerRunning is not asynchronous. It's a synchronous method that returns a Task. So these messages will always appear together:

```<code>InnerRunning: Begin method
InnerRunning: Sleeping For 5 seconds
InnerRunning: Wake up and exit
</code>```

If you want InnerRunning to asynchronously wait for the Task.Run delegate, then you need to await that task in that method:

```<code>_testOutput.WriteLine("InnerRunning: Begin method");
_testOutput.WriteLine("InnerRunning: Sleeping For 5 seconds");
await Task.Run(() => Thread.Sleep(5000));
_testOutput.WriteLine("InnerRunning: Wake up and exit");
</code>```

For more introductory information around async/await, I recommend my async intro.

Body:
I have created an experiment (run in XUnit) to test output. I use three methods - the test method, an asynchronous method that calls await, and an inner Task that sleeps for 5 seconds.

    [Fact]
    public void TestAsyncRunning()
    {
        _testOutput.WriteLine("Beginning Test");
        _testOutput.WriteLine("Calling RunningAsync");

        var t = RunningAsync();

        _testOutput.WriteLine("In outer method, after calling async method");

        t.Wait(); //IOW, Thread.Join();

        _testOutput.WriteLine("Exiting Test");
    }

    private async Task RunningAsync()
    {
        _testOutput.WriteLine("RunningAsync: Enter Method");
        _testOutput.WriteLine("RunningAsync: Calling and awaiting inner running");
        await InnerRunning();
        _testOutput.WriteLine("RunningAsync: Returning");
    }

    private Task InnerRunning()
    {
        _testOutput.WriteLine("InnerRunning: Begin method");
        _testOutput.WriteLine("InnerRunning: Sleeping For 5 seconds");
        var t = Task.Run(() => Thread.Sleep(5000));
        _testOutput.WriteLine("InnerRunning: Wake up and exit");
        return t;
    }

In the following output, the lines with the asterisks is where the unexpected order occurs.

The output I expect is

Beginning Test
Calling RunningAsync
RunningAsync: Enter Method
RunningAsync: Calling and awaiting inner running
InnerRunning: Begin method
InnerRunning: Sleeping For 5 seconds
*In outer method, after calling async method
*InnerRunning: Wake up and exit
RunningAsync: Returning
Exiting Test

The output I get is

Beginning Test
Calling RunningAsync
RunningAsync: Enter Method
RunningAsync: Calling and awaiting inner running
InnerRunning: Begin method
InnerRunning: Sleeping For 5 seconds
*InnerRunning: Wake up and exit
*In outer method, after calling async method
RunningAsync: Returning
Exiting Test

It appears that the async method is actually running async but the method it calls is running synchronously. Does this have to do with the TaskScheduler? I am clearly missing something...….

Body:
InnerRunning is not asynchronous. It's a synchronous method that returns a Task. So these messages will always appear together:

InnerRunning: Begin method
InnerRunning: Sleeping For 5 seconds
InnerRunning: Wake up and exit

If you want InnerRunning to asynchronously wait for the Task.Run delegate, then you need to await that task in that method:

_testOutput.WriteLine("InnerRunning: Begin method");
_testOutput.WriteLine("InnerRunning: Sleeping For 5 seconds");
await Task.Run(() => Thread.Sleep(5000));
_testOutput.WriteLine("InnerRunning: Wake up and exit");

For more introductory information around async/await, I recommend my async intro.


问:
Possible workaround for async negedge reset?
I'd like to have a register with async reset signal, like following:

```<code>always @(posedge clk or negedge rst_n)
begin
    if(!rst_n)
        out <= 1'b0
    else
        out <= in
end
</code>```

I have tried class AsyncReset() and withReset(). However, the generated code uses a posedge reset and the variable of AsyncReset() does not accept !.

Is there any workaround for this?

答:
While you cannot invert the AsyncReset type directly (generally applying logic to an AsyncReset is bad because it can glitch), you can cast to a Bool and back:

  val reset_n = (!reset.asBool).asAsyncReset
  val reg = withReset(reset_n)(RegInit(0.U(8.W)))
```

Runnable example: https://scastie.scala-lang.org/ERy0qHt2Q3OvWIsp9qiiNg

Body:
I'd like to have a register with async reset signal, like following:

always @(posedge clk or negedge rst_n)
begin
    if(!rst_n)
        out <= 1'b0
    else
        out <= in
end

I have tried class AsyncReset() and withReset(). However, the generated code uses a posedge reset and the variable of AsyncReset() does not accept !.

Is there any workaround for this?

Body:
While you cannot invert the AsyncReset type directly (generally applying logic to an AsyncReset is bad because it can glitch), you can cast to a Bool and back:

  val reset_n = (!reset.asBool).asAsyncReset
  val reg = withReset(reset_n)(RegInit(0.U(8.W)))

Runnable example: https://scastie.scala-lang.org/ERy0qHt2Q3OvWIsp9qiiNg


问:
Grep to extract one-line comments starting with or enclosed in forward slash/asterisk
I'm trying to make a regex to identify a comment. It has to start with // and end with a new line or a *) pattern.</p>

答:
This should work:

```<code>$ grep -n -E '^//|^/\*.*\*/$' j.java
2:/* Computation done in imperial units. FIXME: Use metric! */
5:// FIXME: change formula to metric units
11:/* FIXME: use floats?? */
14:// hmmm... FIXME: use symbol??
</code>```

Note that I extended the version w/ /* to NOT match on the first line
of a multi-line comment.

Body:
This should work:

$ grep -n -E '^//|^/\*.*\*/$' j.java
2:/* Computation done in imperial units. FIXME: Use metric! */
5:// FIXME: change formula to metric units
11:/* FIXME: use floats?? */
14:// hmmm... FIXME: use symbol??

Note that I extended the version w/ /* to NOT match on the first line
of a multi-line comment.


问:
How to get this probability outcome in R?
New to R. Not sure how to go about this problem. Essentially I want to create a Monte Carlo simulation. However this is how it's supposed to go:
There are only 3 people (A,B,C) And only come into contact once in this order: (A-->B) (B-->C). Starting out, A is 100% sick, while B and C are 0% sick. Each time a person comes into contact with another, they have a 50% chance of being sick How would i go and replicate that in R?  I understand the mathematics behind this but unsure how to code it. This is what i have so far:

```<code>a='positive'
corona = c('positive','negative')
sample(x = corona, size = 1, replace = TRUE)
</code>```

I know the output will only give me the results of whether B is sick or not. How would i continue to see if C is sick?

答:
You could write a helper function to do the "infecting". Let's assume that 1 is "sick" and 0 is "not sick"

```<code>infect <- function(x, rate=.5) {
   current_sick <- x==1
   new_sick <- runif(sum(current_sick)) < rate
   x[current_sick] <- as.numeric(new_sick) # turn TRUE/FALSE to 1/0
   x
}
</code>```

This function looks where all the 1's are, then for each of those individuals, it tosses a coin to see of the next person will be sick (not changing any of the non-sick values)

Then to test with 1000 people, you can do

```<code>A <- rep(1, 1000) # all sick
B <- infect(A)
C <- infect(B)
</code>```

This draws 1000 A's. And we go though two transmission steps, doing all 1000 samples at once. If you run mean(C) you should get something close to 0.25.

Body:
New to R. Not sure how to go about this problem. Essentially I want to create a Monte Carlo simulation. However this is how it's supposed to go:
There are only 3 people (A,B,C) And only come into contact once in this order: (A-->B) (B-->C). Starting out, A is 100% sick, while B and C are 0% sick. Each time a person comes into contact with another, they have a 50% chance of being sick How would i go and replicate that in R?  I understand the mathematics behind this but unsure how to code it. This is what i have so far:

a='positive'
corona = c('positive','negative')
sample(x = corona, size = 1, replace = TRUE)

I know the output will only give me the results of whether B is sick or not. How would i continue to see if C is sick?

Body:
You could write a helper function to do the "infecting". Let's assume that 1 is "sick" and 0 is "not sick"

infect <- function(x, rate=.5) {
   current_sick <- x==1
   new_sick <- runif(sum(current_sick)) < rate
   x[current_sick] <- as.numeric(new_sick) # turn TRUE/FALSE to 1/0
   x
}

This function looks where all the 1's are, then for each of those individuals, it tosses a coin to see of the next person will be sick (not changing any of the non-sick values)

Then to test with 1000 people, you can do

A <- rep(1, 1000) # all sick
B <- infect(A)
C <- infect(B)

This draws 1000 A's. And we go though two transmission steps, doing all 1000 samples at once. If you run mean(C) you should get something close to 0.25.


问:
Eloquent Removing Columns
I'm having a really strange issue with my eloquent query. I have a table called Calls which I am joining to Contacts and Companies. I am trying to reference the column calls.id but it has been replaced with the id for Companies.

Here is my query:

```<code>$calls=DB::table('calls')
        ->leftJoin('contacts','calls.contact_id','=','contacts.id')
        ->leftJoin('companies','calls.company_id','=','companies.id')
        ->where('completed','=',false)
        ->orderBy('call_on','asc')
        ->get();

return $calls;
</code>```

I have seen on Github that this seems to be a known bug but no-one has put forward a workaround.

Can anyone point me in the right direction?

答:
The most direction solution to your immediate question is to add a select to your Eloquent query:

$calls=DB::select('calls.* from calls')
        ->leftJoin('contacts','calls.contact_id','=','contacts.id')
        ->leftJoin('companies','calls.company_id','=','companies.id')
        ->where('completed','=',false)
        ->orderBy('call_on','asc')
        ->get();

return $calls;
```

<p>Instead of the default <code>select *</code>, explicitly dictate what is returned. However, this can be done a lot more cleanly with Eloquent using models:</p>

<pre class="lang-php prettyprint-override"><code>Calls::whereHas('companies', function (Builder $query) {
    $query->where('completed', false);
})->orderBy('call_on', 'asc')->get();
</code>```

In order for this to work you need to setup the relationship on the model level:

// App\Calls model:
public function companies() {
    return $this->belongsTo(App\Companies::class);
}

// App\Companies model:
public function calls() {
    return $this->hasMany(App\Calls::class);
}
```

Title: Eloquent Removing Columns

Body:
I'm having a really strange issue with my eloquent query. I have a table called Calls which I am joining to Contacts and Companies. I am trying to reference the column calls.id but it has been replaced with the id for Companies.

Here is my query:

$calls=DB::table('calls')
        ->leftJoin('contacts','calls.contact_id','=','contacts.id')
        ->leftJoin('companies','calls.company_id','=','companies.id')
        ->where('completed','=',false)
        ->orderBy('call_on','asc')
        ->get();

return $calls;

I have seen on Github that this seems to be a known bug but no-one has put forward a workaround.

Can anyone point me in the right direction?

Body:
The most direction solution to your immediate question is to add a select to your Eloquent query:

$calls=DB::select('calls.* from calls')
        ->leftJoin('contacts','calls.contact_id','=','contacts.id')
        ->leftJoin('companies','calls.company_id','=','companies.id')
        ->where('completed','=',false)
        ->orderBy('call_on','asc')
        ->get();

return $calls;

Instead of the default select *, explicitly dictate what is returned. However, this can be done a lot more cleanly with Eloquent using models:

Calls::whereHas('companies', function (Builder $query) {
    $query->where('completed', false);
})->orderBy('call_on', 'asc')->get();

In order for this to work you need to setup the relationship on the model level:

// App\Calls model:
public function companies() {
    return $this->belongsTo(App\Companies::class);
}

// App\Companies model:
public function calls() {
    return $this->hasMany(App\Calls::class);
}


问:
Angularjs multiple HTTP POST requests causing net::ERR_INSUFFICIENT_RESOURCES
In my app I'm getting list of hosts provided by user in textarea field form and insert them into my database using HTTP POST to API.

All works fine until the list exceeds 2.5k hosts when I get net::ERR_INSUFFICIENT_RESOURCES error. I read that it is related to some Chrome limitations.

How can I overcome this limitation? I was trying to split the list to the bunches and introduce some delay between them but it doesn't work (it seems all bunches are started asynchronously in the same time).

Controller:

```<code>AddHostsController.$inject = ['$scope', 'Authentication', 'App', 'Hosts', '$filter', '$timeout'];

function AddHostsController($scope, Authentication, App, Hosts, $filter, $timeout) {
    var vm = this;
    vm.submit = submit;
    ...some other staff...

    function submit() {
      var fulllist = [];
      vm.firstbunch = [];
      vm.secondbunch = [];
      fulllist = vm.host_list.split('\n');
      vm.firstbunch = fulllist.slice(0,1500);
      vm.secondbunch = fulllist.slice(1500,);

      $timeout(function() { vm.firstbunch.forEach(submitHost);}, 2000)
      .then(firstBunchSuccessFn, firstBunchErrorFn);

      function firstBunchSuccessFn(){
        vm.secondbunch.forEach(submitHost);
      }

      function firstBunchErrorFn(){
        console.log("Something went wrong!");
      }

      function submitHost(value, index, array){
        App.addhosts(...some args..., value).then(addHostsSuccessFn, addHostsErrorFn);

        function addHostsSuccessFn(response) {
        }

        function addHostsErrorFn(response) {
          console.error('Failure!');
        }
     }
}
</code>```

Service:

```<code>.factory('App', App);

App.$inject = ['$http'];

function App($http) {
    var App = {
      addhosts: addhosts,
    };

    return App;

    function addhosts(...some other.., value) {

        return $http.post('/api/v1/hosts/', {
            ...some other...
            value: value
        });
    }
</code>```

答:
Instead of executing the requests in parallel, chain them:

```<code>var configArr = [/* Array of config objects */];
var resultsArrPromise = configArr.reduce( reducerFn, $q.when([]) );

responseArrPromise
  .then(function (responseArr) {
    responseArr.forEach( response => console.log(response.data) );
}).catch(function (errorResponse) {
    console.log(errorResponse);
});

function reducerFn(acc, config) {
    var accArrPromise = acc.then(function(responseArr) {
        var httpPromise = $http(config);
        return $q.all( [...responseArr, httpPromise] );
    });
    return accArrPromise;
}
</code>```

The reducer starts with a promise of an empty array. Each iteration of the reducer chains another HTTP promise to the array of responses. The result is a promise that resolves to an array of responses. By chaining the HTTP requests, they are executed sequentially instead of in parallel.

Body:
In my app I'm getting list of hosts provided by user in textarea field form and insert them into my database using HTTP POST to API.

All works fine until the list exceeds 2.5k hosts when I get net::ERR_INSUFFICIENT_RESOURCES error. I read that it is related to some Chrome limitations.

How can I overcome this limitation? I was trying to split the list to the bunches and introduce some delay between them but it doesn't work (it seems all bunches are started asynchronously in the same time).

Controller:

AddHostsController.$inject = ['$scope', 'Authentication', 'App', 'Hosts', '$filter', '$timeout'];

function AddHostsController($scope, Authentication, App, Hosts, $filter, $timeout) {
    var vm = this;
    vm.submit = submit;
    ...some other staff...

    function submit() {
      var fulllist = [];
      vm.firstbunch = [];
      vm.secondbunch = [];
      fulllist = vm.host_list.split('\n');
      vm.firstbunch = fulllist.slice(0,1500);
      vm.secondbunch = fulllist.slice(1500,);

      $timeout(function() { vm.firstbunch.forEach(submitHost);}, 2000)
      .then(firstBunchSuccessFn, firstBunchErrorFn);

      function firstBunchSuccessFn(){
        vm.secondbunch.forEach(submitHost);
      }

      function firstBunchErrorFn(){
        console.log("Something went wrong!");
      }

      function submitHost(value, index, array){
        App.addhosts(...some args..., value).then(addHostsSuccessFn, addHostsErrorFn);

        function addHostsSuccessFn(response) {
        }

        function addHostsErrorFn(response) {
          console.error('Failure!');
        }
     }
}

Service:

.factory('App', App);

App.$inject = ['$http'];

function App($http) {
    var App = {
      addhosts: addhosts,
    };

    return App;

    function addhosts(...some other.., value) {

        return $http.post('/api/v1/hosts/', {
            ...some other...
            value: value
        });
    }

Body:
Instead of executing the requests in parallel, chain them:

var configArr = [/* Array of config objects */];
var resultsArrPromise = configArr.reduce( reducerFn, $q.when([]) );

responseArrPromise
  .then(function (responseArr) {
    responseArr.forEach( response => console.log(response.data) );
}).catch(function (errorResponse) {
    console.log(errorResponse);
});

function reducerFn(acc, config) {
    var accArrPromise = acc.then(function(responseArr) {
        var httpPromise = $http(config);
        return $q.all( [...responseArr, httpPromise] );
    });
    return accArrPromise;
}

The reducer starts with a promise of an empty array. Each iteration of the reducer chains another HTTP promise to the array of responses. The result is a promise that resolves to an array of responses. By chaining the HTTP requests, they are executed sequentially instead of in parallel.


问:
Javascript .toLocaleString() not honoring '2-digit'
Original Question:
How do I get the hour/month to respect a '2-digit' formatting.

```<code>const event = new Date(2012, 3, 20, 3, 0, 0);
</code>```

Edit...
Apologies all, I don't use this very often

The real issue is depending on which version of chrome you are on, it respects this formatting differently:

For example:

```<code>new Date(1561984526000).toLocaleString("ja-JP", {hour: "2-digit"})
// Chrome 80 (and other releases): "08時"
// Chrome 79: "8時"
</code>```

答:
Personally I never trust in toLocaleString function, I prefer to use getMonth and lpad to formatting a date manually.

Another advantage is that you don't depend on anything to do it

```<code>function lpad (strModify, intMaxPad)
{
    if (typeof strModify == 'undefined')
    {
        return false;
    }
    strModify = strModify.toString();
    return strModify.length < intMaxPad ? lpad("0" + strModify, intMaxPad) : strModify;
}

$(function(){

    var objDate = new Date(2012, 3, 20, 3, 0, 0);
    console.log( lpad((objDate.getMonth() + 1), 2) + '/' + lpad(objDate.getDate(), 2) + '/' + objDate.getFullYear()  );
});
</code>```

You can also use the Moment Luxon library

Body:
Original Question:
How do I get the hour/month to respect a '2-digit' formatting.

const event = new Date(2012, 3, 20, 3, 0, 0);

Edit...
Apologies all, I don't use this very often

The real issue is depending on which version of chrome you are on, it respects this formatting differently:

For example:

new Date(1561984526000).toLocaleString("ja-JP", {hour: "2-digit"})
// Chrome 80 (and other releases): "08時"
// Chrome 79: "8時"

Body:
Personally I never trust in toLocaleString function, I prefer to use getMonth and lpad to formatting a date manually.

Another advantage is that you don't depend on anything to do it

function lpad (strModify, intMaxPad)
{
    if (typeof strModify == 'undefined')
    {
        return false;
    }
    strModify = strModify.toString();
    return strModify.length < intMaxPad ? lpad("0" + strModify, intMaxPad) : strModify;
}

$(function(){

    var objDate = new Date(2012, 3, 20, 3, 0, 0);
    console.log( lpad((objDate.getMonth() + 1), 2) + '/' + lpad(objDate.getDate(), 2) + '/' + objDate.getFullYear()  );
});

You can also use the Moment Luxon library


问:
Unable to configure SQS queue notification in S3
I created an SQS queue and added policy under permission tab allowing only my account users to configure the configure the notification

Policy Document

```<code>{
  "Version": "2012-10-17",
  "Id": "arn:aws:sqs:us-east-1:111111111111:sqsqueue/SQSDefaultPolicy",
  "Statement": [
    {
      "Sid": "Sid111111111111",
      "Effect": "Allow",
      "Principal": {
        "AWS": "111111111111"
      },
      "Action": [
        "sqs:SendMessage",
        "sqs:ReceiveMessage"
      ],
      "Resource": "arn:aws:sqs:us-east-1:111111111111:queue"
    }
  ]
</code>```

Navigate to S3 and try to configure event notification for the above queue, it is throwing an error

Unable to validate the following destination configurations. Permissions on the destination queue do not allow S3 to publish
  notifications from this bucket.
  (arn:aws:sqs:us-east-1:111111111111:queue)*

am I doing something wrong? Can someone help me please

答:
I was able to resolve this issue by adding "Service": "s3.amazonaws.com"
in the Principal tag.

Here the policy document

```<code>    {
  "Version": "2012-10-17",
  "Id": "arn:aws:sqs:us-east-1:111111111111:sqsqueue/SQSDefaultPolicy",
  "Statement": [
    {
      "Sid": "Sid111111111111",
      "Effect": "Allow",
      "Principal": {
        "Service": "s3.amazonaws.com"
      },
      "Action": [
        "sqs:SendMessage",
        "sqs:ReceiveMessage"
      ],
      "Resource": "arn:aws:sqs:us-east-1:111111111111:queue"
    }
  ]

</code>```

This is explained in https://forums.aws.amazon.com/thread.jspa?threadID=173251

Body:
I created an SQS queue and added policy under permission tab allowing only my account users to configure the configure the notification

Policy Document

{
  "Version": "2012-10-17",
  "Id": "arn:aws:sqs:us-east-1:111111111111:sqsqueue/SQSDefaultPolicy",
  "Statement": [
    {
      "Sid": "Sid111111111111",
      "Effect": "Allow",
      "Principal": {
        "AWS": "111111111111"
      },
      "Action": [
        "sqs:SendMessage",
        "sqs:ReceiveMessage"
      ],
      "Resource": "arn:aws:sqs:us-east-1:111111111111:queue"
    }
  ]

Navigate to S3 and try to configure event notification for the above queue, it is throwing an error

Unable to validate the following destination configurations. Permissions on the destination queue do not allow S3 to publish
  notifications from this bucket.
  (arn:aws:sqs:us-east-1:111111111111:queue)*

am I doing something wrong? Can someone help me please

Body:
I was able to resolve this issue by adding "Service": "s3.amazonaws.com"
in the Principal tag.

Here the policy document

    {
  "Version": "2012-10-17",
  "Id": "arn:aws:sqs:us-east-1:111111111111:sqsqueue/SQSDefaultPolicy",
  "Statement": [
    {
      "Sid": "Sid111111111111",
      "Effect": "Allow",
      "Principal": {
        "Service": "s3.amazonaws.com"
      },
      "Action": [
        "sqs:SendMessage",
        "sqs:ReceiveMessage"
      ],
      "Resource": "arn:aws:sqs:us-east-1:111111111111:queue"
    }
  ]

This is explained in https://forums.aws.amazon.com/thread.jspa?threadID=173251


问:
image border not displaying html email
I am trying to send an html email with an image border as

```<code><p align="center">
    <img src="images/pic1.jpg" width="443" height="148" align="middle"
         style="border: 1px solid grey; padding:10px;" border="1"/>
</p>
</code>```

However, the border just does not display in any of the email clients. How can i fix this?

答: try changing the color either to it's value, #808080  or it's properly spelled version 'gray'</p>

Title: image border not displaying html email

Body:
I am trying to send an html email with an image border as

However, the border just does not display in any of the email clients. How can i fix this?


问:
SwiftUI Transitions of Conditional Child Views
I'm trying to understand and experiment with swiftUI view transitions and could use some insight into why the following does not work the way I expect:

```<code>struct ContentView: View {
@State private var showOverlay: Bool = false

var body: some View {
    ZStack {
        VStack {
            Button(action: {
                withAnimation(.easeInOut) {
                    self.showOverlay = true
                }
            }) {
                Text("Hello, World!")
            }
        }
        .zIndex(0)
        .animation(nil)
        .blur(radius: showOverlay ? 3 : 0)

        if showOverlay {
            HStack {
                Button(action: {
                    withAnimation(.easeInOut) {
                        self.showOverlay = false
                    }
                }) {
                    Text("Close")
                }
                .frame(width: 80, height: 80)
                .background(Color.red)
                .transition(.move(edge: .top))

                Button(action: {
                    withAnimation(.easeInOut) {
                        self.showOverlay = false
                    }
                }) {
                    Text("Close")
                }
                .frame(width: 80, height: 80)
                .background(Color.red)
                .transition(.move(edge: .bottom))
            }
            .zIndex(1.0)
        }
    }
}
</code>```

There is a conditional HStack of two buttons.
When the @State parameter showOverlay is changed it is done within a withAnimation block.
The transitions on the individual buttons are not honored.

If I remove the HStack, and put the zIndex(1) on each button, then the removal transition occurs, but not the insertion transition.

I want both buttons to transition in their designated ways when their group is added to the view.

Questions:
Why does wrapping in an HStack cause the inner transitions to be ignored?
Why does the edge transition only work in 1 direction?

答:
Transition works for view which is appeared/disappeared. In the provided code snapshot appeared/disappeared HStack, so transition should be applied to it.

Note: transitions must be tested on Simulator or real device, most of them do not work in Preview.

Below is modified part of code which gives worked behaviour. Tested with Xcode 11.2 / iOS 13.2

```<code>if showOverlay {
    HStack {
        Button(action: {
            withAnimation(.easeInOut) {
                self.showOverlay = false
            }
        }) {
            Text("Close")
        }
        .frame(width: 80, height: 80)
        .background(Color.red)

        Button(action: {
            withAnimation(.easeInOut) {
                self.showOverlay = false
            }
        }) {
            Text("Close")
        }
        .frame(width: 80, height: 80)
        .background(Color.red)
    }
    .transition(.move(edge: .top)) // << only in this place needed
    .zIndex(1.0)
}
</code>```

Body:
I'm trying to understand and experiment with swiftUI view transitions and could use some insight into why the following does not work the way I expect:

struct ContentView: View {
@State private var showOverlay: Bool = false

var body: some View {
    ZStack {
        VStack {
            Button(action: {
                withAnimation(.easeInOut) {
                    self.showOverlay = true
                }
            }) {
                Text("Hello, World!")
            }
        }
        .zIndex(0)
        .animation(nil)
        .blur(radius: showOverlay ? 3 : 0)

        if showOverlay {
            HStack {
                Button(action: {
                    withAnimation(.easeInOut) {
                        self.showOverlay = false
                    }
                }) {
                    Text("Close")
                }
                .frame(width: 80, height: 80)
                .background(Color.red)
                .transition(.move(edge: .top))

                Button(action: {
                    withAnimation(.easeInOut) {
                        self.showOverlay = false
                    }
                }) {
                    Text("Close")
                }
                .frame(width: 80, height: 80)
                .background(Color.red)
                .transition(.move(edge: .bottom))
            }
            .zIndex(1.0)
        }
    }
}

There is a conditional HStack of two buttons.
When the @State parameter showOverlay is changed it is done within a withAnimation block.
The transitions on the individual buttons are not honored.

If I remove the HStack, and put the zIndex(1) on each button, then the removal transition occurs, but not the insertion transition.

I want both buttons to transition in their designated ways when their group is added to the view.

Questions:
Why does wrapping in an HStack cause the inner transitions to be ignored?
Why does the edge transition only work in 1 direction?

Body:
Transition works for view which is appeared/disappeared. In the provided code snapshot appeared/disappeared HStack, so transition should be applied to it.

Note: transitions must be tested on Simulator or real device, most of them do not work in Preview.

Below is modified part of code which gives worked behaviour. Tested with Xcode 11.2 / iOS 13.2

if showOverlay {
    HStack {
        Button(action: {
            withAnimation(.easeInOut) {
                self.showOverlay = false
            }
        }) {
            Text("Close")
        }
        .frame(width: 80, height: 80)
        .background(Color.red)

        Button(action: {
            withAnimation(.easeInOut) {
                self.showOverlay = false
            }
        }) {
            Text("Close")
        }
        .frame(width: 80, height: 80)
        .background(Color.red)
    }
    .transition(.move(edge: .top)) // << only in this place needed
    .zIndex(1.0)
}


问:
xxxx@gmail.com does not have bigquery.jobs.create permission in project yyyy
I am new to Google Cloud and BigQuery

I have a cloud instance with 2 projects.  One is a Compute Engine project and another is a BigQuery project.  I can successfully get an Access Token and also a refresh token from the Compute Engine project.  However, when I attempt to access the BigQuery project, the error below occurs:

xxxx@gmail.com does not have bigquery.jobs.create permission in project yyyy

I've created datasets in BigQuery, copied public data into each. I also confirmed the xxxx@gmail.com is the owner for each of the datasets.   I am able to successfully query the datasets.

```<code>In IAM, the xxxx@gmail.com has the following:
roles/bigquery.user
roles/bigquery.admin
roles/bigquery.owner
roles/bigquery.viewer
</code>```

I've reviewed the following links but the suggestions have not helped. Any ideas on how to resolve the error?

https://cloud.google.com/bigquery/docs/access-control

Google Big-query api 403-Forbidden Exception

Google API OAuth2, Service Account, "error" : "invalid_grant"

The user does not have bigquery.jobs.create permission in project gdelt-bq

Running queries in BigQuery without being a project User

https://github.com/getredash/redash/issues/1684

The user does not have bigquery.jobs.create permission in project gdelt-bq

Error :service account does not have bigquery.jobs.create permission

Although the error is not on the service account, I also reviewed:
Error :service account does not have bigquery.jobs.create permission

```<code>The service accounts for both the Compute Engine project and the BigQuery
project have the following:
roles/bigquery.user
roles/bigquery.admin
roles/bigquery.data viewer
roles/bigquery.data editor
</code>```

Thanks!

答:
There are 3 separate service accounts at the most.
One the default dataflow service account, and the other the controller service account, and then the user account or the service account which you trigger the job.

On the above case, it is important to provide the required permission to the user account or service account triggering the job, and also the controller service account with the same permissions. If you don't use a controller service account that is passed to the dataflow job, then a default compute account and it's permission is taken.

Body:
I am new to Google Cloud and BigQuery

I have a cloud instance with 2 projects.  One is a Compute Engine project and another is a BigQuery project.  I can successfully get an Access Token and also a refresh token from the Compute Engine project.  However, when I attempt to access the BigQuery project, the error below occurs:

xxxx@gmail.com does not have bigquery.jobs.create permission in project yyyy

I've created datasets in BigQuery, copied public data into each. I also confirmed the xxxx@gmail.com is the owner for each of the datasets.   I am able to successfully query the datasets.

In IAM, the xxxx@gmail.com has the following:
roles/bigquery.user
roles/bigquery.admin
roles/bigquery.owner
roles/bigquery.viewer

I've reviewed the following links but the suggestions have not helped. Any ideas on how to resolve the error?

https://cloud.google.com/bigquery/docs/access-control

Google Big-query api 403-Forbidden Exception

Google API OAuth2, Service Account, "error" : "invalid_grant"

The user does not have bigquery.jobs.create permission in project gdelt-bq

Running queries in BigQuery without being a project User

https://github.com/getredash/redash/issues/1684

The user does not have bigquery.jobs.create permission in project gdelt-bq

Error :service account does not have bigquery.jobs.create permission

Although the error is not on the service account, I also reviewed:
Error :service account does not have bigquery.jobs.create permission

The service accounts for both the Compute Engine project and the BigQuery
project have the following:
roles/bigquery.user
roles/bigquery.admin
roles/bigquery.data viewer
roles/bigquery.data editor

Thanks!


问:
Find exact substring in cell using excel formula
I have the string "L5+L6+L7+L10" in a cell, and then I have a column with the values L1, L2, ... , L10 on each cell. I need to know which of those values are contained in the main string but with an exact match.

To solve my problem, I tried the formula =IF(ISNUM(SEARCH(B3;$F$2));"Found";"Not found") and the results I get are shown in this image.

However, this results are incorrect because I need only L5, L6, L7 and L10 to be found, and not L1.

Is there a way to do so only using excel formulas?

答:
The FILTERXML function can help in this case:

```<code>=SUMPRODUCT(--(B3=FILTERXML("<data><a>" & SUBSTITUTE($F$2;"+";"</a><a>") & "</a></data>";"//a")))
</code>```

Body:
The FILTERXML function can help in this case:

=SUMPRODUCT(--(B3=FILTERXML("<data><a>" & SUBSTITUTE($F$2;"+";"</a><a>") & "</a></data>";"//a")))


问:
Not able to return palindromes
Here is my code:

```<code>def palin(n,m):
   palindromes=[]
   for i in range(n,m):                         #to check for all numbers less than r
       str_i = str(i)
       len_i = len(str_i)
       check = 0
       if len_i == 1:                           #for all numbers less than 10
           palindromes.append(i)

       elif len_i%2 == 0:                       #if length is even
           for a in range(int((len_i/2))):
               if str_i[a] == str_i[-a-1]:
                   check = check+1              #increments check by one if the ath digit is equal to len_i-ath digit

                if check == len_i/2:                #checks whether var check has value of half the length of number
                   palindromes.append(i)

       else:                                    #if length is odd
           for a in range(int((len_i -1)/2)):
               if str_i[a] == str_i[-a-1]:
                   check = check+1

               if check == (len_i-1)/2:
                   palindromes.append(i)

       return palindromes

  lst = palin(100,1000)
  print(lst)
  input("WOW!")
</code>```

When I run the following code, an empty list is printed instead of printing a list containing all the palindromes in the given range.
I've tried this code without defining palin() function ad it works just fine.

答:
To check for palindromes just do :</p>

```<code>palindromes = lambda m,n: [i for i in range(m,n) if str(i)==str(i)[::-1]]
palindrome(100,1000)
</code>```

Title: Not able to return palindromes

Body:
Here is my code:

def palin(n,m):
   palindromes=[]
   for i in range(n,m):                         #to check for all numbers less than r
       str_i = str(i)
       len_i = len(str_i)
       check = 0
       if len_i == 1:                           #for all numbers less than 10
           palindromes.append(i)

       elif len_i%2 == 0:                       #if length is even
           for a in range(int((len_i/2))):
               if str_i[a] == str_i[-a-1]:
                   check = check+1              #increments check by one if the ath digit is equal to len_i-ath digit

                if check == len_i/2:                #checks whether var check has value of half the length of number
                   palindromes.append(i)

       else:                                    #if length is odd
           for a in range(int((len_i -1)/2)):
               if str_i[a] == str_i[-a-1]:
                   check = check+1

               if check == (len_i-1)/2:
                   palindromes.append(i)

       return palindromes

  lst = palin(100,1000)
  print(lst)
  input("WOW!")

When I run the following code, an empty list is printed instead of printing a list containing all the palindromes in the given range.
I've tried this code without defining palin() function ad it works just fine.

Body:
To check for palindromes just do :

palindromes = lambda m,n: [i for i in range(m,n) if str(i)==str(i)[::-1]]
palindrome(100,1000)


问:
c# linq: how to retrieve pieces of data from a returned record
So i have the query:

```<code> var query =
                from product in db.LUT_ProductInfos
                where product.flavor == flavor && product.Container == container
                select flavor;
</code>```

which is returning 1 record (it should always return one record). How do i pull individual attribute values from the result? For example, if it returns 1 record with 3 columns like firstName lastName phoneNumber, and i want to do something with each of the values like

```<code>string fName = firstName
string lName = lastName
int pNumber = phoneNumber
</code>```

without getting into data mapping for objects, what is the most direct way to extract those values from the result variable query

答:
```<code>var row = db.LUT_ProductInfos
    .SingleOrDefault(product => product.flavor == flavor && product.Container == container);

if (row != null)
{
    string firstName = row.fName;
    string lastName = row.lName;
    string phone = row.pNumber;
}
</code>```

Body:
So i have the query:

 var query =
                from product in db.LUT_ProductInfos
                where product.flavor == flavor && product.Container == container
                select flavor;

which is returning 1 record (it should always return one record). How do i pull individual attribute values from the result? For example, if it returns 1 record with 3 columns like firstName lastName phoneNumber, and i want to do something with each of the values like

string fName = firstName
string lName = lastName
int pNumber = phoneNumber

without getting into data mapping for objects, what is the most direct way to extract those values from the result variable query


问:
how to skip_validations after a create callback
I have an User model.
Each User have a profile with some validations.

When I create an User I have this callback => after_create :create_profile

How can I do to skip validations for create_profile

答:
As mentioned in the comments, I think skipping validations is probably a bad idea here (and in general). Modifying the relevant validations on Profile so they only run on update would be preferable, if possible.

But if you absolutely need to skip the validations, then you could do this in the create_profile method:

```<code>def create_profile
  profile = initialize_the_profile

  # etc.

  profile.save(validate: false)
end
</code>```

Body:
As mentioned in the comments, I think skipping validations is probably a bad idea here (and in general). Modifying the relevant validations on Profile so they only run on update would be preferable, if possible.

But if you absolutely need to skip the validations, then you could do this in the create_profile method:

def create_profile
  profile = initialize_the_profile

  # etc.

  profile.save(validate: false)
end


问:
How to force UIC to generate ui_mainwindow.h in the source directory using cmake
UIC successfully creates the ui_mainwindow.h file but it stores it in the build directory. This causes the compile time error 'ui_mainwindow.h: No such file or directory found'.

If I add the full path to the ui_mainwindow.h file in the build directory, cmake (catkin_make) successfully builds the project. Obviously I'd like to avoid using the absolute path to a header file in my source code.

The relevant parts of my CMakeLists:

```<code>set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)

find_package(Qt5 REQUIRED COMPONENTS Widgets Core )
add_executable(monitor src/mainwindow.cpp src/main.cpp src/mainwindow.ui)
qt5_use_modules(monitor Widgets)

target_link_libraries(monitor Qt5::Core Qt5::Widgets ${catkin_LIBRARIES} ${PCL_LIBRARIES} ${OpenCV_LIBRARIES} ${OpenCV_LIBS} )
</code>```

How do I force UIC to build the ui_mainwindow.h file in my source directory. Or how do I include the cmake build directory in my CMakeLists.txt

I've tried

```<code>qt5_wrap_ui (monitor_UI src/mainwindow.ui OPTIONS -o 'ui_mainwindow.h')
add_executable(monitor src/mainwindow.cpp src/main.cpp ${monitor_UI})
</code>```

with no success.

答:
The AUTOGEN_BUILD_DIR CMake variable specifies where AUTOUIC should generate files. If you want the generated files to be placed in your current source directory, you can set it to CMAKE_CURRENT_SOURCE_DIR:

```<code>set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)
set(AUTOGEN_BUILD_DIR ${CMAKE_CURRENT_SOURCE_DIR})
</code>```

An additional note from the CMake-Qt documentation for using AUTOUIC with the AUTOGEN_BUILD_DIR variable:

The generated ui_*.h files are placed in the <AUTOGEN_BUILD_DIR>/include directory which is automatically added to the target’s INCLUDE_DIRECTORIES.

So, you should not have to explicitly list the directory containing the generated headers in an include_directories() command.

Body:
UIC successfully creates the ui_mainwindow.h file but it stores it in the build directory. This causes the compile time error 'ui_mainwindow.h: No such file or directory found'.

If I add the full path to the ui_mainwindow.h file in the build directory, cmake (catkin_make) successfully builds the project. Obviously I'd like to avoid using the absolute path to a header file in my source code.

The relevant parts of my CMakeLists:

set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)

find_package(Qt5 REQUIRED COMPONENTS Widgets Core )
add_executable(monitor src/mainwindow.cpp src/main.cpp src/mainwindow.ui)
qt5_use_modules(monitor Widgets)

target_link_libraries(monitor Qt5::Core Qt5::Widgets ${catkin_LIBRARIES} ${PCL_LIBRARIES} ${OpenCV_LIBRARIES} ${OpenCV_LIBS} )

How do I force UIC to build the ui_mainwindow.h file in my source directory. Or how do I include the cmake build directory in my CMakeLists.txt

I've tried

qt5_wrap_ui (monitor_UI src/mainwindow.ui OPTIONS -o 'ui_mainwindow.h')
add_executable(monitor src/mainwindow.cpp src/main.cpp ${monitor_UI})

with no success.

Body:
The AUTOGEN_BUILD_DIR CMake variable specifies where AUTOUIC should generate files. If you want the generated files to be placed in your current source directory, you can set it to CMAKE_CURRENT_SOURCE_DIR:

set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_AUTOUIC ON)
set(AUTOGEN_BUILD_DIR ${CMAKE_CURRENT_SOURCE_DIR})

An additional note from the CMake-Qt documentation for using AUTOUIC with the AUTOGEN_BUILD_DIR variable:

The generated ui_*.h files are placed in the <AUTOGEN_BUILD_DIR>/include directory which is automatically added to the target’s INCLUDE_DIRECTORIES.

So, you should not have to explicitly list the directory containing the generated headers in an include_directories() command.


问:
Angular 7 AmCharts PDF font
I'm using Angular 7 and AmCharts and I'm exporting a PDF (using the included pdfmake library), but I can't change the default font of the generated PDF. I alread created the vfs_fonts.js with the fonts I need and including it in my angular.json in the scripts section. In the component where I generate the report I do the following:

```<code>let pdfMake = res[0];

pdfMake.fonts = {
    "Open Sans": {
        "normal": 'OpenSans-Regular.ttf',
        "bold": 'OpenSans-Bold.ttf',
        "italics": 'OpenSans-Italic.ttf',
        "bolditalics": 'OpenSans-BoldItalic.ttf'
    }
}

let doc = {
    header: this.drawHeader(),
    footer: this.drawFooter(),
    pageSize: "A4",
    pageOrientation: "portrait",
    pageMargins: [40, 80, 40, 60],
    content: [],
    defaultStyle: {
        font: "Open Sans"
    }
};
</code>```

But I get the following error:

```<code>ERROR Error: Uncaught (in promise): Error: Font 'Open Sans' in style 'normal' is not defined in the font section of the document definition.
Error: Font 'Open Sans' in style 'normal' is not defined in the font section of the document definition
</code>```

How can i solve? Thank you

答: This may be due to the whitespace in Open Sans. Try to change it into OpenSans

Title: Angular 7 AmCharts PDF font

Body:
I'm using Angular 7 and AmCharts and I'm exporting a PDF (using the included pdfmake library), but I can't change the default font of the generated PDF. I alread created the vfs_fonts.js with the fonts I need and including it in my angular.json in the scripts section. In the component where I generate the report I do the following:

let pdfMake = res[0];

pdfMake.fonts = {
    "Open Sans": {
        "normal": 'OpenSans-Regular.ttf',
        "bold": 'OpenSans-Bold.ttf',
        "italics": 'OpenSans-Italic.ttf',
        "bolditalics": 'OpenSans-BoldItalic.ttf'
    }
}

let doc = {
    header: this.drawHeader(),
    footer: this.drawFooter(),
    pageSize: "A4",
    pageOrientation: "portrait",
    pageMargins: [40, 80, 40, 60],
    content: [],
    defaultStyle: {
        font: "Open Sans"
    }
};

But I get the following error:

ERROR Error: Uncaught (in promise): Error: Font 'Open Sans' in style 'normal' is not defined in the font section of the document definition.
Error: Font 'Open Sans' in style 'normal' is not defined in the font section of the document definition

How can i solve? Thank you


问:
How to match, lookup and project with filtering on the other table in MongoDB?
My goal is to get a list of active alerts and the corresponding read dates for a given user.

I have an alerts collection

```<code>{
    "id" : "id",
    "field1": 1,
    "field2": 1,
    "field3": 1,
    "field4": 1,
    "status" : { "name": "ACTIVE" }
}

</code>```

I am tracking when a user has read an alert using a alertstracking collection

```<code>{
    "alertid" : "alertidvalue",
    "userid" : "useridvalue",
    "id" : "id",
    "readdate" : ISODate("2020-02-14T00:45:45.959+0000")
}
</code>```

This is the working query I have but was wondering if there are better/faster ways to do it.
I was going to index alertid, userid fields on the alertstracking collection.

```<code>db.getCollection("alerts").aggregate([
    {
        $match: {
            "status.name": "ACTIVE"
        }
    },
    {
        $lookup: {
            from: "alertstracking",
            localField: "id",
            foreignField: "alertid",
            as: "alerttrack"
        }
    },
    {
        $project: {
            "id": 1,
            "field1": 1,
            "field2": 1,
            "field3": 1,
            "field4": 1,
            "useralerttrack": {
                $filter: {
                    input: "$alerttrack",
                    as: "track",
                    cond: {
                        $eq: ["$$track.userid", "useridvalue"]
                    }
                }
            }
        }
    },
    {
        $project: {
            "id": 1,
            "field1": 1,
            "field2": 1,
            "field3": 1,
            "field4": 1,
            "readdate": {
                $arrayElemAt: ["$useralerttrack.readdate", 0]
            }
        }
    }
])
</code>```

I am hoping to avoid using $project twice and repeating the fields I want.
I had to do it to be able to access useralerttrack.

答:
You can try that like this :

```<code> db.getCollection("alerts").aggregate([
    {
        $match: {
            "status.name": "ACTIVE"
        }
    },
    {
        $lookup:
        {
            from: "alertstracking",
            let: { id: "$id" },
            pipeline: [
                {
                    $match:
                    {
                        $expr:
                        {
                            $and:
                                [
                                    { $eq: ["$alertid", "$$id"] },
                                    { $eq: ["$userid", "useridvalue"] }
                                ]
                        }
                    }
                }, { $project: { _id: 0, readdate: 1 } }
            ],
            as: "readdate"
        }
    }, {
        $addFields: {
            readdate: {
                $arrayElemAt: ["$readdate.readdate", 0]
            }
        }
    }
])
</code>```

Test : MongoDB-Playground

Body:
My goal is to get a list of active alerts and the corresponding read dates for a given user.

I have an alerts collection

{
    "id" : "id",
    "field1": 1,
    "field2": 1,
    "field3": 1,
    "field4": 1,
    "status" : { "name": "ACTIVE" }
}

I am tracking when a user has read an alert using a alertstracking collection

{
    "alertid" : "alertidvalue",
    "userid" : "useridvalue",
    "id" : "id",
    "readdate" : ISODate("2020-02-14T00:45:45.959+0000")
}

This is the working query I have but was wondering if there are better/faster ways to do it.
I was going to index alertid, userid fields on the alertstracking collection.

db.getCollection("alerts").aggregate([
    {
        $match: {
            "status.name": "ACTIVE"
        }
    },
    {
        $lookup: {
            from: "alertstracking",
            localField: "id",
            foreignField: "alertid",
            as: "alerttrack"
        }
    },
    {
        $project: {
            "id": 1,
            "field1": 1,
            "field2": 1,
            "field3": 1,
            "field4": 1,
            "useralerttrack": {
                $filter: {
                    input: "$alerttrack",
                    as: "track",
                    cond: {
                        $eq: ["$$track.userid", "useridvalue"]
                    }
                }
            }
        }
    },
    {
        $project: {
            "id": 1,
            "field1": 1,
            "field2": 1,
            "field3": 1,
            "field4": 1,
            "readdate": {
                $arrayElemAt: ["$useralerttrack.readdate", 0]
            }
        }
    }
])

I am hoping to avoid using $project twice and repeating the fields I want.
I had to do it to be able to access useralerttrack.

Body:
You can try that like this :

 db.getCollection("alerts").aggregate([
    {
        $match: {
            "status.name": "ACTIVE"
        }
    },
    {
        $lookup:
        {
            from: "alertstracking",
            let: { id: "$id" },
            pipeline: [
                {
                    $match:
                    {
                        $expr:
                        {
                            $and:
                                [
                                    { $eq: ["$alertid", "$$id"] },
                                    { $eq: ["$userid", "useridvalue"] }
                                ]
                        }
                    }
                }, { $project: { _id: 0, readdate: 1 } }
            ],
            as: "readdate"
        }
    }, {
        $addFields: {
            readdate: {
                $arrayElemAt: ["$readdate.readdate", 0]
            }
        }
    }
])

Test : MongoDB-Playground


问:
Converting a member function to a static function in C++
I am writing a memory testing framework, in which I replace dynamic memory allocation functions with my own (eg. malloc, realloc, free, etc.). However, the system expects static functions (I can not change this).

I have a MemoryTester class, which logs the memory calls, and I want to bind its member function implementations of the memory allocation functions. Is this possible with C++?

EDIT:

Here is some code highlighting what I'm trying to do:

```<code>typedef void*(allocateFuncPtr) (uint8_t);
typedef void (freeFuncPtr) (void*);

void setAllocateFunction(allocateFuncPtr) {...}
void setFreeFunction(freeFuncPtr) {...}

class MemoryTester
{
    void *malloc(uint8_t size);
    void free(void *ptr);
}

int main()
{
    MemoryTester *tester = new MemoryTester();

    //want to set allocate and free functions to those in tester
    setAllocateFunction( tester->getAllocateFunction() );
    setFreeFunction( tester->getFreeFunction() );

    return 0;
}
</code>```

答: Not unless you make a global object. If the framework takes regular function pointers, then you're stuck with what it provides, and if it doesn't provide for the traditional void* userdata style, then you're stuffed, or it's global object time.</p>

Body:
I am writing a memory testing framework, in which I replace dynamic memory allocation functions with my own (eg. malloc, realloc, free, etc.). However, the system expects static functions (I can not change this).

I have a MemoryTester class, which logs the memory calls, and I want to bind its member function implementations of the memory allocation functions. Is this possible with C++?

EDIT:

Here is some code highlighting what I'm trying to do:

typedef void*(allocateFuncPtr) (uint8_t);
typedef void (freeFuncPtr) (void*);

void setAllocateFunction(allocateFuncPtr) {...}
void setFreeFunction(freeFuncPtr) {...}

class MemoryTester
{
    void *malloc(uint8_t size);
    void free(void *ptr);
}

int main()
{
    MemoryTester *tester = new MemoryTester();

    //want to set allocate and free functions to those in tester
    setAllocateFunction( tester->getAllocateFunction() );
    setFreeFunction( tester->getFreeFunction() );

    return 0;
}