问:
Trying to reverse a linked list using recursion and pointer to pointer but reversell function not giving expected proper output
I was trying to reverse a linked list using recursion and pointer to pointer but reversell function is not working properly as expected. Only reversell function has some problem all other functions are working totally fine. I have used pointer to pointer in insertlast function also and it is working correctly.

Actually i am following
https://www.youtube.com/watch?v=KYH83T4q6Vs&list=PL2_aWCzGMAwI3W_JlcBbtYTwiQSsOTa6P&index=11
This video but I tried using pointer to pointer. The code shown in video didn't use pointer to pointer. He has used head as global variable.

```<code>#include <iostream>
using namespace std;

struct node{
    int data;
    struct node* next;
};

void print(node* head){
    while(head !=  NULL){
        cout<<head->data<<" ";
        head=head->next;
    }
}

void reversell(node** head){
    node* temp = (*head);
    if(temp->next == NULL){
        (*head)=temp;
        return;
    }
    reversell(&(temp->next));
    node* temp1 = temp->next;
    temp1->next = temp;
    temp->next = NULL;

}

void insertlast(node** head,int x){
    node* temp = new node;
    temp->data=x;
    if((*head)==NULL){
        (*head)=temp;
        temp->next=NULL;
        return;
    }
    node* temp1=(*head);
    while((temp1->next) != NULL){
        temp1=temp1->next;
    }
    temp1->next=temp;
    temp->next=NULL;
}

int main()
{
    cout<<"How many numbers do you want to add to linked list"<<endl;
    int x;
    cin>>x;
    node* head=NULL;
    cout<<"Please Enter your numbers now"<<endl;
    for (int i=0;i<x;i++){
        int num;
        cin>>num;
        insertlast(&head,num);
    }
    print(head);
    cout<<endl;
    reversell(&head);
    print(head);
    return 0;
}
</code>```

I am currently getting output as shown below:

How many numbers do you want to add to linked list

5

Please Enter your numbers now

1 2 3 4 5

1 2 3 4 5

1

Process finished with exit code 0

Expected output is:

How many numbers do you want to add to linked list

5

Please Enter your numbers now

1 2 3 4 5

1 2 3 4 5

5 4 3 2 1

Process finished with exit code 0

答:
Your function reversell is partial ok, but you missing to keep the output. You can try this:

```<code>void reverse(node* head, node **headRef)
{
    node* firstTemp = NULL;
    node* secondTemp = NULL;

    //empty list
    if(!head)
        return;

    firstTemp = head;
    secondTemp = firstTemp->next;

    //list has only one node
    if(!secondTemp)
    {
         *headRef = firstTemp;
         return;
    }

    reverse(secondTemp, headRef);

    secondTemp->next = firstTemp;
    firstTemp->next = NULL;
}

void reversell(node **head)
{
     reverse(*head, head);
}
</code>```

Body:
I was trying to reverse a linked list using recursion and pointer to pointer but reversell function is not working properly as expected. Only reversell function has some problem all other functions are working totally fine. I have used pointer to pointer in insertlast function also and it is working correctly.

Actually i am following
https://www.youtube.com/watch?v=KYH83T4q6Vs&list=PL2_aWCzGMAwI3W_JlcBbtYTwiQSsOTa6P&index=11
This video but I tried using pointer to pointer. The code shown in video didn't use pointer to pointer. He has used head as global variable.

#include <iostream>
using namespace std;

struct node{
    int data;
    struct node* next;
};

void print(node* head){
    while(head !=  NULL){
        cout<data<<" ";
        head=head->next;
    }
}

void reversell(node** head){
    node* temp = (*head);
    if(temp->next == NULL){
        (*head)=temp;
        return;
    }
    reversell(&(temp->next));
    node* temp1 = temp->next;
    temp1->next = temp;
    temp->next = NULL;

}

void insertlast(node** head,int x){
    node* temp = new node;
    temp->data=x;
    if((*head)==NULL){
        (*head)=temp;
        temp->next=NULL;
        return;
    }
    node* temp1=(*head);
    while((temp1->next) != NULL){
        temp1=temp1->next;
    }
    temp1->next=temp;
    temp->next=NULL;
}

int main()
{
    cout<<"How many numbers do you want to add to linked list"<<endl;
    int x;
    cin>>x;
    node* head=NULL;
    cout<<"Please Enter your numbers now"<<endl;
    for (int i=0;i<x;i++){
        int num;
        cin>>num;
        insertlast(&head,num);
    }
    print(head);
    cout<<endl;
    reversell(&head);
    print(head);
    return 0;
}

I am currently getting output as shown below:

How many numbers do you want to add to linked list

5

Please Enter your numbers now

1 2 3 4 5

1 2 3 4 5

1

Process finished with exit code 0

Expected output is:

How many numbers do you want to add to linked list

5

Please Enter your numbers now

1 2 3 4 5

1 2 3 4 5

5 4 3 2 1

Process finished with exit code 0

Body:
Your function reversell is partial ok, but you missing to keep the output. You can try this:

void reverse(node* head, node **headRef)
{
    node* firstTemp = NULL;
    node* secondTemp = NULL;

    //empty list
    if(!head)
        return;

    firstTemp = head;
    secondTemp = firstTemp->next;

    //list has only one node
    if(!secondTemp)
    {
         *headRef = firstTemp;
         return;
    }

    reverse(secondTemp, headRef);

    secondTemp->next = firstTemp;
    firstTemp->next = NULL;
}

void reversell(node **head)
{
     reverse(*head, head);
}


来源: stackexchange

问:
Making onClickListener a static method
```<code>View.OnClickListener ocl = new View.OnClickListener(){
    public void onClick(View v) {
        this.ocl_action();
    }

    public void ocl_action() {
        // TODO Auto-generated method stub
        for(int i=0; i<5;i++){                               }
            Toast.makeText(ControllerProjMain.this,"hi",Toast.LENGTH_LONG).show();
        }
    }
};
</code>```

It does not work if I just call ocl.ocl_action();

答: Define ocl_action() function outside listener body and remove keyword 'this' while function calling.</p>

ContentLicense: CC BY-SA 4.0

Title: Making onClickListener a static method

Body:
View.OnClickListener ocl = new View.OnClickListener(){
    public void onClick(View v) {
        this.ocl_action();
    }

    public void ocl_action() {
        // TODO Auto-generated method stub
        for(int i=0; i<5;i++){                               }
            Toast.makeText(ControllerProjMain.this,"hi",Toast.LENGTH_LONG).show();
        }
    }
};

It does not work if I just call ocl.ocl_action();


问:
Best canonical String to represent a Calendar object?
I need to store a Calendar object as a String and also be able to load a Calendar object from that String. What do I need in my String to accurately represent everything a Calendar holds?

For instance, if I used SimpleDateFormatter and use the pattern yyyyMMddHHmmssSSSzz, which is year, month, date, hour, minute, second, millisecond, and timezone, would I be able to reliably recreate the Calendar object from that String?

答: Your pattern is OK but you may encounter difficulty with culture and language specificity. I would recommend using the numerical representation of the month instead of the three-letter abbreviation for the most flexibility and to avoid trouble. You also need to consider whether or not you need to track timezone info. If this time stamp was generated as UTC or your app is meant to run in a single timezone then you're fine.</p>

ContentLicense: CC BY-SA 3.0


问:
TypeError: Cannot handle this data type - Wrong mode for `PIL.Image.fromarray`?
I'm trying to use PIL.Image.fromarray:

```<code>import matplotlib.pyplot as plt
import numpy as np
from PIL import Image

a = np.array([[[255, 0, 0], [0, 255, 0], [0, 0, 255]]])
im = Image.fromarray(a, mode="RGB")
im.save("test.png")
plt.imshow(im)
plt.show()
</code>```

I expected to see 3 pixels red, green and blue.

However, if I omit mode keyword parameter as shown in the docs example, I get:

TypeError: Cannot handle this data type

And if I set mode="RGB", the saved image file test.png and the matplotlib window both look like this:

答:
According to https://pillow.readthedocs.io/en/latest/handbook/concepts.html#concept-modes mode RGB should be 3x8-bit pixels. However, numpy.ndarray has type int64 by default:

```<code>>>> a = np.array([[[255, 0, 0], [0, 255, 0], [0, 0, 255]]])
>>> a.dtype
dtype('int64')
</code>```

That's where

TypeError: Cannot handle this data type

came from. If I set the correct 8-bit dtype keyword for the array, everything works fine, even without specifying the mode keyword:

```<code>import matplotlib.pyplot as plt
import numpy as np
from PIL import Image

a = np.array([[[255, 0, 0], [0, 255, 0], [0, 0, 255]]])
im = Image.fromarray(a, mode="RGB")
im.save("test.png")
plt.imshow(im)
plt.show()
</code>```

Body:
I'm trying to use PIL.Image.fromarray:

import matplotlib.pyplot as plt
import numpy as np
from PIL import Image

a = np.array([[[255, 0, 0], [0, 255, 0], [0, 0, 255]]])
im = Image.fromarray(a, mode="RGB")
im.save("test.png")
plt.imshow(im)
plt.show()

I expected to see 3 pixels red, green and blue.

However, if I omit mode keyword parameter as shown in the docs example, I get:

TypeError: Cannot handle this data type

And if I set mode="RGB", the saved image file test.png and the matplotlib window both look like this:

Body:
According to https://pillow.readthedocs.io/en/latest/handbook/concepts.html#concept-modes mode RGB should be 3x8-bit pixels. However, numpy.ndarray has type int64 by default:

>>> a = np.array([[[255, 0, 0], [0, 255, 0], [0, 0, 255]]])
>>> a.dtype
dtype('int64')

That's where

TypeError: Cannot handle this data type

came from. If I set the correct 8-bit dtype keyword for the array, everything works fine, even without specifying the mode keyword:

import matplotlib.pyplot as plt
import numpy as np
from PIL import Image

a = np.array([[[255, 0, 0], [0, 255, 0], [0, 0, 255]]])
im = Image.fromarray(a, mode="RGB")
im.save("test.png")
plt.imshow(im)
plt.show()


问:
Flutter Network Image does not fit in Circular Avatar
I am trying to retrieve bunch of images from an api. I want the images to be displayed in Circular form so I am using CircleAvatar Widget, but I keep getting images in square format.
 Here is a screenshot of images

Here is the code I am using

```<code>ListTile(leading: CircleAvatar(child: Image.network("${snapshot.data.hitsList[index].previewUrl}",fit: BoxFit.scaleDown,)),),
</code>```

I tryied using all the properties of BoxFit like cover, contain,fitWidth,fitHeight etc but none of them works.

答:
Here is a round picture with a shadow:</p>

```<code>child: AspectRatio(
    aspectRatio: 1/1,
    child: Container(
        margin: EdgeInsets.all(
            10.0
        ),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(100.0),
            boxShadow:[
              BoxShadow(
                  color: Color.fromARGB(60, 0, 0, 0),
                  blurRadius: 5.0,
                  offset: Offset(5.0, 5.0)
              )
            ],
            image: DecorationImage(
                fit: BoxFit.cover,
                image: NetworkImage(user.image)
            )
        )
    )
)
</code>```

Body:
I am trying to retrieve bunch of images from an api. I want the images to be displayed in Circular form so I am using CircleAvatar Widget, but I keep getting images in square format.
 Here is a screenshot of images

Here is the code I am using

