问:
Adding mysqli_connect() function stops running the script
When I add the mysqli_connect statement in my php file it stops working the whole script. If make this statement comment my php file works as expected. I am adding this file to a wordpress website.

I have tried to connect using mysql_connect() also but the result is same.

My Code:

```<code><?php

require_once ($_SERVER['DOCUMENT_ROOT'].'/wp-config.php');

ini_set('display_errors', 1);
error_reporting(E_ALL);

//phpinfo();

echo DB_NAME ."<br>";
echo DB_USER ."<br>";
echo DB_PASSWORD ."<br>";
echo DB_HOST."<br>"

$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD,DB_NAME);
// database port is also 3306 which is default

if (!$conn) {
    echo  "Connection failed: " . mysqli_connect_error();
}
echo "Connected successfully";

?>
</code>```

php.info() outputs that mysqli is installed is also enabled.

Do I need to include some file to access mysqli_connect() function.

How can I connect to the database?

答:
Use this code. You missed semi colon at end of DB_HOST."
" line. Every thing is fine in code.

```<code><?php

require_once ($_SERVER['DOCUMENT_ROOT'].'/wp-config.php');

ini_set('display_errors', 1);
error_reporting(E_ALL);

//phpinfo();

echo DB_NAME ."<br>";
echo DB_USER ."<br>";
echo DB_PASSWORD ."<br>";
echo DB_HOST."<br>";

$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD,DB_NAME);
// database port is also 3306 which is default

if (!$conn) {
    echo  "Connection failed: " . mysqli_connect_error();
}
echo "Connected successfully";

?>
</code>```

Body:
When I add the mysqli_connect statement in my php file it stops working the whole script. If make this statement comment my php file works as expected. I am adding this file to a wordpress website.

I have tried to connect using mysql_connect() also but the result is same.

My Code:

<?php

require_once ($_SERVER['DOCUMENT_ROOT'].'/wp-config.php');

ini_set('display_errors', 1);
error_reporting(E_ALL);

//phpinfo();

echo DB_NAME ."
";
echo DB_USER ."
";
echo DB_PASSWORD ."
";
echo DB_HOST."
"

$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD,DB_NAME);
// database port is also 3306 which is default

if (!$conn) {
    echo  "Connection failed: " . mysqli_connect_error();
}
echo "Connected successfully";

?>

php.info() outputs that mysqli is installed is also enabled.

Do I need to include some file to access mysqli_connect() function.

How can I connect to the database?

Body:
Use this code. You missed semi colon at end of DB_HOST."<br>" line. Every thing is fine in code.

<?php

require_once ($_SERVER['DOCUMENT_ROOT'].'/wp-config.php');

ini_set('display_errors', 1);
error_reporting(E_ALL);

//phpinfo();

echo DB_NAME ."<br>";
echo DB_USER ."<br>";
echo DB_PASSWORD ."<br>";
echo DB_HOST."<br>";

$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD,DB_NAME);
// database port is also 3306 which is default

if (!$conn) {
    echo  "Connection failed: " . mysqli_connect_error();
}
echo "Connected successfully";

?>


来源: stackexchange

问:
Python beautiful soup4- find_all returns "[]"
I am using python BS4 to scrape the https://skinup.gg website. I am trying to get the multiplier class, in order, from a website.

I tried to scrape the information by taking all the data from the div history class. However it just returns [] and I am stumped on how to get the multipliers.

I wonder if it is because the div tag class values are constantly changing. Which leads me to my second question: how do they have dynamic values in html tags? Is it done via Javascript?

Excuse my grammar.

Here is my code:

```<code>import urllib.request
import requests
from bs4 import BeautifulSoup
import urllib

page = requests.g et("https://skinup.gg/"
soup = BeautifulSoup(page.content, "html.parser")

print(soup.find_all('div', attrs={'class': 'win'}))
</code>```

Relevant website code:

```<code><div class="history"><div class="win" style="">
  <time class="date">23:05</time>
  <span class="multiplier">2.19</span>
</div><div class="win" style="">
  <time class="date">23:04</time>
  <span class="multiplier">2.62</span>
</div><div class="lose" style="">
  <time class="date">23:04</time>
  <span class="multiplier">1.75</span>
</div><div class="lose" style="">
  <time class="date">23:04</time>
  <span class="multiplier">1.00</span>
</div><div class="lose" style="">
  <time class="date">23:04</time>
  <span class="multiplier">1.21</span>
</div><div style="">
  <time class="date">23:03</time>
  <span class="multiplier">1.82</span>
</div><div class="lose" style="">
  <time class="date">23:03</time>
  <span class="multiplier">1.00</span>
</div><div class="win" style="">
  <time class="date">23:03</time>
  <span class="multiplier">2.91</span>
</div><div class="lose" style="">
  <time class="date">23:02</time>
  <span class="multiplier">1.01</span>
</div><div class="win" style="">
  <time class="date">23:02</time>
  <span class="multiplier">1184.44</span>
</div><div class="win" style="">
  <time class="date">23:01</time>
  <span class="multiplier">36.81</span>
</div><div class="lose" style="">
  <time class="date">22:59</time>
  <span class="multiplier">1.38</span>
</div><div class="win" style="">
  <time class="date">22:59</time>
  <span class="multiplier">2.42</span>
</div><div class="win" style="">
  <time class="date">22:59</time>
  <span class="multiplier">8.00</span>
</div><div class="win" style="">
  <time class="date">22:58</time>
  <span class="multiplier">3.42</span>
</div><div class="win" style="">
  <time class="date">22:57</time>
  <span class="multiplier">2.04</span>
</div><div class="lose" style="">
  <time class="date">22:57</time>
  <span class="multiplier">1.17</span>
</div><div class="lose" style="">
  <time class="date">22:57</time>
  <span class="multiplier">1.24</span>
</div><div class="lose" style="">
  <time class="date">22:57</time>
  <span class="multiplier">1.11</span>
</div><div class="lose" style="">
  <time class="date">22:56</time>
  <span class="multiplier">1.53</span>
</div>

                </div>
</code>```

答:
As t.m.adam mentioned , urllib or requests can't get the dynamic page source.

But when you see the page you linked with chrome developer tools, you can see that div win class is generated when round.multiplier >2.

 These are received by 'socketcluster/' which use wss protocol.

so you should use python wss module to acheive your goal.

ContentLicense: CC BY-SA 3.0

Body:
I am using python BS4 to scrape the https://skinup.gg website. I am trying to get the multiplier class, in order, from a website.

I tried to scrape the information by taking all the data from the div history class. However it just returns [] and I am stumped on how to get the multipliers.

I wonder if it is because the div tag class values are constantly changing. Which leads me to my second question: how do they have dynamic values in html tags? Is it done via Javascript?

Excuse my grammar.

Here is my code:

import urllib.request
import requests
from bs4 import BeautifulSoup
import urllib

