问:
HSQLDB View (INNER-JOIN) faulty during runtime

Setting

I have a problem with a db view. We are using Java 7, Google Guice, Hibernate 5.1.0.Final, liquibase 3.5.3 and HSQLDB 2.3.4.
We parse a couple of files and save the data to the hsqldb (file mode). Then we use a combination of two views to collect the data for our file export.

Problem

So the problem I have is as follows:
Our select query will give us a different result during runtime compared to opening the hsqldb afterwards. This is the problem simplified:

Views

These are are similar (but much simplified) to the views we use:

```<code>CREATE VIEW COMBINED AS
SELECT i.ID, o.*
FROM
    OCCURRENCE o
    JOIN IDENTIFIER i ON o.REF_IDENTIFIER_REVISION = i.ID

CREATE VIEW COMBINED_2 AS
SELECT
    combinedView.ID_OCCURRENCE as ID_PARENT,
    combinedChild.ID_OCCURRENCE as ID_CHILD,
    ConfData.DATA,
FROM
    COMBINED combinedView
    INNER JOIN CONF_DATA ConfData ON ConfData.ID = combinedView.ID_PARENT
    JOIN OCCURRENCE combinedChild ON combinedView.ID_OCCURRENCE = combinedChild.REF_PARENTOCCURRENCE
</code>```

Query

We the perform a query on the second view:

```<code>TypedQuery<ViewEntity> query = entityManager.get().createQuery("select v from ViewEntity v", VerwendungGeoPosEntity.class);
</code>```

Table OCCURRENCE

I will skip IDENTIFIER because in my problem the data is irrelevant. In my case the data of IDENTIFIER is the same for all cases. I included the first view just in case it might be the case that having a view including a view is the cause of the problem.

```<code>ID     | NAME
------ | ------
1      | Parent 1
2      | Child 1
</code>```

Table CONF_DATA

```<code>ID     | DATA
------ | ------
1      | Parent Data 1
2      | Parent Data 2
</code>```

View during runtime

```<code>ID_PARENT | ID_CHILD | DATA
------    | ------   | ------
1         | 2        | Parent Data 1
1         | 2        | Parent Data 1
</code>```

View after runtime

```<code>ID_PARENT | ID_CHILD | DATA
------    | ------   | ------
1         | 2        | Parent Data 1
1         | 2        | Parent Data 2
</code>```

Has anyone encountered this problem before? I would greatly appreciate the help.

答:
I found the problem.

While the entities for all tables where in the persistence.xml the entity for the view COMBINED_2 was not. :$

After adding the entity to the context everything worked.

No problem was indicated during run time. But when I created a JUnit test for this special case I got a message, that the entity was not mapped.

Body:
Setting

I have a problem with a db view. We are using Java 7, Google Guice, Hibernate 5.1.0.Final, liquibase 3.5.3 and HSQLDB 2.3.4.
We parse a couple of files and save the data to the hsqldb (file mode). Then we use a combination of two views to collect the data for our file export.

Problem

So the problem I have is as follows:
Our select query will give us a different result during runtime compared to opening the hsqldb afterwards. This is the problem simplified:

Views

These are are similar (but much simplified) to the views we use:

CREATE VIEW COMBINED AS
SELECT i.ID, o.*
FROM
    OCCURRENCE o
    JOIN IDENTIFIER i ON o.REF_IDENTIFIER_REVISION = i.ID

CREATE VIEW COMBINED_2 AS
SELECT
    combinedView.ID_OCCURRENCE as ID_PARENT,
    combinedChild.ID_OCCURRENCE as ID_CHILD,
    ConfData.DATA,
FROM
    COMBINED combinedView
    INNER JOIN CONF_DATA ConfData ON ConfData.ID = combinedView.ID_PARENT
    JOIN OCCURRENCE combinedChild ON combinedView.ID_OCCURRENCE = combinedChild.REF_PARENTOCCURRENCE

Query

We the perform a query on the second view:

TypedQuery<ViewEntity> query = entityManager.get().createQuery("select v from ViewEntity v", VerwendungGeoPosEntity.class);

Table OCCURRENCE

I will skip IDENTIFIER because in my problem the data is irrelevant. In my case the data of IDENTIFIER is the same for all cases. I included the first view just in case it might be the case that having a view including a view is the cause of the problem.

ID     | NAME
------ | ------
1      | Parent 1
2      | Child 1

Table CONF_DATA

ID     | DATA
------ | ------
1      | Parent Data 1
2      | Parent Data 2

View during runtime

ID_PARENT | ID_CHILD | DATA
------    | ------   | ------
1         | 2        | Parent Data 1
1         | 2        | Parent Data 1

View after runtime

ID_PARENT | ID_CHILD | DATA
------    | ------   | ------
1         | 2        | Parent Data 1
1         | 2        | Parent Data 2

Has anyone encountered this problem before? I would greatly appreciate the help.


来源: stackexchange

问:
EF Code first Multi level inheritence issues
I have a multi level inheriance heriarchy consisting of the following classes:

```<code>public abstract class BasePoco
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
}

public class Activity : BasePoco
{
    public ActivityType ActivityType { get; set; }

    [MaxLength(1000)]
    public string Description { get; set; }
}
</code>```

Now there is a special type of Activity which is called a data capture activity.
Which is of two types: DataCaptureActivity and MasterDataCaptureActivity

```<code>public class DataCaptureActivityBase : Activity
{

    [MaxLength(100)]
    public string Title { get; set; }
}
</code>```

Derived Classes :

```<code>[Table("DataCaptureActivities")]
public class DataCaptureActivity : DataCaptureActivityBase
{
    public virtual DataCaptureActivityType DataCaptureActivityType { get; set; }
}

[Table("MasterDataCaptureActivities")]
public class MasterDataCaptureActivity : DataCaptureActivityBase
{
    public virtual string SomeOtherField{ get; set; }
}
</code>```

The problem is upon creating a migration, The column Title which should be a part of DataCaptureActivity is actually coming up as a part of the Activity table.
Please note that DataCaptureActivityBase should not be a table in my schema. It is just for holding the common parameters DataCaptureActivities table and its inherited types.

The Schema I am targeting is :

```<code>Activity
-------------------------------
Id  | ActivityType  | Description

DataCaptureActivity
--------------------------------
Id | Title

MasterDataCaptureActivity
--------------------------------
Id | Title | SomeOtherField
</code>```

答:
Your context is similar to this

```<code>public DbSet<Activity> Activity { get; set; }
public DbSet<DataCaptureActivity> DataCaptureActivities { get; set; }
public DbSet<MasterDataCaptureActivity> MasterDataCaptureActivities { get; set; }
</code>```

What you are conceptually saying to EF is that DataCaptureActivity is an Activity and that MasterDataCaptureActivity is an Activity. On the database you are creating all the three entities.

With this model, the statement

```<code>context.Activities.ToList();
</code>```

retrieve all the Activities (the union of the three sets).

To do it with your model, EF on the database will create the Activity table with a Discriminator. The table structures will be this (look at 1-1 relationships):

```<code>ExecuteNonQuery==========
CREATE TABLE [Activity] (
 [Id] int not null identity(1,1)
, [ActivityType] int not null
, [Description] text null
, [Title] varchar(100) null
, [Discriminator] varchar(128) not null
);
ALTER TABLE [Activity] ADD CONSTRAINT [PK_Activity_7ea65be8] PRIMARY KEY ([Id])
ExecuteNonQuery==========
CREATE TABLE [DataCaptureActivities] (
 [Id] int not null
, [DataCaptureActivityType] int not null
);
ALTER TABLE [DataCaptureActivities] ADD CONSTRAINT [PK_DataCaptureActivities_7ea65be8] PRIMARY KEY ([Id])
ExecuteNonQuery==========
CREATE TABLE [MasterDataCaptureActivities] (
 [Id] int not null
, [SomeOtherField] text null
);
ALTER TABLE [MasterDataCaptureActivities] ADD CONSTRAINT [PK_MasterDataCaptureActivities_7ea65be8] PRIMARY KEY ([Id])
ExecuteNonQuery==========
CREATE INDEX [IX_Id] ON [DataCaptureActivities] ([Id])
ExecuteNonQuery==========
CREATE INDEX [IX_Id] ON [MasterDataCaptureActivities] ([Id])
ExecuteNonQuery==========
ALTER TABLE [DataCaptureActivities] ADD CONSTRAINT [FK_DataCaptureActivities_Activity_Id] FOREIGN KEY ([Id]) REFERENCES [Activity] ([Id])
ExecuteNonQuery==========
ALTER TABLE [MasterDataCaptureActivities] ADD CONSTRAINT [FK_MasterDataCaptureActivities_Activity_Id] FOREIGN KEY ([Id]) REFERENCES [Activity] ([Id])
</code>```

Also, this statement

```<code>using (var context = new Context(GetConnection()))
{
    context.DataCaptureActivities.Add(new DataCaptureActivity() {Description = "Description"});
    context.SaveChanges();
}
</code>```

Will generate this DML statements (2 insert statements!!!)

```<code>ExecuteDbDataReader==========
insert into [Activity]([ActivityType], [Description], [Title], [Discriminator])
values (@p0, @p1, null, @p2);
select [Id]
from [Activity]
where [Id] = @@identity
@p0 = 0
@p1 = Description
@p2 = DataCaptureActivity
ExecuteNonQuery==========
insert into [DataCaptureActivities]([Id], [DataCaptureActivityType])
values (@p0, @p1);

@p0 = 1
@p1 = 0
</code>```

The solution to target your tables

You need to change your model saying that DataCaptureActivities and MasterDataCaptureActivities are not Activities.

For example:

```<code>public abstract class BasePoco
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
}

public class BaseActivity : BasePoco
{
    public ActivityType ActivityType { get; set; }

    [MaxLength(1000)]
    public string Description { get; set; }
}

[Table("Activity")]
public class Activity : BaseActivity
{
}

public class DataCaptureActivityBase : BaseActivity
{

    [MaxLength(100)]
    public string Title { get; set; }
}

[Table("DataCaptureActivities")]
public class DataCaptureActivity : DataCaptureActivityBase
{
    public virtual DataCaptureActivityType DataCaptureActivityType { get; set; }
}

[Table("MasterDataCaptureActivities")]
public class MasterDataCaptureActivity : DataCaptureActivityBase
{
    public virtual string SomeOtherField { get; set; }
}
</code>```

In this case, the tables structures will be this

```<code>ExecuteNonQuery==========
CREATE TABLE [Activity] (
 [Id] int not null identity(1,1)
, [ActivityType] int not null
, [Description] text null
);
ALTER TABLE [Activity] ADD CONSTRAINT [PK_Activity_2b28bd47] PRIMARY KEY ([Id])
ExecuteNonQuery==========
CREATE TABLE [DataCaptureActivities] (
 [Id] int not null identity(1,1)
, [DataCaptureActivityType] int not null
, [Title] varchar(100) null
, [ActivityType] int not null
, [Description] text null
);
ALTER TABLE [DataCaptureActivities] ADD CONSTRAINT [PK_DataCaptureActivities_2b28bd47] PRIMARY KEY ([Id])
ExecuteNonQuery==========
CREATE TABLE [MasterDataCaptureActivities] (
 [Id] int not null identity(1,1)
, [SomeOtherField] text null
, [Title] varchar(100) null
, [ActivityType] int not null
, [Description] text null
);
ALTER TABLE [MasterDataCaptureActivities] ADD CONSTRAINT [PK_MasterDataCaptureActivities_2b28bd47] PRIMARY KEY ([Id])
</code>```

But in this case, if you want to enum all the ActivityBase you need to join them (Union) on the client.

ContentLicense: CC BY-SA 3.0

Body:
I have a multi level inheriance heriarchy consisting of the following classes:

public abstract class BasePoco
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
}

public class Activity : BasePoco
{
    public ActivityType ActivityType { get; set; }

