问:
C# ElasticSearch get external objects by nested list element property comparison
Let's suppose we have the following 2 objects (Please ignore the strange situation, as it is used only to model the real issue):

```<code>public class Person
{
    public string FullName { get; set; }
    public decimal TotalSalary { get; set; }
    public List<Position> Positions { get; set; } = new List<Position>();
}

public class Position
{
    public string Name { get; set; }
    public bool IsCurrentPosition { get; set; }
    public DateTime ExpirationDate { get; set; }
    public int? MonthsWorked { get; set; }
    public bool HasAverageLimitStatistic { get; set; } = false;
    public int AverageMonthLimit { get; set; } = 0;
    public decimal Salary { get; set; }
    public string CompanyName { get; set; }
}
</code>```

How do I write a query in NEST (C#) to find all people who work (or worked) on positions which are coming close to AverageMonthLimit in a timespan of a year, (positions without AverageMonthLimit are ignored); in case MonthsWorked is provided than compare it to AverageMonthLimit, otherwise take today's date and compare it to ExpirationDate.

PS: If the position has the statistic, then minimal AverageMonthLimit is of 36 months. People might work on several jobs.

NOTE: MSSQL script would probably look like:

```<code>SELECT *
FROM Person p
JOIN Position pos
    ON pos.PersonId = p.Id
WHERE
    pos.HasAverageLimitStatistic = 1
        AND pos.AverageMonthLimit > pos.MonthsWorked
        AND pos.AverageMonthLimit - 12 < pos.MonthsWorked
    OR pos.HasAverageLimitStatistic = 0
        AND DATEDIFF(MONTH, GETDATE(), pos.ExpirationDate) > 0
        AND DATEDIFF(MONTH, GETDATE(), pos.ExpirationDate) < 12
</code>```

UPDATE

Correct me if I'm wrong, but I presume the question boils down to the following, where query is unknown:

```<code>var response = _elasticClient.Search<Person>(s => s.Query(q =>
    .DateRange(x => x
    .Field(p => p.Employees
        .First(pos => pos.HasAverageLimitStatistic == null)
        .ExpirationDate)
    .GreaterThan(DateTime.Now)
    .LessThan(DateTime.Now.AddYear(1)))
    // upper code finds customers who don't have statistic
|| q.Nested(x => x
    .Path(p => p.Positions)
    .Query(qq => qq.Script.Inline(" ?????? "))));
</code>```

答:
When querying against nested types, you need to use nested queries, which will take care of querying against the internal documents that nested types are modelled with.

Here's what your SQL query would look like in Elasticsearch

```<code>var searchResponse = client.Search<Person>(s => s
    .Query(q => q
        .Nested(n => n
            .Path(p => p.Positions)
            .Query(nq => (+nq
                .Term(f => f.Positions.First().HasAverageLimitStatistic, true) && +nq
                .Script(sq => sq
                    .Inline("doc['positions.monthsWorked'].value != 0 && doc['positions.averageMonthLimit'].value > doc['positions.monthsWorked'].value")
                ) && +nq
                .Script(sq => sq
                    .Inline("doc['positions.monthsWorked'].value != 0 && (doc['positions.averageMonthLimit'].value - 12) < doc['positions.monthsWorked'].value")
                )) || (+nq
                .Term(f => f.Positions.First().HasAverageLimitStatistic, false) && +nq
                .DateRange(d => d
                    .Field(f => f.Positions.First().ExpirationDate)
                    .GreaterThan(DateTime.Now.Date)
                    .LessThan(DateTime.Now.Date.AddYears(1))
                ))
            )
        )
    )
);
</code>```

There's a fair bit going here, so I'll break it down

Inside the top level query, a nested query will be performed. Since all predicates (i.e. WHERE clauses) are based on properties of nested types, these queries will all be inside of the nested query.

Specify the Path to the nested type on the top level type

Inside the nested query's query, 3 queries are &&ed together within parentheses for the first set of predicates where HasAverageLimitStatistic is true and 3 queries are &&ed together in parentheses for the second set of predicates where HasAverageLimitStatistic is false.

Since all queries test whether some condition is true or not, we can forgo calculating a score for them by making them filter clauses in a bool query. NEST has handy shorthand for bool query filter clauses in the form of the unary + operator. Similarly, there are overloaded operators combining queries with && and ||

Because you want to compare two properties on an indexed document, you need to use a script query to do this. In Elasticsearch 5.x, the default language for this is Painless.

The query DSL JSON for the above query is

```<code>{
  "query": {
    "nested": {
      "query": {
        "bool": {
          "should": [
            {
              "bool": {
                "filter": [
                  {
                    "term": {
                      "positions.hasAverageLimitStatistic": {
                        "value": true
                      }
                    }
                  },
                  {
                    "script": {
                      "script": {
                        "inline": "doc['positions.monthsWorked'].value != 0 && doc['positions.averageMonthLimit'].value > doc['positions.monthsWorked'].value"
                      }
                    }
                  },
                  {
                    "script": {
                      "script": {
                        "inline": "doc['positions.monthsWorked'].value != 0 && (doc['positions.averageMonthLimit'].value - 12) < doc['positions.monthsWorked'].value"
                      }
                    }
                  }
                ]
              }
            },
            {
              "bool": {
                "filter": [
                  {
                    "term": {
                      "positions.hasAverageLimitStatistic": {
                        "value": false
                      }
                    }
                  },
                  {
                    "range": {
                      "positions.expirationDate": {
                        "gt": "2017-06-03T00:00:00-07:00",
                        "lt": "2018-06-03T00:00:00-07:00"
                      }
                    }
                  }
                ]
              }
            }
          ]
        }
      },
      "path": "positions"
    }
  }
}
</code>```

Finally, here's a complete example to demonstrate

```<code>void Main()
{
    var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));

    var connectionSettings = new ConnectionSettings(pool)
        .InferMappingFor<Person>(m => m
            .IndexName("people")
        )
        .PrettyJson()
        .DisableDirectStreaming()
        .OnRequestCompleted(response =>
            {
                // log out the request
                if (response.RequestBodyInBytes != null)
                {
                    Console.WriteLine(
                        $"{response.HttpMethod} {response.Uri} \n" +
                        $"{Encoding.UTF8.GetString(response.RequestBodyInBytes)}");
                }
                else
                {
                    Console.WriteLine($"{response.HttpMethod} {response.Uri}");
                }

                Console.WriteLine();

                // log out the response
                if (response.ResponseBodyInBytes != null)
                {
                    Console.WriteLine($"Status: {response.HttpStatusCode}\n" +
                             $"{Encoding.UTF8.GetString(response.ResponseBodyInBytes)}\n" +
                             $"{new string('-', 30)}\n");
                }
                else
                {
                    Console.WriteLine($"Status: {response.HttpStatusCode}\n" +
                             $"{new string('-', 30)}\n");
                }
            });

    var client = new ElasticClient(connectionSettings);

    if (client.IndexExists("people").Exists)
    {
        client.DeleteIndex("people");
    }

    client.CreateIndex("people", c => c
        .Mappings(m => m
            .Map<Person>(mm => mm
                .AutoMap()
                .Properties(p => p
                    .Nested<Position>(n => n
                        .Name(nn => nn.Positions)
                        .AutoMap()
                    )
                )
            )
        )
    );

    client.IndexMany(new[] {
        new Person
        {
            FullName = "Person 1",
            TotalSalary = 100000,
            Positions = new List<Position>
            {
                new Position
                {
                    Name = "Janitor",
                    AverageMonthLimit = 5,
                    MonthsWorked = 3,
                    HasAverageLimitStatistic = true
                }
            }
        },
        new Person
        {
            FullName = "Person 2",
            TotalSalary = 150000,
            Positions = new List<Position>
            {
                new Position
                {
                    Name = "Coach",
                    AverageMonthLimit = 5,
                    HasAverageLimitStatistic = true
                }
            }
        },
        new Person
        {
            FullName = "Person 3",
            TotalSalary = 200000,
            Positions = new List<Position>
            {
                new Position
                {
                    Name = "Teacher",
                    HasAverageLimitStatistic = false,
                    ExpirationDate = DateTime.Now.AddMonths(6)
                }
            }
        },
        new Person
        {
            FullName = "Person 4",
            TotalSalary = 250000,
            Positions = new List<Position>
            {
                new Position
                {
                    Name = "Head",
                    HasAverageLimitStatistic = false,
                    ExpirationDate = DateTime.Now.AddYears(2)
                }
            }
        }
    });

    client.Refresh(IndexName.From<Person>());

    var searchResponse = client.Search<Person>(s => s
        .Query(q => q
            .Nested(n => n
                .Path(p => p.Positions)
                .Query(nq => (+nq
                    .Term(f => f.Positions.First().HasAverageLimitStatistic, true) && +nq
                    .Script(sq => sq
                        .Inline("doc['positions.monthsWorked'].value != 0 && doc['positions.averageMonthLimit'].value > doc['positions.monthsWorked'].value")
                    ) && +nq
                    .Script(sq => sq
                        .Inline("doc['positions.monthsWorked'].value != 0 && (doc['positions.averageMonthLimit'].value - 12) < doc['positions.monthsWorked'].value")
                    )) || (+nq
                    .Term(f => f.Positions.First().HasAverageLimitStatistic, false) && +nq
                    .DateRange(d => d
                        .Field(f => f.Positions.First().ExpirationDate)
                        .GreaterThan(DateTime.Now.Date)
                        .LessThan(DateTime.Now.Date.AddYears(1))
                    ))
                )
            )
        )
    );

}

public class Person
{
    public string FullName { get; set; }
    public decimal TotalSalary { get; set; }
    public List<Position> Positions { get; set; } = new List<Position>();
}

public class Position
{
    public string Name { get; set; }
    public bool IsCurrentPosition { get; set; }
    public DateTime ExpirationDate { get; set; }
    public int? MonthsWorked { get; set; }
    public bool HasAverageLimitStatistic { get; set; } = false;
    public int AverageMonthLimit { get; set; } = 0;
    public decimal Salary { get; set; }
    public string CompanyName { get; set; }
}
</code>```

Based on the query criteria, only Person 1 and Person 3 are returned.

Body:
Let's suppose we have the following 2 objects (Please ignore the strange situation, as it is used only to model the real issue):

public class Person
{
    public string FullName { get; set; }
    public decimal TotalSalary { get; set; }
    public List<Position> Positions { get; set; } = new List<Position>();
}

public class Position
{
    public string Name { get; set; }
    public bool IsCurrentPosition { get; set; }
    public DateTime ExpirationDate { get; set; }
    public int? MonthsWorked { get; set; }
    public bool HasAverageLimitStatistic { get; set; } = false;
    public int AverageMonthLimit { get; set; } = 0;
    public decimal Salary { get; set; }
    public string CompanyName { get; set; }
}

How do I write a query in NEST (C#) to find all people who work (or worked) on positions which are coming close to AverageMonthLimit in a timespan of a year, (positions without AverageMonthLimit are ignored); in case MonthsWorked is provided than compare it to AverageMonthLimit, otherwise take today's date and compare it to ExpirationDate.

PS: If the position has the statistic, then minimal AverageMonthLimit is of 36 months. People might work on several jobs.

NOTE: MSSQL script would probably look like:

SELECT *
FROM Person p
JOIN Position pos
    ON pos.PersonId = p.Id
WHERE
    pos.HasAverageLimitStatistic = 1
        AND pos.AverageMonthLimit > pos.MonthsWorked
        AND pos.AverageMonthLimit - 12 < pos.MonthsWorked
    OR pos.HasAverageLimitStatistic = 0
        AND DATEDIFF(MONTH, GETDATE(), pos.ExpirationDate) > 0
        AND DATEDIFF(MONTH, GETDATE(), pos.ExpirationDate) < 12

UPDATE

Correct me if I'm wrong, but I presume the question boils down to the following, where query is unknown:

var response = _elasticClient.Search<Person>(s => s.Query(q =>
    .DateRange(x => x
    .Field(p => p.Employees
        .First(pos => pos.HasAverageLimitStatistic == null)
        .ExpirationDate)
    .GreaterThan(DateTime.Now)
    .LessThan(DateTime.Now.AddYear(1)))
    // upper code finds customers who don't have statistic
|| q.Nested(x => x
    .Path(p => p.Positions)
    .Query(qq => qq.Script.Inline(" ?????? "))));

Body:
When querying against nested types, you need to use nested queries, which will take care of querying against the internal documents that nested types are modelled with.

Here's what your SQL query would look like in Elasticsearch

var searchResponse = client.Search<Person>(s => s
    .Query(q => q
        .Nested(n => n
            .Path(p => p.Positions)
            .Query(nq => (+nq
                .Term(f => f.Positions.First().HasAverageLimitStatistic, true) && +nq
                .Script(sq => sq
                    .Inline("doc['positions.monthsWorked'].value != 0 && doc['positions.averageMonthLimit'].value > doc['positions.monthsWorked'].value")
                ) && +nq
                .Script(sq => sq
                    .Inline("doc['positions.monthsWorked'].value != 0 && (doc['positions.averageMonthLimit'].value - 12) < doc['positions.monthsWorked'].value")
                )) || (+nq
                .Term(f => f.Positions.First().HasAverageLimitStatistic, false) && +nq
                .DateRange(d => d
                    .Field(f => f.Positions.First().ExpirationDate)
                    .GreaterThan(DateTime.Now.Date)
                    .LessThan(DateTime.Now.Date.AddYears(1))
                ))
            )
        )
    )
);

There's a fair bit going here, so I'll break it down

Inside the top level query, a nested query will be performed. Since all predicates (i.e. WHERE clauses) are based on properties of nested types, these queries will all be inside of the nested query.

Specify the Path to the nested type on the top level type

Inside the nested query's query, 3 queries are &&ed together within parentheses for the first set of predicates where HasAverageLimitStatistic is true and 3 queries are &&ed together in parentheses for the second set of predicates where HasAverageLimitStatistic is false.

Since all queries test whether some condition is true or not, we can forgo calculating a score for them by making them filter clauses in a bool query. NEST has handy shorthand for bool query filter clauses in the form of the unary + operator. Similarly, there are overloaded operators combining queries with && and ||

Because you want to compare two properties on an indexed document, you need to use a script query to do this. In Elasticsearch 5.x, the default language for this is Painless.

The query DSL JSON for the above query is

{
  "query": {
    "nested": {
      "query": {
        "bool": {
          "should": [
            {
              "bool": {
                "filter": [
                  {
                    "term": {
                      "positions.hasAverageLimitStatistic": {
                        "value": true
                      }
                    }
                  },
                  {
                    "script": {
                      "script": {
                        "inline": "doc['positions.monthsWorked'].value != 0 && doc['positions.averageMonthLimit'].value > doc['positions.monthsWorked'].value"
                      }
                    }
                  },
                  {
                    "script": {
                      "script": {
                        "inline": "doc['positions.monthsWorked'].value != 0 && (doc['positions.averageMonthLimit'].value - 12) < doc['positions.monthsWorked'].value"
                      }
                    }
                  }
                ]
              }
            },
            {
              "bool": {
                "filter": [
                  {
                    "term": {
                      "positions.hasAverageLimitStatistic": {
                        "value": false
                      }
                    }
                  },
                  {
                    "range": {
                      "positions.expirationDate": {
                        "gt": "2017-06-03T00:00:00-07:00",
                        "lt": "2018-06-03T00:00:00-07:00"
                      }
                    }
                  }
                ]
              }
            }
          ]
        }
      },
      "path": "positions"
    }
  }
}

Finally, here's a complete example to demonstrate

void Main()
{
    var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));

    var connectionSettings = new ConnectionSettings(pool)
        .InferMappingFor<Person>(m => m
            .IndexName("people")
        )
        .PrettyJson()
        .DisableDirectStreaming()
        .OnRequestCompleted(response =>
            {
                // log out the request
                if (response.RequestBodyInBytes != null)
                {
                    Console.WriteLine(
                        $"{response.HttpMethod} {response.Uri} \n" +
                        $"{Encoding.UTF8.GetString(response.RequestBodyInBytes)}");
                }
                else
                {
                    Console.WriteLine($"{response.HttpMethod} {response.Uri}");
                }

                Console.WriteLine();

                // log out the response
                if (response.ResponseBodyInBytes != null)
                {
                    Console.WriteLine($"Status: {response.HttpStatusCode}\n" +
                             $"{Encoding.UTF8.GetString(response.ResponseBodyInBytes)}\n" +
                             $"{new string('-', 30)}\n");
                }
                else
                {
                    Console.WriteLine($"Status: {response.HttpStatusCode}\n" +
                             $"{new string('-', 30)}\n");
                }
            });

    var client = new ElasticClient(connectionSettings);

    if (client.IndexExists("people").Exists)
    {
        client.DeleteIndex("people");
    }

    client.CreateIndex("people", c => c
        .Mappings(m => m
            .Map<Person>(mm => mm
                .AutoMap()
                .Properties(p => p
                    .Nested<Position>(n => n
                        .Name(nn => nn.Positions)
                        .AutoMap()
                    )
                )
            )
        )
    );

    client.IndexMany(new[] {
        new Person
        {
            FullName = "Person 1",
            TotalSalary = 100000,
            Positions = new List<Position>
            {
                new Position
                {
                    Name = "Janitor",
                    AverageMonthLimit = 5,
                    MonthsWorked = 3,
                    HasAverageLimitStatistic = true
                }
            }
        },
        new Person
        {
            FullName = "Person 2",
            TotalSalary = 150000,
            Positions = new List<Position>
            {
                new Position
                {
                    Name = "Coach",
                    AverageMonthLimit = 5,
                    HasAverageLimitStatistic = true
                }
            }
        },
        new Person
        {
            FullName = "Person 3",
            TotalSalary = 200000,
            Positions = new List<Position>
            {
                new Position
                {
                    Name = "Teacher",
                    HasAverageLimitStatistic = false,
                    ExpirationDate = DateTime.Now.AddMonths(6)
                }
            }
        },
        new Person
        {
            FullName = "Person 4",
            TotalSalary = 250000,
            Positions = new List<Position>
            {
                new Position
                {
                    Name = "Head",
                    HasAverageLimitStatistic = false,
                    ExpirationDate = DateTime.Now.AddYears(2)
                }
            }
        }
    });

    client.Refresh(IndexName.From<Person>());

    var searchResponse = client.Search<Person>(s => s
        .Query(q => q
            .Nested(n => n
                .Path(p => p.Positions)
                .Query(nq => (+nq
                    .Term(f => f.Positions.First().HasAverageLimitStatistic, true) && +nq
                    .Script(sq => sq
                        .Inline("doc['positions.monthsWorked'].value != 0 && doc['positions.averageMonthLimit'].value > doc['positions.monthsWorked'].value")
                    ) && +nq
                    .Script(sq => sq
                        .Inline("doc['positions.monthsWorked'].value != 0 && (doc['positions.averageMonthLimit'].value - 12) < doc['positions.monthsWorked'].value")
                    )) || (+nq
                    .Term(f => f.Positions.First().HasAverageLimitStatistic, false) && +nq
                    .DateRange(d => d
                        .Field(f => f.Positions.First().ExpirationDate)
                        .GreaterThan(DateTime.Now.Date)
                        .LessThan(DateTime.Now.Date.AddYears(1))
                    ))
                )
            )
        )
    );

}

public class Person
{
    public string FullName { get; set; }
    public decimal TotalSalary { get; set; }
    public List<Position> Positions { get; set; } = new List<Position>();
}

public class Position
{
    public string Name { get; set; }
    public bool IsCurrentPosition { get; set; }
    public DateTime ExpirationDate { get; set; }
    public int? MonthsWorked { get; set; }
    public bool HasAverageLimitStatistic { get; set; } = false;
    public int AverageMonthLimit { get; set; } = 0;
    public decimal Salary { get; set; }
    public string CompanyName { get; set; }
}

Based on the query criteria, only Person 1 and Person 3 are returned.


来源: stackexchange

问:
Errors after Meteor upgrade
I've just performed meteor update which took me to v1.5. I'm getting a lot of TypeError: module.exportDefault is not a function errors.
Currently it's at
at meteorInstall.node_modules.meteor.react-meteor-data.ReactMeteorData.jsx (packages/react-meteor-data/ReactMeteorData.jsx:1:8)
but it happens on several packages. I think it's do with dynamic imports but I can't get to the bottom of it.
Pulling my hair out.

答:
I had a similar problem because modules@0.10.0-pre.1 was installed.
Try to set the version of the modules package to 0.9.1.

1) Install meteor add modules@0.9.1