ListTile(leading: CircleAvatar(child: Image.network("${snapshot.data.hitsList[index].previewUrl}",fit: BoxFit.scaleDown,)),),

I tryied using all the properties of BoxFit like cover, contain,fitWidth,fitHeight etc but none of them works.

Body:
Here is a round picture with a shadow:

child: AspectRatio(
    aspectRatio: 1/1,
    child: Container(
        margin: EdgeInsets.all(
            10.0
        ),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(100.0),
            boxShadow:[
              BoxShadow(
                  color: Color.fromARGB(60, 0, 0, 0),
                  blurRadius: 5.0,
                  offset: Offset(5.0, 5.0)
              )
            ],
            image: DecorationImage(
                fit: BoxFit.cover,
                image: NetworkImage(user.image)
            )
        )
    )
)


问:
How to automatically add data annotations to generated Entities?
I have a bunch of Entity classes generated automatically from from a database connection. I 'd like to add data annotations automatically, for example if a column is of type varchar(100), then i'd like to have the data annotation [StringLength(100)], or if it is not a nullable field, I'd like to have the [Required] annotation. Is this possible?

The only question I found about this is almost 10 years old and the answer at the time is no longer working.

Thanks in advance for any help.

答:
With some more research and some trial and error I managed to do it. Basically it involves editing the T4 template generated by Entity Framework.

After you add the ADO.NET Entity Data Model > EF Designer from data..., you get an EDMX file, and if you expand it on Visual Studio there's a .tt file with the same name as the .edmx file.

On that file, I added under <#=codeStringGenerator.UsingDirectives(inHeader: false)#> the using statement for data annotations:

```<code>using System.ComponentModel.DataAnnotations;
</code>```

Then, a few lines below, after the simpleProperties declaration, in the foreach I added the following:

```<code>foreach (var edmProperty in simpleProperties) // <-- Original foreach statement
        {
            if(edmProperty.Nullable == false)
            {
            #>    [Required]
<#
            }
            if(edmProperty.MaxLength != null)
            {
            #>    [StringLength(<#=edmProperty.MaxLength#>)]
<#
            }
//Rest of the auto-generated code...
</code>```

Saving this file will update the auto-generated .cs files accordingly:

```<code>namespace MyNamespace
{
    using System;
    using System.Collections.Generic;

    using System.ComponentModel.DataAnnotations;

    public partial class MyModel
    {
        [Required]
        public int Id { get; set; }
        [Required]
        [StringLength(20)]
        public string MyField { get; set; }
    }
}
</code>```

Body:
With some more research and some trial and error I managed to do it. Basically it involves editing the T4 template generated by Entity Framework.

After you add the ADO.NET Entity Data Model > EF Designer from data..., you get an EDMX file, and if you expand it on Visual Studio there's a .tt file with the same name as the .edmx file.

On that file, I added under <#=codeStringGenerator.UsingDirectives(inHeader: false)#> the using statement for data annotations:

using System.ComponentModel.DataAnnotations;

Then, a few lines below, after the simpleProperties declaration, in the foreach I added the following:

foreach (var edmProperty in simpleProperties) // <-- Original foreach statement
        {
            if(edmProperty.Nullable == false)
            {
            #>    [Required]
<#
            }
            if(edmProperty.MaxLength != null)
            {
            #>    [StringLength(<#=edmProperty.MaxLength#>)]
<#
            }
//Rest of the auto-generated code...

Saving this file will update the auto-generated .cs files accordingly:

namespace MyNamespace
{
    using System;
    using System.Collections.Generic;

    using System.ComponentModel.DataAnnotations;

    public partial class MyModel
    {
        [Required]
        public int Id { get; set; }
        [Required]
        [StringLength(20)]
        public string MyField { get; set; }
    }
}


问:
How to install mcrypt on PHP 7.3.3 ubuntu
I tried to follow:
PHP Warning: PHP Startup: Unable to load dynamic library 'mcrypt.so'

```<code>sudo apt-get -y install gcc make autoconf libc-dev pkg-config
sudo apt-get -y install php7.2-dev
sudo apt-get -y install libmcrypt-dev
sudo pecl install mcrypt-1.0.1
</code>```

I get:

```<code>pecl/mcrypt requires PHP (version >= 7.2.0, version <= 7.3.0, excluded versions: 7.3.0), installed version is 7.3.3-1+ubuntu14.04.1+deb.sury.org+1
No valid packages found
install failed
</code>```

I use prestashop which require this

答:
Use this, it's working perfectly in php-7.3:

```<code>sudo apt-get -y install gcc make autoconf libc-dev pkg-config
sudo apt-get -y install libmcrypt-dev
sudo pecl install mcrypt-1.0.1
</code>```

Autodetect: HIT ENTER

```<code>sudo bash -c "echo extension=/usr/lib/php/[folder in your pc]/mcrypt.so > /etc/php/7.3/cli/conf.d/mcrypt.ini"
</code>```

```<code>sudo bash -c "echo extension=/usr/lib/php/[folder in your pc]/mcrypt.so > /etc/php/7.3/apache2/conf.d/mcrypt.ini"
</code>```

php -i | grep mcrypt

Body:
I tried to follow:
PHP Warning: PHP Startup: Unable to load dynamic library 'mcrypt.so'

sudo apt-get -y install gcc make autoconf libc-dev pkg-config
sudo apt-get -y install php7.2-dev
sudo apt-get -y install libmcrypt-dev
sudo pecl install mcrypt-1.0.1

I get:

pecl/mcrypt requires PHP (version >= 7.2.0, version <= 7.3.0, excluded versions: 7.3.0), installed version is 7.3.3-1+ubuntu14.04.1+deb.sury.org+1
No valid packages found
install failed

I use prestashop which require this

Body:
Use this, it's working perfectly in php-7.3:

sudo apt-get -y install gcc make autoconf libc-dev pkg-config
sudo apt-get -y install libmcrypt-dev
sudo pecl install mcrypt-1.0.1

Autodetect: HIT ENTER

sudo bash -c "echo extension=/usr/lib/php/[folder in your pc]/mcrypt.so > /etc/php/7.3/cli/conf.d/mcrypt.ini"

sudo bash -c "echo extension=/usr/lib/php/[folder in your pc]/mcrypt.so > /etc/php/7.3/apache2/conf.d/mcrypt.ini"

php -i | grep mcrypt


问:
Liquibase: Change column to an autoincrement column (identity) in DB2
I'm trying to change a BIGINT Column to an autoincremented column in DB2 but I can't seem find how.
I tried doing it like this:

```<code>    <changeSet id="08.01" author="...">
        <addColumn tableName="table_name">
            <column name="id" type="bigint">
                <constraints nullable="true"/>
            </column>

            <column name="member_type" type="varchar(100)">
                <constraints nullable="true"/>
            </column>
        </addColumn>
    </changeSet>

    <changeSet id="08.02" author="...">
        <addAutoIncrement tableName="table_name"
                          columnDataType="bigint"
                          columnName="id"/>
    </changeSet>
</code>```

and when it runs I get this error:

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'liquibase' defined in class path resource [org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration$LiquibaseConfiguration.class]: Invocation of init method failed; nested exception is liquibase.exception.MigrationFailedException: Migration failed for change set classpath:db/changelog/08-separation.xml::08.01::author:
     Reason: liquibase.exception.DatabaseException: DB2 SQL Error: SQLCODE=-270, SQLSTATE=42997, SQLERRMC=72, DRIVER=4.13.127 [Failed SQL: ALTER TABLE SCHEMATEST.table_name ALTER COLUMN id SET GENERATED BY DEFAULT AS IDENTITY]
    at org.springframework.bean
...
...
...
Caused by: liquibase.exception.MigrationFailedException: Migration failed for change set classpath:db/changelog/08separation.xml::08.01::author:
     Reason: liquibase.exception.DatabaseException: DB2 SQL Error: SQLCODE=-270, SQLSTATE=42997, SQLERRMC=72, DRIVER=4.13.127 [Failed SQL: ALTER TABLE SCHEMATEST.table_name ALTER COLUMN id SET GENERATED BY DEFAULT AS IDENTITY]
...
...
...
Caused by: com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-270, SQLSTATE=42997, SQLERRMC=72, DRIVER=4.13.127
</code>```

答:
I found an answer myself at this link and the explanation is this:

Every DB2 admin discovers sooner or later that DB2 can not add
  identity column to existing table easily. Following statements fails
  due to syntax error: alter table public.clicks add column id integer
  generated always as identity   But i have good news for everyone. It
  can be still done, but it requires more steps.

Add not null integer column
You need to provide default value for it otherwise db2 will refuse it to make not null
alter table public.clicks add column id integer not null default 0

Drop default value from column
I am not exactly sure why it is needed because some manuals on internet omits this step but i was not able to make it work without this on DB2 9.7.3 LUW
alter table public.clicks alter column id drop default

Now set column to always generated (add the autoincrement)
alter table public.clicks alter column id set generated always as identity

Reorg table to make it writeable (I didn't do this and it still works)
reorg table public.clicks

Now replace zeros with generated itentity values
update public.clicks set id = default

And optionally make id column primary key for table
alter table public.clicks add constraint pkey primary key(id)

And the liquibase code for it:

defaultSchemaNames comes from spring properties which I defined like this. I don't know if there's a better way to get the schema but this one works also

```<code># in application.properties I've set this
liquibase.parameters.defaultSchemaName=MY_SCHEMA_NAME
</code>```

The liquibase.xml

```<code>    <property name="defaultSchema" value="${defaultSchemaName}" />

    <changeSet id="08.01.00" author="alex@mail.com">
        <dropPrimaryKey tableName="members" constraintName="pk_members_relation"/>
    </changeSet>

    <changeSet id="08.01" author="alex@mail.com">
        <addColumn tableName="members">
            <column name="id" type="BIGINT" defaultValue="0">
                <constraints nullable="false"/>
            </column>

            <column name="member_type" type="varchar(100)">
                <constraints nullable="true"/>
            </column>
        </addColumn>
    </changeSet>

    <changeSet id="08.02" author="alex@mail.com">
        <dropDefaultValue tableName="members" columnName="id"/>
    </changeSet>

    <changeSet id="08.03" author="alex@mail.com">
        <addAutoIncrement tableName="members" columnName="id" columnDataType="bigint"/>
    </changeSet>

    <changeSet id="08.04" author="alex@mail.com">
        <sql>
            UPDATE ${defaultSchema}.members SET id = default
        </sql>
    </changeSet>
</code>```

Body:
I'm trying to change a BIGINT Column to an autoincremented column in DB2 but I can't seem find how.
I tried doing it like this:

    <changeSet id="08.01" author="...">
        <addColumn tableName="table_name">
            <column name="id" type="bigint">
                <constraints nullable="true"/>
            </column>

            <column name="member_type" type="varchar(100)">
                <constraints nullable="true"/>
            </column>
        </addColumn>
    </changeSet>

    <changeSet id="08.02" author="...">
        <addAutoIncrement tableName="table_name"
                          columnDataType="bigint"
                          columnName="id"/>
    </changeSet>

and when it runs I get this error:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'liquibase' defined in class path resource [org/springframework/boot/autoconfigure/liquibase/LiquibaseAutoConfiguration$LiquibaseConfiguration.class]: Invocation of init method failed; nested exception is liquibase.exception.MigrationFailedException: Migration failed for change set classpath:db/changelog/08-separation.xml::08.01::author:
     Reason: liquibase.exception.DatabaseException: DB2 SQL Error: SQLCODE=-270, SQLSTATE=42997, SQLERRMC=72, DRIVER=4.13.127 [Failed SQL: ALTER TABLE SCHEMATEST.table_name ALTER COLUMN id SET GENERATED BY DEFAULT AS IDENTITY]
    at org.springframework.bean
...
...
...
Caused by: liquibase.exception.MigrationFailedException: Migration failed for change set classpath:db/changelog/08separation.xml::08.01::author:
     Reason: liquibase.exception.DatabaseException: DB2 SQL Error: SQLCODE=-270, SQLSTATE=42997, SQLERRMC=72, DRIVER=4.13.127 [Failed SQL: ALTER TABLE SCHEMATEST.table_name ALTER COLUMN id SET GENERATED BY DEFAULT AS IDENTITY]
...
...
...
Caused by: com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-270, SQLSTATE=42997, SQLERRMC=72, DRIVER=4.13.127

Body:
I found an answer myself at this link and the explanation is this:

Every DB2 admin discovers sooner or later that DB2 can not add
  identity column to existing table easily. Following statements fails
  due to syntax error: alter table public.clicks add column id integer
  generated always as identity   But i have good news for everyone. It
  can be still done, but it requires more steps.

Add not null integer column
You need to provide default value for it otherwise db2 will refuse it to make not null
alter table public.clicks add column id integer not null default 0

Drop default value from column
I am not exactly sure why it is needed because some manuals on internet omits this step but i was not able to make it work without this on DB2 9.7.3 LUW
alter table public.clicks alter column id drop default

Now set column to always generated (add the autoincrement)
alter table public.clicks alter column id set generated always as identity

Reorg table to make it writeable (I didn't do this and it still works)
reorg table public.clicks

Now replace zeros with generated itentity values
update public.clicks set id = default

And optionally make id column primary key for table
alter table public.clicks add constraint pkey primary key(id)

And the liquibase code for it:

defaultSchemaNames comes from spring properties which I defined like this. I don't know if there's a better way to get the schema but this one works also

# in application.properties I've set this
liquibase.parameters.defaultSchemaName=MY_SCHEMA_NAME

The liquibase.xml

    <property name="defaultSchema" value="${defaultSchemaName}" />

    <changeSet id="08.01.00" author="alex@mail.com">
        <dropPrimaryKey tableName="members" constraintName="pk_members_relation"/>
    </changeSet>

    <changeSet id="08.01" author="alex@mail.com">
        <addColumn tableName="members">
            <column name="id" type="BIGINT" defaultValue="0">
                <constraints nullable="false"/>
            </column>

            <column name="member_type" type="varchar(100)">
                <constraints nullable="true"/>
            </column>
        </addColumn>
    </changeSet>

    <changeSet id="08.02" author="alex@mail.com">
        <dropDefaultValue tableName="members" columnName="id"/>
    </changeSet>

    <changeSet id="08.03" author="alex@mail.com">
        <addAutoIncrement tableName="members" columnName="id" columnDataType="bigint"/>
    </changeSet>

    <changeSet id="08.04" author="alex@mail.com">
        <sql>
            UPDATE ${defaultSchema}.members SET id = default
        </sql>
    </changeSet>


问:
How to create record with specifying foreign key?
I have Users and Bets tables as 1:M relations. However, I didn't want to have any Bet record without User reference.

So I have the following constrained relations:

```<code>Bet.belongsTo(User, {
    foreignKey: {
        allowNull: false
    }
});
User.hasMany(Bet);
</code>```

This is creating foreign key in Bets which can't be null.
This is how I intend to create Bet record:

```<code>User.findOne({
    where: {email: 'aaa@bbb.ccc'}
}).then(u => {
    Bet.create({
        User: u,
        ...
    })
    .then(b => {
        console.log('done');
    });
})
</code>```

Is there any way to specify User while creating Bet? I know I could do it with <foreignkey>: u.id, but I wonder if there is a way to do it on higher level, like using include and not explicitly referring to foreign key.

答:
In defining a relation between User and Bet you'll have gained some association methods on those models.

Using the create method you can instead create a new Bet from the User instance which will both create a new Bet in the DB and associate it to the User.

```<code>User.findOne({
    where: { email: 'aaa@bbb.ccc' }
})
    .then(user =>
    {
        user.createBet({ ... })
            .then(bet =>
            {
                console.log('done');
            });
    });
</code>```

Body:
I have Users and Bets tables as 1:M relations. However, I didn't want to have any Bet record without User reference.

So I have the following constrained relations:

Bet.belongsTo(User, {
    foreignKey: {
        allowNull: false
    }
});
User.hasMany(Bet);

This is creating foreign key in Bets which can't be null.
This is how I intend to create Bet record:

User.findOne({
    where: {email: 'aaa@bbb.ccc'}
}).then(u => {
    Bet.create({
        User: u,
        ...
    })
    .then(b => {
        console.log('done');
    });
})

Is there any way to specify User while creating Bet? I know I could do it with <foreignkey>: u.id, but I wonder if there is a way to do it on higher level, like using include and not explicitly referring to foreign key.

Body:
In defining a relation between User and Bet you'll have gained some association methods on those models.

Using the create method you can instead create a new Bet from the User instance which will both create a new Bet in the DB and associate it to the User.

User.findOne({
    where: { email: 'aaa@bbb.ccc' }
})
    .then(user =>
    {
        user.createBet({ ... })
            .then(bet =>
            {
                console.log('done');
            });
    });


问:
Managing an objects Constructors across multiple software versions
I'm designing a library where I am debating if I should use a constructor to initialize objects in the api's model.  My considerations are:

By using a constructor I can enforce what data is required to have a valid object according to the model.

However, by using a constructor I am curious as to how to maintain the code as it is modified in order to maintain this requirement without breaking existing code across the code base.

I could avoid using constructors in the object design, but I need the library to communicate to the developer using it which fields are required in order for the object to satisfy its model.

How can I create an object model that expresses the requirement of particular properties being initialized as well as provide scalability as it relates to code maintenance?

```<code>dim objV1 as new ObjectOfSomeType(Param1, Param2, Param3)
</code>```

VS

```<code>dim objV1 as new ObjectOfSomeType()

objV1.Property1 = Param1
objV1.Property2 = Param2
objV1.Property3 = Param3
</code>```

答:
I'm not versed on design patterns; so take what I'm suggesting with a grain of salt and maybe see if my answer gets up/down voted before deciding to use it.

I would suggest simply following these guidlines:

The arguments which SHOULD be in your constructor is any data expected to be unchanged throughout the lifetime of your object.  You should NOT provide setters for these.

Beyond that, you can OPTIONALLY provide other arguments of variables which will be commonly set, just to make the code a little easier for the api consumer.  This is something that you know will be commonly used immediately after calling the constructor.  So, say for example, if you had a User object and nickName variable within it, you would likely want to provide an option for that in the constructor, just so the the consumer doesn't always have to call new User(); and then user.setNickName("name"); every single time they instantiate the object.

Also worth noting, you should be able to do what I described defining only ONE constructor using optional arguments, if you're using c#.  http://msdn.microsoft.com/en-us/library/dd264739.aspx

Body:
I'm designing a library where I am debating if I should use a constructor to initialize objects in the api's model.  My considerations are:

By using a constructor I can enforce what data is required to have a valid object according to the model.

However, by using a constructor I am curious as to how to maintain the code as it is modified in order to maintain this requirement without breaking existing code across the code base.

I could avoid using constructors in the object design, but I need the library to communicate to the developer using it which fields are required in order for the object to satisfy its model.

How can I create an object model that expresses the requirement of particular properties being initialized as well as provide scalability as it relates to code maintenance?

dim objV1 as new ObjectOfSomeType(Param1, Param2, Param3)

VS

dim objV1 as new ObjectOfSomeType()

objV1.Property1 = Param1
objV1.Property2 = Param2
objV1.Property3 = Param3


问:
Facing difficulty to use pdfform.js in react app
I would like to use a pdfform.js library(package) within react app. I have tried by using the npm pdfform but no luck.

Any help is much appreciated.

https://github.com/phihag/pdfform.js

答:
Here is a working demo, maybe it will help you.

<!DOCTYPE html>

 <meta charset="utf-8" />
 <title>pddform.js demo</title>
 <link rel="stylesheet" href="https://phihag.github.io/pdfform.js/docs/demo.css" />

 <form class="url_form">

Upload a PDF form file: <input type="file" name="file" />

  or download one: <input type="text" size="40" value="Spielberichtsbogen_2BL.pdf" name="url" /><button role="submit">Download</button>
 </form>

 <form class="cur_file"></form>

 <form class="lib_form">
  PDF library:
  <input type="radio" name="pdflib" value="minipdf" checked="checked" />minipdf
  <input type="radio" name="pdflib" value="pdf.js" />PDF.js
 </form>

 <form class="fill_form"><button class="fill" disabled="disabled">Fill and download PDF</button></form>

 <form class="list_form">
 </form>

Loading (this may take a while since PDF.js is gigantic)

```

Body:
Here is a working demo, maybe it will help you.

<!DOCTYPE html>
<html>

<head>
 <meta charset="utf-8" />
 <title>pddform.js demo</title>
 <link rel="stylesheet" href="https://phihag.github.io/pdfform.js/docs/demo.css" />
</head>

<body>
 <div class="error"></div>
 <form class="url_form">
  <div>Upload a PDF form file: <label><input type="file" name="file" /></label></div>

  <label>or download one: <input type="text" size="40" value="Spielberichtsbogen_2BL.pdf" name="url" /><button role="submit">Download</button></label>
 </form>

 <form class="cur_file"></form>

 <form class="lib_form">
  PDF library:
  <label><input type="radio" name="pdflib" value="minipdf" checked="checked" />minipdf</label>
  <label><input type="radio" name="pdflib" value="pdf.js" />PDF.js</label>
 </form>

 <form class="fill_form"><button class="fill" disabled="disabled">Fill and download PDF</button></form>

 <form class="list_form">
 </form>

 <div class="loading">Loading (this may take a while since PDF.js is gigantic)</div>

 <!-- In a real-life scenario, you want to chose EITHER minipdf (smaller) -->
 <script src="https://phihag.github.io/pdfform.js/minipdf.js"></script>

 <!-- .. OR pdf.js (huge, but better compatibility).
pdf.worker.js is slightly modified to export the actual classes we care about -->
 <script src="https://phihag.github.io/pdfform.js/customlibs/pdf.worker.js"></script>
 <script src="https://phihag.github.io/pdfform.js/minipdf_js.js"></script>

 <!-- pako and pdfform.js are required either way -->
 <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pako/1.0.3/pako.min.js" integrity="sha256-X7u/eQo6oIgWqc5jOmTjQn3loM8Lse0ock76Gkkn/Ro="
  crossorigin="anonymous"></script>
 <script src="https://phihag.github.io/pdfform.js/pdfform.js"></script>

 <!-- FileSaver.js is just needed for the demo, although you'll probably use it in some form as well -->
 <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.0.0/FileSaver.min.js"></script>

 <script src="https://phihag.github.io/pdfform.js/docs/demo.js"></script>

</body>

</html>


问:
how to convert python ndarray to c++ char*?
I'm using swig to wrap a c++ library, it needs to get image data as char*. I can read the image in python. But how can i trans it to c++?

I konw I might need to use typemap. I tried several ways, but I always get a picture with only stripes.

This is my interface file:

/* np2char */
%module np2char

%{
    #define SWIG_FILE_WITH_INIT
    #include <opencv2/opencv.hpp>
    using namespace cv;
%}

%inline %{
  typedef char* Image_Data_Type;
  typedef int Image_Width_Type;
  typedef int Image_Height_Type;

  struct Image_Info {
      Image_Data_Type imageData;
      Image_Width_Type imageWidth;
      Image_Height_Type imageHeight;
  };

  int Imageshow(Image_Info ImageInfo) {
      Mat img(ImageInfo.imageHeight, ImageInfo.imageWidth, CV_8UC3, ImageInfo.imageData);
      imshow("img_in_cpp", img);
      waitKey(0);
      destroyAllWindows();
      return 0;
  }

%}
```

<p>This is my setup.py:</p>

<pre class="lang-py prettyprint-override"><code>"""
setup.py
"""
from distutils.core import setup,Extension

module1 = Extension('_np2char',
            sources=['np2char_wrap.cxx'],
            include_dirs=['include'],
            libraries = ["opencv_world342"],
            library_dirs=["lib"],
            )

setup(name = "np2char",
      version = "1.0",
      description = 'This package is used to trans ndarray to char*',
      ext_modules = [module1],
      py_modules=['np2char'])
</code>```

and this is my python file:

import np2char
import cv2

img1 = cv2.imread("1.jpg")

img_info = np2char.Image_Info()
img_info.imageData = img1.data
img_info.imageWidth = img1.shape[1]
img_info.imageHeight = img1.shape[0]

np2char.Imageshow(img_info)
```

<p>I have tried </p>

<pre class="lang-c prettyprint-override"><code>%typemap(in) Image_Data_Type{
  $1 = reinterpret_cast<char*>(PyLong_AsLongLong($input));
}
</code>```

, and in python side
img_info.imageData=img1.ctypes.data
But still I got only stripes. It seems that imagedata is copied to other places in memory. In the process, it was truncated by '\0'.

答:
haha, I figured it out myself.

In SWIG Documentation 5.5.2,

SWIG assumes that all members of type char * have been dynamically allocated using malloc() and that they are NULL-terminated ASCII strings.

  If this behavior differs from what you need in your applications, the SWIG "memberin" typemap can be used to change it.

So, what I need is "typemap(memberin)":

%typemap(in) Image_Data_Type{
  $1 = reinterpret_cast<Image_Data_Type>(PyLong_AsLongLong($input));
}

%typemap(memberin) Image_Data_Type{
  $1 = $input;
}

%typemap(out) Image_Data_Type{
  $result = PyLong_FromLongLong(reinterpret_cast<__int64>($1));
}
```

It's a bit ugly using integer to transfer pointer. Is there a better way?

Body:
I'm using swig to wrap a c++ library, it needs to get image data as char*. I can read the image in python. But how can i trans it to c++?

I konw I might need to use typemap. I tried several ways, but I always get a picture with only stripes.

This is my interface file:

/* np2char */
%module np2char

%{
    #define SWIG_FILE_WITH_INIT
    #include <opencv2/opencv.hpp>
    using namespace cv;
%}

%inline %{
  typedef char* Image_Data_Type;
  typedef int Image_Width_Type;
  typedef int Image_Height_Type;

  struct Image_Info {
      Image_Data_Type imageData;
      Image_Width_Type imageWidth;
      Image_Height_Type imageHeight;
  };

  int Imageshow(Image_Info ImageInfo) {
      Mat img(ImageInfo.imageHeight, ImageInfo.imageWidth, CV_8UC3, ImageInfo.imageData);
      imshow("img_in_cpp", img);
      waitKey(0);
      destroyAllWindows();
      return 0;
  }

%}

This is my setup.py:

"""
setup.py
"""
from distutils.core import setup,Extension

module1 = Extension('_np2char',
            sources=['np2char_wrap.cxx'],
            include_dirs=['include'],
            libraries = ["opencv_world342"],
            library_dirs=["lib"],
            )

setup(name = "np2char",
      version = "1.0",
      description = 'This package is used to trans ndarray to char*',
      ext_modules = [module1],
      py_modules=['np2char'])

and this is my python file:

import np2char
import cv2

img1 = cv2.imread("1.jpg")

img_info = np2char.Image_Info()
img_info.imageData = img1.data
img_info.imageWidth = img1.shape[1]
img_info.imageHeight = img1.shape[0]

np2char.Imageshow(img_info)

I have tried

%typemap(in) Image_Data_Type{
  $1 = reinterpret_cast<char*>(PyLong_AsLongLong($input));
}

, and in python side
img_info.imageData=img1.ctypes.data
But still I got only stripes. It seems that imagedata is copied to other places in memory. In the process, it was truncated by '\0'.

Body:
haha, I figured it out myself.

In SWIG Documentation 5.5.2,

SWIG assumes that all members of type char * have been dynamically allocated using malloc() and that they are NULL-terminated ASCII strings.

  If this behavior differs from what you need in your applications, the SWIG "memberin" typemap can be used to change it.

So, what I need is "typemap(memberin)":

%typemap(in) Image_Data_Type{
  $1 = reinterpret_cast<Image_Data_Type>(PyLong_AsLongLong($input));
}

%typemap(memberin) Image_Data_Type{
  $1 = $input;
}

%typemap(out) Image_Data_Type{
  $result = PyLong_FromLongLong(reinterpret_cast<__int64>($1));
}

It's a bit ugly using integer to transfer pointer. Is there a better way?


问:
Count total user that subscribe and unsubscribe at the same day
I want to count total user that subscribe and unsubscribe the service at the same day.
The user will be the MSISDN and subscription will be OperationType.
If user subscribe, OperationType = 1, and if the user unsubscribe, OperationType = 2. The user can subscribe and unsubscribe the service on the same day.

Subscribe : OperationType = 1
Unsubscribe : OperationType = 2

Structure & Data of tbl_process
Refer to my data. I have two same user (which is MSISDN) that subscribe and later unsubscribe to the service.

This is my result based on query below. I somehow manage to get list of user that subscribe and unsubscribe on the same day. But now I want to count total user who got 2 OperationType, which is 1 & 2 (this is based on my query).

Below is my query:

SELECT DISTINCT(msisdn), operationType
FROM tbl_process
WHERE DATE(RequestTS) = '2019-03-14'
AND STATUS = 3
ORDER BY msisdn;```

答:
select DATE,count(*) from
(select
 date(RequestTs) as DATE,
 msisdn,
  count(distinct operationType)
from
  tbl_process t1
group by 1
 having count(distinct operationType) > 1
 ) a group by 1

select count(distinct msisdn) from
(select
 date(RequestTs) as DATE,
 msisdn,
  count(distinct operationType)
from
  tbl_process t1
group by 1
 having count(distinct operationType) > 1
 ) a group by 1


问:
How to return total number of records with TOP * select
I have over 300 000 rows, I would like to return total number of the records even if I pick only 20/50/100 records using TOP * statement.

Is it possible to filter select like

select top 50 * from table where rule1=rule1 and rule=rule2

Let's say that total number of records if database is 300 000 and select above would return 4 000 records. But physically it will return only 50 records, I need to know how manu is there in database using this where statement (it would return 4000).

Thanks

答:
```<code>select top 50 *, count(*) over()
from table
where rule1=rule1 and rule=rule2
</code>```


问:
Function doesn't update the variable
My function is update the ArrayList, but doesn't update the boolean, it's very weird!

I just not understand, or them both updates, or them both not.

```<code>private ArrayList<String> arrayList = new ArrayList<>();
private boolean isEmpty = true;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    addNames(arrayList, isEmpty);
    Log.d("status", arrayList.size() + " " + isEmpty);

}

private void addNames(ArrayList<String> names, boolean empty) {
    names.add("Moshe");
    names.add("Noa");
    names.add("Haim");
    empty = false;
}
</code>```

How can i update the isEmpty variable?
(this.isEmpty = false; is not good for me, i need another way)

答:
You want to set the field to the arg, so empty=false should instead be

```<code>this.isEmpty = empty
</code>```

As just setting empty = false sets the passed in argument 'empty' to false rather than the field

Title: Function doesn't update the variable

Body:
My function is update the ArrayList, but doesn't update the boolean, it's very weird!

I just not understand, or them both updates, or them both not.

private ArrayList<String> arrayList = new ArrayList<>();
private boolean isEmpty = true;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    addNames(arrayList, isEmpty);
    Log.d("status", arrayList.size() + " " + isEmpty);

}

