问:
Merge Partition Locking table in sql server
I have a BIG table with 400kk rows.

I want to partition this table but I`m having a problem when merging the two older Partition Functions.

I have this table:

```<code>CREATE TABLE [dbo].[PartitionDemo](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [myDate] [date] NOT NULL,
    [variable] [varchar](100) NULL,
 CONSTRAINT [pk_PartitionDemo] PRIMARY KEY CLUSTERED
(
    [myDate] ASC,
    [Id] ASC
)ON [PartitionDemo_PS](mydate)
)

CREATE PARTITION SCHEME [PartitionDemo_PS] AS PARTITION [PartitionDemo_PF] TO ([PartitionDemo_FG_Prev], [PartitionDemo_FG_Historical], [PartitionDemo_FG_201609], [PartitionDemo_FG_201610], [PartitionDemo_FG_201611], [PartitionDemo_FG_201612], [PartitionDemo_FG_201701], [PartitionDemo_FG_201702], [PartitionDemo_FG_201703], [PartitionDemo_FG_201704])
GO

CREATE PARTITION FUNCTION [PartitionDemo_PF](date) AS RANGE RIGHT FOR VALUES (N'2015-03-01T00:00:00.000', N'2016-09-01T00:00:00.000', N'2016-10-01T00:00:00.000', N'2016-11-01T00:00:00.000', N'2016-12-01T00:00:00.000', N'2017-01-01T00:00:00.000', N'2017-02-01T00:00:00.000', N'2017-03-01T00:00:00.000', N'2017-04-01T00:00:00.000')
GO
</code>```

This is my table with 400kk rows.

What I do to merge partition is:

```<code>CREATE TABLE [staging].[PartitionDemo](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [myDate] [date] NOT NULL,
    [variable] [varchar](100) NULL,
 CONSTRAINT [pk_PartitionDemo] PRIMARY KEY CLUSTERED
(
    [myDate] ASC,
    [Id] ASC
)ON [PartitionDemo_PS](mydate)
)
GO

ALTER TABLE PartitionDemo
SWITCH PARTITION 2 TO [staging].[PartitionDemo] PARTITION 2

ALTER TABLE PartitionDemo
SWITCH PARTITION 3 TO [staging].[PartitionDemo] PARTITION 3

ALTER PARTITION FUNCTION [PartitionDemo_PF]()
    MERGE RANGE ('2016-03-01');
</code>```

The problem is that it locks both tables while merging.

What is the workaround with this problem?

答:
If you remove the first boundary with this function and scheme, all data before 2015-03-01 will be moved to the PartitionDemo_FG_Prev filegroup instead of the PartitionDemo_FG_Historical filegroup as intended.  I recommend a NULL partition boundary to ensure the first partition is always empty.  This will also allow you to remove files from this unused filegroup and facilitate partition maintenance going forward. See http://www.dbdelta.com/table-partitioning-best-practices/ for more information on this practice.

A brief schema modification lock will be acquired during the SWITCH, MERGE, and SPLIT operations but those should fast meta-data operations because no data movement is needed. The physical data movement is done by the staging table CREATE INDEX...DROP_EXISTING-ON, which also avoids a sort to rebuild the index. This script acquires an exclusive table lock during the SWITCH, MERGE, and SPLIT operations to avoid deadlocking with other activity.

```<code>--create staging table exactly like original table
CREATE TABLE [staging].[PartitionDemo](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [myDate] [date] NOT NULL,
    [variable] [varchar](100) NULL,
 CONSTRAINT [pk_PartitionDemo] PRIMARY KEY CLUSTERED
    (
        [myDate] ASC,
        [Id] ASC
    ) ON [PartitionDemo_PS](mydate)
);

--create temporary partition function and scheme with desired end state
CREATE PARTITION FUNCTION [StagingPartitionDemo_PF](date) AS RANGE RIGHT FOR VALUES (
      CAST(NULL AS datetime)     --NULL boundary ensures first parttion is always empty
    , N'2016-09-01T00:00:00.000' --upper boundary of historical data fg (less than this date)
    , N'2016-10-01T00:00:00.000'
    , N'2016-11-01T00:00:00.000'
    , N'2016-12-01T00:00:00.000'
    , N'2017-01-01T00:00:00.000'
    , N'2017-02-01T00:00:00.000'
    , N'2017-03-01T00:00:00.000'
    , N'2017-04-01T00:00:00.000'
    );
CREATE PARTITION SCHEME [StagingPartitionDemo_PS] AS PARTITION [StagingPartitionDemo_PF] TO (
      [PartitionDemo_FG_Prev]
    , [PartitionDemo_FG_Historical]
    , [PartitionDemo_FG_201609]
    , [PartitionDemo_FG_201610]
    , [PartitionDemo_FG_201611]
    , [PartitionDemo_FG_201612]
    , [PartitionDemo_FG_201701]
    , [PartitionDemo_FG_201702]
    , [PartitionDemo_FG_201703]
    , [PartitionDemo_FG_201704]
    );
GO

SET XACT_ABORT ON;
BEGIN TRAN;

--acquire exclusive table lock to prevent deadlocking with concurrent activity
SELECT TOP(0) myDate FROM dboPartitionDemo WITH(TABLOCKX);

--switch first partition into staging (in case data exists before 2015-03-01)
ALTER TABLE dbo.PartitionDemo
    SWITCH PARTITION $PARTITION.PartitionDemo_PF(CAST(NULL AS datetime))
    TO [staging].[PartitionDemo] PARTITION $PARTITION.PartitionDemo_PF(CAST(NULL AS datetime));

--switch second partition into staging (on or after 2015-03-01 and before 2016-09-01)
ALTER TABLE dbo.PartitionDemo
    SWITCH PARTITION $PARTITION.PartitionDemo_PF('2015-03-01T00:00:00.000')
    TO [staging].[PartitionDemo] PARTITION $PARTITION.PartitionDemo_PF('2015-03-01T00:00:00.000');

--switch third partition into staging (on or after 2016-09-01 and before 2016-10-01)
ALTER TABLE dbo.PartitionDemo
    SWITCH PARTITION $PARTITION.PartitionDemo_PF('2016-09-01T00:00:00.000')
    TO [staging].[PartitionDemo] PARTITION $PARTITION.PartitionDemo_PF('2016-09-01T00:00:00.000');

COMMIT;
GO

--rebuild staging table on temporary partition scheme
CREATE UNIQUE CLUSTERED INDEX pk_PartitionDemo ON staging.PartitionDemo(
        [myDate] ASC,
        [Id] ASC
    )
WITH(DROP_EXISTING=ON)
ON [StagingPartitionDemo_PS](mydate);
GO

SET XACT_ABORT ON;
BEGIN TRAN;

--acquire exclusive table lock to prevent deadlocking with concurrent activity
SELECT TOP(0) myDate FROM dboPartitionDemo WITH(TABLOCKX);

--modify original partition scheme to match temporary one
ALTER PARTITION SCHEME PartitionDemo_PS
    NEXT USED PartitionDemo_FG_Historical;
ALTER PARTITION FUNCTION PartitionDemo_PF()
    SPLIT RANGE(CAST(NULL AS datetime));
ALTER PARTITION FUNCTION PartitionDemo_PF()
    MERGE RANGE('2015-03-01T00:00:00.000');

--switch historical data partition partition back to main table
ALTER TABLE staging.PartitionDemo
    SWITCH PARTITION $PARTITION.PartitionDemo_PF(NULL)
    TO dbo.[PartitionDemo] PARTITION $PARTITION.PartitionDemo_PF(CAST(NULL AS datetime));

--switch 2016-09-01 partition back to main table
ALTER TABLE staging.PartitionDemo
    SWITCH PARTITION $PARTITION.PartitionDemo_PF('2016-09-01T00:00:00.000')
    TO dbo.[PartitionDemo] PARTITION $PARTITION.PartitionDemo_PF('2016-09-01T00:00:00.000');

COMMIT;
GO
</code>```

Body:
I have a BIG table with 400kk rows.

I want to partition this table but I`m having a problem when merging the two older Partition Functions.

I have this table:

CREATE TABLE [dbo].[PartitionDemo](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [myDate] [date] NOT NULL,
    [variable] [varchar](100) NULL,
 CONSTRAINT [pk_PartitionDemo] PRIMARY KEY CLUSTERED
(
    [myDate] ASC,
    [Id] ASC
)ON [PartitionDemo_PS](mydate)
)

CREATE PARTITION SCHEME [PartitionDemo_PS] AS PARTITION [PartitionDemo_PF] TO ([PartitionDemo_FG_Prev], [PartitionDemo_FG_Historical], [PartitionDemo_FG_201609], [PartitionDemo_FG_201610], [PartitionDemo_FG_201611], [PartitionDemo_FG_201612], [PartitionDemo_FG_201701], [PartitionDemo_FG_201702], [PartitionDemo_FG_201703], [PartitionDemo_FG_201704])
GO

CREATE PARTITION FUNCTION [PartitionDemo_PF](date) AS RANGE RIGHT FOR VALUES (N'2015-03-01T00:00:00.000', N'2016-09-01T00:00:00.000', N'2016-10-01T00:00:00.000', N'2016-11-01T00:00:00.000', N'2016-12-01T00:00:00.000', N'2017-01-01T00:00:00.000', N'2017-02-01T00:00:00.000', N'2017-03-01T00:00:00.000', N'2017-04-01T00:00:00.000')
GO

This is my table with 400kk rows.

What I do to merge partition is:

CREATE TABLE [staging].[PartitionDemo](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [myDate] [date] NOT NULL,
    [variable] [varchar](100) NULL,
 CONSTRAINT [pk_PartitionDemo] PRIMARY KEY CLUSTERED
(
    [myDate] ASC,
    [Id] ASC
)ON [PartitionDemo_PS](mydate)
)
GO

ALTER TABLE PartitionDemo
SWITCH PARTITION 2 TO [staging].[PartitionDemo] PARTITION 2

ALTER TABLE PartitionDemo
SWITCH PARTITION 3 TO [staging].[PartitionDemo] PARTITION 3

ALTER PARTITION FUNCTION [PartitionDemo_PF]()
    MERGE RANGE ('2016-03-01');

The problem is that it locks both tables while merging.

What is the workaround with this problem?

Body:
If you remove the first boundary with this function and scheme, all data before 2015-03-01 will be moved to the PartitionDemo_FG_Prev filegroup instead of the PartitionDemo_FG_Historical filegroup as intended.  I recommend a NULL partition boundary to ensure the first partition is always empty.  This will also allow you to remove files from this unused filegroup and facilitate partition maintenance going forward. See http://www.dbdelta.com/table-partitioning-best-practices/ for more information on this practice.