page = requests.g et("https://skinup.gg/"
soup = BeautifulSoup(page.content, "html.parser")

print(soup.find_all('div', attrs={'class': 'win'}))

Relevant website code:

  <time class="date">23:05</time>
  2.19

  <time class="date">23:04</time>
  2.62

  <time class="date">23:04</time>
  1.75

  <time class="date">23:04</time>
  1.00

  <time class="date">23:04</time>
  1.21

  <time class="date">23:03</time>
  1.82

  <time class="date">23:03</time>
  1.00

  <time class="date">23:03</time>
  2.91

  <time class="date">23:02</time>
  1.01

  <time class="date">23:02</time>
  1184.44

  <time class="date">23:01</time>
  36.81

  <time class="date">22:59</time>
  1.38

  <time class="date">22:59</time>
  2.42

  <time class="date">22:59</time>
  8.00

  <time class="date">22:58</time>
  3.42

  <time class="date">22:57</time>
  2.04

  <time class="date">22:57</time>
  1.17

  <time class="date">22:57</time>
  1.24

  <time class="date">22:57</time>
  1.11

  <time class="date">22:56</time>
  1.53


问:
Why automatic currying in ML family languages
ML family languages have automatic currying - where a function call with two arguments is considered to apply them one at a time, f x y = (f x) y - whereas other language families don't.

Is this just a historical accident, or is there a technical reason for this?

Note that I am not asking whether automatic currying is net good or bad (that's a subjective judgment). I'm asking whether it synergizes with other features of ML family languages so as to make it more natural to include in those languages, and if so, what are those features and what is the nature of the synergy? Or conversely, are there features of other language families that would clash with any attempt to provide automatic currying?

Edit: in addition to the given answers, it occurs to me that there is probably another factor: if you are writing the compiler in a language with pattern matching, it's okay for the AST to be more complex, which means it's okay for the conventional 'call with a tuple' construct to be a compound term. So given that the compiler is often written in its own language, automatic currying and pattern matching go well together.

答:
It certainly is no accident.

For one, it simplifies the language: no need to introduce functions with multiple arguments as a separate concept; every function has exactly one argument. Multiple arguments can be expressed either by tuples or by currying.

Second, it is very convenient in practice, as various patterns relying on partial application (e.g., higher-order functions, combinator libraries, etc) demonstrate..


问:
restore a model trained with variable input length in tensorflow results in InvalidArgumentError
I am rather new to tensorflow and am currently experimenting with models of varying complexity. I have a problem with the save and restore functionality of the package. As far as I did understand the tutorials, I should be able to restore a trained graph and run it with some new input at some later point. However, I get the following error when I try to do just that.:

InvalidArgumentError (see above for traceback): Shape [-1,10] has negative dimensions
       [[Node: Placeholder = Placeholderdtype=DT_FLOAT, shape=[?,10], _device="/job:localhost/replica:0/task:0/cpu:0"]]

My understanding of the message is that the restored graph does not like one dimension to be left arbitrary, which in turn is necessary for practical cases where I don't know beforehand how large my input will be. A code snippet as a minimal example, producing the error above, can be found below. I know how to restore each tensor individually but this gets impractical pretty quickly when the models grow in complexity. I am thankful for any help I get and apologize in case my question is stupid.

```<code>import numpy as np
import tensorflow as tf

def generate_random_input():
    alist = []
    for _ in range(10):
        alist.append(np.random.uniform(-1, 1, 100))
    return np.array(alist).T
def generate_random_target():
    return np.random.uniform(-1, 1, 100)

x = tf.placeholder('float', [None, 10])
y = tf.placeholder('float')

# the model
w1 = tf.get_variable('w1', [10, 1], dtype=tf.float32, initializer=tf.contrib.layers.xavier_initializer(seed=1))
b1 = tf.get_variable('b1', [1], dtype=tf.float32, initializer=tf.contrib.layers.xavier_initializer(seed=1))

result = tf.add(tf.matmul(x, w1), b1, name='result')

loss = tf.reduce_mean(tf.losses.mean_squared_error(predictions=result, labels=y))
optimizer = tf.train.AdamOptimizer(0.03).minimize(loss)
saver = tf.train.Saver()
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    sess.run([optimizer, loss], feed_dict={x: generate_random_input(), y: generate_random_target()})
    saver.save(sess, 'file_name')

# now load the model in another session:
sess2 = tf.Session()
saver = tf.train.import_meta_graph('file_name.meta')
saver.restore(sess2, tf.train.latest_checkpoint('./'))
graph = tf.get_default_graph()
pred = graph.get_operation_by_name('result')
test_result = sess2.run(pred, feed_dict={x: generate_random_input()})
</code>```

答: in the last line, you don't feed_dict the label_palceholder with the data. So in the placeholder, the [-1] dimension is still -1, other than the batch size. That's the cause.</p>

Body:
I am rather new to tensorflow and am currently experimenting with models of varying complexity. I have a problem with the save and restore functionality of the package. As far as I did understand the tutorials, I should be able to restore a trained graph and run it with some new input at some later point. However, I get the following error when I try to do just that.:

InvalidArgumentError (see above for traceback): Shape [-1,10] has negative dimensions
       [[Node: Placeholder = Placeholderdtype=DT_FLOAT, shape=[?,10], _device="/job:localhost/replica:0/task:0/cpu:0"]]

My understanding of the message is that the restored graph does not like one dimension to be left arbitrary, which in turn is necessary for practical cases where I don't know beforehand how large my input will be. A code snippet as a minimal example, producing the error above, can be found below. I know how to restore each tensor individually but this gets impractical pretty quickly when the models grow in complexity. I am thankful for any help I get and apologize in case my question is stupid.

import numpy as np
import tensorflow as tf

def generate_random_input():
    alist = []
    for _ in range(10):
        alist.append(np.random.uniform(-1, 1, 100))
    return np.array(alist).T
def generate_random_target():
    return np.random.uniform(-1, 1, 100)

x = tf.placeholder('float', [None, 10])
y = tf.placeholder('float')

# the model
w1 = tf.get_variable('w1', [10, 1], dtype=tf.float32, initializer=tf.contrib.layers.xavier_initializer(seed=1))
b1 = tf.get_variable('b1', [1], dtype=tf.float32, initializer=tf.contrib.layers.xavier_initializer(seed=1))

result = tf.add(tf.matmul(x, w1), b1, name='result')

loss = tf.reduce_mean(tf.losses.mean_squared_error(predictions=result, labels=y))
optimizer = tf.train.AdamOptimizer(0.03).minimize(loss)
saver = tf.train.Saver()
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    sess.run([optimizer, loss], feed_dict={x: generate_random_input(), y: generate_random_target()})
    saver.save(sess, 'file_name')

# now load the model in another session:
sess2 = tf.Session()
saver = tf.train.import_meta_graph('file_name.meta')
saver.restore(sess2, tf.train.latest_checkpoint('./'))
graph = tf.get_default_graph()
pred = graph.get_operation_by_name('result')
test_result = sess2.run(pred, feed_dict={x: generate_random_input()})


问:
MySQL 5.7 and connection attribute
I have looked everywhere and well researched into different solutions. I have come closer to the solution by reducing the number of errors. Here is my piece of code that's giving me a headache

```<code>from flask import Flask, render_template, json, request
from flaskext.mysql import MySQL
from werkzeug import generate_password_hash,check_password_hash

mysql = MySQL()
app = Flask(__name__)

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'root'
app.config['MYSQL_DB'] = 'BucketList'

mysql.init_app(app)
cur = mysql.connection.cursor()
</code>```

I have been running the app.py file and keep getting the following error:

AttributeError: 'MySQL' object has no attribute 'connection'.

I am using MySQL 5.7 and attempting to create my first web app using a tutorial that's dated back in time. The above piece of code is after editing it closer to relevant standards.

答:
The part of your code in which you instantiate the MySQl() object is incorrect. Instead of:

```<code>mysql = MySQL()
app = Flask(__name__)
</code>```

It should be

```<code>app = Flask(__name__)
mysql = MySQL(app)
</code>```

Title: MySQL 5.7 and connection attribute

Body:
I have looked everywhere and well researched into different solutions. I have come closer to the solution by reducing the number of errors. Here is my piece of code that's giving me a headache

from flask import Flask, render_template, json, request
from flaskext.mysql import MySQL
from werkzeug import generate_password_hash,check_password_hash

mysql = MySQL()
app = Flask(__name__)

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'root'
app.config['MYSQL_DB'] = 'BucketList'

mysql.init_app(app)
cur = mysql.connection.cursor()

I have been running the app.py file and keep getting the following error:

AttributeError: 'MySQL' object has no attribute 'connection'.

I am using MySQL 5.7 and attempting to create my first web app using a tutorial that's dated back in time. The above piece of code is after editing it closer to relevant standards.

Body:
The part of your code in which you instantiate the MySQl() object is incorrect. Instead of:

mysql = MySQL()
app = Flask(__name__)

It should be

app = Flask(__name__)
mysql = MySQL(app)


问:
Java: problems using stream to read a file
using what has been previously suggested to me here, I'm trying to read a file using Path and streams in the following way:

```<code>Path p= Paths.get(file);
        try (Stream<String> lines = Files.lines(p, StandardCharsets.UTF_8)) { // 1
            lines.map(line -> line.split(";"))                          // 2
                 .forEach(lineAsArray -> {
                     if (lineAsArray[0].equals("E")) {
                         creaEditore(lineAsArray[2], Integer.parseInt(lineAsArray[3]), lineAsArray[4]);
                     }
                     else if (lineAsArray[0].equals("L")) {
                        Libro tmp = null;
                        try {
                            tmp = creaLibro(lineAsArray[1], lineAsArray[2], Integer.parseInt(lineAsArray[3]), Double.parseDouble(lineAsArray[4]), lineAsArray[5]);
                        } catch (NumberFormatException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (EditoreInesistente e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        tmp.setQuantita(Integer.parseInt(lineAsArray[6]));
                     }
                 });
        }
        catch (IOException io)
        {
            System.out.println("Wrong reading");
        }
</code>```

Each line contains at the beginning a letter that corresponds to the object I want to create (either an "Editore" or a "Libro") and the following fields contains the value of its attributes (all fields are separated by a semi-column). However, when executing, I get the following exceptions and errors:

```<code>Exception in thread "main" java.lang.NumberFormatException: For input string: "cheih@gja.it"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at libreria.Libreria.lambda$4(Libreria.java:122)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(Unknown Source)
    at java.util.stream.ReferencePipeline$3$1.accept(Unknown Source)
    at java.util.Iterator.forEachRemaining(Unknown Source)
    at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Unknown Source)
    at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
    at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(Unknown Source)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(Unknown Source)
    at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
    at java.util.stream.ReferencePipeline.forEach(Unknown Source)
    at libreria.Libreria.leggi(Libreria.java:120)
    at Esempio.main(Esempio.java:20)
</code>```

Debugging I discovered that everything is perfectly working when reading the first line, but then the program is not able to parse it and get each field using lineAsArray[]. Can someone help me? The requirements of the program also asked for not considering lines with incorrect sintax, would my code do something like that automatically?

Here the sintax of my file:

Thanks in advance for your help,
Gianluca.

答:
When your case is E, your code is following

```<code>if (lineAsArray[0].equals("E")) {
   creaEditore(lineAsArray[2], Integer.parseInt(lineAsArray[3]), lineAsArray[4]);
   }
</code>```

And you are trying to convert value of lineAsArray[3] into Int.
In this case value at index 3 is "cheih@gja.it" which cannot be converted to int. Which is why you are getting this exception

Body:
using what has been previously suggested to me here, I'm trying to read a file using Path and streams in the following way:

Path p= Paths.get(file);
        try (Stream<String> lines = Files.lines(p, StandardCharsets.UTF_8)) { // 1
            lines.map(line -> line.split(";"))                          // 2
                 .forEach(lineAsArray -> {
                     if (lineAsArray[0].equals("E")) {
                         creaEditore(lineAsArray[2], Integer.parseInt(lineAsArray[3]), lineAsArray[4]);
                     }
                     else if (lineAsArray[0].equals("L")) {
                        Libro tmp = null;
                        try {
                            tmp = creaLibro(lineAsArray[1], lineAsArray[2], Integer.parseInt(lineAsArray[3]), Double.parseDouble(lineAsArray[4]), lineAsArray[5]);
                        } catch (NumberFormatException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (EditoreInesistente e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        tmp.setQuantita(Integer.parseInt(lineAsArray[6]));
                     }
                 });
        }
        catch (IOException io)
        {
            System.out.println("Wrong reading");
        }

Each line contains at the beginning a letter that corresponds to the object I want to create (either an "Editore" or a "Libro") and the following fields contains the value of its attributes (all fields are separated by a semi-column). However, when executing, I get the following exceptions and errors:

Exception in thread "main" java.lang.NumberFormatException: For input string: "cheih@gja.it"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at libreria.Libreria.lambda$4(Libreria.java:122)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(Unknown Source)
    at java.util.stream.ReferencePipeline$3$1.accept(Unknown Source)
    at java.util.Iterator.forEachRemaining(Unknown Source)
    at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Unknown Source)
    at java.util.stream.AbstractPipeline.copyInto(Unknown Source)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(Unknown Source)
    at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(Unknown Source)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(Unknown Source)
    at java.util.stream.AbstractPipeline.evaluate(Unknown Source)
    at java.util.stream.ReferencePipeline.forEach(Unknown Source)
    at libreria.Libreria.leggi(Libreria.java:120)
    at Esempio.main(Esempio.java:20)

Debugging I discovered that everything is perfectly working when reading the first line, but then the program is not able to parse it and get each field using lineAsArray[]. Can someone help me? The requirements of the program also asked for not considering lines with incorrect sintax, would my code do something like that automatically?

Here the sintax of my file:

Thanks in advance for your help,
Gianluca.

Body:
When your case is E, your code is following

if (lineAsArray[0].equals("E")) {
   creaEditore(lineAsArray[2], Integer.parseInt(lineAsArray[3]), lineAsArray[4]);
   }

And you are trying to convert value of lineAsArray[3] into Int.
In this case value at index 3 is "cheih@gja.it" which cannot be converted to int. Which is why you are getting this exception


问:
How to take data from DB table put into entity that has an inherited class with EF?
I have a SQL view that I am pulling in with entity framework. The view represents two existing objects that are joined together. I figured the best way to do this would be to have object inherit the other object.

I'm getting this error:

System.Data.Entity.Core.EntityCommandExecutionException: An error
  occurred while executing the command definition. See the inner
  exception for details. ---> System.Data.SqlClient.SqlException:
  Invalid column name 'Discriminator'.

Here is what I have setup:

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Class1>()
     .ToTable("mySQLView", "TEST")
     .HasKey(r => new { r.Property1 });

    modelBuilder.Entity<Class1>().Property(r => r.Property1).HasColumnName("Key1");
    modelBuilder.Entity<Class1>().Property(r => r.Property2).HasColumnName("Column2");

    modelBuilder.Entity<Class1>().Property(r => r.Property3).HasColumnName("Column3");
    modelBuilder.Entity<Class1>().Property(r => r.Property4).HasColumnName("Column4");
}
</code>```

Here are my two classes:

```<code>public class Class1 : Class2
{
    public string Property1 { get; set; }
    public string Property2 { get; set; }
}

public class Class2
{
    public string Property3 { get; set; }
    public string Property4 { get; set; }
}
</code>```

Class2 is being utilized by separate DB calls. Class1 is only being used in one of those calls. Any help on how to structure my classes or setup EF correctly would be greatly appreciated!

答:
The problem is that you are using TPH (Table Per Hieararchy) that is a way that EF uses to implement inherithance. Using TPH EF needs a column named discriminator to associate the record with a specific entity of the hierarchy.

In your case I think you need TPT (but it depends on what you want access to classes). To do it just set the name of the Class2 table (or view) using ToTable. Otherwise you can add Discriminator column but you should leave EF to handle it.

Body:
I have a SQL view that I am pulling in with entity framework. The view represents two existing objects that are joined together. I figured the best way to do this would be to have object inherit the other object.

I'm getting this error:

System.Data.Entity.Core.EntityCommandExecutionException: An error
  occurred while executing the command definition. See the inner
  exception for details. ---> System.Data.SqlClient.SqlException:
  Invalid column name 'Discriminator'.

Here is what I have setup:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Class1>()
     .ToTable("mySQLView", "TEST")
     .HasKey(r => new { r.Property1 });

    modelBuilder.Entity<Class1>().Property(r => r.Property1).HasColumnName("Key1");
    modelBuilder.Entity<Class1>().Property(r => r.Property2).HasColumnName("Column2");

    modelBuilder.Entity<Class1>().Property(r => r.Property3).HasColumnName("Column3");
    modelBuilder.Entity<Class1>().Property(r => r.Property4).HasColumnName("Column4");
}

Here are my two classes:

public class Class1 : Class2
{
    public string Property1 { get; set; }
    public string Property2 { get; set; }
}

public class Class2
{
    public string Property3 { get; set; }
    public string Property4 { get; set; }
}

Class2 is being utilized by separate DB calls. Class1 is only being used in one of those calls. Any help on how to structure my classes or setup EF correctly would be greatly appreciated!


问:
Arabic language in android
android still not fully support Arabic language even in last version 2.3 and maybe not in 3.0 also

any way i am programmer if i want to make it Arabic support how to start to make it fully support Arabic ?

because i found some the companies like Samsung and HTC add fully Arabic support to there devices this mean every body if he has a good knowledge with the system can add support.

答:
I found a couple projects which attempt that, maybe you could look at those and see what exactly needs to be done

https://sites.google.com/a/ut.utm.edu/arabic-android/

Title: Arabic language in android

ContentLicense: CC BY-SA 2.5


问:
Send cursor to the end of input value in React
I am dynamically passing a value to my input field when clicking delete (in order to edit the last input entry).

I can see that in Chrome once the input value gets rendered the cursor shows up a the beginning of the word, while in Safari and Firefox goes at the end of the value but the last letter gets deleted.

How can I always see the cursor at the end without deleting the last letter(unless I hit backspace twice)?

```<code>  tagEvent(e) {
    const tag = this.text.value;
    const tagGroup = tag.split(" ");
    const tiles = this.props.tiles;
    const hasTiles = Object.keys(tiles).length > 0;

    if(e.keyCode === 32 || e.keyCode === 13){
      e.preventDefault();
      tagGroup.map(tag => this.props.addTile(tag));
      this.tagForm.reset();
    }

    if(e.keyCode === 8 && hasTiles && tag === '' ) {
      this.props.editLastTile();
      this.tagForm.reset();
    }
  }

  render() {
    return (
      <div className="input-wrapper">
        <form ref={(input) => this.tagForm = input}>
          <input ref={(input) => this.text = input}
                 type="text"
                 name="new-item"
                 placeholder="type and press space"
                 autoComplete="off"
                 defaultValue={this.props.value}
                 onKeyDown={(e) => this.tagEvent(e)} />
        </form>
      </div>
    )
  }
</code>```

Here a Pen with the full code

Thanks a lot for the help!

答:
You can explicitly set cursor position, to do so add this to Input:

```<code>componentDidUpdate(prevProps) {
    if (prevProps.value !== this.props.value) {
        this.text.selectionStart = this.text.value.length;
        this.text.selectionEnd = this.text.value.length;
    }
}
</code>```

To prevent removing last character add a e.preventDefault() after if(e.keyCode === 8 && hasTiles && tag === '' ) {

Edited Pen

Body:
I am dynamically passing a value to my input field when clicking delete (in order to edit the last input entry).

I can see that in Chrome once the input value gets rendered the cursor shows up a the beginning of the word, while in Safari and Firefox goes at the end of the value but the last letter gets deleted.

How can I always see the cursor at the end without deleting the last letter(unless I hit backspace twice)?

  tagEvent(e) {
    const tag = this.text.value;
    const tagGroup = tag.split(" ");
    const tiles = this.props.tiles;
    const hasTiles = Object.keys(tiles).length > 0;

    if(e.keyCode === 32 || e.keyCode === 13){
      e.preventDefault();
      tagGroup.map(tag => this.props.addTile(tag));
      this.tagForm.reset();
    }

    if(e.keyCode === 8 && hasTiles && tag === '' ) {
      this.props.editLastTile();
      this.tagForm.reset();
    }
  }

  render() {
    return (

        <form ref={(input) => this.tagForm = input}>
          <input ref={(input) => this.text = input}
                 type="text"
                 name="new-item"
                 placeholder="type and press space"
                 autoComplete="off"
                 defaultValue={this.props.value}
                 onKeyDown={(e) => this.tagEvent(e)} />
        </form>

    )
  }

Here a Pen with the full code

Thanks a lot for the help!

Body:
You can explicitly set cursor position, to do so add this to Input:

componentDidUpdate(prevProps) {
    if (prevProps.value !== this.props.value) {
        this.text.selectionStart = this.text.value.length;
        this.text.selectionEnd = this.text.value.length;
    }
}

To prevent removing last character add a e.preventDefault() after if(e.keyCode === 8 && hasTiles && tag === '' ) {

Edited Pen


问:
Akka Http - how to read Content-Disposition from HttpResponse headers?
I'm using Akka Http to download a file and I'm having trouble extracting the filename from response headers. My response headers look like this:

```<code>Server: custom_server
Date: Sat, 8 Jul 2017 01:30:39 GMT
Connection: keep-alive
Pragma: public
Cache-Control: must-revalidate
Expires: Thu, 01 Jan 1970 00:00:00 GMT
content-disposition: attachment;filename*=UTF-8''my_custom_name.pdf
Strict-Transport-Security: max-age=15768000
</code>```

When i'm trying to check if the content-disposition header exists I'm always receiving false:

```<code>val hasDispositionHeader = response.headers.exists {
  case headers.`Content-Disposition`(contentDisposition, params) => true
  case _ => false
}
</code>```

Tried to use the java api too with no success:

```<code>val fileName = response.header[ContentDisposition].get.value
</code>```

I have noticed that the content-disposition header key is lowercase (it's a remote server I have no control over) - any idea on how to deal with this?

Many thanks for your help!

答:
Looking at http://doc.akka.io/docs/akka/2.4.11.1/scala/http/common/http-model.html#HttpResponse, I see response.headers is a Seq, so:

```<code>response.headers.find(_name.toLowerCase == "content-disposition")
</code>```

Body:
I'm using Akka Http to download a file and I'm having trouble extracting the filename from response headers. My response headers look like this:

Server: custom_server
Date: Sat, 8 Jul 2017 01:30:39 GMT
Connection: keep-alive
Pragma: public
Cache-Control: must-revalidate
Expires: Thu, 01 Jan 1970 00:00:00 GMT
content-disposition: attachment;filename*=UTF-8''my_custom_name.pdf
Strict-Transport-Security: max-age=15768000

When i'm trying to check if the content-disposition header exists I'm always receiving false:

val hasDispositionHeader = response.headers.exists {
  case headers.`Content-Disposition`(contentDisposition, params) => true
  case _ => false
}

Tried to use the java api too with no success:

val fileName = response.header[ContentDisposition].get.value

I have noticed that the content-disposition header key is lowercase (it's a remote server I have no control over) - any idea on how to deal with this?

Many thanks for your help!

Body:
Looking at http://doc.akka.io/docs/akka/2.4.11.1/scala/http/common/http-model.html#HttpResponse, I see response.headers is a Seq, so:

response.headers.find(_name.toLowerCase == "content-disposition")


问:
Upgrading Node on an Azure website?
I'm trying to run some pre deployment tasks (unit tests etc) with NPM on an Azure website, however the version of node on the VM is v0.10.32, the current version of node is v4.2.4.

I have non administrative access to the command line via the SCM website, no RDP etc.

Is there any way to upgrade?

答:
2017 update. All above didn't work for me in.

I changed:

```<code>// package.json
engines":{"node": "8.0.0"}
</code>```

and then I added app settings value

```<code><appSettings>
    <add key="WEBSITE_NODE_DEFAULT_VERSION" value="8.0.0" />
</appSettings>
</code>```

I restarted an app million times, and the solution was to change iisnode.yml

```<code>nodeProcessCommandLine: "D:\Program Files (x86)\nodejs\8.0.0\node.exe"
</code>```

That's it. I hope it will help someone.

Update

Just to clarify things: I'm talking about App Service

And if you ftp to your App you will see iisnode.yml here:

Title: Upgrading Node on an Azure website?

Body:
2017 update. All above didn't work for me in.

I changed:

// package.json
engines":{"node": "8.0.0"}

and then I added app settings value

<appSettings>
    <add key="WEBSITE_NODE_DEFAULT_VERSION" value="8.0.0" />
</appSettings>

I restarted an app million times, and the solution was to change iisnode.yml

nodeProcessCommandLine: "D:\Program Files (x86)\nodejs\8.0.0\node.exe"

That's it. I hope it will help someone.

Update

Just to clarify things: I'm talking about App Service

And if you ftp to your App you will see iisnode.yml here:


问:
c# uwp GridView ItemsWrapGrid bottom margin
In UWP I am creating horizontal GridView.

For ItemsPanelTemplate I am using ItemsWrapGrid as following:

```<code><GridView.ItemsPanel>
    <ItemsPanelTemplate>
        <ItemsWrapGrid Orientation="Vertical"
                       MaximumRowsOrColumns="1"
                       ItemWidth="200"
                       ItemHeight="100"/>
    </ItemsPanelTemplate>
</GridView.ItemsPanel>
</code>```

The problem is that I have some bottom margin that is the same height as the scrollbar. When scrollbar is hidden there is this empty space, and the items are cutted.

I have tried to change margins, paddings...but no luck.

Any idea?

答:
If anyone have this problem, I have just added:

```<code>Margin="0,0,0,-10"
</code>```

inside ItemsWrapGrid.

And it fixed it.

Body:
In UWP I am creating horizontal GridView.

For ItemsPanelTemplate I am using ItemsWrapGrid as following:

<GridView.ItemsPanel>
    <ItemsPanelTemplate>
        <ItemsWrapGrid Orientation="Vertical"
                       MaximumRowsOrColumns="1"
                       ItemWidth="200"
                       ItemHeight="100"/>
    </ItemsPanelTemplate>
</GridView.ItemsPanel>

The problem is that I have some bottom margin that is the same height as the scrollbar. When scrollbar is hidden there is this empty space, and the items are cutted.

I have tried to change margins, paddings...but no luck.

Any idea?

Body:
If anyone have this problem, I have just added:

Margin="0,0,0,-10"

inside ItemsWrapGrid.

And it fixed it.


答:
You missed a semicolon at echo DB_HOST."

```<code>    require_once ($_SERVER['DOCUMENT_ROOT'].'/wp-config.php');

    ini_set('display_errors', 1);
    error_reporting(E_ALL);

    //phpinfo();

    echo DB_NAME ."<br>";
    echo DB_USER ."<br>";
    echo DB_PASSWORD ."<br>";
    echo DB_HOST."<br>";

    $conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD,DB_NAME);
    // database port is also 3306 which is default

    if (!$conn) {
        echo  "Connection failed: " . mysqli_connect_error();
    }
    echo "Connected successfully";

    ?>
</code>```

Title: Adding mysqli_connect() function stops running the script

Body:
You missed a semicolon at echo DB_HOST."

    require_once ($_SERVER['DOCUMENT_ROOT'].'/wp-config.php');

    ini_set('display_errors', 1);
    error_reporting(E_ALL);

    //phpinfo();

    echo DB_NAME ."<br>";
    echo DB_USER ."<br>";
    echo DB_PASSWORD ."<br>";
    echo DB_HOST."<br>";

    $conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD,DB_NAME);
    // database port is also 3306 which is default

    if (!$conn) {
        echo  "Connection failed: " . mysqli_connect_error();
    }
    echo "Connected successfully";

    ?>


问:
Improved clojurescipt repl functionality for descjop project
I'm building a project based on descjop and reagent, created using the command:

```<code>lein new descjop <myproj> +reagent
</code>```

The repl started by lein figwheel works ok but has very basic functionality. There is no command history, and no cursor control. Ideally I would like the full cider/nrepl/clj-refactor functionality but just some basic history and command editing would do.

Is there any easy way to improve the current repl? I have tried exploring the generated code, but I can't see how the decjop template is setting up the clojurescript repl. Any clues to how this works would be helpful.

Alternatively is there any way I can set up an alternative clojurescript repl to connect with my running electron app?

答:
If you are on a Unix type machine then you can install rlwrap. Then instead of starting the REPL from the command line like so:

```<code>lein figwheel
</code>```

Start it like this:

```<code>rlwrap lein figwheel
</code>```

Then you will get history (using up and down arrows) and basic editing.

Body:
I'm building a project based on descjop and reagent, created using the command:

lein new descjop <myproj> +reagent

The repl started by lein figwheel works ok but has very basic functionality. There is no command history, and no cursor control. Ideally I would like the full cider/nrepl/clj-refactor functionality but just some basic history and command editing would do.

Is there any easy way to improve the current repl? I have tried exploring the generated code, but I can't see how the decjop template is setting up the clojurescript repl. Any clues to how this works would be helpful.

Alternatively is there any way I can set up an alternative clojurescript repl to connect with my running electron app?

Body:
If you are on a Unix type machine then you can install rlwrap. Then instead of starting the REPL from the command line like so:

lein figwheel

Start it like this:

rlwrap lein figwheel

Then you will get history (using up and down arrows) and basic editing.


问:
c++ hide terminal with GTKMM gui apps
I've been looking around on the cplusplus forum and here on stackoverflow, but I have not been able to find an answer. All I find is Windows stuff or people working with IDE'S that do the work for them.

I am creating an application with c++ and GTKMM and nothing else, I just have a texteditor and a compiler that I control with my terminal (I adress this because a lot of people always talk about IDE'S and stuff) on UNIX based computers.

When I run my application (./application) I always see my terminal along with my gui application and I would like to hide the terminal. How would I achieve this?

Thanks in prior :)

答: So I found out it differs from operation system. I've written out what I've found on my website, so check it out if you want to create a mac application.</p>

Title: c++ hide terminal with GTKMM gui apps

ContentLicense: CC BY-SA 4.0


问:
Exception in property when setting a binary value
I have the following method which gives me a stackoverflow exception on setting a value. I can't step into it and debug it application just crashes few seconds later. Here is the code

```<code>public byte[] ImageTIFF
{
    get
    {
        try
        {
            string filePath = ImageTIFFDir + ImageId + ".TIFF";

            if (File.Exists(filePath))
            {
                return File.ReadAllBytes(ImageTIFFDir + ImageCollectionId + ".TIFF");
            }
            else
            {
                return null;
            }
        }
        catch (Exception e)
        {
            Logger.log("Can't read TIFF image from file.", e);
            throw;
        }
    }
    set
    {
        try
        {
            ImageTIFF = value;
        }
        catch (Exception e)
        {
            Logger.log("Can't set image TIFF.", e);
            throw;
        }

    }
}
</code>```

This gets called during an export and it fails on a first call:

```<code>someImage.ImageTIFF = File.ReadAllBytes(imageName);
</code>```

答:
Change the code to

```<code>private byte[] m_ImageTIFF;
public byte[] ImageTIFF
{
  get{...}
  set { m_ImageTIFF = value;}
}
</code>```

You need a backing store for the property.

Body:
I have the following method which gives me a stackoverflow exception on setting a value. I can't step into it and debug it application just crashes few seconds later. Here is the code

public byte[] ImageTIFF
{
    get
    {
        try
        {
            string filePath = ImageTIFFDir + ImageId + ".TIFF";

            if (File.Exists(filePath))
            {
                return File.ReadAllBytes(ImageTIFFDir + ImageCollectionId + ".TIFF");
            }
            else
            {
                return null;
            }
        }
        catch (Exception e)
        {
            Logger.log("Can't read TIFF image from file.", e);
            throw;
        }
    }
    set
    {
        try
        {
            ImageTIFF = value;
        }
        catch (Exception e)
        {
            Logger.log("Can't set image TIFF.", e);
            throw;
        }

    }
}

This gets called during an export and it fails on a first call:

someImage.ImageTIFF = File.ReadAllBytes(imageName);

Body:
Change the code to

private byte[] m_ImageTIFF;
public byte[] ImageTIFF
{
  get{...}
  set { m_ImageTIFF = value;}
}

You need a backing store for the property.


问:
Calculate the max and the min difference between two adjacent numbers
Having a matrix A like:

```<code>     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]   11   14   17   20   23   26
[2,]   12   15   18   21   24   27
[3,]   13   16   19   22   25   28
</code>```

I want to calculate the max and the min difference between two adjacent numbers in all rows.
And then filter to limit only rows where adjacent numbers min is less between 4 and 7 and max is between 6 an 12
The output should return no row.

For the following matrix:

```<code>     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]   11   16   17   28   23   26
[2,]   12   15   18   21   24   27
[3,]   13   16   19   22   25   28
</code>```

the result should be row 1

Body:
Having a matrix A like:

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]   11   14   17   20   23   26
[2,]   12   15   18   21   24   27
[3,]   13   16   19   22   25   28

I want to calculate the max and the min difference between two adjacent numbers in all rows.
And then filter to limit only rows where adjacent numbers min is less between 4 and 7 and max is between 6 an 12
The output should return no row.

For the following matrix:

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]   11   16   17   28   23   26
[2,]   12   15   18   21   24   27
[3,]   13   16   19   22   25   28

the result should be row 1

Body:
Here is a vectorized approach

library(matrixStats)
m1 <- abs(m[,-ncol(m) ] - m[,-1])
m[rowMins(m1) %in% 4:7 & rowMaxs(m1) %in% 6:12,]
#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]   21   15   22   13   23   17
#[2,]   27   18   13   25   16   11

data

set.seed(2)
m <- matrix(sample(11:28, 54, TRUE), nrow = 9)


问:
Render mongodb documents with varying schema
Has anyone come across an elegant way/library to render Mongodb documents with varying schema ?
I am basically using NodeJS+Express+EJS and would like to display a number of documents. The document schema is not fixed so solutions like Datatables would have been ideal but requires the columns to be fixed. I am trying to see if anyone has come across an innovative way of dealing with this problem in a way thats also visually attractive and user friendly for the end user.
Every document has an _id and _created. So perhaps I render a list of these and once clicked it opens and shows all the other fields which could be different document to document.
Thanks
Tony</p>

答:
What you mentioned at the end is the convention, as far as I know. It's not something you may do but you should. Show the minimum and the most important information of records in a list. User clicks one to get more of its detail in a new page, dialog, or expanded screen. This is what we see in most of the web and mobile apps.

The URLs for pages and Restful APIs also follow this convention resource/, resource/id and api/resource, api/resource/id.

In case the fields are not that many and you absolutely require full info per record in the list, then you can follow some scheme like below. It takes into account variable fields:

```<code>//example mongodb documents
var docs = [{
        _id: "59608c980b526c5e0d72f30f",
        firstName: "Steve",
        lastName: "Smith",
        fullName: "Steve A Smith"

    },
    {
        _id: "59608c980b526c5e0d72f300",
        firstName: "John",
        lastName: "Steward",
        address: "Park Lane",
        email: "j_stwd@gmail.com"

    }];
