问:
I get NullPointerException in Java
Hello I get NullPointerException in this program can you help me ? Author class has private attributes and getter setter methods. Fileoperations class read a file and use stringtokenizer to split line by line. I getting an error at " athr[0].setId(tempId); " line. When i read from file tempId equals 100. I think problem is at Autor class but I couldn't fix that.

Author

```<code>public class Author {

    private int id;
    private String name;
    private String univ;
    private String depart;
    private String email;
    private String article[] = new String[5];
    private int artCtr=0;

    public int getArtCtr() {
        return artCtr;
    }

    public void setArtCtr(int artCtr) {
        this.artCtr = artCtr;
    }

    FileOperations flp =new FileOperations();

    public String getArticle(int nmb) {
        return article[nmb];
    }

    public void setArticle(String article,int nmb) {
        this.article[nmb] = article;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUniv() {
        return univ;
    }

    public void setUniv(String univ) {
        this.univ = univ;
    }

    public String getDepart() {
        return depart;
    }

    public void setDepart(String depart) {
        this.depart = depart;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

}
</code>```

FileOperations

```<code>import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;

public class FileOperations {

    Author athr[] = new Author[500];
    int athCtr = 0;
    int flag = 0;
    String temp;
    int tempId;

    public void strAthr(String path) throws IOException {
        String metin = "Suheyb";
        System.out.println(path);
        FileReader fl = new FileReader(path);

        try (BufferedReader read = new BufferedReader(fl)) {

            while (metin != null) {
                metin = read.readLine();
                if (metin != null) {
                    StringTokenizer str = new StringTokenizer(metin, "/t ");

                    if (str.hasMoreTokens()) {
                        temp = str.nextToken();
                        tempId = Integer.parseInt(str.nextToken());
                        System.out.println(tempId + " " + athCtr);

                        if (athCtr != 0) {
                            for (int i = 0; i < athCtr; i++) {
                                if (athr[i].getId() == tempId) {
                                    flag = 1;
                                    if (str.hasMoreTokens()) {
                                        athr[i].setName(str.nextToken());
                                        if (str.hasMoreTokens()) {
                                            athr[i].setDepart(str.nextToken());
                                            if (str.hasMoreTokens()) {
                                                athr[i].setEmail(str
                                                        .nextToken());
                                                if (str.hasMoreTokens()) {
                                                    athr[i].setArticle(
                                                            str.nextToken(), 0);
                                                    athr[i].setArtCtr(1);
                                                    if (str.hasMoreTokens()) {
                                                        athr[i].setArticle(
                                                                str.nextToken(),
                                                                1);
                                                        athr[i].setArtCtr(2);
                                                        if (str.hasMoreTokens()) {
                                                            athr[i].setArticle(
                                                                    str.nextToken(),
                                                                    2);
                                                            athr[i].setArtCtr(3);
                                                            if (str.hasMoreTokens()) {
                                                                athr[i].setArticle(
                                                                        str.nextToken(),
                                                                        3);
                                                                athr[i].setArtCtr(4);
                                                                if (str.hasMoreTokens()) {
                                                                    athr[i].setArticle(
                                                                            str.nextToken(),
                                                                            4);
                                                                    athr[i].setArtCtr(5);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            if (flag != 0) {
                                flag = 0;
                                athr[athCtr].setId(tempId);
                                if (str.hasMoreTokens()) {
                                    athr[athCtr].setName(str.nextToken());
                                    if (str.hasMoreTokens()) {
                                        athr[athCtr].setDepart(str.nextToken());
                                        if (str.hasMoreTokens()) {
                                            athr[athCtr].setEmail(str
                                                    .nextToken());
                                            if (str.hasMoreTokens()) {
                                                athr[athCtr].setArticle(
                                                        str.nextToken(), 0);
                                                athr[athCtr].setArtCtr(1);
                                                if (str.hasMoreTokens()) {
                                                    athr[athCtr].setArticle(
                                                            str.nextToken(), 1);
                                                    athr[athCtr].setArtCtr(2);
                                                    if (str.hasMoreTokens()) {
                                                        athr[athCtr]
                                                                .setArticle(
                                                                        str.nextToken(),
                                                                        2);
                                                        athr[athCtr]
                                                                .setArtCtr(3);
                                                        if (str.hasMoreTokens()) {
                                                            athr[athCtr]
                                                                    .setArticle(
                                                                            str.nextToken(),
                                                                            3);
                                                            athr[athCtr]
                                                                    .setArtCtr(4);
                                                            if (str.hasMoreTokens()) {
                                                                athr[athCtr]
                                                                        .setArticle(
                                                                                str.nextToken(),
                                                                                4);
                                                                athr[athCtr]
                                                                        .setArtCtr(5);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                athCtr++;

                            }

                        }

                        else {
                            System.out.println(tempId);
                            athr[0].setId(tempId);
                            System.out.println(athr[0].getId());
                            if (str.hasMoreTokens()) {

                                athr[athCtr].setName(str.nextToken());
                                if (str.hasMoreTokens()) {
                                    athr[athCtr].setDepart(str.nextToken());
                                    if (str.hasMoreTokens()) {
                                        athr[athCtr].setEmail(str.nextToken());
                                        if (str.hasMoreTokens()) {
                                            athr[athCtr].setArticle(
                                                    str.nextToken(), 0);
                                            athr[athCtr].setArtCtr(1);
                                            if (str.hasMoreTokens()) {
                                                athr[athCtr].setArticle(
                                                        str.nextToken(), 1);
                                                athr[athCtr].setArtCtr(2);
                                                if (str.hasMoreTokens()) {
                                                    athr[athCtr].setArticle(
                                                            str.nextToken(), 2);
                                                    athr[athCtr].setArtCtr(3);
                                                    if (str.hasMoreTokens()) {
                                                        athr[athCtr]
                                                                .setArticle(
                                                                        str.nextToken(),
                                                                        3);
                                                        athr[athCtr]
                                                                .setArtCtr(4);
                                                        if (str.hasMoreTokens()) {
                                                            athr[athCtr]
                                                                    .setArticle(
                                                                            str.nextToken(),
                                                                4);
                                                athr[athCtr]
                                                        .setArtCtr(5);
                                            }
                                        }
                                    }
                                }

enter code here

        }
                                    }
                                }
                            }
                            athCtr++;
                        }
                    }
                }
            }
        }
    }

}
</code>```

答:
I agree with this answer, than we need to initial use array element before using it.

```<code>for(int z=0;z<athr.length;z++){
     athr[z]=new Author();
   }
</code>```

But it looks like you are processing TSV file and storing data in Author object.

The simplest way to achieve this with less complexity would be

apache common csv example

It’s would really ease your program. It’s worth of having look as it.

## book.csv ##

author,title

Dan Simmons,Hyperion

Douglas Adams,The Hitchhiker's Guide to the Galaxy

code to read csv

```<code>List<Author> authList = ArrayList<>();
Author author = null;
Reader in = new FileReader("book.csv");
    Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(in);
    for (CSVRecord record : records) {
        author = new Author();
        author.setAuthor(record.get(0));
        author.setTitle(record.get(1));
        authList.add(author);
    }
</code>```

Title: I get NullPointerException in Java

Body:
Hello I get NullPointerException in this program can you help me ? Author class has private attributes and getter setter methods. Fileoperations class read a file and use stringtokenizer to split line by line. I getting an error at " athr[0].setId(tempId); " line. When i read from file tempId equals 100. I think problem is at Autor class but I couldn't fix that.

Author

public class Author {

    private int id;
    private String name;
    private String univ;
    private String depart;
    private String email;
    private String article[] = new String[5];
    private int artCtr=0;

    public int getArtCtr() {
        return artCtr;
    }

    public void setArtCtr(int artCtr) {
        this.artCtr = artCtr;
    }

    FileOperations flp =new FileOperations();

    public String getArticle(int nmb) {
        return article[nmb];
    }