A brief schema modification lock will be acquired during the SWITCH, MERGE, and SPLIT operations but those should fast meta-data operations because no data movement is needed. The physical data movement is done by the staging table CREATE INDEX...DROP_EXISTING-ON, which also avoids a sort to rebuild the index. This script acquires an exclusive table lock during the SWITCH, MERGE, and SPLIT operations to avoid deadlocking with other activity.

--create staging table exactly like original table
CREATE TABLE [staging].[PartitionDemo](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [myDate] [date] NOT NULL,
    [variable] [varchar](100) NULL,
 CONSTRAINT [pk_PartitionDemo] PRIMARY KEY CLUSTERED
    (
        [myDate] ASC,
        [Id] ASC
    ) ON [PartitionDemo_PS](mydate)
);

--create temporary partition function and scheme with desired end state
CREATE PARTITION FUNCTION [StagingPartitionDemo_PF](date) AS RANGE RIGHT FOR VALUES (
      CAST(NULL AS datetime)     --NULL boundary ensures first parttion is always empty
    , N'2016-09-01T00:00:00.000' --upper boundary of historical data fg (less than this date)
    , N'2016-10-01T00:00:00.000'
    , N'2016-11-01T00:00:00.000'
    , N'2016-12-01T00:00:00.000'
    , N'2017-01-01T00:00:00.000'
    , N'2017-02-01T00:00:00.000'
    , N'2017-03-01T00:00:00.000'
    , N'2017-04-01T00:00:00.000'
    );
CREATE PARTITION SCHEME [StagingPartitionDemo_PS] AS PARTITION [StagingPartitionDemo_PF] TO (
      [PartitionDemo_FG_Prev]
    , [PartitionDemo_FG_Historical]
    , [PartitionDemo_FG_201609]
    , [PartitionDemo_FG_201610]
    , [PartitionDemo_FG_201611]
    , [PartitionDemo_FG_201612]
    , [PartitionDemo_FG_201701]
    , [PartitionDemo_FG_201702]
    , [PartitionDemo_FG_201703]
    , [PartitionDemo_FG_201704]
    );
GO

SET XACT_ABORT ON;
BEGIN TRAN;

--acquire exclusive table lock to prevent deadlocking with concurrent activity
SELECT TOP(0) myDate FROM dboPartitionDemo WITH(TABLOCKX);

--switch first partition into staging (in case data exists before 2015-03-01)
ALTER TABLE dbo.PartitionDemo
    SWITCH PARTITION $PARTITION.PartitionDemo_PF(CAST(NULL AS datetime))
    TO [staging].[PartitionDemo] PARTITION $PARTITION.PartitionDemo_PF(CAST(NULL AS datetime));

--switch second partition into staging (on or after 2015-03-01 and before 2016-09-01)
ALTER TABLE dbo.PartitionDemo
    SWITCH PARTITION $PARTITION.PartitionDemo_PF('2015-03-01T00:00:00.000')
    TO [staging].[PartitionDemo] PARTITION $PARTITION.PartitionDemo_PF('2015-03-01T00:00:00.000');

--switch third partition into staging (on or after 2016-09-01 and before 2016-10-01)
ALTER TABLE dbo.PartitionDemo
    SWITCH PARTITION $PARTITION.PartitionDemo_PF('2016-09-01T00:00:00.000')
    TO [staging].[PartitionDemo] PARTITION $PARTITION.PartitionDemo_PF('2016-09-01T00:00:00.000');

COMMIT;
GO

--rebuild staging table on temporary partition scheme
CREATE UNIQUE CLUSTERED INDEX pk_PartitionDemo ON staging.PartitionDemo(
        [myDate] ASC,
        [Id] ASC
    )
WITH(DROP_EXISTING=ON)
ON [StagingPartitionDemo_PS](mydate);
GO

SET XACT_ABORT ON;
BEGIN TRAN;

--acquire exclusive table lock to prevent deadlocking with concurrent activity
SELECT TOP(0) myDate FROM dboPartitionDemo WITH(TABLOCKX);

--modify original partition scheme to match temporary one
ALTER PARTITION SCHEME PartitionDemo_PS
    NEXT USED PartitionDemo_FG_Historical;
ALTER PARTITION FUNCTION PartitionDemo_PF()
    SPLIT RANGE(CAST(NULL AS datetime));
ALTER PARTITION FUNCTION PartitionDemo_PF()
    MERGE RANGE('2015-03-01T00:00:00.000');

--switch historical data partition partition back to main table
ALTER TABLE staging.PartitionDemo
    SWITCH PARTITION $PARTITION.PartitionDemo_PF(NULL)
    TO dbo.[PartitionDemo] PARTITION $PARTITION.PartitionDemo_PF(CAST(NULL AS datetime));

--switch 2016-09-01 partition back to main table
ALTER TABLE staging.PartitionDemo
    SWITCH PARTITION $PARTITION.PartitionDemo_PF('2016-09-01T00:00:00.000')
    TO dbo.[PartitionDemo] PARTITION $PARTITION.PartitionDemo_PF('2016-09-01T00:00:00.000');

COMMIT;
GO


来源: stackexchange

问:
I can't put a CSS class on a template
I'm reading a book about Angular 2 and one of the chapters is about Forms. I'm using Semantic UI Framework and when I put a class, specify the "error" class the div is disappear. Is very very strange I don't know what happened. I have to mention what works perfectly if I replace "error" class with another like "negative" for instead.</p>

```<code>import { Component } from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  Validators,
  AbstractControl,
  FormControl
} from '@angular/forms';

@Component({
  selector: 'demo-form-sku-builder',
  template: `
  <div class="ui raised segment">
    <h2 class="ui header">Demo Form: Sku with Builder</h2>
    <form [formGroup]="myForm"
      (ngSubmit)="onSubmit(myForm.value)"
      class="ui form">

      <div class="field"
        [class.error]="!sku.valid && sku.touched">
        <label for="skuInput">SKU</label>
        <input type="text"
          id="skuInput"
          placeholder="SKU"
          [formControl]="myForm.controls['sku']">
        <div *ngIf="!sku.valid"
          class="ui error message">SKU is invalid</div>
        <div *ngIf="!sku.hasError('required')"
          class="ui error message">SKU is required</div>
      </div>

    <button type="submit" class="ui button">Submit</button>
    </form>
  </div>
  `
})
export class DemoFormSkuBuilder {
  myForm: FormGroup;
  sku: AbstractControl;

  constructor(fb: FormBuilder) {
    this.myForm = fb.group({
      'sku': ['', Validators.required]
    });

    this.sku = this.myForm.controls['sku'];
  }

  onSubmit(value: string): void {
    console.log('you submitted value: ', value);
  }
}
</code>```

答:
Use below code instead of [class.error]="!sku.valid && sku.touched"

```<code><div class="field" [ngClass]="{ 'error' : !sku.valid && sku.touched}">
</code>```

For more detail

Another way of doing is

```<code>import { Component } from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  Validators,
  AbstractControl,
  FormControl
} from '@angular/forms';

@Component({
  selector: 'demo-form-sku-builder',
  template: `
  <div class="ui raised segment">
    <h2 class="ui header">Demo Form: Sku with Builder</h2>
    <form #myForm=ngForm
      (submit)="onSubmit(myForm.value)"
      class="ui form">

      <div class="field"
      [ngClass]="{ 'error' : !sku.valid && sku.touched}">
        <label for="skuInput">SKU</label>
        <input type="text"
          id="skuInput"
          placeholder="SKU"
          name='sku'
          #sku='ngModel' ngModel
          required>
        <div *ngIf="!sku.valid"
          class="ui error message">SKU is invalid</div>
        <div *ngIf="!sku.touched && !sku.errors?.required"
          class="ui error message">SKU is required</div>
      </div>

    <button type="submit" class="ui button">Submit</button>
    </form>
  </div>
  `
})
export class DemoFormSkuBuilder {

  constructor() {
  }

  onSubmit(value: string): void {
    console.log('you submitted value: ', value);
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: I can't put a CSS class on a template

Body:
I'm reading a book about Angular 2 and one of the chapters is about Forms. I'm using Semantic UI Framework and when I put a class, specify the "error" class the div is disappear. Is very very strange I don't know what happened. I have to mention what works perfectly if I replace "error" class with another like "negative" for instead.

import { Component } from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  Validators,
  AbstractControl,
  FormControl
} from '@angular/forms';

@Component({
  selector: 'demo-form-sku-builder',
  template: `

Demo Form: Sku with Builder

    <form [formGroup]="myForm"
      (ngSubmit)="onSubmit(myForm.value)"
      class="ui form">

        SKU
        <input type="text"
          id="skuInput"
          placeholder="SKU"
          [formControl]="myForm.controls['sku']">

SKU is invalid