private void addNames(ArrayList<String> names, boolean empty) {
    names.add("Moshe");
    names.add("Noa");
    names.add("Haim");
    empty = false;
}

How can i update the isEmpty variable?
(this.isEmpty = false; is not good for me, i need another way)

Body:
You want to set the field to the arg, so empty=false should instead be

this.isEmpty = empty

As just setting empty = false sets the passed in argument 'empty' to false rather than the field


问:
How to display HTML in TextView?
I have simple HTML:

```<code><h2>Title</h2><br>
<p>description here</p>
</code>```

I want to display HTML styled text it in TextView. How to do this?

答:
If you use androidx.* classes in your project, you should use HtmlCompat.fromHtml(text, flag).

Source of the method is:

```<code>@NonNull
    public static Spanned fromHtml(@NonNull String source, @FromHtmlFlags int flags) {
        if (Build.VERSION.SDK_INT >= 24) {
            return Html.fromHtml(source, flags);
        }
        //noinspection deprecation
        return Html.fromHtml(source);
    }
</code>```

It is better to use HtmlCompat.fromHtml than Html.fromHtml as there is less code- only one line of code, and it's recommended way to use it.

Title: How to display HTML in TextView?

Body:
I have simple HTML:

Title

description here

I want to display HTML styled text it in TextView. How to do this?

Body:
If you use androidx.* classes in your project, you should use HtmlCompat.fromHtml(text, flag).

Source of the method is:

@NonNull
    public static Spanned fromHtml(@NonNull String source, @FromHtmlFlags int flags) {
        if (Build.VERSION.SDK_INT >= 24) {
            return Html.fromHtml(source, flags);
        }
        //noinspection deprecation
        return Html.fromHtml(source);
    }

It is better to use HtmlCompat.fromHtml than Html.fromHtml as there is less code- only one line of code, and it's recommended way to use it.


问:
MySQL load and delete on same PHP page
I am trying to load data from MySQL and then display the results. I would like be able to delete the associated record as well.

```<code><?php
include 'conn.php';

$sql = "SELECT * FROM Reviews LIMIT 3";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<h1> " . $row["rTitle"]. " </h1>" . $row["rText"]. "<br> <a href="delete.php?id={$row['id']}">Delete</a>";
}
} else {
echo "0 results";
}

$id = $_GET['rID'];
mysql_query("DELETE FROM Reviews WHERE id = {$id}");

$conn->close();

?>
</code>```

I have a problem with this line:

```<code>echo "<h1> " . $row["rTitle"]. " </h1>" . $row["rText"]. "<br> <a href="delete.php?id={$row['id']}">Delete</a>";
</code>```

Error: syntax error, unexpected 'delete' (T_STRING), expecting ',' or ';

What am I doing wrong? Thank you.

