问:
Use IEntityTypeConfiguration with a base entity
In EF Core 2.0, we have the ability to derive from IEntityTypeConfiguration for cleaner Fluent API mappings (source).

How can I extend this pattern to utilize a base entity? In the example below, how can I have a BaseEntityConfiguration to reduce duplication in LanguageConfiguration and MaintainerConfiguration, modifying properties that are in the BaseEntity only in the BaseEntityConfiguration? What would such a BaseEntityConfiguration look like; and how would it be used, if at all, in OnModelCreating()? See the TODOs in-code near the end of the example.

Example:

```<code>public abstract class BaseEntity
{
    public long Id { get; set; }
    public DateTime CreatedDateUtc { get; set; }
    public DateTime? ModifiedDateUtc { get; set; }
}

public class Language : BaseEntity
{
    public string Iso6392 { get; set; }
    public string LocalName { get; set; }
    public string Name { get; set; }
}

public class Maintainer : BaseEntity
{
    public string Email { get; set; }
    public string Name { get; set; }
}

public class FilterListsDbContext : DbContext
{
    public FilterListsDbContext(DbContextOptions options) : base(options)
    {
    }

    public DbSet<Language> Languages { get; set; }
    public DbSet<Maintainer> Maintainers { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        //TODO: Possibly add something like BaseEntityConfiguration?
        modelBuilder.ApplyConfiguration(new LanguageConfiguration());
        modelBuilder.ApplyConfiguration(new MaintainerConfiguration());
    }
}

public class LanguageConfiguration : IEntityTypeConfiguration<Language>
{
    public void Configure(EntityTypeBuilder<Language> entityTypeBuilder)
    {
        //TODO: Move this to something like BaseEntityConfiguration?
        entityTypeBuilder.Property(b => b.CreatedDateUtc).HasDefaultValueSql("CURRENT_TIMESTAMP");
    }
}

public class MaintainerConfiguration : IEntityTypeConfiguration<Maintainer>
{
    public void Configure(EntityTypeBuilder<Maintainer> entityTypeBuilder)
    {
        //TODO: Move this to something like BaseEntityConfiguration?
        entityTypeBuilder.Property(b => b.CreatedDateUtc).HasDefaultValueSql("CURRENT_TIMESTAMP");
    }
}
</code>```

答:
There is another way to solve the problem, and that is to use Template Method Design Pattern. Like this:

```<code>public abstract class BaseEntityTypeConfiguration<TBase> : IEntityTypeConfiguration<TBase>
    where TBase : BaseEntity
{
    public void Configure(EntityTypeBuilder<TBase> entityTypeBuilder)
    {
        //Base Configuration

        ConfigureOtherProperties(builder);
    }

    public abstract void ConfigureOtherProperties(EntityTypeBuilder<TEntity> builder);
}

public class MaintainerConfiguration : BaseEntityTypeConfiguration<Maintainer>
{
    public override void ConfigureOtherProperties(EntityTypeBuilder<Maintainer> entityTypeBuilder)
    {
        entityTypeBuilder.Property(b => b.CreatedDateUtc).HasDefaultValueSql("CURRENT_TIMESTAMP");
    }
}
</code>```

With this way you don't need to write any single line in child configuration.

Body:
In EF Core 2.0, we have the ability to derive from IEntityTypeConfiguration for cleaner Fluent API mappings (source).

How can I extend this pattern to utilize a base entity? In the example below, how can I have a BaseEntityConfiguration to reduce duplication in LanguageConfiguration and MaintainerConfiguration, modifying properties that are in the BaseEntity only in the BaseEntityConfiguration? What would such a BaseEntityConfiguration look like; and how would it be used, if at all, in OnModelCreating()? See the TODOs in-code near the end of the example.

Example:

public abstract class BaseEntity
{
    public long Id { get; set; }
    public DateTime CreatedDateUtc { get; set; }
    public DateTime? ModifiedDateUtc { get; set; }
}

public class Language : BaseEntity
{
    public string Iso6392 { get; set; }
    public string LocalName { get; set; }
    public string Name { get; set; }
}

public class Maintainer : BaseEntity
{
    public string Email { get; set; }
    public string Name { get; set; }
}

public class FilterListsDbContext : DbContext
{
    public FilterListsDbContext(DbContextOptions options) : base(options)
    {
    }

    public DbSet<Language> Languages { get; set; }
    public DbSet<Maintainer> Maintainers { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        //TODO: Possibly add something like BaseEntityConfiguration?
        modelBuilder.ApplyConfiguration(new LanguageConfiguration());
        modelBuilder.ApplyConfiguration(new MaintainerConfiguration());
    }
}

public class LanguageConfiguration : IEntityTypeConfiguration<Language>
{
    public void Configure(EntityTypeBuilder<Language> entityTypeBuilder)
    {
        //TODO: Move this to something like BaseEntityConfiguration?
        entityTypeBuilder.Property(b => b.CreatedDateUtc).HasDefaultValueSql("CURRENT_TIMESTAMP");
    }
}

public class MaintainerConfiguration : IEntityTypeConfiguration<Maintainer>
{
    public void Configure(EntityTypeBuilder<Maintainer> entityTypeBuilder)
    {
        //TODO: Move this to something like BaseEntityConfiguration?
        entityTypeBuilder.Property(b => b.CreatedDateUtc).HasDefaultValueSql("CURRENT_TIMESTAMP");
    }
}

Body:
There is another way to solve the problem, and that is to use Template Method Design Pattern. Like this:

public abstract class BaseEntityTypeConfiguration<TBase> : IEntityTypeConfiguration<TBase>
    where TBase : BaseEntity
{
    public void Configure(EntityTypeBuilder<TBase> entityTypeBuilder)
    {
        //Base Configuration

        ConfigureOtherProperties(builder);
    }

    public abstract void ConfigureOtherProperties(EntityTypeBuilder<TEntity> builder);
}

public class MaintainerConfiguration : BaseEntityTypeConfiguration<Maintainer>
{
    public override void ConfigureOtherProperties(EntityTypeBuilder<Maintainer> entityTypeBuilder)
    {
        entityTypeBuilder.Property(b => b.CreatedDateUtc).HasDefaultValueSql("CURRENT_TIMESTAMP");
    }
}

With this way you don't need to write any single line in child configuration.


来源: stackexchange

问:
Why I am able to access mongodb without running local mongo server?
I am beginning with server side programming by following a online course. As per my understanding, we use mongoose.connect(url) to connect to mongodb where url can be localhost url on which mongodb server is running.

But recently I forgot to run the local mongodb server using mongod. When I ran my node app with following code, it worked just fine :

```<code>var mongoose = require('mongoose');

mongoose.Promise = global.Promise;

mongoose.connect(process.env.MONGO_URL || 'mongodb://localhost:27017/TodoApp');

const {Todo} = require('./../server/models/todos');
const {ObjectID} = require('mongodb');

Todo.remove({}).then((result)=>{
  console.log(result);
});
</code>```

It worked fine with no error even though mongodb server was not running. When I checked the local database using Robo-3T tool, the documents were removed. I have verified this again.

I am unable to understand why my node app was able to connect to mongodb://localhost:27017/TodoApp even though mongodb server was not running on localhost:27017. Also, why Robo-3T tool was able to connect to this localhost: 27017 if server was not running.

Thanks.

答: It occurs when you don't stop the server explicitly and close your terminal.The server is running in background.You can see that in your task manager as well. Press Ctrl+C to quit and it will stop your server.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am beginning with server side programming by following a online course. As per my understanding, we use mongoose.connect(url) to connect to mongodb where url can be localhost url on which mongodb server is running.

But recently I forgot to run the local mongodb server using mongod. When I ran my node app with following code, it worked just fine :

var mongoose = require('mongoose');

mongoose.Promise = global.Promise;

mongoose.connect(process.env.MONGO_URL || 'mongodb://localhost:27017/TodoApp');

const {Todo} = require('./../server/models/todos');
const {ObjectID} = require('mongodb');

Todo.remove({}).then((result)=>{
  console.log(result);
});

It worked fine with no error even though mongodb server was not running. When I checked the local database using Robo-3T tool, the documents were removed. I have verified this again.

I am unable to understand why my node app was able to connect to mongodb://localhost:27017/TodoApp even though mongodb server was not running on localhost:27017. Also, why Robo-3T tool was able to connect to this localhost: 27017 if server was not running.

Thanks.

ContentLicense: CC BY-SA 4.0


问:
Argument of type 'number' is not assignable to parameter of type 'string' giving error
Here is my code

const currentTimeStamp = `${(parseInt(Date.now() / 1000))}`;
const [roomName, setRoomName] = useState<string>(currentTimeStamp || '');
```

it throws an error in production :

Argument of type 'number' is not assignable to parameter of type 'string'.  TS2345

答:
You can remove the parseInt(), because Date.now() return already a number and also Date.now() / 1000.

parseInt() is complaining because it should be given a string instead of a number.

You can do:

```<code>const currentTimeStamp = `${(Date.now() / 1000)}`;
</code>```

Body:
Here is my code

const currentTimeStamp = `${(parseInt(Date.now() / 1000))}`;
const [roomName, setRoomName] = useState<string>(currentTimeStamp || '');

it throws an error in production :

Argument of type 'number' is not assignable to parameter of type 'string'.  TS2345

Body:
You can remove the parseInt(), because Date.now() return already a number and also Date.now() / 1000.

parseInt() is complaining because it should be given a string instead of a number.

You can do:

const currentTimeStamp = `${(Date.now() / 1000)}`;


问:
setting Language of tableau server does not work
I set Language of tableau server and

```<code>tsm restart
</code>```

and then I got

```<code>Stopping service...
Job id is '8', timeout is 60 minutes.
Service stopped successfully.
Starting service...
</code>```

However, language is still English

答:
Have you checked this post: https://help.tableau.com/current/server/en-us/lang_intro.htm

It says language is derived by a number of factors. Could be your change is overridden by preferences elsewhere

Body:
I set Language of tableau server and

tsm restart

and then I got

Stopping service...
Job id is '8', timeout is 60 minutes.
Service stopped successfully.
Starting service...

However, language is still English


问:
Excel Countif across multiple columns
I am trying to count instances of two conditions across two columns of a same sheet. I am basically trying to count the number of data points that have one specific value for one column and one for an adjacent column like an AND logic.
 Can anyone suggest if there is someway i can do this with COUNTIF or do i need to use anything else? </p>

答:
You can do that using the countifs function wherein it will check multiple criteria. See the link for an example.

Using Countifs function

Title: Excel Countif across multiple columns


问:
An error occurred: @Output not initialized
I'm working on an angular app for managers to keep track of their teams, and I'm stuck with an @Output error :

```<code>An error occurred: @Output deleteMeeting not initialized in 'MeetingItemComponent'.
</code>```

I have a Meetings component, generating a list of MeetingItem components. I want to perform actions when the user clicks on different buttons (edit, delete, show details).

Here is my parent Meetings template :

```<code><div class="meeting__list" [@newMeeting]="meetings.length">
  <app-meeting-item
    *ngFor="let meeting of meetings"
    [meeting]="meeting"
    (deleteMeeting)="deleteMeeting($event)"
    (openMeetingDialog)="openMeetingDialog($event)"
    (messageClick)="openMessage($event)"
  ></app-meeting-item>