SKU is required

    <button type="submit" class="ui button">Submit</button>
    </form>

  `
})
export class DemoFormSkuBuilder {
  myForm: FormGroup;
  sku: AbstractControl;

  constructor(fb: FormBuilder) {
    this.myForm = fb.group({
      'sku': ['', Validators.required]
    });

    this.sku = this.myForm.controls['sku'];
  }

  onSubmit(value: string): void {
    console.log('you submitted value: ', value);
  }
}

Body:
Use below code instead of [class.error]="!sku.valid && sku.touched"

<div class="field" [ngClass]="{ 'error' : !sku.valid && sku.touched}">

For more detail

Another way of doing is

import { Component } from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  Validators,
  AbstractControl,
  FormControl
} from '@angular/forms';

@Component({
  selector: 'demo-form-sku-builder',
  template: `
  <div class="ui raised segment">
    <h2 class="ui header">Demo Form: Sku with Builder</h2>
    <form #myForm=ngForm
      (submit)="onSubmit(myForm.value)"
      class="ui form">

      <div class="field"
      [ngClass]="{ 'error' : !sku.valid && sku.touched}">
        <label for="skuInput">SKU</label>
        <input type="text"
          id="skuInput"
          placeholder="SKU"
          name='sku'
          #sku='ngModel' ngModel
          required>
        <div *ngIf="!sku.valid"
          class="ui error message">SKU is invalid</div>
        <div *ngIf="!sku.touched && !sku.errors?.required"
          class="ui error message">SKU is required</div>
      </div>

    <button type="submit" class="ui button">Submit</button>
    </form>
  </div>
  `
})
export class DemoFormSkuBuilder {

  constructor() {
  }

  onSubmit(value: string): void {
    console.log('you submitted value: ', value);
  }
}


问:
Correct way to use encryption in Xamarin shared project
I'm currently developing a Xamarin Forms Project and I need to use a few encryption methods that would normally be available through namespace System.Security.Cryptography namely RSACryptoServiceProvider. So far I have been using PCLCrypto nuget package to use other methods such MD5 hashing but I haven't figured out how to use RSA specifically. I was also wondering if it would be better to implement those methods directly on each native Project instead and then use them on the shared one instead of using the nuget.

Any thoughts on this? If someone could point me towards some documentation for PCLCrypto equivalent to what I need it would be fine as well, I just need some lights on this concern and some clarification since I've read some other questions but there isn't really a consensus.

答:
Because the Nuget package for Cryptography is not PCL friendly, you might want to utilize Xamarin.Forms DependencyService. You can implement those Crypto methods natively and just call the actual implementations via the DependencyService.

Create an interface in your PCL (e.g. ICrypto).

Create a method in that interface that, for example, validates a password (e.g. bool PasswordValid).

Add the Nuget package for System.Security.Cryptography to your native project.

Create a class in your native code that will implement that interface (e.g. Crypto_Android) and have an implementation for the method (e.g. bool PasswordValid)

Call this code from your PCL via DependencyService. The syntax would be something like this:

bool valid = DependencyService.Get< ICrypto >().PasswordValid(password);

NOTE: For the code on actual Cryptography you can check the PCLCrypto Github link provided above by Tifa.

A simple DependencyService example can be found here.


问:
SSIS Run multiple Execute Process tasks in parallel
I have a package that needs to run the separate Execute process task that make command line calls in parallel.

I have tested this and SSIS seems to only allow them to execute consecutively (One call waits for the before it finishes despite being in separate simultaneous flows)  Has anyone had any luck getting SSIS to run this in parallel

答:
Try adding a Sequence Container and inside it add multiple Execute process Task (separate tasks) and do not connect any task inside the container. Just connect the container with other items.

And check your Package MaxConcurrentExecutables property


问:
Create a calendar day table
I am trying to write a code where i can plug in a date and my table below will populate the expected date table with all the date for the particular month from CD1(Calendar Day 1) all the way to CD30 or CD31 or in February case CD28.  I know i should begin my code with something like

```<code>Declare @startdate as datetime
Set @startdate = '20170401'
</code>```

But after that I get confused with the DateAdd and DatePart code to create this query to produce the results

```date rule  | expected date |
----------------------------
| CD1      | 4/1/2017      |
| CD2      | 4/2/2017      |
| CD3      | 4/3/2017      |
| CD4      | 4/4/2017      |
| CD5      | 4/5/2017      |
| CD6      | 4/6/2017      |
```

Can anyone provide any assistance?

答:
```<code>DECLARE @startdate datetime = '2017-04-01'
DECLARE @startdate_for_loop datetime
SET @startdate_for_loop = @startdate

CREATE TABLE #T (date_rule nvarchar(100), exp_date datetime)
declare @x int = 1
WHILE MONTH(@startdate) = MONTH(@startdate_for_loop)
BEGIN
 INSERT INTO #T VALUES ('CD' + CAST(@x as nvarchar(max)), @startdate_for_loop)
 SET @x = @x + 1
 SET @startdate_for_loop = DATEADD(DD, 1, @startdate_for_loop)
END

SELECT * FROM #T
</code>```

Title: Create a calendar day table

Body:
I am trying to write a code where i can plug in a date and my table below will populate the expected date table with all the date for the particular month from CD1(Calendar Day 1) all the way to CD30 or CD31 or in February case CD28.  I know i should begin my code with something like

Declare @startdate as datetime
Set @startdate = '20170401'

But after that I get confused with the DateAdd and DatePart code to create this query to produce the results

date rule  | expected date |
----------------------------
| CD1      | 4/1/2017      |
| CD2      | 4/2/2017      |
| CD3      | 4/3/2017      |
| CD4      | 4/4/2017      |
| CD5      | 4/5/2017      |
| CD6      | 4/6/2017      |

Can anyone provide any assistance?


问:
Inconsistent behavior in JavaScript's conditional checking
I want to build an object obj1 with property obj2, which is another object.  To avoid redeclaring obj1 and obj2, I use the following code:

```<code>if (!obj1) obj1 = {};
if (!obj1.obj2) obj1.obj2 = {};
// code to use obj1
</code>```

Assume, obj1 and obj1.obj2 aren't defined yet, the code causes the browser to report the error "obj1 is not defined".

If I change the code to:

```<code>if (typeof obj1==='undefined') obj1 = {};
if (!obj1.obj2) obj1.obj2 = {};
// code to use obj1
</code>```

Then there's no error, while I think it should report "obj2 is not defined".  I'm puzzled as to why the JavaScript treats the short-hand falsy check of a reference and a property differently.  Can anyone shed a light on that?

答:
The "obj1" reference is not declared at all, as a result you get an error.

Use the following syntax for such kind of check:

```<code>var obj1 = obj1 || {};
</code>```

By the way:

```<code>if (typeof obj1==='undefined') obj1 = {};
</code>```

does not help if obj1 == null.

Don't declare global variables (without var).
And I strongly recommend you to read the JavaScript: The Definitive Guide, 5th Edition.
You may skip some chapters but pay your attention to Chapters 3, 7, 8, 9. They must be read and understood.

ContentLicense: CC BY-SA 2.5

Body:
I want to build an object obj1 with property obj2, which is another object.  To avoid redeclaring obj1 and obj2, I use the following code:

if (!obj1) obj1 = {};
if (!obj1.obj2) obj1.obj2 = {};
// code to use obj1

Assume, obj1 and obj1.obj2 aren't defined yet, the code causes the browser to report the error "obj1 is not defined".

If I change the code to:

if (typeof obj1==='undefined') obj1 = {};
if (!obj1.obj2) obj1.obj2 = {};
// code to use obj1

Then there's no error, while I think it should report "obj2 is not defined".  I'm puzzled as to why the JavaScript treats the short-hand falsy check of a reference and a property differently.  Can anyone shed a light on that?

Body:
The "obj1" reference is not declared at all, as a result you get an error.

Use the following syntax for such kind of check:

var obj1 = obj1 || {};

By the way:

if (typeof obj1==='undefined') obj1 = {};

does not help if obj1 == null.

Don't declare global variables (without var).
And I strongly recommend you to read the JavaScript: The Definitive Guide, 5th Edition.
You may skip some chapters but pay your attention to Chapters 3, 7, 8, 9. They must be read and understood.


问:
MS-Excel automatic increase number if text not same

As shown above picture i need put number on column B that automatic increase if text on column A not same so the the result would be

Can I do that with ms-excel?

答:
Using vba, assuming your working on the 1st sheet, you can use code like this:</p>

```<code>Sub uniqueIdx()

  Dim idx As Integer: idx = 1
  Dim c As Range

  With Sheets(1)
    For Each c In .Range("A1", .Cells(Rows.Count, 1).End(xlUp)):
      .Cells(c.row, 2).Value = idx
      If (c.Value <> c.Offset(1, 0).Value) Then idx = idx + 1
    Next
  End With

End Sub
</code>```

Body:
Using vba, assuming your working on the 1st sheet, you can use code like this:

Sub uniqueIdx()

  Dim idx As Integer: idx = 1
  Dim c As Range

  With Sheets(1)
    For Each c In .Range("A1", .Cells(Rows.Count, 1).End(xlUp)):
      .Cells(c.row, 2).Value = idx
      If (c.Value <> c.Offset(1, 0).Value) Then idx = idx + 1
    Next
  End With

End Sub


问:
I want to send argv from python without using command line prompt
I need to invoke visualstudio .exe file and also send a location on my computer as an argument to it from my python script.
NOTE: I know its easy doing it via command prompt, tried it and works fine. But I need to do it via scripts only.

P.S: Python Beginner.

Here is my code:

```<code>browse.filename = filedialog.askdirectory(initialdir=[("All files", "*")])
Path_Name = browse.filename
src_files = os.listdir(Path_Name)
Argument = Path_Name + '/' + src_files[x]
print (Argument)
subprocess.Popen("C:/Users/Kailash/Documents/Visual_Studio_2015/Projects/Python_Test/Debug/Python_Test.exe Argument")
</code>```

The last line open the location and executes the Python_Test.exe successfully but sends the argument as "Argument" only. But I need this to send Path_Name + '/' + src_files[x] which is actually a location on my computer.

I believe am missing something really small.

Any help is greatly appreciated!

答:
You've included Argument as part of the string. Instead do

subprocess.Popen("C:/Users/Kailash/Documents/Visual_Studio_2015/Projects/Python_Test/Debug/Python_Test.exe " + Argument)

BTW, normally you would make your variables start with a lowercase letter.

Body:
I need to invoke visualstudio .exe file and also send a location on my computer as an argument to it from my python script.
NOTE: I know its easy doing it via command prompt, tried it and works fine. But I need to do it via scripts only.

P.S: Python Beginner.

Here is my code:

browse.filename = filedialog.askdirectory(initialdir=[("All files", "*")])
Path_Name = browse.filename
src_files = os.listdir(Path_Name)
Argument = Path_Name + '/' + src_files[x]
print (Argument)
subprocess.Popen("C:/Users/Kailash/Documents/Visual_Studio_2015/Projects/Python_Test/Debug/Python_Test.exe Argument")

The last line open the location and executes the Python_Test.exe successfully but sends the argument as "Argument" only. But I need this to send Path_Name + '/' + src_files[x] which is actually a location on my computer.

I believe am missing something really small.

Any help is greatly appreciated!


问:
python encode error appears when there is Chinese in the string
Below code throw encode error:

```<code>import os

path = u"E:\\project\\robot_framework\\第一个测试项目\\logs\\log-20170330-094807.html"

os.system("scp "+path+" root@192.168.0.160:/root/jenkins/workspace/RobotFramework/logs/")
</code>```

error message:

Traceback (most recent call last):

```<code>  File "E:\project\robot_framework\PythonDemo\src\try.py", line 12, in <module>
    os.system("scp "+path+" root@192.168.0.160:/root/jenkins/workspace/RobotFramework/logs/")
UnicodeEncodeError: 'ascii' codec can't encode characters in position 31-37: ordinal not in range(128)
</code>```

答:
You can try to encode the string

```<code>import os