</code>```

On view (ejs with ? as delimiter)

```<code>    <div class="row">
        <? docs.forEach(function(doc, index) { ?>
          <? for(var key in doc){ ?>
              <?= key !== '_id'? (key + ": " + doc[key]) : "" ?> <br>
          <? } ?>
        <? }) ?>
    </div>
</code>```

You would obviously want to put each record in some card or container and beautify it. Also, maybe split the key names or map them to more human friendly format like First Name instead of firstName.

Body:
What you mentioned at the end is the convention, as far as I know. It's not something you may do but you should. Show the minimum and the most important information of records in a list. User clicks one to get more of its detail in a new page, dialog, or expanded screen. This is what we see in most of the web and mobile apps.

The URLs for pages and Restful APIs also follow this convention resource/, resource/id and api/resource, api/resource/id.

In case the fields are not that many and you absolutely require full info per record in the list, then you can follow some scheme like below. It takes into account variable fields:

//example mongodb documents
var docs = [{
        _id: "59608c980b526c5e0d72f30f",
        firstName: "Steve",
        lastName: "Smith",
        fullName: "Steve A Smith"

    },
    {
        _id: "59608c980b526c5e0d72f300",
        firstName: "John",
        lastName: "Steward",
        address: "Park Lane",
        email: "j_stwd@gmail.com"

    }];

On view (ejs with ? as delimiter)

    <div class="row">
        <? docs.forEach(function(doc, index) { ?>
          <? for(var key in doc){ ?>
              <?= key !== '_id'? (key + ": " + doc[key]) : "" ?> <br>
          <? } ?>
        <? }) ?>
    </div>

You would obviously want to put each record in some card or container and beautify it. Also, maybe split the key names or map them to more human friendly format like First Name instead of firstName.


问:
Sending Bulk Email Async Without violating Limits Spring Boot
I have to send bulk email through java SMTP. Currently I send email synchronously which is taking a lot of time and since every email provider have their per hour limit, so I have to sleep thread to avoid limitation.

What will be the best approach to send email Asynchronously without violating limitation using SMTP.

Thanks in advance.

答:
You should be able to send mails asynchronously running a new thread or using executor service.

But since you need capability to throttle outgoing mails you need a store and forward mechanism. Ideal solution would be using a queue where mesages can be posted. And then there should be a queue consumer which will be responsible for reading from the queue and sending the actual mail.


问:
WPF - Why doesn't Microsoft supply a decent set of most-used controls ?
I've been playing with WPF for some months now, and I quite like it.
But one of the things I don't get is why MS doesn't put a little more effort in helping developers by supplying basic controls, and I need to get this off my chest :)

For example, I figure most applications somewhere will need to let you edit some properties - for configuration or whatever.
What would be the most used types in a proprety-grid editor ?

text

numbers (byte, float/double, int, etc)

colors

....etc.

So why isn't there even something as simple as a control to edit numbers ? Like a generic NumericUpDown control that allows you to type in numbers (no text, no pasting invalid input) or spin them up/down according to some given rules (decimal, floating point, min/maxvalue) ?
Why isn't there a generic colorpicker, so people get the same user-experience in every application ?
Why isn't there a standard implementation of a SearchTextBox, a BreadCrumb-control, or all these other standard control types users have gotten accustomed to the last 10 years ?

(..but at least they DID have the time to implement a generic splashscreen - because everyone knows that greatly increases user-productivity....)

The well-known ideal is always to give people the same user-experience over different applications. So even if some of those controls would be easy to make - it would be preferred to have one version over different applications.

I see people all over the internet trying to do the same stuff over and over again.
Okay, so MS started a WPF Toolkit project on Codeplex that tries to implement some controls, but only did so half-heartedly and is completely dead by now (last update of the roadmap dates back to Mar 21 2009).

The result of this is that a lot of people starting a WPF-project end up spending a lot of time on trying to figure out how to create some generic controls and get really frustrated.

Wasn't the mantra "Developers, developers, developers!" ..?

/Rant

答:
I think Microsoft - and some people responding here - are forgetting about the most important part of this post :

"The well-known ideal is always to give people the same user-experience over different applications. So even if some of those controls would be easy to make - it would be preferred to have one version over different applications"

Just Google Image Search on "WPF Color Picker" ( http://www.google.nl/images?q=wpf+color+picker ) and you'll see this idea go down the drain.


问:
Sorting JSON Array by a double nested value?
I am unable to find a reasonable solution as I am pulling JSON data from firebase and pulling it from node.js into an html file. I want to sort my data via a property called "value" by not sure how to access a sub-sub-value to sort by in JQuery and am wondering if someone could help lead me in the right direction.

```<code>{
    key: "a",
    {
         key: "ab",
         {
               value: 2
         }
         key: "ac",
         {
               value: 0
         }
    }
},
    {
    key: "b",
    {
         key: "bb",
         {
               value: 1
         }
    }
},
</code>```

Output:

```<code>[{ac}, {bb}, {ab}]
</code>```

答:
Mocking up your JSON from the original image:

 var data = {
        key1: {
            "a": { "deliveryshort": "12152017" },
            "b": { "deliveryshort": "10122015" },
            "c": { "deliveryshort": "11302016" },
            "d": { "deliveryshort": "09022014" }
        },
        key2: {
            "a": { "deliveryshort": "10102017" },
            "b": { "deliveryshort": "09102017" }
        },
    };
    function parseDate(dateStr) {
        var month = "" + dateStr[0] + dateStr[1];
        var day = "" + dateStr[2] + dateStr[3];
        var year = "" + dateStr[4] + dateStr[5] + dateStr[6] + dateStr[7];
        var result = new Date(year, month, day);
        return result;
    }
    function sortBy(data, property, converter) {
        var j = new Array();
        for (var item in data) {
            j.push([item, data[item], converter(data[item][property])]);
        }
        j.sort(function (a, b) { return a[2] - b[2] });
        return j;

    }
    function sortData(data) {
        var d = {};
        for (var item in data) {
            var sorted = sortBy(data[item], "deliveryshort", function (a) { return parseDate(a); });
           /*var normalized = new Array();
            for (var i = 0; i < sorted.length; i++) {
                var ni = sorted[i];
                var key = ni[0];
                var obj = ni[1];
                normalized[key] = obj;
            }*/
            d[item] = sorted;
        }

        console.log(d);
        return d;
    }
    sortData(data);```