    [MaxLength(1000)]
    public string Description { get; set; }
}

Now there is a special type of Activity which is called a data capture activity.
Which is of two types: DataCaptureActivity and MasterDataCaptureActivity

public class DataCaptureActivityBase : Activity
{

    [MaxLength(100)]
    public string Title { get; set; }
}

Derived Classes :

[Table("DataCaptureActivities")]
public class DataCaptureActivity : DataCaptureActivityBase
{
    public virtual DataCaptureActivityType DataCaptureActivityType { get; set; }
}

[Table("MasterDataCaptureActivities")]
public class MasterDataCaptureActivity : DataCaptureActivityBase
{
    public virtual string SomeOtherField{ get; set; }
}

The problem is upon creating a migration, The column Title which should be a part of DataCaptureActivity is actually coming up as a part of the Activity table.
Please note that DataCaptureActivityBase should not be a table in my schema. It is just for holding the common parameters DataCaptureActivities table and its inherited types.

The Schema I am targeting is :

Activity
-------------------------------
Id  | ActivityType  | Description

DataCaptureActivity
--------------------------------
Id | Title

MasterDataCaptureActivity
--------------------------------
Id | Title | SomeOtherField

Body:
Your context is similar to this

public DbSet<Activity> Activity { get; set; }
public DbSet<DataCaptureActivity> DataCaptureActivities { get; set; }
public DbSet<MasterDataCaptureActivity> MasterDataCaptureActivities { get; set; }

What you are conceptually saying to EF is that DataCaptureActivity is an Activity and that MasterDataCaptureActivity is an Activity. On the database you are creating all the three entities.

With this model, the statement

context.Activities.ToList();

retrieve all the Activities (the union of the three sets).

To do it with your model, EF on the database will create the Activity table with a Discriminator. The table structures will be this (look at 1-1 relationships):

ExecuteNonQuery==========
CREATE TABLE [Activity] (
 [Id] int not null identity(1,1)
, [ActivityType] int not null
, [Description] text null
, [Title] varchar(100) null
, [Discriminator] varchar(128) not null
);
ALTER TABLE [Activity] ADD CONSTRAINT [PK_Activity_7ea65be8] PRIMARY KEY ([Id])
ExecuteNonQuery==========
CREATE TABLE [DataCaptureActivities] (
 [Id] int not null
, [DataCaptureActivityType] int not null
);
ALTER TABLE [DataCaptureActivities] ADD CONSTRAINT [PK_DataCaptureActivities_7ea65be8] PRIMARY KEY ([Id])
ExecuteNonQuery==========
CREATE TABLE [MasterDataCaptureActivities] (
 [Id] int not null
, [SomeOtherField] text null
);
ALTER TABLE [MasterDataCaptureActivities] ADD CONSTRAINT [PK_MasterDataCaptureActivities_7ea65be8] PRIMARY KEY ([Id])
ExecuteNonQuery==========
CREATE INDEX [IX_Id] ON [DataCaptureActivities] ([Id])
ExecuteNonQuery==========
CREATE INDEX [IX_Id] ON [MasterDataCaptureActivities] ([Id])
ExecuteNonQuery==========
ALTER TABLE [DataCaptureActivities] ADD CONSTRAINT [FK_DataCaptureActivities_Activity_Id] FOREIGN KEY ([Id]) REFERENCES [Activity] ([Id])
ExecuteNonQuery==========
ALTER TABLE [MasterDataCaptureActivities] ADD CONSTRAINT [FK_MasterDataCaptureActivities_Activity_Id] FOREIGN KEY ([Id]) REFERENCES [Activity] ([Id])

Also, this statement

using (var context = new Context(GetConnection()))
{
    context.DataCaptureActivities.Add(new DataCaptureActivity() {Description = "Description"});
    context.SaveChanges();
}

Will generate this DML statements (2 insert statements!!!)

ExecuteDbDataReader==========
insert into [Activity]([ActivityType], [Description], [Title], [Discriminator])
values (@p0, @p1, null, @p2);
select [Id]
from [Activity]
where [Id] = @@identity
@p0 = 0
@p1 = Description
@p2 = DataCaptureActivity
ExecuteNonQuery==========
insert into [DataCaptureActivities]([Id], [DataCaptureActivityType])
values (@p0, @p1);

@p0 = 1
@p1 = 0

The solution to target your tables

You need to change your model saying that DataCaptureActivities and MasterDataCaptureActivities are not Activities.

For example:

public abstract class BasePoco
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
}

public class BaseActivity : BasePoco
{
    public ActivityType ActivityType { get; set; }

    [MaxLength(1000)]
    public string Description { get; set; }
}

[Table("Activity")]
public class Activity : BaseActivity
{
}

public class DataCaptureActivityBase : BaseActivity
{

    [MaxLength(100)]
    public string Title { get; set; }
}

[Table("DataCaptureActivities")]
public class DataCaptureActivity : DataCaptureActivityBase
{
    public virtual DataCaptureActivityType DataCaptureActivityType { get; set; }
}

[Table("MasterDataCaptureActivities")]
public class MasterDataCaptureActivity : DataCaptureActivityBase
{
    public virtual string SomeOtherField { get; set; }
}

In this case, the tables structures will be this

ExecuteNonQuery==========
CREATE TABLE [Activity] (
 [Id] int not null identity(1,1)
, [ActivityType] int not null
, [Description] text null
);
ALTER TABLE [Activity] ADD CONSTRAINT [PK_Activity_2b28bd47] PRIMARY KEY ([Id])
ExecuteNonQuery==========
CREATE TABLE [DataCaptureActivities] (
 [Id] int not null identity(1,1)
, [DataCaptureActivityType] int not null
, [Title] varchar(100) null
, [ActivityType] int not null
, [Description] text null
);
ALTER TABLE [DataCaptureActivities] ADD CONSTRAINT [PK_DataCaptureActivities_2b28bd47] PRIMARY KEY ([Id])
ExecuteNonQuery==========
CREATE TABLE [MasterDataCaptureActivities] (
 [Id] int not null identity(1,1)
, [SomeOtherField] text null
, [Title] varchar(100) null
, [ActivityType] int not null
, [Description] text null
);
ALTER TABLE [MasterDataCaptureActivities] ADD CONSTRAINT [PK_MasterDataCaptureActivities_2b28bd47] PRIMARY KEY ([Id])

But in this case, if you want to enum all the ActivityBase you need to join them (Union) on the client.


问:
Apply a frame to an image
I have two images, one of them is like a frame (image that has a custom border and transparent background) and I have another image, I need to apply/merge these two images to show the second image with the frame.

I have seen different examples but I cannot find a solution.

Thanks!

答:
The easiest way to overlap components in WPF is simply have both items in a Grid, occupying the same 'cell' in the order you want them to display:

```<code><Grid>
    <Image Source="D:\photo.png"></Image>
    <Image Source="D:\frame.png"></Image>
</Grid>
</code>```

This will show them like this:

However, this is only overlaying them in the the UI of the application - if you want to, say, save/export these images its a different operation involving image processing/rendering. Although you could render the Grid component to an image.

Even if that's the ultimate goal, it could be more efficient to display them like the above while the user is 'picking' a frame, as it'll be fast an efficient - then properly process the image to render them together when the user presses the 'export' button.

Edit: To render two images into one, try using Graphics from System.Drawing:

```<code>using (Graphics g = Graphics.FromImage(photo))
{
    g.DrawImage(frame, x, y)
    g.Save();
}
photo.Save(...);
</code>```

Depends on your requirements.

Title: Apply a frame to an image

Body:
The easiest way to overlap components in WPF is simply have both items in a Grid, occupying the same 'cell' in the order you want them to display:

<Grid>
    <Image Source="D:\photo.png"></Image>
    <Image Source="D:\frame.png"></Image>
</Grid>

This will show them like this:

However, this is only overlaying them in the the UI of the application - if you want to, say, save/export these images its a different operation involving image processing/rendering. Although you could render the Grid component to an image.

Even if that's the ultimate goal, it could be more efficient to display them like the above while the user is 'picking' a frame, as it'll be fast an efficient - then properly process the image to render them together when the user presses the 'export' button.

Edit: To render two images into one, try using Graphics from System.Drawing:

using (Graphics g = Graphics.FromImage(photo))
{
    g.DrawImage(frame, x, y)
    g.Save();
}
photo.Save(...);

Depends on your requirements.


问:
Mortal Fibonacci Rabbits -error at values greater than 6
I try to count Mortal Fibonacci Rabbits. The task assumes that rabbits die out after a fixed number of months.

The picture shows how the number of rabbits changes over time Rabbits

The Fibonacci sequence for Mortal Rabbits looks like this:

{1,1,2,2,3,4,5,7,9,12,16,21,28 (...)}

My code is simple - unfortunately only counts to 6 (inclusive).

```<code>function rabbits(n){

if (n<=2){
    return 1
}
else if (n===3 || n===4){
    return 2
}
else {
    f1 = 1
    f2 = 1
    f3 = 2
    f4 = 2
        for (i = 5; i <= n; i++) {
            f = f2 + f3
            f3 = f2
            f2 = f
        }
        return f
    }
}

 console.log(rabbits(1)) // 1
console.log(rabbits(2))  //1
console.log(rabbits(3))  // 2
console.log(rabbits(4))  //2
console.log(rabbits(5))  //3
console.log(rabbits(6))  //4
console.log(rabbits(7))  //7
console.log(rabbits(8))  //11
console.log(rabbits(9))  //18
console.log(rabbits(10)) //29
</code>```