path = u"E:\\project\\robot_framework\\第一个测试项目\\logs\\log-20170330-094807.html".encode("utf-8")
os.system("scp "+path+" root@192.168.0.160:/root/jenkins/workspace/RobotFramework/logs/")
</code>```

Another way:

```<code>import sys
reload(sys)
sys.setdefaultencoding('utf-8')
</code>```

The above code maybe solve some encoding problems, but the use of sys.setdefaultencoding() is discouraged,

See more details from Unicode HOWTO.

Body:
Below code throw encode error:

import os

path = u"E:\\project\\robot_framework\\第一个测试项目\\logs\\log-20170330-094807.html"

os.system("scp "+path+" root@192.168.0.160:/root/jenkins/workspace/RobotFramework/logs/")

error message:

Traceback (most recent call last):

  File "E:\project\robot_framework\PythonDemo\src\try.py", line 12, in <module>
    os.system("scp "+path+" root@192.168.0.160:/root/jenkins/workspace/RobotFramework/logs/")
UnicodeEncodeError: 'ascii' codec can't encode characters in position 31-37: ordinal not in range(128)

Body:
You can try to encode the string

import os

path = u"E:\\project\\robot_framework\\第一个测试项目\\logs\\log-20170330-094807.html".encode("utf-8")
os.system("scp "+path+" root@192.168.0.160:/root/jenkins/workspace/RobotFramework/logs/")

Another way:

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

The above code maybe solve some encoding problems, but the use of sys.setdefaultencoding() is discouraged,

See more details from Unicode HOWTO.


问:
How can I animate the element when animation finished its sequence
I want to animate the parent-round-div when returning back to its original size. Is it possible to make animation after finishing its current animation?

This is my code:

```<code>.parent-round-div{
  position: absolute;
  border: 2px solid black;
  border-radius: 50%;
  width: 70px;
  height: 70px;
  background: green;
  -webkit-animation-name: sizeAnimate;
  -webkit-animation-duration: 2s ;
  -webkit-animation-iteration-count: infinite;
  animation-name: sizeAnimate;
  animation-duration: 2s;
  animation-iteration-count: infinite;
}
.child-round-div{
  margin:10%;
  position:relative;
  top: 40%;
  left: 40%;
  transform: translate(-50%, -50%);
  border: 1px solid black;
  border-radius: 50%;
  height: 70px;
  width:70px;
  font-size: 50px;
  text-align: center;
  background: red;
}
@-webkit-keyframes sizeAnimate{
  from{
    width: 70px;
    height: 70px;
  }
  to{
    width: 80px;
    height: 80px;
  }
}
@keyframes sizeAnimate{
  from{
    width:70px;
    height: 70px;
  }
  to{
    width: 80px;
    height: 80px;
  }
}

<div class = "parent-round-div">
  <div class="child-round-div">
    A
  </div>
</div>
</code>```

答:
To put a correct answer on my question rather than deleting the question, I copy and pasted the answer of Harry. (found on the jsfiddle link he commented)
This is his answer:

.parent-round-div {
  position: absolute;
  border: 2px solid black;
  border-radius: 50%;
  width: 70px;
  height: 70px;
  background: green;
  animation-name: sizeAnimate;
  animation-duration: 2s;
  animation-iteration-count: infinite;
}

.child-round-div {
  margin: 10%;
  position: relative;
  top: 40%;
  left: 40%;
  transform: translate(-50%, -50%);
  border: 1px solid black;
  border-radius: 50%;
  height: 70px;
  width: 70px;
  font-size: 50px;
  text-align: center;
  background: red;
}
@keyframes sizeAnimate {
  0%, 100% {
    width: 70px;
    height: 70px;
  }
  45%, 55% {
    width: 80px;
    height: 80px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent-round-div">
  <div class="child-round-div">
    A
  </div>
</div></code>```

Thank you!

Body:
I want to animate the parent-round-div when returning back to its original size. Is it possible to make animation after finishing its current animation?

This is my code:

.parent-round-div{
  position: absolute;
  border: 2px solid black;
  border-radius: 50%;
  width: 70px;
  height: 70px;
  background: green;
  -webkit-animation-name: sizeAnimate;
  -webkit-animation-duration: 2s ;
  -webkit-animation-iteration-count: infinite;
  animation-name: sizeAnimate;
  animation-duration: 2s;
  animation-iteration-count: infinite;
}
.child-round-div{
  margin:10%;
  position:relative;
  top: 40%;
  left: 40%;
  transform: translate(-50%, -50%);
  border: 1px solid black;
  border-radius: 50%;
  height: 70px;
  width:70px;
  font-size: 50px;
  text-align: center;
  background: red;
}
@-webkit-keyframes sizeAnimate{
  from{
    width: 70px;
    height: 70px;
  }
  to{
    width: 80px;
    height: 80px;
  }
}
@keyframes sizeAnimate{
  from{
    width:70px;
    height: 70px;
  }
  to{
    width: 80px;
    height: 80px;
  }
}

    A

Body:
To put a correct answer on my question rather than deleting the question, I copy and pasted the answer of Harry. (found on the jsfiddle link he commented)
This is his answer:

.parent-round-div {
  position: absolute;
  border: 2px solid black;
  border-radius: 50%;
  width: 70px;
  height: 70px;
  background: green;
  animation-name: sizeAnimate;
  animation-duration: 2s;
  animation-iteration-count: infinite;
}

.child-round-div {
  margin: 10%;
  position: relative;
  top: 40%;
  left: 40%;
  transform: translate(-50%, -50%);
  border: 1px solid black;
  border-radius: 50%;
  height: 70px;
  width: 70px;
  font-size: 50px;
  text-align: center;
  background: red;
}
@keyframes sizeAnimate {
  0%, 100% {
    width: 70px;
    height: 70px;
  }
  45%, 55% {
    width: 80px;
    height: 80px;
  }
}

<div class="parent-round-div">
  <div class="child-round-div">
    A
  </div>
</div>

Thank you!


问:
Unable to activate windows store app the app didn't start
First of all I would like to say that I already tried all the solutions I could find on the internet, including Unable to Activate Windows Store App

I recently upgraded my Windows 7 machine to Windows 8.1 to be capable of developing Windows Store apps using Visual Studio 2013. When I open a blank project (Windows Store -> Blank App) and run it I get this error:

Unable to activate Windows Store app 'Package Name'. The App1.exe
  process started, but the activation request failed with error 'The app
  didn't start'.

See help for advice on troubleshooting the issue.

I already tried:

Reinstalling Windows (Clean install)

Reinstalling Visual Studio 2013

Installing Visual Studio 2012 (same error)

Deleting "bin" and "obj" folder

Cleaning the solution

Uninstalling the app from start menu

Creating a new project

Acquiring the license multiple times (the license is valid)

Making sure that app.config doesn't exist

Investigating the Windows Event Log which says

Activation of the app 'Package Name' for the Windows.Launch contract failed with error: The app didn't start..

but found nothing useful

Adding a new Windows user

Run everything as administrator

and at last, changing the desktop background :)

None of this did bring a solution. Does anyone have an idea what else could be the reason for this error?

Thank you.

答:
In my solution, I have a non-UWP project (Multiplatform development) that builds with a different Solution Platform.

I was attempting to run the UWP project in Debug, but as the wrong Solution Platform.

Edit:
I also get this when I build my project for Any-CPU, instead of x64.


问:
Flex Layout: can width be 100% of the *visible* area of a larger container
I've got the following situation, where I have an outer Vbox that is set at a fixed width, and then inside it there is a header made from an HBox and a content area (Canvas) that is much wider than the enclosing VBox (and therefore requires scrollbars on the outer VBox to see it all).

I would like to set the width of the header to fill the entire width of the outer container, but only the visible part, and to remain fixed so that when I scroll to view the content, the header doesn't move.

Can anyone tell me how I can acomplish this please

```<code>    ______________________________
   |  _________________________   |
   | |_________________________|  |
   |                     |
   |  ____________________________|_ _ _ _ _
   | |                            |         |
   | |                            |         |
   | |                            |         |
   | |                            |         |
   |  ---------------------------------------
   |                              |
   |______________________________|
   |<|__________________________|>|
</code>```

答:
Use Group as a wrapper:</p>

```<code><Child1/>

<s:Group width="100%">
    <Child2 left="0" right="0'/>
</s:Group>

<Child3/>
</code>```

Body:
I've got the following situation, where I have an outer Vbox that is set at a fixed width, and then inside it there is a header made from an HBox and a content area (Canvas) that is much wider than the enclosing VBox (and therefore requires scrollbars on the outer VBox to see it all).

I would like to set the width of the header to fill the entire width of the outer container, but only the visible part, and to remain fixed so that when I scroll to view the content, the header doesn't move.

Can anyone tell me how I can acomplish this please

    ______________________________
   |  _________________________   |
   | |_________________________|  |
   |                     |
   |  ____________________________|_ _ _ _ _
   | |                            |         |
   | |                            |         |
   | |                            |         |
   | |                            |         |
   |  ---------------------------------------
   |                              |
   |______________________________|
   |<|__________________________|>|

Body:
Use Group as a wrapper:

<Child1/>

<s:Group width="100%">
    <Child2 left="0" right="0'/>
</s:Group>

<Child3/>


问:
Confusing about Custom Post Type Category and taxonomies
I created three Custom Post Types, one of them is called "TV". I also created a category in the WP dashboard that appears in all those three Custom Post Types as well the "Posts" too. I assigned several posts from those Custom Post Types and Posts to the category. However, when I tried to display the category both in "the_query" loop and the Category Posts Widget plugin, the category did not display the posts from the Custom Post Types. It only display posts that was from the "Posts".

I looked online and the Wordpress Codex in https://codex.wordpress.org/Function_Reference/register_post_type said that "When registering a post type, always register your taxonomies using the taxonomies argument".

I don't really get it. I thought that Taxonomy is same as Category, right? And that it's already called in register_post_type() when I added taxonomies' => array( 'category', 'post_tag' ) in this code below:

```<code>// Register Custom Post Type
function tvs_post_type() {

    $labels = array(
        'name'                  => _x( 'TV', 'Post Type General Name', 'text_domain' ),
        'singular_name'         => _x( 'TV', 'Post Type Singular Name', 'text_domain' ),
        'menu_name'             => __( 'TV', 'text_domain' ),
        'name_admin_bar'        => __( 'Post Type', 'text_domain' ),
        'archives'              => __( 'Item Archives', 'text_domain' ),
        'parent_item_colon'     => __( 'Parent TV:', 'text_domain' ),
        'all_items'             => __( 'All TVs', 'text_domain' ),
        'add_new_item'          => __( 'Add New Post', 'text_domain' ),
        'add_new'               => __( 'Add New Post', 'text_domain' ),
        'new_item'              => __( 'New Item', 'text_domain' ),
        'edit_item'             => __( 'Edit Post', 'text_domain' ),
        'update_item'           => __( 'Update Post', 'text_domain' ),
        'view_item'             => __( 'View Post', 'text_domain' ),
        'search_items'          => __( 'Search Posts', 'text_domain' ),
        'not_found'             => __( 'No posts found', 'text_domain' ),
        'not_found_in_trash'    => __( 'Not posts found in Trash', 'text_domain' ),
        'featured_image'        => __( 'Featured Image', 'text_domain' ),
        'set_featured_image'    => __( 'Set featured image', 'text_domain' ),
        'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),
        'use_featured_image'    => __( 'Use as featured image', 'text_domain' ),
        'insert_into_item'      => __( 'Insert into item', 'text_domain' ),
        'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ),
        'items_list'            => __( 'Items list', 'text_domain' ),
        'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
        'filter_items_list'     => __( 'Filter items list', 'text_domain' ),
    );
    $args = array(
        'label'                 => __( 'TV', 'text_domain' ),
        'description'           => __( 'tv information pages', 'text_domain' ),
        'labels'                => $labels,
        'supports'              => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'custom-fields', ),
        'taxonomies'            => array( 'category', 'post_tag' ),
        'hierarchical'          => false,
        'public'                => true,
        'show_ui'               => true,
        'show_in_menu'          => true,
        'menu_position'         => 5,
        'show_in_admin_bar'     => true,
        'show_in_nav_menus'     => true,
        'can_export'            => true,
        'has_archive'           => true,
        'exclude_from_search'   => false,
        'publicly_queryable'    => true,
        'capability_type'       => 'page',
    );
    register_post_type( 'tv', $args );

}
add_action( 'init', 'tvs_post_type', 0 );
</code>```