    public void setArticle(String article,int nmb) {
        this.article[nmb] = article;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUniv() {
        return univ;
    }

    public void setUniv(String univ) {
        this.univ = univ;
    }

    public String getDepart() {
        return depart;
    }

    public void setDepart(String depart) {
        this.depart = depart;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

}

FileOperations

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;

public class FileOperations {

    Author athr[] = new Author[500];
    int athCtr = 0;
    int flag = 0;
    String temp;
    int tempId;

    public void strAthr(String path) throws IOException {
        String metin = "Suheyb";
        System.out.println(path);
        FileReader fl = new FileReader(path);

        try (BufferedReader read = new BufferedReader(fl)) {

            while (metin != null) {
                metin = read.readLine();
                if (metin != null) {
                    StringTokenizer str = new StringTokenizer(metin, "/t ");

                    if (str.hasMoreTokens()) {
                        temp = str.nextToken();
                        tempId = Integer.parseInt(str.nextToken());
                        System.out.println(tempId + " " + athCtr);

                        if (athCtr != 0) {
                            for (int i = 0; i < athCtr; i++) {
                                if (athr[i].getId() == tempId) {
                                    flag = 1;
                                    if (str.hasMoreTokens()) {
                                        athr[i].setName(str.nextToken());
                                        if (str.hasMoreTokens()) {
                                            athr[i].setDepart(str.nextToken());
                                            if (str.hasMoreTokens()) {
                                                athr[i].setEmail(str
                                                        .nextToken());
                                                if (str.hasMoreTokens()) {
                                                    athr[i].setArticle(
                                                            str.nextToken(), 0);
                                                    athr[i].setArtCtr(1);
                                                    if (str.hasMoreTokens()) {
                                                        athr[i].setArticle(
                                                                str.nextToken(),
                                                                1);
                                                        athr[i].setArtCtr(2);
                                                        if (str.hasMoreTokens()) {
                                                            athr[i].setArticle(
                                                                    str.nextToken(),
                                                                    2);
                                                            athr[i].setArtCtr(3);
                                                            if (str.hasMoreTokens()) {
                                                                athr[i].setArticle(
                                                                        str.nextToken(),
                                                                        3);
                                                                athr[i].setArtCtr(4);
                                                                if (str.hasMoreTokens()) {
                                                                    athr[i].setArticle(
                                                                            str.nextToken(),
                                                                            4);
                                                                    athr[i].setArtCtr(5);
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            if (flag != 0) {
                                flag = 0;
                                athr[athCtr].setId(tempId);
                                if (str.hasMoreTokens()) {
                                    athr[athCtr].setName(str.nextToken());
                                    if (str.hasMoreTokens()) {
                                        athr[athCtr].setDepart(str.nextToken());
                                        if (str.hasMoreTokens()) {
                                            athr[athCtr].setEmail(str
                                                    .nextToken());
                                            if (str.hasMoreTokens()) {
                                                athr[athCtr].setArticle(
                                                        str.nextToken(), 0);
                                                athr[athCtr].setArtCtr(1);
                                                if (str.hasMoreTokens()) {
                                                    athr[athCtr].setArticle(
                                                            str.nextToken(), 1);
                                                    athr[athCtr].setArtCtr(2);
                                                    if (str.hasMoreTokens()) {
                                                        athr[athCtr]
                                                                .setArticle(
                                                                        str.nextToken(),
                                                                        2);
                                                        athr[athCtr]
                                                                .setArtCtr(3);
                                                        if (str.hasMoreTokens()) {
                                                            athr[athCtr]
                                                                    .setArticle(
                                                                            str.nextToken(),
                                                                            3);
                                                            athr[athCtr]
                                                                    .setArtCtr(4);
                                                            if (str.hasMoreTokens()) {
                                                                athr[athCtr]
                                                                        .setArticle(
                                                                                str.nextToken(),
                                                                                4);
                                                                athr[athCtr]
                                                                        .setArtCtr(5);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                athCtr++;

                            }

                        }

                        else {
                            System.out.println(tempId);
                            athr[0].setId(tempId);
                            System.out.println(athr[0].getId());
                            if (str.hasMoreTokens()) {

                                athr[athCtr].setName(str.nextToken());
                                if (str.hasMoreTokens()) {
                                    athr[athCtr].setDepart(str.nextToken());
                                    if (str.hasMoreTokens()) {
                                        athr[athCtr].setEmail(str.nextToken());
                                        if (str.hasMoreTokens()) {
                                            athr[athCtr].setArticle(
                                                    str.nextToken(), 0);
                                            athr[athCtr].setArtCtr(1);
                                            if (str.hasMoreTokens()) {
                                                athr[athCtr].setArticle(
                                                        str.nextToken(), 1);
                                                athr[athCtr].setArtCtr(2);
                                                if (str.hasMoreTokens()) {
                                                    athr[athCtr].setArticle(
                                                            str.nextToken(), 2);
                                                    athr[athCtr].setArtCtr(3);
                                                    if (str.hasMoreTokens()) {
                                                        athr[athCtr]
                                                                .setArticle(
                                                                        str.nextToken(),
                                                                        3);
                                                        athr[athCtr]
                                                                .setArtCtr(4);
                                                        if (str.hasMoreTokens()) {
                                                            athr[athCtr]
                                                                    .setArticle(
                                                                            str.nextToken(),
                                                                4);
                                                athr[athCtr]
                                                        .setArtCtr(5);
                                            }
                                        }
                                    }
                                }

enter code here

        }
                                    }
                                }
                            }
                            athCtr++;
                        }
                    }
                }
            }
        }
    }

}

Body:
I agree with this answer, than we need to initial use array element before using it.

for(int z=0;z<athr.length;z++){
     athr[z]=new Author();
   }

But it looks like you are processing TSV file and storing data in Author object.

The simplest way to achieve this with less complexity would be

apache common csv example

It’s would really ease your program. It’s worth of having look as it.

## book.csv ##

author,title

Dan Simmons,Hyperion

Douglas Adams,The Hitchhiker's Guide to the Galaxy

code to read csv

List<Author> authList = ArrayList<>();
Author author = null;
Reader in = new FileReader("book.csv");
    Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(in);
    for (CSVRecord record : records) {
        author = new Author();
        author.setAuthor(record.get(0));
        author.setTitle(record.get(1));
        authList.add(author);
    }


来源: stackexchange

问:
Wait until a message has been received and pass the message body using C# RabbitMQ
I want to read a message from a queue, and once available wants to send the byte[] outside the consumer class.

```<code>public byte[] Receive()
{
    if (messagingAdapter == null)
        return default(byte[]);

    byte[] messageBody = null;
    var channel = messagingAdapter.GetChannel();
    channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);
    using (var subscription = new Subscription(channel, containerName, false))
    {
        while (channel.IsOpen)
        {
            var success = subscription.Next(5000, out BasicDeliverEventArgs eventArgs);
            if (success == false) continue;
            messageBody = eventArgs.Body;
            channel.BasicAck(eventArgs.DeliveryTag, false);
        }
    }
    return messageBody;
}
</code>```

In the above code, there are two issues (can be more).

1) Even after writing prefetchCount = 1, it still reads all the messages.
2) Ever after waiting for 5 seconds, I never get a success and I'm not able to send the body to outside.

I have written one more code, which does the same thing but in the post itself, it was written that it is not recommended way of doing.

Sample Code:

```<code>using (var signal = new ManualResetEvent(false))
{
    var consumer = new EventingBasicConsumer(channel);

    consumer.Received +=

    (sender, args) =>
    {
        messageBody = args.Body;
        signal.Set();
    };
    //// start consuming
    channel.BasicConsume(containerName, true, consumer);
    // wait until message is received or timeout reached
    bool timeout = !signal.WaitOne(TimeSpan.FromSeconds(10));
    // cancel subscription
    channel.BasicCancel(consumer.ConsumerTag);
    if (timeout)
    {
        // timeout reached - do what you need in this case
        throw new Exception("timeout");
    }
    return messageBody;
    // at this point messageBody is received
}
</code>```

答:
Try reading with channel.BasicGet instead, something like this:

```<code>private byte[] ReadRabbitMsg(IModel channel, string queue)
{
    if (channel.MessageCount(queue) == 0) return null;
    BasicGetResult result = channel.BasicGet(queue, true);
    if (result == null) return null;
    else
    {
        IBasicProperties props = result.BasicProperties;
        byte[] buff = result.Body;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to read a message from a queue, and once available wants to send the byte[] outside the consumer class.

public byte[] Receive()
{
    if (messagingAdapter == null)
        return default(byte[]);

    byte[] messageBody = null;
    var channel = messagingAdapter.GetChannel();
    channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);
    using (var subscription = new Subscription(channel, containerName, false))
    {
        while (channel.IsOpen)
        {
            var success = subscription.Next(5000, out BasicDeliverEventArgs eventArgs);
            if (success == false) continue;
            messageBody = eventArgs.Body;
            channel.BasicAck(eventArgs.DeliveryTag, false);
        }
    }
    return messageBody;
}

In the above code, there are two issues (can be more).

1) Even after writing prefetchCount = 1, it still reads all the messages.
2) Ever after waiting for 5 seconds, I never get a success and I'm not able to send the body to outside.

I have written one more code, which does the same thing but in the post itself, it was written that it is not recommended way of doing.

Sample Code:

using (var signal = new ManualResetEvent(false))
{
    var consumer = new EventingBasicConsumer(channel);

    consumer.Received +=

    (sender, args) =>
    {
        messageBody = args.Body;
        signal.Set();
    };
    //// start consuming
    channel.BasicConsume(containerName, true, consumer);
    // wait until message is received or timeout reached
    bool timeout = !signal.WaitOne(TimeSpan.FromSeconds(10));
    // cancel subscription
    channel.BasicCancel(consumer.ConsumerTag);
    if (timeout)
    {
        // timeout reached - do what you need in this case
        throw new Exception("timeout");
    }
    return messageBody;
    // at this point messageBody is received
}

Body:
Try reading with channel.BasicGet instead, something like this:

private byte[] ReadRabbitMsg(IModel channel, string queue)
{
    if (channel.MessageCount(queue) == 0) return null;
    BasicGetResult result = channel.BasicGet(queue, true);
    if (result == null) return null;
    else
    {
        IBasicProperties props = result.BasicProperties;
        byte[] buff = result.Body;
    }
}


问:
Regular expression to match single parentheses
I need to parse excel formulas to generate C-compatible code. Now I need to parse the "power" expressions using Java:

```<code>1. F15^2
2. (A1*A2)^2
3. SQRT((A1*A2)^2)
</code>```

I have the following regular expression:

```<code>(\([^)]*\)|\w+)\^(\([^)]*\)|\w+)
</code>```

This expression parses 1. and 2. correctly.

```<code>1. Group1: F15, group2: 2
2. Group1: (A1*A2), group2: 2
</code>```

However for 3. it returns 1 parenthesis too much:

```<code>3. Group1: ((A1*A2), group2: 2
</code>```

How should I modify my regular expression so group 1 becomes (A1*A2) instead of ((A1*A2) ?

Body:
I need to parse excel formulas to generate C-compatible code. Now I need to parse the "power" expressions using Java:

1. F15^2
2. (A1*A2)^2
3. SQRT((A1*A2)^2)

I have the following regular expression:

(\([^)]*\)|\w+)\^(\([^)]*\)|\w+)

This expression parses 1. and 2. correctly.

1. Group1: F15, group2: 2
2. Group1: (A1*A2), group2: 2

However for 3. it returns 1 parenthesis too much:

3. Group1: ((A1*A2), group2: 2

How should I modify my regular expression so group 1 becomes (A1*A2) instead of ((A1*A2) ?

Body:
adding () should work

(\([^)^(]*\)|\w+)\^(\([^)^(]*\)|\w+)


问:
Effort (C#) - 'Sequence contains no matching element' when seeding data to any of my entities
I am trying to build some unit tests for a few web service calls in my project. I am using Entity Framework 6.1.3 in my project to retrieve the data at the service layer (with a code-first approach). I did some research on how to Mock a DatabaseContext object and I found out that Effort can do this.

I followed the documentation when implementing Effort in my unit tests but when I try to seed data to my entities I get a "System.InvalidOperationException: 'Sequence contains no matching element'" exception. I am not entirely sure why this is happening. Any help will be much appreciated. Thanks!

Here is how the code looks like....

```<code>  //THE CALLER -- Doing what Effort suggests to do.

    var dbConnection = DbConnectionFactory.CreateTransient();
        FakeDbContext = new FakeDbContext(dbConnection);
        DatabaseSeed.AddTestData(FakeDbContext);
</code>```

Here is where I seed data to the entities...

```<code>public static void AddTestData(IFakeDbContext context)
    {
        //**************** IT CRASHES HERE *********************
        context.FakeEntity1.AddOrUpdate(new FakeEntity1
        {
           Name1 = "TestingName1",
           LastName1 = "TestingLastName1"

        });

        context.SaveChanges();
    }
</code>```

Here is my Entity Model...

```<code>[Table("rpt.FakeEntity1")]
public partial class FakeEntity1 : IFakeEntity1
{
    [Key]
    [Column(Order = 0)]
    [StringLength(20)]
    public string Name1 { get; set; }

    [Key]
    [Column(Order = 1)]
    [StringLength(20)]
    public string LastName1 { get; set; }

}
</code>```

Here is my DatabaseContext...

```<code>public partial class FakeDbContext: IFakeDbContext
{

    public FakeDbContext(DbConnection dbConnection)
                          : base(dbConnection, true)
    {
        //Effort requires this.
    }

}

public interface IFakeDbContext :IDisposable
{

    DbSet<FakeEntity1> FakeEntity1 {get; set;}

}
</code>```

I also have another class FakeDbContext.Base that overrides OnModelCreating.

Here is the Stack Trace:

StackTrace

答:
hope this helps.

Many answers says you have to add FirstorDefault() in your EF statements but this error also occurs in the incorrect properties using data annotations.

When using Data Annotations, be careful with the properties that you add.

Example below, I missed the TypeName = "string", which should have been nvarchar as it is the data type in the database.

Also, take note of the Order = n,(starts with 0)

Encountered this while updating a past colleagues source code.

```<code>[Display(Name = "Name")]
[MaxLength(4000)]
[Column("Name", Order = 14, TypeName = "string")]
public string Name { get; set; }
</code>```

then I corrected my code with

```<code>[Display(Name = "Name")]
[MaxLength(4000)]
[Column("Name", Order = 15, TypeName = "nvarchar")]
public string Name { get; set; }
</code>```

:)

Body:
I am trying to build some unit tests for a few web service calls in my project. I am using Entity Framework 6.1.3 in my project to retrieve the data at the service layer (with a code-first approach). I did some research on how to Mock a DatabaseContext object and I found out that Effort can do this.

I followed the documentation when implementing Effort in my unit tests but when I try to seed data to my entities I get a "System.InvalidOperationException: 'Sequence contains no matching element'" exception. I am not entirely sure why this is happening. Any help will be much appreciated. Thanks!

Here is how the code looks like....

  //THE CALLER -- Doing what Effort suggests to do.

    var dbConnection = DbConnectionFactory.CreateTransient();
        FakeDbContext = new FakeDbContext(dbConnection);
        DatabaseSeed.AddTestData(FakeDbContext);

Here is where I seed data to the entities...

public static void AddTestData(IFakeDbContext context)
    {
        //**************** IT CRASHES HERE *********************
        context.FakeEntity1.AddOrUpdate(new FakeEntity1
        {
           Name1 = "TestingName1",
           LastName1 = "TestingLastName1"

        });

        context.SaveChanges();
    }

Here is my Entity Model...

[Table("rpt.FakeEntity1")]
public partial class FakeEntity1 : IFakeEntity1
{
    [Key]
    [Column(Order = 0)]
    [StringLength(20)]
    public string Name1 { get; set; }

    [Key]
    [Column(Order = 1)]
    [StringLength(20)]
    public string LastName1 { get; set; }

}

Here is my DatabaseContext...

public partial class FakeDbContext: IFakeDbContext
{

    public FakeDbContext(DbConnection dbConnection)
                          : base(dbConnection, true)
    {
        //Effort requires this.
    }

}

public interface IFakeDbContext :IDisposable
{

    DbSet<FakeEntity1> FakeEntity1 {get; set;}

}

I also have another class FakeDbContext.Base that overrides OnModelCreating.

Here is the Stack Trace:

StackTrace

Body:
hope this helps.

Many answers says you have to add FirstorDefault() in your EF statements but this error also occurs in the incorrect properties using data annotations.

When using Data Annotations, be careful with the properties that you add.

Example below, I missed the TypeName = "string", which should have been nvarchar as it is the data type in the database.

Also, take note of the Order = n,(starts with 0)

Encountered this while updating a past colleagues source code.

[Display(Name = "Name")]
[MaxLength(4000)]
[Column("Name", Order = 14, TypeName = "string")]
public string Name { get; set; }

then I corrected my code with

[Display(Name = "Name")]
[MaxLength(4000)]
[Column("Name", Order = 15, TypeName = "nvarchar")]
public string Name { get; set; }

:)


问:
Fixed header above scrollable table
I am trying to have a table header, in a seperate div stay in place while a div undernearth is able to scroll al arge list of records. Both divs are in a div named Layer 3. Hereis the css file I am using:

#Layer3
{
    position:absolute;
    width: 89%;
    height: 40%;
    left: 10%;
    top: 56%;
    background-color: #f1ffff;
}

#Layer3 h1 {
    font-size: medium;
    color: #000033;
    text-decoration: none;
    text-align: center;
}

.tableheader {
}

.tablecontent {
    overflow: auto;
}
```

<p>and part of the php code I am using to generate the html:</p>

```echo '
';

echo "
{$query} Auctions
" . "\n";
echo "
";
echo '
';

echo "

" . "\n";

echo "Seller ID	" . "\n";
echo "Start Date	" . "\n";
echo "Description	" . "\n";

echo "
\n";

// printing table rows

foreach ($rows as $row)
{
    $pk = $row['ARTICLE_NO'];
    echo '
' . "\n";

    // table contens generated in here

    echo '
' . "\n";
}
}

echo "
";
```

I am not sure what I have missed, but tableheader does not seem to be stationary, or even separate from tablecontent.

答:
Allow me to pear down your problem to just the bare elements you're interested in.  In particular, I'll get rid of all the
 nodes.  Here's your very basic table:

```<code><table>
   <thead class="tableheader">
      <tr>
         <th>Seller ID</th>
         <th>Start Date</th>
         <th>Description</th>
      </tr>
   </thead>
   <tbody class="scrolling">
      <tr>
         <td>28</td><td>25 January 2009</td><td>Hello World!</td>
      </tr>
      <tr> etc. </tr>
   </tbody>
</table>
</code>```

(Notice the use of the
 element.)

Now here's the style sheet that will produce the scrolling you want:

.tableheader {
    display: block;
}

.scrolling {
    display: block;
    height: 300px;
    overflow: auto;
    width: 100%
}

th, td { /* first column */
    width: 200px
}

th + th, td + td { /* second column */
    width: 240px
}

th + th + th, td + td + td { /* third column */
    width: 316px
}
```

Notice that a consequence of setting display:block is that you have to fix the width of columns...

Title: Fixed header above scrollable table

Body:
I am trying to have a table header, in a seperate div stay in place while a div undernearth is able to scroll al arge list of records. Both divs are in a div named Layer 3. Hereis the css file I am using:

#Layer3
{
    position:absolute;
    width: 89%;
    height: 40%;
    left: 10%;
    top: 56%;
    background-color: #f1ffff;
}

#Layer3 h1 {
    font-size: medium;
    color: #000033;
    text-decoration: none;
    text-align: center;
}

.tableheader {
}

.tablecontent {
    overflow: auto;
}

and part of the php code I am using to generate the html:

echo '
';

echo "
{$query} Auctions
" . "\n";
echo "
";
echo '
';

echo "

" . "\n";

echo "Seller ID	" . "\n";
echo "Start Date	" . "\n";
echo "Description	" . "\n";

echo "
\n";

// printing table rows

foreach ($rows as $row)
{
    $pk = $row['ARTICLE_NO'];
    echo '
' . "\n";

    // table contens generated in here

    echo '
' . "\n";
}
}

echo "
";

I am not sure what I have missed, but tableheader does not seem to be stationary, or even separate from tablecontent.

Body:
Allow me to pear down your problem to just the bare elements you're interested in.  In particular, I'll get rid of all the <div> nodes.  Here's your very basic table:

<table>
   <thead class="tableheader">
      <tr>
         <th>Seller ID</th>
         <th>Start Date</th>
         <th>Description</th>
      </tr>
   </thead>
   <tbody class="scrolling">
      <tr>
         <td>28</td><td>25 January 2009</td><td>Hello World!</td>
      </tr>
      <tr> etc. </tr>
   </tbody>
</table>

(Notice the use of the <thead> element.)

Now here's the style sheet that will produce the scrolling you want:

.tableheader {
    display: block;
}

.scrolling {
    display: block;
    height: 300px;
    overflow: auto;
    width: 100%
}

th, td { /* first column */
    width: 200px
}

th + th, td + td { /* second column */
    width: 240px
}

th + th + th, td + td + td { /* third column */
    width: 316px
}

Notice that a consequence of setting display:block is that you have to fix the width of columns...

OwnerDisplayName: pierdeux

LastEditorDisplayName: pierdeux


问:
Appengine Datastore Advantages
I have used sql databases a fair bit and can see a lot of benefit in normalised databases that can be joined and searched and relationships built in them.

What are the advantages to the sort of 'object database' that google has in Appengine's datastore?

答:
Technically it's a lot easier to program since the datastore is bundled with the SDK and easier to share source code and collaborate since you're getting all components from the same vendor rather than patching together an RDMS, a scripting engine and hosting.

Economically, the costeffectiveness GAE ha is a huge advantage since you only pay for what you use. With other services and other hosting you pay like a subscriber while with the model GAE has you pay per quota.

ContentLicense: CC BY-SA 2.5

Title: Appengine Datastore Advantages


问:
Twig path without default locale
in my Symfony 3.3 project I use locale system to change the user language. I have configured my routing to allow the 'en' version for not having it in the url.

```<code>acme_front_office:
    resource: "@AcmeFrontOfficeBundle/Resources/config/routing.yml"
    prefix:   /{_locale}
    defaults: { _locale: 'en'}
    requirements:
        _locale: '|en|fr'
</code>```

So those url redirect all to the same page :

```<code>/home
/en/home
/fr/home
</code>```

But in my twig templates the {{ path() }} function set by default the right locale except that when my user see the english version of the website I want that the generated url head to /home and not /en/home.

If you have a clue on how to do that without changing all the path() calls to override the _locale param I will be very thankful.

Have a good day ;)

答:
So after some digging, the solution that I came up with is to rewrite some parts of the Symfony Routing system. If you want to check the solution you can find the code in the following gitlab repo, in the Routing dir.

TranslateBundle Repo

Title: Twig path without default locale

Body:
in my Symfony 3.3 project I use locale system to change the user language. I have configured my routing to allow the 'en' version for not having it in the url.

acme_front_office:
    resource: "@AcmeFrontOfficeBundle/Resources/config/routing.yml"
    prefix:   /{_locale}
    defaults: { _locale: 'en'}
    requirements:
        _locale: '|en|fr'

So those url redirect all to the same page :

/home
/en/home
/fr/home

But in my twig templates the {{ path() }} function set by default the right locale except that when my user see the english version of the website I want that the generated url head to /home and not /en/home.

If you have a clue on how to do that without changing all the path() calls to override the _locale param I will be very thankful.

Have a good day ;)

ContentLicense: CC BY-SA 4.0


问:
C++ Reading numbers from a file into an array and printing them into a different array
edit here's what's on the file

```<code>76 89 150 135 200 76 12 100 150 28 178 189 167 200 175 150 87 99 129 149 176 200 87 35 157 189
</code>```

I want help with something pretty simple. Below is a program that reads a text file with a number of grades on it. The program takes those numbers, stores them in an array, then determines what category they belong in, hence the setCategories function I've written. Once it sets the categories the number of each number in a category is stored in an array and that array is printed to another text file. Or at least it's supposed to - as of right now I don't have the getData and printData functions defined, which are the two I have positioned to do all the leg work/ I need some help writing these functions, for some reason I can't seem to wrap my head around them.

```<code> #include <iostream>
#include <fstream>

using namespace std;

void getData(istream & in, int A[], int & count)
{
    while(!in.eof())
    {
        in >> A[count++];
    }
}

void printData(ostream & out, int ctd[], int count)
{
    for (int i=0; i < count; i++)
    {
        out << ctd[i] << endl;
    }
}

void setCategories(int c[], int g[], int size) {
    int i;
    for (i = 0; i < size; i++) {
        if (g[i] > 174)
            c[7]++;
        else if (g[i] > 149)
            c[6]++;
        else if (g[i] > 124)
            c[5]++;
        else if (g[i] > 99)
            c[4]++;
        else if (g[i] > 74)
            c[3]++;
        else if (g[i] > 49)
            c[2]++;
        else if (g[i] > 24)
            c[1]++;
        else c[0]++;
    }
}

int main() {

    ofstream outFile;
    ifstream inFile;

    int categories[8] = {0, 0, 0, 0, 0, 0, 0, 0};
    int grades[40];
    int count = 0;

    inFile.open("/Users/holdentatlow/Desktop/computer_science_projects/test_scores.txt");
    outFile.open("/Users/holdentatlow/Desktop/computer_science_projects/results.txt");

    outFile << "Matthew Holden Tatlow" << endl;

    getData(inFile, grades, count);
    setCategories(categories, grades, count);
    printData(outFile, categories, count);

    return 0;

}
</code>```

Right now, my output file is pure nonsense:

```<code>  Matthew Holden Tatlow
1
2
0
6
1
3
5
8
262169208
1
0
0
262169416
1
-1196213792
32767
-520085504
32712
-520085410
32712
-520085410
32712
0
0
0
0
</code>```

答:
Here's a quick and dirty shot at the two functions:

```<code>void getData(istream & in, int A[], int & count)
{
    while(!in.eof())
    {
        in >> A[count++];
    }
}

void printData(ostream & out, int ctd[], int count)
{
    for (int i=0; i < count; i++)
    {
        out << ctd[i] << endl;
    }
}
</code>```

Note that I've changed the signature of printData to include a count. I am also just guessing at what you want here, so.. ymmv.

Body:
edit here's what's on the file

76 89 150 135 200 76 12 100 150 28 178 189 167 200 175 150 87 99 129 149 176 200 87 35 157 189

I want help with something pretty simple. Below is a program that reads a text file with a number of grades on it. The program takes those numbers, stores them in an array, then determines what category they belong in, hence the setCategories function I've written. Once it sets the categories the number of each number in a category is stored in an array and that array is printed to another text file. Or at least it's supposed to - as of right now I don't have the getData and printData functions defined, which are the two I have positioned to do all the leg work/ I need some help writing these functions, for some reason I can't seem to wrap my head around them.

 #include <iostream>
#include <fstream>

using namespace std;

void getData(istream & in, int A[], int & count)
{
    while(!in.eof())
    {
        in >> A[count++];
    }
}

void printData(ostream & out, int ctd[], int count)
{
    for (int i=0; i < count; i++)
    {
        out << ctd[i] << endl;
    }
}

void setCategories(int c[], int g[], int size) {
    int i;
    for (i = 0; i < size; i++) {
        if (g[i] > 174)
            c[7]++;
        else if (g[i] > 149)
            c[6]++;
        else if (g[i] > 124)
            c[5]++;
        else if (g[i] > 99)
            c[4]++;
        else if (g[i] > 74)
            c[3]++;
        else if (g[i] > 49)
            c[2]++;
        else if (g[i] > 24)
            c[1]++;
        else c[0]++;
    }
}

int main() {

    ofstream outFile;
    ifstream inFile;

    int categories[8] = {0, 0, 0, 0, 0, 0, 0, 0};
    int grades[40];
    int count = 0;

    inFile.open("/Users/holdentatlow/Desktop/computer_science_projects/test_scores.txt");
    outFile.open("/Users/holdentatlow/Desktop/computer_science_projects/results.txt");

    outFile << "Matthew Holden Tatlow" << endl;

    getData(inFile, grades, count);
    setCategories(categories, grades, count);
    printData(outFile, categories, count);

    return 0;

}

Right now, my output file is pure nonsense:

  Matthew Holden Tatlow
1
2
0
6
1
3
5
8
262169208
1
0
0
262169416
1
-1196213792
32767
-520085504
32712
-520085410
32712
-520085410
32712
0
0
0
0

Body:
Here's a quick and dirty shot at the two functions:

void getData(istream & in, int A[], int & count)
{
    while(!in.eof())
    {
        in >> A[count++];
    }
}

void printData(ostream & out, int ctd[], int count)
{
    for (int i=0; i < count; i++)
    {
        out << ctd[i] << endl;
    }
}

Note that I've changed the signature of printData to include a count. I am also just guessing at what you want here, so.. ymmv.


问:
Flexiprovider -- SecretKey manipulation
I'm using flexiprovider do some test about encrypting and decrypting text files using AES. I want to encrypt a text file, then encrypt the original but changing 1 bit of the key and then analyze the disturbance or variation between the two encrypted files but I'm keep getting this error "Exception in thread "main" java.security.InvalidKeyException: Unsupported key."
Well, here's my code</p>

```<code>public static void perturbacaoAES() throws Exception {
    Security.addProvider(new FlexiCoreProvider());

    Cipher cipher = Cipher.getInstance("AES128_CBC", "FlexiCore");
    KeyGenerator keyGen = KeyGenerator.getInstance("AES", "FlexiCore");
    SecretKey secKey = keyGen.generateKey();

    cipher.init(Cipher.ENCRYPT_MODE, secKey);

    FileInputStream fis = new FileInputStream("Zero.txt");
    FileOutputStream fos = new FileOutputStream("ZeroCifrado.txt");
    try (CipherOutputStream cos = new CipherOutputStream(fos, cipher)) {
        byte[] block = new byte[8];
        int i;
        while ((i = fis.read(block)) != -1) {
            cos.write(block, 0, i);
        }
    }
    fis.close();
    fos.close();

    byte[] newKey = secKey.getEncoded();

    newKey[0] ^= 1 << 1;

    secKey = new SecretKeySpec(newKey, "AES128_CBC");

    cipher.init(Cipher.ENCRYPT_MODE, secKey);

    FileInputStream nfis = new FileInputStream("Zero.txt");
    FileOutputStream nfos = new FileOutputStream("ZeroChaveCifrado.txt");
    try (CipherOutputStream cos = new CipherOutputStream(nfos, cipher)) {
        byte[] block = new byte[8];
        int i;
        while ((i = nfis.read(block)) != -1) {
            cos.write(block, 0, i);
        }
    }

}
</code>```

答: Well, looks like the method was expecting a RijndaelKey object and not a SecretKeySpec object. </p>

Title: Flexiprovider -- SecretKey manipulation

Body:
I'm using flexiprovider do some test about encrypting and decrypting text files using AES. I want to encrypt a text file, then encrypt the original but changing 1 bit of the key and then analyze the disturbance or variation between the two encrypted files but I'm keep getting this error "Exception in thread "main" java.security.InvalidKeyException: Unsupported key."
Well, here's my code

public static void perturbacaoAES() throws Exception {
    Security.addProvider(new FlexiCoreProvider());

    Cipher cipher = Cipher.getInstance("AES128_CBC", "FlexiCore");
    KeyGenerator keyGen = KeyGenerator.getInstance("AES", "FlexiCore");
    SecretKey secKey = keyGen.generateKey();

    cipher.init(Cipher.ENCRYPT_MODE, secKey);

    FileInputStream fis = new FileInputStream("Zero.txt");
    FileOutputStream fos = new FileOutputStream("ZeroCifrado.txt");
    try (CipherOutputStream cos = new CipherOutputStream(fos, cipher)) {
        byte[] block = new byte[8];
        int i;
        while ((i = fis.read(block)) != -1) {
            cos.write(block, 0, i);
        }
    }
    fis.close();
    fos.close();

    byte[] newKey = secKey.getEncoded();

    newKey[0] ^= 1 << 1;

    secKey = new SecretKeySpec(newKey, "AES128_CBC");

    cipher.init(Cipher.ENCRYPT_MODE, secKey);

    FileInputStream nfis = new FileInputStream("Zero.txt");
    FileOutputStream nfos = new FileOutputStream("ZeroChaveCifrado.txt");
    try (CipherOutputStream cos = new CipherOutputStream(nfos, cipher)) {
        byte[] block = new byte[8];
        int i;
        while ((i = nfis.read(block)) != -1) {
            cos.write(block, 0, i);
        }
    }

}


问:
VBA code to search for string then a second string and return lines of data from a text file
I am trying to search through large log files to find a string of text, then if that string is present to find another string of text and then return the next 5 lines of data. I have managed to search the text file for the string and return the 5 lines after however I cannot seem to get the macro to search for both lines of text before returning the 5 lines.

For example if the text file looked like this:

17:42:56: Log File Closed
17:42:56: PrintInvoice: 2
17:42:56: copyReportData:
17:42:56: getNextRptDataID:
17:42:58: CalcDelCharge:
17:42:58:    Sub Total: 3.80
17:42:58:    Del Total: 0.00
17:42:58:    Disc Total: 0.00
17:42:58:    Vat Total: 0.00
17:42:58:    Inv Total: 3.80
18:33:00: CalculateAmtDue:
18:33:00: CalculateChange:
18:33:00: UpdateDelCharge:
18:33:00: UpdateTotals
18:42:58: CalcDelCharge:
18:42:58:    Sub Total: 5.80
18:42:58:    Del Total: 0.00
18:42:58:    Disc Total: 0.00
18:42:58:    Vat Total: 0.00
18:42:58:    Inv Total: 5.80

I want to extract the 5 lines after the first 'CalcDelCharge' as it is follows 'PrintInvoice: 2', which is one of the strings I am also wanting to search for.

The text file contains 'CalcDelCharge' throughout, however I am only interested in the instances when it comes after 'PrintInvoice: 2', which appears much less frequently.

Here is what I have so far

```<code>Dim fn As String, txt As String, delim As String, a() As String
Dim i As Long, ii As Long, iii As Long, x, y
fn = "C:\Documents\tilllogfile.log"
delim = vbTab
temp = CreateObject("Scripting.FileSystemObject").OpenTextFile(fn).ReadAll
x = Split(temp, vbCrLf)
ReDim a(1 To UBound(x) + 1, 1 To 100)
For i = 0 To UBound(x)
    If InStr(1, x(i), "CalcDelCharge", 1) Then
    For ii = 0 To 5
        n = n + 1: y = Split(x(i + ii), delim)
        For iii = 0 To UBound(y)
            a(n, iii + 1) = y(iii)
        Next
    Next
End If
</code>```

This will extract 5 lines after all 'CalcDelCharge' and put it into a spreadsheet for me, I have not been able to narrow it down to the instances when it follows 'PrintInvoice: 2'.

Any help would be greatly appreciated.

Thanks.

答:
Here is my version (with no booleans), just uses some nested loops. Here we place the values into an array for you to do whatever you want with:

Sample Data:

```<code>Option Explicit
Sub Test()
Dim searchvalue1 As String, searchvalue2 As String, myarray() As Variant, i As Long, j As Long, k As Long, l As Long

ReDim myarray(0 To 0)
searchvalue1 = "PrintInvoice: 2"
searchvalue2 = "CalcDelCharge:"
l = 1

For i = 1 To 100
    If InStr(Range("A" & i).Value, searchvalue1) > 0 Then
        For j = i + 1 To 100
            If InStr(Range("A" & j).Value, searchvalue2) > 0 Then
                For k = 0 To 4
                    ReDim Preserve myarray(UBound(myarray) + 1) As Variant
                    myarray(k) = Range("A" & j + l).Value
                    l = l + 1
                    Debug.Print myarray(k)
                Next k
            End If
        Next j
    End If
Next i

End Sub
</code>```

Immediate window:

Body:
I am trying to search through large log files to find a string of text, then if that string is present to find another string of text and then return the next 5 lines of data. I have managed to search the text file for the string and return the 5 lines after however I cannot seem to get the macro to search for both lines of text before returning the 5 lines.

For example if the text file looked like this:

17:42:56: Log File Closed
17:42:56: PrintInvoice: 2
17:42:56: copyReportData:
17:42:56: getNextRptDataID:
17:42:58: CalcDelCharge:
17:42:58:    Sub Total: 3.80
17:42:58:    Del Total: 0.00
17:42:58:    Disc Total: 0.00
17:42:58:    Vat Total: 0.00
17:42:58:    Inv Total: 3.80
18:33:00: CalculateAmtDue:
18:33:00: CalculateChange:
18:33:00: UpdateDelCharge:
18:33:00: UpdateTotals
18:42:58: CalcDelCharge:
18:42:58:    Sub Total: 5.80
18:42:58:    Del Total: 0.00
18:42:58:    Disc Total: 0.00
18:42:58:    Vat Total: 0.00
18:42:58:    Inv Total: 5.80

I want to extract the 5 lines after the first 'CalcDelCharge' as it is follows 'PrintInvoice: 2', which is one of the strings I am also wanting to search for.

The text file contains 'CalcDelCharge' throughout, however I am only interested in the instances when it comes after 'PrintInvoice: 2', which appears much less frequently.

Here is what I have so far

Dim fn As String, txt As String, delim As String, a() As String
Dim i As Long, ii As Long, iii As Long, x, y
fn = "C:\Documents\tilllogfile.log"
delim = vbTab
temp = CreateObject("Scripting.FileSystemObject").OpenTextFile(fn).ReadAll
x = Split(temp, vbCrLf)
ReDim a(1 To UBound(x) + 1, 1 To 100)
For i = 0 To UBound(x)
    If InStr(1, x(i), "CalcDelCharge", 1) Then
    For ii = 0 To 5
        n = n + 1: y = Split(x(i + ii), delim)
        For iii = 0 To UBound(y)
            a(n, iii + 1) = y(iii)
        Next
    Next
End If

This will extract 5 lines after all 'CalcDelCharge' and put it into a spreadsheet for me, I have not been able to narrow it down to the instances when it follows 'PrintInvoice: 2'.

Any help would be greatly appreciated.

Thanks.

Body:
Here is my version (with no booleans), just uses some nested loops. Here we place the values into an array for you to do whatever you want with:

Sample Data:

Option Explicit
Sub Test()
Dim searchvalue1 As String, searchvalue2 As String, myarray() As Variant, i As Long, j As Long, k As Long, l As Long

ReDim myarray(0 To 0)
searchvalue1 = "PrintInvoice: 2"
searchvalue2 = "CalcDelCharge:"
l = 1

For i = 1 To 100
    If InStr(Range("A" & i).Value, searchvalue1) > 0 Then
        For j = i + 1 To 100
            If InStr(Range("A" & j).Value, searchvalue2) > 0 Then
                For k = 0 To 4
                    ReDim Preserve myarray(UBound(myarray) + 1) As Variant
                    myarray(k) = Range("A" & j + l).Value
                    l = l + 1
                    Debug.Print myarray(k)
                Next k
            End If
        Next j
    End If
Next i

End Sub

Immediate window:


问:
how to use Oauth connector in mule?
I'm very new to mulesoft and anypoint platform. can anybody please guide me about how to use  Oauth connector in mule and also how to apply Oauth 2.0 policy to api?

 thanks in advance.

答:
Please go through the document to understand about policy. https://docs.mulesoft.com/api-manager/introduction-to-policy-management.

Using OAuth Connector needs the parameters which is required for any OAuth. Client secret, client id, etc. So please have a look into it.

Title: how to use Oauth connector in mule?


问:
Adding variable inside .find() with data attribute
I have the following:

```<code>.find("[data-list='read']")
</code>```

and I want to add a JS variable inside, something like this:

```<code>.find("[data-list=''+ $variable +'']")
</code>```

Obviously, the two single quotations won't work in this case. Do I need to escape the single quotations in some way? What's the approach in JS?

答:
You can use template literals or just concatenate the strings preserving the "text'" + var + "'text" style.

var variable = 'myText';
var tlSelector = `[data-list='${variable}']`;
var concStrings = "[data-list='" + variable +"']";

console.log(tlSelector);
console.log(concStrings);```

Body:
I have the following:

.find("[data-list='read']")

and I want to add a JS variable inside, something like this:

.find("[data-list=''+ $variable +'']")

Obviously, the two single quotations won't work in this case. Do I need to escape the single quotations in some way? What's the approach in JS?


问:
Account Linking In Alexa
We are building complete serverless architecture using AWS services for all of our api's (using API Gateway + Lambda functions + DynamoDB) and to control our devices we are using aws-iot platform. Mobile to devices interaction will happen over the aws-iot. On mobile side for user management we are using firebase and all business logic is in Lambda function. Now we want to work with Alexa with our existing architecture flow, but we are confused with the account linking part.  Do we have to implement our own auth server which will take care of authorization part or should we move to cognito user pool + login with Amazon, so that we will have user management and auth at the same platform.</p>

答: The documentation states the following providers can be used for authentication Github, Facebook, Twitter, Google. I don't see how you'd be able to link in with Amazon / Alexa. Also I'm not sure why you would want to use Firebase and not AWS Cognito.   </p>

Title: Account Linking In Alexa


问:
predicting proper regular expression from seeing target string
I want to know it is possible to predict proper regular expression by seeing several strings. For example, regex ^[a-z0-9_-]{3,16}$ will match my-us3r_n4m3 and ^[a-z0-9_-]{6,18}$ match myp4ssw0rd. But after seeing my-us3r_n4m3, is it possible output ^[a-z0-9_-]{3,16}$ or ^[a-z0-9_-]{6,18}$from seeing myp4ssw0rd.

I guess this would be stupid question, and I don't want to predict exact regular expression.

Anyone who has idea for this, pls let me know.
Thanks.

答:
The problem is that there is an infinite number of regular expressions that have matched your string.  Even simpler than /.*/ is // which also matches everything.

Still, you can find a practical solution for your problem if you describe more precisely what your regular expression should look like.  For the type of regexes that you used in your example, the following will do the job:

```<code>my @strings = ('myp4ssw0rd', 'my-us3r_n4m3');

my %characters;
my ($min, $max) = map { length } $strings[0], $strings[0];

foreach my $string (@strings) {
    my $l = length $string;
    if ($l < $min) {
        $min = $l;
    } elsif ($l > $max) {
        $max = $l;
    }
    map { $characters{$_} = 1 } split //, $string;
}

my $range = join '', map { quotemeta $_ } keys %characters;
print "[$range]{$min,$max}\n";
</code>```

But that is very generic.  It pretty much answers three questions:

which characters were used in the passwords?

what was the minimum length?

what was the maximum length?

Not really rocket science but you can maybe use it as a starting point to a solution of the problem.

Body:
The problem is that there is an infinite number of regular expressions that have matched your string.  Even simpler than /.*/ is // which also matches everything.

Still, you can find a practical solution for your problem if you describe more precisely what your regular expression should look like.  For the type of regexes that you used in your example, the following will do the job:

my @strings = ('myp4ssw0rd', 'my-us3r_n4m3');

my %characters;
my ($min, $max) = map { length } $strings[0], $strings[0];

foreach my $string (@strings) {
    my $l = length $string;
    if ($l < $min) {
        $min = $l;
    } elsif ($l > $max) {
        $max = $l;
    }
    map { $characters{$_} = 1 } split //, $string;
}

my $range = join '', map { quotemeta $_ } keys %characters;
print "[$range]{$min,$max}\n";

But that is very generic.  It pretty much answers three questions:

which characters were used in the passwords?

what was the minimum length?

what was the maximum length?

Not really rocket science but you can maybe use it as a starting point to a solution of the problem.


答:
String concatenation should look like this:

```<code>"[data-list='" + $variable + "']"
</code>```

To break it down: string1 + string2 + string3 where

```<code>string1 = "[data-list='"
string2 = $variable
string3 = "']"
</code>```

Title: Adding variable inside .find() with data attribute

Body:
String concatenation should look like this:

"[data-list='" + $variable + "']"

To break it down: string1 + string2 + string3 where

string1 = "[data-list='"
string2 = $variable
string3 = "']"


问:
How to create invincible windows application using c# and windows services
I wrote a windows form application running in my local system. I wanna make it invictible. I mean, I want to the users cannot kill the process using task manager or any other third party application. So I wrote a windows service to run this application on startup. I thought I need to run windows service as SYSTEM but how can I do that ?

Is there any spesific suggestion for this kind a situation ?

答:
I also had the same problem with an application at work, which the users shouldn't be able to close.

You have to allow the servie Allow service to interact with desktop.
Heres an example how to do this while installing the service: http://www.codeproject.com/KB/install/cswindowsservicedesktop.aspx

Now you are able the launch a GUI application from the service, for the current logged in user. You should look in a intervall if the process for the current user is still running, if not just start it again.

See here for current user processes: http://www.codeproject.com/KB/cs/processownersid.aspx


问:
Firebase redirect user to a page after clicking verification link
I'm using firebase in my web app with Ionic and I would like to redirect the user to a specific page (the login page, in my case) after he clicks on the link in the verification email.

At the moment, when the user clicks on the verification link, he is redirected on another browser page that says that he has confirmed the email.

I would like to redirect him directly to a page of my web app, without passing through that confirmation.

Is it possible to do that?

答:
Yes it's possible. Look in the firebase.console on the left for "Authentication".
Then find "Templates" and look for "Email address verification". I think it's default opened. On the template you will see a small pencil, click on it. After that you can change your template however you want. At the bottom you will find the link "customize action URL". Open this link, paste your URL in the modal window and save. That's it.


问:
How to do Typing Replay in JavaScript?
I am wondering how typeracer is doing this kinda words reply with also mistakes made while typing I am confused and I have no Idea how to do this in JavaScript

答:
There are hundreds of plugins available out there. One simple way is to use something like this:

var app = document.getElementById('app');

var typewriter = new Typewriter(app, {
  loop: true
});

typewriter.typeString('Hello World!')
  .pauseFor(2500)
  .deleteAll()
  .typeString('Strings can be removed')
  .pauseFor(2500)
  .deleteChars(7)
  .typeString('altered!')
  .start();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/TypewriterJS/1.0.0/typewriter.min.js"></script>
<div id="app"></div></code>```

Title: How to do Typing Replay in JavaScript?

Body:
There are hundreds of plugins available out there. One simple way is to use something like this:

var app = document.getElementById('app');

var typewriter = new Typewriter(app, {
  loop: true
});

typewriter.typeString('Hello World!')
  .pauseFor(2500)
  .deleteAll()
  .typeString('Strings can be removed')
  .pauseFor(2500)
  .deleteChars(7)
  .typeString('altered!')
  .start();

<script src="https://cdnjs.cloudflare.com/ajax/libs/TypewriterJS/1.0.0/typewriter.min.js"></script>
<div id="app"></div>


问:
"the outputpath property is not set for this project" error
I have a multi project solution in Visual Studio 2008. I just added a new Configuration called Release-VersionIncrement to the solution, specifying "use release" configuration as baseline. All project files were updated with that configuration. However, when I am trying to compile a specific project using this configuration, I get the following error:

Error 5   The OutputPath property is not
  set for this project.  Please check to
  make sure that you have specified a
  valid Configuration/Platform
  combination.
  Configuration='Release-VersionIncrement'
  Platform='AnyCPU' C:\WINDOWS\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets    539 9   DataConversion

What's happening here? The project compiles fine in Release or Debug configuration.

答:
When I added new solution configuration in my solution, I got an error, "The OutputPath property is not set for project X. Please check to make sure that you have specified a valid combination of Configuration and Platform for this project.  Configuration='QA'  Platform='AnyCPU'.  This error may also appear if some other project is trying to follow a project-to-project reference to this project, this project has been unloaded or is not included in the solution, and the referencing project does not build using the same or an equivalent Configuration or Platform.   ProjectY".

In my case issue was due to highlighted part of the error description. Project X part of my solution was having a project reference to ProjectY of another solution(different branch).

I've resolved this issue by modifying project X to use project reference to ProjectY in the current solution. Hope this helps someone having similar issue.


问:
Unable to create a list that is able to dinstinguish between integer and float based on user input
The code is supposed to create a list of five list's, with each list created from the numbers the user input each time (of five). So e.g. if user key in

```<code>1 2 3 4 5

1 2

1.5 2

2.2

1
</code>```

The output should be : [[1, 2, 3, 4, 5], [1, 2], [1.5, 2], [2,2], [1]]
Any help is appreciated. I understand that to solve this problem, you need to convert the string into a int or float, but cannot seem to get it to work.

```<code>nlist = []
n = len(nlist)

while n < 5:
    num = input("Enter a Number: ").split()

    for x in num:

        if '.' in num[x]:
            num[x] = float(num[x])
        else:
            num[x] = int(num[x])

    nlist.append(num)
    n = n + 1
print(nlist)
</code>```

答:
Basically in your code you try to acces the xth element of list num within your for in loop, however x is not the index of an element inside the list but a reference to it.

Take a look at the modified code:

```<code>nlist = []
n = len(nlist)

while n < 5:
    num = input("Enter a Number: ").split()

    tmplist = []
    for x in num:

        if '.' in x:
            x = float(x)
        else:
            x = int(x)

        tmplist.append(x)

    nlist.append(tmplist)
    n = n + 1
print(nlist)
</code>```

So for the following input:

```<code>Enter a Number: 1 2 3 4 5
Enter a Number: 1 2
Enter a Number: 1.5 2
Enter a Number: 2.2
Enter a Number: 1
</code>```

It will output:

```<code>[[1, 2, 3, 4, 5], [1, 2], [1.5, 2], [2.2], [1]]
</code>```

Body:
The code is supposed to create a list of five list's, with each list created from the numbers the user input each time (of five). So e.g. if user key in

1 2 3 4 5

1 2

1.5 2

2.2

1

The output should be : [[1, 2, 3, 4, 5], [1, 2], [1.5, 2], [2,2], [1]]
Any help is appreciated. I understand that to solve this problem, you need to convert the string into a int or float, but cannot seem to get it to work.

nlist = []
n = len(nlist)

while n < 5:
    num = input("Enter a Number: ").split()

    for x in num:

        if '.' in num[x]:
            num[x] = float(num[x])
        else:
            num[x] = int(num[x])

    nlist.append(num)
    n = n + 1
print(nlist)

Body:
Basically in your code you try to acces the xth element of list num within your for in loop, however x is not the index of an element inside the list but a reference to it.

Take a look at the modified code:

nlist = []
n = len(nlist)

while n < 5:
    num = input("Enter a Number: ").split()

    tmplist = []
    for x in num:

        if '.' in x:
            x = float(x)
        else:
            x = int(x)

        tmplist.append(x)

    nlist.append(tmplist)
    n = n + 1
print(nlist)

So for the following input:

Enter a Number: 1 2 3 4 5
Enter a Number: 1 2
Enter a Number: 1.5 2
Enter a Number: 2.2
Enter a Number: 1

It will output:

[[1, 2, 3, 4, 5], [1, 2], [1.5, 2], [2.2], [1]]


问:
Array skip for loop
I am facing an issue in removing a specific field from my nested arrays.
I provide you an example of my arrays:

```<code> Array

       (
            [0] => Array
                (
                    [no] => 1
                    [id] => 4
                    [cmp_name] => dimple
                    [group_code] => 35727748
                    [dd_name] =>
                    [email_id] => soima@xsinfosol.com
                    [mobile_no] => 9971858674
                    [additional_email] =>
                    [additional_mobile] =>
                    [email_status] => Sent
                    [sms_status] => 0
                    [read_status] => <i class='fa fa-square-o' style='font-size:30px;color:red'></i>
                    [mail_acceptence] => <i class='fa fa-thumbs-o-down' style='font-size:30px;color:red'></i>
                    [sms_acceptence] => 0
                    [action] => <a href='#' data-toggle='modal' data-target='#template_detail_1' class='btn btn-info btn-xs pop' data-placement='top' title='dimple'><i class='fa fa-list-alt'></i></a><button class='btn btn-danger btn-xs delete-swl' data-toggle='tooltip' data-placement='top' title='4' ><i class='fa fa-trash-o'></i></button>
                )

            [1] => Array
                (
                    [no] => 2
                    [id] => 4
                    [cmp_name] => dimple
                    [group_code] => 35727748
                    [dd_name] =>
                    [email_id] => deepakdreams.soni@gmail.com
                    [mobile_no] => 9971858674
                    [additional_email] =>
                    [additional_mobile] =>
                    [email_status] => Sent
                    [sms_status] => 0
                    [read_status] => <i class='fa fa-check-square-o' style='font-size:30px;color:green'></i>
                    [mail_acceptence] => <i class='fa fa-thumbs-o-up' style='font-size:30px;color:green'></i>
                    [sms_acceptence] => 0
                    [action] => <a href='#' data-toggle='modal' data-target='#template_detail_1' class='btn btn-info btn-xs pop' data-placement='top' title='dimple'><i class='fa fa-list-alt'></i></a><button class='btn btn-danger btn-xs delete-swl' data-toggle='tooltip' data-placement='top' title='4' ><i class='fa fa-trash-o'></i></button>
                )
        }
</code>```

I want to remove read_status from both of my nested arrays.

答:
```<code>for($i=0;$i<count($array);$i++){
    unset($array[$i]['read_status']);
}
</code>```

For more info

Title: Array skip for loop

Body:
I am facing an issue in removing a specific field from my nested arrays.
I provide you an example of my arrays:

 Array

       (
            [0] => Array
                (
                    [no] => 1
                    [id] => 4
                    [cmp_name] => dimple
                    [group_code] => 35727748
                    [dd_name] =>
                    [email_id] => soima@xsinfosol.com
                    [mobile_no] => 9971858674
                    [additional_email] =>
                    [additional_mobile] =>
                    [email_status] => Sent
                    [sms_status] => 0
                    [read_status] =>
                    [mail_acceptence] =>
                    [sms_acceptence] => 0
                    [action] => <button class='btn btn-danger btn-xs delete-swl' data-toggle='tooltip' data-placement='top' title='4' ></button>
                )

            [1] => Array
                (
                    [no] => 2
                    [id] => 4
                    [cmp_name] => dimple
                    [group_code] => 35727748
                    [dd_name] =>
                    [email_id] => deepakdreams.soni@gmail.com
                    [mobile_no] => 9971858674
                    [additional_email] =>
                    [additional_mobile] =>
                    [email_status] => Sent
                    [sms_status] => 0
                    [read_status] =>
                    [mail_acceptence] =>
                    [sms_acceptence] => 0
                    [action] => <button class='btn btn-danger btn-xs delete-swl' data-toggle='tooltip' data-placement='top' title='4' ></button>
                )
        }

I want to remove read_status from both of my nested arrays.

Body:
for($i=0;$i<count($array);$i++){
    unset($array[$i]['read_status']);
}

For more info


问:
Choosing rows based on grouping condition and field condition
I would like to know how could I choose out these plots where I have together trees "HB" and "KU"?

This is an example of my dataset:

```<code>       plot ID             tree
1    10000503711            LV
2  1000057448111            LV
3  1000057448111            HB
4  1000057448111            KU
5    10000603711            LV
6  1000063448111            TM
7  1000063448111            KS
</code>```

So the result should be something like this (it shouldn't erase other tree species from my dataset but it should choose those plot ID-s where there are both "KU" and "HB"):

```<code>   2  1000057448111            LV
   3  1000057448111            HB
   4  1000057448111            KU
</code>```

Note that some plots have multiple trees growing in them resulting multiple rows per plot. And some plots only have one tree species.

Thank you for your help!

Body:
I would like to know how could I choose out these plots where I have together trees "HB" and "KU"?

This is an example of my dataset:

       plot ID             tree
1    10000503711            LV
2  1000057448111            LV
3  1000057448111            HB
4  1000057448111            KU
5    10000603711            LV
6  1000063448111            TM
7  1000063448111            KS

So the result should be something like this (it shouldn't erase other tree species from my dataset but it should choose those plot ID-s where there are both "KU" and "HB"):

   2  1000057448111            LV
   3  1000057448111            HB
   4  1000057448111            KU

Note that some plots have multiple trees growing in them resulting multiple rows per plot. And some plots only have one tree species.

Thank you for your help!

Body:
Here's a base solution.

ss <- read.table(text = "       plot ID             tree
1    10000503711            LV
                 2  1000057448111            LV
                 3  1000057448111            HB
                 4  1000057448111            KU
                 5    10000603711            LV
                 6  1000063448111            TM
                 7  1000063448111            KS", header = TRUE,
                 colClasses = c("numeric", "character", "character"))

ss[ss$ID %in% unique(ss[ss$tree %in% c("HB", "KU"), "ID"]), ]

  plot            ID tree
2    2 1000057448111   LV
3    3 1000057448111   HB
4    4 1000057448111   KU


问:
How can I have my netty client detect if my netty server listens on a port (is available)?
I have a netty client that works fine if the server application is listening. But if the server application is not running and therefore not listening on the port, the client still runs as if it expects the server to be there.

I would like to handle the case when the server is not listening and in such a case not even send the data (and do something else instead, like telling the user to contact an admin or so). Is this even possible?

Note:
If the client attempts to connect to an unspecified port or ip, my client throws exceptions which I can handle. My issue is that no exceptions are thrown when the server is not listening on the port it should normally listen to.

答:
Yeap. Sometimes you can't detect that server is down/not listening on port anymore.

So for that case, you may add to your client pipeline ReadTimeoutHandler. Which will throw ReadTimeoutException in case your client didn't get any message from the server within the certain period of time.
However, this may be not enough. For example, when your connection between server and client is not very active this exception could be thrown too. So for that case, you may need to implement ping-pong handlers, that will tell for your ReadTimeoutHandler that connection is active and it will not throw the exception in that case.


问:
Set a page margins
I have this stylesheet, but the right and left margins are too large (about 5 cm), I don't know how to reduce them. I'd like to have 3 cm right and left.

I tried to change page_width, but it did't work.

Thanks,

rubik

答:
Okay, well number one your

```<code>div.document {
    width: {{ page_width }}px;
    margin: 0 auto;
}
</code>```

is set to margin: 0 auto; which makes it centered so your page will be 940px and will be centered (Resizing your page will confirm this). You probably have to change your content width along with the wrapper width, but keep in mind that the amount of padding depends on how large your viewport is.

Alternate

If you just want to make it strictly 3cm on the left and right sides and make the content in the middle have a fluid layout you can do this:

```<code>        margin: 0 3cm;
        position: absolute;
        width: auto;
</code>```

Title: Set a page margins

Body:
Okay, well number one your

div.document {
    width: {{ page_width }}px;
    margin: 0 auto;
}

is set to margin: 0 auto; which makes it centered so your page will be 940px and will be centered (Resizing your page will confirm this). You probably have to change your content width along with the wrapper width, but keep in mind that the amount of padding depends on how large your viewport is.

Alternate

If you just want to make it strictly 3cm on the left and right sides and make the content in the middle have a fluid layout you can do this:

        margin: 0 3cm;
        position: absolute;
        width: auto;


问:
Is that possible to use css variable in css "background url"
I would like to set a base domain with all of my pictures in CSS file, here's what I tried:

global.css

```<code>:root
{
  --bgd: #C0C0C0;
  --picdomain: "https://somedomain.com/";
}
</code>```

s1.css

```<code>@import url("global.css");

body
{
  background-color: var(--bgd); //works if only it exist
  background: url(var(--picdomain)"some/path/images/pic.png"); //no effect
}
</code>```

And load s1.css in html

```<code><link rel="stylesheet" type="text/css" href="s1.css">
</code>```

The HTML's background-color did changed, but background didn't show up. So I tried other way:

global.css

```<code>@picdomain: "https://somedomain.com";
</code>```

s1.css

```<code>background: url("@picdomain/some/path/images/pic.png");  //can't read variable from imported css
</code>```

didn't help

Only works while I set full URL for an image, like below:

global.css

```<code>:root
{
  --bgd: #C0C0C0;
  --picdomain: url("https://somedomain.com/some/path/images/pic.png");
}
</code>```

s1.css

```<code>@import url("global.css");

body
{
  background-color: var(--bgd); //works if only it exist
  background: var(--picdomain); //no effect
}
</code>```

But this isn't what I want......Is that possible to use css variable in "background"?

答:
```<code>    <style type="text/css">
    :root {
        --slide-1: url("{{url('public/assets/images/logo-nfs.png')}}"); /*this is laravel*/
        --slide-2: url("<?php echo 'images/logo-nfs.png';?>");
    }`enter code here`

    .header111 {
      background-image : var(--slide-1); /*this is php*/
    }

    .header22 {
      background-image : var(--slide-2);
    }

    </style>

<div class="header111">
  test here
</div>

<div class="header22">
  test here
</div>
<br>
</code>```

Body:
I would like to set a base domain with all of my pictures in CSS file, here's what I tried:

global.css

:root
{
  --bgd: #C0C0C0;
  --picdomain: "https://somedomain.com/";
}

s1.css

@import url("global.css");

body
{
  background-color: var(--bgd); //works if only it exist
  background: url(var(--picdomain)"some/path/images/pic.png"); //no effect
}

And load s1.css in html

<link rel="stylesheet" type="text/css" href="s1.css">

The HTML's background-color did changed, but background didn't show up. So I tried other way:

global.css

@picdomain: "https://somedomain.com";

s1.css

background: url("@picdomain/some/path/images/pic.png");  //can't read variable from imported css

didn't help

Only works while I set full URL for an image, like below:

global.css

:root
{
  --bgd: #C0C0C0;
  --picdomain: url("https://somedomain.com/some/path/images/pic.png");
}

s1.css

@import url("global.css");

body
{
  background-color: var(--bgd); //works if only it exist
  background: var(--picdomain); //no effect
}

But this isn't what I want......Is that possible to use css variable in "background"?


问:
How much can we scale the data in Neo4j
I have 5 million products and 100 000 sellers as data in Neo4j database.The sellers have some common products among all the products portfolio. These products and sellers are the nodes and the relationships between them are edges in the Neo4j database. How to scale the Neo4j database. Can anyone help me out.

答:
With just some millions of nodes (and generally the double in term of relationships), the size of your database will be less than 10Gb ...

So about the storage, everything fits on a server (even on a USB key ^^).

For the rest of your question (complexity & query performance) it depends a lot of what kind of queries you want to do, so it's an opened question ...

The only thing I can tell you without more information, is that the performance of queries is not dependent of the size of your graph.

Cheers.

Title: How much can we scale the data in Neo4j


问:
Convert PHP array to JavaScript array
I want to convert a multi-dimensional PHP array to JavaScript and found this script in a post here;

```<code><script type='text/javascript'>
<?php
$js_array = json_encode($php_array);
echo "var javascript_array = ". $js_array . ";\n";
?>
</script>
</code>```

But the JS array remains empty. Is it because I have a multi-dimensional array?

答:
You can also try something more manual like this:</p>

```<code><?php
// $phpArray= ...
?>
<script type="text/javascript">

  var jsArray = {};
  <?php foreach($phpArray as $key => $val){ ?>
      jsArray.<?php echo $key; ?> = "<?php echo $val; ?>";
  <?php } ?>
  console.log(jsArray);
</script>
</code>```

Title: Convert PHP array to JavaScript array

Body:
I want to convert a multi-dimensional PHP array to JavaScript and found this script in a post here;

But the JS array remains empty. Is it because I have a multi-dimensional array?

Body:
You can also try something more manual like this:

<?php
// $phpArray= ...
?>
<script type="text/javascript">

  var jsArray = {};
  <?php foreach($phpArray as $key => $val){ ?>
      jsArray.<?php echo $key; ?> = "<?php echo $val; ?>";
  <?php } ?>
  console.log(jsArray);
</script>


问:
Generic class with array
I want to create a custom generic class for my Java project and this is how far I got - I found the code as an example on how to create generic arrays.

```<code>public class RegisterSet<T> {
   private T[] register;
   public <T> RegisterSet(int size) {
      register = (T[])Array.newInstance(T, size);
   }
}
</code>```

Now, I get the error Incompatible types - found: T[], required: T[] which makes absolutely no sense to me - how can I fix this?

答:
There are two bugs:

First: The class defines a type T, and second the Method defines it own type T, but both T's hase nothing to do with each other. -- So you have to remove the extra Type T from the methods declaration:

```<code>public RegisterSet(int size) {
</code>```

instead of:

```<code> public <T> RegisterSet(int size) {
</code>```

Second: The method  Array.newInstance requires an instance of Class as its first parameter, but the type T is not an instance of class. - What you need is to intoduce an new parameter of type Class to you constructor argument list, and use this parameter for array creation.

At least all together should look like:

```<code>  import java.lang.reflect.Array;

  public class RegisterSet<T> {
    private T[] register;

    public RegisterSet(int size, Class<T> clazz) {
       @SuppressWarnings("unchecked")
       T[] register = (T[]) Array.newInstance(clazz, size);
    }
  }

  ...
  new RegisterSet<Integer>(5, Integer.class)
</code>```

Title: Generic class with array

Body:
I want to create a custom generic class for my Java project and this is how far I got - I found the code as an example on how to create generic arrays.

public class RegisterSet<T> {
   private T[] register;
   public <T> RegisterSet(int size) {
      register = (T[])Array.newInstance(T, size);
   }
}

Now, I get the error Incompatible types - found: T[], required: T[] which makes absolutely no sense to me - how can I fix this?

Body:
There are two bugs:

First: The class defines a type T, and second the Method defines it own type T, but both T's hase nothing to do with each other. -- So you have to remove the extra Type T from the methods declaration:

public RegisterSet(int size) {

instead of:

 public <T> RegisterSet(int size) {

Second: The method  Array.newInstance requires an instance of Class as its first parameter, but the type T is not an instance of class. - What you need is to intoduce an new parameter of type Class to you constructor argument list, and use this parameter for array creation.

At least all together should look like:

  import java.lang.reflect.Array;

  public class RegisterSet<T> {
    private T[] register;

    public RegisterSet(int size, Class<T> clazz) {
       @SuppressWarnings("unchecked")
       T[] register = (T[]) Array.newInstance(clazz, size);
    }
  }

  ...
  new RegisterSet<Integer>(5, Integer.class)


问:
Unit Testing with jest enzyme returns SyntaxError: Unexpected token
I'm trying to run a unit test on React. I'm using jest and enzyme.

Here's my .babelrc

```<code>{
    "presets": ["es2015", "react", "airbnb"]
}
</code>```

My test file:

```<code>import React from 'react';
import { shallow, mount, render } from 'enzyme';

import Home from './Home/Home.js';

describe('Home', function() {
    it('should render without throwing an error', function() {
        expect(shallow(<Home />).contains(<div className="columns is-mobile"></div>)).toBe(true);
    });
});
</code>```

when I run npm test

I get the following error:

```<code>FAIL  client\components\Home.test.js
  ● Test suite failed to run

    C:\Users\KeOt777\Kevin Ruiz - Front End Software Engineer\video_portal_api-master\client\components\Home\Home.css:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.columns {
                                                                                ^

    SyntaxError: Unexpected token .

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:305:17)
      at Object.<anonymous> (client/components/Home/Home.js:4:1)
      at Object.<anonymous> (client/components/Home.test.js:4:13)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        2.373s
Ran all test suites.
npm ERR! Test failed.  See above for more details.
</code>```

Can anyone help me see why my test is failing to run?

答:
you can try to use ES6 proxy instead. Install via npm using

```<code>npm install --save-dev identity-obj-proxy
</code>```

then in your configuration file for jest, change module mapper for css to something like this

```<code>"\\.(css|less)$": "identity-obj-proxy"
</code>```

See more in jest docs.

Body:
I'm trying to run a unit test on React. I'm using jest and enzyme.

Here's my .babelrc

{
    "presets": ["es2015", "react", "airbnb"]
}

My test file:

import React from 'react';
import { shallow, mount, render } from 'enzyme';

import Home from './Home/Home.js';

describe('Home', function() {
    it('should render without throwing an error', function() {
        expect(shallow(<Home />).contains(

)).toBe(true);
    });
});

when I run npm test

I get the following error:

FAIL  client\components\Home.test.js
  ● Test suite failed to run

    C:\Users\KeOt777\Kevin Ruiz - Front End Software Engineer\video_portal_api-master\client\components\Home\Home.css:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.columns {
                                                                                ^

    SyntaxError: Unexpected token .

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:305:17)
      at Object.<anonymous> (client/components/Home/Home.js:4:1)
      at Object.<anonymous> (client/components/Home.test.js:4:13)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        2.373s
Ran all test suites.
npm ERR! Test failed.  See above for more details.

Can anyone help me see why my test is failing to run?

Body:
you can try to use ES6 proxy instead. Install via npm using

npm install --save-dev identity-obj-proxy

then in your configuration file for jest, change module mapper for css to something like this

"\\.(css|less)$": "identity-obj-proxy"

See more in jest docs.


问:
My htaccess file keeps bring up 404 errors
I am not to clued up on these and I'm struggling to get this one working.

I just keep getting 404 errors, can someone give me a hand?

```<code>RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [QSA,L]
</code>```

This is what I have so far. I'm using the CodeIgniter framework.

答:
```<code>try this.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</code>```

Body:
I am not to clued up on these and I'm struggling to get this one working.

I just keep getting 404 errors, can someone give me a hand?

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [QSA,L]

This is what I have so far. I'm using the CodeIgniter framework.


问:
Visual Studio 2017 Indent Guide Coloring
In Visual Studio 2015, I had coloring for the indent guides like this.

I can't seem to find this feature in Visual Studio 2017.  Is there an extension that does this?

There's an option in the Fonts and Colors to change the color for all Guidelines.  But what I want is the same in 2015 where it's automatically color coded (blue, green, teal, purple, etc.) depending on the type/level of the braces.

答: Native in VS2017. It's called "Structure Guide Lines"