Body:
I am unable to find a reasonable solution as I am pulling JSON data from firebase and pulling it from node.js into an html file. I want to sort my data via a property called "value" by not sure how to access a sub-sub-value to sort by in JQuery and am wondering if someone could help lead me in the right direction.

{
    key: "a",
    {
         key: "ab",
         {
               value: 2
         }
         key: "ac",
         {
               value: 0
         }
    }
},
    {
    key: "b",
    {
         key: "bb",
         {
               value: 1
         }
    }
},

Output:

[{ac}, {bb}, {ab}]


问:
Echoing a Product of Two Variables in PHP
I have the following code:

```<code>    $sel_referrals1="SELECT SUM(amount) as da_sum FROM topup WHERE user_id IN(SELECT t1.referree
FROM referrals AS t1
LEFT JOIN referrals AS t2 ON t2.referrer = t1.referree
LEFT JOIN referrals AS t3 ON t3.referrer = t2.referree
LEFT JOIN referrals AS t4 ON t4.referrer = t3.referree
LEFT JOIN referrals AS t5 ON t5.referrer = t4.referree
LEFT JOIN referrals AS t6 ON t6.referrer = t5.referree
LEFT JOIN referrals AS t7 ON t7.referrer = t6.referree
LEFT JOIN referrals AS t8 ON t8.referrer = t7.referree
LEFT JOIN referrals AS t9 ON t9.referrer = t8.referree
LEFT JOIN referrals AS t10 ON t10.referrer = t9.referree
LEFT JOIN referrals AS t11 ON t11.referrer = t10.referree
WHERE t1.referrer = '{$_SESSION['user']}')
AND YEAR(date_time) = YEAR(CURRENT_DATE())
AND MONTH(date_time) = MONTH(CURRENT_DATE())";

    $selected1=mysqli_query($conn,$sel_referrals1);
    $sel_level1_array=mysqli_fetch_row($selected1);
    $level1=number_format($sel_level1_array[0],2);
</code>```