Help? So confused....

答:
Never mind. I figured most of it out. What is need to call the category for the Custom Post Types is to add post_type to the query as in

```<code><?php
    $args = array (
        'cat'              => 3,
        'post_type'        => array( 'post', 'tv', 'print', 'radio' ), //defined the post type. The default is post.
        'posts_per_page'   => 3
    );

     $the_query = new WP_Query( $args ); ?>
            <?php if ( $the_query->have_posts() ) : ?>

        <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
           <?php the_title(); ?>
        <?php endwhile;  ?>

    <?php endif;
     wp_reset_postdata();
    ?>
</code>```

As for the Category Posts Widget plugin, it looks like it only display the posts with the post_type => post in the query, I think? So I went with Ultimate Posts Widget plugin and it works.

Body:
I created three Custom Post Types, one of them is called "TV". I also created a category in the WP dashboard that appears in all those three Custom Post Types as well the "Posts" too. I assigned several posts from those Custom Post Types and Posts to the category. However, when I tried to display the category both in "the_query" loop and the Category Posts Widget plugin, the category did not display the posts from the Custom Post Types. It only display posts that was from the "Posts".

I looked online and the Wordpress Codex in https://codex.wordpress.org/Function_Reference/register_post_type said that "When registering a post type, always register your taxonomies using the taxonomies argument".

I don't really get it. I thought that Taxonomy is same as Category, right? And that it's already called in register_post_type() when I added taxonomies' => array( 'category', 'post_tag' ) in this code below:

// Register Custom Post Type
function tvs_post_type() {

    $labels = array(
        'name'                  => _x( 'TV', 'Post Type General Name', 'text_domain' ),
        'singular_name'         => _x( 'TV', 'Post Type Singular Name', 'text_domain' ),
        'menu_name'             => __( 'TV', 'text_domain' ),
        'name_admin_bar'        => __( 'Post Type', 'text_domain' ),
        'archives'              => __( 'Item Archives', 'text_domain' ),
        'parent_item_colon'     => __( 'Parent TV:', 'text_domain' ),
        'all_items'             => __( 'All TVs', 'text_domain' ),
        'add_new_item'          => __( 'Add New Post', 'text_domain' ),
        'add_new'               => __( 'Add New Post', 'text_domain' ),
        'new_item'              => __( 'New Item', 'text_domain' ),
        'edit_item'             => __( 'Edit Post', 'text_domain' ),
        'update_item'           => __( 'Update Post', 'text_domain' ),
        'view_item'             => __( 'View Post', 'text_domain' ),
        'search_items'          => __( 'Search Posts', 'text_domain' ),
        'not_found'             => __( 'No posts found', 'text_domain' ),
        'not_found_in_trash'    => __( 'Not posts found in Trash', 'text_domain' ),
        'featured_image'        => __( 'Featured Image', 'text_domain' ),
        'set_featured_image'    => __( 'Set featured image', 'text_domain' ),
        'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),
        'use_featured_image'    => __( 'Use as featured image', 'text_domain' ),
        'insert_into_item'      => __( 'Insert into item', 'text_domain' ),
        'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ),
        'items_list'            => __( 'Items list', 'text_domain' ),
        'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
        'filter_items_list'     => __( 'Filter items list', 'text_domain' ),
    );
    $args = array(
        'label'                 => __( 'TV', 'text_domain' ),
        'description'           => __( 'tv information pages', 'text_domain' ),
        'labels'                => $labels,
        'supports'              => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'custom-fields', ),
        'taxonomies'            => array( 'category', 'post_tag' ),
        'hierarchical'          => false,
        'public'                => true,
        'show_ui'               => true,
        'show_in_menu'          => true,
        'menu_position'         => 5,
        'show_in_admin_bar'     => true,
        'show_in_nav_menus'     => true,
        'can_export'            => true,
        'has_archive'           => true,
        'exclude_from_search'   => false,
        'publicly_queryable'    => true,
        'capability_type'       => 'page',
    );
    register_post_type( 'tv', $args );

}
add_action( 'init', 'tvs_post_type', 0 );

Help? So confused....

Body:
Never mind. I figured most of it out. What is need to call the category for the Custom Post Types is to add post_type to the query as in

<?php
    $args = array (
        'cat'              => 3,
        'post_type'        => array( 'post', 'tv', 'print', 'radio' ), //defined the post type. The default is post.
        'posts_per_page'   => 3
    );

     $the_query = new WP_Query( $args ); ?>
            <?php if ( $the_query->have_posts() ) : ?>

        <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
           <?php the_title(); ?>
        <?php endwhile;  ?>

    <?php endif;
     wp_reset_postdata();
    ?>

As for the Category Posts Widget plugin, it looks like it only display the posts with the post_type => post in the query, I think? So I went with Ultimate Posts Widget plugin and it works.


问:
Angular 2 keyframe animation with properties with hyphens
I am trying to re-create this animation on my component: https://github.com/daneden/animate.css/blob/master/source/zooming_exits/zoomOutUp.css

I can't find any examples of using easing on keyframes.  The only easing example I can see is for a single step and it works by passing in a string instead of a number for the animation duration i.e animate(1s 1s ease).

What is the proper way to add in properties that have hyphens in them and do easing with keyframes?

The docs only has a few properties so I am not even sure if this is doing it the right way but it appears to work but I think it might not actually using the easing and transform origin specified.

This is what I tried:

```<code>transition('* => unloaded', [
    animate(1000, keyframes([
        style({
            opacity: 1,
            transform: 'scale3d(.475, .475, .475) translate3d(0, 60px, 0)',
           'animation-timing-function': 'cubic-bezier(0.550, 0.055, 0.675, 0.190)',
            offset: 0.4
        }),
        style({
            opacity: 0,
            transform: 'scale3d(.1, .1, .1) translate3d(0, -2000px, 0)',
            'transform-origin': 'center bottom',
            'animation-timing-function': 'cubic-bezier(0.175, 0.885, 0.320, 1)',
            offset: 1
        })
    ]))
])
</code>```

It works but it doesn't look like the animate.css animation.  I don't think it's taking all settings.

What is the right way to do this?

答:
As mentioned in the comments, instead of hyphens you will use camel case (ie: transformOrigin) as this is what JavaScript understands.

Additionally, it sounds like you need to utilize states to achieve your desired easing animation effects. After you define states, you can define transitions between the states. Each transition controls the timing of switching between one set of styles and the next:

```<code>transition('inactive => active',
animate('100ms ease-in')),
transition('active => inactive',
animate('100ms ease-out'))
</code>```

Take a look at the Angular2 Animation Documentation as it goes into great detail on this.

Body:
I am trying to re-create this animation on my component: https://github.com/daneden/animate.css/blob/master/source/zooming_exits/zoomOutUp.css

I can't find any examples of using easing on keyframes.  The only easing example I can see is for a single step and it works by passing in a string instead of a number for the animation duration i.e animate(1s 1s ease).

What is the proper way to add in properties that have hyphens in them and do easing with keyframes?

The docs only has a few properties so I am not even sure if this is doing it the right way but it appears to work but I think it might not actually using the easing and transform origin specified.

This is what I tried:

transition('* => unloaded', [
    animate(1000, keyframes([
        style({
            opacity: 1,
            transform: 'scale3d(.475, .475, .475) translate3d(0, 60px, 0)',
           'animation-timing-function': 'cubic-bezier(0.550, 0.055, 0.675, 0.190)',
            offset: 0.4
        }),
        style({
            opacity: 0,
            transform: 'scale3d(.1, .1, .1) translate3d(0, -2000px, 0)',
            'transform-origin': 'center bottom',
            'animation-timing-function': 'cubic-bezier(0.175, 0.885, 0.320, 1)',
            offset: 1
        })
    ]))
])

It works but it doesn't look like the animate.css animation.  I don't think it's taking all settings.

What is the right way to do this?

Body:
As mentioned in the comments, instead of hyphens you will use camel case (ie: transformOrigin) as this is what JavaScript understands.

Additionally, it sounds like you need to utilize states to achieve your desired easing animation effects. After you define states, you can define transitions between the states. Each transition controls the timing of switching between one set of styles and the next:

transition('inactive => active',
animate('100ms ease-in')),
transition('active => inactive',
animate('100ms ease-out'))

Take a look at the Angular2 Animation Documentation as it goes into great detail on this.


问:
Problems extending my Django user model
I have a simple django app, and am trying to set up a custom Django User Model so that I can have users log in with their email field.  I think I set everything up well enough, its all fairly straightforward, however when trying to actually run the migrations I get this error:

```<code>django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial
</code>```

Seems weird?

I'm having trouble understanding why it's having trouble understanding.

Heres the User model Im implementing

```<code>from __future__ import unicode_literals

from django.db import models
from django.core.mail import send_mail
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from django.utils.translation import ugettext_lazy as _

from .managers import UserManager

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    display_name = models.CharField(_('display name'), max_length=30, blank=True)
    bio = models.TextField(blank=True)
    date_joined = models.DateTimeField(_('date joined'), auto_now_add=True)
    is_active = models.BooleanField(_('active'), default=True)
    avatar = models.ImageField(upload_to='avatars/', null=True, blank=True)

objects = UserManager()

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []

class Meta:
    verbose_name = _('user')
    verbose_name_plural = _('users')

def get_full_name(self):
    '''
    Returns the first_name plus the last_name, with a space in between.
    '''
    full_name = '%s %s' % (self.first_name, self.last_name)
    return full_name.strip()

def get_short_name(self):
    '''
    Returns the short name for the user.
    '''
    return self.first_name

def email_user(self, subject, message, from_email=None, **kwargs):
    '''
    Sends an email to this User.
    '''
    send_mail(subject, message, from_email, [self.email], **kwargs)
</code>```