</div>
</code>```

My MeetingItem template (only the part concerned by this post) :

```<code><span class="meeting__actions">
    <mat-icon *ngIf="meeting.message" (click)="onMessageClick(meeting)" matTooltip="Read the message"
      matTooltipPosition="above" class="icon--notes">notes</mat-icon>
    <mat-icon (click)="onOpenMeetingDialog(meeting)" matTooltip="Edit this meeting" matTooltipPosition="above" class="icon--edit">edit</mat-icon>
    <mat-icon (click)="onDeleteMeeting(meeting.id)" matTooltip="Delete this meeting" matTooltipPosition="above" class="icon--delete">delete_outline</mat-icon>
  </span>
</code>```

My MeetingItem component :

```<code>import { Component, Input, Output } from '@angular/core';
import { EventEmitter } from 'events';

@Component({
  selector: 'app-meeting-item',
  templateUrl: './meeting-item.component.html',
  styleUrls: ['./meeting-item.component.scss']
})
export class MeetingItemComponent {

  @Input() meeting;

  @Output() deleteMeeting = new EventEmitter();
  @Output() openMeetingDialog = new EventEmitter();
  @Output() messageClick = new EventEmitter();

  constructor() {}

  onDeleteMeeting(meetingId) {
    this.deleteMeeting.emit(meetingId);
  }

  onOpenMeetingDialog(meeting) {
    this.openMeetingDialog.emit(meeting);
  }

  onMessageClick(meeting) {
    this.messageClick.emit(meeting);
  }
}
</code>```

答:
change the import : import { EventEmitter } from 'events';
with : import { EventEmitter } from '@angular/core';

Body:
I'm working on an angular app for managers to keep track of their teams, and I'm stuck with an @Output error :

An error occurred: @Output deleteMeeting not initialized in 'MeetingItemComponent'.

I have a Meetings component, generating a list of MeetingItem components. I want to perform actions when the user clicks on different buttons (edit, delete, show details).

Here is my parent Meetings template :

  <app-meeting-item
    *ngFor="let meeting of meetings"
    [meeting]="meeting"
    (deleteMeeting)="deleteMeeting($event)"
    (openMeetingDialog)="openMeetingDialog($event)"
    (messageClick)="openMessage($event)"
  ></app-meeting-item>

My MeetingItem template (only the part concerned by this post) :

    <mat-icon *ngIf="meeting.message" (click)="onMessageClick(meeting)" matTooltip="Read the message"
      matTooltipPosition="above" class="icon--notes">notes</mat-icon>
    <mat-icon (click)="onOpenMeetingDialog(meeting)" matTooltip="Edit this meeting" matTooltipPosition="above" class="icon--edit">edit</mat-icon>
    <mat-icon (click)="onDeleteMeeting(meeting.id)" matTooltip="Delete this meeting" matTooltipPosition="above" class="icon--delete">delete_outline</mat-icon>

My MeetingItem component :

import { Component, Input, Output } from '@angular/core';
import { EventEmitter } from 'events';

@Component({
  selector: 'app-meeting-item',
  templateUrl: './meeting-item.component.html',
  styleUrls: ['./meeting-item.component.scss']
})
export class MeetingItemComponent {

  @Input() meeting;

  @Output() deleteMeeting = new EventEmitter();
  @Output() openMeetingDialog = new EventEmitter();
  @Output() messageClick = new EventEmitter();

  constructor() {}

  onDeleteMeeting(meetingId) {
    this.deleteMeeting.emit(meetingId);
  }

  onOpenMeetingDialog(meeting) {
    this.openMeetingDialog.emit(meeting);
  }

  onMessageClick(meeting) {
    this.messageClick.emit(meeting);
  }
}


问:
Data is not inserting in the database
I am creating a wbsite and I have the following code in c#.net

```<code>public void btnSubmit_Click(TextBox txtEmailAdd, TextBox txtFirstName, TextBox txtLastName, TextBox txtDob, DropDownList drpdwnState, TextBox txtZipCode, DropDownList drpdwnCountry, Label lblMsg)
    {
        string[] ParameterName = { "@EmailId", "@FirstName", "@LastName", "@DOB", "@State", "@PostalCode", "@Country"};
        ArrayList ParameterValue = new ArrayList();
        ParameterValue.Add(Convert.ToString(txtEmailAdd.Text));
        ParameterValue.Add(Convert.ToString(txtFirstName.Text));
        ParameterValue.Add(Convert.ToString(txtLastName.Text));
        ParameterValue.Add(Convert.ToString(txtDob.Text));
        ParameterValue.Add(Convert.ToString(drpdwnState.SelectedItem.Text));
        ParameterValue.Add(Convert.ToString(txtZipCode.Text));
        ParameterValue.Add(Convert.ToString(drpdwnCountry.SelectedItem.Text));

        int i = objDataAccess.Insert_Update_DeleteRecord("[WaterKingdom].[Master].[usp_EmailForm_Insert]", CommandType.StoredProcedure, ParameterName, ParameterValue);

            lblMsg.Text = "Thanks for sending mail.";

    }
</code>```

and I am using the following stored procedure:

```<code>ALTER PROCEDURE [Master].[usp_EmailForm_Insert]
@EmailId varchar(50),
@FirstName varchar(50),
@LastName varchar(50),
@DOB varchar(50),
@State varchar(50),
@PostalCode varchar(50),
@Country varchar(50)
AS
BEGIN
INSERT INTO [Master].[EmailForm]
(EmailId,FirstName,LastName,DOB,State,PostalCode,Country)
VALUES
 (@EmailId,@FirstName,@LastName,@DOB,@State,@PostalCode,@Country)
END
</code>```

still the data is not storing in the database.where is the fault Please help me.
Thanks in advance.

答: Use sqlprofiler, observe traces, you will be able to see what query dbms receives. but please use try catch first.</p>

Title: Data is not inserting in the database

Body:
I am creating a wbsite and I have the following code in c#.net

public void btnSubmit_Click(TextBox txtEmailAdd, TextBox txtFirstName, TextBox txtLastName, TextBox txtDob, DropDownList drpdwnState, TextBox txtZipCode, DropDownList drpdwnCountry, Label lblMsg)
    {
        string[] ParameterName = { "@EmailId", "@FirstName", "@LastName", "@DOB", "@State", "@PostalCode", "@Country"};
        ArrayList ParameterValue = new ArrayList();
        ParameterValue.Add(Convert.ToString(txtEmailAdd.Text));
        ParameterValue.Add(Convert.ToString(txtFirstName.Text));
        ParameterValue.Add(Convert.ToString(txtLastName.Text));
        ParameterValue.Add(Convert.ToString(txtDob.Text));
        ParameterValue.Add(Convert.ToString(drpdwnState.SelectedItem.Text));
        ParameterValue.Add(Convert.ToString(txtZipCode.Text));
        ParameterValue.Add(Convert.ToString(drpdwnCountry.SelectedItem.Text));

        int i = objDataAccess.Insert_Update_DeleteRecord("[WaterKingdom].[Master].[usp_EmailForm_Insert]", CommandType.StoredProcedure, ParameterName, ParameterValue);

            lblMsg.Text = "Thanks for sending mail.";

    }

and I am using the following stored procedure:

ALTER PROCEDURE [Master].[usp_EmailForm_Insert]
@EmailId varchar(50),
@FirstName varchar(50),
@LastName varchar(50),
@DOB varchar(50),
@State varchar(50),
@PostalCode varchar(50),
@Country varchar(50)
AS
BEGIN
INSERT INTO [Master].[EmailForm]
(EmailId,FirstName,LastName,DOB,State,PostalCode,Country)
VALUES
 (@EmailId,@FirstName,@LastName,@DOB,@State,@PostalCode,@Country)
END

still the data is not storing in the database.where is the fault Please help me.
Thanks in advance.


问:
Inserting value in middle table in sqlite
I am trying to insert a value in a middle table, which is created by having two other tables relationship many to many. So this middle table has 2 foreign keys(idProduct and idWarehouse), one for each table and an additional row(storage). So I have trouble inserting in this third row.
It gives this error:

```<code>    Result: near "SELECT": syntax error
At line 1:
INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage)
VALUES
(SELECT
</code>```

This is my code:

```<code>    INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage)
VALUES
(SELECT id FROM Products
WHERE nameProduct = 'cheese',
SELECT id FROM Warehouse
WHERE nameWarehouse = 'Vegas',
'10')
</code>```

答:
Each of the queries must be enclosed inside parantheses:

```<code>INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage) VALUES
(
  (SELECT id FROM Products WHERE nameProduct = 'cheese'),
  (SELECT id FROM Warehouse WHERE nameWarehouse = 'Vegas'),
  '10'
);
</code>```

This will work if theses queries return always only 1 row, so both columns nameProduct and nameWarehouse must be unique.

The statement can also be written without the VALUES clause, with SELECT:

```<code>INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage)
SELECT
  (SELECT id FROM Products WHERE nameProduct = 'cheese'),
  (SELECT id FROM Warehouse WHERE nameWarehouse = 'Vegas'),
  '10';
</code>```

Body:
I am trying to insert a value in a middle table, which is created by having two other tables relationship many to many. So this middle table has 2 foreign keys(idProduct and idWarehouse), one for each table and an additional row(storage). So I have trouble inserting in this third row.
It gives this error:

    Result: near "SELECT": syntax error
At line 1:
INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage)
VALUES
(SELECT

This is my code:

    INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage)
VALUES
(SELECT id FROM Products
WHERE nameProduct = 'cheese',
SELECT id FROM Warehouse
WHERE nameWarehouse = 'Vegas',
'10')

Body:
Each of the queries must be enclosed inside parantheses:

INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage) VALUES
(
  (SELECT id FROM Products WHERE nameProduct = 'cheese'),
  (SELECT id FROM Warehouse WHERE nameWarehouse = 'Vegas'),
  '10'
);

This will work if theses queries return always only 1 row, so both columns nameProduct and nameWarehouse must be unique.

The statement can also be written without the VALUES clause, with SELECT:

INSERT INTO ProductsInWarehouse (idProduct, idWarehouse, storage)
SELECT
  (SELECT id FROM Products WHERE nameProduct = 'cheese'),
  (SELECT id FROM Warehouse WHERE nameWarehouse = 'Vegas'),
  '10';


问:
Print list in terminal on multiple lines
i am really beginner and just starting programming with python since 2 weeks.
here is my question i cant find anywhere or i cant figure out the solution.
i want to see my result in terminal with multiple line , for example i want to calculate long for loop and the result show up this loop on terminal with very long a single line.
is there any solution for this?
and sorry for my bad english isnt my native language.

Code:

```<code>list = list(range(1,100))
for x in list:
    if x % 3 == 0 or x % 5 == 0:
        print(x, end=' ')