$level1 evaluates as 1260.00.I have another variable $rate1 which is set as follows: $rate1=0.02.I need to multiply $level1 with $rate1. But, when code executes the   multiplication of $level1 * $rate1, the result yields 0.02.

My expected result is 25.20. What am I doing wrong?

答: The data type of the $level1 is String in 3 operation (which will be converted into integer with value equal to 1).</p>

Body:
I have the following code:

    $sel_referrals1="SELECT SUM(amount) as da_sum FROM topup WHERE user_id IN(SELECT t1.referree
FROM referrals AS t1
LEFT JOIN referrals AS t2 ON t2.referrer = t1.referree
LEFT JOIN referrals AS t3 ON t3.referrer = t2.referree
LEFT JOIN referrals AS t4 ON t4.referrer = t3.referree
LEFT JOIN referrals AS t5 ON t5.referrer = t4.referree
LEFT JOIN referrals AS t6 ON t6.referrer = t5.referree
LEFT JOIN referrals AS t7 ON t7.referrer = t6.referree
LEFT JOIN referrals AS t8 ON t8.referrer = t7.referree
LEFT JOIN referrals AS t9 ON t9.referrer = t8.referree
LEFT JOIN referrals AS t10 ON t10.referrer = t9.referree
LEFT JOIN referrals AS t11 ON t11.referrer = t10.referree
WHERE t1.referrer = '{$_SESSION['user']}')
AND YEAR(date_time) = YEAR(CURRENT_DATE())
AND MONTH(date_time) = MONTH(CURRENT_DATE())";

    $selected1=mysqli_query($conn,$sel_referrals1);
    $sel_level1_array=mysqli_fetch_row($selected1);
    $level1=number_format($sel_level1_array[0],2);

$level1 evaluates as 1260.00.I have another variable $rate1 which is set as follows: $rate1=0.02.I need to multiply $level1 with $rate1. But, when code executes the   multiplication of $level1 * $rate1, the result yields 0.02.

My expected result is 25.20. What am I doing wrong?


问:
IBM WebSphere User Inactivity Timeout
How do I set a user inactivity timeout in IBM WebSphere (Integrated Solutions Console, 7.0.0.43)?
As long as the user is actively using the WebSphere console, they should be logged in as long as they want, but if they're inactive for a certain period of time, I want them to be prompted to login once more.
Any assistance is much appreciated.</p>

答:
There is a default timeout set for 30 minutes.

Use the official documentation to change the ISC session timeout:

https://www.ibm.com/support/knowledgecenter/SSEQTP_8.5.5/com.ibm.websphere.base.iseries.doc/isc/cons_sessionto.html

Alternatively you can try to edit file manually

Go to DMGR profile.In the profile home directory navigate to the following subdirectory "/config/cells//applications/isclite.ear/deployments/isclite" and open the file "deployment.xml". Modify the value "invalidationTimeout" .

src: http://orebmann.blogspot.com/2014/10/increase-session-timeout-of-websphere.html?m=1

Title: IBM WebSphere User Inactivity Timeout


问:
Parse error in list monad's `do` notation
OK, so here's a weird one.

This works perfectly:

```<code>test = do
  x <- [1..5]
  y <- [1..5]
  [x+y, x-y]
</code>```

But this:

```<code>test = do
  x <- [1..5]
  y <- [1..5]
  [
    x+y,
    x-y
  ]
</code>```

fails miserably. GHC utterly refuses to parse this. No matter how I fidget with it, I can't seem to convince GHC to allow me to spread the list across multiple lines. Which is a problem, because if you replace x+y and x-y with really big expressions, it quickly becomes hard to read...

Does anybody know why isn't this working, and how can I force it to work? (Or at least do something that looks legible?)

答:
If I parse this, I get the following error:

```<code>File.hs:10:3: error:
    parse error (possibly incorrect indentation or mismatched brackets)
</code>```

I think the parsers simply sees the closing square bracket ] as a new statement. And it complains that the previous statement had no closing bracket (and the new one a closing bracket without an opening bracket). If you push it one column to the right, it parses correctly (at least with GHC-8.0.2)

```<code>test = do
  x <- [1..5]
  y <- [1..5]
  [
    x+y,
    x-y
   ] -- one space to the right
</code>```

As long as you do not go back to the previous indentation level (here one space to the left), it should probably be fine. Since the compiler will see it as one do-statement.

Body:
OK, so here's a weird one.

This works perfectly:

test = do
  x <- [1..5]
  y <- [1..5]
  [x+y, x-y]

But this:

test = do
  x <- [1..5]
  y <- [1..5]
  [
    x+y,
    x-y
  ]

fails miserably. GHC utterly refuses to parse this. No matter how I fidget with it, I can't seem to convince GHC to allow me to spread the list across multiple lines. Which is a problem, because if you replace x+y and x-y with really big expressions, it quickly becomes hard to read...

Does anybody know why isn't this working, and how can I force it to work? (Or at least do something that looks legible?)

Body:
If I parse this, I get the following error:

File.hs:10:3: error:
    parse error (possibly incorrect indentation or mismatched brackets)

I think the parsers simply sees the closing square bracket ] as a new statement. And it complains that the previous statement had no closing bracket (and the new one a closing bracket without an opening bracket). If you push it one column to the right, it parses correctly (at least with GHC-8.0.2)

test = do
  x <- [1..5]
  y <- [1..5]
  [
    x+y,
    x-y
   ] -- one space to the right

As long as you do not go back to the previous indentation level (here one space to the left), it should probably be fine. Since the compiler will see it as one do-statement.


问:
Is there !< and !> in JavaScript?
Someone told me that there's !< and !> in JavaScript. I tried it but it didn't work. Is there something like this in JavaScript? If not in JavaScript, is it there in any other language?</p>