答:
Basically, you have already created some User accounts or at least have created superuser account. Since you are changing the User model after I assume you have already made migrations at least once, Django has conflict with old user model with the new one.

Solution is to delete all accounts in admin including superuser. Then delete your migrations files in migrations folder. And also I think delete your sqlite data file. Run migrations again and it should work.

You should have created custom user model before any migration.

Title: Problems extending my Django user model

Body:
I have a simple django app, and am trying to set up a custom Django User Model so that I can have users log in with their email field.  I think I set everything up well enough, its all fairly straightforward, however when trying to actually run the migrations I get this error:

django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency accounts.0001_initial

Seems weird?

I'm having trouble understanding why it's having trouble understanding.

Heres the User model Im implementing

from __future__ import unicode_literals

from django.db import models
from django.core.mail import send_mail
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from django.utils.translation import ugettext_lazy as _

from .managers import UserManager

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('email address'), unique=True)
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    display_name = models.CharField(_('display name'), max_length=30, blank=True)
    bio = models.TextField(blank=True)
    date_joined = models.DateTimeField(_('date joined'), auto_now_add=True)
    is_active = models.BooleanField(_('active'), default=True)
    avatar = models.ImageField(upload_to='avatars/', null=True, blank=True)

objects = UserManager()

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []

class Meta:
    verbose_name = _('user')
    verbose_name_plural = _('users')

def get_full_name(self):
    '''
    Returns the first_name plus the last_name, with a space in between.
    '''
    full_name = '%s %s' % (self.first_name, self.last_name)
    return full_name.strip()

def get_short_name(self):
    '''
    Returns the short name for the user.
    '''
    return self.first_name

def email_user(self, subject, message, from_email=None, **kwargs):
    '''
    Sends an email to this User.
    '''
    send_mail(subject, message, from_email, [self.email], **kwargs)


问:
Remove odd numbers in array
I am trying to come up with another way to remove all of the odd numbers from an array. A friend was able to come up with this solution and I understand what it does, but I am failing to find another solution to it. Do you have any ideas for another solution to do this?

JavaScript

```<code>let myArray = [1,3,5,7,9,2,4,6,8];
let it = myArray.length;

for(let i=0; i<it; i++) {
  for(let j=0; j<myArray.length; j++ )
    if(myArray[j]%2 === 1){
      myArray.splice(j,1)
      break;
    }
  };

  console.log(myArray);
</code>```

答:
let myArray = [1, 3, 5, 7, 9, 2, 4, 6, 8];

myArray = myArray.filter(e => e % 2 === 0)

console.log(myArray);```

Title: Remove odd numbers in array

Body:
I am trying to come up with another way to remove all of the odd numbers from an array. A friend was able to come up with this solution and I understand what it does, but I am failing to find another solution to it. Do you have any ideas for another solution to do this?

JavaScript

let myArray = [1,3,5,7,9,2,4,6,8];
let it = myArray.length;

for(let i=0; i<it; i++) {
  for(let j=0; j<myArray.length; j++ )
    if(myArray[j]%2 === 1){
      myArray.splice(j,1)
      break;
    }
  };

  console.log(myArray);


问:
python regex to find the substring from the string
I have a string:

```<code> <robot generated="20170330 17:19:11.956" generator="Robot 3.0.2 (Python 2.7.13 on win32)">
</code>```

I want to get the value of "generated", but with below code, it doesn't work

```<code>import re
doc=r'<robot generated="20170330 17:19:11.956" generator="Robot 3.0.2 (Python 2.7.13 on win32)">'
match = re.match(r'generated="(\d+ \d+:\d+:\d+.\d+)',doc)
</code>```

the value of match is none. can anyone help?

答:
You don't necessarily need regular expressions in this case. Here is an alternative idea that uses BeautifulSoup XML/HTML parser with dateutil datetime parser:

```<code>In [1]: from dateutil.parser import parse

In [2]: from bs4 import BeautifulSoup

In [3]: data = '<robot generated="20170330 17:19:11.956" generator="Robot 3.0.2 (Python 2.7.13 on win32)">'

In [4]: parse(BeautifulSoup(data, "html.parser").robot['generated'])
Out[4]: datetime.datetime(2017, 3, 30, 17, 19, 11, 956000)
</code>```

I find this approach beautiful, easy and straightforward.

Body:
I have a string:

 <robot generated="20170330 17:19:11.956" generator="Robot 3.0.2 (Python 2.7.13 on win32)">

I want to get the value of "generated", but with below code, it doesn't work

import re
doc=r'<robot generated="20170330 17:19:11.956" generator="Robot 3.0.2 (Python 2.7.13 on win32)">'
match = re.match(r'generated="(\d+ \d+:\d+:\d+.\d+)',doc)

the value of match is none. can anyone help?

Body:
You don't necessarily need regular expressions in this case. Here is an alternative idea that uses BeautifulSoup XML/HTML parser with dateutil datetime parser:

In [1]: from dateutil.parser import parse

In [2]: from bs4 import BeautifulSoup

In [3]: data = '<robot generated="20170330 17:19:11.956" generator="Robot 3.0.2 (Python 2.7.13 on win32)">'

In [4]: parse(BeautifulSoup(data, "html.parser").robot['generated'])
Out[4]: datetime.datetime(2017, 3, 30, 17, 19, 11, 956000)

I find this approach beautiful, easy and straightforward.


问:
PHP, MYSQL, phpmyadmin - Using a html form to input records to a database
My objective is to have two separate php pages.One page is for a user to input data into form fields (first name, last name, product, size), and the other is to display the updated table (after the user submits their fields).
So far, I have created the two pages, with a functional form and a page that displays my tables results. Here is my code:

Form.php

```<code><form action="process.php" method="post">
<p>
First Name:<input type="text" name="first_name"><br>
Last Name:<input type="text" name="last_name"><br>
Product:<input type="text" name="product"><br>
Size:<input type="text" name="size"><br>
</p>
<input type="submit" name="submit">
</form>

<?php
if (isset($POST['submit'])) {
    $con = mysql_connect("localhost","username","password");
if (!$con){
die("Connection was not successful:" . mysql_error());
}
mysql_select_db("database_name",$con);

$sql = "INSERT INTO Order_1 (First_Name, Last_Name, Product, Size) VALUES ('$_POST[first_name]','$_POST[last_name]','$_POST[product]','$_POST[size]')";

$myData = mysql_query($sql,$con);

mysql_close($con);
}
?>
</code>```

And here is my results.php page, which displays my table:

```<code><?php

$con = mysql_connect("localhost","username","password");
if (!$con){
die("Connection was not successful:" . mysql_error());
}
mysql_select_db("database name",$con);
$sql = "SELECT * FROM Order_1";
$myData = mysql_query($sql,$con);
echo "<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Product</th>
<th>Size</th>
</tr>";

while($record = mysql_fetch_array($myData)){
echo "<tr>";
echo "<td>" . $record['First Name'] . "</td>";
echo "<td>" . $record['Last Name'] . "</td>";
echo "<td>" . $record['Product'] . "</td>";
echo "<td>" . $record['Size'] . "</td>";
echo "</tr>";
}
echo"</table>";
mysql_close($con);