</code>```

Output:

```<code>3 5 6 9 10 12 15 18 20 21 24 25 etc...
</code>```

But i want this one:

```<code>3 5 6 9 10
12 15 18 20 21
</code>```

答:
```<code>x_list = range(1,100)
n = 0
for x in x_list:
    if x % 3 == 0 or x % 5 == 0:
        if n == 4:
           print(x, end='\n')
           n = 0
        else:
           print(x, end=' ')
           n = n + 1
</code>```

Body:
i am really beginner and just starting programming with python since 2 weeks.
here is my question i cant find anywhere or i cant figure out the solution.
i want to see my result in terminal with multiple line , for example i want to calculate long for loop and the result show up this loop on terminal with very long a single line.
is there any solution for this?
and sorry for my bad english isnt my native language.

Code:

list = list(range(1,100))
for x in list:
    if x % 3 == 0 or x % 5 == 0:
        print(x, end=' ')

Output:

3 5 6 9 10 12 15 18 20 21 24 25 etc...

But i want this one:

3 5 6 9 10
12 15 18 20 21


问:
Eigen difference between Vector, VectorX, VectorXi
Context

I'm attempting to find the best one dimensional storage type for int. I am planning to use the Eigen::Vector objects as "index containers" (i.e. stores int values that represent indices of a larger Vector) and then do some custom validation of these "index containers" later on. While I may remove values out of this "index container", I will never add new ones to it: so size will always be <= n

However I have noticed that there are several different Eigen::Vector typedefs of which the documentation does not specify the differences. I can get a idea from the signature of the typedef, but largely am still unsure as to which one is appropriate.

Eigen::Vector

Eigen::VectorX

Eigen::VectorXi

Could someone please explain the key differences in these typedefs, I have some ideas as to which one means for example VectorXi the "i" represents int.

Edit

A example of what I mean by "index container" has been requested:

Imagine I have a boolean vector with values {true, false, true, true, false}

From this, my index container would have the values {0, 2, 3}

And the point of this question is to figure out the best kind of Eigen object for the index container

Edit 2

Unrelated, but why a index container?
I need to perform multiple different validation rules that are directly based on the index values.

E.g.
Validation 1: If any values in cont2 are smaller then cont1[0], remove them

```<code>cont1 cont2
--    --
0,    2,
5,    3,
10,   8,
13    12,

for (i = 0; i <= cont2.size(); i++)
    if cont2[i] <= cont1[0]:
       cont2.remove(i)
    else:
       break

</code>```

答:
There is no typdef Eigen::Vector or Eigen::VectorX. The format of such convenience typedefs is Eigen::VectorNt, where the possible choices for N and tare described in the Eigen documentation:

Convenience typedefs

Eigen defines the following Matrix typedefs:

```<code>MatrixNt for Matrix<type, N, N>. For example, MatrixXi for Matrix<int, Dynamic, Dynamic>.
VectorNt for Matrix<type, N, 1>. For example, Vector2f for Matrix<float, 2, 1>.
RowVectorNt for Matrix<type, 1, N>. For example, RowVector3d for Matrix<double, 1, 3>.
</code>```

Where:

```<code>N can be any one of 2, 3, 4, or X (meaning Dynamic).
t can be any one of i (meaning int), f (meaning float), d (meaning double), cf (meaning complex<float>), or cd (meaning complex<double>).
</code>```

These are all variants of the dense Eigen::Matrix class.

It is not entirely clear what you mean with the "index container" that will refer to elements of a larger vector. The index numbers could be stored in an Eigen::VectorXi container, but there could be better options. If only those elements listed in the "index container" are required, and all other elements of the large vector are zero, then an Eigen::SparseVector would be useful. If you provide a specific example it will be easier to help.

Body:
Context

I'm attempting to find the best one dimensional storage type for int. I am planning to use the Eigen::Vector objects as "index containers" (i.e. stores int values that represent indices of a larger Vector) and then do some custom validation of these "index containers" later on. While I may remove values out of this "index container", I will never add new ones to it: so size will always be <= n

However I have noticed that there are several different Eigen::Vector typedefs of which the documentation does not specify the differences. I can get a idea from the signature of the typedef, but largely am still unsure as to which one is appropriate.

Eigen::Vector

Eigen::VectorX

Eigen::VectorXi

Could someone please explain the key differences in these typedefs, I have some ideas as to which one means for example VectorXi the "i" represents int.

Edit

A example of what I mean by "index container" has been requested:

Imagine I have a boolean vector with values {true, false, true, true, false}

From this, my index container would have the values {0, 2, 3}

And the point of this question is to figure out the best kind of Eigen object for the index container

Edit 2

Unrelated, but why a index container?
I need to perform multiple different validation rules that are directly based on the index values.

E.g.
Validation 1: If any values in cont2 are smaller then cont1[0], remove them

cont1 cont2
--    --
0,    2,
5,    3,
10,   8,
13    12,

for (i = 0; i <= cont2.size(); i++)
    if cont2[i] <= cont1[0]:
       cont2.remove(i)
    else:
       break

Body:
There is no typdef Eigen::Vector or Eigen::VectorX. The format of such convenience typedefs is Eigen::VectorNt, where the possible choices for N and tare described in the Eigen documentation:

Convenience typedefs

Eigen defines the following Matrix typedefs:

MatrixNt for Matrix<type, N, N>. For example, MatrixXi for Matrix<int, Dynamic, Dynamic>.
VectorNt for Matrix<type, N, 1>. For example, Vector2f for Matrix<float, 2, 1>.
RowVectorNt for Matrix<type, 1, N>. For example, RowVector3d for Matrix<double, 1, 3>.

Where:

N can be any one of 2, 3, 4, or X (meaning Dynamic).
t can be any one of i (meaning int), f (meaning float), d (meaning double), cf (meaning complex<float>), or cd (meaning complex<double>).

These are all variants of the dense Eigen::Matrix class.

It is not entirely clear what you mean with the "index container" that will refer to elements of a larger vector. The index numbers could be stored in an Eigen::VectorXi container, but there could be better options. If only those elements listed in the "index container" are required, and all other elements of the large vector are zero, then an Eigen::SparseVector would be useful. If you provide a specific example it will be easier to help.


问:
R integrate: determining number of subdivisions
I have a function f that given and input produces two numerical vectors x and y of the same length. For my application, I am passing these vectors into aproxfun by calling

```<code>return(integrate(approxfun(x,y), range(x)[1], range(x)[2], subdivisions = 300))
</code>```

I am executing this process on ~ 1000 different data points. The problem that's occuring is that I keep getting one of two errors:

```<code>Error in integrate(....): maximum number of subdivisions reached
</code>```

or

```<code>Error in integrate(...): extremely bad integrand behavior
</code>```

I have found that both of these errors trigger or pass on different inputs depending on the number of subdivisions I choose for each call. I have spent the past three hours through trial and error to try and determine a value in which my entire application will finish. Is there a way to systematically determine a value of subdivisions based on the vectors x and y on each call that will allow integrate to execute? I don't necessarily need the subdivisions to be the same for each call, I just need a good approximation at every instance. Any other information on how integrate works in regard to this process would also be very helpful.

For reference, the values i have tried in order have been: 100, 400, 200, 250, 300

答:
I came across this post when this error popped out for me. Just wanted to share that the simplest thing i found that works is, obviously increasing the number of subdivisions (because the error is clear that's the problem). And for the bad behaviour, i think smoothing your data and then estimating the function works every time. The problem might be noisy data etc

I almost always use signal::sgolayfilt with very conservative parameters for a quick test.

Body:
I have a function f that given and input produces two numerical vectors x and y of the same length. For my application, I am passing these vectors into aproxfun by calling

return(integrate(approxfun(x,y), range(x)[1], range(x)[2], subdivisions = 300))

I am executing this process on ~ 1000 different data points. The problem that's occuring is that I keep getting one of two errors:

Error in integrate(....): maximum number of subdivisions reached

or

Error in integrate(...): extremely bad integrand behavior

I have found that both of these errors trigger or pass on different inputs depending on the number of subdivisions I choose for each call. I have spent the past three hours through trial and error to try and determine a value in which my entire application will finish. Is there a way to systematically determine a value of subdivisions based on the vectors x and y on each call that will allow integrate to execute? I don't necessarily need the subdivisions to be the same for each call, I just need a good approximation at every instance. Any other information on how integrate works in regard to this process would also be very helpful.

For reference, the values i have tried in order have been: 100, 400, 200, 250, 300


问:
How to enable a button based on a TextBox in GridView in ASP.Net using JavaScript?
I have a TextBox in the TemplateField of a GridView. And I have one button below the GridView. I want to enable the Button when I enter some text in the TextBox in the GridView. How to do this? I am using ASP.Net and C#.Net.

My Source Code of the GridView:

```<code><table>
    <tr>
       <td>