答:
```<code>echo '<h1>'.$row["rTitle"].'</h1>'.$row["rText"].'<br> <a href="/delete.php?id='.$row['id'].'">Delete</a>';
</code>```

This will work and always try to use single ' while framing html code bcz ' is faster than ".

Title: MySQL load and delete on same PHP page

Body:
I am trying to load data from MySQL and then display the results. I would like be able to delete the associated record as well.

<?php
include 'conn.php';

$sql = "SELECT * FROM Reviews LIMIT 3";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "
 " . $row["rTitle"]. "
" . $row["rText"]. "
 Delete";
}
} else {
echo "0 results";
}

$id = $_GET['rID'];
mysql_query("DELETE FROM Reviews WHERE id = {$id}");

$conn->close();

?>

I have a problem with this line:

echo "
 " . $row["rTitle"]. "
" . $row["rText"]. "
 Delete";

Error: syntax error, unexpected 'delete' (T_STRING), expecting ',' or ';

What am I doing wrong? Thank you.

Body:
echo '<h1>'.$row["rTitle"].'</h1>'.$row["rText"].'<br> <a href="/delete.php?id='.$row['id'].'">Delete</a>';

This will work and always try to use single ' while framing html code bcz ' is faster than ".


问:
WebDriverException: Message: Service chromedriver unexpectedly exited. Status code was: 127
I'd like to construct my crawler using selenium on my server.

Thus I had installed/download required dependencies- such as chromedriver, chromium-browser etc on my Ubuntu17.10 server

However, when I run following code:

```<code>driver = webdriver.Chrome()
</code>```

It returns following error:

```<code>---------------------------------------------------------------------------
WebDriverException                        Traceback (most recent call last)
<ipython-input-14-2cdab8938403> in <module>()
----> 1 driver = webdriver.Chrome()

/home/zachary/.local/lib/python3.6/site-packages/selenium/webdriver/chrome/webdriver.py in __init__(self, executable_path, port, options, service_args, desired_capabilities, service_log_path, chrome_options)
     66             service_args=service_args,
     67             log_path=service_log_path)
---> 68         self.service.start()
     69
     70         try:

/home/zachary/.local/lib/python3.6/site-packages/selenium/webdriver/common/service.py in start(self)
     96         count = 0
     97         while True:
---> 98             self.assert_process_still_running()
     99             if self.is_connectable():
    100                 break

/home/zachary/.local/lib/python3.6/site-packages/selenium/webdriver/common/service.py in assert_process_still_running(self)
    109             raise WebDriverException(
    110                 'Service %s unexpectedly exited. Status code was: %s'
--> 111                 % (self.path, return_code)
    112             )
    113

WebDriverException: Message: Service chromedriver unexpectedly exited. Status code was: 127
</code>```

What does it mean that it's excited..?

I can't get what the original intention of that error code and where to start to fix it.

It looks very rare case.

Maybe relevant:

I had install ubuntu desktop 17.10 on my desktop but failed to get GUI boot. Thus I am just using terminal only, but it well works so far.
I had installed ssh and remote controlling jupyter notebook from my mac to server desktop, and those errors comes from it.
Hope this info is relevant to solve this error, otherwise will abort it.

答:
Reverting to older versions might also be a solution...

I am using Ubuntu 18.10 and installed the latest Selenium (3.141.0) and ChromeDriver (75.0.3770.8), but also had the same permission problems, and status code 127 afterwards.

I tried installing Chromium and noticed that Ubuntu was using Version 73. So I reverted from the latest version of Chromedriver (75 at this time), back to Version 73 and that worked for me.

Body:
I'd like to construct my crawler using selenium on my server.

Thus I had installed/download required dependencies- such as chromedriver, chromium-browser etc on my Ubuntu17.10 server

However, when I run following code:

driver = webdriver.Chrome()

It returns following error:

---------------------------------------------------------------------------
WebDriverException                        Traceback (most recent call last)
<ipython-input-14-2cdab8938403> in <module>()
----> 1 driver = webdriver.Chrome()

/home/zachary/.local/lib/python3.6/site-packages/selenium/webdriver/chrome/webdriver.py in __init__(self, executable_path, port, options, service_args, desired_capabilities, service_log_path, chrome_options)
     66             service_args=service_args,
     67             log_path=service_log_path)
---> 68         self.service.start()
     69
     70         try:

/home/zachary/.local/lib/python3.6/site-packages/selenium/webdriver/common/service.py in start(self)
     96         count = 0
     97         while True:
---> 98             self.assert_process_still_running()
     99             if self.is_connectable():
    100                 break

/home/zachary/.local/lib/python3.6/site-packages/selenium/webdriver/common/service.py in assert_process_still_running(self)
    109             raise WebDriverException(
    110                 'Service %s unexpectedly exited. Status code was: %s'
--> 111                 % (self.path, return_code)
    112             )
    113

WebDriverException: Message: Service chromedriver unexpectedly exited. Status code was: 127

What does it mean that it's excited..?

I can't get what the original intention of that error code and where to start to fix it.

It looks very rare case.

Maybe relevant:

I had install ubuntu desktop 17.10 on my desktop but failed to get GUI boot. Thus I am just using terminal only, but it well works so far.
I had installed ssh and remote controlling jupyter notebook from my mac to server desktop, and those errors comes from it.
Hope this info is relevant to solve this error, otherwise will abort it.


问:
1000 questions in android need to create 1000 activities?
I'm doing a app that will ask question to users like:

what is the capital of australia?

Camberra - paris - washington - toquio

and I will have 4 options, so user can select the right one.

When it choose the answer the next question will show.

I'd like to know if I need to create one activity for each of this questions/answers or there is another method? can I have examples?

答: 'You can use Viewpager or viewFlipper for that purpose. in this way you can show all of your's questions in one activity'</p>


问:
The accuracy of oracle when compare two date in SQL
It is in two procedures which are running in order. In procedure one, the running timestamp of system time is 2019/5/30 12:02:58.100. The sql is as below

```<code>insert into A(xxx,xxx,cdate) values(xxx,xxx,sysdate)
</code>```

And I find the cdate field of this inserted row is 2019/5/30 12:02:58, without the millisecond.

And then procedure two runs, the running timestamp of system time is 2019/5/30 12:02:58.200. The SQL is as below

```<code>select xxx from A where cdate<sysdate
</code>```

This returns none result. It is weird because I just inserted a row with cdate 2019/5/30 12:02:58. This should be less than sysdate.

When Oracle stores date value like 2019/5/30 12:02:58, does it throw millsecond away or does it just store it in background and not show it?

While comparing cdate<sysdate, which two values does it use? I guess it is using 2019/5/30 12:02:58 < 2019/5/30 12:02:58, so this returns false.

答: If your column is a DATE type then it doesn't store milliseconds. SYSDATE doesn't return them either. Ensure your column is a TIMESTAMP with a suitable number for fractional precision to store the milliseconds you want, and ensure you're comparing it with SYSTIMESTAMP</p>

Body:
It is in two procedures which are running in order. In procedure one, the running timestamp of system time is 2019/5/30 12:02:58.100. The sql is as below

insert into A(xxx,xxx,cdate) values(xxx,xxx,sysdate)

And I find the cdate field of this inserted row is 2019/5/30 12:02:58, without the millisecond.

And then procedure two runs, the running timestamp of system time is 2019/5/30 12:02:58.200. The SQL is as below

select xxx from A where cdate<sysdate

This returns none result. It is weird because I just inserted a row with cdate 2019/5/30 12:02:58. This should be less than sysdate.

When Oracle stores date value like 2019/5/30 12:02:58, does it throw millsecond away or does it just store it in background and not show it?

While comparing cdate<sysdate, which two values does it use? I guess it is using 2019/5/30 12:02:58 < 2019/5/30 12:02:58, so this returns false.


问:
Angular Display GMT Date time using pipe
I know how to display the DateTime in angular using by pipe

```<code>{{ dateObj | date:'medium' }}
</code>```

How to display the GMT time using a pipe

答:
You can achieve the above by making the following changes:

```<code>{{ today | date : 'medium':'GMT' }}
</code>```

According to the DatePipe documentation,

The 2nd parameter refers to the timezone. Therefore, you can simply just pass 'GMT' to your expression, and it should transform the date values to the required timezone.

A timezone offset (such as '+0430'), or a standard UTC/GMT or
  continental US timezone abbreviation. Default is the local system
  timezone of the end-user's machine.

```<code>{{ value_expression | date [ : format [ : timezone [ : locale ] ] ] }}
</code>```

Body:
I know how to display the DateTime in angular using by pipe

{{ dateObj | date:'medium' }}

How to display the GMT time using a pipe

Body:
You can achieve the above by making the following changes:

{{ today | date : 'medium':'GMT' }}

According to the DatePipe documentation,

The 2nd parameter refers to the timezone. Therefore, you can simply just pass 'GMT' to your expression, and it should transform the date values to the required timezone.

A timezone offset (such as '+0430'), or a standard UTC/GMT or
  continental US timezone abbreviation. Default is the local system
  timezone of the end-user's machine.

{{ value_expression | date [ : format [ : timezone [ : locale ] ] ] }}


问:
Cannot find element within iframe using Selenium
I'm trying to locate elements within the iframe but got no luck.

I think because of my code cannot switch to the iframe and that's why I couldn't locate the elements within it.

Below is my code.

I have tried

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, '/html/body/iframe')))
driver.find_element_by_name('applicant.name').send_keys('email')

```

<p>I also tried this</p>

<pre class="lang-py prettyprint-override"><code>iframe = driver.find_element_by_xpath('/html/body/iframe')
driver.switch_to.frame(iframe)
driver.implicitly_wait(10)
driver.find_element_by_name('applicant.name').send_keys('email')
</code>```

I tried look for xpath, id of the applicant.name but notthing work so far. Any help or suggestions would be appreciated.

Here the site:
https://www.indeed.com/cmp/Paratus-Partners-LLC/jobs/Full-Stack-Developer-7814e52be25090f3?from=iaBackPress&q=software%20developer&vjs=3

答:
There are some elements with the xpath /html/body/iframe

I was looking for the applicant.name and it was only to create after click on the postulate button.

I think that you have to check the xpath for the iframe, maybe something like this can work

```<code>"//iframe[contains(@src,'resumeapply')]"
</code>```

Body:
I'm trying to locate elements within the iframe but got no luck.

I think because of my code cannot switch to the iframe and that's why I couldn't locate the elements within it.

Below is my code.

I have tried

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, '/html/body/iframe')))
driver.find_element_by_name('applicant.name').send_keys('email')

I also tried this

iframe = driver.find_element_by_xpath('/html/body/iframe')
driver.switch_to.frame(iframe)
driver.implicitly_wait(10)
driver.find_element_by_name('applicant.name').send_keys('email')

I tried look for xpath, id of the applicant.name but notthing work so far. Any help or suggestions would be appreciated.

Here the site:
https://www.indeed.com/cmp/Paratus-Partners-LLC/jobs/Full-Stack-Developer-7814e52be25090f3?from=iaBackPress&q=software%20developer&vjs=3

Body:
There are some elements with the xpath /html/body/iframe

I was looking for the applicant.name and it was only to create after click on the postulate button.

I think that you have to check the xpath for the iframe, maybe something like this can work

"//iframe[contains(@src,'resumeapply')]"