?>
</code>```

I currently have two records in my table, that I manually typed into phpmyadmin. When i fill out this form, and click submit, it takes me to the "process.php" but nothing has changed. It's still only displaying the two records I have. And inside my PHPmyAdmin, it only has those two records. So my form isn't working how i'd like -- inputting a record submitted from the form, from a user, and displaying the entire table, included the record just recorded from the user, on the "process.php" code.
I have gone over my code for (oh my god its been 4 hours now) and I can't find the solution. I've tested numerous things. Can anyone help? It'd be much appreciated.

答:
```<code>$sql = "INSERT INTO Order_1 (First_Name, Last_Name, Product, Size) VALUES ('".$_POST[first_name]."','".$_POST[last_name]."','".$_POST[product]."','".$_POST[size]."')";
</code>```

You forgot to concatenate the variable inside your query that is why it is not inserting.

Body:
My objective is to have two separate php pages.One page is for a user to input data into form fields (first name, last name, product, size), and the other is to display the updated table (after the user submits their fields).
So far, I have created the two pages, with a functional form and a page that displays my tables results. Here is my code:

Form.php

<form action="process.php" method="post">

First Name:<input type="text" name="first_name">

Last Name:<input type="text" name="last_name">

Product:<input type="text" name="product">

Size:<input type="text" name="size">

<input type="submit" name="submit">
</form>

<?php
if (isset($POST['submit'])) {
    $con = mysql_connect("localhost","username","password");
if (!$con){
die("Connection was not successful:" . mysql_error());
}
mysql_select_db("database_name",$con);

$sql = "INSERT INTO Order_1 (First_Name, Last_Name, Product, Size) VALUES ('$_POST[first_name]','$_POST[last_name]','$_POST[product]','$_POST[size]')";

$myData = mysql_query($sql,$con);

mysql_close($con);
}
?>

And here is my results.php page, which displays my table:

<?php

$con = mysql_connect("localhost","username","password");
if (!$con){
die("Connection was not successful:" . mysql_error());
}
mysql_select_db("database name",$con);
$sql = "SELECT * FROM Order_1";
$myData = mysql_query($sql,$con);
echo "

First Name
Last Name
Product
Size

";

while($record = mysql_fetch_array($myData)){
echo "
";
echo "" . $record['First Name'] . "	";
echo "" . $record['Last Name'] . "	";
echo "" . $record['Product'] . "	";
echo "" . $record['Size'] . "	";
echo "
";
}
echo"
";
mysql_close($con);

?>

I currently have two records in my table, that I manually typed into phpmyadmin. When i fill out this form, and click submit, it takes me to the "process.php" but nothing has changed. It's still only displaying the two records I have. And inside my PHPmyAdmin, it only has those two records. So my form isn't working how i'd like -- inputting a record submitted from the form, from a user, and displaying the entire table, included the record just recorded from the user, on the "process.php" code.
I have gone over my code for (oh my god its been 4 hours now) and I can't find the solution. I've tested numerous things. Can anyone help? It'd be much appreciated.

Body:
$sql = "INSERT INTO Order_1 (First_Name, Last_Name, Product, Size) VALUES ('".$_POST[first_name]."','".$_POST[last_name]."','".$_POST[product]."','".$_POST[size]."')";

You forgot to concatenate the variable inside your query that is why it is not inserting.


问:
Conditional mutating with dplyr for only some rows
I use ifelse with mutate to conditionally change variable names within a column. For example:

```<code>mutate(df, thiscol = ifelse((new == "oldname"), "newname", NA)
</code>```

But I would like to change it so that instead of variables that don't fit the conditions turning into NA, they just stay as they were.

答:
If we need to change only some elements and keep the rest as the same, then another option is replace

```<code>df %>%
    mutate(thiscol = replace(thiscol, new == "oldname", "newname"))
</code>```

Body:
I use ifelse with mutate to conditionally change variable names within a column. For example:

mutate(df, thiscol = ifelse((new == "oldname"), "newname", NA)

But I would like to change it so that instead of variables that don't fit the conditions turning into NA, they just stay as they were.

Body:
If we need to change only some elements and keep the rest as the same, then another option is replace

df %>%
    mutate(thiscol = replace(thiscol, new == "oldname", "newname"))


问:
Sorting PHP Array by Integer Values while keeping Key
I have an array like this

```<code>[Title 1] => 2
[Title 2] => 4
[Title 3] => 3
[Title 4] => 1
</code>```

All I'm trying to do is sort the integer value in the array, to get an output like this:

```<code>[Title 2] => 4
[Title 3] => 3
[Title 1] => 2
[Title 4] => 1
</code>```

I don't think it matters, but my array is created by the array_count_values function.

```<code>$array = array_count_values($originalarray);
</code>```

I've looked through the manual on PHP: Array Sorting but can't get anything to work.

I've tried a few things that look like they might work.

```<code>$newarray = arsort($array);
</code>```

This just outputs 1

same with rsort.

The closest I've come is by using array_multisort by using it as such:

```<code>$array = array_count_values($originalarray);
$newarray = array_multisort($array, SORT_NUMERIC, SORT_DESC);
</code>```

Now if I do a print_r($array) it outputs like this:

```<code>[Title 2] => 4
[1] => 3
[Title 1] => 2
[2] => 1
</code>```

Meaning it's, for some reason, and seemingly randomly, destroying the key value in the array and putting in place 1, 2, etc in place of Title #

This seems like it would be so easy, yet I've been trying multiple things without luck. Can anyone shine some light on this for me?

答:
sort functions in php return boolean not an array - http://php.net/manual/en/function.arsort.php
Sort function will update the array you put as parameter
Should be like this

```<code><?php
$array = [];
arsort($array);
var_dump($array);
</code>```

Body:
I have an array like this

[Title 1] => 2
[Title 2] => 4
[Title 3] => 3
[Title 4] => 1

All I'm trying to do is sort the integer value in the array, to get an output like this:

[Title 2] => 4
[Title 3] => 3
[Title 1] => 2
[Title 4] => 1

I don't think it matters, but my array is created by the array_count_values function.

$array = array_count_values($originalarray);

I've looked through the manual on PHP: Array Sorting but can't get anything to work.

I've tried a few things that look like they might work.

$newarray = arsort($array);

This just outputs 1

same with rsort.

The closest I've come is by using array_multisort by using it as such:

$array = array_count_values($originalarray);
$newarray = array_multisort($array, SORT_NUMERIC, SORT_DESC);

Now if I do a print_r($array) it outputs like this:

[Title 2] => 4
[1] => 3
[Title 1] => 2
[2] => 1

Meaning it's, for some reason, and seemingly randomly, destroying the key value in the array and putting in place 1, 2, etc in place of Title #

This seems like it would be so easy, yet I've been trying multiple things without luck. Can anyone shine some light on this for me?

Body:
sort functions in php return boolean not an array - http://php.net/manual/en/function.arsort.php
Sort function will update the array you put as parameter
Should be like this

<?php
$array = [];
arsort($array);
var_dump($array);


问:
C# SQL Server: Application works with database from another pc
I have my application written in C#, it uses a SQL Server database. I have a connection to a database in my C# code, some queries to write/read from database.

Now consider following: if I want to run this app from another PC, this PC has no SQL Server, will this app work? (I assume not) If not then how can this another PC still work with database? Is there a way to programmatically create database on another PC using C# so it has a name I need, columns I need. I created my database using SQL Server Management Studio.

答:
I guess your application works with a local server.
First of all you should check in your application at startup if there is any local mssql server running. If not, you should handle it by installing one programmatically.

Read this answer how to do this if you don't know it.

After that you have to create the database, it's tables, maybe adding user priviliges. Write a SQL script that gets started by a class that starts it.

Read this to see how to start a SQL script in C#


问:
fatal error: openssl/rsa.h: No such file or directory
I got this error when I executed g++ mycode.cpp, and this .cpp file include a line #include<openssl/rsa.h>. Now, I know the error's reason, and I have tow plan to resolve it:

I can add the openssl path to /etc/profile,

or I also can copy openssl folder to /usr/include, so I did the first plan, like this:

```<code>CPLUS_INCLUDE_PATH=$CPLUS_INCLUDE_PATH:/mylib

export CPLUS_INCLUDE_PATH
</code>```

(my openssl folder's path is /mylib/openssl)

and I got this error again.

Then I try second plan, and it passed complie,(like this /usr/include/openssl).

Now, my problem is,

why the header ("openssl/rsa.h") can be found under /usr/include/ but can not be found under /mylib/, even I had add the path(/mylib) to /etc/profile?

答:
Try to reinstall the library using the apt-get

```<code>sudo apt-get install libssl-dev
</code>```

Body:
I got this error when I executed g++ mycode.cpp, and this .cpp file include a line #include<openssl/rsa.h>. Now, I know the error's reason, and I have tow plan to resolve it:

I can add the openssl path to /etc/profile,

or I also can copy openssl folder to /usr/include, so I did the first plan, like this:

CPLUS_INCLUDE_PATH=$CPLUS_INCLUDE_PATH:/mylib

export CPLUS_INCLUDE_PATH

(my openssl folder's path is /mylib/openssl)

and I got this error again.

Then I try second plan, and it passed complie,(like this /usr/include/openssl).

Now, my problem is,

why the header ("openssl/rsa.h") can be found under /usr/include/ but can not be found under /mylib/, even I had add the path(/mylib) to /etc/profile?

Body:
Try to reinstall the library using the apt-get

sudo apt-get install libssl-dev


问:
GetExternalLoginInfo() returns null
I'm trying to use an Azure AD to authenticate users. Everything seems to be working fine until the redirect to RegisterExternalLogin.aspx.cs. For some reason the Context.GetOwinContext().Authentication.GetExternalLoginInfo() method keeps returning null, causing the application to redirect. Since it redirects here it's failing to create a new Identity User which is causing me issues further down the line.

```<code>public void ConfigureAuth(IAppBuilder app)
{
    // Configure the db context, user manager and signin manager to use a single instance per request
    app.CreatePerOwinContext(ApplicationDbContext.Create);
    app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
    app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

    // app.UseCookieAuthentication(new CookieAuthenticationOptions());
    var openIDOptions = new OpenIdConnectAuthenticationOptions
    {
        ClientId = clientId,
        Authority = authority,
        PostLogoutRedirectUri = postLogoutRedirectUri,
        RedirectUri = postLogoutRedirectUri,
        Notifications = new OpenIdConnectAuthenticationNotifications
        {
            AuthenticationFailed = context =>
            {
                context.HandleResponse();
                context.Response.Redirect("/Error?message=" + context.Exception.Message);
                return Task.FromResult(0);
            }
        }
    };
    openIDOptions.Scope = "openid profile email";
    app.UseOpenIdConnectAuthentication(openIDOptions);
}
</code>```

Here's the Page_Load() from RegisterExternalLogin.aspx.cs

```<code>protected void Page_Load()
{
    // Process the result from an auth provider in the request
    ProviderName = IdentityHelper.GetProviderNameFromRequest(Request);
    if (String.IsNullOrEmpty(ProviderName))
    {
        RedirectOnFail();
        return;
    }
    if (!IsPostBack)
    {
        var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
        var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>();
        var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
        if (loginInfo == null)
        {
            RedirectOnFail();
            return;
        }
        var user = manager.Find(loginInfo.Login);
        if (user != null)
        {
            signInManager.SignIn(user, isPersistent: false, rememberBrowser: false);
            IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
        }
        else if (User.Identity.IsAuthenticated)
        {
            // Apply Xsrf check when linking
            var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId());
            if (verifiedloginInfo == null)
            {
                RedirectOnFail();
                return;
            }

            var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login);
            if (result.Succeeded)
            {
                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
            }
            else
            {
                AddErrors(result);
                return;
            }
        }
        else
        {
            email.Text = loginInfo.Email;
        }
    }
}
</code>```

I saw a couple of answers related to cookies but these don't seem to fix the issue for me. Any help would be much appreciated.

答:
To implement Azure AD external login using OpenID Connect with ASP.NET identity .You need to enable the application to use a cookie to store information for the signed in user and use a cookie to temporarily store information about a user logging in with a third party login provider . Please refer to below configuration:</p>

```<code>// Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });

        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        // Use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
             //app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

        // Enables the application to remember the second login verification factor such as phone or email.
        // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
        // This is similar to the RememberMe option when you log in.
       //app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

        var openIDOptions = new OpenIdConnectAuthenticationOptions
        {
            ClientId = clientId,
            Authority = authority,
            PostLogoutRedirectUri = postLogoutRedirectUri,
            RedirectUri = postLogoutRedirectUri,
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                AuthenticationFailed = context =>
                {
                    context.HandleResponse();
                    context.Response.Redirect("/Error?message=" + context.Exception.Message);
                    return Task.FromResult(0);
                }
            }
        };
        openIDOptions.Scope = "openid profile email";
        app.UseOpenIdConnectAuthentication(openIDOptions);