From 7 upwards - instead of F (n-2) + F (n-3) - counts F (n-1) + (F (n-2).

I have no idea why this is happening. Where is the error?

I'm just starting an adventure with JS and I'm afraid that complicated code I can not understand (what and why) - so I ask for advice / help modifying the existing one so that the beginner understands.

EDIT//

Okay, problem solved. This is a working code:

```<code>var Fib=[]

for(i=1;i<=n;i++){

if(i===1||i===2){

    Fib.push(1)
}

else if(i===3|| i===4){

    Fib.push(2)
}

else{

    fib=Fib[Fib.length-2]+Fib[Fib.length-3]
    Fib.push(fib)
}

}

console.log(Fib)
</code>```

答:
I'm not sure about the right forumla to get "Fibonacci numbers", I used that one from Wikipedia.

Anyway I think you could use an array in order to get the previous value, see following please:

function rabbits(n){
  let fib = [];
  for(let i=1; i<=15; i++){
    fib.push(i+i-1);
  }
  return fib[n-1];
}

for(let i=1; i<=10; i++){
  console.log("rabbits("+ i + ") = ", rabbits(i));
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span>From Wikipedia:</span>
<cite>
In mathematics, the Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence, and characterized by the fact that every number after the first two is the sum of the two preceding ones.
</cite></code>```

Body:
I try to count Mortal Fibonacci Rabbits. The task assumes that rabbits die out after a fixed number of months.

The picture shows how the number of rabbits changes over time Rabbits

The Fibonacci sequence for Mortal Rabbits looks like this:

{1,1,2,2,3,4,5,7,9,12,16,21,28 (...)}

My code is simple - unfortunately only counts to 6 (inclusive).

function rabbits(n){

if (n<=2){
    return 1
}
else if (n===3 || n===4){
    return 2
}
else {
    f1 = 1
    f2 = 1
    f3 = 2
    f4 = 2
        for (i = 5; i <= n; i++) {
            f = f2 + f3
            f3 = f2
            f2 = f
        }
        return f
    }
}

 console.log(rabbits(1)) // 1
console.log(rabbits(2))  //1
console.log(rabbits(3))  // 2
console.log(rabbits(4))  //2
console.log(rabbits(5))  //3
console.log(rabbits(6))  //4
console.log(rabbits(7))  //7
console.log(rabbits(8))  //11
console.log(rabbits(9))  //18
console.log(rabbits(10)) //29

From 7 upwards - instead of F (n-2) + F (n-3) - counts F (n-1) + (F (n-2).

I have no idea why this is happening. Where is the error?

I'm just starting an adventure with JS and I'm afraid that complicated code I can not understand (what and why) - so I ask for advice / help modifying the existing one so that the beginner understands.

EDIT//

Okay, problem solved. This is a working code:

var Fib=[]

for(i=1;i<=n;i++){

if(i===1||i===2){

    Fib.push(1)
}

else if(i===3|| i===4){

    Fib.push(2)
}

else{

    fib=Fib[Fib.length-2]+Fib[Fib.length-3]
    Fib.push(fib)
}

}

console.log(Fib)

Body:
I'm not sure about the right forumla to get "Fibonacci numbers", I used that one from Wikipedia.

Anyway I think you could use an array in order to get the previous value, see following please:

function rabbits(n){
  let fib = [];
  for(let i=1; i<=15; i++){
    fib.push(i+i-1);
  }
  return fib[n-1];
}

for(let i=1; i<=10; i++){
  console.log("rabbits("+ i + ") = ", rabbits(i));
}

<span>From Wikipedia:</span>
<cite>
In mathematics, the Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence, and characterized by the fact that every number after the first two is the sum of the two preceding ones.
</cite>


问:
Does assigning objects to null in Java impact garbage collection?
Does assigning an unused object reference to null in Java improve the garbage collection process in any measurable way?

My experience with Java (and C#) has taught me that is often counter intuitive to try and outsmart the virtual machine or JIT compiler, but I've seen co-workers use this method and I am curious if this is a good practice to pick up or one of those voodoo programming superstitions?

答:
It depends.

Generally speaking shorter you keep references to your objects, faster they'll get collected.

If your method takes say 2 seconds to execute and you don't need an object anymore after one second of method execution, it makes sense to clear any references to it. If GC sees that after one second, your object is still referenced, next time it might check it in a minute or so.

Anyway, setting all references to null by default is to me premature optimization and nobody should do it unless in specific rare cases where it measurably decreases memory consuption.

OwnerDisplayName: nemo

LastEditorDisplayName: nemo

OwnerDisplayName: lubos hasko

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: lubos hasko


问:
How does SSL use symmetric and asymmetric encryption? And how do I manage certificated for multiple sites on one host?
First, some quotation from Microsoft TechNet's Managing Microsoft Certificate Services and SSL:

To recap, secure SSL sessions are established using the following technique:

The user's Web browser contacts the server using a secure URL.

The IIS server sends the browser its public key and server certificate.

The client and server negotiate the level of encryption to use for the
  secure communications.

The client browser encrypts a session key with the server's public
  key and sends the encrypted data back
  to the server.

The IIS Server decrypts the message sent by the client using its private
  key, and the session is established.

Both the client and the server use the session key to encrypt and decrypt
  transmitted data.

So, basically speaking, the SSL use the asymmetric encryption (public/private key pair) to deliver the shared session key, and finally achieved a communication way with symmetric encryption.

Is this right?

Add - 1 - 5:55 PM 12/17/2010

I am using IIS to host my websites. Suppose I have multiple sites on my single machine, and I want the client brower to use SSL URL to connect my sites. How many certificates do I need? Which of the following approach should I take?

1 - Apply for a single certicate and associate it to my single server machine which hosts mutiple sites.

2 - Apply for several certificates and associate each of my sites with its own certificate.

In IIS7, it seems I could only do approach 1.

Update - 1 - 6:09 PM 12/17/2010

I figure it out. I could install mutiple certificates on my server machine and bind each site with seperate certificate as necessary.

答:
You can only have a single SSL cert  per listening port on the server.  This is because the very first thing that is sent is the server certificate (as in your timeline).  This is before the HTTP request so if you try to host two domains on a single server (say foo.com and bar.com) there is no way for the server to know which certificate to send to the client.

There are a few different ways to solve this problem:

Host different domains on different servers

Host different domains on different ports (eg. foo.com is serverd from 443 and bar.com is served from 8443).  If you put your host behind multiple load-balancers, you can have them service all the sites on 443.

If the different domains are all sub-domains of a single parent domain, you can get a wildcard certificate. (e.g. domains www.foo.com, bar.foo.com, and baz.foo.com can all use a certificate for *.foo.com)

Get a single certificate for one of the domains and have the other domains listed as AltNames.  (e.g. both foo.com and bar.com can use a foo.com certificate with a bar.com AltName)


问:
Ionic bar-header padding-top when status bar is hidden
I have a problem using the bar-header component of the ionic-framework. I always have a padding-top of a few pixels (see screenshot). I'm using the cordova plugin org.apache.cordova.statusbar to hide the status bar like this:

```<code>  if(window.StatusBar) {
    StatusBar.hide();
    StatusBar.overlaysWebView(false);
  }
</code>```

Any help will be highly appreciated.

答:
Overwrite these ionic css rules in your main.css. This fixed the problem for me:</p>

```<code>.platform-ios.platform-cordova:not(.fullscreen) .bar-header:not(.bar-subheader).item-input-inset .item-input-wrapper {
    margin-top: 0px !important;
}
.platform-ios.platform-cordova:not(.fullscreen) .bar-header:not(.bar-subheader) > * {
    margin-top: 0px;
}
</code>```

Body:
I have a problem using the bar-header component of the ionic-framework. I always have a padding-top of a few pixels (see screenshot). I'm using the cordova plugin org.apache.cordova.statusbar to hide the status bar like this:

  if(window.StatusBar) {
    StatusBar.hide();
    StatusBar.overlaysWebView(false);
  }

Any help will be highly appreciated.

Body:
Overwrite these ionic css rules in your main.css. This fixed the problem for me:

.platform-ios.platform-cordova:not(.fullscreen) .bar-header:not(.bar-subheader).item-input-inset .item-input-wrapper {
    margin-top: 0px !important;
}
.platform-ios.platform-cordova:not(.fullscreen) .bar-header:not(.bar-subheader) > * {
    margin-top: 0px;
}


问:
Getting rid of loops for appending character vector
I am super new to R but have some experience with coding in EViews. From the post I have been reading on this site, I understand that loops can usually be replaced by faster codes in R.
So, here's my question: I am trying to get a vector of characters in R. Each "character" will be a variable name made up of a country code and a variable.
So If I have two countries and three variables, I would need a vector of 2x3=6 characters.
This is code I came up with:

```<code>list_pgo=character(0)
for (y in allb){ ###concept code a b c
for (x in cty){ ###country code fr us
tempb <- paste(x,"pgo",y,"_id",sep="") ##variable name should be xpgoy_id
list_pgo<-append(list_pgo,tempb,after=length(list_pgo)) ### result should be something like frpgoa_id uspgoa_id frpgob_id uspgob_id frpgoc_id uspgoc_id
}
}
</code>```

Thanks a lot in advance for your help

答:
The following should do what you want. Many functions in R are already vectorised (such as paste), meaning that they accept vectors and perform element-wise operations with R's usual reuse/repeat rules if the vector lengths do not match.

```<code># Define your toy data (as character vectors)
allb <- c("a", "b", "c")
cty <- c("fr", "us")

# Get all combinations
all.comb <- expand.grid(x = allb, y = cty)

# Combine columns of generated matrix
list_pgo <- paste0(all.comb$x, "pgo", all.comb$y, "_id")
print(list_pgo)
#[1] "apgofr_id" "bpgofr_id" "cpgofr_id" "apgous_id" "bpgous_id" "cpgous_id"
</code>```

Edit: Other ways and methods of course exists, but functions that already are vectorised are often much faster than the apply-family of functions that can be considered to be "loop-hiding" only.

Comparing the above to the one-liner in the comments:

```<code>library("microbenchmark")

fun1 <-function() {
  all.comb <- expand.grid(x = allb, y= cty)
  paste0(all.comb$x,"pgo",all.comb$y,"_id")
}

fun2 <- function() {
  apply(expand.grid(allb,cty), 1, function(x) paste(x[1],"pgo",x[2],"_id",sep=""))
}

microbenchmark(fun1(), fun2())
#Unit: microseconds
#   expr    min       lq     mean   median      uq      max neval
# fun1()  88.80 136.7705 185.3204 150.1570 163.098 3722.469   100
# fun2() 246.32 286.9275 353.2598 305.8925 326.419 4920.156   100
</code>```

Body:
I am super new to R but have some experience with coding in EViews. From the post I have been reading on this site, I understand that loops can usually be replaced by faster codes in R.
So, here's my question: I am trying to get a vector of characters in R. Each "character" will be a variable name made up of a country code and a variable.
So If I have two countries and three variables, I would need a vector of 2x3=6 characters.
This is code I came up with:

list_pgo=character(0)
for (y in allb){ ###concept code a b c
for (x in cty){ ###country code fr us
tempb <- paste(x,"pgo",y,"_id",sep="") ##variable name should be xpgoy_id
list_pgo<-append(list_pgo,tempb,after=length(list_pgo)) ### result should be something like frpgoa_id uspgoa_id frpgob_id uspgob_id frpgoc_id uspgoc_id
}
}

Thanks a lot in advance for your help

Body:
The following should do what you want. Many functions in R are already vectorised (such as paste), meaning that they accept vectors and perform element-wise operations with R's usual reuse/repeat rules if the vector lengths do not match.

# Define your toy data (as character vectors)
allb <- c("a", "b", "c")
cty <- c("fr", "us")

# Get all combinations
all.comb <- expand.grid(x = allb, y = cty)

# Combine columns of generated matrix
list_pgo <- paste0(all.comb$x, "pgo", all.comb$y, "_id")
print(list_pgo)
#[1] "apgofr_id" "bpgofr_id" "cpgofr_id" "apgous_id" "bpgous_id" "cpgous_id"

Edit: Other ways and methods of course exists, but functions that already are vectorised are often much faster than the apply-family of functions that can be considered to be "loop-hiding" only.

Comparing the above to the one-liner in the comments:

library("microbenchmark")

fun1 <-function() {
  all.comb <- expand.grid(x = allb, y= cty)
  paste0(all.comb$x,"pgo",all.comb$y,"_id")
}

fun2 <- function() {
  apply(expand.grid(allb,cty), 1, function(x) paste(x[1],"pgo",x[2],"_id",sep=""))
}

microbenchmark(fun1(), fun2())
#Unit: microseconds
#   expr    min       lq     mean   median      uq      max neval
# fun1()  88.80 136.7705 185.3204 150.1570 163.098 3722.469   100
# fun2() 246.32 286.9275 353.2598 305.8925 326.419 4920.156   100


问:
Regex Pattern Matching until the first whitespace before the first series of characters containing a specific character
Consider the following string:

```<code>ab cd ef gh/
</code>```

How would I extract ab cd ef?

I would like to be able to match until the first whitespace before the first series containing a specific character, which in the case above is /.

EDIT: I'm trying to set a config file to parse some logs into Logstash, so I was wondering whether it was possible to do this just with regex rules.

答:
```<code>([^\/]+)\s+[^\/]*\/
</code>```

Explanation:

```<code>(      start of Subpattern
[^\/]+ match one or more Elements that are no /.
       ^ is the Negation-Operator
       / needs to be escaped.
       + stands for one or more
)      end of Subpattern
\s+    match one or more Whitespaces
[^\/]* match no or any amount of Characters that are not a /
       * stands for Zero or any Amount
\/     match /
</code>```

The content of the Subpattern returns the Match.

Example:

```<code>preg_match('/([^\/]+)\s+[^\/]*\//', $input, $result);

print_r($result);
</code>```

Body:
Consider the following string:

ab cd ef gh/

How would I extract ab cd ef?

I would like to be able to match until the first whitespace before the first series containing a specific character, which in the case above is /.

EDIT: I'm trying to set a config file to parse some logs into Logstash, so I was wondering whether it was possible to do this just with regex rules.

Body:
([^\/]+)\s+[^\/]*\/

Explanation:

(      start of Subpattern
[^\/]+ match one or more Elements that are no /.
       ^ is the Negation-Operator
       / needs to be escaped.
       + stands for one or more
)      end of Subpattern
\s+    match one or more Whitespaces
[^\/]* match no or any amount of Characters that are not a /
       * stands for Zero or any Amount
\/     match /

The content of the Subpattern returns the Match.

Example:

preg_match('/([^\/]+)\s+[^\/]*\//', $input, $result);

print_r($result);


问:
When would a do-while loop be the better than a while-loop?
This is a highly subjective question, so I'll be more specific. Is there any time that a do-while loop would be a better style of coding than a normal while-loop?

e.g.

```<code>int count = 0;
do {
   System.out.println("Welcome to Java");
   count++;
} while (count < 10);`
</code>```

It doesn't seem to make sense to me to check the while condition after evaluating the do-statement (aka forcing the do statement to run at least once).

For something simple like my above example, I would imagine that:

```<code>int count = 0;
while(count < 10) {
   System.out.println("Welcome to Java"); count++;
}
</code>```

would be generally considered to have been written in a better writing style.

Can anyone provide me a working example of when a do-while loop would be considered the only/best option? Do you have a do-while loop in your code? What role does it play and why did you opt for the do-while loop?

(I've got an inkling feeling that the do-while loop may be of use in coding games. Correct me, game developers, if I am wrong!)

答:
/*
while loop

5 bucks

1 chocolate = 1 bucks

```<code>while my money is greater than 1 bucks
  select chocolate
  pay 1 bucks to the shopkeeper
  money = money - 1
end
</code>```

come to home and cant go to while shop because my money = 0 bucks
*/

```<code>#include<stdio.h>
int main(){
  int money = 5;

  while( money >= 1){
    printf("inside the shopk and selecting chocolate\n");
    printf("after selecting chocolate paying 1 bucks\n");
    money = money - 1 ;
    printf("my remaining moeny = %d\n", money);
    printf("\n\n");
  }

  printf("dont have money cant go inside the shop, money = %d",  money);

  return 0;
}
</code>```

infinite money

```<code>while( codition ){ // condition will always true ....infinite loop
  statement(s)
}
</code>```

please visit this video for better understanding
https://www.youtube.com/watch?v=eqDv2wxDMJ8&t=25s

Body:
This is a highly subjective question, so I'll be more specific. Is there any time that a do-while loop would be a better style of coding than a normal while-loop?

e.g.

int count = 0;
do {
   System.out.println("Welcome to Java");
   count++;
} while (count < 10);`

It doesn't seem to make sense to me to check the while condition after evaluating the do-statement (aka forcing the do statement to run at least once).

For something simple like my above example, I would imagine that:

int count = 0;
while(count < 10) {
   System.out.println("Welcome to Java"); count++;
}

would be generally considered to have been written in a better writing style.

Can anyone provide me a working example of when a do-while loop would be considered the only/best option? Do you have a do-while loop in your code? What role does it play and why did you opt for the do-while loop?

(I've got an inkling feeling that the do-while loop may be of use in coding games. Correct me, game developers, if I am wrong!)

Body:
/*
while loop

5 bucks

1 chocolate = 1 bucks

while my money is greater than 1 bucks
  select chocolate
  pay 1 bucks to the shopkeeper
  money = money - 1
end

come to home and cant go to while shop because my money = 0 bucks
*/

#include<stdio.h>
int main(){
  int money = 5;

  while( money >= 1){
    printf("inside the shopk and selecting chocolate\n");
    printf("after selecting chocolate paying 1 bucks\n");
    money = money - 1 ;
    printf("my remaining moeny = %d\n", money);
    printf("\n\n");
  }

  printf("dont have money cant go inside the shop, money = %d",  money);

  return 0;
}

infinite money

while( codition ){ // condition will always true ....infinite loop
  statement(s)
}

please visit this video for better understanding
https://www.youtube.com/watch?v=eqDv2wxDMJ8&t=25s


问:
Can Birt be used on a none Java web application?
I am currently doing a research about reporting tools and particulary focusing on Birt only I have noticed that it is ment for Java web applications, I can't find enough resources on Birt integration with other technologies such as .Net or Nodejs, does any body have links or resources in which I can see an example of how to integrate Birt in web applications other than Java ?

答: You can use the REST or JavaScriptAPI as mentioned before to display where you want. You can use JavaComponents or the BIRT runtime to generate HTML that can also be displayed using your preferred server. The engines require Java but you can decide how to interact with the engines or how to serve the content.</p>


问:
symfony doesn't like PostgreSQL with doctrine:build-schema
I'm having a weird thing happen when I run doctrine:build-schema with my PostgreSQL database. It should just work, of course, but instead I'm getting this:

```<code>jason@ve:~/salon$ ./symfony doctrine:build-schema
>> doctrine  generating yaml schema from database

  SQLSTATE[42P01]: Undefined table: 7 ERROR:  missing FROM-clause entry for table "t"
  LINE 6: ...                                                  t.typtype ...
                                                               ^. Failing Query: "
SELECT
ordinal_position as attnum,
column_name as field,
udt_name as type,
data_type as complete_type,
t.typtype AS typtype,
is_nullable as isnotnull,
column_default as default,
(
  SELECT 't'
  FROM pg_index, pg_attribute a, pg_class c, pg_type t
  WHERE c.relname = table_name AND a.attname = column_name
  AND a.attnum > 0 AND a.attrelid = c.oid AND a.atttypid = t.oid
  AND c.oid = pg_index.indrelid AND a.attnum = ANY (pg_index.indkey)
  AND pg_index.indisprimary = 't'
  AND format_type(a.atttypid, a.atttypmod) NOT LIKE 'information_schema%'
) as pri,
character_maximum_length as length
FROM information_schema.COLUMNS
WHERE table_name = 'salon'
ORDER BY ordinal_position"
</code>```

Any idea why this is happening?

The crappy part is that even if I can fix the SQL query, the real problem is that symfony/Doctrine is not working as expected. Doctrine claims to support PostgreSQL it appears that other people are using PostgreSQL with build-schema without problems, so this is weird.

I'm on symfony 1.4.8 and Doctrine 1.2.

答: The t.typtype clause doesn't make any sense there.  The query is broken in that regard.  You should report this to the authors.

Body:
I'm having a weird thing happen when I run doctrine:build-schema with my PostgreSQL database. It should just work, of course, but instead I'm getting this:

jason@ve:~/salon$ ./symfony doctrine:build-schema
>> doctrine  generating yaml schema from database

  SQLSTATE[42P01]: Undefined table: 7 ERROR:  missing FROM-clause entry for table "t"
  LINE 6: ...                                                  t.typtype ...
                                                               ^. Failing Query: "
SELECT
ordinal_position as attnum,
column_name as field,
udt_name as type,
data_type as complete_type,
t.typtype AS typtype,
is_nullable as isnotnull,
column_default as default,
(
  SELECT 't'
  FROM pg_index, pg_attribute a, pg_class c, pg_type t
  WHERE c.relname = table_name AND a.attname = column_name
  AND a.attnum > 0 AND a.attrelid = c.oid AND a.atttypid = t.oid
  AND c.oid = pg_index.indrelid AND a.attnum = ANY (pg_index.indkey)
  AND pg_index.indisprimary = 't'
  AND format_type(a.atttypid, a.atttypmod) NOT LIKE 'information_schema%'
) as pri,
character_maximum_length as length
FROM information_schema.COLUMNS
WHERE table_name = 'salon'
ORDER BY ordinal_position"

Any idea why this is happening?

The crappy part is that even if I can fix the SQL query, the real problem is that symfony/Doctrine is not working as expected. Doctrine claims to support PostgreSQL it appears that other people are using PostgreSQL with build-schema without problems, so this is weird.

I'm on symfony 1.4.8 and Doctrine 1.2.


问:
search data in elastic search based on some fields
I am new to EL and want to search on this data based on "type:": "load".

Please help

```<code>    {
   "took": 14,
   "timed_out": false,
   "_shards": {
      "total": 5,
      "successful": 5,
      "failed": 0
   },
   "hits": {
      "total": 1109,
      "max_score": 1,
      "hits": [
         {"_index": "4",
            "_type": "aa",
            "_id": "xx",
            "_score": 1,
            "_source": {
               "useRange": false,
               "Blueprint": 4,
               "standardDeviation": 0,
               "occurrences": 0,
               "type:": "load",
               }...
               {
               }
</code>```

答:
Elasticsearch Documentation will help you:
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html

EDIT

Query is curl -XGET 'localhost:9200/sample/_search?q=type:load&pretty'

and Output will be

```<code>{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 1,
    "max_score" : 0.30685282,
    "hits" : [ {
      "_index" : "sample",
      "_type" : "data",
      "_id" : "1",
      "_score" : 0.30685282,
      "_source" : {
        "useRange" : false,
        "Blueprint" : 4,
        "standardDeviation" : 0,
        "occurrences" : 0,
        "type" : "load"
      }
    } ]
  }
}
</code>```

Body:
I am new to EL and want to search on this data based on "type:": "load".

Please help

    {
   "took": 14,
   "timed_out": false,
   "_shards": {
      "total": 5,
      "successful": 5,
      "failed": 0
   },
   "hits": {
      "total": 1109,
      "max_score": 1,
      "hits": [
         {"_index": "4",
            "_type": "aa",
            "_id": "xx",
            "_score": 1,
            "_source": {
               "useRange": false,
               "Blueprint": 4,
               "standardDeviation": 0,
               "occurrences": 0,
               "type:": "load",
               }...
               {
               }

Body:
Elasticsearch Documentation will help you:
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html

EDIT

Query is curl -XGET 'localhost:9200/sample/_search?q=type:load&pretty'

and Output will be

{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 1,
    "max_score" : 0.30685282,
    "hits" : [ {
      "_index" : "sample",
      "_type" : "data",
      "_id" : "1",
      "_score" : 0.30685282,
      "_source" : {
        "useRange" : false,
        "Blueprint" : 4,
        "standardDeviation" : 0,
        "occurrences" : 0,
        "type" : "load"
      }
    } ]
  }
}


问:
Limit this PHP foreach statement to just 5 loops
How could I limit this foraech statement to just 5 loops? I think I should just use Break but I'm not sure where to put it. </p>

```<code> <?php if(!empty($locations)): foreach($locations as $location):  ?>
<?php if(empty($location["title"])) continue; ?>
<li>
    <a href="<?php esc_attr_e($url.$glue.http_build_query($location["query"])) ?>">
        <?php esc_html_e($location["title"]) ?>
    </a>
    <?php if($param->count): ?>
    <div class="wpjb-widget-item-count">
        <div class="wpjb-widget-item-num"><?php echo intval($location["count"]) ?></div>
    </div>
    <?php endif; ?>
</li>
<?php endforeach; ?>
</code>```

答:
You can use for():</p>

```<code><?php if(!empty($locations)):
for($i=0; $i<5; $i++) {
    $location = $locations[$i];
    <?php if(empty($locations["title"])) continue; ?>
        <li>
            <a href="<?php esc_attr_e($url.$glue.http_build_query($location["query"])) ?>">
                <?php esc_html_e($location["title"]) ?>
            </a>
            <?php if($param->count): ?>
            <div class="wpjb-widget-item-count">
                <div class="wpjb-widget-item-num"><?php echo intval($location["count"]) ?></div>
            </div>
            <?php endif; ?>
        </li>
}
</code>```

Body:
How could I limit this foraech statement to just 5 loops? I think I should just use Break but I'm not sure where to put it.

 <?php if(!empty($locations)): foreach($locations as $location):  ?>
<?php if(empty($location["title"])) continue; ?>

    <a href="<?php esc_attr_e($url.$glue.http_build_query($location["query"])) ?>">
        <?php esc_html_e($location["title"]) ?>

    <?php if($param->count): ?>

<?php echo intval($location["count"]) ?>

    <?php endif; ?>

<?php endforeach; ?>

Body:
You can use for():

<?php if(!empty($locations)):
for($i=0; $i<5; $i++) {
    $location = $locations[$i];
    <?php if(empty($locations["title"])) continue; ?>
        <li>
            <a href="<?php esc_attr_e($url.$glue.http_build_query($location["query"])) ?>">
                <?php esc_html_e($location["title"]) ?>
            </a>
            <?php if($param->count): ?>
            <div class="wpjb-widget-item-count">
                <div class="wpjb-widget-item-num"><?php echo intval($location["count"]) ?></div>
            </div>
            <?php endif; ?>
        </li>
}


问:
SQL query to fetch rows from one table which are not present in other 3 tables
I have 4 tables,

A, B , C , D

A has column Aid,
B has column Aid,
C has column Aid,
D has column Aid

(Aid is common column in all the 4 tables)

now i want to fetch rows from A table which are not present in B or C or D
can anyone please let me know the SQL query for this.

答:
Use NOT IN operator

```<code>Select * from A
Where Aid not in (
  Select Aid from B
  Union all
  Select Aid from C
  Union all
  Select Aid from D
)
</code>```

ert that.. If aid is null in table A, but B,C & D don't have null,
  null won't be returned. Left join is superior in that case... – JGFMK
  43 mins ago

If table A contains NULL in aid column, then left join query will always return that row regardless of there will go NULL in other tables or not. Please examine this simple test case http://rextester.com/ESZWH45744

Body:
Use NOT IN operator

Select * from A
Where Aid not in (
  Select Aid from B
  Union all
  Select Aid from C
  Union all
  Select Aid from D
)

ert that.. If aid is null in table A, but B,C & D don't have null,
  null won't be returned. Left join is superior in that case... – JGFMK
  43 mins ago

If table A contains NULL in aid column, then left join query will always return that row regardless of there will go NULL in other tables or not. Please examine this simple test case http://rextester.com/ESZWH45744


问:
How to make use of a hypothesis containing forall in Coq?
I am trying to prove the equivalence of P \/ Q and ~ P -> Q, under the assumption of Excluded Middle,

```<code>Theorem eq_of_or :
  excluded_middle ->
  forall P Q : Prop,
    (P \/ Q) <-> (~ P -> Q).
</code>```

where the Excluded Middle is the following.

```<code>Definition excluded_middle := forall P : Prop, P \/ ~ P.
</code>```

Actually, the proof of one direction does not require the Excluded Middle. In my attempt at proving the other direction, I get stuck when I am trying to utilize the Excluded Middle among the hypotheses,

```<code>Proof.
  intros EM P Q. split.
  { intros [H | H]. intros HNP.
    - unfold not in HNP. exfalso.
      apply HNP. apply H.
    - intros HNP. apply H. }
  { intros H. unfold excluded_middle in EM.
    unfold not in EM. unfold not in H.
  }
</code>```

where the current environment is the following:

```<code>1 subgoal
EM : forall P : Prop, P \/ (P -> False)
P, Q : Prop
H : (P -> False) -> Q
______________________________________(1/1)
P \/ Q
</code>```

I understand that under such circumstance, what we need to do next is to do something like the "case analysis" of P, including the use of tactics left and right, if my proof makes sense till now.

Thanks in advance for any advice and suggestion!

答:
You can instantiate EM : forall P : Prop, P \/ ~ P with any proposition (I instantiated it with P below and destructed it immediately), since
EM is essentially a function that takes an arbitrary proposition P and returns a proof of either P or ~ P.

```<code>Theorem eq_of_or' :
  excluded_middle ->
  forall P Q : Prop, (~ P -> Q) -> P \/ Q.
Proof.
  intros EM P Q.
  destruct (EM P) as [p | np].     (* <- the key part is here *)
  - left. apply p.
  - right.
    apply (H np).
    (* or, equivalently, *)
    Undo.
    apply H.
    apply np.
    Undo 2.
    (* we can also combine two `apply` into one: *)
    apply H, np.
Qed.
</code>```

Body:
I am trying to prove the equivalence of P \/ Q and ~ P -> Q, under the assumption of Excluded Middle,

Theorem eq_of_or :
  excluded_middle ->
  forall P Q : Prop,
    (P \/ Q) <-> (~ P -> Q).

where the Excluded Middle is the following.

Definition excluded_middle := forall P : Prop, P \/ ~ P.

Actually, the proof of one direction does not require the Excluded Middle. In my attempt at proving the other direction, I get stuck when I am trying to utilize the Excluded Middle among the hypotheses,

Proof.
  intros EM P Q. split.
  { intros [H | H]. intros HNP.
    - unfold not in HNP. exfalso.
      apply HNP. apply H.
    - intros HNP. apply H. }
  { intros H. unfold excluded_middle in EM.
    unfold not in EM. unfold not in H.
  }

where the current environment is the following:

1 subgoal
EM : forall P : Prop, P \/ (P -> False)
P, Q : Prop
H : (P -> False) -> Q
______________________________________(1/1)
P \/ Q

I understand that under such circumstance, what we need to do next is to do something like the "case analysis" of P, including the use of tactics left and right, if my proof makes sense till now.

Thanks in advance for any advice and suggestion!

Body:
You can instantiate EM : forall P : Prop, P \/ ~ P with any proposition (I instantiated it with P below and destructed it immediately), since
EM is essentially a function that takes an arbitrary proposition P and returns a proof of either P or ~ P.

Theorem eq_of_or' :
  excluded_middle ->
  forall P Q : Prop, (~ P -> Q) -> P \/ Q.
Proof.
  intros EM P Q.
  destruct (EM P) as [p | np].     (* <- the key part is here *)
  - left. apply p.
  - right.
    apply (H np).
    (* or, equivalently, *)
    Undo.
    apply H.
    apply np.
    Undo 2.
    (* we can also combine two `apply` into one: *)
    apply H, np.
Qed.


问:
forms appear poorly scaled at runtime
I have created a form in visual studio (vb.net winforms) and it looks great in designer however at runtime it appears extremely out of scale (on my computer only) - my computer is using resolution of 3840x2160 with DPI scaling of 250% - this is obviously the problem how do I make my application deal with this better?

I have tried using Autoscalemode, autosize, and autosizemode with the form only appearing more broken than it currently does.

Here is the appearance in designer:

Here is the appearance at runtime on my computer:

答: Make sure that you didn't change the default anchor property of the tools. Also make sure that you don't change location or size of the tools at runtime.</p>

Title: forms appear poorly scaled at runtime


问:
Using Slice Pipe with variable parameters in *ngFor
Using the Angular2 pipe slice I can do something like this to only show the first five elements of my items.

```<code><ion-item *ngFor='let item of items | slice:0:5">
</code>```

How can I use variables instead of hardcoding 0 and 5? I want to do something like this and define start and end in my *.ts file.

```<code><ion-item *ngFor='let item of items | slice:"start":"end"'>
</code>```

答:
Just remove "(double quotes) from the start and end variable

```<code><ion-item *ngFor='let item of items | slice:start:end'>
</code>```

Body:
Using the Angular2 pipe slice I can do something like this to only show the first five elements of my items.

<ion-item *ngFor='let item of items | slice:0:5">

How can I use variables instead of hardcoding 0 and 5? I want to do something like this and define start and end in my *.ts file.

<ion-item *ngFor='let item of items | slice:"start":"end"'>

Body:
Just remove "(double quotes) from the start and end variable

<ion-item *ngFor='let item of items | slice:start:end'>


问:
Summernote set default font size and font
I'm using last version  summernote library. How i can set default font size and font?
I'm trying like this, but its not working:

```<code> $('.text-editor').summernote({
        toolbar: [
            ['style', ['style']],
            ['font', ['bold', 'italic', 'underline', 'superscript', 'subscript', 'strikethrough', 'clear']],
            ['fontname', ['fontname']],
            ['fontsize', ['fontsize']],
            ['color', ['color']],
            ['para', ['ul', 'ol', 'paragraph']],
            ['height', ['height']],
            ['table', ['table']],
            ['insert', ['link', 'picture', 'video', 'hr']],
            ['view', ['codeview']]
        ],
        fontsize: '16'
    });
</code>```

https://jsfiddle.net/dtgr5q29/142/

答:
A possible solution to this is to apply directly the font-size style to the editor div using jQuery

```<code>$('.active-textcontainer').summernote({
    toolbar: [
        ['style', ['bold', 'italic', 'underline']],
        ['fontsize', ['fontsize']],
        ['color', ['color']],
        ['para', ['ul', 'ol', 'paragraph']]
    ],
     height:150
});

$('.note-editable').css('font-size','18px');
</code>```

More .. How to set font-size in summernote?

Thanks

Body:
I'm using last version  summernote library. How i can set default font size and font?
I'm trying like this, but its not working:

 $('.text-editor').summernote({
        toolbar: [
            ['style', ['style']],
            ['font', ['bold', 'italic', 'underline', 'superscript', 'subscript', 'strikethrough', 'clear']],
            ['fontname', ['fontname']],
            ['fontsize', ['fontsize']],
            ['color', ['color']],
            ['para', ['ul', 'ol', 'paragraph']],
            ['height', ['height']],
            ['table', ['table']],
            ['insert', ['link', 'picture', 'video', 'hr']],
            ['view', ['codeview']]
        ],
        fontsize: '16'
    });

https://jsfiddle.net/dtgr5q29/142/

Body:
A possible solution to this is to apply directly the font-size style to the editor div using jQuery

$('.active-textcontainer').summernote({
    toolbar: [
        ['style', ['bold', 'italic', 'underline']],
        ['fontsize', ['fontsize']],
        ['color', ['color']],
        ['para', ['ul', 'ol', 'paragraph']]
    ],
     height:150
});

$('.note-editable').css('font-size','18px');

More .. How to set font-size in summernote?

Thanks


问:
Laravel Blades - Assign JS variable to PHP variable
Is it possible to assign javascript variable to php variable?

Defined:
{{ $var }} and @{{ jsVar }}

I'd like to something like this (this example not working): {{ $var = jsVar }}.

This is needed to pass the parameter to e.g. generate named routes. I can't do something like that route('user', ['id' => jsVar])

答: I usually use like this, in order to send some variable to js function myCustomFunction({{$laravel_var}})


问:
Could not install : Newtonsoft.Json
I want to download and parse the JSON in my Windows Phone project, so I decided to download newtonsoft.json library via Nuget in Visual Studios, but I'm receiving the following:

```<code>PM> Install-Package Newtonsoft.Json
Successfully installed 'Newtonsoft.Json 6.0.1'.
Successfully uninstalled 'Newtonsoft.Json 6.0.1'.
Install failed. Rolling back...

Install-Package : Could not install package 'Newtonsoft.Json 6.0.1'. You are trying to install this package into a project that targets 'WindowsPhone,Version=v8.0', but the package does not
contain any assembly references that are compatible with that framework. For more information, contact the package author.
At line:1 char:1
 + Install-Package Newtonsoft.Json
 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 + CategoryInfo          : NotSpecified: (:) [Install-Package], InvalidOperationException
 + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand
</code>```

答: This is most likely caused by the source package being incorrect, please see my answer on this question Package error question</p>

Title: Could not install : Newtonsoft.Json

Body:
I want to download and parse the JSON in my Windows Phone project, so I decided to download newtonsoft.json library via Nuget in Visual Studios, but I'm receiving the following:

PM> Install-Package Newtonsoft.Json
Successfully installed 'Newtonsoft.Json 6.0.1'.
Successfully uninstalled 'Newtonsoft.Json 6.0.1'.
Install failed. Rolling back...

Install-Package : Could not install package 'Newtonsoft.Json 6.0.1'. You are trying to install this package into a project that targets 'WindowsPhone,Version=v8.0', but the package does not
contain any assembly references that are compatible with that framework. For more information, contact the package author.
At line:1 char:1
 + Install-Package Newtonsoft.Json
 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 + CategoryInfo          : NotSpecified: (:) [Install-Package], InvalidOperationException
 + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand


问:
Determine when image finished loading with JavaScript or jQuery:
How can I detect with JavaScript or jQuery when an image has finished loading, be it from the server or the browser cache?
I want to load various images in the same  tag and detect when the loading of a new images has finished.

答:
The onload document's event will fire only after all the elements, images included, have fully loaded.

The onload 's event will fire after the single image have fully loaded.

So you can attach a listener to these events, using jQuery objects or DOM's addEventListener (and IE's attachEvent)

ContentLicense: CC BY-SA 4.0

Body:
The onload document's event will fire only after all the elements, images included, have fully loaded.

The onload <img>'s event will fire after the single image have fully loaded.

So you can attach a listener to these events, using jQuery objects or DOM's addEventListener (and IE's attachEvent)


问:
Ant - copy only file not directory
I need to copy all files in a folder except directory in that folder using Ant script.

Im using below script to do that.

```<code><copy todir="targetsir">
  <fileset dir="srcdir">
     <include name="**/*.*"/>
  </fileset>
</copy>
</code>```

But it copies all files and directory in that folder.

how to restrict/filter directory in that folder?

thanks,

答:
If your folder has many subdirectories and you don't want them to be copied (if you want only files) try this..</p>

```<code><target name="copy">
<copy todir="out" flatten="true">
<fileset dir="tn">
<filename name="**/cit.txt" />
</fileset>
</copy>
</target>
</code>```

Title: Ant - copy only file not directory

Body:
I need to copy all files in a folder except directory in that folder using Ant script.

Im using below script to do that.

<copy todir="targetsir">
  <fileset dir="srcdir">
     <include name="**/*.*"/>
  </fileset>
</copy>

But it copies all files and directory in that folder.

how to restrict/filter directory in that folder?

thanks,

Body:
If your folder has many subdirectories and you don't want them to be copied (if you want only files) try this..

<target name="copy">
<copy todir="out" flatten="true">
<fileset dir="tn">
<filename name="**/cit.txt" />
</fileset>
</copy>
</target>


问:
pyparsing partial match or recursion limit hit
Using pyparsing, I seem to be having trouble understanding why my grammar either matches partially or hits a recursion limit.

```<code>lparens = Suppress("(")
rparens = Suppress(")")
name = Word(alphanums, exact=1)
expression = Forward()
function = Group(Literal("λ") + OneOrMore(name) + Literal(".").suppress() + expression)
application = Group(expression + expression) #<-- the problem *I think*
exp1 = ( name | function | application )
exp2 = (lparens + exp1 + rparens) | exp1
expression << exp2
</code>```

So the following will parse but only picks up the "a" and does not apply the application step:

```<code>expression.parseString("ab") #result is: (['a'], {})
expression.parseString("(ab)") #result is: exception - recursion limit reached.
</code>```

In the first example why did it stop at 'a' and not apply the application step and run into the same infinite look it does in the second example?

In the second example it matches '(' and so it needs the ')' to finish the exp1. So it should parse the name 'a' and since there is no following ')' it should abandon that and try function (which fails) and then move on to application. Then it parses name 'a' (first match) and should move on to name 'b' completing the name, the application, and then match ')' to complete the exp1 and the expression.

Obviously this is not what happens.

edit: forgot to add the following works:

```<code>expression.parseString("((λa.a)(λa.a))")
</code>```

` #result: ([([(['λ', 'a', 'a'], {}), (['λ', 'a', 'a'], {})], {})], {})

adding setDebug() and setName() to the various elements and parsing '(ab)' yields:

```<code>Match expression at loc 0(1,1)
Match exp2 at loc 0(1,1)
Match lparens at loc 0(1,1)
Matched lparens -> []
Match exp1 at loc 1(1,2)
Match name at loc 1(1,2)
Matched name -> ['a']
Matched exp1 -> ['a']
Match rparens at loc 2(1,3)
Exception raised:Expected ")" (at char 2), (line:1, col:3)
Match name at loc 0(1,1)
Exception raised:Expected name (at char 0), (line:1, col:1)
Match function at loc 0(1,1)
Exception raised:Expected "λ" (at char 0), (line:1, col:1)
Match application at loc 0(1,1)
Match expression at loc 0(1,1)
Match exp2 at loc 0(1,1)
Match lparens at loc 0(1,1)
Matched lparens -> []
Match exp1 at loc 1(1,2)
Match name at loc 1(1,2)
Matched name -> ['a']
Matched exp1 -> ['a']
Match rparens at loc 2(1,3)
Exception raised:Expected ")" (at char 2), (line:1, col:3)
Match name at loc 0(1,1)
Exception raised:Expected name (at char 0), (line:1, col:1)
Match function at loc 0(1,1)
Exception raised:Expected "λ" (at char 0), (line:1, col:1)
Match application at loc 0(1,1)
Match expression at loc 0(1,1)
Match exp2 at loc 0(1,1)
Match lparens at loc 0(1,1)
Matched lparens -> []
Match exp1 at loc 1(1,2)
Match name at loc 1(1,2)
... etc etc etc...
</code>```

答:
I struggled with your question, as I did not really have a good grasp of just what you were trying to parse. Fortunately, the lambda character in your function definition was enough of a tip-off that I searched for some background on lambda calculus notation, and found a decent description here: http://palmstroem.blogspot.com/2012/05/lambda-calculus-for-absolute-dummies.html

From this I came up with a simple BNF:

```<code>expr ::= (name | function | '(' expr ')')+
function ::= 'λ' name+ '.' expr
name ::= a single character 'a'..'z' or 'A'..'Z'
</code>```

Translating to pyparsing from here looks like:

```<code>lparens = Suppress("(")
rparens = Suppress(")")
dot = Suppress('.')
# work around output encoding issues by displaying as '^'
λ = Literal('λ').setParseAction(replaceWith('^'))

# Forward() placeholder for recursive expression
expression = Forward()

# implement BNF bottom-up
name = oneOf(list(alphas))
function = Group(λ + Group(OneOrMore(name))("head") + dot + expression("body"))
lambda_term = name | function | lparens + expression + rparens
expression <<= Group(OneOrMore(lambda_term))
</code>```

This parses your sample expression as:

```<code>((λa.a)(λa.a))
[[[[['^', ['a'], ['a']]], [['^', ['a'], ['a']]]]]]
</code>```

This seems like a lot of extra nesting to wade through. We can reduce some of it by tweaking expression slightly, to Group only if there are 2 or more expressions, otherwise parse a single ungrouped expression. The tuple multiplication feature lets us define this as:

```<code>expression <<= Group(lambda_term*(2,)) | lambda_term
</code>```

Giving:

```<code>[[['^', ['a'], 'a'], ['^', ['a'], 'a']]]
</code>```

Or more clearly:

```<code>[
    [
        ['^', ['a'], 'a'],
        ['^', ['a'], 'a']
    ]
]
</code>```

In your posted parser, you also had a concept of "application". I speculate that what you call an application is what the cited article-for-dummies refers to as "resolving". To resolve a function, you take subsequent expressions one-for-one with each name in the function head, and replace the name in the body with its respective expression. I tried to comprehend this at parse time, but struggled with expressions where the function was nested within other functions, or the head and body were defined in nested parentheses, with the replacement expressions separated from the function by several nesting levels. I came to the conclusion that resolution has to be done after parsing of names and functions is complete. The structure that pyparsing imparts to the results should make it straightforward to walk the results and successively resolve names with expressions.

Here is the complete parser code:

```<code>"""
(from http://palmstroem.blogspot.com/2012/05/lambda-calculus-for-absolute-dummies.html)

BNF:
  expr ::= (name | function | '(' expr ')')+
  name ::= ['a'..'z' 'A'..'Z']+
  function ::= lambda name+ '.' expr
"""

lparens = Suppress("(")
rparens = Suppress(")")
dot = Suppress('.')
# work around output encoding issues by displaying as '^'
λ = Literal('λ').setParseAction(replaceWith('^'))

# Forward() placeholder for recursive expression
expression = Forward()

# implement BNF bottom-up
name = oneOf(list(alphas))
function = Group(λ + Group(OneOrMore(name))("head") + dot + expression("body"))
lambda_term = name | function | lparens + expression + rparens
#~ expression <<= Group(OneOrMore(lambda_term))
expression <<= Group(lambda_term*(2,)) | lambda_term

tests = """\
    ((λa.a)(λa.a))
    (λy.xy) ab
    λx.λy.xzy
""".splitlines()
for t in tests:
    t = t.strip()
    print(t.replace('λ','^'))
    expression.parseString(t, parseAll=True).pprint()
    print()
</code>```

Body:
Using pyparsing, I seem to be having trouble understanding why my grammar either matches partially or hits a recursion limit.

lparens = Suppress("(")
rparens = Suppress(")")
name = Word(alphanums, exact=1)
expression = Forward()
function = Group(Literal("λ") + OneOrMore(name) + Literal(".").suppress() + expression)
application = Group(expression + expression) #<-- the problem *I think*
exp1 = ( name | function | application )
exp2 = (lparens + exp1 + rparens) | exp1
expression << exp2

So the following will parse but only picks up the "a" and does not apply the application step:

expression.parseString("ab") #result is: (['a'], {})
expression.parseString("(ab)") #result is: exception - recursion limit reached.

In the first example why did it stop at 'a' and not apply the application step and run into the same infinite look it does in the second example?

In the second example it matches '(' and so it needs the ')' to finish the exp1. So it should parse the name 'a' and since there is no following ')' it should abandon that and try function (which fails) and then move on to application. Then it parses name 'a' (first match) and should move on to name 'b' completing the name, the application, and then match ')' to complete the exp1 and the expression.

Obviously this is not what happens.

edit: forgot to add the following works:

expression.parseString("((λa.a)(λa.a))")

` #result: ([([(['λ', 'a', 'a'], {}), (['λ', 'a', 'a'], {})], {})], {})

adding setDebug() and setName() to the various elements and parsing '(ab)' yields:

Match expression at loc 0(1,1)
Match exp2 at loc 0(1,1)
Match lparens at loc 0(1,1)
Matched lparens -> []
Match exp1 at loc 1(1,2)
Match name at loc 1(1,2)
Matched name -> ['a']
Matched exp1 -> ['a']
Match rparens at loc 2(1,3)
Exception raised:Expected ")" (at char 2), (line:1, col:3)
Match name at loc 0(1,1)
Exception raised:Expected name (at char 0), (line:1, col:1)
Match function at loc 0(1,1)
Exception raised:Expected "λ" (at char 0), (line:1, col:1)
Match application at loc 0(1,1)
Match expression at loc 0(1,1)
Match exp2 at loc 0(1,1)
Match lparens at loc 0(1,1)
Matched lparens -> []
Match exp1 at loc 1(1,2)
Match name at loc 1(1,2)
Matched name -> ['a']
Matched exp1 -> ['a']
Match rparens at loc 2(1,3)
Exception raised:Expected ")" (at char 2), (line:1, col:3)
Match name at loc 0(1,1)
Exception raised:Expected name (at char 0), (line:1, col:1)
Match function at loc 0(1,1)
Exception raised:Expected "λ" (at char 0), (line:1, col:1)
Match application at loc 0(1,1)
Match expression at loc 0(1,1)
Match exp2 at loc 0(1,1)
Match lparens at loc 0(1,1)
Matched lparens -> []
Match exp1 at loc 1(1,2)
Match name at loc 1(1,2)
... etc etc etc...

Body:
I struggled with your question, as I did not really have a good grasp of just what you were trying to parse. Fortunately, the lambda character in your function definition was enough of a tip-off that I searched for some background on lambda calculus notation, and found a decent description here: http://palmstroem.blogspot.com/2012/05/lambda-calculus-for-absolute-dummies.html

From this I came up with a simple BNF:

expr ::= (name | function | '(' expr ')')+
function ::= 'λ' name+ '.' expr
name ::= a single character 'a'..'z' or 'A'..'Z'

Translating to pyparsing from here looks like:

lparens = Suppress("(")
rparens = Suppress(")")
dot = Suppress('.')
# work around output encoding issues by displaying as '^'
λ = Literal('λ').setParseAction(replaceWith('^'))

# Forward() placeholder for recursive expression
expression = Forward()

# implement BNF bottom-up
name = oneOf(list(alphas))
function = Group(λ + Group(OneOrMore(name))("head") + dot + expression("body"))
lambda_term = name | function | lparens + expression + rparens
expression <<= Group(OneOrMore(lambda_term))

This parses your sample expression as:

((λa.a)(λa.a))
[[[[['^', ['a'], ['a']]], [['^', ['a'], ['a']]]]]]

This seems like a lot of extra nesting to wade through. We can reduce some of it by tweaking expression slightly, to Group only if there are 2 or more expressions, otherwise parse a single ungrouped expression. The tuple multiplication feature lets us define this as:

expression <<= Group(lambda_term*(2,)) | lambda_term

Giving:

[[['^', ['a'], 'a'], ['^', ['a'], 'a']]]

Or more clearly:

[
    [
        ['^', ['a'], 'a'],
        ['^', ['a'], 'a']
    ]
]

In your posted parser, you also had a concept of "application". I speculate that what you call an application is what the cited article-for-dummies refers to as "resolving". To resolve a function, you take subsequent expressions one-for-one with each name in the function head, and replace the name in the body with its respective expression. I tried to comprehend this at parse time, but struggled with expressions where the function was nested within other functions, or the head and body were defined in nested parentheses, with the replacement expressions separated from the function by several nesting levels. I came to the conclusion that resolution has to be done after parsing of names and functions is complete. The structure that pyparsing imparts to the results should make it straightforward to walk the results and successively resolve names with expressions.

Here is the complete parser code:

"""
(from http://palmstroem.blogspot.com/2012/05/lambda-calculus-for-absolute-dummies.html)

BNF:
  expr ::= (name | function | '(' expr ')')+
  name ::= ['a'..'z' 'A'..'Z']+
  function ::= lambda name+ '.' expr
"""

lparens = Suppress("(")
rparens = Suppress(")")
dot = Suppress('.')
# work around output encoding issues by displaying as '^'
λ = Literal('λ').setParseAction(replaceWith('^'))

# Forward() placeholder for recursive expression
expression = Forward()

# implement BNF bottom-up
name = oneOf(list(alphas))
function = Group(λ + Group(OneOrMore(name))("head") + dot + expression("body"))
lambda_term = name | function | lparens + expression + rparens
#~ expression <<= Group(OneOrMore(lambda_term))
expression <<= Group(lambda_term*(2,)) | lambda_term

tests = """\
    ((λa.a)(λa.a))
    (λy.xy) ab
    λx.λy.xzy
""".splitlines()
for t in tests:
    t = t.strip()
    print(t.replace('λ','^'))
    expression.parseString(t, parseAll=True).pprint()
    print()


问:
How to disable automatic scrolling to top
How can I disable auto scroll to the top of table view when I append new data to data source of it.

The problem is visible in the following gif.

Edit: Added ViewController, ViewModel and MessageEntity.

Used frameworks are: RxSwift, RxDataSources for reactive datasource of table view.

ViewController:

```<code>class RabbitMqVC: BaseViewController {

    struct Cells {
        static let message = ReusableCell<MessageCell>(nibName: "MessageCell")
        static let messageTheir = ReusableCell<MessageCellTheir>(nibName: "MessageCellTheir")
    }

    @IBOutlet
    weak var tableView: UITableView!{
        didSet{
            rabbitMqViewModel.sections
                    .drive(tableView.rx.items(dataSource: dataSource))
                    .addDisposableTo(disposeBag)
        }
    }

    private let dataSource = RxTableViewSectionedAnimatedDataSource<RabbitMqViewModel.MessageSections>()
    private let rabbitMqViewModel : rabbitMqViewModel

    init(rabbitMqViewModel: rabbitMqViewModel) {
        self.rabbitMqViewModel = rabbitMqViewModel
        super.init(nibName: "RabbitMqVC", bundle: nil)

        dataSource.configureCell = { _, tableView, indexPath, item in
            let randomNumber = 1.random(to: 2)
            let cell = randomNumber == 1 ? tableView.dequeue(Cells.message, for: indexPath) : tableView.dequeue(Cells.messageTheir, for: indexPath)

            cell.message = item

            return cell
        }

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(Cells.message)
        tableView.register(Cells.messageTheir)
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 80

    }

}
</code>```

ViewModel:

```<code>class RabbitMqViewModel: ViewModel {

    enum MessageSections: AnimatableSectionModelType {

        typealias Item = MessageEntity
        typealias Identity = Int

        case messages(messages: [MessageEntity])

        var items: [Item] {
            switch self {
            case .messages(messages:let messages):
                return messages
            }
        }

        var identity: Int {
            return 1
        }

        init(original: MessageSections, items: [Item]) {

            switch original {
            case .messages:
                self = .messages(messages: items)
            }
        }
    }

    // input
    let didLoad = PublishSubject<Void>()

    //output
    let sections: Driver<[MessageSections]>

    init(service: RabbitMqService,){
        let messages: Observable<[MessageEntity]> = didLoad
                .flatMapLatest { _ -> Observable<[MessageEntity]> in
                    return service.listenMessages()
                }
                .share()

        self.sections = messages
                .map { (messages) -> [RabbitMqViewModel.MessageSections] in
                    var sections: [MessageSections] = []
                    sections.append(.messages(messages: messages))

                    return sections
                }
                .asDriver(onErrorJustReturn: [])

    }

}
</code>```

MessageEntity:

```<code>struct MessageEntity {

    let id: String
    let conversationId: String
    let messageText: String
    let sent: Date
    let isSentByClient: Bool
    let senderName: String
    let commodityClientId : Int?

}

extension MessageEntity: IdentifiableType, Equatable {

    typealias Identity = Int

    public var identity: Identity {
        return id.hashValue
    }
    public static func ==(lhs: MessageEntity, rhs: MessageEntity) -> Bool {
        return lhs.id == rhs.id
    }
}
</code>```

答:
```<code>estimatedRowHeight = 1
</code>```

Fixed it.

Body:
How can I disable auto scroll to the top of table view when I append new data to data source of it.

The problem is visible in the following gif.

Edit: Added ViewController, ViewModel and MessageEntity.

Used frameworks are: RxSwift, RxDataSources for reactive datasource of table view.

ViewController:

class RabbitMqVC: BaseViewController {

    struct Cells {
        static let message = ReusableCell<MessageCell>(nibName: "MessageCell")
        static let messageTheir = ReusableCell<MessageCellTheir>(nibName: "MessageCellTheir")
    }

    @IBOutlet
    weak var tableView: UITableView!{
        didSet{
            rabbitMqViewModel.sections
                    .drive(tableView.rx.items(dataSource: dataSource))
                    .addDisposableTo(disposeBag)
        }
    }

    private let dataSource = RxTableViewSectionedAnimatedDataSource<RabbitMqViewModel.MessageSections>()
    private let rabbitMqViewModel : rabbitMqViewModel

    init(rabbitMqViewModel: rabbitMqViewModel) {
        self.rabbitMqViewModel = rabbitMqViewModel
        super.init(nibName: "RabbitMqVC", bundle: nil)

        dataSource.configureCell = { _, tableView, indexPath, item in
            let randomNumber = 1.random(to: 2)
            let cell = randomNumber == 1 ? tableView.dequeue(Cells.message, for: indexPath) : tableView.dequeue(Cells.messageTheir, for: indexPath)

            cell.message = item

            return cell
        }

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(Cells.message)
        tableView.register(Cells.messageTheir)
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 80

    }

}

ViewModel:

class RabbitMqViewModel: ViewModel {

    enum MessageSections: AnimatableSectionModelType {

        typealias Item = MessageEntity
        typealias Identity = Int

        case messages(messages: [MessageEntity])

        var items: [Item] {
            switch self {
            case .messages(messages:let messages):
                return messages
            }
        }

        var identity: Int {
            return 1
        }

        init(original: MessageSections, items: [Item]) {

            switch original {
            case .messages:
                self = .messages(messages: items)
            }
        }
    }

    // input
    let didLoad = PublishSubject<Void>()

    //output
    let sections: Driver<[MessageSections]>

    init(service: RabbitMqService,){
        let messages: Observable<[MessageEntity]> = didLoad
                .flatMapLatest { _ -> Observable<[MessageEntity]> in
                    return service.listenMessages()
                }
                .share()

        self.sections = messages
                .map { (messages) -> [RabbitMqViewModel.MessageSections] in
                    var sections: [MessageSections] = []
                    sections.append(.messages(messages: messages))

                    return sections
                }
                .asDriver(onErrorJustReturn: [])

    }

}

MessageEntity:

struct MessageEntity {

    let id: String
    let conversationId: String
    let messageText: String
    let sent: Date
    let isSentByClient: Bool
    let senderName: String
    let commodityClientId : Int?

}

extension MessageEntity: IdentifiableType, Equatable {

    typealias Identity = Int

    public var identity: Identity {
        return id.hashValue
    }
    public static func ==(lhs: MessageEntity, rhs: MessageEntity) -> Bool {
        return lhs.id == rhs.id
    }
}

Body:
estimatedRowHeight = 1

Fixed it.


问:
angular 4 unit testing error `TypeError: ctor is not a constructor`
I am trying to test my route resolver and while testing I got TypeError: ctor is not a constructor and no idea why it happen while typescript compile time no error.

```<code>TypeError: ctor is not a constructor
TypeError: ctor is not a constructor
    at _createClass (http://localhost:9877/_karma_webpack_/vendor.bundle.js:42355:26)
    at _createProviderInstance$1 (http://localhost:9877/_karma_webpack_/vendor.bundle.js:42330:26)
    at resolveNgModuleDep (http://localhost:9877/_karma_webpack_/vendor.bundle.js:42315:17)
    at _createClass (http://localhost:9877/_karma_webpack_/vendor.bundle.js:42362:26)
    at _createProviderInstance$1 (http://localhost:9877/_karma_webpack_/vendor.bundle.js:42330:26)
    at resolveNgModuleDep (http://localhost:9877/_karma_webpack_/vendor.bundle.js:42315:17)
    at NgModuleRef_.webpackJsonp../node_modules/@angular/core/@angular/core.es5.js.NgModuleRef_.get (http://localhost:9877/_karma_webpack_/vendor.bundle.js:43401:16)
    at TestBed.webpackJsonp../node_modules/@angular/core/@angular/core/testing.es5.js.TestBed.get (http://localhost:9877/_karma_webpack_/vendor.bundle.js:48412:47)
    at http://localhost:9877/_karma_webpack_/vendor.bundle.js:48418:61
    at Array.map (native)
</code>```

答:
This can be an error in the providers declarations.

When you try to mock a provider and use useClass instead of useValue the error "TypeError: ctor is not a constructor" is fired.

Here is an example that fires the error :

```<code>providers: [{provide: OrderService, useClass: new OrderServiceMock()}]
</code>```

The correct declaration is :

```<code>providers: [{provide: OrderService, useValue: new OrderServiceMock()}]
</code>```

Body:
I am trying to test my route resolver and while testing I got TypeError: ctor is not a constructor and no idea why it happen while typescript compile time no error.

TypeError: ctor is not a constructor
TypeError: ctor is not a constructor
    at _createClass (http://localhost:9877/_karma_webpack_/vendor.bundle.js:42355:26)
    at _createProviderInstance$1 (http://localhost:9877/_karma_webpack_/vendor.bundle.js:42330:26)
    at resolveNgModuleDep (http://localhost:9877/_karma_webpack_/vendor.bundle.js:42315:17)
    at _createClass (http://localhost:9877/_karma_webpack_/vendor.bundle.js:42362:26)
    at _createProviderInstance$1 (http://localhost:9877/_karma_webpack_/vendor.bundle.js:42330:26)
    at resolveNgModuleDep (http://localhost:9877/_karma_webpack_/vendor.bundle.js:42315:17)
    at NgModuleRef_.webpackJsonp../node_modules/@angular/core/@angular/core.es5.js.NgModuleRef_.get (http://localhost:9877/_karma_webpack_/vendor.bundle.js:43401:16)
    at TestBed.webpackJsonp../node_modules/@angular/core/@angular/core/testing.es5.js.TestBed.get (http://localhost:9877/_karma_webpack_/vendor.bundle.js:48412:47)
    at http://localhost:9877/_karma_webpack_/vendor.bundle.js:48418:61
    at Array.map (native)

Body:
This can be an error in the providers declarations.

When you try to mock a provider and use useClass instead of useValue the error "TypeError: ctor is not a constructor" is fired.

Here is an example that fires the error :

providers: [{provide: OrderService, useClass: new OrderServiceMock()}]

The correct declaration is :

providers: [{provide: OrderService, useValue: new OrderServiceMock()}]


问:
React Router - Stay at the same page after refresh
I'm learning React. I have page with 4 subpages and i use React Router to go through those pages. Everything works fine except for reloading page. When i go from page "home" to "about" or other it's ok, but when i refresh page then it render again page "about" for a second and then it change page to home (home is default/first page).I want it to stay at that page which is currently rendered, not go back to home after every refresh.
There is my code in index.js file where i render whole app and use router:

```<code><Provider store={store}>
    <Router path="/" history={browserHistory}>
        <Route path="/home" component={App}>
            <Route path="/" component={Home}/>
            <Route path="/allhotels" component={AllHotels}/>
            <Route path="/addhotel" component={AddHotel} />
            <Route path="/about" component={About} />
        </Route>
        <Route path="/signin" component={SignIn} />
        <Route path="/signup" component={SignUp} />
    </Router>
</Provider>, document.getElementById('root')
</code>```

In "App" i have Navigation and there i render rest of conent from Home, AllHotels etc.

There is code from App.jsx

```<code>class App extends Component {

render() {
    return (
        <div className="app-comp">
            <Navigation />
            <div> {this.props.children}</div>
        </div>
    )
  }
}
</code>```

I also attach gif which shows my problem.

https://gifyu.com/image/boMp

In backend i use Firebase if it's important.

Thanks in advance.

答:
Add into your webpack.config.js this option

```<code>devServer: {
    historyApiFallback: true
},
</code>```

Body:
I'm learning React. I have page with 4 subpages and i use React Router to go through those pages. Everything works fine except for reloading page. When i go from page "home" to "about" or other it's ok, but when i refresh page then it render again page "about" for a second and then it change page to home (home is default/first page).I want it to stay at that page which is currently rendered, not go back to home after every refresh.
There is my code in index.js file where i render whole app and use router:

<Provider store={store}>
    <Router path="/" history={browserHistory}>
        <Route path="/home" component={App}>
            <Route path="/" component={Home}/>
            <Route path="/allhotels" component={AllHotels}/>
            <Route path="/addhotel" component={AddHotel} />
            <Route path="/about" component={About} />
        </Route>
        <Route path="/signin" component={SignIn} />
        <Route path="/signup" component={SignUp} />
    </Router>
</Provider>, document.getElementById('root')

In "App" i have Navigation and there i render rest of conent from Home, AllHotels etc.

There is code from App.jsx

class App extends Component {

render() {
    return (

            <Navigation />

 {this.props.children}

    )
  }
}

I also attach gif which shows my problem.

https://gifyu.com/image/boMp

In backend i use Firebase if it's important.

Thanks in advance.

Body:
Add into your webpack.config.js this option

devServer: {
    historyApiFallback: true
},


答:
it's a Server-side vs Client-side issue
check the following thread, it might give you some insights.. React-router urls don't work when refreshing or writting manually</p>

Title: React Router - Stay at the same page after refresh


问:
Mimic tapply behaviour in data.table
I'm looking to mimic the keeping of factors by tapply using data.table, for example

```<code>library(data.table)
amounts <- data.table(year = factor(2014:2017, levels = 2010:2017),
                      amount = 1:4)
tapply(amounts$amount, amounts$year, sum)
</code>```

yields

```<code>2010 2011 2012 2013 2014 2015 2016 2017
  NA   NA   NA   NA    1    2    3    4
</code>```

However, the approach using data.table doesn't show the years for which no rows are present:

```<code>amounts[ , list(sumAmount = sum(amount)), by = year]

   year sumAmount
1: 2014         1
2: 2015         2
3: 2016         3
4: 2017         4
</code>```

Is there a clean way to do this in data.table?

答:
One option would be to use dcast from data.table

```<code>dcast(amounts, 1 ~ year, value.var = 'amount', sum, drop = FALSE, fill = NA)
</code>```

Title: Mimic tapply behaviour in data.table

Body:
I'm looking to mimic the keeping of factors by tapply using data.table, for example

library(data.table)
amounts <- data.table(year = factor(2014:2017, levels = 2010:2017),
                      amount = 1:4)
tapply(amounts$amount, amounts$year, sum)

yields

2010 2011 2012 2013 2014 2015 2016 2017
  NA   NA   NA   NA    1    2    3    4

However, the approach using data.table doesn't show the years for which no rows are present:

amounts[ , list(sumAmount = sum(amount)), by = year]

   year sumAmount
1: 2014         1
2: 2015         2
3: 2016         3
4: 2017         4

Is there a clean way to do this in data.table?

Body:
One option would be to use dcast from data.table

dcast(amounts, 1 ~ year, value.var = 'amount', sum, drop = FALSE, fill = NA)


问:
Kotlin for assertThat(foo, instanceOf(Bar.class))
How would you write assertThat(foo, instanceOf(Bar.class)) with Kotlin?

Seems that it does not like the .class

I would like to go for an assertion which is a bit more "precise" than just an assertTrue(foo is Bar) if possible

答:
assertThat(foo, instanceOf(Bar::class.java))

Documentation: https://kotlinlang.org/docs/reference/java-interop.html#getclass


问:
Mysqli delete query
When creating a mysqli delete query how can I run a PHP code to delete the files associated with the info deleted?

I know of mysqli::$affected_rows but it doesn't really help me.

答:
The following line deleted all the rows that contained the word "Cron" in the 'Title' column.

```<code>mysqli_query($con,"delete from `foexstco_rr`.`Timings` where `Title`='Cron'");
</code>```

The next line deleted everything.

```<code>mysqli_query($con,"delete from `foexstco_rr`.`Timings`");
</code>```

This line deleted the rows that contained the 3 conditions. Note that ** and ** had to separate each condition.

```<code>mysqli_query($con,"delete from `foexstco_rr`.`Timings` where `Number`='77' and `Title`='Cron' and `Cols`='1'");
</code>```

If you printed the MySqli response, "1" will mean that the command has been carried out but it does not necessarily mean that any rows have been deleted. "0" means the command has been incorrectly written.

Title: Mysqli delete query

Body:
The following line deleted all the rows that contained the word "Cron" in the 'Title' column.

mysqli_query($con,"delete from `foexstco_rr`.`Timings` where `Title`='Cron'");

The next line deleted everything.

mysqli_query($con,"delete from `foexstco_rr`.`Timings`");

This line deleted the rows that contained the 3 conditions. Note that ** and ** had to separate each condition.

mysqli_query($con,"delete from `foexstco_rr`.`Timings` where `Number`='77' and `Title`='Cron' and `Cols`='1'");

If you printed the MySqli response, "1" will mean that the command has been carried out but it does not necessarily mean that any rows have been deleted. "0" means the command has been incorrectly written.


问:
Validation on name TextBoxes
I have a grid where in insert/edit mode you can update the item for a person's names.

I've been asked to provide validation to ensure only alphanumerics are added.

After talking with a colleague we were thinking only validation for length should be done.

The user should be able to enter any characters they like.

Does this sound correct? I understand some names could contain special characters etc.

答:
There's tutorials for name validation available on Microsoft.com that are superior to your suggestions.  Its easy enough to implement one of these pre-written Regex patterns so go for that instead.  </p>

```<code>^[a-zA-Z''-'\s]{1,40}$
</code>```

<p>*Validates a name. Allows up to 40 uppercase and lowercase characters and a few special characters that are common to some names. </p>

Title: Validation on name TextBoxes

Body:
There's tutorials for name validation available on Microsoft.com that are superior to your suggestions.  Its easy enough to implement one of these pre-written Regex patterns so go for that instead.

^[a-zA-Z''-'\s]{1,40}$

*Validates a name. Allows up to 40 uppercase and lowercase characters and a few special characters that are common to some names.


问:
Curl error: Failed to connect to ipaddress port 8080
problem

```<code>  Curl error: Failed to connect to 103.16.101.52 port 8080: Connection refusedresource(4) of type (mysql result)
</code>```

code snippets works in localsystem.

it's not working prod enviornment.

php curl snippet

```<code>try {

    $runfile = 'http://103.16.101.52:8080/sendsms/bulksms?username=XXX&password=XXX&type=0&dlr=1&destination='. $row['phone_number'] . '&source=XXX&message='.$message;

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $runfile);

    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

    $content = curl_exec ($ch);

    if(curl_exec($ch) === false)
    {
        echo 'Curl error: ' . curl_error($ch);
    }
    else
    {
        echo 'Operation completed without any errors';
    }
    var_dump($result);die;
    curl_close ($ch);

    }
    catch (\Exception $e) {

    $message = $e->getMessage();
    print_r($message);
    die;
    }
</code>```

i googled and found

```<code>   CURLE_NOT_BUILT_IN (4)

   A requested feature, protocol or option was not found built-in in
  this libcurl due to a build-time decision. This means that a feature
   or option was not enabled or explicitly disabled when libcurl was
   built and in order to get it to function you have to get a rebuilt libcurl.
</code>```

does this error belongs ipv4 or ipv6.

im using cpanel  please suggest.

Solution that worked for me

i tried with 80 port

```<code>  $runfile = 'http://103.16.101.52:80
</code>```

答:
Just to put this as a proper answer...
Use port 80, 8080 is usually used when you have something else running that also uses 80. (I use containers and 8080 is directed to my phpmyadmin container, 80 to my Apache container)</p>

Body:
problem

  Curl error: Failed to connect to 103.16.101.52 port 8080: Connection refusedresource(4) of type (mysql result)

code snippets works in localsystem.

it's not working prod enviornment.

php curl snippet

try {

    $runfile = 'http://103.16.101.52:8080/sendsms/bulksms?username=XXX&password=XXX&type=0&dlr=1&destination='. $row['phone_number'] . '&source=XXX&message='.$message;

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $runfile);

    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

    $content = curl_exec ($ch);

    if(curl_exec($ch) === false)
    {
        echo 'Curl error: ' . curl_error($ch);
    }
    else
    {
        echo 'Operation completed without any errors';
    }
    var_dump($result);die;
    curl_close ($ch);

    }
    catch (\Exception $e) {

    $message = $e->getMessage();
    print_r($message);
    die;
    }

i googled and found

   CURLE_NOT_BUILT_IN (4)

   A requested feature, protocol or option was not found built-in in
  this libcurl due to a build-time decision. This means that a feature
   or option was not enabled or explicitly disabled when libcurl was
   built and in order to get it to function you have to get a rebuilt libcurl.

does this error belongs ipv4 or ipv6.

im using cpanel  please suggest.

Solution that worked for me

i tried with 80 port

  $runfile = 'http://103.16.101.52:80