答:
No. In JavaScript and many other languages (for numbers - not NaN - and strings):

"!<" is >=

"!>" is <=

Check this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators

Title: Is there !< and !> in JavaScript?


问:
Redirect content of /dev/ttySDIO0 to a file
Is there any way to redirect the content of a tty device (/dev/ttySDIO0) file so that its content can be managed using a file IO operations. I don't prefer to use 'cat' here.

Thank you.

答:
You can use socat which can connect to a tty on one side with a lot of command line options, and the other end can be pretty much anything that accepts read/write or send/receive call. From the above link :

Socat is a command line based utility
  that establishes two bidirectional
  byte streams and transfers data
  between them. Because the streams can
  be constructed from a large set of
  different types of data sinks and
  sources (see address types), and
  because lots of address options may be
  applied to the streams, socat can be
  used for many different purposes.


答:
I guess you declared $level1 with number_format(1260,2) value!
That its echo $level1."
"; gives you 1,260.00!
You should declare it plain number!

Title: Echoing a Product of Two Variables in PHP

Body:
I guess you declared $level1 with number_format(1260,2) value!
That its echo $level1."<br>"; gives you 1,260.00!
You should declare it plain number!


问:
Quadcopter PID in Unity Malfunctioning When Rotated
I'm making a Quadcopter simulator game with Unity (5.6.0f3). My quadcopter has four evenly spaced "rotors" attached to a central body (and legs) with Fixed Joints. It flies (currently only upwards) by applying force to the rotors (rigidbody.AddForce method).
I'm using PID controllers to stabilize the copter, and I've done enough tuning that it stabilizes pretty well when subject to outside forces...

However, when I rotate the copter around the Y-Axis (yaw) and the forward axis of the copter comes near -90 degrees, the stabilization freaks out and pitches the copter up or down dramatically (and for some reason, it alternates between up and down if I keep applying Yaw in the same direction after the copter stabilizes again, and it happens at the same -90 degrees every time).

I can't figure out what's wrong-- the PID controllers I'm using only stabilize Pitch (rotation around the X axis) and Roll (rotation around the Z axis), so changing the Y rotation shouldn't affect anything.

I'm only using the transform.Rotate method to rotate the copter (so there's nothing to do with forces or another PID controller for Yaw).

Has anyone else come across a similar problem when working with a PID controller?

答:
When you rotate an object around one of the axis sometimes the other axes get aligned, causing weird behavior. This is called Gimbal Lock, google it. That's the reason we have Quaternions - they are hard to read and work in mysterious ways, but they never get 'locked'

[Edit] I'm sorry, I'm trying to be as specific as the question allows me to be


问:
PHP can't read my html inside a file
I have a template class that I can echo out files through it.
I give the address of my file to template class and echo it out.
I have 4 files named: index, topic, topics, register and all of them are doing perfect but topic.php is empty.here is my code for example for the register inside a register controller file.what should I do? thank you.</p>

```<code><?php
$template = new template('templates/register.php');//include the template
//display template
echo $template;
</code>```

答:
Try

```<code><?php
    $template = file_get_contents('templates/register.php'); //include the template
    //display template
    echo $template;
</code>```

If you want to use the code for some other purpose like for including its content you should instead use include('file_url');

Refer http://uk3.php.net/manual/en/function.include.php

Let me know if it doesn't work

Title: PHP can't read my html inside a file

Body:
I have a template class that I can echo out files through it.
I give the address of my file to template class and echo it out.
I have 4 files named: index, topic, topics, register and all of them are doing perfect but topic.php is empty.here is my code for example for the register inside a register controller file.what should I do? thank you.

<?php
$template = new template('templates/register.php');//include the template
//display template
echo $template;

Body:
Try

<?php
    $template = file_get_contents('templates/register.php'); //include the template
    //display template
    echo $template;

If you want to use the code for some other purpose like for including its content you should instead use include('file_url');

Refer http://uk3.php.net/manual/en/function.include.php

Let me know if it doesn't work


问:
Lua - why is string after function call allowed?
I'm trying to implement a simple C++ function, which checks a syntax of Lua script. For that I'm using Lua's compiler function luaL_loadbufferx() and checking its return value afterwards.

Recently, I have ran into a problem, because the code, that I thought should be marked invalid, was not detected and instead the script failed later at a runtime (eg. in lua_pcall()).

Example Lua code (can be tested on official Lua demo):

```<code>function myfunc()
   return "everyone"
end

-- Examples of unexpected behaviour:
-- The following lines pass the compile time check without errors.
print("Hello " .. myfunc() "!") -- Runtime error: attempt to call a string value
print("Hello " .. myfunc() {1,2,3}) -- Runtime error: attempt to call a string value

-- Other examples:
-- The following lines contain examples of invalid syntax, which IS detected by compiler.
print("Hello " myfunc() .. "!") -- Compile error: ')' expected near 'myfunc'
print("Hello " .. myfunc() 5) -- Compile error: ')' expected near '5'
print("Hello " .. myfunc() .. ) -- Compile error: unexpected symbol near ')'
</code>```

The goal is obviously to catch all syntax errors at compile time. So my questions are:

What exactly is meant by calling a string value?

Why is this syntax allowed in the first place? Is it some Lua feature I'm unaware of, or the luaL_loadbufferx() is faulty in this particular example?

Is it possible to detect such errors by any other method without running it? Unfortunately, my function doesn't have access to global variables at compile time, so I can't just just run the code directly via lua_pcall().

Note: I'm using Lua version 5.3.4 (manual here).

Thank you very much for your help.

答:
Another approach is to change string's metatable making a call to a string valid.

```<code>local mt = getmetatable ""
mt.__call = function (self, args) return self .. args end
print(("x") "y") -- outputs `xy`
</code>```

Now those valid syntax calls to a string will result in string concatenation instead of runtime errors.

Body:
I'm trying to implement a simple C++ function, which checks a syntax of Lua script. For that I'm using Lua's compiler function luaL_loadbufferx() and checking its return value afterwards.

Recently, I have ran into a problem, because the code, that I thought should be marked invalid, was not detected and instead the script failed later at a runtime (eg. in lua_pcall()).

Example Lua code (can be tested on official Lua demo):

function myfunc()
   return "everyone"
end

-- Examples of unexpected behaviour:
-- The following lines pass the compile time check without errors.
print("Hello " .. myfunc() "!") -- Runtime error: attempt to call a string value
print("Hello " .. myfunc() {1,2,3}) -- Runtime error: attempt to call a string value

-- Other examples:
-- The following lines contain examples of invalid syntax, which IS detected by compiler.
print("Hello " myfunc() .. "!") -- Compile error: ')' expected near 'myfunc'
print("Hello " .. myfunc() 5) -- Compile error: ')' expected near '5'
print("Hello " .. myfunc() .. ) -- Compile error: unexpected symbol near ')'

The goal is obviously to catch all syntax errors at compile time. So my questions are:

What exactly is meant by calling a string value?

Why is this syntax allowed in the first place? Is it some Lua feature I'm unaware of, or the luaL_loadbufferx() is faulty in this particular example?

Is it possible to detect such errors by any other method without running it? Unfortunately, my function doesn't have access to global variables at compile time, so I can't just just run the code directly via lua_pcall().

Note: I'm using Lua version 5.3.4 (manual here).

Thank you very much for your help.

Body:
Another approach is to change string's metatable making a call to a string valid.

local mt = getmetatable ""
mt.__call = function (self, args) return self .. args end
print(("x") "y") -- outputs `xy`

Now those valid syntax calls to a string will result in string concatenation instead of runtime errors.


问:
How to crop image based on binary mask
I am using torch with some semantic segmentation algorithms to produce a binary mask of the segmented images. I would then like to crop the images based on that mask. To be clear I need to crop it on a per pixel basis. It seems like a simple problem but the only solution I can conjure up is to either invert a draw mask function like in the Coco API, or iterate over each pixel in the array and mask together setting the pixel to black if not needed. I feel like there is a better way of doing this. Libraries in Lua, Python, Go, or C++ will work for me. Any ideas?

答:
Use OpenCV .copyTo with the mask option

http://docs.opencv.org/2.4/modules/core/doc/basic_structures.html#mat-copyto

Title: How to crop image based on binary mask


问:
APK not install when run the App after updation on Existing App
I have already Published App in Play Store. Now I add few things and want to upload it with new color and options but when I click on Run in Android Studio the "error message shown" as attached in img url here. I update my previous VersionCode from '1' to '2' and VersionName from '2.0' to '3.0'. But still not install apk in my Debug Device to check before published.
Where I missing and what exactly this error msg tell. Please help to solve this error. No Coding error in Android Studio found.

http://imgur.com/iPbU19Q

答: This error occur when you want to launch app that already install on device .In some device android studio unable to uninstall and relaunch the app so first uninstall app from device then try to launch. Or in some device like xiaomi when you try to launch app from android studio, a prompt show on device to allow installation when you not allow then it show that error.</p>


问:
RegEx for the

 tags
i am working on the C# WinForm application. In that application, i have snippet like this:

```<code><ul>
<li>abc
<li>bbc
<li>xyz
<li>pqr </li></li></li></li>
</ul>
</code>```

but, i want to get output like..

```<code><ul>
<li>abc</li>
<li>bbc</li>
<li>xyz</li>
<li>pqr</li>
</ul>
</code>```

Is there any method using which this thing can be done?

Can anybody suggest me any RegEx for this problem?

Thanks. Regards.

答:
This works on your specific example, but may well break on other input (for example, if
 tags were to span linebreaks), so if it's not producing the desired results, please edit your question with more details.

```<code>cleanString = Regex.Replace(subjectString, "(?:</li>)+", "", RegexOptions.IgnoreCase);
resultString = Regex.Replace(cleanString, "<li>(.*)", "<li>$1</li>", RegexOptions.IgnoreCase);
</code>```

Title:
RegEx for the

 tags

Body:
i am working on the C# WinForm application. In that application, i have snippet like this:

abc

bbc

xyz

pqr

but, i want to get output like..

abc

bbc

xyz

pqr

Is there any method using which this thing can be done?

Can anybody suggest me any RegEx for this problem?

Thanks. Regards.

Body:
This works on your specific example, but may well break on other input (for example, if <li> tags were to span linebreaks), so if it's not producing the desired results, please edit your question with more details.

cleanString = Regex.Replace(subjectString, "(?:</li>)+", "", RegexOptions.IgnoreCase);
resultString = Regex.Replace(cleanString, "<li>(.*)", "<li>$1</li>", RegexOptions.IgnoreCase);


问:
How in iOS to localize text of the month in UIDatePicker, and if it is possible at all?
I make search and up to now I see that UIDatePicker is working with localization of the device.

I have app which has internal lozalization. I need to change month's text dependantly of my internal localization. As I read it appears that this is not possible - I have to make my own custom picker.

Is there a way to achieve that without custom Dat picker?

答:
Swift 3.0 and New

This code will locale picker to Chinese.
Here datePicker is object of UIDatePicker.

```<code>datePicker.locale = Locale.init(localeIdentifier: "zh-Hans")
</code>```

Use "en" instead of "zh-Hans" for English .

Use "az-Arab" instead of "zh-Hans" for Arabic.

Use "uz-Latn" instead of "zh-Hans" for Latin.