</code>```

Title: GetExternalLoginInfo() returns null

Body:
I'm trying to use an Azure AD to authenticate users. Everything seems to be working fine until the redirect to RegisterExternalLogin.aspx.cs. For some reason the Context.GetOwinContext().Authentication.GetExternalLoginInfo() method keeps returning null, causing the application to redirect. Since it redirects here it's failing to create a new Identity User which is causing me issues further down the line.

public void ConfigureAuth(IAppBuilder app)
{
    // Configure the db context, user manager and signin manager to use a single instance per request
    app.CreatePerOwinContext(ApplicationDbContext.Create);
    app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
    app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

    // app.UseCookieAuthentication(new CookieAuthenticationOptions());
    var openIDOptions = new OpenIdConnectAuthenticationOptions
    {
        ClientId = clientId,
        Authority = authority,
        PostLogoutRedirectUri = postLogoutRedirectUri,
        RedirectUri = postLogoutRedirectUri,
        Notifications = new OpenIdConnectAuthenticationNotifications
        {
            AuthenticationFailed = context =>
            {
                context.HandleResponse();
                context.Response.Redirect("/Error?message=" + context.Exception.Message);
                return Task.FromResult(0);
            }
        }
    };
    openIDOptions.Scope = "openid profile email";
    app.UseOpenIdConnectAuthentication(openIDOptions);
}

Here's the Page_Load() from RegisterExternalLogin.aspx.cs

protected void Page_Load()
{
    // Process the result from an auth provider in the request
    ProviderName = IdentityHelper.GetProviderNameFromRequest(Request);
    if (String.IsNullOrEmpty(ProviderName))
    {
        RedirectOnFail();
        return;
    }
    if (!IsPostBack)
    {
        var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
        var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>();
        var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
        if (loginInfo == null)
        {
            RedirectOnFail();
            return;
        }
        var user = manager.Find(loginInfo.Login);
        if (user != null)
        {
            signInManager.SignIn(user, isPersistent: false, rememberBrowser: false);
            IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
        }
        else if (User.Identity.IsAuthenticated)
        {
            // Apply Xsrf check when linking
            var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId());
            if (verifiedloginInfo == null)
            {
                RedirectOnFail();
                return;
            }

            var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login);
            if (result.Succeeded)
            {
                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
            }
            else
            {
                AddErrors(result);
                return;
            }
        }
        else
        {
            email.Text = loginInfo.Email;
        }
    }
}

I saw a couple of answers related to cookies but these don't seem to fix the issue for me. Any help would be much appreciated.

Body:
To implement Azure AD external login using OpenID Connect with ASP.NET identity .You need to enable the application to use a cookie to store information for the signed in user and use a cookie to temporarily store information about a user logging in with a third party login provider . Please refer to below configuration:

// Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });

        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        // Use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
             //app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

        // Enables the application to remember the second login verification factor such as phone or email.
        // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
        // This is similar to the RememberMe option when you log in.
       //app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

        var openIDOptions = new OpenIdConnectAuthenticationOptions
        {
            ClientId = clientId,
            Authority = authority,
            PostLogoutRedirectUri = postLogoutRedirectUri,
            RedirectUri = postLogoutRedirectUri,
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                AuthenticationFailed = context =>
                {
                    context.HandleResponse();
                    context.Response.Redirect("/Error?message=" + context.Exception.Message);
                    return Task.FromResult(0);
                }
            }
        };
        openIDOptions.Scope = "openid profile email";
        app.UseOpenIdConnectAuthentication(openIDOptions);


问:
Comparing two NSDates and ignoring the time component
What is the most efficient/recommended way of comparing two NSDates?  I would like to be able to see if both dates are on the same day, irrespective of the time and have started writing some code that uses the timeIntervalSinceDate: method within the NSDate class and gets the integer of this value divided by the number of seconds in a day.  This seems long winded and I feel like I am missing something obvious.

The code I am trying to fix is:

```<code>if (!([key compare:todaysDate] == NSOrderedDescending))
{
    todaysDateSection = [eventSectionsArray count] - 1;
}
</code>```

where key and todaysDate are NSDate objects and todaysDate is creating using:

```<code>NSDate *todaysDate = [[NSDate alloc] init];
</code>```

Regards

Dave

答:
For developers coding in Swift 3</p>

```<code>if(NSCalendar.current.isDate(selectedDate, inSameDayAs: NSDate() as Date)){
     // Do something
}
</code>```

Body:
What is the most efficient/recommended way of comparing two NSDates?  I would like to be able to see if both dates are on the same day, irrespective of the time and have started writing some code that uses the timeIntervalSinceDate: method within the NSDate class and gets the integer of this value divided by the number of seconds in a day.  This seems long winded and I feel like I am missing something obvious.

The code I am trying to fix is:

if (!([key compare:todaysDate] == NSOrderedDescending))
{
    todaysDateSection = [eventSectionsArray count] - 1;
}

where key and todaysDate are NSDate objects and todaysDate is creating using:

NSDate *todaysDate = [[NSDate alloc] init];

Regards

Dave

Body:
For developers coding in Swift 3

if(NSCalendar.current.isDate(selectedDate, inSameDayAs: NSDate() as Date)){
     // Do something
}


问:
How to take multiple input in a single line in python
I am using list comphrensions for this:

```<code>x = [i for i in int(raw_input("Enter Input:")).split(",")]
Enter Input : 1 2 3 4 5
</code>```

But it throws the error:

```<code>Traceback (most recent call last):
File "python", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1 2 3 4 5'
</code>```

Can someone please sort it out.

答:
```<code>x = [int(i) for i in raw_input("Enter Input:").split(" ")]
</code>```

Body:
I am using list comphrensions for this:

x = [i for i in int(raw_input("Enter Input:")).split(",")]
Enter Input : 1 2 3 4 5

But it throws the error:

Traceback (most recent call last):
File "python", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1 2 3 4 5'

Can someone please sort it out.


问:
phpStorm/Xdebug can't show show child arrays of objects
I'm trying to debug this code:

```<code>  public function removeBlankLines() {
    $this->qp->find('br');
  } // <-- break point is here
</code>```

When I drill down into the $this object (using phpStorm) I can't see the child array I'm interested in.  It just displays "can not get property"  Screenshot:

I'm "listen for debug connections" feature.  I'm running the script from the command line.  PHP version:

```<code>[bwood@mbp ~]$ php -v
PHP 5.4.24 (cli) (built: Jan 19 2014 21:32:15)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2013 Zend Technologies
with Xdebug v2.2.3, Copyright (c) 2002-2013, by Derick Rethans
</code>```

Maybe related: http://bugs.xdebug.org/view.php?id=996?

答:
You will also get a ! can not get property error if the property you are attempting to inspect is inherited from a parent class and not visible from your current scope.

Example:

xDebug will annotate the relevant property like such:

```<code>$childClass = {path\to\child\Child}
    *path\to\class\Parent*property = {path\to\property\Property}
</code>```

Where:

Parent is the base class

Child is the extending class

property is the inherited property, defined on Parent

Note the asterisk * which identify this case and denote 'not visible from current scope'.

Solution:

The quick solution to enable debugging is to set the parent's property's visibility to public.

ie

```<code>class Parent {
    public $property;  // instead of private or protected
}

class Child extends Parent{
    // You can now inspect parent::$property for instances of Child
}
</code>```

Remember to set the property visibility back to the correct value when finished testing.

Body:
I'm trying to debug this code:

  public function removeBlankLines() {
    $this->qp->find('br');
  } // <-- break point is here

When I drill down into the $this object (using phpStorm) I can't see the child array I'm interested in.  It just displays "can not get property"  Screenshot:

I'm "listen for debug connections" feature.  I'm running the script from the command line.  PHP version:

[bwood@mbp ~]$ php -v
PHP 5.4.24 (cli) (built: Jan 19 2014 21:32:15)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2013 Zend Technologies
with Xdebug v2.2.3, Copyright (c) 2002-2013, by Derick Rethans

Maybe related: http://bugs.xdebug.org/view.php?id=996?

Body:
You will also get a ! can not get property error if the property you are attempting to inspect is inherited from a parent class and not visible from your current scope.

Example:

xDebug will annotate the relevant property like such:

$childClass = {path\to\child\Child}
    *path\to\class\Parent*property = {path\to\property\Property}

Where:

Parent is the base class

Child is the extending class

property is the inherited property, defined on Parent

Note the asterisk * which identify this case and denote 'not visible from current scope'.

Solution:

The quick solution to enable debugging is to set the parent's property's visibility to public.

ie

class Parent {
    public $property;  // instead of private or protected
}

class Child extends Parent{
    // You can now inspect parent::$property for instances of Child
}

Remember to set the property visibility back to the correct value when finished testing.


问:
How to decide where to handle an exception - in scope of function it been thrown or in global one?
I`m writing client-server app for windows using WinSock and I have class for server.

while initialising server I have such code:

```<code>
class Server {
    static const int MaxClients = 10;
    std::vector connections;
    CRITICAL_SECTION cs;
    int port;
    SOCKET ServerSocket;
    sockaddr_in ServerAddress;
    void init();
public:
    Server(int Port);
    void addConnection(const Client& newClient);
    void closeConnection(int index);
    void Listen();
    int size();
    /*virtual void ClientService();
    virtual void SendMsg(const std::string& msg);*/
    virtual ~Server();
};

void Server::init() {
    WSADATA wsaData;
    if(WSAStartup(MAKEWORD(2, 2), &wsaData))
        throw Exception("WinSock init failed");
    ServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ServerSocket == INVALID_SOCKET)
        throw Exception("Socket failed to create!");
    ServerAddress.sin_family = AF_INET;
    ServerAddress.sin_addr.s_addr = htonl(INADDR_ANY);
    ServerAddress.sin_port = htons(port);
    if(bind(ServerSocket,(sockaddr*)&ServerAddress,sizeof(ServerAddress)) == SOCKET_ERROR)
    {
        throw Exception("Binding failed");
        closesocket(ServerSocket);
    }
}
</code>```

where do I need to handle exceptions? Here, in init() private method (which is called from constructor) or in main function?
Any rules existing where to place handlers for exceptions and what does it depend on?

答:
It depends on whether you're actually going to handle the exception, e.g. retry with a slightly different input, or decide to ignore the problem and proceed anyway (rarely appropriate, but can be useful). In this case, you may well want to catch the exception close to its source.

In most cases, the only thing you can really do with an exception is log it and abort the operation (e.g. serve the user an error page in a web app, or pop up a friendly "this program has crashed, sorry" dialog and exit). In this case, your catch block is likely to be quite close to the top of the stack - e.g. in the main method.

Body:
I`m writing client-server app for windows using WinSock and I have class for server.

while initialising server I have such code:

class Server {
    static const int MaxClients = 10;
    std::vector connections;
    CRITICAL_SECTION cs;
    int port;
    SOCKET ServerSocket;
    sockaddr_in ServerAddress;
    void init();
public:
    Server(int Port);
    void addConnection(const Client& newClient);
    void closeConnection(int index);
    void Listen();
    int size();
    /*virtual void ClientService();
    virtual void SendMsg(const std::string& msg);*/
    virtual ~Server();
};

void Server::init() {
    WSADATA wsaData;
    if(WSAStartup(MAKEWORD(2, 2), &wsaData))
        throw Exception("WinSock init failed");
    ServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ServerSocket == INVALID_SOCKET)
        throw Exception("Socket failed to create!");
    ServerAddress.sin_family = AF_INET;
    ServerAddress.sin_addr.s_addr = htonl(INADDR_ANY);
    ServerAddress.sin_port = htons(port);
    if(bind(ServerSocket,(sockaddr*)&ServerAddress,sizeof(ServerAddress)) == SOCKET_ERROR)
    {
        throw Exception("Binding failed");
        closesocket(ServerSocket);
    }
}

where do I need to handle exceptions? Here, in init() private method (which is called from constructor) or in main function?
Any rules existing where to place handlers for exceptions and what does it depend on?

OwnerDisplayName: Jon Skeet