问:
Could not load type Castle.Proxies.IReadinessProxy when running xUnit integration tests in parallel with Autofac
I am having an issue that I've been many days unable to resolve.
I use xUnit with a given-then-when abstraction to make tests more readable.

I am using a wrapper over EventStore and running some integration tests. They all go well.. except one that fails when running all in parallel (and xUnit runs in parallel), but if I run them all sequentially they all succeed.

I cannot understand why this would be an issue because every single fact is supposed to run the constructor (the given) and the functionality to test (the when). And in each fact I instantiate an Autofac ContainerBuilder, build the container and resolve its IComponentContext, so in theory every test should be isoalted and idempotent as intended.

This is the exception I keep receiving:

```<code>Autofac.Core.DependencyResolutionException : An exception was thrown while activating SalesOrder.EventStore.Infra.EventStore.EventStore -> SalesOrder.EventStore.Infra.EventStore.DomainEventsRetriever -> SalesOrder.EventStore.Infra.EventStore.Factories.DomainEventFactory -> λ:SalesOrder.EventStore.Infra.EventStore.EventTypeResolver.
---- System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types.
Could not load type 'Castle.Proxies.IReadinessProxy' from assembly 'DynamicProxyGenAssembly2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
   at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters, Object& decoratorTarget) in C:\projects\autofac\src\Autofac\Core\Resolving\InstanceLookup.cs:line 136
   at Autofac.Core.Resolving.InstanceLookup.Execute() in C:\projects\autofac\src\Autofac\Core\Resolving\InstanceLookup.cs:line 85
   at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters) in C:\projects\autofac\src\Autofac\Core\Resolving\ResolveOperation.cs:line 130
   at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters) in C:\projects\autofac\src\Autofac\Core\Resolving\ResolveOperation.cs:line 83
   at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance) in C:\projects\autofac\src\Autofac\ResolutionExtensions.cs:line 1041
   at Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable`1 parameters) in C:\projects\autofac\src\Autofac\ResolutionExtensions.cs:line 871
   at Autofac.ResolutionExtensions.Resolve[TService](IComponentContext context, IEnumerable`1 parameters) in C:\projects\autofac\src\Autofac\ResolutionExtensions.cs:line 300
   at SalesOrder.EventStore.Infra.EventStore.Autofac.IntegrationTests.EventStoreExtensionsTests.ResolveTests.Given_A_Container_With_Event_Store_Registered_When_Resolving_An_IEventStore.When() in C:\src\SalesOrder.EventStore\SalesOrder.EventStore.Infra.EventStore.Autofac.IntegrationTests\EventStoreExtensionsTests\ResolveTests.cs:line 53
   at SalesOrder.EventStore.Infra.EventStore.Autofac.IntegrationTests.EventStoreExtensionsTests.ResolveTests.Given_A_Container_With_Event_Store_Registered_When_Resolving_An_IEventStore..ctor()
----- Inner Stack Trace -----
   at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
   at System.Reflection.RuntimeModule.GetTypes()
   at System.Reflection.Assembly.GetTypes()
   at SalesOrder.EventStore.Infra.EventStore.Autofac.EventStoreExtensions.<>c.<RegisterResolvers>b__6_2(Assembly s) in C:\src\SalesOrder.EventStore\SalesOrder.EventStore.Infra.EventStore.Autofac\EventStoreExtensions.cs:line 174
   at System.Linq.Enumerable.SelectManySingleSelectorIterator`2.MoveNext()
   at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
   at System.Collections.Generic.List`1.AddEnumerable(IEnumerable`1 enumerable)
   at SalesOrder.EventStore.Infra.EventStore.Factories.EventTypeResolverFactory.Create(IEnumerable`1 existingTypes, IReadOnlyDictionary`2 domainEventSerializerDeserializers) in C:\src\SalesOrder.EventStore\SalesOrder.EventStore.Infra.EventStore\Factories\EventTypeResolverFactory.cs:line 16
   at SalesOrder.EventStore.Infra.EventStore.Autofac.EventStoreExtensions.<>c__DisplayClass6_0.<RegisterResolvers>b__1(IComponentContext context) in C:\src\SalesOrder.EventStore\SalesOrder.EventStore.Infra.EventStore.Autofac\EventStoreExtensions.cs:line 180
   at Autofac.Builder.RegistrationBuilder.<>c__DisplayClass0_0`1.<ForDelegate>b__0(IComponentContext c, IEnumerable`1 p) in C:\projects\autofac\src\Autofac\Builder\RegistrationBuilder.cs:line 62
   at Autofac.Core.Activators.Delegate.DelegateActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters) in C:\projects\autofac\src\Autofac\Core\Activators\Delegate\DelegateActivator.cs:line 71
   at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters, Object& decoratorTarget) in C:\projects\autofac\src\Autofac\Core\Resolving\InstanceLookup.cs:line 118
</code>```

This is the test with only one Fact that fails when running in parallel with others:

```<code>public class Given_A_Container_With_Event_Store_Registered_When_Resolving_An_IEventStore
    : Given_When_Then_Test
{
    private IEventStore _sut;
    private IComponentContext _componentContext;

    protected override void Given()
    {
        var builder = new ContainerBuilder();
        builder
            .RegisterEventStore(
                ctx =>
                {
                    var eventStoreOptions =
                        new EventStoreOptions
                        {
                            Url = EventStoreTestConstants.TestUrl,
                            Port = EventStoreTestConstants.TestPort
                        };
                    return eventStoreOptions;
                },
                ctx =>
                {
                    var readinessOptions =
                        new ReadinessOptions
                        {
                            Timeout = EventStoreTestConstants.TestTimeout
                        };
                    return readinessOptions;
                });

        var container = builder.Build();
        _componentContext = container.Resolve<IComponentContext>();
    }

    protected override void When()
    {
        _sut = _componentContext.Resolve<IEventStore>();
    }

    [Fact]
    public void Then_It_Should_Not_Be_Null()
    {
        _sut.Should().NotBeNull();
    }
}
</code>```

Any clue what may be happening here?
I've had a look at Autofac's guidelines on concurrency: https://autofaccn.readthedocs.io/en/latest/advanced/concurrency.html but I think I am already using properly the component context.

UPDATE 1: FYI this is the GivenThenWhen template I use. But nothing very special here (I think!)

```<code>namespace ToolBelt.TestSupport
{
    public abstract class Given_When_Then_Test
        : IDisposable
    {
        protected Given_When_Then_Test()
        {
            Setup();
        }

        private void Setup()
        {
            Given();
            When();
        }

        protected abstract void Given();

        protected abstract void When();

        public void Dispose()
        {
            Cleanup();
        }

        protected virtual void Cleanup()
        {
        }
    }

    public abstract class Given_WhenAsync_Then_Test
        : IDisposable
    {
        protected Given_WhenAsync_Then_Test()
        {
            Task.Run(async () => { await SetupAsync(); }).GetAwaiter().GetResult();
        }

        private async Task SetupAsync()
        {
            Given();
            await WhenAsync();
        }

        protected abstract void Given();

        protected abstract Task WhenAsync();

        public void Dispose()
        {
            Cleanup();
        }

        protected virtual void Cleanup()
        {
        }
    }
}
</code>```

UPDATE 2: And this is the IoCC Autofac registration's method I am using for my implementation and all the tests. A bit complex because I use reflection to keep the EventStore wrapper fully generic, but just in case somebody sees something funky there that might affect the tests..

```<code>public static class EventStoreExtensions
{
    public static void RegisterEventStore(
        this ContainerBuilder builder,
        Func<IComponentContext, EventStoreOptions> optionsRetriever,
        Func<IComponentContext, ReadinessOptions> readinessOptionsRetriever,
        Func<IComponentContext, CustomDomainEventMappersOptions> customDomainEventMappersOptionsRetriever = null)
    {
        RegisterEventStoreConnection(builder, optionsRetriever);
        RegisterFactories(builder);
        RegisterEventStoreManager(builder);
        RegisterConverters(builder);
        RegisterResolvers(builder, customDomainEventMappersOptionsRetriever);
        RegisterEventStoreServices(builder);
        RegisterEventStoreReadinessCheck(builder, readinessOptionsRetriever);
    }

    private static void RegisterEventStoreReadinessCheck(
        ContainerBuilder builder,
        Func<IComponentContext, ReadinessOptions> readinessOptionsRetriever)
    {
        builder
            .Register(context =>
            {
                var ctx = context.Resolve<IComponentContext>();
                var readinessOptions = readinessOptionsRetriever.Invoke(ctx);

                var timeout = readinessOptions.Timeout;
                var eventStoreConnection = context.Resolve<IEventStoreConnection>();

                var eventStoreReadiness =
                    new EventStoreReadiness(
                        eventStoreConnection,
                        timeout);

                return eventStoreReadiness;

            })
            .As<IEventStoreReadiness>()
            .As<IReadiness>()
            .SingleInstance();
    }

    private static void RegisterEventStoreConnection(
        ContainerBuilder builder,
        Func<IComponentContext, EventStoreOptions> optionsRetriever)
    {
        builder
            .Register(context =>
            {
                var ctx = context.Resolve<IComponentContext>();
                var eventStoreOptions = optionsRetriever.Invoke(ctx);

                ConnectionSettings connectionSetting =
                    ConnectionSettings
                        .Create()
                        .KeepReconnecting();

                var urlString = eventStoreOptions.Url;
                var port = eventStoreOptions.Port;
                var ipAddress = IPAddress.Parse(urlString);
                var tcpEndPoint = new IPEndPoint(ipAddress, port);

                var eventStoreConnection = EventStoreConnection.Create(connectionSetting, tcpEndPoint);
                return eventStoreConnection;
            })
            .As<IEventStoreConnection>()
            .SingleInstance();
    }

    private static void RegisterFactories(
        ContainerBuilder builder)
    {
        builder
            .RegisterType<DomainEventFactory>()
            .As<IDomainEventFactory>()
            .SingleInstance();

        builder
            .RegisterType<EventDataFactory>()
            .As<IEventDataFactory>()
            .SingleInstance();

        builder
            .RegisterType<ExpectedVersionFactory>()
            .As<IExpectedVersionFactory>()
            .SingleInstance();

        builder
            .RegisterType<IdFactory>()
            .As<IIdFactory>()
            .SingleInstance();

        builder
            .RegisterType<StreamNameFactory>()
            .As<IStreamNameFactory>()
            .SingleInstance();

        builder
            .RegisterType<RetrievedEventFactory>()
            .As<IRetrievedEventFactory>()
            .SingleInstance();
    }

    private static void RegisterEventStoreManager(ContainerBuilder builder)
    {
        builder
            .RegisterType<EventStoreManager>()
            .As<IEventStoreManager>()
            .SingleInstance();
    }

    private static void RegisterConverters(ContainerBuilder builder)
    {
        builder
            .Register(context =>
            {
                var utf8Encoding = new BytesConverter(Encoding.UTF8);
                return utf8Encoding;
            })
            .As<IBytesConverter>()
            .SingleInstance();

        builder
            .RegisterType<NewtonsoftConverter>()
            .As<IJsonConverter>()
            .SingleInstance();
    }

    private static void RegisterResolvers(
        ContainerBuilder builder,
        Func<IComponentContext, CustomDomainEventMappersOptions> customDomainEventMappersOptionsRetriever)
    {
        builder
            .Register(context =>
            {
                var ctx = context.Resolve<IComponentContext>();
                var customDomainEventMappersOptions = customDomainEventMappersOptionsRetriever?.Invoke(ctx);
                var domainEventSerializerDeserializers =
                    customDomainEventMappersOptions?.DomainEventSerializerDeserializers;
                var mapperResolver = MapperResolverFactory.Create(domainEventSerializerDeserializers);
                return mapperResolver;
            })
            .As<IMapperResolver>()
            .SingleInstance();

        builder
            .Register(context =>
            {
                var ctx = context.Resolve<IComponentContext>();

                var assembliesLoaded = AppDomain.CurrentDomain.GetAssemblies();
                var domainEventTypes =
                    assembliesLoaded
                        .SelectMany(s => s.GetTypes())
                        .Where(x => typeof(IDomainEvent).IsAssignableFrom(x)
                                    && x.IsClass);
                var customDomainEventMappersOptions = customDomainEventMappersOptionsRetriever?.Invoke(ctx);
                var domainEventSerializerDeserializers =
                    customDomainEventMappersOptions?.DomainEventSerializerDeserializers;
                var typeResolver =
                    EventTypeResolverFactory.Create(
                        domainEventTypes,
                        domainEventSerializerDeserializers);
                return typeResolver;
            })
            .As<IEventTypeResolver>()
            .SingleInstance();
    }

    private static void RegisterEventStoreServices(ContainerBuilder builder)
    {
        builder
            .RegisterType<EventStoreRepository>()
            .As<IEventStoreRepository>();

        builder
            .RegisterType<DomainEventsPersister>()
            .As<IDomainEventsPersister>();

        builder
            .RegisterType<DomainEventsRetriever>()
            .As<IDomainEventsRetriever>();

        builder
            .RegisterType<EventStore>()
            .As<IEventStore>();
    }
}
</code>```

UPDATE 3: This is the whole repository in case somebody is bored and wants to try to reproduce it. It is a generic event store wrapper used for event sourcing implemented for Greg Young's Event Store product using the official C# driver.

https://gitlab.com/DiegoDrivenDesign/DiDrDe.EventStore

Funnily enough, this issue seems to disappear every once in a while. In fact, often, after restarting the PC all the tests pass properly. Other times it doesn't so I suspect it has something to do with the fact that I'm loading assemblies at runtime and something gets out of whack :(

UPDATE 9 Sep 2021
The async execution I was doing is not entirely correct. There is a way to embrace async execution with xUnit that may have been playing a role in this race condition. This is a better implementation of the given-when-then pattern all my tests inherit from. Thanks to IAsyncLifetime I am able to asynchronously (and await) the preconditions and the action itself.

```<code>using System.Threading.Tasks;
using Xunit;

