问:
How to mail in C# with the Gmail SMTP server?

Possible Duplicate:

  Sending email through Gmail SMTP server with C#

For mailing with C# and using the Gmail SMTP server is there any kind of tricky thing that we should do? Because after lot of searching I found some ways for doing this, but I'm getting a failure exception as a result. I guess it's because I don't handle TSL for Gmail (because it works with TSL), but I don't know how to handle TSL with C# for doing this. I really appreciate any help or link to a useful sample. Here's my code:

```<code>public string SendMail(string senderMail, string receiverMail, string attachmentPath)
{
  var fromMailAddress = new MailAddress(senderMail);
  var toMailAddress = new MailAddress(receiverMail);

  MailMessage mailMessage = new MailMessage(fromMailAddress, toMailAddress);
  mailMessage.Subject = "My Subject";
  mailMessage.Body = "This is the body of this message for testing purposes";

  Attachment attachFile = new Attachment(attachmentPath);
  mailMessage.Attachments.Add(attachFile);

  SmtpClient emailClient = new SmtpClient();

  NetworkCredential credential = new NetworkCredential();
  credential.UserName = fromMailAddress.User;
  credential.Password = "password";

  emailClient.Credentials = credential;
  emailClient.Port = 587;
  emailClient.Host = "smtp.gmail.com";

  //emailClient.EnableSsl = true; //Here should be for TSL, but how?

  emailClient.Send(mailMessage);
}
</code>```

答:
Try the following code. This is the working code I have been using for a long time.

```<code>    // Configure mail client (may need additional
    // code for authenticated SMTP servers).
    SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 587);

    // Set the network credentials.
    mailClient.Credentials = new NetworkCredential("YourGmailEmail@gmail.com", "YourGmailPassword");

    //Enable SSL.
    mailClient.EnableSsl = true;

    // Create the mail message (from, to, subject, body).
    MailMessage mailMessage = new MailMessage();
    mailMessage.From = new MailAddress("zain.you2@gmail.com");
    mailMessage.To.Add(to);

    mailMessage.Subject = subject;
    mailMessage.Body = body;
    mailMessage.IsBodyHtml = isBodyHtml;
    mailMessage.Priority = mailPriority;

    // Send the mail.
    mailClient.Send(mailMessage);
</code>```

Reference: Sending Email using a Gmail Account.

Body:
Possible Duplicate:

  Sending email through Gmail SMTP server with C#

For mailing with C# and using the Gmail SMTP server is there any kind of tricky thing that we should do? Because after lot of searching I found some ways for doing this, but I'm getting a failure exception as a result. I guess it's because I don't handle TSL for Gmail (because it works with TSL), but I don't know how to handle TSL with C# for doing this. I really appreciate any help or link to a useful sample. Here's my code:

public string SendMail(string senderMail, string receiverMail, string attachmentPath)
{
  var fromMailAddress = new MailAddress(senderMail);
  var toMailAddress = new MailAddress(receiverMail);

  MailMessage mailMessage = new MailMessage(fromMailAddress, toMailAddress);
  mailMessage.Subject = "My Subject";
  mailMessage.Body = "This is the body of this message for testing purposes";

  Attachment attachFile = new Attachment(attachmentPath);
  mailMessage.Attachments.Add(attachFile);

  SmtpClient emailClient = new SmtpClient();

  NetworkCredential credential = new NetworkCredential();
  credential.UserName = fromMailAddress.User;
  credential.Password = "password";

  emailClient.Credentials = credential;
  emailClient.Port = 587;
  emailClient.Host = "smtp.gmail.com";

  //emailClient.EnableSsl = true; //Here should be for TSL, but how?

  emailClient.Send(mailMessage);
}

Body:
Try the following code. This is the working code I have been using for a long time.

    // Configure mail client (may need additional
    // code for authenticated SMTP servers).
    SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 587);

    // Set the network credentials.
    mailClient.Credentials = new NetworkCredential("YourGmailEmail@gmail.com", "YourGmailPassword");

    //Enable SSL.
    mailClient.EnableSsl = true;

    // Create the mail message (from, to, subject, body).
    MailMessage mailMessage = new MailMessage();
    mailMessage.From = new MailAddress("zain.you2@gmail.com");
    mailMessage.To.Add(to);

    mailMessage.Subject = subject;
    mailMessage.Body = body;
    mailMessage.IsBodyHtml = isBodyHtml;
    mailMessage.Priority = mailPriority;

    // Send the mail.
    mailClient.Send(mailMessage);

Reference: Sending Email using a Gmail Account.


来源: stackexchange

问:
Fill 2D array square and print in specific patterns
Ive been working on this assignment question for about 4 days now and I'm about to go crazy. We have specific directions to follow for this code;

"Your program should proceed as follows:

Display a welcome message.

Prompt the user for an integer which is  3. If the number entered is < 3. keep prompting the user until they enter a number  3 (use a do/while).    This number will determine the size of the square array.

Fill the array as per pattern 1 and display it using printf to format the array.

Fill the same array as per pattern 2 and display it using printf t0 format the array.

Display a closing message."

Pattern:

I'm still stuck on pattern one. I tried to do first do a for loop which in it there's an if statement that checks if the column number is even or not, if it is, to print out the code backwards. The question also recommends using a while loop and a do/while loop...?

Also any tips on to how to go about the second patterns.

Here is my code.

```<code>import java.util.Scanner;
public class a3q33
{

  public static void main(String[] args)
  {
    Scanner keyboard = new Scanner(System.in);

    int n;

    do
    {
        System.out.println("How many rows/columns do you want your array to have? (Must be at least 3)");

        n=keyboard.nextInt();

    } while(n < 3);

    int [][] arr = new int [n][n];

     int i, j, k=1;

    for(i=0;i<n;i++)
    {
         if(i % 2 != 0)
         {
             for(j=n;j>0;j--)
             {
                 k = k+n;
                 arr[i][j]=k;
                 k--;
             }
         }

         else
         {
             for(j=0;j<n;j++)
             {
                 arr[i][j]=k;
                 k++;
             }
         }
    }

    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            System.out.printf(arr[i][j]+" ");

        }
            System.out.printf("");
            System.out.println();
    }

    }
}
</code>```

Any help would be greatly appreciated!