2) Remove versions file or set modules version to 0.9.1.

ContentLicense: CC BY-SA 3.0

Title: Errors after Meteor upgrade


问:
POST method not inserting data into database table
I'm trying to play around with databases and inserting data dynamically with php.
At the moment I have a form with 'post' method and everything seems logical to me but it isn't inserting the data into the table.

Code is attached below, would appreciate if someone could point me into the right direction.

index.php:

```<code><form action="index.php" method="post">

<label for="name">Name</label>
<input type="text" name="name" required>

<label for="breed">Breed</label>
<input type="text" name="breed">

<label for="age">Age</label>
<input type="text" name="age">

<input type="submit" name="submit" value="Submit">

</form>

<?php

require "connect.php";

if('submit') {
    $name = $_POST['name'];
    $breed = $_POST['breed'];
    $age = $_POST['age'];

    $newdog = mysqli_query('INSERT INTO `dogs`(`name`, `breed`, `age`) VALUES ([$name],[$breed],[$age)');

    if ($newdog) {
        echo "$name has been added to the database";
    } else {
        echo "$name has not been added to database.";
    };
};

?>
</code>```

connect.php:

```<code><?php

$connect = mysqli_connect('localhost', 'max', 'password', 'db_test');

?>
</code>```

答:
Change if('submit') {

TO

```<code>if(isset($_POST['submit'])){//check if it is set

}
</code>```

Also change this line:

$newdog = mysqli_query('INSERT INTOdogs(name,breed,age) VALUES ([$name],[$breed],[$age)');

TO

$newdog = mysqli_query($connect, 'INSERT INTOdogs(name,breed,age) VALUES ($name,$breed,$age)');//remove square bracktes and add connection variable

Your code is very well vulnerable to SQL injection

Using prepared statements,

```<code>$stmt = $connect->prepare("INSERT INTO dogs (`name`, `breed`, `age`) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $name, $breed, $age);
if($stmt->execute() == true){
   echo 'Saved';
} else {
   echo 'Error '. $stmt->error;
 }
</code>```

Body:
I'm trying to play around with databases and inserting data dynamically with php.
At the moment I have a form with 'post' method and everything seems logical to me but it isn't inserting the data into the table.

Code is attached below, would appreciate if someone could point me into the right direction.

index.php:

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

Name
<input type="text" name="name" required>

Breed
<input type="text" name="breed">

Age
<input type="text" name="age">

<input type="submit" name="submit" value="Submit">

</form>

<?php

require "connect.php";

if('submit') {
    $name = $_POST['name'];
    $breed = $_POST['breed'];
    $age = $_POST['age'];

    $newdog = mysqli_query('INSERT INTO `dogs`(`name`, `breed`, `age`) VALUES ([$name],[$breed],[$age)');

    if ($newdog) {
        echo "$name has been added to the database";
    } else {
        echo "$name has not been added to database.";
    };
};

?>

connect.php:

<?php

$connect = mysqli_connect('localhost', 'max', 'password', 'db_test');

?>

Body:
Change if('submit') {

TO

if(isset($_POST['submit'])){//check if it is set

}

Also change this line:

$newdog = mysqli_query('INSERT INTOdogs(name,breed,age) VALUES ([$name],[$breed],[$age)');

TO

$newdog = mysqli_query($connect, 'INSERT INTOdogs(name,breed,age) VALUES ($name,$breed,$age)');//remove square bracktes and add connection variable

Your code is very well vulnerable to SQL injection

Using prepared statements,

$stmt = $connect->prepare("INSERT INTO dogs (`name`, `breed`, `age`) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $name, $breed, $age);
if($stmt->execute() == true){
   echo 'Saved';
} else {
   echo 'Error '. $stmt->error;
 }


问:
awk - if condition is met, print specific lines before and after
Having the following blastout.txt:

blastout.txt

I need to search all lines that contain Identities = [>=50] and

print the one line above that contains Query=

print the 5th line below

example output (only first lines shown here):

```<code>Query= HWI-ST863:386:C5Y8UACXX:3:1307:8061:42115 1:N:0:ACACGAAT
Sbjct  2030309  ATGACGCTCACCTTGGTGTCGATATCCTCACCTGCGGTGCCAATGCCGCTGCCCGCGGTC  2030250
Query= HWI-ST863:386:C5Y8UACXX:3:2209:19756:21341 1:N:0:ACACGAAT
Sbjct  2418742  CAGGCGTTCCGGCAGTTTGTGCTGGAAGAGGCCCGTGGCCTGGCGGAGCCTCTGCCGGCG  2418683
Query= HWI-ST863:386:C5Y8UACXX:3:1302:8580:7972 1:N:0:ACACGAAT
Sbjct  3178017  CCAGTTATGCTTGGGGCAGGTGAGCTTGTTGCCTTCCAGGGCGAGCTCGGGGATATCCGT  3178076
</code>```

I solved 2.:

```<code>awk 'c&&!--c;/Identities =/ && ($3+0)>=50 {c=5}' blastout.txt
</code>```

that was feasable for me because the structure of the file is always the same. But for the 1. the number of lines is changing, and it can also happen that for one entry of Query=, there is more than one line that match the pattern.

Your help in implementing this is very much appreciated!

答:
```<code>/Query/{q=$0} c...; /Identities/...{print q; c=5}
</code>```

If that's not all you need then edit your question to contain concise, testable sample input and expected output. Don't ask/expect us to go off looking at other sites for examples as that implies you're being too lazy to come up with a concise example of your problem and want us to do the work for you of trying to understand some large dataset.

Spelled out:

```<code>awk '/Query/{q=$0} c&&!--c; /Identities =/ && ($3+0)>=50 {print q; c=5}' blastout.txt
</code>```

Body:
Having the following blastout.txt:

blastout.txt

I need to search all lines that contain Identities = [>=50] and

print the one line above that contains Query=

print the 5th line below

example output (only first lines shown here):

Query= HWI-ST863:386:C5Y8UACXX:3:1307:8061:42115 1:N:0:ACACGAAT
Sbjct  2030309  ATGACGCTCACCTTGGTGTCGATATCCTCACCTGCGGTGCCAATGCCGCTGCCCGCGGTC  2030250
Query= HWI-ST863:386:C5Y8UACXX:3:2209:19756:21341 1:N:0:ACACGAAT
Sbjct  2418742  CAGGCGTTCCGGCAGTTTGTGCTGGAAGAGGCCCGTGGCCTGGCGGAGCCTCTGCCGGCG  2418683
Query= HWI-ST863:386:C5Y8UACXX:3:1302:8580:7972 1:N:0:ACACGAAT
Sbjct  3178017  CCAGTTATGCTTGGGGCAGGTGAGCTTGTTGCCTTCCAGGGCGAGCTCGGGGATATCCGT  3178076

I solved 2.:

awk 'c&&!--c;/Identities =/ && ($3+0)>=50 {c=5}' blastout.txt

that was feasable for me because the structure of the file is always the same. But for the 1. the number of lines is changing, and it can also happen that for one entry of Query=, there is more than one line that match the pattern.

Your help in implementing this is very much appreciated!

Body:
/Query/{q=$0} c...; /Identities/...{print q; c=5}

If that's not all you need then edit your question to contain concise, testable sample input and expected output. Don't ask/expect us to go off looking at other sites for examples as that implies you're being too lazy to come up with a concise example of your problem and want us to do the work for you of trying to understand some large dataset.

Spelled out:

awk '/Query/{q=$0} c&&!--c; /Identities =/ && ($3+0)>=50 {print q; c=5}' blastout.txt


问:
DocuSign Api - TextTab size
I am having trouble with creating texttabs via the docusign REST API.
The creation succeed, but when I open the DocuSign page to sign the document, the created texttabs have not the defined size.
Interestingly the created notetabs with the same size work properly.
I compare the texttab with a Textbox with the size 100 px * 100 px.

How can I fix this issue?

```<code>    "textTabs": [
        {
            "height": 100,
            "name": "Test1",
            "width": 100,
            "disableAutoSize": "true",
            "documentId": "1",
            "pageNumber": "1",
            "xPosition": "291",
            "yPosition": "244"
        }
    ]
</code>```

答:
DocuSign adds some additional offsets based on the Tab Type that is being used.

See this answer for more information.

Troubleshooting Tip:
I suggest, you use the DocuSign Web Sending UI to tag your documents and use the lisEnvelopeRecipients to retrieve the Tab positions. You can then use the Tab positions for your subsequent API calls.

Title: DocuSign Api - TextTab size

Body:
I am having trouble with creating texttabs via the docusign REST API.
The creation succeed, but when I open the DocuSign page to sign the document, the created texttabs have not the defined size.
Interestingly the created notetabs with the same size work properly.
I compare the texttab with a Textbox with the size 100 px * 100 px.

How can I fix this issue?

    "textTabs": [
        {
            "height": 100,
            "name": "Test1",
            "width": 100,
            "disableAutoSize": "true",
            "documentId": "1",
            "pageNumber": "1",
            "xPosition": "291",
            "yPosition": "244"
        }
    ]


问:
SSE2: Double precision log function
I need open source (no restriction on license) implementation of log function, something with signature

```<code>__m128d _mm_log_pd(__m128d);
</code>```

It is available in Intel Short Vector Math Library (part of ICC), but ICC is neither free nor open source. I am looking for implementation using intrinsics only.

It should use special rational function approximations. I need something almost as accurate as cmath log, say 9-10 decimal digits, but faster.

答: If you cannot find an existing open source implementation it is relatively easy to create your own using the standard method of a Taylor series. See Wikipedia for this and a variety of other methods. </p>

ContentLicense: CC BY-SA 2.5

Title: SSE2: Double precision log function

Body:
I need open source (no restriction on license) implementation of log function, something with signature

__m128d _mm_log_pd(__m128d);

It is available in Intel Short Vector Math Library (part of ICC), but ICC is neither free nor open source. I am looking for implementation using intrinsics only.

It should use special rational function approximations. I need something almost as accurate as cmath log, say 9-10 decimal digits, but faster.


问:
Django 1.11 - Password reset
I have an issue with a password modification form.
I don't want to use the password reset function from Django.

```<code>def view_password(request):
    if request.user.is_authenticated():
        if request.method == 'POST':
            form = ChangePasswordForm(request.POST)
            if form.is_valid():
                new_password = form.cleaned_data['new_password']
                confirm_password = form.cleaned_data['confirm_password']
                if new_password == confirm_password:
                    strengh = new_password[0].isalpha()
                    if all(c.isalpha() == strengh for c in new_password):
                        messages.add_message(request, messages.INFO, 'Le mot de passe doit contenir au moins 8 charactères lettres et chiffres.')
                    else:
                        update = User.objects.get(id=request.user.id)
                        update.set_password('new_password')
                        update.save()
                        messages.add_message(request, messages.INFO, 'Votre mot de passe a bien été changé.')
                else:
                    messages.add_message(request, messages.INFO, 'La confirmation du mot de passe est incorrect.')
            else:
                messages.add_message(request, messages.INFO, 'Une erreur est survenue pendant la modification.')
        else:
            form = ChangePasswordForm()
        return render(request, 'password.html', locals())
    else:
        from start.views import view_logon
        messages.add_message(request, messages.INFO, 'Vous devez être connecté pour accéder à cette page.')
        return redirect(view_logon)
</code>```

The form works well and the modification of the password is done. However, after looked at the database, it seems that the new password is not well hashed. Indeed when I try to login with the new password or the old password, it doesn't work.

Thanks for your help.

答:
Change the line,

```<code>update.set_password('new_password')
</code>```

To,

```<code>update.set_password(new_password)
</code>```

You were setting the password as 'new_password' for every users. That's why you can't login.

set_password takes the argument as a string and hashes as the password.

Title: Django 1.11 - Password reset

Body:
I have an issue with a password modification form.
I don't want to use the password reset function from Django.

def view_password(request):
    if request.user.is_authenticated():
        if request.method == 'POST':
            form = ChangePasswordForm(request.POST)
            if form.is_valid():
                new_password = form.cleaned_data['new_password']
                confirm_password = form.cleaned_data['confirm_password']
                if new_password == confirm_password:
                    strengh = new_password[0].isalpha()
                    if all(c.isalpha() == strengh for c in new_password):
                        messages.add_message(request, messages.INFO, 'Le mot de passe doit contenir au moins 8 charactères lettres et chiffres.')
                    else:
                        update = User.objects.get(id=request.user.id)
                        update.set_password('new_password')
                        update.save()
                        messages.add_message(request, messages.INFO, 'Votre mot de passe a bien été changé.')
                else:
                    messages.add_message(request, messages.INFO, 'La confirmation du mot de passe est incorrect.')
            else:
                messages.add_message(request, messages.INFO, 'Une erreur est survenue pendant la modification.')
        else:
            form = ChangePasswordForm()
        return render(request, 'password.html', locals())
    else:
        from start.views import view_logon
        messages.add_message(request, messages.INFO, 'Vous devez être connecté pour accéder à cette page.')
        return redirect(view_logon)

The form works well and the modification of the password is done. However, after looked at the database, it seems that the new password is not well hashed. Indeed when I try to login with the new password or the old password, it doesn't work.

Thanks for your help.

Body:
Change the line,

update.set_password('new_password')

To,

update.set_password(new_password)

You were setting the password as 'new_password' for every users. That's why you can't login.

set_password takes the argument as a string and hashes as the password.


问:
Editing one item in a list in Knockout JS
I have a demo application where I've managed to implement changing all items and sorting all items. Now I would like to update only one item at position [1] in the array of the list so that the list updates. How can I do it?</p>

```<code>this.changeOne=function(){
this.allItems[1]={name:"jjjjjjjjjjjjjjjjjjjjjj"};
}
</code>```

答:
The first element is this.allItems()[0].

Then, you only need to change the name property.

Like this:

```<code>    this.changeOne=function(){
        this.allItems()[0].name("jjjjjjjjjjjjjjjjjjjjjj");
    }
</code>```

In this function you need to check if there is elements (I not checked it!!).

More information at this link observable arrays

Body:
I have a demo application where I've managed to implement changing all items and sorting all items. Now I would like to update only one item at position [1] in the array of the list so that the list updates. How can I do it?

this.changeOne=function(){
this.allItems[1]={name:"jjjjjjjjjjjjjjjjjjjjjj"};
}

Body:
The first element is this.allItems()[0].

Then, you only need to change the name property.

Like this:

    this.changeOne=function(){
        this.allItems()[0].name("jjjjjjjjjjjjjjjjjjjjjj");
    }

In this function you need to check if there is elements (I not checked it!!).

More information at this link observable arrays


问:
AddToSet operation requires a target array field
Trying to make use of Azure DocumentDB/CosmsoDB using the MongoDB driver.  I have learned that there are many limitations as the full set of features is not currently implemented.  I want to use aggregate functions, specifically $group, and .distinct but I don't think that is available yet.  As a work around, I am trying to maintain a separate "tracking" document to enable "distinct".  trying to update a document using $addToSet, but getting the following:

```<code>MongoError: Message: {"Errors":["Encountered exception while executing function. Exception = Error: AddToSet operation requires a target array field.\r\nStack trace: Error: AddToSet operation requires a target array field.\n   at arrayAddToSet (__.sys.commonUpdate.js:2907:25)\n   at handleUpdate (__.sys.commonUpdate.js:2649:29)\n   at processOneResult (__.sys.commonUpdate.js:2484:25)\n   at queryCallback (__.sys.commonUpdate.js:2461:21)\n   at Anonymous function (__.sys.commonUpdate.js:619:29)"]}
</code>```

The update command i am using:

```<code>var usersDocument = collection.updateOne(
   { "type": "users" },
   { $addToSet: {users: "someone@gmail.com"} },
    function(err, count, status) {
        console.log("updateOne err: " + err)
        console.log("updateOne count: " + count)
        console.log("updateOne status: " + status)
    }
)
</code>```

This seems to me to be a pretty straight-forward command, pulled from the mongo documentation and fields adjusted as needed.  Maybe I am missing something really basic?

My ultimate goal was to make sure that my code was portable as to be able to move it into a Mongo cluster, if I so desired (not be locked into Azure-specific).  To get started and not have to manage a multi-server cluster, Azure CosmosDB looked like a great jumpstart, but the limitations are maddening.

UPDATE:
Now that I have fixed my document and I actually have a field with an array, $addToSet is just replacing the value, rather than adding to the array. I'll create a new question for that.

答:
Yup, something basic.  The error message was actually correct.  After inspecting the existing document:
I found:

```<code>{ "users": "[]" }
</code>```

And changed it to:

```<code>{ "users": [] }
</code>```

Now it is working.

Body:
Trying to make use of Azure DocumentDB/CosmsoDB using the MongoDB driver.  I have learned that there are many limitations as the full set of features is not currently implemented.  I want to use aggregate functions, specifically $group, and .distinct but I don't think that is available yet.  As a work around, I am trying to maintain a separate "tracking" document to enable "distinct".  trying to update a document using $addToSet, but getting the following:

MongoError: Message: {"Errors":["Encountered exception while executing function. Exception = Error: AddToSet operation requires a target array field.\r\nStack trace: Error: AddToSet operation requires a target array field.\n   at arrayAddToSet (__.sys.commonUpdate.js:2907:25)\n   at handleUpdate (__.sys.commonUpdate.js:2649:29)\n   at processOneResult (__.sys.commonUpdate.js:2484:25)\n   at queryCallback (__.sys.commonUpdate.js:2461:21)\n   at Anonymous function (__.sys.commonUpdate.js:619:29)"]}

The update command i am using:

var usersDocument = collection.updateOne(
   { "type": "users" },
   { $addToSet: {users: "someone@gmail.com"} },
    function(err, count, status) {
        console.log("updateOne err: " + err)
        console.log("updateOne count: " + count)
        console.log("updateOne status: " + status)
    }
)

This seems to me to be a pretty straight-forward command, pulled from the mongo documentation and fields adjusted as needed.  Maybe I am missing something really basic?

My ultimate goal was to make sure that my code was portable as to be able to move it into a Mongo cluster, if I so desired (not be locked into Azure-specific).  To get started and not have to manage a multi-server cluster, Azure CosmosDB looked like a great jumpstart, but the limitations are maddening.

UPDATE:
Now that I have fixed my document and I actually have a field with an array, $addToSet is just replacing the value, rather than adding to the array. I'll create a new question for that.

Body:
Yup, something basic.  The error message was actually correct.  After inspecting the existing document:
I found:

{ "users": "[]" }

And changed it to:

{ "users": [] }

Now it is working.


问:
grouping data by year in python
i have a csv file containing data starting from 2006/01/01 to 2011/01/01 , it contains: ( timestapm, heure, lat, lon, impact) and i need to calculate the average of impacts per month over years and then plot it.
i believe i should group data daily , then monthly, then by year.

here's a sample of my data :

```<code> timestamp,heure,lat,lon,impact,type
 2007-01-01 00:00:00,13:58:43,33.837,-9.205,10.3,1
 2007-01-02 00:00:00,00:07:28,34.5293,-10.2384,17.7,1
 2007-01-02 00:00:00,23:01:03,35.0617,-1.435,-17.1,2
 2007-01-03 00:00:00,01:14:29,36.5685,0.9043,36.8,1
 2007-01-03 00:00:00,05:03:51,34.1919,-12.5061,-48.9,1
</code>```

and here's the code i am using :

```<code>names =["timestamp","heure","lat","lon","impact","type"]
data = pd.read_csv('flash.txt', names=names, parse_dates=['timestamp'], index_col=['timestamp'])
print (data.head())
daily = data.groupby(pd.TimeGrouper(freq='D'))['impact'].count()
monthly = daily.groupby(pd.TimeGrouper(freq='M'))['impact'].count()
ax = yearly.plot(kind='bar')
plt.show()
</code>```

And here's the result i am getting :

SO, my main request, is how to group by year in order to have ( january of first year in the file until january of last year in the file gathered in one bar) and so on for all the months.
any ideas ?

答:
You can make a groupby combination:
(assuming that you have an index of time datetime)

```<code>data.groupby([(data.index.year),(data.index.month)])['impact'].count()
</code>```

This will group by year and by month

Title: grouping data by year in python

Body:
i have a csv file containing data starting from 2006/01/01 to 2011/01/01 , it contains: ( timestapm, heure, lat, lon, impact) and i need to calculate the average of impacts per month over years and then plot it.
i believe i should group data daily , then monthly, then by year.

here's a sample of my data :

 timestamp,heure,lat,lon,impact,type
 2007-01-01 00:00:00,13:58:43,33.837,-9.205,10.3,1
 2007-01-02 00:00:00,00:07:28,34.5293,-10.2384,17.7,1
 2007-01-02 00:00:00,23:01:03,35.0617,-1.435,-17.1,2
 2007-01-03 00:00:00,01:14:29,36.5685,0.9043,36.8,1
 2007-01-03 00:00:00,05:03:51,34.1919,-12.5061,-48.9,1

and here's the code i am using :

names =["timestamp","heure","lat","lon","impact","type"]
data = pd.read_csv('flash.txt', names=names, parse_dates=['timestamp'], index_col=['timestamp'])
print (data.head())
daily = data.groupby(pd.TimeGrouper(freq='D'))['impact'].count()
monthly = daily.groupby(pd.TimeGrouper(freq='M'))['impact'].count()
ax = yearly.plot(kind='bar')
plt.show()

And here's the result i am getting :

SO, my main request, is how to group by year in order to have ( january of first year in the file until january of last year in the file gathered in one bar) and so on for all the months.
any ideas ?

Body:
You can make a groupby combination:
(assuming that you have an index of time datetime)

data.groupby([(data.index.year),(data.index.month)])['impact'].count()

This will group by year and by month


问:
Wait for specific text in DOM element before continuing
I have a function that should wait for some text to change before it returns a value:

```<code>function getElementText() {
   while(isLoading()) {
   }
   return $('#element').text();
}

function isLoading() {
    return  $('#element')[0] &&
            $('#element').text().indexOf('Loading') >= 0;
}
</code>```

However I think the empty while is not a good option (will it block the event loop?)

答:
No need of jQuery or any other external library, you can simply use MutationObserver: https://developer.mozilla.org/en/docs/Web/API/MutationObserver

Here a simple example, you will have a notice of type characterData when your text changes (after 5 seconds in my example):

// select the target node
var target = document.getElementById('some-id');

// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true, attributes: true, subtree: true };

// pass in the target node, as well as the observer options
observer.observe(target, config);

// later, you can stop observing
//observer.disconnect();
setTimeout(function() {
 target.innerText = 'Changed text!';
}, 5000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="some-id">
  AAA
</div></code>```

Remove from the config of the observer all the properties you don't need to spy for changes

Body:
I have a function that should wait for some text to change before it returns a value:

function getElementText() {
   while(isLoading()) {
   }
   return $('#element').text();
}

function isLoading() {
    return  $('#element')[0] &&
            $('#element').text().indexOf('Loading') >= 0;
}

However I think the empty while is not a good option (will it block the event loop?)

Body:
No need of jQuery or any other external library, you can simply use MutationObserver: https://developer.mozilla.org/en/docs/Web/API/MutationObserver

Here a simple example, you will have a notice of type characterData when your text changes (after 5 seconds in my example):

// select the target node
var target = document.getElementById('some-id');

// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true, attributes: true, subtree: true };

// pass in the target node, as well as the observer options
observer.observe(target, config);

// later, you can stop observing
//observer.disconnect();
setTimeout(function() {
 target.innerText = 'Changed text!';
}, 5000);

<div id="some-id">
  AAA
</div>

Remove from the config of the observer all the properties you don't need to spy for changes


问:
Divide Matrix by vector in armadillo
I have a sparse matrix and a vector, both constructed in armadillo. Now I want to divide the matrix by the vector, i.e. divide the first column of the matrix by the first element, and so on. Now I can do that in a loop:

```<code>int r_num = 5000;
arma::colvec r_vec = arma::linspace(0, 1, r_num);
double dh = abs(r_vec(1)-r_vec(0));
arma::sp_cx_mat r1_matrix = arma::sp_cx_mat(r_num, r_num);
r1_matrix.diag(0).fill(0);
r1_matrix.diag(1).fill(8);
r1_matrix.diag(-1).fill(-8);
r1_matrix.diag(2).fill(-1);
r1_matrix.diag(-2).fill(1);

arma::cx_colvec divider_vec = r_vec*std::complex<double>{1.0, 0.0};
divider_vec(0) = 1;

for (size_t i = 0; i < r_num; i++)
{
    if (i % 100 == 0)
        std::cout << i << " of " << r_num << '\n';
    r1_matrix.col(i) = r1_matrix.col(i) / divider_vec(i);
}
</code>```

but that is extremely slow (especially after I will increase r_num afterwards). When using the usual approach

```<code>r1_matrix = r1_matrix/divider_vec;
</code>```

I get the error of mismatched dimensions ((5000x5000) and (5000x1)). Is there another faster way?

答:
Apart maybe for specifics due to sparse matrices or armadillo (which I do not know at all), the best way I think about to solve your problem is to compute the inverse of your vector, store it as the diagonal of a diagonal matrix (of the size of your matrix) and then multiply your matrix by this computed one.

Some examples using Eigen :

```<code>#include <Eigen/Core>
#include <iostream>

using namespace Eigen;

int main()
{
    Matrix<float, 3, 3> r1_matrix;
    r1_matrix <<
        2, 3, 5,
        4, 6, 10,
        6, 9, 15;

    Matrix<float, 3, 1> divider_vec;
    divider_vec << 2, 3, 5;
    divider_vec = divider_vec.cwiseInverse();

    Matrix<float, 3, 3> divider_mat = divider_vec.asDiagonal();

    r1_matrix = r1_matrix * divider_mat;

    std::cout << std::endl << r1_matrix << std::endl;

    Matrix<float, 5, 3> r2_matrix;
    r2_matrix <<
        2, 3, 5,
        4, 6, 10,
        6, 9, 15,
        8, 12, 20,
        10, 15, 25;

    Matrix<float, 3, 5> divider_mat2 = Matrix<float, 3, 5>::Zero();
    divider_mat2.block<3, 3>(0, 0) = divider_mat;

    r2_matrix = (r2_matrix * divider_mat2).block<5, 3>(0, 0);
    std::cout << std::endl << r2_matrix << std::endl;

    SparseMatrix<float> sp_matrix(5, 5);
    std::vector<Triplet<float>> data =
    {
        { 0, 0, 2.f }, { 2, 1, 6.f }, { 1, 2, 10.f }, { 3, 3, 14.f }, { 4, 3, 21.f }, { 1, 4, 11.f }
    };
    sp_matrix.setFromTriplets(data.begin(), data.end());

    Matrix<float, 5, 1> divider_vec2;
    divider_vec2 << 2, 3, 5, 7, 11;
    divider_vec2 = divider_vec2.cwiseInverse();
    SparseMatrix<float> divider_sp_mat(5, 5);
    data.clear();

    for (int i = 0; i < 5; ++i)
    {
        data.push_back(Triplet<float>{ i, i, divider_vec2[i]});
    }

    divider_sp_mat.setFromTriplets(data.begin(), data.end());

    sp_matrix = sp_matrix * divider_sp_mat;
    std::cout << std::endl << sp_matrix << std::endl;
    return 0;
}
</code>```

I am not sure if there is another way than making a square matrix when the matrix has more rows than columns though.

Title: Divide Matrix by vector in armadillo

Body:
I have a sparse matrix and a vector, both constructed in armadillo. Now I want to divide the matrix by the vector, i.e. divide the first column of the matrix by the first element, and so on. Now I can do that in a loop:

int r_num = 5000;
arma::colvec r_vec = arma::linspace(0, 1, r_num);
double dh = abs(r_vec(1)-r_vec(0));
arma::sp_cx_mat r1_matrix = arma::sp_cx_mat(r_num, r_num);
r1_matrix.diag(0).fill(0);
r1_matrix.diag(1).fill(8);
r1_matrix.diag(-1).fill(-8);
r1_matrix.diag(2).fill(-1);
r1_matrix.diag(-2).fill(1);

arma::cx_colvec divider_vec = r_vec*std::complex<double>{1.0, 0.0};
divider_vec(0) = 1;

for (size_t i = 0; i < r_num; i++)
{
    if (i % 100 == 0)
        std::cout << i << " of " << r_num << '\n';
    r1_matrix.col(i) = r1_matrix.col(i) / divider_vec(i);
}

but that is extremely slow (especially after I will increase r_num afterwards). When using the usual approach

r1_matrix = r1_matrix/divider_vec;

I get the error of mismatched dimensions ((5000x5000) and (5000x1)). Is there another faster way?

Body:
Apart maybe for specifics due to sparse matrices or armadillo (which I do not know at all), the best way I think about to solve your problem is to compute the inverse of your vector, store it as the diagonal of a diagonal matrix (of the size of your matrix) and then multiply your matrix by this computed one.

Some examples using Eigen :

#include <Eigen/Core>
#include <iostream>

using namespace Eigen;

int main()
{
    Matrix<float, 3, 3> r1_matrix;
    r1_matrix <<
        2, 3, 5,
        4, 6, 10,
        6, 9, 15;

    Matrix<float, 3, 1> divider_vec;
    divider_vec << 2, 3, 5;
    divider_vec = divider_vec.cwiseInverse();

    Matrix<float, 3, 3> divider_mat = divider_vec.asDiagonal();

    r1_matrix = r1_matrix * divider_mat;

    std::cout << std::endl << r1_matrix << std::endl;

    Matrix<float, 5, 3> r2_matrix;
    r2_matrix <<
        2, 3, 5,
        4, 6, 10,
        6, 9, 15,
        8, 12, 20,
        10, 15, 25;

    Matrix<float, 3, 5> divider_mat2 = Matrix<float, 3, 5>::Zero();
    divider_mat2.block<3, 3>(0, 0) = divider_mat;

    r2_matrix = (r2_matrix * divider_mat2).block<5, 3>(0, 0);
    std::cout << std::endl << r2_matrix << std::endl;

    SparseMatrix<float> sp_matrix(5, 5);
    std::vector<Triplet<float>> data =
    {
        { 0, 0, 2.f }, { 2, 1, 6.f }, { 1, 2, 10.f }, { 3, 3, 14.f }, { 4, 3, 21.f }, { 1, 4, 11.f }
    };
    sp_matrix.setFromTriplets(data.begin(), data.end());

    Matrix<float, 5, 1> divider_vec2;
    divider_vec2 << 2, 3, 5, 7, 11;
    divider_vec2 = divider_vec2.cwiseInverse();
    SparseMatrix<float> divider_sp_mat(5, 5);
    data.clear();

    for (int i = 0; i < 5; ++i)
    {
        data.push_back(Triplet<float>{ i, i, divider_vec2[i]});
    }

    divider_sp_mat.setFromTriplets(data.begin(), data.end());

    sp_matrix = sp_matrix * divider_sp_mat;
    std::cout << std::endl << sp_matrix << std::endl;
    return 0;
}

I am not sure if there is another way than making a square matrix when the matrix has more rows than columns though.


问:
Reading a remote file with java on linux
I need to read a remote file using a java app, but the file is in apache server on linux.
I tried with "\\" but doesn't work like windows.
How can i do that?</p>

答:
This depends on a number of things. But we don't really know what question you're asking. Are you asking how to retrieve a document over HTTP? How to do a file copy from Linux? Network shares?

If the file is served by the webserver (in the docroot), the easiest way is probably to request it over HTTP using the URL class as stated above.

If the file is NOT under the webroot (i.e. can't be specified as http://webserver.name/some/path/to/file) then you'll need to use some other method. I'm assuming this is what you meant - you mention \\, the Windows file-sharing (SMB) protocol prefix. The easiest way is to use SSH and scp/sftp, which is probably already installed on the Linux machine - you may need to enable it, and you'll need a login. Then it's as simple as scp user@host:/remote/file/path local/path. You can set up SSH keys to avoid a password.


问:
Create all combinations from regex
I have sentences that define a template for random combinations:

```<code>I like dogs/cats
I want to eat today/(the next day)
</code>```

I tried using a regex:

```<code>m = re.search(r'(?P<list>[A-Za-z]+/([A-Za-z]+)+)', sentence)
words = m.group('list').split('/')
combs = [comb for comb in [sentence.replace(m.group('list'), w) for w in words]]
</code>```

For the first sentence I get ['i like dogs', 'i like cats'] which is what I want. For the second sentence, re.search returns None. What I would like to get is ['I want to eat today', 'I want to eat the next day'].

How do I need to change the regex?

答:
(I want to eat today)*|(the next day)

Is the regex that will select the text you want...

Title: Create all combinations from regex

Body:
I have sentences that define a template for random combinations:

I like dogs/cats
I want to eat today/(the next day)

I tried using a regex:

m = re.search(r'(?P<list>[A-Za-z]+/([A-Za-z]+)+)', sentence)
words = m.group('list').split('/')
combs = [comb for comb in [sentence.replace(m.group('list'), w) for w in words]]

For the first sentence I get ['i like dogs', 'i like cats'] which is what I want. For the second sentence, re.search returns None. What I would like to get is ['I want to eat today', 'I want to eat the next day'].

How do I need to change the regex?


问:
Move an array element from a position to another with condition
i 'm looking for a quick and robust way to move an element of an array to the top of the stack. My case is:
I have an array of objects like this:

```<code>array = [{label: yu, value: uy}, {label: EUR, value: EUR}, {label: CY, value: CY}].
</code>```

I want to move the element with value EUR to the top of the array so as to be the first element. How to do this?

答:
While you like to sort the array, I suggest to use the delta of the comparison directly without using a conditional operator. The advantage of this solution is, it works for more than one object in the array. All items with the same key/value pair are sorted to top.

const toTop = (key, value) => (a, b) => (b[key] === value) - (a[key] === value);
let array = [{ label: 'yu', value: 'uy' }, { label: 'EUR', value: 'EUR' }, { label: 'CY', value: 'CY' }];

array.sort(toTop('value', 'EUR'));

console.log(array);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
i 'm looking for a quick and robust way to move an element of an array to the top of the stack. My case is:
I have an array of objects like this:

array = [{label: yu, value: uy}, {label: EUR, value: EUR}, {label: CY, value: CY}].

I want to move the element with value EUR to the top of the array so as to be the first element. How to do this?

Body:
While you like to sort the array, I suggest to use the delta of the comparison directly without using a conditional operator. The advantage of this solution is, it works for more than one object in the array. All items with the same key/value pair are sorted to top.

const toTop = (key, value) => (a, b) => (b[key] === value) - (a[key] === value);
let array = [{ label: 'yu', value: 'uy' }, { label: 'EUR', value: 'EUR' }, { label: 'CY', value: 'CY' }];

array.sort(toTop('value', 'EUR'));

console.log(array);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Validating construcor parameters determined by another parameter
I have the following enum

```<code>public enum StudentType {
    Domestic, International;
}
</code>```

and a Student class with the following constructor:

```<code>//Left out additonal parameters and validation
public Student(StudentType type, List<String> documents){

  if(type == null){
     throw new IllegalArgumentException("You must provide Student type");
  }
  this.type = type;
  this.documents = this.validateList(documents);
}
</code>```

and a private method to validate the list:

```<code>private List<String> validateList(List<String> validate){
   if(this.type == StudentType.Domestic && validate.isEmpty()){
        return validate;
    }
    else
      if(this.type == StudentType.Domestic && !validate.isEmpty()){
        return Collections.emptyList();
   }
   return new ArrayList<String>(validate);
}
</code>```

My plan to make the Student class immutable.

Explanation:

Only students that are International require documentation(passports, etc). Domestic students don't require any documentation.

In my constructor I check to make sure the type isn't null, the client must provide either domestic or international.

In my private validateList method I check the student type, and if the List is empty or not. If it's domestic and empty, return the list, if it's domensitc and not empty, return an empty collection, otherwise return the ArrayList<String> of documents.

My question concerns if checking the type in the private method is code smell? My concern is that one parameter(list of documents), is determined/validated by the type of student. If checking the type in the private method is code smell, what should I do instead?

答:
I see several problems with the code you posted, but not the ones you think it has.

First, we don't know where documents come from. I assume it's just a mistake in the code, and that it's in fact a second parameter.

Now, the code:

```<code>private List<String> validateList(List<String> validate){
   if(this.type == StudentType.Domestic && validate.isEmpty()){
        return validate;
    }
    else
      if(this.type == StudentType.Domestic && !validate.isEmpty()){
        return Collections.emptyList();
   }
   return new ArrayList<String>(validate);
}
</code>```

First, instead of rejecting the argument if it's invalid (as you're doing for a null student type), you just ignore the argument and use an empty list instead. That is not a good idea in general. If the caller passes a non empty list, it certainly don't expect for this list to be ignored silently. If the list should be empty, then reject non-empty lists by throwing an exception.

Second: the last line of code suggests that you want to make a defensive copy of the list passed as argument. But you don't do that in the first branch of your if block. And since the two branches consist in storing an empty collection anyway, it could thus be replaced by

```<code>private List<String> validateList(List<String> validate) {
    return this.type == StudentType.Domestic ? Collections.emptyList() : new ArrayList<>(validate);
}
</code>```

Finally, (and back to my first point), since a caller should never pass a non-empty list if the student type if domestic, you could make that impossible by using two factory methods instead of a constructor:

```<code>private Student(StudentType type, List<String> documents) {
    this.type = type;
    this.documents = documents;
}

public static Student createDomestic() {
    return new Student(StudentType.DOMESTIC), Collections.emptyList());
}

public static Student createInternational(List<Document> documents) {
    return new Student(StudentType.INTERNATIONAL, new ArrayList<>(documents);
}
</code>```

Body:
I have the following enum

public enum StudentType {
    Domestic, International;
}

and a Student class with the following constructor:

//Left out additonal parameters and validation
public Student(StudentType type, List<String> documents){

  if(type == null){
     throw new IllegalArgumentException("You must provide Student type");
  }
  this.type = type;
  this.documents = this.validateList(documents);
}

and a private method to validate the list:

private List<String> validateList(List<String> validate){
   if(this.type == StudentType.Domestic && validate.isEmpty()){
        return validate;
    }
    else
      if(this.type == StudentType.Domestic && !validate.isEmpty()){
        return Collections.emptyList();
   }
   return new ArrayList<String>(validate);
}

My plan to make the Student class immutable.

Explanation:

Only students that are International require documentation(passports, etc). Domestic students don't require any documentation.

In my constructor I check to make sure the type isn't null, the client must provide either domestic or international.

In my private validateList method I check the student type, and if the List is empty or not. If it's domestic and empty, return the list, if it's domensitc and not empty, return an empty collection, otherwise return the ArrayList<String> of documents.

My question concerns if checking the type in the private method is code smell? My concern is that one parameter(list of documents), is determined/validated by the type of student. If checking the type in the private method is code smell, what should I do instead?

Body:
I see several problems with the code you posted, but not the ones you think it has.

First, we don't know where documents come from. I assume it's just a mistake in the code, and that it's in fact a second parameter.

Now, the code:

private List<String> validateList(List<String> validate){
   if(this.type == StudentType.Domestic && validate.isEmpty()){
        return validate;
    }
    else
      if(this.type == StudentType.Domestic && !validate.isEmpty()){
        return Collections.emptyList();
   }
   return new ArrayList<String>(validate);
}

First, instead of rejecting the argument if it's invalid (as you're doing for a null student type), you just ignore the argument and use an empty list instead. That is not a good idea in general. If the caller passes a non empty list, it certainly don't expect for this list to be ignored silently. If the list should be empty, then reject non-empty lists by throwing an exception.

Second: the last line of code suggests that you want to make a defensive copy of the list passed as argument. But you don't do that in the first branch of your if block. And since the two branches consist in storing an empty collection anyway, it could thus be replaced by

private List<String> validateList(List<String> validate) {
    return this.type == StudentType.Domestic ? Collections.emptyList() : new ArrayList<>(validate);
}

Finally, (and back to my first point), since a caller should never pass a non-empty list if the student type if domestic, you could make that impossible by using two factory methods instead of a constructor:

private Student(StudentType type, List<String> documents) {
    this.type = type;
    this.documents = documents;
}

public static Student createDomestic() {
    return new Student(StudentType.DOMESTIC), Collections.emptyList());
}

public static Student createInternational(List<Document> documents) {
    return new Student(StudentType.INTERNATIONAL, new ArrayList<>(documents);
}


问:
ajax best practice
let's say i have the following HTML page.

```<code><A panel to display list of items>
  Item A
  Item B
  Item C
  ...

<A panel to display details about item>
  Details on item X:
</code>```

I want to write the page so that whenever the user clicks on one of the items, the detail about the selected item will show up on the bottom panel.

However, few problems that I want to solve are:

How should I prevent duplicate requests. (like, user presses links to item A and B before the detail of item A returns from the server).

If I want to display "detail is now loading...", where should I put the code?

答:
you can register click handlers, which fire ajax requests to load the data.

There are multiple ways to handle your concern about not firing multiple requests:

Just unregister the handlers on the other Items when you click one of them, and put them back when your request returns.

You can have an object in the scope of the request handlers that you set a property on, like 'requestInProgress', that you set to true and false appropriately.  In other words, use closures.

Displaying 'detail is now loading' is simple -- you can just set the value of the Panel dom, or the innerhtml if you want, to that message before you fire the request, and set the actual returned value when the request returns.

Note that many js libraries, like jQuery, provide an API around making ajax requests that might simplify things.  For example, the jQuery.ajax method takes an object literal that can contain the functions 'beforeSend', 'complete', 'success' so you do things before, after, and on the case of success (among other functions, check out http://api.jquery.com/jQuery.ajax/)

You can certainly do what you want with bare-metal js, but libraries can make your life easier.

Title: ajax best practice

Body:
let's say i have the following HTML page.

  Item A
  Item B
  Item C
  ...

  Details on item X:

I want to write the page so that whenever the user clicks on one of the items, the detail about the selected item will show up on the bottom panel.

However, few problems that I want to solve are:

How should I prevent duplicate requests. (like, user presses links to item A and B before the detail of item A returns from the server).

If I want to display "detail is now loading...", where should I put the code?


答:
I would rewrite the validateList method in the following manner:

```<code>private List<String> validateList(List<String> validate){
   if(this.type == StudentType.Domestic){
        return Collections.emptyList();
   }
   return new ArrayList<String>(validate);
}
</code>```

Explanation

As long as you simply need to return no documents if the student type is domestic, i combined two conditions into one. It is not really important for us if the domestic student has his documents or not, we do not need to check this.

Title: Validating construcor parameters determined by another parameter

Body:
I would rewrite the validateList method in the following manner:

private List<String> validateList(List<String> validate){
   if(this.type == StudentType.Domestic){
        return Collections.emptyList();
   }
   return new ArrayList<String>(validate);
}

Explanation

As long as you simply need to return no documents if the student type is domestic, i combined two conditions into one. It is not really important for us if the domestic student has his documents or not, we do not need to check this.


问:
Raise anchor ng-click on enter keypress for accessibility in angular
I am working on a problem for accessibility issues in my project. One scenario I am struggling is, we have anchor tag with ng-click event. When someone is hitting tab and reached anchor tag on the page using keyboard, they are hitting enter key, and they think it should do something. But, unfortunately enter key and click events works well with button control but not with anchor. Anyone has any suggestions how to solve this problem?

thanks in advance.

答:
I faced a similar issue, and resolved it be creating a simple directive which would intercept the keydown/keypress events on a link, and then call a function associated with the directive.

Here is the directive:

```<code> // Allows for the interception of the enter key, and then calling a passed in function
(function () {
    'use strict';
    angular
        .module('app.directives')
        .directive('convEnter', convEnter);

    function convEnter() {
        var directive = {
            restrict: 'A',
            link: link
        };
        return directive;

        ////////////////////////////////////////////////////////////////////////

        function link(scope, element, attrs) {
            element.bind('keydown keypress', function (event) {
                if (event.which === 13) {
                    scope.$apply(function () {
                        scope.$eval(attrs.convEnter, { 'event': event });
                    });

                    event.preventDefault();
                }
            });
        }
    }
})();
</code>```

To use it, you would simply apply it to your link, ie:

```<code><a conv-enter="vm.click()" ng-click="vm.click()">Click Link</a>
</code>```

Of course this is a bit repetitive as you are specifying "vm.click()" twice;  you could optimize this if desired by having the directive simply call the "click" function on the element itself, as long as you always wanted the click and the enter key to invoke the same function.  (In my scenario, I sometimes needed to distinguish between the two, and hence i allowed passing in a separate function)

Body:
I faced a similar issue, and resolved it be creating a simple directive which would intercept the keydown/keypress events on a link, and then call a function associated with the directive.

Here is the directive:

 // Allows for the interception of the enter key, and then calling a passed in function
(function () {
    'use strict';
    angular
        .module('app.directives')
        .directive('convEnter', convEnter);

    function convEnter() {
        var directive = {
            restrict: 'A',
            link: link
        };
        return directive;

        ////////////////////////////////////////////////////////////////////////

        function link(scope, element, attrs) {
            element.bind('keydown keypress', function (event) {
                if (event.which === 13) {
                    scope.$apply(function () {
                        scope.$eval(attrs.convEnter, { 'event': event });
                    });

                    event.preventDefault();
                }
            });
        }
    }
})();

To use it, you would simply apply it to your link, ie:

<a conv-enter="vm.click()" ng-click="vm.click()">Click Link</a>

Of course this is a bit repetitive as you are specifying "vm.click()" twice;  you could optimize this if desired by having the directive simply call the "click" function on the element itself, as long as you always wanted the click and the enter key to invoke the same function.  (In my scenario, I sometimes needed to distinguish between the two, and hence i allowed passing in a separate function)


问:
Filtering out data in Spark dataframe in Scala
I have a dataframe df, which contains below data:

```<code>**customers**   **product**   **Val_id**
     1               A            1
     2               B            X
     3               C
     4               D            Z
</code>```

I have successfully filtered for data where column val_id is blank

```<code>df.where(col("val_id").isin(""))
</code>```

But I am not able to figure out a way to filter data where column val_id is not blank, i tried something like below, but did not work for me:

```<code>df.where(col("val_id").isnotin(""))
</code>```

Can anyone please help me to achieve it using Spark Scala.

答:
You can use filter to get desired output:</p>

```<code>df.filter("rule_id != ''")
</code>```

Body:
I have a dataframe df, which contains below data:

**customers**   **product**   **Val_id**
     1               A            1
     2               B            X
     3               C
     4               D            Z

I have successfully filtered for data where column val_id is blank

df.where(col("val_id").isin(""))

But I am not able to figure out a way to filter data where column val_id is not blank, i tried something like below, but did not work for me:

df.where(col("val_id").isnotin(""))

Can anyone please help me to achieve it using Spark Scala.

Body:
You can use filter to get desired output:

df.filter("rule_id != ''")


问:
Azure AD B2C - Token validation does not work
I would like to use Azure AD B2C but have several difficulties using it.
One problem I have is to validate the signature of the token.
First I wanted to validate the token "manually" using jwt.io.

According to the Microsoft Docs, validating the signature should work like this:

Your app can use the  kid  claim in the JWT header to select the public key in the JSON document that is used to sign a particular token. It can then perform signature validation by using the correct public key and the indicated algorithm.

My understandig: Grab the kid value out of the header, lookup the key in the metadata under the location of jwks_uri, (assumption) use the value of "n" to verify the signature.

But Jwt.io, jsonwebtoken.io, and jose-jwt all say, that the signature is invalid.

What am I missing?

答:
Jwt.io seems to only support HS265 with a string secret and RS256 with a string secret or a certificate.

Azure AD B2C uses the more native form of RS256 which as per RFC 3447, section 3.1 defines that the public key consists of two components: n and e. The JWK contains both n and e which can be used to generate public key and validate the token signature.

In order to use Jwt.io, you'll need to convert Azure AD B2C's n + e format for the key to a cert format. See this example for a reference on how to do this: Go Language Convert Modulus exponent to X.509 certificate

ContentLicense: CC BY-SA 4.0


问:
UWP Frame.GoBack with argument
The scenario is I have a calendar page, the page displays all days of the month with an Add button on each day:

As  I click the add button it takes me to a different page, if the user taps the hardware back button I want the app to go back to the calendar page but I want the page scrolled to the date the user originally tapped the add button for.

The scrolling to the date is fine - If, as a test, I navigate to a page with NavigationEventArgs.Parameter = "2016-01-17" then my page scrolls to the 17th.

The problem I have is that I don't seem to be able to specify a parameter on the rootFrame.GoBack(); call.

So, is there a way to specify a parameter on the rootFrame.GoBack(); call manually edit the backbuttonstack - if there is such a thing - so that the required argument is there.

答:
There is no way how to directly pass parameter using GoBack method but there is a workaround:

On your calendar page set NavigationCacheMode to NavigationCacheMode.Required so when you call Frame.GoBack the calendar page state will be the same as before you navigated to the different page:

```<code><Page <!-- some unrelated XAML code -->
      NavigationCacheMode="Required"
      >
</code>```

EDIT - reply to the comment:

What NavigationCacheMode.Required does is that the frame is not creating a new instance of the page every time you navigate to it but only for the first time. But the OnNavigatedTo method is still called every time you navigate to it. I don't know your code but if you're not doing so, you'll have to check whether there is any parameter passed and whether it's string. So in your OnNavigatedTo method override you'll do something like this:

```<code>string parameter = e.Parameter as string;

if (parameter != null)
{
    // Use parameter to scroll to date you need
}
</code>```

Title: UWP Frame.GoBack with argument

Body:
There is no way how to directly pass parameter using GoBack method but there is a workaround:

On your calendar page set NavigationCacheMode to NavigationCacheMode.Required so when you call Frame.GoBack the calendar page state will be the same as before you navigated to the different page:

<Page <!-- some unrelated XAML code -->
      NavigationCacheMode="Required"
      >

EDIT - reply to the comment:

What NavigationCacheMode.Required does is that the frame is not creating a new instance of the page every time you navigate to it but only for the first time. But the OnNavigatedTo method is still called every time you navigate to it. I don't know your code but if you're not doing so, you'll have to check whether there is any parameter passed and whether it's string. So in your OnNavigatedTo method override you'll do something like this:

string parameter = e.Parameter as string;

if (parameter != null)
{
    // Use parameter to scroll to date you need
}


问:
Python : Increase a string
I am not really familiar with Python yet.
I have a string like "11223300". Now I want to increase the last byte of that string ( from "00" to "FF"). I tried to convert the string into an integer ( integer=int(string,16)) and increase it, and convert it back later, but that does not work for me. Maybe one of you guys has a better idea.

```<code>string = "11223300"
counter = int(string, 16)

for i in range(255):
    counter = counter + 1
    IV = hex(counter)
</code>```

Now I want to convert the IV from hex into a string

Thanks!

答:
You can use format to convert int to your hex string, which will not keep the 0x prefix:

```<code>string = "11223300"
counter = int(string, 16)

for i in range(255):
    counter = counter + 1
    IV = format(counter, 'X')
print(IV)
</code>```

Output:

```<code>112233FF
</code>```

Title: Python : Increase a string

Body:
I am not really familiar with Python yet.
I have a string like "11223300". Now I want to increase the last byte of that string ( from "00" to "FF"). I tried to convert the string into an integer ( integer=int(string,16)) and increase it, and convert it back later, but that does not work for me. Maybe one of you guys has a better idea.

string = "11223300"
counter = int(string, 16)

for i in range(255):
    counter = counter + 1
    IV = hex(counter)

Now I want to convert the IV from hex into a string

Thanks!

Body:
You can use format to convert int to your hex string, which will not keep the 0x prefix:

string = "11223300"
counter = int(string, 16)

for i in range(255):
    counter = counter + 1
    IV = format(counter, 'X')
print(IV)

Output:

112233FF


答:
The DOMSubtreeModified event will be triggered when a change occurs in the element, so you can use that to detect if the text is loaded.

You can use a callback function to return the value when it has loaded. Or even better: (jQuery) promises!

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

function isLoading() {
    return element.innerText.indexOf('Loading') >= 0;
}

function getElementText() {
    var def = $.Deferred();

    if (!isLoading()) {
        def.resolve(element.innerText);
        return def.promise();
    }

    $(element).on('DOMSubtreeModified', function () {
        if (!isLoading()) {
            def.resolve(element.innerText);
        }
    });

    return def.promise();
}

getElementText().then(function (text) {
    // Text is loaded!
    alert(text);
});

// Load text after 3 seconds for demonstration
setTimeout(function () {
    element.innerText = 'Changed!';
}, 3000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="element">Loading</div></code>```

Title: Wait for specific text in DOM element before continuing

Body:
I have a function that should wait for some text to change before it returns a value:

function getElementText() {
   while(isLoading()) {
   }
   return $('#element').text();
}

function isLoading() {
    return  $('#element')[0] &&
            $('#element').text().indexOf('Loading') >= 0;
}

However I think the empty while is not a good option (will it block the event loop?)

Body:
The DOMSubtreeModified event will be triggered when a change occurs in the element, so you can use that to detect if the text is loaded.

You can use a callback function to return the value when it has loaded. Or even better: (jQuery) promises!

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

function isLoading() {
    return element.innerText.indexOf('Loading') >= 0;
}

function getElementText() {
    var def = $.Deferred();

    if (!isLoading()) {
        def.resolve(element.innerText);
        return def.promise();
    }

    $(element).on('DOMSubtreeModified', function () {
        if (!isLoading()) {
            def.resolve(element.innerText);
        }
    });

    return def.promise();
}

getElementText().then(function (text) {
    // Text is loaded!
    alert(text);
});

// Load text after 3 seconds for demonstration
setTimeout(function () {
    element.innerText = 'Changed!';
}, 3000);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="element">Loading</div>


问:
how to create a string from char array by adding char by char in java
How to create a String in Java by adding char by char.
I have to do it like this, because i have to add a "," between al letters.
I tried it like this, but it had not worked.</p>

```<code>String t;
int l = t.length();
char[] a;
a = new char[l];
String rel = ",";
String ret = null;

for (int i = 0; i<l; i++){
    a[i] = new Character(t.charAt(0));
}

for (int v = 0; v<l; v--){
    ret += a[v];
    ret += rel;
}
</code>```

答:
If you use empty strings instead of null and initialize it then it works. </p>

```<code>String t = "foobarbaz";
int l = t.length();
char[] a;
a = new char[l];
String rel = ",";
String ret = "";
for (int i = 0; i<l; i++){
    a[i] = t.charAt(i);
}
for (int v = 0; v<l; v++){
    ret += a[v];
    ret += rel;
}
System.out.println(ret);
</code>```

Body:
How to create a String in Java by adding char by char.
I have to do it like this, because i have to add a "," between al letters.
I tried it like this, but it had not worked.

String t;
int l = t.length();
char[] a;
a = new char[l];
String rel = ",";
String ret = null;

for (int i = 0; i<l; i++){
    a[i] = new Character(t.charAt(0));
}

for (int v = 0; v<l; v--){
    ret += a[v];
    ret += rel;
}

Body:
If you use empty strings instead of null and initialize it then it works.

String t = "foobarbaz";
int l = t.length();
char[] a;
a = new char[l];
String rel = ",";
String ret = "";
for (int i = 0; i<l; i++){
    a[i] = t.charAt(i);
}
for (int v = 0; v<l; v++){
    ret += a[v];
    ret += rel;
}
System.out.println(ret);


问:
Integrating dropzone.js with laravel
I'm trying to integrate dropzone.js with laravel 5 but I get empty FileBag when trying to dd($request).

In my view:

```<code><form action="create-submit" class="dropzone" enctype="multipart/form-data">...</form>
</code>```

I included dropzone.css and basic.css, also I included dropzone.js in my HTML.

Route:

```<code>Route::get('content/create-submit', [
    'as' => 'create-submit', 'uses' => 'ContentController@createSubmit'
]);
</code>```

Controller:

```<code>public function createSubmit (Request $request) {
    dd($request);
}
</code>```

Am I missing something?

Is there an easy solution to integrate dropzone.js to laravel? Pls help

答:
try manually initialize your dropzone like

```<code>jQuery(document).ready(function () {
var myDropzone = new Dropzone("#my-dropzone", {
                url: "/dropzone",
                headers: {
                   'x-csrf-token': document.querySelectorAll('meta[name=csrf-token]')[0].getAttributeNode('content').value,
                }
              });
});
</code>```

and  in your controller

```<code>public function dropzone(Request $request)
    {
        $img    = $request->file('file'); //access dropzone files
    }
</code>```

Also, if no header token passed you will probably will not get any request.

For more detailed integration with laravel dropzone you can refer to this tutorial Integrating Dropzone.js in Laravel 5 applications

Title: Integrating dropzone.js with laravel

Body:
I'm trying to integrate dropzone.js with laravel 5 but I get empty FileBag when trying to dd($request).

In my view:

<form action="create-submit" class="dropzone" enctype="multipart/form-data">...</form>

I included dropzone.css and basic.css, also I included dropzone.js in my HTML.

Route:

Route::get('content/create-submit', [
    'as' => 'create-submit', 'uses' => 'ContentController@createSubmit'
]);

Controller:

public function createSubmit (Request $request) {
    dd($request);
}

Am I missing something?

Is there an easy solution to integrate dropzone.js to laravel? Pls help

Body:
try manually initialize your dropzone like

jQuery(document).ready(function () {
var myDropzone = new Dropzone("#my-dropzone", {
                url: "/dropzone",
                headers: {
                   'x-csrf-token': document.querySelectorAll('meta[name=csrf-token]')[0].getAttributeNode('content').value,
                }
              });
});

and  in your controller

public function dropzone(Request $request)
    {
        $img    = $request->file('file'); //access dropzone files
    }

Also, if no header token passed you will probably will not get any request.

For more detailed integration with laravel dropzone you can refer to this tutorial Integrating Dropzone.js in Laravel 5 applications


问:
POST method not inserting data into database table
I'm trying to play around with databases and inserting data dynamically with php.
At the moment I have a form with 'post' method and everything seems logical to me but it isn't inserting the data into the table.

Code is attached below, would appreciate if someone could point me into the right direction.

index.php:

```<code><form action="index.php" method="post">

<label for="name">Name</label>
<input type="text" name="name" required>

<label for="breed">Breed</label>
<input type="text" name="breed">

<label for="age">Age</label>
<input type="text" name="age">

<input type="submit" name="submit" value="Submit">

</form>

<?php

require "connect.php";

if('submit') {
    $name = $_POST['name'];
    $breed = $_POST['breed'];
    $age = $_POST['age'];

    $newdog = mysqli_query('INSERT INTO `dogs`(`name`, `breed`, `age`) VALUES ([$name],[$breed],[$age)');

    if ($newdog) {
        echo "$name has been added to the database";
    } else {
        echo "$name has not been added to database.";
    };
};

?>
</code>```

connect.php:

```<code><?php

$connect = mysqli_connect('localhost', 'max', 'password', 'db_test');

?>
</code>```

答:
```<code><?php

require "connect.php";

if(isset($_POST['submit'])) {
    $name = $_POST['name'];
    $breed = $_POST['breed'];
    $age = $_POST['age'];

    $newdog = mysqli_query($connect, 'INSERT INTO dogs(name, breed, age) VALUES ("'.$name.'","'.$breed.'","'.$age.'")');

    if ($newdog) {
        echo "$name has been added to the database";
    } else {
        echo "$name has not been added to database.";
    };
};

?>
</code>```

Body:
I'm trying to play around with databases and inserting data dynamically with php.
At the moment I have a form with 'post' method and everything seems logical to me but it isn't inserting the data into the table.

Code is attached below, would appreciate if someone could point me into the right direction.

index.php:

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

Name
<input type="text" name="name" required>

Breed
<input type="text" name="breed">

Age
<input type="text" name="age">

<input type="submit" name="submit" value="Submit">

</form>

<?php

require "connect.php";

if('submit') {
    $name = $_POST['name'];
    $breed = $_POST['breed'];
    $age = $_POST['age'];

    $newdog = mysqli_query('INSERT INTO `dogs`(`name`, `breed`, `age`) VALUES ([$name],[$breed],[$age)');

    if ($newdog) {
        echo "$name has been added to the database";
    } else {
        echo "$name has not been added to database.";
    };
};

?>

connect.php:

<?php

$connect = mysqli_connect('localhost', 'max', 'password', 'db_test');

?>


问:
How can I loop through a JavaScript object array?
I am trying to loop through the following:

```<code>{
    "messages": [{
        "msgFrom": "13223821242",
        "msgBody": "Hi there"
    }, {
        "msgFrom": "Bill",
        "msgBody": "Hello!"
    }]
}
</code>```

I want to retrieve msgFrom and msgBody

I've tried:

```<code>        for (var key in data) {
           var obj = data[key];
           for (var prop in obj) {
              if(obj.hasOwnProperty(prop)){
                console.log(prop + " = " + obj[prop]);
              }
           }
        }
</code>```

But the console log prints [Object]

Any ideas what im doing wrong?

答:
To reference the contents of the single array containing one or more objects i.e. everything in the brackets of something like this
{messages: [{"a":1,"b":2}] } ,just add [0] to the query to get the first array element

e.g. messages[0] will reference the object {"a":1,"b":2}
as opposed to just messages which would reference the entire array [{"a":1,"b":2}]

from there you can work with the result as typical object and use Object.keys for example to get "a" and "b".

Body:
I am trying to loop through the following:

{
    "messages": [{
        "msgFrom": "13223821242",
        "msgBody": "Hi there"
    }, {
        "msgFrom": "Bill",
        "msgBody": "Hello!"
    }]
}

I want to retrieve msgFrom and msgBody

I've tried:

        for (var key in data) {
           var obj = data[key];
           for (var prop in obj) {
              if(obj.hasOwnProperty(prop)){
                console.log(prop + " = " + obj[prop]);
              }
           }
        }

But the console log prints [Object]

Any ideas what im doing wrong?