for more : click here

Body:
Swift 3.0 and New

This code will locale picker to Chinese.
Here datePicker is object of UIDatePicker.

datePicker.locale = Locale.init(localeIdentifier: "zh-Hans")

Use "en" instead of "zh-Hans" for English .

Use "az-Arab" instead of "zh-Hans" for Arabic.

Use "uz-Latn" instead of "zh-Hans" for Latin.

for more : click here


问:
ienumerable , looping in mvc
I'm creating a page with multiple file uploader in MVC.

What I want to achieve is when I submit values the images uploaded should be named as guid and an incrementing i value, like guid0 , guid1, guid2. I tried for loop but its saving only one image until loop ends . i++ isn't working though.

My controller looks like this:

```<code>public ActionResult Home(SomeClass someclass, IEnumerable<HttpPostedFileBase> files)
    {
        var guid = Guid.NewGuid().ToString();
        someclass.filename = guid;
        int i = 0;
        foreach (var file in files)
        {
            if (file.ContentLength > 0)
             {
                var fileName = guid + "" + i + ".jpg";
                var path = Path.Combine(Server.MapPath("~/Content/admin/Upload"), fileName);
                file.SaveAs(path);
                i++;
             }
         }
         db.someclasses.Add(someclass);
         db.SaveChanges();
         return RedirectToAction("Preview");
      }
</code>```

And my view looks like this

```<code><input type="file" name="files" id=1>
<input type="file" name="files" id=2>
</code>```

Update : I'm receiving 11 files at the if loop but once they go through the loop there is only single image in the images folder named fdea36c3-545a-4e08-8af4-7fa6bd88bc6b0 . what i'm trying to achieve is all 11 images named as fdea36c3-545a-4e08-8af4-7fa6bd88bc6b0, fdea36c3-545a-4e08-8af4-7fa6bd88bc6b1,fdea36c3-545a-4e08-8af4-7fa6bd88bc6b2.....so on .

答:
Well, I am not very familiar with HTML inputs, but I think you should use "multiple" attribute in you SINGLE file input tag.
Or rename "files" to "files[]".
Look at this</p>

Title: ienumerable , looping in mvc

Body:
I'm creating a page with multiple file uploader in MVC.

What I want to achieve is when I submit values the images uploaded should be named as guid and an incrementing i value, like guid0 , guid1, guid2. I tried for loop but its saving only one image until loop ends . i++ isn't working though.

My controller looks like this:

public ActionResult Home(SomeClass someclass, IEnumerable<HttpPostedFileBase> files)
    {
        var guid = Guid.NewGuid().ToString();
        someclass.filename = guid;
        int i = 0;
        foreach (var file in files)
        {
            if (file.ContentLength > 0)
             {
                var fileName = guid + "" + i + ".jpg";
                var path = Path.Combine(Server.MapPath("~/Content/admin/Upload"), fileName);
                file.SaveAs(path);
                i++;
             }
         }
         db.someclasses.Add(someclass);
         db.SaveChanges();
         return RedirectToAction("Preview");
      }

And my view looks like this

<input type="file" name="files" id=1>
<input type="file" name="files" id=2>

Update : I'm receiving 11 files at the if loop but once they go through the loop there is only single image in the images folder named fdea36c3-545a-4e08-8af4-7fa6bd88bc6b0 . what i'm trying to achieve is all 11 images named as fdea36c3-545a-4e08-8af4-7fa6bd88bc6b0, fdea36c3-545a-4e08-8af4-7fa6bd88bc6b1,fdea36c3-545a-4e08-8af4-7fa6bd88bc6b2.....so on .


问:
Problems with e-mail validation Regex on Ruby
I've just started to learn how to use Regex and I'm trying to create a regex to validate an e-mail adress in Ruby. This is what I got so far:

```<code>emailregex = /([a-zA-Z]+([_\-.][a-zA-Z]*)*@\D+[.]\D+)/
str = "abc_def@hotmail.com"
puts str.scan emailregex
</code>```

Expected Output:

```<code>abc_def@hotmail.com
</code>```

Actual Output:

```<code>abc_def@hotmail.com
_def
</code>```

I've seen a few e-mail regex validations, but I want to know what is wrong with my regex. Thanks in advice.

答:
scan will output only the capture groups if at least 1 capture group (...) is in the regex.

That regex has 2 capture groups, and _def is the last occurence of the inner capture group.

You could make the inner a non-capturing group (?:...) to avoid that.

For example:

```<code>str = "emails : abc_def@hotmail.com x_y_z@hotmail.com"
emailregex = /([a-zA-Z]+(?:[_.-][a-zA-Z]*)*@\S+[.]\S+)/
puts str.scan emailregex
</code>```

Outputs:

```<code>abc_def@hotmail.com
x_y_z@hotmail.com
</code>```

Btw, scan can be usefull to get an array of matches from a text based on a pattern.

But to actually validate a string against a pattern? There's another way.

Example:

```<code>emailregex = /^[a-z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i

puts ("Papa.Smurf@smurfs.town" =~ emailregex ? true : false)

puts ("Joda.says:email.is.not" =~ emailregex ? true : false)
</code>```

Body:
I've just started to learn how to use Regex and I'm trying to create a regex to validate an e-mail adress in Ruby. This is what I got so far:

emailregex = /([a-zA-Z]+([_\-.][a-zA-Z]*)*@\D+[.]\D+)/
str = "abc_def@hotmail.com"
puts str.scan emailregex

Expected Output:

abc_def@hotmail.com

Actual Output:

abc_def@hotmail.com
_def

I've seen a few e-mail regex validations, but I want to know what is wrong with my regex. Thanks in advice.

Body:
scan will output only the capture groups if at least 1 capture group (...) is in the regex.

That regex has 2 capture groups, and _def is the last occurence of the inner capture group.

You could make the inner a non-capturing group (?:...) to avoid that.

For example:

str = "emails : abc_def@hotmail.com x_y_z@hotmail.com"
emailregex = /([a-zA-Z]+(?:[_.-][a-zA-Z]*)*@\S+[.]\S+)/
puts str.scan emailregex

Outputs:

abc_def@hotmail.com
x_y_z@hotmail.com

Btw, scan can be usefull to get an array of matches from a text based on a pattern.

But to actually validate a string against a pattern? There's another way.

Example:

emailregex = /^[a-z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i

puts ("Papa.Smurf@smurfs.town" =~ emailregex ? true : false)

puts ("Joda.says:email.is.not" =~ emailregex ? true : false)


问:
search php multidimensional associative array using key value pair with sql like '%LIKE%' construct
I have this PHP function that works well at searching a multidimensional associative array using a key value pair. I would now like to extend it to search for an array where the key value pair has an SQL-like construct similar to this: name = '%john%'.

```<code>function search($array, $key, $value)
{
    $results = array();
    like_search_r($array, $key, $value, $results);
    return $results[0];
}

function like_search_r($array, $key, $value, &$results)
{
    if (!is_array($array)) {
        return;
    }

    if (isset($array[$key]) && $array[$key] == $value) {
        $results[] = $array;
    }

    foreach ($array as $subarray) {
        like_search_r($subarray, $key, $value, $results);
    }
}
</code>```

I found a good example here filter values from an array similar to SQL LIKE '%search%' using PHP but it only searches a one-dimensional array. The key in this example is preg_grep but I have not figured how to use it in a multidimensional associative array. Any help is appreciated.

EDITED: I would love to be able to pass an array of key values pairs to do one sql like filter. The original requirements remain the same. Filter must support something similar to sql '%like%', no input is required, return the root array when a combination of matches are met. If a key/value pair does not match ignore and move on to the next key/value pair. My input array looks like this:

```<code>     array('FIRST_NAME'=>'ma','MIDDLE_NAME'=>'bill',
     'LAST_NAME'=>'jo','ALIASES'=>'phil',
     'DOB'=>'2017-07-05','COUNTRY_OF_BIRTH'=>'Jamaica',
     'Countries1'=>array(array('COUNTRY_CODE'=>'JM'),array('COUNTRY_CODE'=>'AL')),
     'Countries2'=>array(array('COUNTRY_CODE'=>'JM'),array('COUNTRY_CODE'=>'AL')));
</code>```

A sample array to be filtered can be found here: https://www.tehplayground.com/dIMKbb6Tcw5YU38R

答:
I think the way to go is with preg_match():

```<code>function match($search, $subject)
{
    $search = str_replace('/', '\\/', $search);

    return preg_match("/$search/i", (string)$subject);
}

function like_search_r($array, $key, $value, array &$results = [])
{
    if (!is_array($array)) {
        return;
    }

    $key   = (string)$key;
    $value = (string)$value;

    foreach ($array as $arrayKey => $arrayValue) {
        if (match($key, $arrayKey) && match($value, $arrayValue)) {
            // add array if we have a match
            $results[] = $array;
        }

        if (is_array($arrayValue)) {
            // only do recursion on arrays
            like_search_r($arrayValue, $key, $value, $results);
        }
    }
}

$array1 = [
    'foo'    => 'bar',
    'subarr' => [
        'test'                 => 'val',
        'dangerous/characters' => 1,
    ],
];

$results1 = [];
like_search_r($array1, 'fo', 'bar', $results1);
print_r($results1);

/*
Array
(
    [0] => Array
        (
            [foo] => bar
            [subarr] => Array
                (
                    [test] => val
                    [dangerous/characters] => 1
                )

        )

)
*/

$results2 = [];
like_search_r($array1, 'est', 'val', $results2);
print_r($results2);

/*
Array
(
    [0] => Array
        (
            [test] => val
            [dangerous/characters] => 1
        )

)
*/

$results3 = [];
like_search_r($array1, 's/c', 1, $results3);
print_r($results3);

/*
Array
(
    [0] => Array
        (
            [test] => val
            [dangerous/characters] => 1
        )

)
*/
</code>```

Adjusted after your comment:

```<code>function match($search, $subject) { /* no change */ }

function like_search_r($array, $key, $value, array &$results = [], $level = 0)
{
    if (!is_array($array)) {
        return false;
    }

    $key   = (string)$key;
    $value = (string)$value;

    $found = false;

    foreach ($array as $arrayKey => $arrayValue) {
        if (match($key, $arrayKey) && match($value, $arrayValue)) {
            return true;
        }

        if (is_array($arrayValue)) {
            // only do recursion on arrays
            // results are only added on top level
            if (like_search_r($arrayValue, $key, $value, $results, $level+1)) {
                if ($level == 1) {
                    $results[] = $array;
                }
                $found = true;
            }
        }
    }

    return $found;
}

$array2   = [['id' => 0, 'values' => ['name' => 'bill']], ['id' => 1, 'values' => ['name' => 'john']]];
$results4 = [];
like_search_r($array2, 'name', 'john', $results4);
print_r($results4);

/*
Array
(
    [0] => Array
        (
            [id] => 1
            [values] => Array
                (
                    [name] => john
                )

        )

)
*/
</code>```

Body:
I have this PHP function that works well at searching a multidimensional associative array using a key value pair. I would now like to extend it to search for an array where the key value pair has an SQL-like construct similar to this: name = '%john%'.

function search($array, $key, $value)
{
    $results = array();
    like_search_r($array, $key, $value, $results);
    return $results[0];
}

function like_search_r($array, $key, $value, &$results)
{
    if (!is_array($array)) {
        return;
    }

    if (isset($array[$key]) && $array[$key] == $value) {
        $results[] = $array;
    }

    foreach ($array as $subarray) {
        like_search_r($subarray, $key, $value, $results);
    }
}

I found a good example here filter values from an array similar to SQL LIKE '%search%' using PHP but it only searches a one-dimensional array. The key in this example is preg_grep but I have not figured how to use it in a multidimensional associative array. Any help is appreciated.

EDITED: I would love to be able to pass an array of key values pairs to do one sql like filter. The original requirements remain the same. Filter must support something similar to sql '%like%', no input is required, return the root array when a combination of matches are met. If a key/value pair does not match ignore and move on to the next key/value pair. My input array looks like this:

     array('FIRST_NAME'=>'ma','MIDDLE_NAME'=>'bill',
     'LAST_NAME'=>'jo','ALIASES'=>'phil',
     'DOB'=>'2017-07-05','COUNTRY_OF_BIRTH'=>'Jamaica',
     'Countries1'=>array(array('COUNTRY_CODE'=>'JM'),array('COUNTRY_CODE'=>'AL')),
     'Countries2'=>array(array('COUNTRY_CODE'=>'JM'),array('COUNTRY_CODE'=>'AL')));

A sample array to be filtered can be found here: https://www.tehplayground.com/dIMKbb6Tcw5YU38R

Body:
I think the way to go is with preg_match():

function match($search, $subject)
{
    $search = str_replace('/', '\\/', $search);

    return preg_match("/$search/i", (string)$subject);
}

function like_search_r($array, $key, $value, array &$results = [])
{
    if (!is_array($array)) {
        return;
    }

    $key   = (string)$key;
    $value = (string)$value;

    foreach ($array as $arrayKey => $arrayValue) {
        if (match($key, $arrayKey) && match($value, $arrayValue)) {
            // add array if we have a match
            $results[] = $array;
        }

        if (is_array($arrayValue)) {
            // only do recursion on arrays
            like_search_r($arrayValue, $key, $value, $results);
        }
    }
}

$array1 = [
    'foo'    => 'bar',
    'subarr' => [
        'test'                 => 'val',
        'dangerous/characters' => 1,
    ],
];

$results1 = [];
like_search_r($array1, 'fo', 'bar', $results1);
print_r($results1);

/*
Array
(
    [0] => Array
        (
            [foo] => bar
            [subarr] => Array
                (
                    [test] => val
                    [dangerous/characters] => 1
                )

        )

)
*/

$results2 = [];
like_search_r($array1, 'est', 'val', $results2);
print_r($results2);

/*
Array
(
    [0] => Array
        (
            [test] => val
            [dangerous/characters] => 1
        )

)
*/

$results3 = [];
like_search_r($array1, 's/c', 1, $results3);
print_r($results3);

/*
Array
(
    [0] => Array
        (
            [test] => val
            [dangerous/characters] => 1
        )

)
*/

Adjusted after your comment:

function match($search, $subject) { /* no change */ }

function like_search_r($array, $key, $value, array &$results = [], $level = 0)
{
    if (!is_array($array)) {
        return false;
    }

    $key   = (string)$key;
    $value = (string)$value;

    $found = false;

    foreach ($array as $arrayKey => $arrayValue) {
        if (match($key, $arrayKey) && match($value, $arrayValue)) {
            return true;
        }

        if (is_array($arrayValue)) {
            // only do recursion on arrays
            // results are only added on top level
            if (like_search_r($arrayValue, $key, $value, $results, $level+1)) {
                if ($level == 1) {
                    $results[] = $array;
                }
                $found = true;
            }
        }
    }

    return $found;
}

$array2   = [['id' => 0, 'values' => ['name' => 'bill']], ['id' => 1, 'values' => ['name' => 'john']]];
$results4 = [];
like_search_r($array2, 'name', 'john', $results4);
print_r($results4);

/*
Array
(
    [0] => Array
        (
            [id] => 1
            [values] => Array
                (
                    [name] => john
                )

        )

)
*/


问:
@Autowire field has Null Pointer Exception ['new' keyword not used]
I had already tried solutions mentioned in  Why is my Spring @Autowired field null? yet the problem persists. I have tried annotating the class DevicePojo(code below) with @Configurable @Service.

Here are my beans
DistributionConfig.java

```<code>@Component
@Configuration
public class DistributionConfig {

    @Qualifier("exponentialDistribution")
    @Bean
    @Scope("prototype")
    public DistributionService exponentialDistribution() {
        return new ExponentiallyDistribute();
    }

    @Qualifier("normalDistribution")
    @Bean
    @Scope("prototype")
    public DistributionService normalDistribution() {
        return new NormallyDistribute();
    }

    @Qualifier("uniformDistribution")
    @Bean
    @Scope("prototype")
    public DistributionService uniformDistribution() {
        return new UniformlyDistribute();
    }
}
</code>```

JsonFileConfig.java

```<code>@Configuration
public class JsonFileConfig {

    private static ObjectMapper mapper=new ObjectMapper();

    @Qualifier("devicesPojo")
    @Bean
    public DevicesPojo[] devicesPojo() throws Exception {
        DevicesPojo[] devicePojo=mapper.readValue(new File(getClass().getClassLoader().getResource("Topo/esnet-devices.json").getFile()),DevicesPojo[].class);
        return devicePojo;
    }

    @Qualifier("linksPojo")
    @Bean
    public LinksPojo[] linksPojo() throws Exception {
        LinksPojo[] linksPojo=mapper.readValue(new File(getClass().getClassLoader().getResource("Topo/esnet-adjcies.json").getFile()),LinksPojo[].class);
        return linksPojo;
    }
}
</code>```

Here is my DevicePojo where i get the null pointer exception.

```<code>@JsonDeserialize(using = DeviceDeserializer.class)
@Component
public class DevicesPojo {

    private String device;
    private List<String> ports;
    private List<Integer> bandwidth;

    @Autowired
    @Qualifier("uniformDistribution")
    private DistributionService uniformDistribution; // Here uniformDistribution is null

    public DevicesPojo(String device, List<String> port, List<Integer> bandwidth) {
        this.device = device;
        this.ports= port;
        this.bandwidth=bandwidth;
        this.uniformDistribution.createUniformDistribution(1000,0,ports.size());
    }

    public String getDevice(){
        return device;
    }

    public String getRandomPortForDevice()
    {
       return ports.get((int)uniformDistribution.getSample());
    }

    public List<String> getAllPorts(){
       return ports;
    }

    public int getBandwidthForPort(String port){
       return bandwidth.get(ports.indexOf(port));
    }
}
</code>```

However, if i replace private DistributionService uniformDistribution;with private DistributionService uniformDistribution=new UniformDistribution() the code is working fine.

答:
There is a mix of problems here.

1. You create your DevicesPojo objects using JSON deserializer. Spring has no chance to interfere and inject the DistributionService.

2. Even if it could interfere, it would fail, since you are trying to use the 'distributionService' object in the constructor. Field injection would work only after an object is constructed.

Now regarding fixing the problems.

Long answer short - don't expect auto-injection in your POJOs.

Normally, dependencies like 'distributionService' in objects that are created on the fly, like your DevicesPojo are avoided altogether.

If you insist on having them, inject them manually at construction time:

```<code>class DevicesPojoFactory {
    @Autowired @Qualifier("uniformDistribution")
    private DistributionService uniformDistribution;
    ObjectMapper mapper = new ObjectMapper();

    DevicesPojo[] readFromFile(String path) {
         DevicesPojo[] devicePojoArr = mapper.readValue(...);
         for (DevicesPojo dp: devicePojoArr) {
              dp.setDistribution(uniformDistribution);
         }
    }
}
</code>```

Body:
I had already tried solutions mentioned in  Why is my Spring @Autowired field null? yet the problem persists. I have tried annotating the class DevicePojo(code below) with @Configurable @Service.

Here are my beans
DistributionConfig.java

@Component
@Configuration
public class DistributionConfig {

    @Qualifier("exponentialDistribution")
    @Bean
    @Scope("prototype")
    public DistributionService exponentialDistribution() {
        return new ExponentiallyDistribute();
    }

    @Qualifier("normalDistribution")
    @Bean
    @Scope("prototype")
    public DistributionService normalDistribution() {
        return new NormallyDistribute();
    }

    @Qualifier("uniformDistribution")
    @Bean
    @Scope("prototype")
    public DistributionService uniformDistribution() {
        return new UniformlyDistribute();
    }
}

JsonFileConfig.java

@Configuration
public class JsonFileConfig {

    private static ObjectMapper mapper=new ObjectMapper();

    @Qualifier("devicesPojo")
    @Bean
    public DevicesPojo[] devicesPojo() throws Exception {
        DevicesPojo[] devicePojo=mapper.readValue(new File(getClass().getClassLoader().getResource("Topo/esnet-devices.json").getFile()),DevicesPojo[].class);
        return devicePojo;
    }

    @Qualifier("linksPojo")
    @Bean
    public LinksPojo[] linksPojo() throws Exception {
        LinksPojo[] linksPojo=mapper.readValue(new File(getClass().getClassLoader().getResource("Topo/esnet-adjcies.json").getFile()),LinksPojo[].class);
        return linksPojo;
    }
}

Here is my DevicePojo where i get the null pointer exception.

@JsonDeserialize(using = DeviceDeserializer.class)
@Component
public class DevicesPojo {

    private String device;
    private List<String> ports;
    private List<Integer> bandwidth;

    @Autowired
    @Qualifier("uniformDistribution")
    private DistributionService uniformDistribution; // Here uniformDistribution is null

    public DevicesPojo(String device, List<String> port, List<Integer> bandwidth) {
        this.device = device;
        this.ports= port;
        this.bandwidth=bandwidth;
        this.uniformDistribution.createUniformDistribution(1000,0,ports.size());
    }

    public String getDevice(){
        return device;
    }

    public String getRandomPortForDevice()
    {
       return ports.get((int)uniformDistribution.getSample());
    }

    public List<String> getAllPorts(){
       return ports;
    }

    public int getBandwidthForPort(String port){
       return bandwidth.get(ports.indexOf(port));
    }
}

However, if i replace private DistributionService uniformDistribution;with private DistributionService uniformDistribution=new UniformDistribution() the code is working fine.

Body:
There is a mix of problems here.

1. You create your DevicesPojo objects using JSON deserializer. Spring has no chance to interfere and inject the DistributionService.

2. Even if it could interfere, it would fail, since you are trying to use the 'distributionService' object in the constructor. Field injection would work only after an object is constructed.

Now regarding fixing the problems.

Long answer short - don't expect auto-injection in your POJOs.

Normally, dependencies like 'distributionService' in objects that are created on the fly, like your DevicesPojo are avoided altogether.

If you insist on having them, inject them manually at construction time:

class DevicesPojoFactory {
    @Autowired @Qualifier("uniformDistribution")
    private DistributionService uniformDistribution;
    ObjectMapper mapper = new ObjectMapper();

    DevicesPojo[] readFromFile(String path) {
         DevicesPojo[] devicePojoArr = mapper.readValue(...);
         for (DevicesPojo dp: devicePojoArr) {
              dp.setDistribution(uniformDistribution);
         }
    }
}