namespace Rubiko.TestSupport.XUnit
{
    public abstract class Given_When_Then_Test_Async
        : IAsyncLifetime
    {
        public async Task InitializeAsync()
        {
            await Given();
            await When();
        }

        public async Task DisposeAsync()
        {
            await Cleanup();
        }

        protected virtual Task Cleanup()
        {
            return Task.CompletedTask;
        }

        protected abstract Task Given();

        protected abstract Task When();
    }
}
</code>```

答: DynamicProxyGenAssembly2 is a temporary assembly built by mocking systems that use CastleProxy. There are some similar opened issues for NSubstitute and Moq that indicate that the problem is a race condition in Castle.Core or even in the .Net Framework (see: TypeLoadException or BadImageFormatException under heavy multi-threaded proxy generation for more details)</p>

Body:
I am having an issue that I've been many days unable to resolve.
I use xUnit with a given-then-when abstraction to make tests more readable.

I am using a wrapper over EventStore and running some integration tests. They all go well.. except one that fails when running all in parallel (and xUnit runs in parallel), but if I run them all sequentially they all succeed.

I cannot understand why this would be an issue because every single fact is supposed to run the constructor (the given) and the functionality to test (the when). And in each fact I instantiate an Autofac ContainerBuilder, build the container and resolve its IComponentContext, so in theory every test should be isoalted and idempotent as intended.

This is the exception I keep receiving:

Autofac.Core.DependencyResolutionException : An exception was thrown while activating SalesOrder.EventStore.Infra.EventStore.EventStore -> SalesOrder.EventStore.Infra.EventStore.DomainEventsRetriever -> SalesOrder.EventStore.Infra.EventStore.Factories.DomainEventFactory -> λ:SalesOrder.EventStore.Infra.EventStore.EventTypeResolver.
---- System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types.
Could not load type 'Castle.Proxies.IReadinessProxy' from assembly 'DynamicProxyGenAssembly2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
   at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters, Object& decoratorTarget) in C:\projects\autofac\src\Autofac\Core\Resolving\InstanceLookup.cs:line 136
   at Autofac.Core.Resolving.InstanceLookup.Execute() in C:\projects\autofac\src\Autofac\Core\Resolving\InstanceLookup.cs:line 85
   at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters) in C:\projects\autofac\src\Autofac\Core\Resolving\ResolveOperation.cs:line 130
   at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters) in C:\projects\autofac\src\Autofac\Core\Resolving\ResolveOperation.cs:line 83
   at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance) in C:\projects\autofac\src\Autofac\ResolutionExtensions.cs:line 1041
   at Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable`1 parameters) in C:\projects\autofac\src\Autofac\ResolutionExtensions.cs:line 871
   at Autofac.ResolutionExtensions.Resolve[TService](IComponentContext context, IEnumerable`1 parameters) in C:\projects\autofac\src\Autofac\ResolutionExtensions.cs:line 300
   at SalesOrder.EventStore.Infra.EventStore.Autofac.IntegrationTests.EventStoreExtensionsTests.ResolveTests.Given_A_Container_With_Event_Store_Registered_When_Resolving_An_IEventStore.When() in C:\src\SalesOrder.EventStore\SalesOrder.EventStore.Infra.EventStore.Autofac.IntegrationTests\EventStoreExtensionsTests\ResolveTests.cs:line 53
   at SalesOrder.EventStore.Infra.EventStore.Autofac.IntegrationTests.EventStoreExtensionsTests.ResolveTests.Given_A_Container_With_Event_Store_Registered_When_Resolving_An_IEventStore..ctor()
----- Inner Stack Trace -----
   at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
   at System.Reflection.RuntimeModule.GetTypes()
   at System.Reflection.Assembly.GetTypes()
   at SalesOrder.EventStore.Infra.EventStore.Autofac.EventStoreExtensions.<>c.<RegisterResolvers>b__6_2(Assembly s) in C:\src\SalesOrder.EventStore\SalesOrder.EventStore.Infra.EventStore.Autofac\EventStoreExtensions.cs:line 174
   at System.Linq.Enumerable.SelectManySingleSelectorIterator`2.MoveNext()
   at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
   at System.Collections.Generic.List`1.AddEnumerable(IEnumerable`1 enumerable)
   at SalesOrder.EventStore.Infra.EventStore.Factories.EventTypeResolverFactory.Create(IEnumerable`1 existingTypes, IReadOnlyDictionary`2 domainEventSerializerDeserializers) in C:\src\SalesOrder.EventStore\SalesOrder.EventStore.Infra.EventStore\Factories\EventTypeResolverFactory.cs:line 16
   at SalesOrder.EventStore.Infra.EventStore.Autofac.EventStoreExtensions.<>c__DisplayClass6_0.<RegisterResolvers>b__1(IComponentContext context) in C:\src\SalesOrder.EventStore\SalesOrder.EventStore.Infra.EventStore.Autofac\EventStoreExtensions.cs:line 180
   at Autofac.Builder.RegistrationBuilder.<>c__DisplayClass0_0`1.<ForDelegate>b__0(IComponentContext c, IEnumerable`1 p) in C:\projects\autofac\src\Autofac\Builder\RegistrationBuilder.cs:line 62
   at Autofac.Core.Activators.Delegate.DelegateActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters) in C:\projects\autofac\src\Autofac\Core\Activators\Delegate\DelegateActivator.cs:line 71
   at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters, Object& decoratorTarget) in C:\projects\autofac\src\Autofac\Core\Resolving\InstanceLookup.cs:line 118

This is the test with only one Fact that fails when running in parallel with others:

public class Given_A_Container_With_Event_Store_Registered_When_Resolving_An_IEventStore
    : Given_When_Then_Test
{
    private IEventStore _sut;
    private IComponentContext _componentContext;

    protected override void Given()
    {
        var builder = new ContainerBuilder();
        builder
            .RegisterEventStore(
                ctx =>
                {
                    var eventStoreOptions =
                        new EventStoreOptions
                        {
                            Url = EventStoreTestConstants.TestUrl,
                            Port = EventStoreTestConstants.TestPort
                        };
                    return eventStoreOptions;
                },
                ctx =>
                {
                    var readinessOptions =
                        new ReadinessOptions
                        {
                            Timeout = EventStoreTestConstants.TestTimeout
                        };
                    return readinessOptions;
                });

        var container = builder.Build();
        _componentContext = container.Resolve<IComponentContext>();
    }

    protected override void When()
    {
        _sut = _componentContext.Resolve<IEventStore>();
    }

    [Fact]
    public void Then_It_Should_Not_Be_Null()
    {
        _sut.Should().NotBeNull();
    }
}

Any clue what may be happening here?
I've had a look at Autofac's guidelines on concurrency: https://autofaccn.readthedocs.io/en/latest/advanced/concurrency.html but I think I am already using properly the component context.

UPDATE 1: FYI this is the GivenThenWhen template I use. But nothing very special here (I think!)

namespace ToolBelt.TestSupport
{
    public abstract class Given_When_Then_Test
        : IDisposable
    {
        protected Given_When_Then_Test()
        {
            Setup();
        }

        private void Setup()
        {
            Given();
            When();
        }

        protected abstract void Given();

        protected abstract void When();

        public void Dispose()
        {
            Cleanup();
        }

        protected virtual void Cleanup()
        {
        }
    }

    public abstract class Given_WhenAsync_Then_Test
        : IDisposable
    {
        protected Given_WhenAsync_Then_Test()
        {
            Task.Run(async () => { await SetupAsync(); }).GetAwaiter().GetResult();
        }

        private async Task SetupAsync()
        {
            Given();
            await WhenAsync();
        }

        protected abstract void Given();

        protected abstract Task WhenAsync();

        public void Dispose()
        {
            Cleanup();
        }

        protected virtual void Cleanup()
        {
        }
    }
}

UPDATE 2: And this is the IoCC Autofac registration's method I am using for my implementation and all the tests. A bit complex because I use reflection to keep the EventStore wrapper fully generic, but just in case somebody sees something funky there that might affect the tests..

public static class EventStoreExtensions
{
    public static void RegisterEventStore(
        this ContainerBuilder builder,
        Func<IComponentContext, EventStoreOptions> optionsRetriever,
        Func<IComponentContext, ReadinessOptions> readinessOptionsRetriever,
        Func<IComponentContext, CustomDomainEventMappersOptions> customDomainEventMappersOptionsRetriever = null)
    {
        RegisterEventStoreConnection(builder, optionsRetriever);
        RegisterFactories(builder);
        RegisterEventStoreManager(builder);
        RegisterConverters(builder);
        RegisterResolvers(builder, customDomainEventMappersOptionsRetriever);
        RegisterEventStoreServices(builder);
        RegisterEventStoreReadinessCheck(builder, readinessOptionsRetriever);
    }