<asp:GridView ID="gvQCAttribute" runat="server" AllowPaging="true" AutoGenerateColumns="false"
                        CellPadding="0" CssClass="datagrid" DataKeyNames="ItemID" EnableTheming="false"
                        PageSize="10" Width="100%">
                        <EmptyDataTemplate>
                            <table border="0" cellpadding="0" cellspacing="1" width="100%">
                                <tr>
                                    <tr>
                                        <th scope="col">
                                            QC Attribute Name
                                        </th>
                                        <th scope="col">
                                            PO Attribute Value
                                        </th>
                                        <th scope="col">
                                            Negative Tolerance
                                        </th>
                                        <th scope="col">
                                            Positive Tolerance
                                        </th>
                                        <th scope="col">
                                            Remarks
                                        </th>
                                    </tr>
                                </tr>
                            </table>
                        </EmptyDataTemplate>
                        <SelectedRowStyle CssClass="rowselect" />
                        <HeaderStyle ForeColor="White" />
                        <AlternatingRowStyle CssClass="table_oddrow" />
                        <RowStyle CssClass="table_evenrow" />
                        <PagerStyle CssClass="pager_style" />
                        <Columns>
                            <asp:TemplateField HeaderText="ItemID" Visible="false">
                                <ItemTemplate>
                                    <asp:Label ID="lblgvItemID" runat="server" Text='<%# Bind("ItemID") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="QCAttributeID" Visible="false">
                                <ItemTemplate>
                                    <asp:Label ID="lblgvQCAttributeID" runat="server" Text='<%# Bind("QCAttributeID") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Attribute Name">
                                <ItemTemplate>
                                    <asp:Label ID="txtQCAttributeName" runat="server" Text='<%# Bind("AttributeName") %>'></asp:Label>
                                </ItemTemplate>
                                <ItemStyle Width="150px" />
                                <ControlStyle Width="100%" />
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="POAttrubute Value">
                                <ItemTemplate>
                                    <asp:TextBox ID="txtPOAttributeValue" runat="server" Text='<%# Bind("POAttributeValue") %>'
                                        onkeyup="return EnableButton(this);" ValidationGroup="Modal" onkeypress="return checkNum(event);"></asp:TextBox>

                                </ItemTemplate>
                                <ItemStyle Width="100px" />
                                <ControlStyle Width="95%" />
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Negative Tolerance">
                                <ItemTemplate>
                                    <asp:TextBox ID="txtNegTolerance" runat="server" Text='<%# Bind("NegativeTolerance") %>'
                                        onkeyup="return EnableButton(this);" ValidationGroup="Modal" onkeypress="return checkNum(event);"></asp:TextBox>

                                </ItemTemplate>
                                <ItemStyle Width="100px" />
                                <ControlStyle Width="95%" />
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Positive Tolerance">
                                <ItemTemplate>
                                    <asp:TextBox ID="txtPosTolerance" runat="server" Text='<%# Bind("PositiveTolerance") %>'
                                        onkeyup="return EnableButton(this);" ValidationGroup="Modal" onkeypress="return checkNum(event);"></asp:TextBox>

                                </ItemTemplate>
                                <ItemStyle Width="100px" />
                                <ControlStyle Width="95%" />
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Remarks">
                                <ItemTemplate>
                                    <asp:TextBox ID="txtRemarks" runat="server" Text='<%# Bind("Remarks") %>' onkeyup="return EnableButton(this);"
                                        ValidationGroup="Modal"></asp:TextBox>
                                </ItemTemplate>
                                <ItemStyle Width="100px" />
                                <ControlStyle Width="95%" />
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>
        </td>
     </tr>
     <tr>
        <td>
         <asp:Button ID="btnmdeSave" runat="server" Text="Save" CssClass="ButtonClass" ValidationGroup="Modal"
                        OnClick="btnmdeSave_Click" />
        </td>
     </tr>
  </table>
</code>```

答:
Use JQuery </p>

```<code>// disabling button
$("#buttonID").attr('disabled','disabled');

$("#textBoxID").keypress(function(){
   // enabling button
   $("#buttonID").removeAttr('disabled');
});
</code>```

Body:
I have a TextBox in the TemplateField of a GridView. And I have one button below the GridView. I want to enable the Button when I enter some text in the TextBox in the GridView. How to do this? I am using ASP.Net and C#.Net.

My Source Code of the GridView:

<asp:GridView ID="gvQCAttribute" runat="server" AllowPaging="true" AutoGenerateColumns="false"
                        CellPadding="0" CssClass="datagrid" DataKeyNames="ItemID" EnableTheming="false"
                        PageSize="10" Width="100%">
                        <EmptyDataTemplate>

                                            QC Attribute Name

                                            PO Attribute Value

                                            Negative Tolerance

                                            Positive Tolerance

                                            Remarks

                        </EmptyDataTemplate>
                        <SelectedRowStyle CssClass="rowselect" />
                        <HeaderStyle ForeColor="White" />
                        <AlternatingRowStyle CssClass="table_oddrow" />
                        <RowStyle CssClass="table_evenrow" />
                        <PagerStyle CssClass="pager_style" />
                        <Columns>
                            <asp:TemplateField HeaderText="ItemID" Visible="false">
                                <ItemTemplate>
                                    <asp:Label ID="lblgvItemID" runat="server" Text='<%# Bind("ItemID") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="QCAttributeID" Visible="false">
                                <ItemTemplate>
                                    <asp:Label ID="lblgvQCAttributeID" runat="server" Text='<%# Bind("QCAttributeID") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Attribute Name">
                                <ItemTemplate>
                                    <asp:Label ID="txtQCAttributeName" runat="server" Text='<%# Bind("AttributeName") %>'></asp:Label>
                                </ItemTemplate>
                                <ItemStyle Width="150px" />
                                <ControlStyle Width="100%" />
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="POAttrubute Value">
                                <ItemTemplate>
                                    <asp:TextBox ID="txtPOAttributeValue" runat="server" Text='<%# Bind("POAttributeValue") %>'
                                        onkeyup="return EnableButton(this);" ValidationGroup="Modal" onkeypress="return checkNum(event);"></asp:TextBox>

                                </ItemTemplate>
                                <ItemStyle Width="100px" />
                                <ControlStyle Width="95%" />
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Negative Tolerance">
                                <ItemTemplate>
                                    <asp:TextBox ID="txtNegTolerance" runat="server" Text='<%# Bind("NegativeTolerance") %>'
                                        onkeyup="return EnableButton(this);" ValidationGroup="Modal" onkeypress="return checkNum(event);"></asp:TextBox>

                                </ItemTemplate>
                                <ItemStyle Width="100px" />
                                <ControlStyle Width="95%" />
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Positive Tolerance">
                                <ItemTemplate>
                                    <asp:TextBox ID="txtPosTolerance" runat="server" Text='<%# Bind("PositiveTolerance") %>'
                                        onkeyup="return EnableButton(this);" ValidationGroup="Modal" onkeypress="return checkNum(event);"></asp:TextBox>

                                </ItemTemplate>
                                <ItemStyle Width="100px" />
                                <ControlStyle Width="95%" />
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Remarks">
                                <ItemTemplate>
                                    <asp:TextBox ID="txtRemarks" runat="server" Text='<%# Bind("Remarks") %>' onkeyup="return EnableButton(this);"
                                        ValidationGroup="Modal"></asp:TextBox>
                                </ItemTemplate>
                                <ItemStyle Width="100px" />
                                <ControlStyle Width="95%" />
                            </asp:TemplateField>
                        </Columns>
                    </asp:GridView>

         <asp:Button ID="btnmdeSave" runat="server" Text="Save" CssClass="ButtonClass" ValidationGroup="Modal"
                        OnClick="btnmdeSave_Click" />

Body:
Use JQuery

// disabling button
$("#buttonID").attr('disabled','disabled');

$("#textBoxID").keypress(function(){
   // enabling button
   $("#buttonID").removeAttr('disabled');
});


问:
Return a string from onCall firebase cloud function
I'm studying firebase cloud function and trying to register a user at firebase auth using javascript and the cloud functions.
What I want to do is to send the data to the cloud function, return data from the cloud function, and then use it on the web app. How can I do it? Here are both codes:

Javascript sends values, which is working well:

```<code>const sendData = firebase.functions().httpsCallable('registerUser');
    sendData({
        email: userEmail,
        password: userPassword

    });