答:
```<code>import java.util.Scanner;

public class a3q33{
    public static void main(String[] args){
        Scanner keyboard = new Scanner(System.in);
        int n;
        do{
            System.out.println("How many rows/columns do you want your array to have? (Must be at least 3)");
            n=keyboard.nextInt();
        } while(n < 3);

        int count = 1;
        int [][] arr = new int [n][n];
        for(int i = 0;i<n; i++){
            if(i%2==0){
                for(int j = 0;j<n; j++){
                    arr [i][j] = count;
                    count++;
                }
            }
            else{
                for(int j = n-1;j>=0; j--){
                    arr [i][j] = count;
                    count++;
                }
            }
        }

        System.out.println("\nPattern 1 \n");
        // print the array
        for (int i = 0; i < n; i++){
            for (int j = 0; j < n; j++){
                System.out.printf("%d\t",arr[i][j]);
            }
            System.out.println();
        }
        // reset count back to 1 and fill the array in the same way only without the if/else
        // for n = 5 for example this will produce  [1, 2,  3,  4,  5 ]
        //                                          [6, 7,  8,  9,  10]
        //                                          [11,12, 13, 14, 15]
        //                                          [16,17, 18, 19, 20]
        //                                          [21,22, 23, 24, 25]

        count = 1;
        for(int i = 0;i<n; i++){
            for(int j = 0;j<n; j++){
                arr [i][j] = count;
                count++;
            }
        }

        // rotate arrays using arraycopy; for array at index 1 rotate by one, at index 2 by 2 and so on see
        //http://stackoverflow.com/questions/31174840/how-to-rotate-an-array
        //
        for (int i = 1; i<n; i++){
            int [] temp = new int [n];
            for (int j = 0; j < n; j++) {
                temp[(j + i) % n] = arr[i][j];
            }
            System.arraycopy(temp, 0, arr[i], 0, n);
            arr[i]=temp;
        }

        System.out.println("\nPattern 2 \n");
         // print the array
        for (int i = 0; i < n; i++){
            for (int j = 0; j < n; j++){
                System.out.printf("%d\t",arr[i][j]);
            }
            System.out.println();
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Ive been working on this assignment question for about 4 days now and I'm about to go crazy. We have specific directions to follow for this code;

"Your program should proceed as follows:

Display a welcome message.

Prompt the user for an integer which is  3. If the number entered is < 3. keep prompting the user until they enter a number  3 (use a do/while).    This number will determine the size of the square array.

Fill the array as per pattern 1 and display it using printf to format the array.

Fill the same array as per pattern 2 and display it using printf t0 format the array.

Display a closing message."

Pattern:

I'm still stuck on pattern one. I tried to do first do a for loop which in it there's an if statement that checks if the column number is even or not, if it is, to print out the code backwards. The question also recommends using a while loop and a do/while loop...?

Also any tips on to how to go about the second patterns.

Here is my code.

import java.util.Scanner;
public class a3q33
{

  public static void main(String[] args)
  {
    Scanner keyboard = new Scanner(System.in);

    int n;

    do
    {
        System.out.println("How many rows/columns do you want your array to have? (Must be at least 3)");

        n=keyboard.nextInt();

    } while(n < 3);

    int [][] arr = new int [n][n];

     int i, j, k=1;

    for(i=0;i<n;i++)
    {
         if(i % 2 != 0)
         {
             for(j=n;j>0;j--)
             {
                 k = k+n;
                 arr[i][j]=k;
                 k--;
             }
         }

         else
         {
             for(j=0;j<n;j++)
             {
                 arr[i][j]=k;
                 k++;
             }
         }
    }

    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            System.out.printf(arr[i][j]+" ");

        }
            System.out.printf("");
            System.out.println();
    }

    }
}

Any help would be greatly appreciated!


问:
How can I name a navigation property a different name from it's entity name in my EF POCO?
I have a POCO Entity named Employee.
And then I have a second POCO Entity named Case.

I want a navigation property that looks like instead this:

```<code>public class Case : BaseEntity
{
    public long EmployeeId { get; set; }
    public virtual Employee Employee{ get; set; }
</code>```

like this:

```<code>public class Case : BaseEntity
{
    public long InitialContactId { get; set; }
    public virtual Employee InitialContact { get; set; }
</code>```

I want to name my property InitialContact.  Not Employee.

But I get this error when EF tries to create the Database:

Unable to determine the relationship represented by navigation property 'Case.InitialContact' of type 'Employee'. Either manually configure the relationship, or ignore this property from the model.

Update 1:

I got it to work like this:

```<code>public class Case : BaseEntity
{
    public long InitialContactId { get; set; }
    [ForeignKey("Id")]
    public virtual Employee InitialContact { get; set; }
    public DateTime InitalConsultDate { get; set; }
    public Guid AppUserId { get; set; }
    public virtual AppUser LerSpecialist { get; set; }
</code>```

}

The primary key is ID in my BaseEntity.  Not EmployeeId.

But I have second part to my question.

Here is my Complete Employee POCO:

```<code>using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using Hrsa.Core.Generic.Model.Framework.Concrete;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace Hrsa.Core.Generic.Model.Lerd
{
    public class Employee : BaseEntity
    {
        [BindNever]
        public string Email { get; set; }
        [BindNever]
        public long OrganizationId { get; set; }
        [BindNever]
        public string Supervisor { get; set; }
        [BindNever]
        public string SupervisorEmail { get; set; }
        [BindNever]
        public string FirstName { get; set; }
        [BindNever]
        public string LastName { get; set; }
        public string Notes { get; set; }
        [BindNever]
        public  long BargainingUnitId { get; set; }
        [BindNever]
        public long PayPlanId { get; set; }
        [BindNever]
        public long GradeRankId { get; set; }
        [BindNever]
        public long PositionTitleId { get; set; }
        [BindNever]
        public long SeriesId { get; set; }
        public bool IsUnionEmployee { get; set; }
        public virtual Organization Organization { get; set; }
        public virtual BargainingUnit BargainingUnit { get; set; }
        public virtual PayPlan PayPlan { get; set; }
        public virtual GradeRank GradeRank { get; set; }
        public virtual PositionTitle PositionTitle { get; set; }
        public virtual  Series Series { get; set; }
        public virtual ICollection<UnionHours> UnionHours { get; set; }
        public virtual ICollection<Case> Cases { get; set; }
        [NotMapped]
        public string UnionEmployeeYesNo => (IsUnionEmployee) ? "Yes" : "No";
   }
}
</code>```

I want my Employee to have many Cases:

```<code>public virtual ICollection<Case> Cases { get; set; }
</code>```

Here is my complete Cases POCO:

```<code>public class Case : BaseEntity
{
    public long InitialContactId { get; set; }
    [ForeignKey("Id")]
    public virtual Employee InitialContact { get; set; }
    public DateTime InitalConsultDate { get; set; }
    public Guid AppUserId { get; set; }
    public virtual AppUser LerSpecialist { get; set; }

}
</code>```

So now my DB looks like this:

So I have my InitialContactId in Cases ok.

But now I need my Case to have many Employees.

So I add this in to my Case POCO:

```<code>public virtual ICollection<Employee> Employees { get; set; }
</code>```

Now it looks like this:

```<code>public class Case : BaseEntity
{
    public long InitialContactId { get; set; }
    [ForeignKey("Id")]
    public virtual Employee InitialContact { get; set; }
    public DateTime InitalConsultDate { get; set; }
    public Guid AppUserId { get; set; }
    public virtual AppUser LerSpecialist { get; set; }

    public virtual ICollection<Employee> Employees { get; set; }
</code>```

}

Now when I run it, I get this error again:

Unable to determine the relationship represented by navigation property 'Case.InitialContact' of type 'Employee'. Either manually configure the relationship, or ignore this property from the model.

Update 2:

I found this article for a Many-Many relationship in .Net Core 1:
http://www.learnentityframeworkcore.com/configuration/many-to-many-relationship-configuration

So now I have a bridge lookup entity:

```<code>public class EmployeeCase
{
    [ForeignKey("Id")]
    public long EmployeeId { get; set; }
    public Employee Employee { get; set; }
    [ForeignKey("Id")]
    public long CaseId { get; set; }
    public Case Case { get; set; }

}
</code>```

Employee POCO:

Changed:

```<code>public virtual ICollection<Case> Cases { get; set; }
</code>```

to:

```<code>public class Case : BaseEntity
{
    public long InitialContactId { get; set; }
    public virtual Employee InitialContact { get; set; }
</code>```0

Case POCO:

Changed:

```<code>public class Case : BaseEntity
{
    public long InitialContactId { get; set; }
    public virtual Employee InitialContact { get; set; }
</code>```1

to:

```<code>public class Case : BaseEntity
{
    public long InitialContactId { get; set; }
    public virtual Employee InitialContact { get; set; }
</code>```2

In my AppDbContext

```<code>    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        #region Many-to-Many Employees Cases
        modelBuilder.Entity<EmployeeCase>()
            .HasKey(ec => new { ec.EmployeeId, ec.CaseId });

        modelBuilder.Entity<EmployeeCase>()
            .HasOne(ec => ec.Employee)
            .WithMany(e => e.EmployeeCases)
            .HasForeignKey(ec => ec.EmployeeId);

        modelBuilder.Entity<EmployeeCase>()
            .HasOne(ec => ec.Case)
            .WithMany(c => c.EmployeeCases)
            .HasForeignKey(ec => ec.CaseId);
        #endregion

    }
</code>```

Now when I run I get this error:

An exception of type 'System.Data.SqlClient.SqlException' occurred in Microsoft.EntityFrameworkCore.Relational.dll but was not handled in user code

Additional information: Introducing FOREIGN KEY constraint 'FK_EmployeeCase_Employees_EmployeeId' on table 'EmployeeCase' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

Could not create constraint or index. See previous errors.

Update 3:

Finally got my tables the way I want with this piece of code from:
Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Get rid of Cascading Circular error on ModelBuilding
        foreach (var relationShip in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
        {
            relationShip.DeleteBehavior = DeleteBehavior.Restrict;
        }

        #region Many-to-Many Employees Cases
        modelBuilder.Entity<EmployeeCase>()
            .HasKey(ec => new { ec.EmployeeId, ec.CaseId });

        modelBuilder.Entity<EmployeeCase>()
            .HasOne(ec => ec.Employee)
            .WithMany(e => e.EmployeeCases)
            .HasForeignKey(ec => ec.EmployeeId);

        modelBuilder.Entity<EmployeeCase>()
            .HasOne(ec => ec.Case)
            .WithMany(c => c.EmployeeCases)
            .HasForeignKey(ec => ec.CaseId);
        #endregion

        base.OnModelCreating(modelBuilder);
    }
</code>```

Update 4:

This did not work after all.
Remvoving the delete behavior for everything messes up my other relationships and I get errors.

How can I fix this?
This is disgusting.
So wishing I did not go Core.

答:
I have made it a habit of explicitly defining my relationships as EF does not always get them the way I want.  I like to create a Mapping folder that contains my entity maps.  The fluent api works great for this and inherits from EntityTypeConfiguration.

Try this.

public class CaseMap : EntityTypeConfiguration<Case>
{
    public CaseMap()
    {
        HasKey(m => m.Id)
        HasRequired(m => m.InitialContact)
        .WithMany(e => e.Cases)
        .HasForeignKey(m => m.InitialContactId);
    }
}

Almost forgot. You need to tell your DbContext where to find these mappings.  Add this to your DbContexts OnModelCreating method.

```<code>modelBuilder.Configurations.AddFromAssembly(typeof(MyContext).Assembly);
</code>```

Body:
I have a POCO Entity named Employee.
And then I have a second POCO Entity named Case.

I want a navigation property that looks like instead this:

public class Case : BaseEntity
{
    public long EmployeeId { get; set; }
    public virtual Employee Employee{ get; set; }

like this:

public class Case : BaseEntity
{
    public long InitialContactId { get; set; }
    public virtual Employee InitialContact { get; set; }

I want to name my property InitialContact.  Not Employee.

But I get this error when EF tries to create the Database:

Unable to determine the relationship represented by navigation property 'Case.InitialContact' of type 'Employee'. Either manually configure the relationship, or ignore this property from the model.

Update 1:

I got it to work like this:

public class Case : BaseEntity
{
    public long InitialContactId { get; set; }
    [ForeignKey("Id")]
    public virtual Employee InitialContact { get; set; }
    public DateTime InitalConsultDate { get; set; }
    public Guid AppUserId { get; set; }
    public virtual AppUser LerSpecialist { get; set; }

}

The primary key is ID in my BaseEntity.  Not EmployeeId.

But I have second part to my question.

Here is my Complete Employee POCO:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using Hrsa.Core.Generic.Model.Framework.Concrete;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace Hrsa.Core.Generic.Model.Lerd
{
    public class Employee : BaseEntity
    {
        [BindNever]
        public string Email { get; set; }
        [BindNever]
        public long OrganizationId { get; set; }
        [BindNever]
        public string Supervisor { get; set; }
        [BindNever]
        public string SupervisorEmail { get; set; }
        [BindNever]
        public string FirstName { get; set; }
        [BindNever]
        public string LastName { get; set; }
        public string Notes { get; set; }
        [BindNever]
        public  long BargainingUnitId { get; set; }
        [BindNever]
        public long PayPlanId { get; set; }
        [BindNever]
        public long GradeRankId { get; set; }
        [BindNever]
        public long PositionTitleId { get; set; }
        [BindNever]
        public long SeriesId { get; set; }
        public bool IsUnionEmployee { get; set; }
        public virtual Organization Organization { get; set; }
        public virtual BargainingUnit BargainingUnit { get; set; }
        public virtual PayPlan PayPlan { get; set; }
        public virtual GradeRank GradeRank { get; set; }
        public virtual PositionTitle PositionTitle { get; set; }
        public virtual  Series Series { get; set; }
        public virtual ICollection<UnionHours> UnionHours { get; set; }
        public virtual ICollection<Case> Cases { get; set; }
        [NotMapped]
        public string UnionEmployeeYesNo => (IsUnionEmployee) ? "Yes" : "No";
   }
}

I want my Employee to have many Cases:

public virtual ICollection<Case> Cases { get; set; }

Here is my complete Cases POCO:

public class Case : BaseEntity
{
    public long InitialContactId { get; set; }
    [ForeignKey("Id")]
    public virtual Employee InitialContact { get; set; }
    public DateTime InitalConsultDate { get; set; }
    public Guid AppUserId { get; set; }
    public virtual AppUser LerSpecialist { get; set; }

}

So now my DB looks like this:

So I have my InitialContactId in Cases ok.

But now I need my Case to have many Employees.

So I add this in to my Case POCO:

public virtual ICollection<Employee> Employees { get; set; }

Now it looks like this:

public class Case : BaseEntity
{
    public long InitialContactId { get; set; }
    [ForeignKey("Id")]
    public virtual Employee InitialContact { get; set; }
    public DateTime InitalConsultDate { get; set; }
    public Guid AppUserId { get; set; }
    public virtual AppUser LerSpecialist { get; set; }

    public virtual ICollection<Employee> Employees { get; set; }

}

Now when I run it, I get this error again:

Unable to determine the relationship represented by navigation property 'Case.InitialContact' of type 'Employee'. Either manually configure the relationship, or ignore this property from the model.

Update 2:

I found this article for a Many-Many relationship in .Net Core 1:
http://www.learnentityframeworkcore.com/configuration/many-to-many-relationship-configuration

So now I have a bridge lookup entity:

public class EmployeeCase
{
    [ForeignKey("Id")]
    public long EmployeeId { get; set; }
    public Employee Employee { get; set; }
    [ForeignKey("Id")]
    public long CaseId { get; set; }
    public Case Case { get; set; }

}

Employee POCO:

Changed:

public virtual ICollection<Case> Cases { get; set; }

to:

// Mapping - Collection of Cases
public virtual ICollection<EmployeeCase> EmployeeCases { get; set; }

Case POCO:

Changed:

public virtual ICollection<Employee> Employees { get; set; }

to:

 // Mapping - Collection of Employees
public virtual ICollection<EmployeeCase> EmployeeCases { get; set; }

In my AppDbContext

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        #region Many-to-Many Employees Cases
        modelBuilder.Entity<EmployeeCase>()
            .HasKey(ec => new { ec.EmployeeId, ec.CaseId });

        modelBuilder.Entity<EmployeeCase>()
            .HasOne(ec => ec.Employee)
            .WithMany(e => e.EmployeeCases)
            .HasForeignKey(ec => ec.EmployeeId);

        modelBuilder.Entity<EmployeeCase>()
            .HasOne(ec => ec.Case)
            .WithMany(c => c.EmployeeCases)
            .HasForeignKey(ec => ec.CaseId);
        #endregion

    }

Now when I run I get this error:

An exception of type 'System.Data.SqlClient.SqlException' occurred in Microsoft.EntityFrameworkCore.Relational.dll but was not handled in user code

Additional information: Introducing FOREIGN KEY constraint 'FK_EmployeeCase_Employees_EmployeeId' on table 'EmployeeCase' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

Could not create constraint or index. See previous errors.

Update 3:

Finally got my tables the way I want with this piece of code from:
Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Get rid of Cascading Circular error on ModelBuilding
        foreach (var relationShip in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
        {
            relationShip.DeleteBehavior = DeleteBehavior.Restrict;
        }

        #region Many-to-Many Employees Cases
        modelBuilder.Entity<EmployeeCase>()
            .HasKey(ec => new { ec.EmployeeId, ec.CaseId });

        modelBuilder.Entity<EmployeeCase>()
            .HasOne(ec => ec.Employee)
            .WithMany(e => e.EmployeeCases)
            .HasForeignKey(ec => ec.EmployeeId);

        modelBuilder.Entity<EmployeeCase>()
            .HasOne(ec => ec.Case)
            .WithMany(c => c.EmployeeCases)
            .HasForeignKey(ec => ec.CaseId);
        #endregion

        base.OnModelCreating(modelBuilder);
    }

Update 4:

This did not work after all.
Remvoving the delete behavior for everything messes up my other relationships and I get errors.

How can I fix this?
This is disgusting.
So wishing I did not go Core.

Body:
I have made it a habit of explicitly defining my relationships as EF does not always get them the way I want.  I like to create a Mapping folder that contains my entity maps.  The fluent api works great for this and inherits from EntityTypeConfiguration.

Try this.

public class CaseMap : EntityTypeConfiguration<Case>
{
    public CaseMap()
    {
        HasKey(m => m.Id)
        HasRequired(m => m.InitialContact)
        .WithMany(e => e.Cases)
        .HasForeignKey(m => m.InitialContactId);
    }
}

Almost forgot. You need to tell your DbContext where to find these mappings.  Add this to your DbContexts OnModelCreating method.

modelBuilder.Configurations.AddFromAssembly(typeof(MyContext).Assembly);


问:
App crashes randomly on viewWillDisappear()
I'm new to Swift, and I find some strange crashes in my app.

The Fabric reports said crashes occurred in viewWillDisappear().

I have two ViewControllers.User tap button in A viewcontroller then they move to B viewcontroller to input something, they user go back, and A get information from B.

I use a delegate to complete this task.

B:

```<code>class LessonNameTagTableViewController: UITableViewController {

...

var delegate:PassingData?

override func viewWillDisappear(_ animated: Bool) {

    lessonName = (tableView.cellForRow(at: IndexPath(row: 0, section: 0))?.viewWithTag(1) as! UITextField ).text!

    delegate?.changeLessonNameTag(name: lessonName, tag: tagColor)
    super.viewWillDisappear(animated)

}
...
}
</code>```

A:

```<code>class LessonEditTableViewController: UITableViewController,PassingData {
var lesson :Lesson?
...
func changeLessonNameTag(name:String,tag:UIColor){
    self.lesson!.lessonName = name
    self.lesson!.lessonTagColor = tag
    tableView.reloadData()

}
...
}
</code>```

The crash happened randomly, I've tested it on my device, and nothing happened.But others said they could repeat this crashes.

I wonder whether I'm using delegate right or it's caused by other reasons.

答:
If IndexPath{0,0} isn't visible when viewWillDisappear is called, then this line will set lessonName = nil as there is no cell for that row.  That will cause the following line to crash.

```<code>lessonName = tableView.cellForRow(at: IndexPath(row: 0, section: 0))?.viewWithTag(1) as! UITextField ).text!
</code>```

As others have mentioned, there are too many forced unwrappings.

However, unless that cell was dynamically populate by the user, you should be able to get the same value from your UITableViewDataSource - so it will work if the cell is visible or not.

Additionally, don't force unwrap lesson in your delegate method - could be nil.

```<code>func changeLessonNameTag(name:String,tag:UIColor){
    self.lesson?.lessonName = name
    self.lesson?.lessonTagColor = tag
    tableView.reloadData()
}
</code>```

Body:
I'm new to Swift, and I find some strange crashes in my app.

The Fabric reports said crashes occurred in viewWillDisappear().

I have two ViewControllers.User tap button in A viewcontroller then they move to B viewcontroller to input something, they user go back, and A get information from B.

I use a delegate to complete this task.

B:

class LessonNameTagTableViewController: UITableViewController {

...

var delegate:PassingData?

override func viewWillDisappear(_ animated: Bool) {

    lessonName = (tableView.cellForRow(at: IndexPath(row: 0, section: 0))?.viewWithTag(1) as! UITextField ).text!

    delegate?.changeLessonNameTag(name: lessonName, tag: tagColor)
    super.viewWillDisappear(animated)

}
...
}

A:

class LessonEditTableViewController: UITableViewController,PassingData {
var lesson :Lesson?
...
func changeLessonNameTag(name:String,tag:UIColor){
    self.lesson!.lessonName = name
    self.lesson!.lessonTagColor = tag
    tableView.reloadData()

}
...
}

The crash happened randomly, I've tested it on my device, and nothing happened.But others said they could repeat this crashes.

I wonder whether I'm using delegate right or it's caused by other reasons.

Body:
If IndexPath{0,0} isn't visible when viewWillDisappear is called, then this line will set lessonName = nil as there is no cell for that row.  That will cause the following line to crash.

lessonName = tableView.cellForRow(at: IndexPath(row: 0, section: 0))?.viewWithTag(1) as! UITextField ).text!

As others have mentioned, there are too many forced unwrappings.

However, unless that cell was dynamically populate by the user, you should be able to get the same value from your UITableViewDataSource - so it will work if the cell is visible or not.

Additionally, don't force unwrap lesson in your delegate method - could be nil.

func changeLessonNameTag(name:String,tag:UIColor){
    self.lesson?.lessonName = name
    self.lesson?.lessonTagColor = tag
    tableView.reloadData()
}


问:
HTTP Error 403 - Forbidden
When I start Debugging on asp.net3.5 . Browser display bellow message

*Server Error in '/attn-web' Application.

HTTP Error 403 - Forbidden.

Version Information: ASP.NET Development Server 9.0.0.0*

答:
It happened to me too. I had moved the project and fetched it again. It turns out that Visual Studio binds the virtual directory name as the source path for the files, and moving a (physical) directory makes IIS adjust the virtual directory to the new path. Visual Studio uses the virtual directory name still, and that causes a conflict.

Deleting in IIS the virtual directory made things work again.

ContentLicense: CC BY-SA 2.5

Title: HTTP Error 403 - Forbidden


问:
Convert to dataframe error
I want to make a dataframe with 110 columns, so i create a class with 110 attributes when i try to convert the rdd to dataframe.

```<code>case class Myclass(var cin_nb:String,...........,var last:String)
import sqlContext.implicts._
file2.map(_.split("\t")).map(a=>Myclass(a(0),a(1),a(2),a(3),.....a(110)).ToDf()
</code>```

I got this error:

```<code>not enough arguments for method apply: (cin_nb: String,...........,last:String)
</code>```

i'm using scala and spark 1.6.  Thank you

答:
You can't do this because there is a hard limit of 22 columns with case classes / StructType schemas. This is due to the Tuple in scala only supporting 22 elements!! To grow a dataframe to more columns you need to expand it using the .withColumn function, or load from file directly into a Dataframe. For example, from parquet, or using the databricks csv parser.

Edit: An example of how to do this with .withColumn

```<code>import scala.util.Random

val numCols = 100
val numRows = 5
val delimiter = "\t"

def generateRowData = (0 until numCols).map(i => Random.alphanumeric.take(5).mkString).mkString(delimiter)

val df = sc.parallelize((0 until numRows).map(i => generateRowData).toList).toDF("data")

def extractCol(i: Int, sep: String) = udf[String, String](_.split(sep)(i))

val result = (0 until numCols).foldLeft(df){case (acc,i) => acc.withColumn(s"c$i", extractCol(i,delimiter)($"data"))}.drop($"data")

result.printSchema
result.show
</code>```

Title: Convert to dataframe error

Body:
I want to make a dataframe with 110 columns, so i create a class with 110 attributes when i try to convert the rdd to dataframe.

case class Myclass(var cin_nb:String,...........,var last:String)
import sqlContext.implicts._
file2.map(_.split("\t")).map(a=>Myclass(a(0),a(1),a(2),a(3),.....a(110)).ToDf()

I got this error:

not enough arguments for method apply: (cin_nb: String,...........,last:String)

i'm using scala and spark 1.6.  Thank you

Body:
You can't do this because there is a hard limit of 22 columns with case classes / StructType schemas. This is due to the Tuple in scala only supporting 22 elements!! To grow a dataframe to more columns you need to expand it using the .withColumn function, or load from file directly into a Dataframe. For example, from parquet, or using the databricks csv parser.

Edit: An example of how to do this with .withColumn

import scala.util.Random

val numCols = 100
val numRows = 5
val delimiter = "\t"

def generateRowData = (0 until numCols).map(i => Random.alphanumeric.take(5).mkString).mkString(delimiter)

val df = sc.parallelize((0 until numRows).map(i => generateRowData).toList).toDF("data")

def extractCol(i: Int, sep: String) = udf[String, String](_.split(sep)(i))

val result = (0 until numCols).foldLeft(df){case (acc,i) => acc.withColumn(s"c$i", extractCol(i,delimiter)($"data"))}.drop($"data")

result.printSchema
result.show


问:
Liferay - Set Expando Field Value in a Javascript Function
I need to set a User Expando field value in a Javascript Function in liferay. It is possible to do?</p>

答:
You can use the json api like this way

```<code>Liferay.Service(
  '/expandovalue/add-value',
  {
    companyId: 20154,
    className: 'com.liferay.portal.model.User',
    tableName: 'CUSTOM_FIELDS',
    columnName: 'test',
    classPK: 30924,
    data: 'test'
  },
  function(obj) {
    console.log(obj);
  }
);
</code>```

where

columnName is the name of your custom field

classPK is the entity id in this case userId

data the value of the custom field

Body:
You can use the json api like this way

Liferay.Service(
  '/expandovalue/add-value',
  {
    companyId: 20154,
    className: 'com.liferay.portal.model.User',
    tableName: 'CUSTOM_FIELDS',
    columnName: 'test',
    classPK: 30924,
    data: 'test'
  },
  function(obj) {
    console.log(obj);
  }
);

where

columnName is the name of your custom field

classPK is the entity id in this case userId

data the value of the custom field


问:
Sort a column by clicking on a Button not on the ColumnHeader of a DataGrid c#
I have a DataGrid with HeadersVisibility="None".
I want to create a Button outside of the DataGrid that does exactly the same as if I clicked on the n column of the DataGrid(order the column).

I have tried the following code (myDataGrid is the name of my DataGrid):

```<code>private void button_Click(object sender, RoutedEventArgs e)
{
     DataGridColumn column = myDataGrid.Columns[0];
     DataGridColumnHeader columnHeader = GetColumnHeaderFromColumn(column);
     columnHeader.OnClick();
}
</code>```

but the function DataGridColumnHeader.OnClick() is inaccessible due to its protection level.

I have also looked at the class DataGrid that is in namespace System.Windows.Controls where I have found this :

```<code>public event DataGridSortingEventHandler Sorting;

/// <summary>
/// Protected method which raises the sorting event and does default sort
/// </summary>
/// <param name="eventArgs"></param>
protected virtual void OnSorting(DataGridSortingEventArgs eventArgs)
{
    eventArgs.Handled = false;
    if (Sorting != null)
    {
        Sorting(this, eventArgs);
    }

    if (!eventArgs.Handled)
    {
        DefaultSort(
                eventArgs.Column,
                /* clearExistinSortDescriptions */
                (Keyboard.Modifiers & ModifierKeys.Shift) != ModifierKeys.Shift);
    }
}

/// <summary>
/// Method to perform sorting on datagrid
/// </summary>
/// <param name="sortColumn"></param>
internal void PerformSort(DataGridColumn sortColumn)
{
    Debug.Assert(sortColumn != null, "column should not be null");

    if (!CanUserSortColumns || !sortColumn.CanUserSort)
    {
        return;
    }
    if (CommitAnyEdit())
    {
        PrepareForSort(sortColumn);

        DataGridSortingEventArgs eventArgs = new DataGridSortingEventArgs(sortColumn);
        OnSorting(eventArgs);

        if (Items.NeedsRefresh)
        {
            try
            {
                Items.Refresh();
            }
            catch (InvalidOperationException invalidOperationException)
            {
                Items.SortDescriptions.Clear();
                throw new InvalidOperationException(SR.Get(SRID.DataGrid_ProbableInvalidSortDescription), invalidOperationException);
            }
        }
    }
}
</code>```

But I wasn't able to use that.
Any idea about how can I do that ?

答:
You should work with SortDescriptions collection instead. This collection allows you to provide set of rules of how to sort items in the view.

You can find a good example on how to use it here: https://stackoverflow.com/a/19952233/6597895

```<code>public static void SortDataGrid(DataGrid dataGrid, int columnIndex = 0, ListSortDirection sortDirection = ListSortDirection.Ascending)
{
    var column = dataGrid.Columns[columnIndex];

    // Clear current sort descriptions
    dataGrid.Items.SortDescriptions.Clear();

    // Add the new sort description
    dataGrid.Items.SortDescriptions.Add(new SortDescription(column.SortMemberPath, sortDirection));

    // Apply sort
    foreach (var col in dataGrid.Columns)
    {
        col.SortDirection = null;
    }
    column.SortDirection = sortDirection;

    // Refresh items to display sort
    dataGrid.Items.Refresh();
}
</code>```

Body:
I have a DataGrid with HeadersVisibility="None".
I want to create a Button outside of the DataGrid that does exactly the same as if I clicked on the n column of the DataGrid(order the column).

I have tried the following code (myDataGrid is the name of my DataGrid):

private void button_Click(object sender, RoutedEventArgs e)
{
     DataGridColumn column = myDataGrid.Columns[0];
     DataGridColumnHeader columnHeader = GetColumnHeaderFromColumn(column);
     columnHeader.OnClick();
}

but the function DataGridColumnHeader.OnClick() is inaccessible due to its protection level.

I have also looked at the class DataGrid that is in namespace System.Windows.Controls where I have found this :

public event DataGridSortingEventHandler Sorting;

///
/// Protected method which raises the sorting event and does default sort
///
/// <param name="eventArgs"></param>
protected virtual void OnSorting(DataGridSortingEventArgs eventArgs)
{
    eventArgs.Handled = false;
    if (Sorting != null)
    {
        Sorting(this, eventArgs);
    }

    if (!eventArgs.Handled)
    {
        DefaultSort(
                eventArgs.Column,
                /* clearExistinSortDescriptions */
                (Keyboard.Modifiers & ModifierKeys.Shift) != ModifierKeys.Shift);
    }
}

///
/// Method to perform sorting on datagrid
///
/// <param name="sortColumn"></param>
internal void PerformSort(DataGridColumn sortColumn)
{
    Debug.Assert(sortColumn != null, "column should not be null");

    if (!CanUserSortColumns || !sortColumn.CanUserSort)
    {
        return;
    }
    if (CommitAnyEdit())
    {
        PrepareForSort(sortColumn);

        DataGridSortingEventArgs eventArgs = new DataGridSortingEventArgs(sortColumn);
        OnSorting(eventArgs);

        if (Items.NeedsRefresh)
        {
            try
            {
                Items.Refresh();
            }
            catch (InvalidOperationException invalidOperationException)
            {
                Items.SortDescriptions.Clear();
                throw new InvalidOperationException(SR.Get(SRID.DataGrid_ProbableInvalidSortDescription), invalidOperationException);
            }
        }
    }
}

But I wasn't able to use that.
Any idea about how can I do that ?

Body:
You should work with SortDescriptions collection instead. This collection allows you to provide set of rules of how to sort items in the view.

You can find a good example on how to use it here: https://stackoverflow.com/a/19952233/6597895

public static void SortDataGrid(DataGrid dataGrid, int columnIndex = 0, ListSortDirection sortDirection = ListSortDirection.Ascending)
{
    var column = dataGrid.Columns[columnIndex];

    // Clear current sort descriptions
    dataGrid.Items.SortDescriptions.Clear();

    // Add the new sort description
    dataGrid.Items.SortDescriptions.Add(new SortDescription(column.SortMemberPath, sortDirection));

    // Apply sort
    foreach (var col in dataGrid.Columns)
    {
        col.SortDirection = null;
    }
    column.SortDirection = sortDirection;

    // Refresh items to display sort
    dataGrid.Items.Refresh();
}


问:
Reading sub-level JSON data using Pandas
I am stuck while reading sublevel data using Pandas.

Background:

I used NYT Archive API to download series of data, I stored it in a JSON file which actually has list of JSON objects in it.

Procedure:

I read the JSON file using read_json method.

pandas_df = pd.read_json("data.json")

When I see sample result using head, it looks like below:

```<code> pandas_df.head()
    copyright  \
0  Copyright (c) 2013 The New York Times Company....
1  Copyright (c) 2013 The New York Times Company....
2  Copyright (c) 2013 The New York Times Company....
3  Copyright (c) 2013 The New York Times Company....
4  Copyright (c) 2013 The New York Times Company....

                                            response
0  {'docs': [{'subsection_name': None, 'slideshow...
1  {'docs': [{'subsection_name': None, 'slideshow...
2  {'docs': [{'subsection_name': None, 'slideshow...
3  {'docs': [{'subsection_name': None, 'slideshow...
4  {'docs': [{'subsection_name': None, 'slideshow...
</code>```

I only need information in the response. So when I change the code like below:

```<code>print(pandas_df["response"].head())
0    {'docs': [{'subsection_name': None, 'slideshow...
1    {'docs': [{'subsection_name': None, 'slideshow...
2    {'docs': [{'subsection_name': None, 'slideshow...
3    {'docs': [{'subsection_name': None, 'slideshow...
4    {'docs': [{'subsection_name': None, 'slideshow...
Name: response, dtype: object
</code>```

Question:

How can I fetch data using elements inside docs? Like subsection, slideshow etc. Can I see it in a tabular format, like a data frame?

Please let me know if any more information is required.

Thanks.

EDIT 1:

Adding first element from the JSON file. This file is too big around 1GB.

```<code>{
  "copyright": "Copyright (c) 2013 The New York Times Company.  All Rights Reserved.",
  "response": {
    "meta": {
      "hits": 7652
    },
    "docs": [
      {
        "web_url": "http://www.nytimes.com/interactive/2016/technology/personaltech/cord-cutting-guide.html",
        "snippet": "We teamed up with The Wirecutter to come up with cord-cutter bundles for movie buffs, sports addicts, fans of premium TV shows, binge watchers and families with children.",
        "lead_paragraph": "We teamed up with The Wirecutter to come up with cord-cutter bundles for movie buffs, sports addicts, fans of premium TV shows, binge watchers and families with children.",
        "abstract": null,
        "print_page": null,
        "blog": [],
        "source": "The New York Times",
        "multimedia": [
          {
            "width": 190,
            "url": "images/2016/10/13/business/13TECHFIX/06TECHFIX-thumbWide.jpg",
            "height": 126,
            "subtype": "wide",
            "legacy": {
              "wide": "images/2016/10/13/business/13TECHFIX/06TECHFIX-thumbWide.jpg",
              "wideheight": "126",
              "widewidth": "190"
            },
            "type": "image"
          },
          {
            "width": 600,
            "url": "images/2016/10/13/business/13TECHFIX/06TECHFIX-articleLarge.jpg",
            "height": 346,
            "subtype": "xlarge",
            "legacy": {
              "xlargewidth": "600",
              "xlarge": "images/2016/10/13/business/13TECHFIX/06TECHFIX-articleLarge.jpg",
              "xlargeheight": "346"
            },
            "type": "image"
          },
          {
            "width": 75,
            "url": "images/2016/10/13/business/13TECHFIX/06TECHFIX-thumbStandard.jpg",
            "height": 75,
            "subtype": "thumbnail",
            "legacy": {
              "thumbnailheight": "75",
              "thumbnail": "images/2016/10/13/business/13TECHFIX/06TECHFIX-thumbStandard.jpg",
              "thumbnailwidth": "75"
            },
            "type": "image"
          }
        ],
        "headline": {
          "main": "The Definitive Guide to Cord-Cutting in 2016, Based on Your Habits",
          "kicker": "Tech Fix"
        },
        "keywords": [
          {
            "rank": "1",
            "is_major": "N",
            "name": "subject",
            "value": "Video Recordings, Downloads and Streaming"
          },
          {
            "rank": "2",
            "is_major": "N",
            "name": "subject",
            "value": "Television Sets and Media Devices"
          },
          {
            "rank": "1",
            "is_major": "Y",
            "name": "subject",
            "value": "Television"
          }
        ],
        "pub_date": "2016-01-01T05:00:00Z",
        "document_type": "multimedia",
        "news_desk": "Technology / Personal Tech",
        "section_name": "Technology",
        "subsection_name": "Personal Tech",
        "byline": {
          "person": [
            {
              "firstname": "Brian",
              "middlename": "X.",
              "lastname": "CHEN",
              "rank": 1,
              "role": "reported",
              "organization": ""
            }
          ],
          "original": "By BRIAN X. CHEN"
        },
        "type_of_material": "Interactive Feature",
        "_id": "57fdfb9895d0e022439c2b57",
        "word_count": null,
        "slideshow_credits": null
      }]}}
</code>```

答:
You should be able to extract all the elements under the docs list which is nested in the response dictionary into a DataFrame.

```<code>import json
with open('data.json') as f:
    data = json.load(f)
df = pd.DataFrame(data['response']['docs'])
</code>```

Body:
I am stuck while reading sublevel data using Pandas.

Background:

I used NYT Archive API to download series of data, I stored it in a JSON file which actually has list of JSON objects in it.

Procedure:

I read the JSON file using read_json method.

pandas_df = pd.read_json("data.json")

When I see sample result using head, it looks like below:

 pandas_df.head()
    copyright  \
0  Copyright (c) 2013 The New York Times Company....
1  Copyright (c) 2013 The New York Times Company....
2  Copyright (c) 2013 The New York Times Company....
3  Copyright (c) 2013 The New York Times Company....
4  Copyright (c) 2013 The New York Times Company....

                                            response
0  {'docs': [{'subsection_name': None, 'slideshow...
1  {'docs': [{'subsection_name': None, 'slideshow...
2  {'docs': [{'subsection_name': None, 'slideshow...
3  {'docs': [{'subsection_name': None, 'slideshow...
4  {'docs': [{'subsection_name': None, 'slideshow...

I only need information in the response. So when I change the code like below:

print(pandas_df["response"].head())
0    {'docs': [{'subsection_name': None, 'slideshow...
1    {'docs': [{'subsection_name': None, 'slideshow...
2    {'docs': [{'subsection_name': None, 'slideshow...
3    {'docs': [{'subsection_name': None, 'slideshow...
4    {'docs': [{'subsection_name': None, 'slideshow...
Name: response, dtype: object

Question:

How can I fetch data using elements inside docs? Like subsection, slideshow etc. Can I see it in a tabular format, like a data frame?

Please let me know if any more information is required.

Thanks.

EDIT 1:

Adding first element from the JSON file. This file is too big around 1GB.

{
  "copyright": "Copyright (c) 2013 The New York Times Company.  All Rights Reserved.",
  "response": {
    "meta": {
      "hits": 7652
    },
    "docs": [
      {
        "web_url": "http://www.nytimes.com/interactive/2016/technology/personaltech/cord-cutting-guide.html",
        "snippet": "We teamed up with The Wirecutter to come up with cord-cutter bundles for movie buffs, sports addicts, fans of premium TV shows, binge watchers and families with children.",
        "lead_paragraph": "We teamed up with The Wirecutter to come up with cord-cutter bundles for movie buffs, sports addicts, fans of premium TV shows, binge watchers and families with children.",
        "abstract": null,
        "print_page": null,
        "blog": [],
        "source": "The New York Times",
        "multimedia": [
          {
            "width": 190,
            "url": "images/2016/10/13/business/13TECHFIX/06TECHFIX-thumbWide.jpg",
            "height": 126,
            "subtype": "wide",
            "legacy": {
              "wide": "images/2016/10/13/business/13TECHFIX/06TECHFIX-thumbWide.jpg",
              "wideheight": "126",
              "widewidth": "190"
            },
            "type": "image"
          },
          {
            "width": 600,
            "url": "images/2016/10/13/business/13TECHFIX/06TECHFIX-articleLarge.jpg",
            "height": 346,
            "subtype": "xlarge",
            "legacy": {
              "xlargewidth": "600",
              "xlarge": "images/2016/10/13/business/13TECHFIX/06TECHFIX-articleLarge.jpg",
              "xlargeheight": "346"
            },
            "type": "image"
          },
          {
            "width": 75,
            "url": "images/2016/10/13/business/13TECHFIX/06TECHFIX-thumbStandard.jpg",
            "height": 75,
            "subtype": "thumbnail",
            "legacy": {
              "thumbnailheight": "75",
              "thumbnail": "images/2016/10/13/business/13TECHFIX/06TECHFIX-thumbStandard.jpg",
              "thumbnailwidth": "75"
            },
            "type": "image"
          }
        ],
        "headline": {
          "main": "The Definitive Guide to Cord-Cutting in 2016, Based on Your Habits",
          "kicker": "Tech Fix"
        },
        "keywords": [
          {
            "rank": "1",
            "is_major": "N",
            "name": "subject",
            "value": "Video Recordings, Downloads and Streaming"
          },
          {
            "rank": "2",
            "is_major": "N",
            "name": "subject",
            "value": "Television Sets and Media Devices"
          },
          {
            "rank": "1",
            "is_major": "Y",
            "name": "subject",
            "value": "Television"
          }
        ],
        "pub_date": "2016-01-01T05:00:00Z",
        "document_type": "multimedia",
        "news_desk": "Technology / Personal Tech",
        "section_name": "Technology",
        "subsection_name": "Personal Tech",
        "byline": {
          "person": [
            {
              "firstname": "Brian",
              "middlename": "X.",
              "lastname": "CHEN",
              "rank": 1,
              "role": "reported",
              "organization": ""
            }
          ],
          "original": "By BRIAN X. CHEN"
        },
        "type_of_material": "Interactive Feature",
        "_id": "57fdfb9895d0e022439c2b57",
        "word_count": null,
        "slideshow_credits": null
      }]}}

Body:
You should be able to extract all the elements under the docs list which is nested in the response dictionary into a DataFrame.

import json
with open('data.json') as f:
    data = json.load(f)
df = pd.DataFrame(data['response']['docs'])


问:
Cannot run executable in TeamCity
I'm attempting to run a .Net console application (in TeamCity) I wrote which will change a variables value in a batch script located in the check out directory.

Unfortunately I'm receiving an error while running the step.
Process exited with code -2146232576

Currently I'm using a Command Line build step with the following settings:

Runner Type: Command Line

Step Name: Update setVars.bat

Execute Step: If all previous steps finished successfully

Run: Executable with parameters

Command Executable: E:\Test\Release\ReplaceText.exe

Command Parameters:

"%system.teamcity.build.checkoutDir%\DeploymentScripts\setVars.bat"

 "(?m)(SET RunDate\s?=\s?[A-Za-z]{4}-[A-Za-z]{5}-(\d+[.]?)+)"

"SET RunDate=Build-%build.number%" "%system.teamcity.build.checkoutDir%\DeploymentScripts\setVars.bat"

There are 4 parameters listed.

1) - Where to locate the batch script

2) - The Regex pattern

3) - The replacement text

4) - The output directory

I'm unable to use the built in file replacer as it reverts back its changes once the build is successful.

I've run the console application on its own and it works just fine. So I'm unsure as to why team city is unable to run the application. The error code tells me nothing.

Any help would be great appreciated.

答:
OK, I found the issue.
When I created the Console application I used VS 2017 with a .Net version of 4.6.2. That version of .Net is not installed on the CI server.

I changed the Console application to target .Net 4.5. This fixed the issue.

Title: Cannot run executable in TeamCity


问:
C# Json.NET Render Flags Enum as String Array
In a .NET Application, I have a set of values that are stored as a [Flags] enum. I want to serialize these to json, but instead of having the result be an integer, I'd like to get an array of string for the flags that are active.

So if I have the following code

```<code>[Flags]
public enum F
{
    Val1 = 1,
    Val2 = 2,
    Val4 = 4,
    Val8 = 8

}

public class C
{
    public F Flags { get; set; }
}

string Serialize() {
    return JsonConvert.SerializeObject(new C { Flags = F.Val1 | F.Val4 });
}
</code>```

I want the Serialize() method to return:

```<code>"{ Flags: [ "Val1", "Val4" ] }"
</code>```

Instead of:

```<code>"{ Flags: 5 }"
</code>```

答:
You have to implement your own converter. Here's an example (a particularly dirty and hacky way of doing it, but it serves as a good demo):

```<code>public class FlagConverter : JsonConverter
{
    public override object ReadJson(JsonReader reader,  Type objectType, Object existingValue, JsonSerializer serializer)
    {
        //If you need to deserialize, fill in the code here
        return null;
    }

    public override void WriteJson(JsonWriter writer, Object value, JsonSerializer serializer)
    {
        var flags = value.ToString()
            .Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries)
            .Select(f => $"\"{f}\"");

        writer.WriteRawValue($"[{string.Join(", ", flags)}]");
    }

    public override bool CanConvert(Type objectType)
    {
        return true;
    }
}
</code>```

Now decorate your enum like this:

```<code>[Flags]
[JsonConverter(typeof(FlagConverter))]
public enum F
{
    Val1 = 1,
    Val2 = 2,
    Val4 = 4,
    Val8 = 8
}
</code>```

And your example serialisation code will now output this:

```<code>{"Flags":["Val1", "Val4"]}
</code>```

Body:
In a .NET Application, I have a set of values that are stored as a [Flags] enum. I want to serialize these to json, but instead of having the result be an integer, I'd like to get an array of string for the flags that are active.

So if I have the following code

[Flags]
public enum F
{
    Val1 = 1,
    Val2 = 2,
    Val4 = 4,
    Val8 = 8

}

public class C
{
    public F Flags { get; set; }
}

string Serialize() {
    return JsonConvert.SerializeObject(new C { Flags = F.Val1 | F.Val4 });
}

I want the Serialize() method to return:

"{ Flags: [ "Val1", "Val4" ] }"

Instead of:

"{ Flags: 5 }"

Body:
You have to implement your own converter. Here's an example (a particularly dirty and hacky way of doing it, but it serves as a good demo):

public class FlagConverter : JsonConverter
{
    public override object ReadJson(JsonReader reader,  Type objectType, Object existingValue, JsonSerializer serializer)
    {
        //If you need to deserialize, fill in the code here
        return null;
    }

    public override void WriteJson(JsonWriter writer, Object value, JsonSerializer serializer)
    {
        var flags = value.ToString()
            .Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries)
            .Select(f => $"\"{f}\"");

        writer.WriteRawValue($"[{string.Join(", ", flags)}]");
    }

    public override bool CanConvert(Type objectType)
    {
        return true;
    }
}

Now decorate your enum like this:

[Flags]
[JsonConverter(typeof(FlagConverter))]
public enum F
{
    Val1 = 1,
    Val2 = 2,
    Val4 = 4,
    Val8 = 8
}

And your example serialisation code will now output this:

{"Flags":["Val1", "Val4"]}


问:
I wonder about a secure gateway of IBM using a web socket?
I want to consider using a Bluemix to run my application? For a firewall problem, I want to use a secure gateway of IBM that is one service in Bluemix. It uses a web socket. I customized a web socket of jetty in the past. So I am wondering if a web socket client makes a permanent connection with a web socket server. Does the server giving data back to the client? If the connection is disconnected for some reason, how can the web socket handle this exception? </p>

答: If you're wondering about how Bluemix Secure Gateway handles these situations, then yes, the Secure Gateway Client creates a persistent secure websocket connection to the Secure Gateway Servers which allows for the necessary communication between your application and your resource(s) behind the firewall.  If the websocket connection goes down, the Secure Gateway Client will attempt to establish a new websocket connection with the Secure Gateway Servers.</p>


问:
Creating a password scrambler
I'm trying to copy a password scrambler from Javascript to C. What it does is take the ASCII character code of the letter, floor it, divide it, and grab a random character out of a given list.

Javascript version:

```<code>function getScrambledPassword(pwd) {
    var cipher = ['k', 's', 'z', 'h', 'x', 'b', 'p', 'j', 'v', 'c', 'g', 'f', 'q', 'n', 't', 'm'];
    var result="";
    if (pwd == null)
        pwd = "";
    pwd = encodeURIComponent(pwd);
    //alert("encoded password: " + pwd);
    for(var i=0;i<pwd.length;i++) {
            var cc = pwd.charCodeAt(i);
        result += cipher[Math.floor(cc/16)] + cipher[cc%16];
    }
    //alert("scrambled password: " + result);
    return result;
}
</code>```

Example of the scrambler being run: https://jsfiddle.net/w5db66va/

What I've done so far:

```<code>#include <stdio.h>
#include <math.h>
#include <string.h>

static char *scramblePassword(char *pwd)
{
    char *cipher[] = {
        "k", "s", "z", "h",
        "x", "b", "p", "j",
        "v", "c", "g", "f",
        "q", "n", "t", "m"
    };

    char *result = "";
    for(int i=0; i < strlen(pwd); i++)
    {
        int cc = (int) pwd[i];
        printf("%d", cc);
        result + cipher[floor(cc/16)] + cipher[cc%16];
    }
    return *result;
}

int main(void)
{
    char *test[] = {"test", "testtwo", "testthree"};
    for (int i=0;i < sizeof(test); i++)
    {
        printf("Original: %s", test[i]);
        printf("Scrambled: %s", scramblePassword(test[i]));
    }
}
</code>```

The issue I'm experiencing is that when I run the c file (after compilation) it will not output anything at all. What am I doing wrong to the point that I cannot get this to run as I'd expect it?

答:
What's happening is you are getting very lucky. Your program invokes undefined behaviour in C.

Looking at this line first

```<code>result + cipher[floor(cc/16)] + cipher[cc%16];
</code>```

First of all, it doesn't do anything. That's just an expression that is thrown away. What you really wanted was:

```<code>result += cipher[floor(cc/16)] + cipher[cc%16];
</code>```

But it still wouldn't have worked because C doesn't really have the concept of a string. Strings are actually just sequences of chars terminated by '\0'. result is just a pointer to such a sequence and, like any other pointer, when you add something to it you just increase the location to which the pointer is pointing.

Also, returning *result actually dereferences the pointer and returns what it is pointing at.

The statement

```<code>result = "";
</code>```

allocates a bit of memory somewhere with an empty sequence of bytes terminated with a \0 i.e. a single nul byte. On the stack (or in a register depending on the implementation), result is allocated and given the address of the nul byte.

When you return *result you return the nul byte but the caller thinks you are returning a pointer so it will interpret that nul byte as a pointer (I'm surprised your code doesn't give errors when compiled actually) and that pointer will probably be a null pointer.

To concatenate strings in C is a tricky operation. You have to use strcat or one of its safer derivatives. You have to make sure that you allocate enough space for the result and you have to do it dynamically with malloc because strings allocated locally go away when you return from the function in whixh they were allocated.

Edit

And another thing....

C has more than one numeric data type. When you divide one integer by another, you get an integer result. if cc is not divisible by 16, the result will already be floor(cc/16)

Title: Creating a password scrambler

Body:
I'm trying to copy a password scrambler from Javascript to C. What it does is take the ASCII character code of the letter, floor it, divide it, and grab a random character out of a given list.

Javascript version:

function getScrambledPassword(pwd) {
    var cipher = ['k', 's', 'z', 'h', 'x', 'b', 'p', 'j', 'v', 'c', 'g', 'f', 'q', 'n', 't', 'm'];
    var result="";
    if (pwd == null)
        pwd = "";
    pwd = encodeURIComponent(pwd);
    //alert("encoded password: " + pwd);
    for(var i=0;i<pwd.length;i++) {
            var cc = pwd.charCodeAt(i);
        result += cipher[Math.floor(cc/16)] + cipher[cc%16];
    }
    //alert("scrambled password: " + result);
    return result;
}

Example of the scrambler being run: https://jsfiddle.net/w5db66va/

What I've done so far:

#include <stdio.h>
#include <math.h>
#include <string.h>

static char *scramblePassword(char *pwd)
{
    char *cipher[] = {
        "k", "s", "z", "h",
        "x", "b", "p", "j",
        "v", "c", "g", "f",
        "q", "n", "t", "m"
    };

    char *result = "";
    for(int i=0; i < strlen(pwd); i++)
    {
        int cc = (int) pwd[i];
        printf("%d", cc);
        result + cipher[floor(cc/16)] + cipher[cc%16];
    }
    return *result;
}

int main(void)
{
    char *test[] = {"test", "testtwo", "testthree"};
    for (int i=0;i < sizeof(test); i++)
    {
        printf("Original: %s", test[i]);
        printf("Scrambled: %s", scramblePassword(test[i]));
    }
}

The issue I'm experiencing is that when I run the c file (after compilation) it will not output anything at all. What am I doing wrong to the point that I cannot get this to run as I'd expect it?

Body:
What's happening is you are getting very lucky. Your program invokes undefined behaviour in C.

Looking at this line first

result + cipher[floor(cc/16)] + cipher[cc%16];

First of all, it doesn't do anything. That's just an expression that is thrown away. What you really wanted was:

result += cipher[floor(cc/16)] + cipher[cc%16];

But it still wouldn't have worked because C doesn't really have the concept of a string. Strings are actually just sequences of chars terminated by '\0'. result is just a pointer to such a sequence and, like any other pointer, when you add something to it you just increase the location to which the pointer is pointing.

Also, returning *result actually dereferences the pointer and returns what it is pointing at.

The statement

result = "";

allocates a bit of memory somewhere with an empty sequence of bytes terminated with a \0 i.e. a single nul byte. On the stack (or in a register depending on the implementation), result is allocated and given the address of the nul byte.

When you return *result you return the nul byte but the caller thinks you are returning a pointer so it will interpret that nul byte as a pointer (I'm surprised your code doesn't give errors when compiled actually) and that pointer will probably be a null pointer.

To concatenate strings in C is a tricky operation. You have to use strcat or one of its safer derivatives. You have to make sure that you allocate enough space for the result and you have to do it dynamically with malloc because strings allocated locally go away when you return from the function in whixh they were allocated.

Edit

And another thing....

C has more than one numeric data type. When you divide one integer by another, you get an integer result. if cc is not divisible by 16, the result will already be floor(cc/16)


问:
Decorate GET URL using forms
I have some question:

I use django form, and fields like MultipleChoiceField

in view.py I clean data and get GET URL like this

http://localhost:8000/?category=&style=&sex=&brand=ASICS&brand=Be+Positive&low_price=&high_price=

Give me advise, can I regroup brand field and hide empty.

I want getting something like this:

http://localhost:8000/?brand=1+2

And else one question:

How can I set empty value(empty_label) for forms.ModelMultipleChoiceFIeld

forms.py:

```<code>brand = forms.MultipleChoiceField(required=False,
                                  widget=forms.SelectMultiple(attrs={'size':1})
                                  )
def __init__(self,app_label=None, *args, **kwargs):
    super(Search, self).__init__(*args, **kwargs)
    self.fields['brand'].choices = [('', 'All brands')]+[(brand.name, brand) for brand in Brand.objects.all() ]
</code>```

views.py:

```<code> if request.method == 'GET' and request.GET:
     form = SearchForm(app_label, request.GET)
     if form.is_valid():
        brands = form.cleaned_data['brand']
        kwargs.update({"brand__name__in": brands})
</code>```

答:
For empty label in forms you could do this -

```<code>class SomeForm(forms.Form):
    h=forms.CharField(label=u'',widget=forms.TextInput(attrs={'value':'Search'}))
</code>```

By keeping label as '', you get the label as empty. The attrs are basically the HTML attributes of the form text field.

UPDATE: I didn't understand the first part of your Q, elaborate...

Title: Decorate GET URL using forms

Body:
I have some question:

I use django form, and fields like MultipleChoiceField

in view.py I clean data and get GET URL like this

http://localhost:8000/?category=&style=&sex=&brand=ASICS&brand=Be+Positive&low_price=&high_price=

Give me advise, can I regroup brand field and hide empty.

I want getting something like this:

http://localhost:8000/?brand=1+2

And else one question:

How can I set empty value(empty_label) for forms.ModelMultipleChoiceFIeld

forms.py:

brand = forms.MultipleChoiceField(required=False,
                                  widget=forms.SelectMultiple(attrs={'size':1})
                                  )
def __init__(self,app_label=None, *args, **kwargs):
    super(Search, self).__init__(*args, **kwargs)
    self.fields['brand'].choices = [('', 'All brands')]+[(brand.name, brand) for brand in Brand.objects.all() ]

views.py:

 if request.method == 'GET' and request.GET:
     form = SearchForm(app_label, request.GET)
     if form.is_valid():
        brands = form.cleaned_data['brand']
        kwargs.update({"brand__name__in": brands})

Body:
For empty label in forms you could do this -

class SomeForm(forms.Form):
    h=forms.CharField(label=u'',widget=forms.TextInput(attrs={'value':'Search'}))

By keeping label as '', you get the label as empty. The attrs are basically the HTML attributes of the form text field.

UPDATE: I didn't understand the first part of your Q, elaborate...


问:
How to Generate Routes for Subcomponents Based on a Base Path
How to get the next route in vue-router

I have the following route: /principal

{path: '/principal', component: Principal}

Now, I need to drive other components that have the same url base,
the new url would be as follows:

/principal/compa

Is it possible to have a single base route be able to display the other components?

Something like this (I know that vue-router does not work like this), but how do you get this behavior?

{
   path: '/principal',
   component: Principal,
   subpath: {
    path: 'compa',
    component: 'CompA'
   }
}

Thanks

答:
There is a children option in VueRouter constructor config to render Vue components with nested routes.

In that particular case, it would be:

{
   path: '/principal',
   component: Principal,
   children: [{
    path: 'compa',  // it would match /principal/compa
    component: CompA
   }]
}
```

<p>From the vue-router doc:</p>

<pre class="lang-js prettyprint-override"><code>const router = new VueRouter({
  routes: [
    {
      path: '/user/:id',
      component: User,
      children: [ // <-- notice the children property
        {
          // UserProfile will be rendered inside User's <router-view>
          // when /user/:id/profile is matched
          path: 'profile',
          component: UserProfile
        },
        {
          // UserPosts will be rendered inside User's <router-view>
          // when /user/:id/posts is matched
          path: 'posts',
          component: UserPosts
        }
      ]
    }
  ]
});
</code>```

Have a look at nested routes for more details.

Body:
There is a children option in VueRouter constructor config to render Vue components with nested routes.

In that particular case, it would be:

{
   path: '/principal',
   component: Principal,
   children: [{
    path: 'compa',  // it would match /principal/compa
    component: CompA
   }]
}

From the vue-router doc:

const router = new VueRouter({
  routes: [
    {
      path: '/user/:id',
      component: User,
      children: [ // <-- notice the children property
        {
          // UserProfile will be rendered inside User's <router-view>
          // when /user/:id/profile is matched
          path: 'profile',
          component: UserProfile
        },
        {
          // UserPosts will be rendered inside User's <router-view>
          // when /user/:id/posts is matched
          path: 'posts',
          component: UserPosts
        }
      ]
    }
  ]
});

Have a look at nested routes for more details.


问:
Attaching an entity of type 'SistemaIndustrial.Domain.Entities.Pessoa'
I'm make update in my table, but the current table should be saved in other table, on pessoaAntiga I  save the Pessoa but at the time it executes the Entity return an error.

```<code> public ActionResult Edit(PessoaViewModel pessoa)
    {
        var pessoaAntiga = _pessoaApp.GetById(pessoa.PessoaId);

        _pessoaApp.Update(Mapper.Map<PessoaViewModel, Pessoa>(pessoa));
        var lista = new List<HistoricoDeAlteraCliFor>();
</code>```

Attaching an entity of type 'SistemaIndustrial.Domain.Entities.Pessoa' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

答:
EF is just telling your that he can't attach this entity because this entity already have a type with this primary key.

This is because your are not updating the correct object.

You need to map pessoachanges to pessoaAntiga.

Have a look to this link to know more about EF update

http://www.entityframeworktutorial.net/update-entity-in-entity-framework.aspx

Body:
I'm make update in my table, but the current table should be saved in other table, on pessoaAntiga I  save the Pessoa but at the time it executes the Entity return an error.

 public ActionResult Edit(PessoaViewModel pessoa)
    {
        var pessoaAntiga = _pessoaApp.GetById(pessoa.PessoaId);

        _pessoaApp.Update(Mapper.Map<PessoaViewModel, Pessoa>(pessoa));
        var lista = new List<HistoricoDeAlteraCliFor>();

Attaching an entity of type 'SistemaIndustrial.Domain.Entities.Pessoa' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.


问:
Is it possible to change the text of selected item in a drop down?
I have a dropdown in which I am displaying items as below:

1             Apple

2              Banana

3              Mango

4              Orange

Now when I select any option, I just want the Number to be displayed not the entire item text. i.e when I select "1    Apple", I just want "1" to be displayed. How do I achieve this?

I've tried changing the text using

```<code> $("#ddlFruits option:selected").text($("#ddlFruits option:selected").text().split(' ')[0])
</code>```

but this also changes the item in dropdown.

答: select-elements have a selectedIndex-property that you could use in the change-event to get the selected option and manipulate its value or innerHTML.

Body:
I have a dropdown in which I am displaying items as below:

1             Apple

2              Banana

3              Mango

4              Orange

Now when I select any option, I just want the Number to be displayed not the entire item text. i.e when I select "1    Apple", I just want "1" to be displayed. How do I achieve this?

I've tried changing the text using

 $("#ddlFruits option:selected").text($("#ddlFruits option:selected").text().split(' ')[0])

but this also changes the item in dropdown.


问:
Find elasticsearch indices with no aliases
I have an elasticsearch cluster whose indices I need to investigate.  Specifically, I want to find all indices that do not have aliases.

Is this even possible?  If so, how?

(Using sense notation for this question.)

I know I can get all indices with their aliases, even if the alias field is empty:

```<code>GET _aliases
</code>```

And I know I can get all indices that have aliases:

```<code>GET /*/_alias/*
</code>```

But can I get all indices without aliases?

Clearly, I can just get all indices, and then use some tool like awk or whatever to do the work for me, but my naïve guess is that it's most efficient for elasticsearch to do all this work at once.

答:
Short answer: There is no easy api for you to find out which indices have not been linked to an alias.

Long answer: You could try the '_cluster/state' endpoint like this:

```<code>GET _cluster/state?filter_path=metadata.indices.test.aliases
</code>```

Where test is the name of your index. It gives the following result:

```<code>{
  "metadata": {
    "indices": {
      "test": {
        "aliases": []
      }
    }
  }
}
</code>```

Now if I try it with an index that is actually linked:

```<code>GET _cluster/state?filter_path=metadata.indices.test_with_alias.aliases
</code>```

I get the following result:

```<code>{
  "metadata": {
    "indices": {
      "test_with_alias": {
        "aliases": [
          "new_alias"
        ]
      }
    }
  }
}
</code>```

It's not the prettiest way to do this, but it's possible :)

Hope this helps!

Body:
I have an elasticsearch cluster whose indices I need to investigate.  Specifically, I want to find all indices that do not have aliases.

Is this even possible?  If so, how?

(Using sense notation for this question.)

I know I can get all indices with their aliases, even if the alias field is empty:

GET _aliases

And I know I can get all indices that have aliases:

GET /*/_alias/*

But can I get all indices without aliases?

Clearly, I can just get all indices, and then use some tool like awk or whatever to do the work for me, but my naïve guess is that it's most efficient for elasticsearch to do all this work at once.

Body:
Short answer: There is no easy api for you to find out which indices have not been linked to an alias.

Long answer: You could try the '_cluster/state' endpoint like this:

GET _cluster/state?filter_path=metadata.indices.test.aliases

Where test is the name of your index. It gives the following result:

{
  "metadata": {
    "indices": {
      "test": {
        "aliases": []
      }
    }
  }
}

Now if I try it with an index that is actually linked:

GET _cluster/state?filter_path=metadata.indices.test_with_alias.aliases

I get the following result:

{
  "metadata": {
    "indices": {
      "test_with_alias": {
        "aliases": [
          "new_alias"
        ]
      }
    }
  }
}

It's not the prettiest way to do this, but it's possible :)

Hope this helps!


问:
Get only meet records in SQL
I have two column one with ID and Type. In ID there are repetitive numbers and in Type "NA", "Cont" and "Dis".

My need is get count of records where Type not equal to "NA" and also if "Dis" found then stop counting the below records.

You can see the attachment where total records are 12 including all type. But after removing NA count is 11 but on 7th rows type is "Dis" , so it will ignore all below records and output s/b 6 only.

Query:

```<code>Select A.ps_indv_id
     , A.Continue
from ( Select A.ps_indv_id
            , A.Continue
            , A.[Row ID]
       from [dbo].[DVT_Persist_Claims] A ) A
left join (Select A.ps_indv_id
                , Min(A.[Row ID])[Row ID]
           from (Select A.ps_indv_id
                      , A.Continue
                      , A.[Row ID]
                 from [dbo].[DVT_Persist_Claims] A ) A
           where A.Continue = 'Discontinue'
           group by A.ps_indv_id ) B
   on A.ps_indv_id = B.ps_indv_id
where A.[Row ID] < B.[Row ID]
</code>```

Example :

```<code>ps_indv_id        Type   Record No.
848803003283483   NA      1
848803003283483   Cont    2
848803003283483   Cont    3
848803003283483   Cont    4
848803003283483   Cont    5
848803003283483   Cont    6
848803003283483   Cont    7
848803003283483   Dis     8
848803003283483   Dis     9
848803003283483   Cont   10
848803003283483   Cont   11
848803003283483   Cont   12
</code>```

答:
Is this the result you are looking for?

```<code>select t.type, count(t.type)
from table t
group by t.type
having t.record_no < (
     select Min(record_no)
     from table
     where Type = 'Dis'
     )
and t.type <> 'NA'
</code>```

If record_no is derived, then let us know the rules for deriving it.

Title: Get only meet records in SQL

Body:
I have two column one with ID and Type. In ID there are repetitive numbers and in Type "NA", "Cont" and "Dis".

My need is get count of records where Type not equal to "NA" and also if "Dis" found then stop counting the below records.

You can see the attachment where total records are 12 including all type. But after removing NA count is 11 but on 7th rows type is "Dis" , so it will ignore all below records and output s/b 6 only.

Query:

Select A.ps_indv_id
     , A.Continue
from ( Select A.ps_indv_id
            , A.Continue
            , A.[Row ID]
       from [dbo].[DVT_Persist_Claims] A ) A
left join (Select A.ps_indv_id
                , Min(A.[Row ID])[Row ID]
           from (Select A.ps_indv_id
                      , A.Continue
                      , A.[Row ID]
                 from [dbo].[DVT_Persist_Claims] A ) A
           where A.Continue = 'Discontinue'
           group by A.ps_indv_id ) B
   on A.ps_indv_id = B.ps_indv_id
where A.[Row ID] < B.[Row ID]

Example :

ps_indv_id        Type   Record No.
848803003283483   NA      1
848803003283483   Cont    2
848803003283483   Cont    3
848803003283483   Cont    4
848803003283483   Cont    5
848803003283483   Cont    6
848803003283483   Cont    7
848803003283483   Dis     8
848803003283483   Dis     9
848803003283483   Cont   10
848803003283483   Cont   11
848803003283483   Cont   12

Body:
Is this the result you are looking for?

select t.type, count(t.type)
from table t
group by t.type
having t.record_no < (
     select Min(record_no)
     from table
     where Type = 'Dis'
     )
and t.type <> 'NA'

If record_no is derived, then let us know the rules for deriving it.


问:
Alternative for ajax async: false
break property fires before ajax completed. Only solution I've found is to make "async: false". But it is deprecated. Is there any better option to wait until ajax completed without setting async to false?</p>

```<code>$.getJSON(jsonUrl, function(data) {
  var type, json, options;

  var globalData = data;

  $.each(globalData.properties, function(key, value) {
    switch(value.type) {
      case 'string':
        type = '<input type="text">'
        break;
      case 'int':
        type = '<input type="number" min="0">'
        break;
      case 'decimal':
        type = '<input type="number" min="0" step="0.01">'
        break;
      case 'date':
        type = '<input type="date">'
        break;
      case 'boolean':
        type = '<input type="checkbox">'
        break;
      case 'json':
        json = './assets/json/' + value.json_name + '.json'

        $.ajax({
          async: false,
          url: json,
          success: function(data) {
            $.each(data, function(index, item) {
              options += '<option value=' + item.key + '>' + item.value + '</option>'
            })

            type = '<select id="issue-form"><option disabled selected value></option>' + options + '</select>';
          }
        });

        break;
    }

    listItem += '<li class="questionnaire_item">' +
                  '<label>' +
                    '<div class="question">' +
                      value.description + ':' +
                    '</div>' +
                    '<div class="input">' +
                      type +
                    '</div>' +
                  '</label>' +
                '</li>';

    type = '';
  })

  form.innerHTML += listItem;
  $('.content').append(form)});
</code>```

答:
The best way to fix this would be to put your break, or your action, in the success callback of your ajax request, beside that you could use a boolean set in a beforeSend callback of your ajax request and wait while your boolean is still false :

```<code>$.getJSON(jsonUrl, function(data) {
var type, json, options;

var globalData = data;

  $.each(globalData.properties, function(key, value) {
  var isBusy = false;
    switch(value.type) {
      case 'string':
        type = '<input type="text">'
        break;
      case 'int':
        type = '<input type="number" min="0">'
        break;
      case 'decimal':
        type = '<input type="number" min="0" step="0.01">'
        break;
      case 'date':
        type = '<input type="date">'
        break;
      case 'boolean':
        type = '<input type="checkbox">'
        break;
      case 'json':
        json = './assets/json/' + value.json_name + '.json'

        $.ajax({
          async: false,
          url: json,
          beforeSend: function(){
            isBusy = true;
          },
          success: function(data) {
            isBusy = false;
            $.each(data, function(index, item) {
              options += '<option value=' + item.key + '>' + item.value + '</option>'
            })

            type = '<select id="issue-form"><option disabled selected value></option>' + options + '</select>';
          }
        });
            while(isBusy) {}
        break;
    }

listItem += '<li class="questionnaire_item">' +
              '<label>' +
                '<div class="question">' +
                  value.description + ':' +
                '</div>' +
                '<div class="input">' +
                  type +
                '</div>' +
              '</label>' +
            '</li>';

type = '';
  })

  form.innerHTML += listItem;
  $('.content').append(form)});
</code>```

But once agains it breaks the whole point of having an AJAX request, you better just prepare your data before loading the page and then show it.

To be honest this solutions is not the best one, i would go with promise as Rory said in the comments.

Title: Alternative for ajax async: false

Body:
break property fires before ajax completed. Only solution I've found is to make "async: false". But it is deprecated. Is there any better option to wait until ajax completed without setting async to false?

$.getJSON(jsonUrl, function(data) {
  var type, json, options;

  var globalData = data;

  $.each(globalData.properties, function(key, value) {
    switch(value.type) {
      case 'string':
        type = '<input type="text">'
        break;
      case 'int':
        type = '<input type="number" min="0">'
        break;
      case 'decimal':
        type = '<input type="number" min="0" step="0.01">'
        break;
      case 'date':
        type = '<input type="date">'
        break;
      case 'boolean':
        type = '<input type="checkbox">'
        break;
      case 'json':
        json = './assets/json/' + value.json_name + '.json'

        $.ajax({
          async: false,
          url: json,
          success: function(data) {
            $.each(data, function(index, item) {
              options += '<option value=' + item.key + '>' + item.value + '</option>'
            })

            type = '<select id="issue-form"><option disabled selected value></option>' + options + '</select>';
          }
        });

        break;
    }

    listItem += '
' +
                  '' +
                    '
' +
                      value.description + ':' +
                    '
' +
                    '
' +
                      type +
                    '
' +
                  '' +
                '
';

    type = '';
  })

  form.innerHTML += listItem;
  $('.content').append(form)});

Body:
The best way to fix this would be to put your break, or your action, in the success callback of your ajax request, beside that you could use a boolean set in a beforeSend callback of your ajax request and wait while your boolean is still false :

$.getJSON(jsonUrl, function(data) {
var type, json, options;

var globalData = data;

  $.each(globalData.properties, function(key, value) {
  var isBusy = false;
    switch(value.type) {
      case 'string':
        type = '<input type="text">'
        break;
      case 'int':
        type = '<input type="number" min="0">'
        break;
      case 'decimal':
        type = '<input type="number" min="0" step="0.01">'
        break;
      case 'date':
        type = '<input type="date">'
        break;
      case 'boolean':
        type = '<input type="checkbox">'
        break;
      case 'json':
        json = './assets/json/' + value.json_name + '.json'

        $.ajax({
          async: false,
          url: json,
          beforeSend: function(){
            isBusy = true;
          },
          success: function(data) {
            isBusy = false;
            $.each(data, function(index, item) {
              options += '<option value=' + item.key + '>' + item.value + '</option>'
            })

            type = '<select id="issue-form"><option disabled selected value></option>' + options + '</select>';
          }
        });
            while(isBusy) {}
        break;
    }

listItem += '<li class="questionnaire_item">' +
              '<label>' +
                '<div class="question">' +
                  value.description + ':' +
                '</div>' +
                '<div class="input">' +
                  type +
                '</div>' +
              '</label>' +
            '</li>';

type = '';
  })

  form.innerHTML += listItem;
  $('.content').append(form)});

But once agains it breaks the whole point of having an AJAX request, you better just prepare your data before loading the page and then show it.

To be honest this solutions is not the best one, i would go with promise as Rory said in the comments.


问:
While loop in bash script breaks systemd service
I'm on Debian and I have a systemd service that calls a bash script.

The script contains an infinite while loop, as I need it to check something every X seconds infinitely.

The systemd service crashes once it hits the "while true; do" line.

The script runs fine if I execute it manually.
Why doesn't systemd like it? What do I do?

Here are the service and the script. As I've indicated, an echo statement before the "while true; do" prints. The echo statement after the "while true; do" line does not print.

/etc/systemd/system/stream.service:

```<code>[Service]
WorkingDirectory=/home/pi/
ExecStart=/home/pi/joi_main.sh
Restart=no
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=stream_service
User=pi
Group=pi
Environment=NODE_ENV=production
[Install]
WantedBy=multi-user.target
</code>```

/home/pi/joi_main.sh:

```<code>#!/bin/bash -e

today=`/bin/date '+%Y_%m_%d__%H_%M_%S'`
exec 2> "/home/pi/stream_logs/$today.$RANDOM.log"
exec 1>&2

#Wait 120s for system to finish booting
sleep 120

#Initial config
export AUDIODEV=mic_mono
export AUDIODRIVER=alsa
sudo sysctl fs.pipe-max-size=1048576

echo "This line prints"

# Check if video buffer is full every minute. if full, the stream needs to restart
while true; do
    echo "This line doesn't"
    if grep "100% full" /home/pi/video_buffer_usage.txt; then
        echo "Buffer is full!"
    # Kill existing processes
        pkill -f “raspivid|rec|buffer|ffmpeg”
    # Wait 10s
         sleep 10
         ./joi_stream.sh &
    fi
    sleep 60
done
</code>```

Journalctl seems completely unhelpful, but here it is. No errors. Why is "session closed"?

```<code>Mar 31 02:13:41 raspberrypi sudo[1369]: pi : TTY=unknown ; PWD=/home/pi ; USER=root ; COMMAND=/sbin/sysctl fs.pipe-max-size=1048576
Mar 31 02:13:41 raspberrypi sudo[1369]: pam_unix(sudo:session): session opened for user root by (uid=0)
Mar 31 02:13:41 raspberrypi sudo[1369]: pam_unix(sudo:session): session closed for user root
</code>```

(Please don't tell me to start yet another systemd service for just this while loop. I want it to be part of this main script because it needs to run after everything else, and if I turn off the main service I don't want the while loop running either, so maintaining two systemd services would only add troube.)

答:
The contents of ./joi_stream.sh were not shared, but here's a problem I see with your systemd solution. It doesn't directly explain your behavior, but may be related:

In your systemd configuration, you redirect both STDOUT and STDERR to syslog, but in your script, you redirect STDERR (file descriptor "2") to a file, and redirect STDOUT (file descriptor "1') to STDERR.

```<code>exec 2> "/home/pi/stream_logs/$today.$RANDOM.log"
exec 1>&2
</code>```

If your ./joi_stream.sh expected your redirection of these file descriptors to another file to work, it may not. If the file is just for logging, I would get rid of these lines and let the systemd journal handle that-- it will tag the logs with your unit you can review your logs specifically:

```<code> journalctl -u your-unit-name.service
</code>```

Also, in systemd, you wouldn't normally put in a sleep to wait until the systemd has booted. Instead, you would use a .timer unit.

The .timer file would instruct to run the main logic every minute, so the "while" loop would not be required. The timer unit would contain directives like:

# Run for the first time 2 minutes after boot
   # and every minute after that
   OnBootSec=120
   OnUnitActiveSec=60

It would be timer unit which is enabled to start on boot. Timer files can be super-simple. Just create a .timer file in /etc/systemd/system and give it the same name as the service file you want it to activate:

```<code>[Unit]
Description=Runs my service every minute

[Timer]
# Run for the first time 2 minutes after boot
# and every minute after that
OnBootSec=120
OnUnitActiveSec=60

[Install]
WantedBy=timers.target
</code>```

To start and test your timer immediately, run:

```<code>sudo systemctl start my-service.timer
</code>```

You can review the status of timers with:

```<code>sudo systemctl list-timers
</code>```

The systemd solution is more robust than the rc.local solution. If your rc.local solution dies for any reason, it will not restart.  However, if your script dies will run under systemd, the timer will still run it again a minute later.

Body:
I'm on Debian and I have a systemd service that calls a bash script.

The script contains an infinite while loop, as I need it to check something every X seconds infinitely.

The systemd service crashes once it hits the "while true; do" line.

The script runs fine if I execute it manually.
Why doesn't systemd like it? What do I do?

Here are the service and the script. As I've indicated, an echo statement before the "while true; do" prints. The echo statement after the "while true; do" line does not print.

/etc/systemd/system/stream.service:

[Service]
WorkingDirectory=/home/pi/
ExecStart=/home/pi/joi_main.sh
Restart=no
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=stream_service
User=pi
Group=pi
Environment=NODE_ENV=production
[Install]
WantedBy=multi-user.target

/home/pi/joi_main.sh:

#!/bin/bash -e

today=`/bin/date '+%Y_%m_%d__%H_%M_%S'`
exec 2> "/home/pi/stream_logs/$today.$RANDOM.log"
exec 1>&2

#Wait 120s for system to finish booting
sleep 120

#Initial config
export AUDIODEV=mic_mono
export AUDIODRIVER=alsa
sudo sysctl fs.pipe-max-size=1048576

echo "This line prints"

# Check if video buffer is full every minute. if full, the stream needs to restart
while true; do
    echo "This line doesn't"
    if grep "100% full" /home/pi/video_buffer_usage.txt; then
        echo "Buffer is full!"
    # Kill existing processes
        pkill -f “raspivid|rec|buffer|ffmpeg”
    # Wait 10s
         sleep 10
         ./joi_stream.sh &
    fi
    sleep 60
done

Journalctl seems completely unhelpful, but here it is. No errors. Why is "session closed"?

Mar 31 02:13:41 raspberrypi sudo[1369]: pi : TTY=unknown ; PWD=/home/pi ; USER=root ; COMMAND=/sbin/sysctl fs.pipe-max-size=1048576
Mar 31 02:13:41 raspberrypi sudo[1369]: pam_unix(sudo:session): session opened for user root by (uid=0)
Mar 31 02:13:41 raspberrypi sudo[1369]: pam_unix(sudo:session): session closed for user root

(Please don't tell me to start yet another systemd service for just this while loop. I want it to be part of this main script because it needs to run after everything else, and if I turn off the main service I don't want the while loop running either, so maintaining two systemd services would only add troube.)

Body:
The contents of ./joi_stream.sh were not shared, but here's a problem I see with your systemd solution. It doesn't directly explain your behavior, but may be related:

In your systemd configuration, you redirect both STDOUT and STDERR to syslog, but in your script, you redirect STDERR (file descriptor "2") to a file, and redirect STDOUT (file descriptor "1') to STDERR.

exec 2> "/home/pi/stream_logs/$today.$RANDOM.log"
exec 1>&2

If your ./joi_stream.sh expected your redirection of these file descriptors to another file to work, it may not. If the file is just for logging, I would get rid of these lines and let the systemd journal handle that-- it will tag the logs with your unit you can review your logs specifically:

 journalctl -u your-unit-name.service

Also, in systemd, you wouldn't normally put in a sleep to wait until the systemd has booted. Instead, you would use a .timer unit.

The .timer file would instruct to run the main logic every minute, so the "while" loop would not be required. The timer unit would contain directives like:

# Run for the first time 2 minutes after boot
   # and every minute after that
   OnBootSec=120
   OnUnitActiveSec=60

It would be timer unit which is enabled to start on boot. Timer files can be super-simple. Just create a .timer file in /etc/systemd/system and give it the same name as the service file you want it to activate:

[Unit]
Description=Runs my service every minute

[Timer]
# Run for the first time 2 minutes after boot
# and every minute after that
OnBootSec=120
OnUnitActiveSec=60

[Install]
WantedBy=timers.target

To start and test your timer immediately, run:

sudo systemctl start my-service.timer

You can review the status of timers with:

sudo systemctl list-timers

The systemd solution is more robust than the rc.local solution. If your rc.local solution dies for any reason, it will not restart.  However, if your script dies will run under systemd, the timer will still run it again a minute later.