    private static void RegisterEventStoreReadinessCheck(
        ContainerBuilder builder,
        Func<IComponentContext, ReadinessOptions> readinessOptionsRetriever)
    {
        builder
            .Register(context =>
            {
                var ctx = context.Resolve<IComponentContext>();
                var readinessOptions = readinessOptionsRetriever.Invoke(ctx);

                var timeout = readinessOptions.Timeout;
                var eventStoreConnection = context.Resolve<IEventStoreConnection>();

                var eventStoreReadiness =
                    new EventStoreReadiness(
                        eventStoreConnection,
                        timeout);

                return eventStoreReadiness;

            })
            .As<IEventStoreReadiness>()
            .As<IReadiness>()
            .SingleInstance();
    }

    private static void RegisterEventStoreConnection(
        ContainerBuilder builder,
        Func<IComponentContext, EventStoreOptions> optionsRetriever)
    {
        builder
            .Register(context =>
            {
                var ctx = context.Resolve<IComponentContext>();
                var eventStoreOptions = optionsRetriever.Invoke(ctx);

                ConnectionSettings connectionSetting =
                    ConnectionSettings
                        .Create()
                        .KeepReconnecting();

                var urlString = eventStoreOptions.Url;
                var port = eventStoreOptions.Port;
                var ipAddress = IPAddress.Parse(urlString);
                var tcpEndPoint = new IPEndPoint(ipAddress, port);

                var eventStoreConnection = EventStoreConnection.Create(connectionSetting, tcpEndPoint);
                return eventStoreConnection;
            })
            .As<IEventStoreConnection>()
            .SingleInstance();
    }

    private static void RegisterFactories(
        ContainerBuilder builder)
    {
        builder
            .RegisterType<DomainEventFactory>()
            .As<IDomainEventFactory>()
            .SingleInstance();

        builder
            .RegisterType<EventDataFactory>()
            .As<IEventDataFactory>()
            .SingleInstance();

        builder
            .RegisterType<ExpectedVersionFactory>()
            .As<IExpectedVersionFactory>()
            .SingleInstance();

        builder
            .RegisterType<IdFactory>()
            .As<IIdFactory>()
            .SingleInstance();

        builder
            .RegisterType<StreamNameFactory>()
            .As<IStreamNameFactory>()
            .SingleInstance();

        builder
            .RegisterType<RetrievedEventFactory>()
            .As<IRetrievedEventFactory>()
            .SingleInstance();
    }

    private static void RegisterEventStoreManager(ContainerBuilder builder)
    {
        builder
            .RegisterType<EventStoreManager>()
            .As<IEventStoreManager>()
            .SingleInstance();
    }

    private static void RegisterConverters(ContainerBuilder builder)
    {
        builder
            .Register(context =>
            {
                var utf8Encoding = new BytesConverter(Encoding.UTF8);
                return utf8Encoding;
            })
            .As<IBytesConverter>()
            .SingleInstance();

        builder
            .RegisterType<NewtonsoftConverter>()
            .As<IJsonConverter>()
            .SingleInstance();
    }

    private static void RegisterResolvers(
        ContainerBuilder builder,
        Func<IComponentContext, CustomDomainEventMappersOptions> customDomainEventMappersOptionsRetriever)
    {
        builder
            .Register(context =>
            {
                var ctx = context.Resolve<IComponentContext>();
                var customDomainEventMappersOptions = customDomainEventMappersOptionsRetriever?.Invoke(ctx);
                var domainEventSerializerDeserializers =
                    customDomainEventMappersOptions?.DomainEventSerializerDeserializers;
                var mapperResolver = MapperResolverFactory.Create(domainEventSerializerDeserializers);
                return mapperResolver;
            })
            .As<IMapperResolver>()
            .SingleInstance();

        builder
            .Register(context =>
            {
                var ctx = context.Resolve<IComponentContext>();

                var assembliesLoaded = AppDomain.CurrentDomain.GetAssemblies();
                var domainEventTypes =
                    assembliesLoaded
                        .SelectMany(s => s.GetTypes())
                        .Where(x => typeof(IDomainEvent).IsAssignableFrom(x)
                                    && x.IsClass);
                var customDomainEventMappersOptions = customDomainEventMappersOptionsRetriever?.Invoke(ctx);
                var domainEventSerializerDeserializers =
                    customDomainEventMappersOptions?.DomainEventSerializerDeserializers;
                var typeResolver =
                    EventTypeResolverFactory.Create(
                        domainEventTypes,
                        domainEventSerializerDeserializers);
                return typeResolver;
            })
            .As<IEventTypeResolver>()
            .SingleInstance();
    }

    private static void RegisterEventStoreServices(ContainerBuilder builder)
    {
        builder
            .RegisterType<EventStoreRepository>()
            .As<IEventStoreRepository>();

        builder
            .RegisterType<DomainEventsPersister>()
            .As<IDomainEventsPersister>();

        builder
            .RegisterType<DomainEventsRetriever>()
            .As<IDomainEventsRetriever>();

        builder
            .RegisterType<EventStore>()
            .As<IEventStore>();
    }
}

UPDATE 3: This is the whole repository in case somebody is bored and wants to try to reproduce it. It is a generic event store wrapper used for event sourcing implemented for Greg Young's Event Store product using the official C# driver.

https://gitlab.com/DiegoDrivenDesign/DiDrDe.EventStore

Funnily enough, this issue seems to disappear every once in a while. In fact, often, after restarting the PC all the tests pass properly. Other times it doesn't so I suspect it has something to do with the fact that I'm loading assemblies at runtime and something gets out of whack :(

UPDATE 9 Sep 2021
The async execution I was doing is not entirely correct. There is a way to embrace async execution with xUnit that may have been playing a role in this race condition. This is a better implementation of the given-when-then pattern all my tests inherit from. Thanks to IAsyncLifetime I am able to asynchronously (and await) the preconditions and the action itself.

using System.Threading.Tasks;
using Xunit;

namespace Rubiko.TestSupport.XUnit
{
    public abstract class Given_When_Then_Test_Async
        : IAsyncLifetime
    {
        public async Task InitializeAsync()
        {
            await Given();
            await When();
        }

        public async Task DisposeAsync()
        {
            await Cleanup();
        }

        protected virtual Task Cleanup()
        {
            return Task.CompletedTask;
        }

        protected abstract Task Given();

        protected abstract Task When();
    }
}


答:
You are using the wrong variable. empty is the method parameter which has method scope only. The class scope variable is isEmpty. You don't need to use this in this case.

use isEmpty = true;

In your scenario, you don't even need to pass the arguments in that method. Those variables are global and can be accessed without passing them as an argument. Also isEmpty is unnecessary when you could use arrayList.isEmpty()

Title: Function doesn't update the variable


问:
Automate entering text into a field where editable field is defined in angular and my test framework is selenium webdriverio
I am trying to enter text into a field in a form. The action on the field is defined in angular and I am not able to locate editable object. . Here is my code piece:

```<code>**Scenario**:
When I enter "xyz" into the "Headline" field
// Entering strings
When('I enter( the) {string} into the {string} field', enterText);
</code>```

```<code>**selection**
/**
 * Enters specific text into an element
 * @param {string} text The text to enter
 * @param {string} field The field key for an element
 * @returns {Promise<WebElement|Error>} The obtained element as a promise
 */
export async function enterText(text, field) {
  console.log('enter text 1');
  const element = getSelector(field);
  console.log(element);
  await World.browser.setValue(element, text);
</code>```

Code where text is to be entered is written in angular and text is being entered in
 tag not in  tag

I have tried using css as selector
div > storyline-editor > cue-storyline > div > cue-story-element-editor-container > mouse-handler > ng-transclude > div > cue-story-element-editor > cue-text-story-element-editor > mouse-handler > ng-transclude > cue-rte > div > div > p

If I use above selector in selenium IDE and run the code it works fine but it is not working for my framework

1) Checking New Article Page Elements14 I enter "Test Headline" into the "Headline" field:
[chrome #0-0] unknown error: cannot focus element

答:
You will see Failed: unknown error: cannot focus element error when you are trying to set values to an element which is not an input.

You need to set the focus or perform a click on the element before setting the value to it.

```<code>export async function enterText(text, field) {
console.log('enter text 1');
const element = getSelector(field);
console.log(element);
await element.click()
await World.browser.setValue(element, text);
</code>```

If that does not work use execute javascript method.

Body:
I am trying to enter text into a field in a form. The action on the field is defined in angular and I am not able to locate editable object. . Here is my code piece:

**Scenario**:
When I enter "xyz" into the "Headline" field
// Entering strings
When('I enter( the) {string} into the {string} field', enterText);

**selection**
/**
 * Enters specific text into an element
 * @param {string} text The text to enter
 * @param {string} field The field key for an element
 * @returns {Promise<WebElement|Error>} The obtained element as a promise
 */
export async function enterText(text, field) {
  console.log('enter text 1');
  const element = getSelector(field);
  console.log(element);
  await World.browser.setValue(element, text);

Code where text is to be entered is written in angular and text is being entered in
 tag not in  tag

I have tried using css as selector
div > storyline-editor > cue-storyline > div > cue-story-element-editor-container > mouse-handler > ng-transclude > div > cue-story-element-editor > cue-text-story-element-editor > mouse-handler > ng-transclude > cue-rte > div > div > p

If I use above selector in selenium IDE and run the code it works fine but it is not working for my framework

1) Checking New Article Page Elements14 I enter "Test Headline" into the "Headline" field:
[chrome #0-0] unknown error: cannot focus element

Body:
You will see Failed: unknown error: cannot focus element error when you are trying to set values to an element which is not an input.

You need to set the focus or perform a click on the element before setting the value to it.

export async function enterText(text, field) {
console.log('enter text 1');
const element = getSelector(field);
console.log(element);
await element.click()
await World.browser.setValue(element, text);

If that does not work use execute javascript method.


问:
How can I use gzip for my angular project?
I read some article about decreasing angular project size, in those articles I founded some solution but one of them was Obscure for me and that was gzipped compression, my question is how I can use gzip for my application?

If it helps you, I'm using asp.net core as my back-end technology.

答:
First, you need to install these two dev dependencies

```<code> "gulp": "^4.0.0",
"gulp-gzip": "^1.4.2",
</code>```

Create a postbuild script in your package.json

```<code>"postbuild": "gulp compress",
</code>```

Create a gulpfile.js file at the same level of package.json file with the following code

```<code>var gulp = require('gulp');
var gzip = require('gulp-gzip');

gulp.task('compress', function() {
    return new Promise(function(resolve, reject) {
        resolve(gulp.src(['./dist/**/*.*'])
        .pipe(gzip())
        .pipe(gulp.dest('./dist')));

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

Whenever you build your project this postbuild command will compress the files for after the build.

Body:
First, you need to install these two dev dependencies

 "gulp": "^4.0.0",
"gulp-gzip": "^1.4.2",

Create a postbuild script in your package.json

"postbuild": "gulp compress",

Create a gulpfile.js file at the same level of package.json file with the following code

var gulp = require('gulp');
var gzip = require('gulp-gzip');

gulp.task('compress', function() {
    return new Promise(function(resolve, reject) {
        resolve(gulp.src(['./dist/**/*.*'])
        .pipe(gzip())
        .pipe(gulp.dest('./dist')));

    })
});

Whenever you build your project this postbuild command will compress the files for after the build.