</code>```

and here, my cloud function, which is registering the user correctly.

```<code>exports.registerUser = functions.https.onCall((data, context) => {
const userEmail = data.email;
const userPassword = data.password;

    admin.auth().createUser({
        email: userEmail,
        emailVerified: false,
        password: userPassword,
        displayName: "name",
        photoURL: "...",
        disabled: false
    })
    .then(() => {
        //want to return messages if succeed or not

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

I want to send the messages from the cloud function and then get it on my javascript code. How can I do it?

答:
See https://firebase.google.com/docs/functions/get-started#review_complete_sample_code

You do something like

```<code>exports.registerUser = functions.https.onCall((data, context) => {
const userEmail = data.email;
const userPassword = data.password;

    const userRecord = admin.auth().createUser({
        email: userEmail,
        emailVerified: false,
        password: userPassword,
        displayName: "name",
        photoURL: "...",
        disabled: false
    })

    // userRecord is promise, not a value
    return userRecord;
   });
</code>```

Body:
I'm studying firebase cloud function and trying to register a user at firebase auth using javascript and the cloud functions.
What I want to do is to send the data to the cloud function, return data from the cloud function, and then use it on the web app. How can I do it? Here are both codes:

Javascript sends values, which is working well:

const sendData = firebase.functions().httpsCallable('registerUser');
    sendData({
        email: userEmail,
        password: userPassword

    });

and here, my cloud function, which is registering the user correctly.

exports.registerUser = functions.https.onCall((data, context) => {
const userEmail = data.email;
const userPassword = data.password;

    admin.auth().createUser({
        email: userEmail,
        emailVerified: false,
        password: userPassword,
        displayName: "name",
        photoURL: "...",
        disabled: false
    })
    .then(() => {
        //want to return messages if succeed or not

      }) });

I want to send the messages from the cloud function and then get it on my javascript code. How can I do it?

Body:
See https://firebase.google.com/docs/functions/get-started#review_complete_sample_code

You do something like

exports.registerUser = functions.https.onCall((data, context) => {
const userEmail = data.email;
const userPassword = data.password;

    const userRecord = admin.auth().createUser({
        email: userEmail,
        emailVerified: false,
        password: userPassword,
        displayName: "name",
        photoURL: "...",
        disabled: false
    })

    // userRecord is promise, not a value
    return userRecord;
   });


问:
JavaScript updating value of array element
I have below JSON Array and I am trying to add new object to one of the array element, but problem that I am facing is:

If I push new object for an array array1 at index 0 of arrayHolder then all the array1 elements are getting updated with new object.

```<code>{
  "arrayHolder": [
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    }
 ]
}
</code>```

I am using below code to push to array1:

```<code>var jsonStr = "{\"arrayHolder\":[{\"array1\": [],\"....."; // Json String
var jsonObj = JSON.parse(jsonStr); // String To object

var newObj = {"value": 1}; // New object that I want to push
jsonObj.arrayHolder[0].array1.push(newObj);

// Even below code has same output
jsonObj.arrayHolder[0]["array1"][0] = newObj;

</code>```

I get below output:

```<code>{
  "arrayHolder": [
    {
      "array1": [{"value": 1}],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [{"value": 1}],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [{"value": 1}],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [{"value": 1}],
      "array2": [],
      "array3": [],
      "array4": []
    }
 ]
}
</code>```

I want to update value of array1 only for the 0th element in the arrayHolder array not for all the array1 elements in the main array.

答:
Please try this Solution, @ehab has given you resion why your solution not working, you are using same object to complete object x and as you know object and array are Ref type in Javascript

var x={
  "arrayHolder": [
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    }
 ]
}
 var jsonStr =JSON.stringify(x)// Json String
var jsonObj = JSON.parse(jsonStr); // String To object
debugger
var newObj = {"value": 1}; // New object that I want to push
jsonObj.arrayHolder[0].array1.push(newObj);

result=JSON.stringify(jsonObj)
console.log("result:"+result)```

result:{"arrayHolder":[{"array1":[{"value":1}],"array2":[],"array3":[],"array4":[]},{"array1":[],"array2":[],"array3":[],"array4":[]},{"array1":[],"array2":[],"array3":[],"array4":[]},{"array1":[],"array2":[],"array3":[],"array4":[]}]}

Body:
I have below JSON Array and I am trying to add new object to one of the array element, but problem that I am facing is:

If I push new object for an array array1 at index 0 of arrayHolder then all the array1 elements are getting updated with new object.

{
  "arrayHolder": [
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    }
 ]
}

I am using below code to push to array1:

var jsonStr = "{\"arrayHolder\":[{\"array1\": [],\"....."; // Json String
var jsonObj = JSON.parse(jsonStr); // String To object

var newObj = {"value": 1}; // New object that I want to push
jsonObj.arrayHolder[0].array1.push(newObj);

// Even below code has same output
jsonObj.arrayHolder[0]["array1"][0] = newObj;

I get below output:

{
  "arrayHolder": [
    {
      "array1": [{"value": 1}],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [{"value": 1}],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [{"value": 1}],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [{"value": 1}],
      "array2": [],
      "array3": [],
      "array4": []
    }
 ]
}

I want to update value of array1 only for the 0th element in the arrayHolder array not for all the array1 elements in the main array.

Body:
Please try this Solution, @ehab has given you resion why your solution not working, you are using same object to complete object x and as you know object and array are Ref type in Javascript

var x={
  "arrayHolder": [
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    },
    {
      "array1": [],
      "array2": [],
      "array3": [],
      "array4": []
    }
 ]
}
 var jsonStr =JSON.stringify(x)// Json String
var jsonObj = JSON.parse(jsonStr); // String To object
debugger
var newObj = {"value": 1}; // New object that I want to push
jsonObj.arrayHolder[0].array1.push(newObj);

result=JSON.stringify(jsonObj)
console.log("result:"+result)

result:{"arrayHolder":[{"array1":[{"value":1}],"array2":[],"array3":[],"array4":[]},{"array1":[],"array2":[],"array3":[],"array4":[]},{"array1":[],"array2":[],"array3":[],"array4":[]},{"array1":[],"array2":[],"array3":[],"array4":[]}]}


答:
As explained in the documentation, to "send data back to the client, return data that can be JSON encoded" and to return errors you should "throw (or return a Promise rejected with) an instance of functions.https.HttpsError".

```<code>exports.registerUser = functions.https.onCall((data, context) => {
    const userEmail = data.email;
    const userPassword = data.password;

    return admin.auth().createUser({  // See the return here
        email: userEmail,
        emailVerified: false,
        password: userPassword,
        displayName: "name",
        photoURL: "...",
        disabled: false
    })
        .then(userRecord => {
            //want to return messages if succeed or not
            return {
                result: 'success'
            };
        })
        .catch(error => {
            throw new functions.https.HttpsError('invalid-argument', 'message');
        })
});
</code>```

You may use different error codes, depending on the type of error. See the doc.

Then, in the client, you need to do as follows:

```<code>sendData({
    email: userEmail,
    password: userPassword
}).then(function(response) {
   // Read result of the Cloud Function.
   var result = response.data.result;
   // ...
 }).catch(function(error) {
   // Getting the Error details.
   var code = error.code;
   var message = error.message;
   var details = error.details;
   // ...
 });
</code>```

Title: Return a string from onCall firebase cloud function

Body:
As explained in the documentation, to "send data back to the client, return data that can be JSON encoded" and to return errors you should "throw (or return a Promise rejected with) an instance of functions.https.HttpsError".

exports.registerUser = functions.https.onCall((data, context) => {
    const userEmail = data.email;
    const userPassword = data.password;

    return admin.auth().createUser({  // See the return here
        email: userEmail,
        emailVerified: false,
        password: userPassword,
        displayName: "name",
        photoURL: "...",
        disabled: false
    })
        .then(userRecord => {
            //want to return messages if succeed or not
            return {
                result: 'success'
            };
        })
        .catch(error => {
            throw new functions.https.HttpsError('invalid-argument', 'message');
        })
});

You may use different error codes, depending on the type of error. See the doc.

Then, in the client, you need to do as follows:

sendData({
    email: userEmail,
    password: userPassword
}).then(function(response) {
   // Read result of the Cloud Function.
   var result = response.data.result;
   // ...
 }).catch(function(error) {
   // Getting the Error details.
   var code = error.code;
   var message = error.message;
   var details = error.details;
   // ...
 });


问:
Is HTML tag such as ,  mandatory?
Thanks for your consideration about this problem.
I started to learn HTML and knew that there're many kinds of tags.
For example, such as (HTML), (head), (body), (a), (div), (table).

But I wonder if these codes can be used separately or should include (HTML), (head), (body) format always.

答:
An HTML document has two* main parts:

head. The head element contains title and meta data of a web document.
body. The body element contains the information that you want to display on a web page.
* To make your web pages compatible with HTML 4, you need to add a document type declaration (DTD) before the HTML element. Many web authoring software add DTD and basic tags automatically when you create a new web page.

In a web page, the first tag (specifically, ) indicates the markup language that is being used for the document. The  tag contains information about the web page. Lastly, the content appears in the  tag. The following illustration provides a summary.

HTML, HEAD, BODY is requried - than all content you should write in BODY section

HERE you can read official documentation https://www.w3.org/TR/html401/struct/global.html

Title: Is HTML tag such as <head>, <HTML> mandatory?


问:
Relative Frequency in Python
Is it possible to calculate the relative frequency of elements occurring in a list in Python?

For example:

```<code>['apple', 'banana', 'apple', 'orange'] # apple for example would be 0.5
</code>```

答:
This simple code will do the job, returns a list of tuples but you can adapt it easily.

```<code>lst = ['apple', 'banana', 'apple', 'orange']
counts = [(word, lst.count(word) / len(lst)) for word in set(lst)]
</code>```

It will return the relative frequencies of each word as below:

```<code>[('orange', 0.25), ('banana', 0.25), ('apple', 0.5)]
</code>```

Note that :

iterate over set(lst) to avoid duplicates

divide the lst.count by len(lst) to get relative frequencies

Title: Relative Frequency in Python

Body:
Is it possible to calculate the relative frequency of elements occurring in a list in Python?

For example:

['apple', 'banana', 'apple', 'orange'] # apple for example would be 0.5

Body:
This simple code will do the job, returns a list of tuples but you can adapt it easily.

lst = ['apple', 'banana', 'apple', 'orange']
counts = [(word, lst.count(word) / len(lst)) for word in set(lst)]

It will return the relative frequencies of each word as below:

[('orange', 0.25), ('banana', 0.25), ('apple', 0.5)]

Note that :

iterate over set(lst) to avoid duplicates

divide the lst.count by len(lst) to get relative frequencies


问:
Return only matching array item instead of all document values in ElasticSearch
I'm new to Elasticsearch. I'm faced with unexpected behaviour with my client's search page result and my investigation has ended up in the ES structure.

I have a document field name, which has this mapping:

```<code>"name": {
    "type": "text",
    "fields": {
        "sort_name": {
            "index": false,
            "type": "keyword"
        }
    }
}
</code>```

So, usually, it has one value, so in this case, it matches a query correctly. But sometimes I have a document, which has an array of product names, which leads to fetching all of the array values into the search page result.

For example, if I have a product, which looks like this:

```<code>{
    ...,
    "name": [
        "Tesla",
        "Model",
        "XXX"
    ]
}
</code>```

So, when I search this on name:

```<code>{
    "from": 0,
    "query": {
        "bool": {
            "must": [
                {
                    "match": {
                        "name": "Tesla"
                    }
                }
            ]
        }
    },
    "size": 150,
    "sort": [
        {
            "_score": {
                "order": "desc"
            }
        }
    ],
    "stored_fields": [
        "_id",
        "_score"
    ]
}
</code>```

It returns this:

```<code>"hits": {
    "total": 1,
    "max_score": 1.0,
    "hits": [
        {
            "_index": "magento2_product_4_v2",
            "_type": "document",
            "_id": "99999",
            "_score": 1.0,
            "_source": {
                "name": [
                    "Tesla",
                    "Model",
                    "XXX"
                ]
            }
        }
    ]
}
</code>```

When I needed only Tesla.

As a result, I will have 2 different products (imagine that Model and XXX are products), that users didn't search.

I would really want to avoid structure changes if that's possible since the new index is created automatically during reindex process (I'm using Magento 2 right now), so could you help me with the query?

答:
You have 1 document in your index magento2_product_4_v2.
This is

```<code>{
    ...,
    "name": [
        "Tesla",
        "Model",
        "XXX"
    ]
}
</code>```

after request you get this document because this doc suits your request.

May be you want create 3 docs?

```<code>{
    ...,
    "name": [
        "Tesla",
    ]
}

{
    ...,
    "name": [
        "Model"
    ]
}

{
    ...,
    "name": [
        "XXX"
    ]
}

</code>```

Body:
I'm new to Elasticsearch. I'm faced with unexpected behaviour with my client's search page result and my investigation has ended up in the ES structure.

I have a document field name, which has this mapping:

"name": {
    "type": "text",
    "fields": {
        "sort_name": {
            "index": false,
            "type": "keyword"
        }
    }
}

So, usually, it has one value, so in this case, it matches a query correctly. But sometimes I have a document, which has an array of product names, which leads to fetching all of the array values into the search page result.

For example, if I have a product, which looks like this:

{
    ...,
    "name": [
        "Tesla",
        "Model",
        "XXX"
    ]
}

So, when I search this on name:

{
    "from": 0,
    "query": {
        "bool": {
            "must": [
                {
                    "match": {
                        "name": "Tesla"
                    }
                }
            ]
        }
    },
    "size": 150,
    "sort": [
        {
            "_score": {
                "order": "desc"
            }
        }
    ],
    "stored_fields": [
        "_id",
        "_score"
    ]
}

It returns this:

"hits": {
    "total": 1,
    "max_score": 1.0,
    "hits": [
        {
            "_index": "magento2_product_4_v2",
            "_type": "document",
            "_id": "99999",
            "_score": 1.0,
            "_source": {
                "name": [
                    "Tesla",
                    "Model",
                    "XXX"
                ]
            }
        }
    ]
}

When I needed only Tesla.

As a result, I will have 2 different products (imagine that Model and XXX are products), that users didn't search.

I would really want to avoid structure changes if that's possible since the new index is created automatically during reindex process (I'm using Magento 2 right now), so could you help me with the query?

Body:
You have 1 document in your index magento2_product_4_v2.
This is

{
    ...,
    "name": [
        "Tesla",
        "Model",
        "XXX"
    ]
}

after request you get this document because this doc suits your request.

May be you want create 3 docs?

{
    ...,
    "name": [
        "Tesla",
    ]
}

{
    ...,
    "name": [
        "Model"
    ]
}

{
    ...,
    "name": [
        "XXX"
    ]
}


问:
Why is the copy constructor of this template class not getting called?
The copy constructor never gets called (I'm using g++ with -std=c++11):

pointers.cpp:

#include <iostream>

template <typename T>
class SharedPtr
{
private:
    int *m_Count;
    T *m_Ptr;

public:
    SharedPtr(T *ptr = nullptr)
        : m_Count(new int), m_Ptr(ptr)
    {
        *m_Count = 1;
    }

    SharedPtr(const SharedPtr &other)
        : m_Count(other.m_Count), m_Ptr(other.m_Ptr)
    {
        std::cout << "Copied: " << *m_Count << std::endl;
        (*m_Count)++;
    }

    ~SharedPtr()
    {
        (*m_Count)--;
        if (*m_Count == 0)
        {
            delete m_Ptr;
            delete m_Count;
        }
    }

    T &operator*()
    {
        return *m_Ptr;
    }
};
```

<p>main.cpp:</p>

<pre class="lang-cpp prettyprint-override"><code>#include "pointers.cpp"
#include <iostream>

class Entity
{
public:
    Entity()
    {
        std::cout << "Entity created!" << std::endl;
    }
    ~Entity()
    {
        std::cout << "Entity destroyed!" << std::endl;
    }
};

int main(int argc, char *argv[])
{
    {
        SharedPtr<Entity> e0;
        std::cin.get();
        {
            SharedPtr<Entity> sharedEntity = new Entity();
            std::cin.get();
            e0 = sharedEntity;
            std::cin.get();
        }
        std::cin.get();
    }

    std::cin.get();
}
</code>```

I looked at other similar questions asked here, but none of them worked.
The copy constructor should be ClassName(const ClassName &other), right?

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam lacinia mattis arcu, vitae interdum leo. Praesent viverra, tortor a tincidunt ullamcorper, arcu urna finibus enim, congue dignissim tortor quam ut dui. Ut eleifend suscipit ligula sagittis consequat. Integer semper orci eu metus mollis sodales. Fusce sollicitudin elementum nisl, non congue odio lobortis non. Duis tempus tristique nisi nec tempor. Sed in ullamcorper nisi. Suspendisse id suscipit magna, eu pellentesque ligula. Nullam aliquam pretium tellus, eget venenatis eros pharetra finibus.

答:
None of the code in main() calls the copy contructor of SharedPtr:

SharedPtr<Entity> e0; calls SharedPtr(T *ptr = nullptr)

SharedPtr<Entity> sharedEntity = new Entity(); calls SharedPtr(T *ptr = nullptr)

e0 = sharedEntity; calls operator=() which is not defined in your SharedPtr

Body:
The copy constructor never gets called (I'm using g++ with -std=c++11):

pointers.cpp:

#include <iostream>

template <typename T>
class SharedPtr
{
private:
    int *m_Count;
    T *m_Ptr;

public:
    SharedPtr(T *ptr = nullptr)
        : m_Count(new int), m_Ptr(ptr)
    {
        *m_Count = 1;
    }

    SharedPtr(const SharedPtr &other)
        : m_Count(other.m_Count), m_Ptr(other.m_Ptr)
    {
        std::cout << "Copied: " << *m_Count << std::endl;
        (*m_Count)++;
    }

    ~SharedPtr()
    {
        (*m_Count)--;
        if (*m_Count == 0)
        {
            delete m_Ptr;
            delete m_Count;
        }
    }

    T &operator*()
    {
        return *m_Ptr;
    }
};

main.cpp:

#include "pointers.cpp"
#include <iostream>

class Entity
{
public:
    Entity()
    {
        std::cout << "Entity created!" << std::endl;
    }
    ~Entity()
    {
        std::cout << "Entity destroyed!" << std::endl;
    }
};

int main(int argc, char *argv[])
{
    {
        SharedPtr<Entity> e0;
        std::cin.get();
        {
            SharedPtr<Entity> sharedEntity = new Entity();
            std::cin.get();
            e0 = sharedEntity;
            std::cin.get();
        }
        std::cin.get();
    }

    std::cin.get();
}

I looked at other similar questions asked here, but none of them worked.
The copy constructor should be ClassName(const ClassName &other), right?

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam lacinia mattis arcu, vitae interdum leo. Praesent viverra, tortor a tincidunt ullamcorper, arcu urna finibus enim, congue dignissim tortor quam ut dui. Ut eleifend suscipit ligula sagittis consequat. Integer semper orci eu metus mollis sodales. Fusce sollicitudin elementum nisl, non congue odio lobortis non. Duis tempus tristique nisi nec tempor. Sed in ullamcorper nisi. Suspendisse id suscipit magna, eu pellentesque ligula. Nullam aliquam pretium tellus, eget venenatis eros pharetra finibus.


问:
How to set only Date in DataTable Column of Type DateTime WEB
Hi All,

My Question is simple but please keep in mind I'm not binding it to any grid or any of ASP.NET control I have my own grid control and I want to keep it as a DateTime Column for sorting purpose.

I'm creating DataTable With Column Type DateTime.

```<code>DataTable data = new DataTable();
data.Columns.Add("Invoice Date", typeof(DateTime));
DataRow dr = data.NewRow();
dr[0] = DateTime.Now;

//Adding filled row to the DataTable object
dataTable.Rows.Add(dr);
</code>```

When the Value is shown on ASP.NET page
it is show something like this:

```<code>"2/28/2011 12:00:00 AM"
</code>```

I have 2 columns like this, In 1 column I want to show just date and in other column i want to show date as "Dec 2011", these formats can be achieved if i use DataColumn with type string but in that case sorting is not working properly.

Please help.

Thanks.

答:
You seem to be mixing your concepts. The purpose of the database, and the table inside it, is to store data---not to format it. It is an implementation detail exactly how this gets stored. Just like you wouldn't care whether the datatable uses UTF-8 or UTF-16 for storing your strings, you shouldn't care what format it stores a date in. In this case, it is almost certainly stored as the number of nanoseconds since 12:00 midnight, January 1, 0001 C.E. That is, if you actually dug around in the binary format of the database, you would find those nanoseconds.

Now, the purpose of your UI layer, i.e. the ASP.NET page, is to display the data. This is where you make any formatting decisions.

One UI layer is whatever software you're using to view the database. That software is converting some number of nanoseconds, which is the internal storage format, into the string "2/28/2011 12:00:00 AM". The reason it is doing this is because that is the default format for displaying points in time.

The UI layer you are coding---the one you have control over---now needs to choose how it converts those nanoseconds into text. If it goes with the default, it will display "2/28/2011 12:00:00 AM". But if you don't want the default, you need to actually specify that. Pranay Rana's answer gives an idea of how to do that. This is the whole point of your UI layer.

Body:
Hi All,

My Question is simple but please keep in mind I'm not binding it to any grid or any of ASP.NET control I have my own grid control and I want to keep it as a DateTime Column for sorting purpose.

I'm creating DataTable With Column Type DateTime.

DataTable data = new DataTable();
data.Columns.Add("Invoice Date", typeof(DateTime));
DataRow dr = data.NewRow();
dr[0] = DateTime.Now;

//Adding filled row to the DataTable object
dataTable.Rows.Add(dr);

When the Value is shown on ASP.NET page
it is show something like this:

"2/28/2011 12:00:00 AM"

I have 2 columns like this, In 1 column I want to show just date and in other column i want to show date as "Dec 2011", these formats can be achieved if i use DataColumn with type string but in that case sorting is not working properly.

Please help.

Thanks.


问:
java.lang.NoSuchMethodError: No virtual method toString(Z)Ljava/lang/String; in class Lokhttp3/Cookie; or its super classe
I'm using retrofit (2.7.2) and OkHttp version (4.4.0) in an Android project and I'm facing a crash on a request.

Dependencies:

```<code>kapt("com.squareup.moshi:moshi-kotlin-codegen:1.9.2")
implementation 'com.squareup.moshi:moshi:1.9.2'
implementation 'com.squareup.retrofit2:retrofit:2.7.2'
implementation 'com.squareup.retrofit2:converter-moshi:2.7.2'

implementation("com.squareup.okhttp3:okhttp:4.4.0")
implementation("com.squareup.okhttp3:okhttp-tls:4.4.0")
implementation "com.squareup.okhttp3:logging-interceptor:4.4.0"
</code>```

Crash:

java.lang.NoSuchMethodError: No virtual method
  toString(Z)Ljava/lang/String; in class Lokhttp3/Cookie; or its super
  classes (declaration of 'okhttp3.Cookie' appears in
  /data/app/com.package-1/base.apk:classes3.dex)
          at okhttp3.JavaNetCookieJar.saveFromResponse(JavaNetCookieJar.java:45)
          at com.facebook.react.modules.network.ReactCookieJarContainer.saveFromResponse(ReactCookieJarContainer.java:36)
          at okhttp3.internal.http.HttpHeaders.receiveHeaders(HttpHeaders.kt:207)
          at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:85)
          at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
          at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:74)
          at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
          at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:197)
          at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:502)
          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
          at java.lang.Thread.run(Thread.java:818)

答:
I used following okhttp3 versions  and woked fine for me...

```<code>implementation 'com.squareup.okhttp3:okhttp:4.7.2'
implementation 'com.squareup.okhttp3:logging-interceptor:4.4.1'
implementation 'com.squareup.okhttp3:okhttp-urlconnection:4.4.1'
</code>```

Body:
I'm using retrofit (2.7.2) and OkHttp version (4.4.0) in an Android project and I'm facing a crash on a request.

Dependencies:

kapt("com.squareup.moshi:moshi-kotlin-codegen:1.9.2")
implementation 'com.squareup.moshi:moshi:1.9.2'
implementation 'com.squareup.retrofit2:retrofit:2.7.2'
implementation 'com.squareup.retrofit2:converter-moshi:2.7.2'

implementation("com.squareup.okhttp3:okhttp:4.4.0")
implementation("com.squareup.okhttp3:okhttp-tls:4.4.0")
implementation "com.squareup.okhttp3:logging-interceptor:4.4.0"

Crash:

java.lang.NoSuchMethodError: No virtual method
  toString(Z)Ljava/lang/String; in class Lokhttp3/Cookie; or its super
  classes (declaration of 'okhttp3.Cookie' appears in
  /data/app/com.package-1/base.apk:classes3.dex)
          at okhttp3.JavaNetCookieJar.saveFromResponse(JavaNetCookieJar.java:45)
          at com.facebook.react.modules.network.ReactCookieJarContainer.saveFromResponse(ReactCookieJarContainer.java:36)
          at okhttp3.internal.http.HttpHeaders.receiveHeaders(HttpHeaders.kt:207)
          at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:85)
          at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
          at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:74)
          at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
          at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:197)
          at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:502)
          at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
          at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
          at java.lang.Thread.run(Thread.java:818)

Body:
I used following okhttp3 versions  and woked fine for me...

implementation 'com.squareup.okhttp3:okhttp:4.7.2'
implementation 'com.squareup.okhttp3:logging-interceptor:4.4.1'
implementation 'com.squareup.okhttp3:okhttp-urlconnection:4.4.1'


问:
The project cannot be built until the build path errors are resolved.
While compiling an android project in eclipse 3.4.2, I am getting The project cannot be built until the build path errors are resolved.

I got a temporary solution  from the blog http://www.scottdstrader.com/blog/ether_archives/000921.html

The resolution was to force a resave of the selected projects (and their .classpath files):

Open the project properties

Select Java Build Path > Libraries

Add a new, arbitrary library (to be deleted later) > OK

Wait for the workspace to refresh (or force a refresh of the project)

The error(s) will go away

Remove the dummy library

The only other references I could find were to make minor alterations of contents of the .classpath file.

Is there any permanent fix for this issue?

答:
I was getting an additional warning

```<code>The compiler compliance specified is 1.6 but a JRE 1.8 is used
</code>```

Resolving this warning make the error also go away.  The steps are as follows:

I right-clicked on it, then clicked on Quick Fix.  From the dialog that opened I selected Open the Compiler Compliance property page, and clicked the Finish button.

(This is same as Java Compiler section.)

In this dialog I found the Compiler compliance level drop down and changed 1.6 to 1.8, and clicked on Apply and close.

I got a message box Compiler Settings Changed which asked if I wanted to Build the project now?.  I clicked on Yes.

The build path error went away.

Body:
I was getting an additional warning

The compiler compliance specified is 1.6 but a JRE 1.8 is used

Resolving this warning make the error also go away.  The steps are as follows:

I right-clicked on it, then clicked on Quick Fix.  From the dialog that opened I selected Open the Compiler Compliance property page, and clicked the Finish button.

(This is same as Java Compiler section.)

In this dialog I found the Compiler compliance level drop down and changed 1.6 to 1.8, and clicked on Apply and close.

I got a message box Compiler Settings Changed which asked if I wanted to Build the project now?.  I clicked on Yes.

The build path error went away.


问:
Wordpress and temporary access url
I hope everybody is well.

I have to set up a new Wordpress site, but this is the first time I need to setup the website "before" the domain name is registered.

I have webspace on shared webhosting and I can setup the Wordpress site using a temporary subdomain for my shared hosting, but this will mean setting up the Wordpress site using the temporary access url instead of the proper domain name that will be done next week.

If I setup the Wordpress site using the temporary url, once the domain name is registered, is simply changing the website address in the Wordpress General settings adequate or will I need to update the database too?

Is there a plugin that will do the above?

Thanks in advance if anyone can assist.

AH

答:
You can proceed and start setting up your WordPress site to start designing, ones you've completed and domain name is registered like you've said, you can:

Backup your File Manager files to a local storage Highlight the content, right click, and click compress then download.

Navigate to the root folder of the now newly registered domain(public_html), and upload the files you downloaded above.

Go to the wp-config.php file, highlight and select edit.

Just before a line with this words /* That’s all, stop editing! Happy blogging. */
Add the lines below then save and close.

```<code>define('WP_HOME','http://example.com');

define('WP_SITEURL','http://example.com');
</code>```

example.com is the new domain.

Now go back to your WordPress site to update the links. Yes, their is a plugin to update links, a lot of them but search for 'Velvet Blues Update URLs' using the plugins-> Add new.

After installing and activating the plugin,go to Tools -> Update urls, enter your old (subdomain) and new (root domain) URLs and in Step 2, check all options except Update All GUIDs.

Click the Update URLs Now button to proceed.

Check out under FaQs of your hosting provider if they've indicated a method on how users can move sites from subdomain to main domain.

Title: Wordpress and temporary access url

Body:
You can proceed and start setting up your WordPress site to start designing, ones you've completed and domain name is registered like you've said, you can:

Backup your File Manager files to a local storage Highlight the content, right click, and click compress then download.

Navigate to the root folder of the now newly registered domain(public_html), and upload the files you downloaded above.

Go to the wp-config.php file, highlight and select edit.

Just before a line with this words /* That’s all, stop editing! Happy blogging. */
Add the lines below then save and close.

define('WP_HOME','http://example.com');

define('WP_SITEURL','http://example.com');

example.com is the new domain.

Now go back to your WordPress site to update the links. Yes, their is a plugin to update links, a lot of them but search for 'Velvet Blues Update URLs' using the plugins-> Add new.

After installing and activating the plugin,go to Tools -> Update urls, enter your old (subdomain) and new (root domain) URLs and in Step 2, check all options except Update All GUIDs.

Click the Update URLs Now button to proceed.

Check out under FaQs of your hosting provider if they've indicated a method on how users can move sites from subdomain to main domain.


问:
How to keep jQuery auto populated dropdown result selected?
I have this dynamic dropdown which fetches result on selection of one select menu, but the challenge I am facing after it auto populates the results on the second dropdown on submit of form the value of second select disappears. How to make it not disappear even after submit?

Here is my HTML & PHP

```<code> <div class="row form-group">
                    <div class="col-md-12">
                    <label class="sr-only" for="job_category">Select Job Category</label>
            <select name="job_category" id="category" class='form-control'>
            <option value='' selected='selected' disabled='disabled'>Select Job Category</option>
            <?php
            $sql="select * from job_category ";
            foreach ($db->query($sql) as $row) {
            ?>
            <option value='<?php echo $row[cat_id]; ?>' <?php if($job_category == ''.$row[cat_id].'') echo 'selected="selected"'; ?>><?php echo $row[cat_name]; ?></option>
            <?php
            }
            ?>
            </select>
            </div>
        </div>

                <div class='row form-group'>
                    <div class='col-md-12'>
                    <label class='sr-only' for='job_subcategory'>Select Job Industry</label>
                <select name='job_subcategory' id='sub-category' class='form-control'>
                <option value='' selected='selected' disabled='disabled'>Select Job Industry</option>
                </select>
                </div>
            </div>
</code>```

Here is my JQ

```<code>$(document).ready(function() {
    $('#category').change(function(){
        var cat_id=$('#category').val();
        $('#sub-category').empty();
        $.get('fetchCategories.php',{'cat_id':cat_id},function(return_data){
        $.each(return_data.data, function(key,value){
                $("#sub-category").append("<option value='" + value.subcat_id +"'>"+value.subcat_name+"</option>");
            });

        }, "json");
        });
    });
</code>```

And my fetchCategories.php

```<code>@$cat_id=$_GET['cat_id'];
//$cat_id=2;
/// Preventing injection attack ////
if(!is_numeric($cat_id)){
echo "Data Error";
exit;
 }
/// end of checking injection attack ////
require "includes/config.php";

$sql="select subcat_name,subcat_id from job_subcategory where cat_id='$cat_id'";
$row=$db->prepare($sql);
$row->execute();
$result=$row->fetchAll(PDO::FETCH_ASSOC);

$main = array('data'=>$result);
echo json_encode($main);
</code>```

答:
You can use localStorage to store the current value which is selected  by user on change of select-box and then when your page gets reload just fetch the stored data from localStorage and then call your ajax to retrieve required data.

Your jquery code will somewhat look like below (Sorry for any syntax error) :

```<code>$(document).ready(function() {
  //check if there is any value in localStorage
  if (localStorage.getItem("save") != null) {
    //get that value
    var value = localStorage.getItem("save");
    console.log(value);
    //set value in selected box
    $("#sub-category").val(value);
  }
  //onchange of subcategory
  $('#sub-category').change(function() {
    var values = $(this).val();
    localStorage.clear(); //clear previous data
    localStorage.setItem("save", values); //add data to storage

  });

  $('#category').change(function() {
    var cat_id = $('#category').val();
    $('#sub-category').empty();
    $.get('fetchCategories.php', {
      'cat_id': cat_id
    }, function(return_data) {
      $.each(return_data.data, function(key, value) {
        $("#sub-category").append("<option value='" + value.subcat_id + "'>" + value.subcat_name + "</option>");
      });

    }, "json");
  });

});
</code>```

Body:
I have this dynamic dropdown which fetches result on selection of one select menu, but the challenge I am facing after it auto populates the results on the second dropdown on submit of form the value of second select disappears. How to make it not disappear even after submit?

Here is my HTML & PHP

                    Select Job Category
            <select name="job_category" id="category" class='form-control'>
            <option value='' selected='selected' disabled='disabled'>Select Job Category</option>
            <?php
            $sql="select * from job_category ";
            foreach ($db->query($sql) as $row) {
            ?>
            <option value='<?php echo $row[cat_id]; ?>' <?php if($job_category == ''.$row[cat_id].'') echo 'selected="selected"'; ?>><?php echo $row[cat_name]; ?></option>
            <?php
            }
            ?>
            </select>

                    Select Job Industry
                <select name='job_subcategory' id='sub-category' class='form-control'>
                <option value='' selected='selected' disabled='disabled'>Select Job Industry</option>
                </select>

Here is my JQ

$(document).ready(function() {
    $('#category').change(function(){
        var cat_id=$('#category').val();
        $('#sub-category').empty();
        $.get('fetchCategories.php',{'cat_id':cat_id},function(return_data){
        $.each(return_data.data, function(key,value){
                $("#sub-category").append("<option value='" + value.subcat_id +"'>"+value.subcat_name+"</option>");
            });

        }, "json");
        });
    });

And my fetchCategories.php

@$cat_id=$_GET['cat_id'];
//$cat_id=2;
/// Preventing injection attack ////
if(!is_numeric($cat_id)){
echo "Data Error";
exit;
 }
/// end of checking injection attack ////
require "includes/config.php";

$sql="select subcat_name,subcat_id from job_subcategory where cat_id='$cat_id'";
$row=$db->prepare($sql);
$row->execute();
$result=$row->fetchAll(PDO::FETCH_ASSOC);

$main = array('data'=>$result);
echo json_encode($main);

Body:
You can use localStorage to store the current value which is selected  by user on change of select-box and then when your page gets reload just fetch the stored data from localStorage and then call your ajax to retrieve required data.

Your jquery code will somewhat look like below (Sorry for any syntax error) :

$(document).ready(function() {
  //check if there is any value in localStorage
  if (localStorage.getItem("save") != null) {
    //get that value
    var value = localStorage.getItem("save");
    console.log(value);
    //set value in selected box
    $("#sub-category").val(value);
  }
  //onchange of subcategory
  $('#sub-category').change(function() {
    var values = $(this).val();
    localStorage.clear(); //clear previous data
    localStorage.setItem("save", values); //add data to storage

  });

  $('#category').change(function() {
    var cat_id = $('#category').val();
    $('#sub-category').empty();
    $.get('fetchCategories.php', {
      'cat_id': cat_id
    }, function(return_data) {
      $.each(return_data.data, function(key, value) {
        $("#sub-category").append("<option value='" + value.subcat_id + "'>" + value.subcat_name + "</option>");
      });

    }, "json");
  });

});


问:
Trimming GPS information with awk
In a little bash script I simply try to trim GPS input data so that I have longitude and latitude values in separate variables:

```<code>  echo $geo_data
  GPS_latitude=$( echo $geo_data | awk -F"+|-" '{print substr($0,index($0,$2-1),1) $2}' )
  GPS_longitude=$( echo $geo_data | awk -F"+|-" '{print substr($0,index($0,$3-1),1) $3}' )
  echo $GPS_latitude
  echo $GPS_longitude
</code>```

But what I get out seems to confuse the +/- signs in front of each component:

```<code>-04.7367+055.5230
-04.7367
-055.5230
</code>```

I thought the index()-parameters would exactly avoid this situation, but obviously I did something wrong. Any idea how to fix this?

Title: Trimming GPS information with awk

Body:
In a little bash script I simply try to trim GPS input data so that I have longitude and latitude values in separate variables:

  echo $geo_data
  GPS_latitude=$( echo $geo_data | awk -F"+|-" '{print substr($0,index($0,$2-1),1) $2}' )
  GPS_longitude=$( echo $geo_data | awk -F"+|-" '{print substr($0,index($0,$3-1),1) $3}' )
  echo $GPS_latitude
  echo $GPS_longitude

But what I get out seems to confuse the +/- signs in front of each component:

-04.7367+055.5230
-04.7367
-055.5230

I thought the index()-parameters would exactly avoid this situation, but obviously I did something wrong. Any idea how to fix this?

Body:
With bash and a regex:

geo_data="-04.7367+055.5230"

[[ "$geo_data" =~ ^([+-][0-9.]+)([+-][0-9.]+)$ ]]
echo "${BASH_REMATCH[1]} ${BASH_REMATCH[2]}"

Output:

-04.7367 +055.5230


问:
Using finditer as performant regex splitter
I have large strings that look similar to this (it is only an excerpt, of course):

content = "78934789;;;;foo foo bar bar;;;;ping pong;;;\n\n\n78923456901;;;;Some more text;;;;;\n\n\n187894;;;;Number 12345 should not match;;;;\n\n\n123456 \n\n\nthis should be included;;;;;;\n\n\n"
```

<p>and I want to return as performant as possible only the substrings that start with a number from 6 to 11 characters long and go to the next of this number or just to the end if such a number cannot be found any more.</p>

<p>So the text consists of any characters (including newlines and other special characters) and the only reliable separator is a number between 6 and 11 characters long. At this separator the text is to be split to start further processing. The processing happens within a web application and should run as an independent thread. Therefore, it would be useful if the substring matches came back iterable.</p>

<p>So I think that <code>re.finditer()</code> is what I need, but I have problems getting this working. I've tried a lot. The version that comes closest to my wanted result is using a regex with a lookahead assertion <code>/(?=\d{6,11}).*/</code> together with <code>re.finditer()</code>, see:</p>

<pre class="lang-py prettyprint-override"><code>In [1]: import re
In [2]: content = "78934789;;;;foo foo bar bar;;;;ping pong;;;\n\n\n78923456901;;;;Some more text;;;;;\n\n\n187894;;;;Number 12345 should not match;;;;\n\n\n123456 \n\n\nthis should be included;;;;;;\n\n\n"
In [3]: pattern = re.compile(r"(?=\d{6,11}).*")
In [4]: for item in re.finditer(pattern, content):
   ...:     print(item)
   ...:
<re.Match object; span=(0, 43), match='78934789;;;;foo foo bar bar;;;;ping pong;;;'>
<re.Match object; span=(46, 80), match='78923456901;;;;Some more text;;;;;'>
<re.Match object; span=(83, 126), match='187894;;;;Number 12345 should not match;;;;'>
<re.Match object; span=(129, 136), match='123456 '>
</code>```

But the newlines and the rest of the content string are not included. I've played a bit with flags like re.DOTALL or re.MULTILINE, and even with regex library which supports lookup assertions with variable lengths. Everything without success, so I'm stuck on this point.

To be as exact as possible, these are the substrings for given content string, a generator should return/yield:

```<code>"78934789;;;;foo foo bar bar;;;;ping pong;;;\n\n\n"
"78923456901;;;;Some more text;;;;;\n\n\n"
"187894;;;;Number 12345 should not match;;;;\n\n\n"
"123456 \n\n\nthis should be included;;;;;;\n\n\n"
</code>```

As you can see in my approach above, newline characters are not included, and using a re.DOTALL flag in my approach would lead to an unwanted behaviour, that .* will match too much, then.

What I want to know is: Is this possible using a regular expression and to be also performant (i.e. not iterating twice over the string) or should I better write my own generator function, instead (eventually a bit more complex)?

答:
The comment from Wiktor Stribiżew finally solved my problem. He suggested to use something like this: re.findall(r'^\d{6,11}\b.*(?:\n(?!\d{6,11}\b).*)*', content, flags=re.M) and provided it also via regex demo page and python demo page.

What I missed is that using a negative lookahead assertion (?!...) will be needed to restrict .* matching too much. With that it was easy to reformulate it using re.finditer():

import re
from typing import Iterable, Optional, Pattern, Union

case_pattern = re.compile(
    rf"""
    \d{6,11}             # case number
    (?s:.(?!\d{6,11}))*  # all until next case
    .*\n*                # rest for last match
    """, re.MULTILINE | re.VERBOSE
)

def split_generator(text: str, pattern: Optional[Union[Pattern, str]] = " ") -> Iterable[str]:
    """Split given text on regex pattern (default: " ")

    A given text (str) is split according to a given regex pattern. If no
    pattern is given, a default is used that simply splits the text at every
    single space.

    This is a generator iterator function that tries to be as performant as
    possible, i.e. iterates over the text only once and only temporarily
    stores parts of the text (the split elements) while yielding them.

    :param text: The text on which the split will be performed
    :param pattern: A regex pattern that will applied as separator
    :return: An iterator which will yield each split item
    """
    yield from (el.group() for el in re.finditer(pattern, text))
```

This seems to be less performant as the answer from Martin P., because of the expensive negative lookahead constraint in the regex. But it handles the memory consumption much better without the need to save something. The regex can probably be optimized, though.

Body:
I have large strings that look similar to this (it is only an excerpt, of course):

content = "78934789;;;;foo foo bar bar;;;;ping pong;;;\n\n\n78923456901;;;;Some more text;;;;;\n\n\n187894;;;;Number 12345 should not match;;;;\n\n\n123456 \n\n\nthis should be included;;;;;;\n\n\n"

and I want to return as performant as possible only the substrings that start with a number from 6 to 11 characters long and go to the next of this number or just to the end if such a number cannot be found any more.

So the text consists of any characters (including newlines and other special characters) and the only reliable separator is a number between 6 and 11 characters long. At this separator the text is to be split to start further processing. The processing happens within a web application and should run as an independent thread. Therefore, it would be useful if the substring matches came back iterable.

So I think that re.finditer() is what I need, but I have problems getting this working. I've tried a lot. The version that comes closest to my wanted result is using a regex with a lookahead assertion /(?=\d{6,11}).*/ together with re.finditer(), see:

In [1]: import re
In [2]: content = "78934789;;;;foo foo bar bar;;;;ping pong;;;\n\n\n78923456901;;;;Some more text;;;;;\n\n\n187894;;;;Number 12345 should not match;;;;\n\n\n123456 \n\n\nthis should be included;;;;;;\n\n\n"
In [3]: pattern = re.compile(r"(?=\d{6,11}).*")
In [4]: for item in re.finditer(pattern, content):
   ...:     print(item)
   ...:
<re.Match object; span=(0, 43), match='78934789;;;;foo foo bar bar;;;;ping pong;;;'>
<re.Match object; span=(46, 80), match='78923456901;;;;Some more text;;;;;'>
<re.Match object; span=(83, 126), match='187894;;;;Number 12345 should not match;;;;'>
<re.Match object; span=(129, 136), match='123456 '>

But the newlines and the rest of the content string are not included. I've played a bit with flags like re.DOTALL or re.MULTILINE, and even with regex library which supports lookup assertions with variable lengths. Everything without success, so I'm stuck on this point.

To be as exact as possible, these are the substrings for given content string, a generator should return/yield:

"78934789;;;;foo foo bar bar;;;;ping pong;;;\n\n\n"
"78923456901;;;;Some more text;;;;;\n\n\n"
"187894;;;;Number 12345 should not match;;;;\n\n\n"
"123456 \n\n\nthis should be included;;;;;;\n\n\n"

As you can see in my approach above, newline characters are not included, and using a re.DOTALL flag in my approach would lead to an unwanted behaviour, that .* will match too much, then.

What I want to know is: Is this possible using a regular expression and to be also performant (i.e. not iterating twice over the string) or should I better write my own generator function, instead (eventually a bit more complex)?

Body:
The comment from Wiktor Stribiżew finally solved my problem. He suggested to use something like this: re.findall(r'^\d{6,11}\b.*(?:\n(?!\d{6,11}\b).*)*', content, flags=re.M) and provided it also via regex demo page and python demo page.

What I missed is that using a negative lookahead assertion (?!...) will be needed to restrict .* matching too much. With that it was easy to reformulate it using re.finditer():

import re
from typing import Iterable, Optional, Pattern, Union

case_pattern = re.compile(
    rf"""
    \d{6,11}             # case number
    (?s:.(?!\d{6,11}))*  # all until next case
    .*\n*                # rest for last match
    """, re.MULTILINE | re.VERBOSE
)

def split_generator(text: str, pattern: Optional[Union[Pattern, str]] = " ") -> Iterable[str]:
    """Split given text on regex pattern (default: " ")

    A given text (str) is split according to a given regex pattern. If no
    pattern is given, a default is used that simply splits the text at every
    single space.

    This is a generator iterator function that tries to be as performant as
    possible, i.e. iterates over the text only once and only temporarily
    stores parts of the text (the split elements) while yielding them.

    :param text: The text on which the split will be performed
    :param pattern: A regex pattern that will applied as separator
    :return: An iterator which will yield each split item
    """
    yield from (el.group() for el in re.finditer(pattern, text))

This seems to be less performant as the answer from Martin P., because of the expensive negative lookahead constraint in the regex. But it handles the memory consumption much better without the need to save something. The regex can probably be optimized, though.