问:
The below SQL query takes around 6-7 min to execute and it will return ~ 5,833,135 rows, can any help me resolve it performance
The below SQL query takes around 6-7 min to execute and it will return ~ 5,833,135 rows, can any help me resolve it performance

SQL

```<code>select
    min(aml.id) as id,
    aml.name as name,
    round(sum(aml.debit),2) as debit,
    round(sum(aml.credit),2) as credit,
    round(sum(aml.balance),2) as balance,
    aml.account_id as account_id,
    aml.move_id as move_id,
    aml.payment_id as payment_id,
    aml.statement_id as statement_id,
    aml.journal_id as journal_id,
    aml.date as date,
    aml.company_id as company_id,
    aml.invoice_id as invoice_id,
    aml.partner_id as partner_id,
    aml.company_currency_id as company_currency_id
from
    account_move_line aml
    left join account_account acc on (acc.id = aml.account_id)
    left join account_move am on (am.id = aml.move_id)
    left join account_payment ap on (ap.id = aml.payment_id)
    left join account_bank_statement abs on (abs.id = aml.statement_id)
    left join account_journal aj on (aj.id = aml.journal_id)
    left join res_company comp on (comp.id = aml.company_id)
    left join account_invoice ai on (ai.id = aml.invoice_id)
    left join res_partner resp on (resp.id = aml.partner_id)
    left join res_currency rc on (rc.id = aml.company_currency_id)
group by
    aml.name,
    aml.debit,
    aml.credit,
    aml.balance,
    aml.account_id,
    aml.move_id,
    aml.payment_id,
    aml.statement_id,
    aml.journal_id,
    aml.date,
    aml.company_id,
    aml.invoice_id,
    aml.partner_id,
    aml.company_currency_id
</code>```

答:
There is not much you can optimize with such a query.

In the order of effectivity:

Put enough RAM in the machine that the whole database is cached.

Set work_mem as big as you can for this query.

If there are nested loop joins in the EXPLAIN output (unlikely), an index on the join column can help.

Body:
The below SQL query takes around 6-7 min to execute and it will return ~ 5,833,135 rows, can any help me resolve it performance

SQL

select
    min(aml.id) as id,
    aml.name as name,
    round(sum(aml.debit),2) as debit,
    round(sum(aml.credit),2) as credit,
    round(sum(aml.balance),2) as balance,
    aml.account_id as account_id,
    aml.move_id as move_id,
    aml.payment_id as payment_id,
    aml.statement_id as statement_id,
    aml.journal_id as journal_id,
    aml.date as date,
    aml.company_id as company_id,
    aml.invoice_id as invoice_id,
    aml.partner_id as partner_id,
    aml.company_currency_id as company_currency_id
from
    account_move_line aml
    left join account_account acc on (acc.id = aml.account_id)
    left join account_move am on (am.id = aml.move_id)
    left join account_payment ap on (ap.id = aml.payment_id)
    left join account_bank_statement abs on (abs.id = aml.statement_id)
    left join account_journal aj on (aj.id = aml.journal_id)
    left join res_company comp on (comp.id = aml.company_id)
    left join account_invoice ai on (ai.id = aml.invoice_id)
    left join res_partner resp on (resp.id = aml.partner_id)
    left join res_currency rc on (rc.id = aml.company_currency_id)
group by
    aml.name,
    aml.debit,
    aml.credit,
    aml.balance,
    aml.account_id,
    aml.move_id,
    aml.payment_id,
    aml.statement_id,
    aml.journal_id,
    aml.date,
    aml.company_id,
    aml.invoice_id,
    aml.partner_id,
    aml.company_currency_id


来源: stackexchange

问:
Move each div with same class into another div
I got 2 divs with the same class and I am trying to move each of the 2 divs into a different div.

setTimeout(function() {
  $(".pac-container").prependTo("#gp-content");
}, 500);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.pac-container {
  width: 50px;
  height: 100px;
  border: 1px solid black;
  padding: 5px;
  margin: 5px;
}

#wrapper1,
#wrapper2 {
  width: 25px;
  height: 75px;
  border: 1px dotted red;
  padding: 5px;
  margin: 5px;
}</code>```

```
</div>
</div>
</p>

<p>My goal is now to move the first <code>pac-container</code> into <code>#wrapper1</code> and the second <code>pac-container</code> into <code>#wrapper2</code>. The <code>pac-container</code> are sitting next to each other at the html-markup and each <code>#wrapper</code> sits on different positions at the html-markup.</p>

<hr>

<h2>Goal</h2>

```

```

答:
To move an element use detach() and appendTo() Try this:

$(".pac-container").each(function(i){
    $(this).detach().appendTo($(".wrapper").eq(i))
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pac-container">pac-container1</div>
<div class="pac-container">pac-container2</div>

<div class="wrapper">wrapper1</div>
<div class="wrapper">wrapper2</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I got 2 divs with the same class and I am trying to move each of the 2 divs into a different div.

setTimeout(function() {
  $(".pac-container").prependTo("#gp-content");
}, 500);

.pac-container {
  width: 50px;
  height: 100px;
  border: 1px solid black;
  padding: 5px;
  margin: 5px;
}

#wrapper1,
#wrapper2 {
  width: 25px;
  height: 75px;
  border: 1px dotted red;
  padding: 5px;
  margin: 5px;
}

My goal is now to move the first pac-container into #wrapper1 and the second pac-container into #wrapper2. The pac-container are sitting next to each other at the html-markup and each #wrapper sits on different positions at the html-markup.

Goal

Body:
To move an element use detach() and appendTo() Try this:

$(".pac-container").each(function(i){
    $(this).detach().appendTo($(".wrapper").eq(i))
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pac-container">pac-container1</div>
<div class="pac-container">pac-container2</div>

<div class="wrapper">wrapper1</div>
<div class="wrapper">wrapper2</div>


问:
Get specific objects from an Array in react-native
I have a static array something like

[apple, banana, orange, lemon, goa, grapes, berry, mango, black grapes]

with no changes in order(order will be fixed). Based on user selection dynamically i am getting two objects like (orange, mango).

Now i need to fetch objects between these two objects i.e.(lemon,goa,grapes,berry) into a different array. Thank you

答:
You can use slice() method to achieve this,</p>

```<code> var a = ['apple',
             'banana',
             'orange',
             'lemon',
             'goa',
             'grapes',
             'berry',
             'mango',
             'black',
             'grapes']
    var d = a.slice(a.indexOf('orange') + 1, a.indexOf('mango'))
    console.log(d)
</code>```

Body:
You can use slice() method to achieve this,

 var a = ['apple',
             'banana',
             'orange',
             'lemon',
             'goa',
             'grapes',
             'berry',
             'mango',
             'black',
             'grapes']
    var d = a.slice(a.indexOf('orange') + 1, a.indexOf('mango'))
    console.log(d)


问:
signalr: how to update all clients having specific cookie value?
We have an API exposed from where our partner networks can send loan offers and this offer gets saved in our MySQL database. For example, they send offer as:

```<code>/api/loanoffer/
{
  "mobile": "+23498234",
  "offer": "$ 23443"
}
</code>```

We want to show this loan offer immediately to all our connected clients (by matching the mobile number of the offer and connected client).

We save mobile information of the users in client cookies. How can we relay this information from mysql database to all the connected clients? It would be best if we can give solution keeping web, ios and android client in mind.

答:
When you get this information and store it in Cookie, store some ID with it as well like username or mobile number which is unique or MD5 the mobile number. Ideally store that on server with connecton ID. When you get it back then send it to that connection ID. However if you cant store that on server then do this

When you need to send that message out then send that message out to all clients. Pass the MD5 mobile number and on client side if it matches the cookie value of MD5 client mobile number then show notification otherwise stay calm and carry on.

Body:
We have an API exposed from where our partner networks can send loan offers and this offer gets saved in our MySQL database. For example, they send offer as:

/api/loanoffer/
{
  "mobile": "+23498234",
  "offer": "$ 23443"
}

We want to show this loan offer immediately to all our connected clients (by matching the mobile number of the offer and connected client).

We save mobile information of the users in client cookies. How can we relay this information from mysql database to all the connected clients? It would be best if we can give solution keeping web, ios and android client in mind.


问:
Delete Button doesn't work properly any more after "Convert Form's Macros to Visual Basic" was executed
I've created two tables

Languages:

    IDLanguage Language
      1      English
      2      German
      3      French
      4      Polish
      5      Italian

Greetings:

    IDGreeting  Greeting       IDLanguage_FK
      1      Good Morning       1
      2      Guten Morgen       2
      3      Bonjour            3

Both tables are connected by the foreign key IDLanguage_FK with the option Enforce Referential Integrity. So the languages Polish and Italian of the table languages has no counterpart in the table greetings.

I've created a form bounded to the languages table with a list box showing all languages and a delete button. Both object elements were created with the Control Wizard.

If I want to delete the language Polish or Italian there won't be a problem. If I want to delete one of the first three languages, an error message pops up, indicating that the record includes related records in the greetings table. Everything fine so far.

Converting the form's macro to Visual Basic causes now problems with the delete button. After the conversion, it's still possible to delete the two non-related languages. But if I try to delete one of the three related languages, then no error message pops up.

The converted VBA code for the delete button looks like the following:

```<code>Private Sub Button_Delete_Click()

On Error GoTo Button_Delete_Click_Err
On Error Resume Next

DoCmd.GoToControl Screen.PreviousControl.Name
Err.Clear

If (Not Form.NewRecord) Then
    DoCmd.RunCommand acCmdDeleteRecord
End If
If (Form.NewRecord And Not Form.Dirty) Then
    Beep
End If
If (Form.NewRecord And Form.Dirty) Then
    DoCmd.RunCommand acCmdUndo
End If
If (MacroError <> 0) Then
    Beep
    MsgBox MacroError.Description, vbOKOnly, ""
End If

DoCmd.RefreshRecord
    Button_Delete_Click_Exit:
       Exit Sub
    Button_Delete_Click_Err:
       MsgBox Error$
       Resume Button_Delete_Click_Exit
End Sub
</code>```

Has anyone faced the same problem, that the error message won't pop up after conversion. For my purposes it's vital to show the user this error message.

答:
Uh, that generated code is a mess (sorry).

You don't get an error message, because it all runs after On Error Resume Next, which ignores all errors.

I suggest you start simple with this, and add special cases as needed:

Private Sub Button_Delete_Click()

On Error GoTo Button_Delete_Click_Err

    If (Not Form.NewRecord) Then
        DoCmd.RunCommand acCmdDeleteRecord
    End If

Button_Delete_Click_Exit:
   Exit Sub
Button_Delete_Click_Err:
   MsgBox Error$
   Resume Button_Delete_Click_Exit

End Sub
```

Body:
I've created two tables

Languages:

    IDLanguage Language
      1      English
      2      German
      3      French
      4      Polish
      5      Italian

Greetings:

    IDGreeting  Greeting       IDLanguage_FK
      1      Good Morning       1
      2      Guten Morgen       2
      3      Bonjour            3

Both tables are connected by the foreign key IDLanguage_FK with the option Enforce Referential Integrity. So the languages Polish and Italian of the table languages has no counterpart in the table greetings.

I've created a form bounded to the languages table with a list box showing all languages and a delete button. Both object elements were created with the Control Wizard.

If I want to delete the language Polish or Italian there won't be a problem. If I want to delete one of the first three languages, an error message pops up, indicating that the record includes related records in the greetings table. Everything fine so far.

Converting the form's macro to Visual Basic causes now problems with the delete button. After the conversion, it's still possible to delete the two non-related languages. But if I try to delete one of the three related languages, then no error message pops up.

The converted VBA code for the delete button looks like the following:

Private Sub Button_Delete_Click()

On Error GoTo Button_Delete_Click_Err
On Error Resume Next

DoCmd.GoToControl Screen.PreviousControl.Name
Err.Clear

If (Not Form.NewRecord) Then
    DoCmd.RunCommand acCmdDeleteRecord
End If
If (Form.NewRecord And Not Form.Dirty) Then
    Beep
End If
If (Form.NewRecord And Form.Dirty) Then
    DoCmd.RunCommand acCmdUndo
End If
If (MacroError <> 0) Then
    Beep
    MsgBox MacroError.Description, vbOKOnly, ""
End If

DoCmd.RefreshRecord
    Button_Delete_Click_Exit:
       Exit Sub
    Button_Delete_Click_Err:
       MsgBox Error$
       Resume Button_Delete_Click_Exit
End Sub

Has anyone faced the same problem, that the error message won't pop up after conversion. For my purposes it's vital to show the user this error message.


答:
You can extract unique values with query like this

```<code>select
  ID,
  Name,
  (
    select string_agg(c, ',')
    from (
      select
        distinct trim(unnest(string_to_array(Categories, ',')))
    ) t (c)
  ) as Categories
from your_table_name;
</code>```

But it's better to aggregate distinct values while grouping.

Title: Split array, extract only unique values, and then re-merge to array in Postgresql

Body:
I have a dataset which has been grouped using this code:

select
array_to_string(array_agg(DISTINCT "Categories"), ',') as "Categories", "Name", ROW_NUMBER() OVER() as "ID"
from data1
group by "Name"

and it looks like this:

+----+--------+-----------------------------------------+
| ID | Name   | Categories                              |
+----+--------+-----------------------------------------+
| 1  | Class1 | Barry, Steve, Luke, Barry, Barry, Luke  |
+----+--------+-----------------------------------------+
| 2  | Class2 | Luke, Barry, Steve                      |
+----+--------+-----------------------------------------+
| 3  | Class3 | Gerald, Jacqueline, David, Barry, Barry |
+----+--------+-----------------------------------------+

I need to have only the unique values in "Categories". However, in the first row, the database considers Barry, Steve, Luke to be a string, and Barry, Luke to be a string, so using DISTINCT doesn't work to cut out the number of Barrys.

We need to split the string using the comma delimiter, but then re-aggregate it.

The output should look like:

+----+--------+-----------------------------------------+
| ID | Name   | Categories                              |
+----+--------+-----------------------------------------+
| 1  | Class1 | Barry, Steve, Luke                      |
+----+--------+-----------------------------------------+
| 2  | Class2 | Luke, Barry, Steve                      |
+----+--------+-----------------------------------------+
| 3  | Class3 | Gerald, Jacqueline, David, Barry        |
+----+--------+-----------------------------------------+

Body:
You can extract unique values with query like this

select
  ID,
  Name,
  (
    select string_agg(c, ',')
    from (
      select
        distinct trim(unnest(string_to_array(Categories, ',')))
    ) t (c)
  ) as Categories
from your_table_name;

But it's better to aggregate distinct values while grouping.


问:
How can I read input from a file line by line in java?
Ok, I know this is a really rookie question, but I looked around online a lot and am yet unable to find the answer to my question:

How can I read input from a file line by line in java?

Assume a file input that has integers on each line, like:

```<code>1
2
3
4
5
</code>```

Here's the snippet of code I am trying to work with:

```<code>public static void main(File fromFile) {

  BufferedReader reader = new BufferedReader(new FileReader(fromFile));

  int x, y;

  //initialize
  x = Integer.parseInt(reader.readLine().trim());
  y = Integer.parseInt(reader.readLine().trim());

}
</code>```

Presumably, this would read in the first two lines and store them as integers in x and y.  So going off the example, x=1, y=2.

It is finding a problem with this, and I don't know why.

答:
We usually use a while loop, the readLine method tells whether the end of file is reached or not:

```<code> List<String> lines = new ArrayList<String>();
 while ((String line = reader.readLine()) != null)
   lines.add(line);
</code>```

Now we have a collection (a list) that holds all lines from the file as separate strings.

To read the content as Integers, just define a collection of integers and parse while reading:

```<code> List<Integer> lines = new ArrayList<Integer>();
 while ((String line = reader.readLine()) != null) {
   try {
     lines.add(Integer.parseInt(line.trim()));
   } catch (NumberFormatException eaten) {
     // this happens if the content is not parseable (empty line, text, ..)
     // we simply ignore those lines
   }
 }
</code>```

Body:
Ok, I know this is a really rookie question, but I looked around online a lot and am yet unable to find the answer to my question:

How can I read input from a file line by line in java?

Assume a file input that has integers on each line, like:

1
2
3
4
5

Here's the snippet of code I am trying to work with:

public static void main(File fromFile) {

  BufferedReader reader = new BufferedReader(new FileReader(fromFile));

  int x, y;

  //initialize
  x = Integer.parseInt(reader.readLine().trim());
  y = Integer.parseInt(reader.readLine().trim());

}

Presumably, this would read in the first two lines and store them as integers in x and y.  So going off the example, x=1, y=2.

It is finding a problem with this, and I don't know why.

Body:
We usually use a while loop, the readLine method tells whether the end of file is reached or not:

 List<String> lines = new ArrayList<String>();
 while ((String line = reader.readLine()) != null)
   lines.add(line);

Now we have a collection (a list) that holds all lines from the file as separate strings.

To read the content as Integers, just define a collection of integers and parse while reading:

 List<Integer> lines = new ArrayList<Integer>();
 while ((String line = reader.readLine()) != null) {
   try {
     lines.add(Integer.parseInt(line.trim()));
   } catch (NumberFormatException eaten) {
     // this happens if the content is not parseable (empty line, text, ..)
     // we simply ignore those lines
   }
 }

ContentLicense: CC BY-SA 2.5


问:
Parsing XML data in PHP array
I have this format of xml which is created automatically and was wondering how to iterate through it and save data into mysql

```<code><sales>

  <site_id="000001" sale_id="80" end_date="20170826" end_time="112420" />

  <site_id="000002" sale_id="81" end_date="20170828" end_time="101001" />

  <site_id="000003" sale_id="82" end_date="20170828" end_time="101001" />

</sales>
</code>```

I am okay with inserting into database, however it is the iteration and capturing in a variable that I am kind of stuck with

答:
It's a not valid XML, it will be something like this:

```<code><sales>

  <sale site_id="000001" sale_id="80" end_date="20170826" end_time="112420"></sale>

  <sale site_id="000002" sale_id="81" end_date="20170828" end_time="101001"></sale>

  <sale site_id="000003" sale_id="82" end_date="20170828" end_time="101001"></sale>

</sales>

$dom = new DOMDocument('1.0', 'utf-8');
$dom->loadXML($xml);

$xpath = new DOMXpath($dom);
$a = $xpath->query("//sale");

$result = array();
$i = 0;
foreach($a as $b)
{
    if ($b->hasAttributes())
    {
        $j = 0;
        $tmp = array();
        foreach ($b->attributes as $attr)
        {
            $tmp[$attr->nodeName] = $attr->nodeValue;
            $j++;
        }
        $result[] = $tmp;
    }
    $i++;
}

print_r($result);
</code>```

`

output:

```<code>Array
(
    [0] => Array
        (
            [site_id] => 000001
            [sale_id] => 80
            [end_date] => 20170826
            [end_time] => 112420
        )

    [1] => Array
        (
            [site_id] => 000002
            [sale_id] => 81
            [end_date] => 20170828
            [end_time] => 101001
        )

    [2] => Array
        (
            [site_id] => 000003
            [sale_id] => 82
            [end_date] => 20170828
            [end_time] => 101001
        )

)
</code>```

Title: Parsing XML data in PHP array

Body:
I have this format of xml which is created automatically and was wondering how to iterate through it and save data into mysql

<sales>

  <site_id="000001" sale_id="80" end_date="20170826" end_time="112420" />

  <site_id="000002" sale_id="81" end_date="20170828" end_time="101001" />

  <site_id="000003" sale_id="82" end_date="20170828" end_time="101001" />

</sales>

I am okay with inserting into database, however it is the iteration and capturing in a variable that I am kind of stuck with

Body:
It's a not valid XML, it will be something like this:

<sales>

  <sale site_id="000001" sale_id="80" end_date="20170826" end_time="112420"></sale>

  <sale site_id="000002" sale_id="81" end_date="20170828" end_time="101001"></sale>

  <sale site_id="000003" sale_id="82" end_date="20170828" end_time="101001"></sale>

</sales>

$dom = new DOMDocument('1.0', 'utf-8');
$dom->loadXML($xml);

$xpath = new DOMXpath($dom);
$a = $xpath->query("//sale");

$result = array();
$i = 0;
foreach($a as $b)
{
    if ($b->hasAttributes())
    {
        $j = 0;
        $tmp = array();
        foreach ($b->attributes as $attr)
        {
            $tmp[$attr->nodeName] = $attr->nodeValue;
            $j++;
        }
        $result[] = $tmp;
    }
    $i++;
}

print_r($result);

`

output:

Array
(
    [0] => Array
        (
            [site_id] => 000001
            [sale_id] => 80
            [end_date] => 20170826
            [end_time] => 112420
        )

    [1] => Array
        (
            [site_id] => 000002
            [sale_id] => 81
            [end_date] => 20170828
            [end_time] => 101001
        )

    [2] => Array
        (
            [site_id] => 000003
            [sale_id] => 82
            [end_date] => 20170828
            [end_time] => 101001
        )

)


问:
How to input function so it can be graphed correctly
Currently I am trying to graph the sin(x) function and a function named myPolys which is the taylor polynomial of sin(x) as it is equal to

```<code>myPolys =
Table[Table[(-1)^((j - 1)/2) x^j/Factorial[j], {j, 1, h, 2}], {h, 1,
      19, 2}];
</code>```

How can I use manipulate to graph both functions so that each part of myPolys is graphed

My graphing code so far:

```<code>Manipulate[Plot[{Sin[x], myPolys[[n]]}, {x, -10, 10},
PlotRange -> {-5, 5}], {n, 1, Length[myPolys], 1}];
</code>```

currently for each iteration of n, myPolys is graphed as separate
x and then x & -(x^3)/3! and then x & -(x^3)/3! & x^5/5! (all are plotted separate o the same graph )

The graph I'm trying to achieve is that for n=1 sin(x) should be plotted and x from myPoly should be plotted, for n=2 it continues and graphs x-(x^3/3!) (instead of plotting, for n=2, x and -x^3/3! seperately) and so on and so forth until n reaches 10.

My graph at the moment:

The graph I'm hoping for:

答:
```<code>myPolys = Table[Sum[(-1)^((j - 1)/2) x^j/Factorial[j],
    {j, 1, h, 2}], {h, 1, 19, 2}];

Manipulate[Plot[{Sin[x], Evaluate@Take[myPolys, n]},
  {x, -10, 10}, PlotRange -> {-5, 5}], {n, 1, Length[myPolys], 1}]
</code>```

Or, in more functional style.

```<code>Clear[myPolys]

myPolys[n_] := Table[Sum[(-1)^((j - 1)/2) x^j/Factorial[j],
   {j, 1, h, 2}], {h, 1, 2 n - 1, 2}]

Manipulate[Plot[{Sin[x], Evaluate@myPolys[n]},
  {x, -10, 10}, PlotRange -> {-5, 5}], {n, 1, 10, 1}]
</code>```

And with legend.

```<code>myLabels[n_] := Table[Sum[(-1)^((j - 1)/2) x^j/ToString[j] <> "!",
   {j, 1, h, 2}], {h, 1, 2 n - 1, 2}]

Manipulate[Plot[{Sin[x], Evaluate@myPolys[n]},
  {x, -10, 10}, PlotRange -> {-5, 5},
  PlotLegends -> Placed[PointLegend[
     Rest@Array[ColorData[97], n + 1], HoldForm /@ myLabels[n],
     LegendMarkers -> {"\[Tilde]", 30}], Left]], {n, 1, 10, 1}]
</code>```

Body:
Currently I am trying to graph the sin(x) function and a function named myPolys which is the taylor polynomial of sin(x) as it is equal to

myPolys =
Table[Table[(-1)^((j - 1)/2) x^j/Factorial[j], {j, 1, h, 2}], {h, 1,
      19, 2}];

How can I use manipulate to graph both functions so that each part of myPolys is graphed

My graphing code so far:

Manipulate[Plot[{Sin[x], myPolys[[n]]}, {x, -10, 10},
PlotRange -> {-5, 5}], {n, 1, Length[myPolys], 1}];

currently for each iteration of n, myPolys is graphed as separate
x and then x & -(x^3)/3! and then x & -(x^3)/3! & x^5/5! (all are plotted separate o the same graph )

The graph I'm trying to achieve is that for n=1 sin(x) should be plotted and x from myPoly should be plotted, for n=2 it continues and graphs x-(x^3/3!) (instead of plotting, for n=2, x and -x^3/3! seperately) and so on and so forth until n reaches 10.

My graph at the moment:

The graph I'm hoping for:

Body:
myPolys = Table[Sum[(-1)^((j - 1)/2) x^j/Factorial[j],
    {j, 1, h, 2}], {h, 1, 19, 2}];

Manipulate[Plot[{Sin[x], Evaluate@Take[myPolys, n]},
  {x, -10, 10}, PlotRange -> {-5, 5}], {n, 1, Length[myPolys], 1}]

Or, in more functional style.

Clear[myPolys]

myPolys[n_] := Table[Sum[(-1)^((j - 1)/2) x^j/Factorial[j],
   {j, 1, h, 2}], {h, 1, 2 n - 1, 2}]

Manipulate[Plot[{Sin[x], Evaluate@myPolys[n]},
  {x, -10, 10}, PlotRange -> {-5, 5}], {n, 1, 10, 1}]

And with legend.

myLabels[n_] := Table[Sum[(-1)^((j - 1)/2) x^j/ToString[j] <> "!",
   {j, 1, h, 2}], {h, 1, 2 n - 1, 2}]

Manipulate[Plot[{Sin[x], Evaluate@myPolys[n]},
  {x, -10, 10}, PlotRange -> {-5, 5},
  PlotLegends -> Placed[PointLegend[
     Rest@Array[ColorData[97], n + 1], HoldForm /@ myLabels[n],
     LegendMarkers -> {"\[Tilde]", 30}], Left]], {n, 1, 10, 1}]


问:
Unexpected namespace prefix "app" found for tag TextView when I try to set fontFamily attribute
I set app:fontFamily="@font/montserrat_bold" on TextView and i get error: Unexpected namespace prefix "app" found for tag TextView. I use Android Studio 3.0. Is there any solution?

答: Try changing TextView to android.support.v7.widget.AppCompatTextView.

ContentLicense: CC BY-SA 4.0


问:
SQL - Tracking student exam records as they move between schools
I'd like to pick some of your glorious minds for an optimal solution to my dilemma.

Scenario:

Schools have children and children take tests.

The tests point to the child, not the school.

If the child moves school, the test records are taken to the new school and the previous school has no record of the test being done as they are linked to the child.

Obviously, this isn't ideal and is the result of the database not being designed with this in mind. What would the correct course of action be; I’ve currently identified the 3 possibilities listed below which would solve the current problem. However, i cannot be sure which is best for the issue at hand - and if any better solutions exist.

Have each test store the school & student within the test records (requiring current records to be updated & increasing the size of the database)

Create a new child record, duplicating the existing data for the new school with a new ID so the test remains linked to the previous school (complicating the ability to identify previous test scores)

Separately keep track of moves to other schools, then use this additional table to identify current and previous using the timestamps (increased complexity and computational requirements)

EDIT:

So i tried to use a basic example, but requests for the task at hand have been requested.

Here's the DB Schema for the tables (simplified for problem, note: Postnatal is not important):

Patients: ID, MidwifeID, TeamID

Midwives: ID

Groups: ID

GroupsMidwives: MidwifeID, GroupsID

PatientObservations: ID, MidwifeID, PatientID

Using a query as follows:

```<code>SELECT Some Information
from Postnatals
JOIN Midwives on Postnatals.MidwifeID = Midwives.ID
JOIN Patients on Patients.PatientID = Postnatals.PatientID
JOIN GroupsMidwives on GroupsMidwives.MidwifeID = Midwives.ID
JOIN Groups on Groups.ID = GroupsMidwives.GroupID
JOIN PatientObservations on PatientObservations.PatientID =
Postnatals.PatientID
WHERE groups.Name = ?
*some extra checks*
GROUP BY Midwives.Firstname, Midwives.Surname, Midwives.ID
</code>```

However, in the event that a midwife is moved to a different team, the data associated with the previous team is now owned by the newly assigned team. As described in the example detailed previously.

Thus a modification (which modification is yet to be realised) is required to make the data submitted - prior to a team change - assigned to the previous team, as of current, because of the way the records are owned by the midwife, this is not possible.

答:
You should below suggestion as per you concern.

Step 1 ) You need to create School Master Table

```<code>ID  |  School | IsActive
1   |  ABC    |    1
2   |  XYZ    |    1
</code>```

Step 2 ) You need to create Children Master having school id as foreign key

```<code>ID  |  School | Children Name| IsActive
1   |  2      |    Mak       |    1
2   |  2      |    Jak       |    1
</code>```

Step 3 ) You need to create test table having children id as foreign key

```<code>ID  |  Children_id | Test Name | IsActive
1   |  2           |    Math   |    1
2   |  2           |    Eng    |    1
</code>```

Now whenever child moves school then make child record inactive and create another active record with new school. This will help you to bifurcate the old test and new test.

do let me know in case morehelp required

Body:
I'd like to pick some of your glorious minds for an optimal solution to my dilemma.

Scenario:

Schools have children and children take tests.

The tests point to the child, not the school.

If the child moves school, the test records are taken to the new school and the previous school has no record of the test being done as they are linked to the child.

Obviously, this isn't ideal and is the result of the database not being designed with this in mind. What would the correct course of action be; I’ve currently identified the 3 possibilities listed below which would solve the current problem. However, i cannot be sure which is best for the issue at hand - and if any better solutions exist.

Have each test store the school & student within the test records (requiring current records to be updated & increasing the size of the database)

Create a new child record, duplicating the existing data for the new school with a new ID so the test remains linked to the previous school (complicating the ability to identify previous test scores)

Separately keep track of moves to other schools, then use this additional table to identify current and previous using the timestamps (increased complexity and computational requirements)

EDIT:

So i tried to use a basic example, but requests for the task at hand have been requested.

Here's the DB Schema for the tables (simplified for problem, note: Postnatal is not important):

Patients: ID, MidwifeID, TeamID

Midwives: ID

Groups: ID

GroupsMidwives: MidwifeID, GroupsID

PatientObservations: ID, MidwifeID, PatientID

Using a query as follows:

SELECT Some Information
from Postnatals
JOIN Midwives on Postnatals.MidwifeID = Midwives.ID
JOIN Patients on Patients.PatientID = Postnatals.PatientID
JOIN GroupsMidwives on GroupsMidwives.MidwifeID = Midwives.ID
JOIN Groups on Groups.ID = GroupsMidwives.GroupID
JOIN PatientObservations on PatientObservations.PatientID =
Postnatals.PatientID
WHERE groups.Name = ?
*some extra checks*
GROUP BY Midwives.Firstname, Midwives.Surname, Midwives.ID

However, in the event that a midwife is moved to a different team, the data associated with the previous team is now owned by the newly assigned team. As described in the example detailed previously.

Thus a modification (which modification is yet to be realised) is required to make the data submitted - prior to a team change - assigned to the previous team, as of current, because of the way the records are owned by the midwife, this is not possible.

Body:
You should below suggestion as per you concern.

Step 1 ) You need to create School Master Table

ID  |  School | IsActive
1   |  ABC    |    1
2   |  XYZ    |    1

Step 2 ) You need to create Children Master having school id as foreign key

ID  |  School | Children Name| IsActive
1   |  2      |    Mak       |    1
2   |  2      |    Jak       |    1

Step 3 ) You need to create test table having children id as foreign key

ID  |  Children_id | Test Name | IsActive
1   |  2           |    Math   |    1
2   |  2           |    Eng    |    1

Now whenever child moves school then make child record inactive and create another active record with new school. This will help you to bifurcate the old test and new test.

do let me know in case morehelp required


问:
can't change my table data in angulars?
i posted a question before but no answer, maybe my code was too long, so i am having this problem, i have a table :

```<code>$scope.slides = [
   {"status":true},
   {"status":false},
   {"status":false},
]
</code>```

when i try to get the value of the first element or second or third element it works by using this :

```<code> var i = $scope.slides[0].status //1,2 for second and third
 alert(i) // it works fine
</code>```

but i want this data to change every second :

```<code> $scope.change = $interval(function($scope){
   if(condition){
      $scope.slides[0].status = false
    }else {
      $scope.slides[0].status = true
  }
   })
</code>```

I am puuting this value in my HTML in the ng-show directive, it seems         nothing is changing ..

Thank you

答:
In theory this should work:</p>

```<code>$scope.change = $interval(function(){
   //change between true and false every second.
   $scope.slides[0].status = !$scope.slides[0].status;
}, 1000); //1000 ms, 1s
</code>```

Title: can't change my table data in angulars?

Body:
i posted a question before but no answer, maybe my code was too long, so i am having this problem, i have a table :

$scope.slides = [
   {"status":true},
   {"status":false},
   {"status":false},
]

when i try to get the value of the first element or second or third element it works by using this :

 var i = $scope.slides[0].status //1,2 for second and third
 alert(i) // it works fine

but i want this data to change every second :

 $scope.change = $interval(function($scope){
   if(condition){
      $scope.slides[0].status = false
    }else {
      $scope.slides[0].status = true
  }
   })

I am puuting this value in my HTML in the ng-show directive, it seems         nothing is changing ..

Thank you

Body:
In theory this should work:

$scope.change = $interval(function(){
   //change between true and false every second.
   $scope.slides[0].status = !$scope.slides[0].status;
}, 1000); //1000 ms, 1s


问:
SQL Server get string
I have two rows like below, from that I need to fetch the previous string in the select. e.g in the first row I need to fetch 'Auto Components', in the second row I need to fetch 'Plastic and Synthetic Resins'. Please suggest.</p>

```<code>Automotive > Auto Components > Auto Parts and Equipment
Chemicals > Commodity Chemicals > Plastic and Synthetic Resins > Plastic Products
</code>```

答:
For more info, see my comment:

```<code>SELECT REVERSE(SUBSTRING(rs, firstangle + 1, secondangle - firstangle - 1))
FROM
(
  SELECT CHARINDEX('>', rs) as firstangle, CHARINDEX('>', rs,  CHARINDEX('>', rs)+1) as secondangle, rs, s
  FROM
  (
    SELECT REVERSE(s) as rs, s
    FROM
    (
        SELECT 'Chemicals > Commodity Chemicals > Plastic and Synthetic Resins > Plastic Products' as s
    ) a
  ) b
)c
</code>```

I did this as several subqueries because it makes it a bit neater than trying to do it all in one go..

All in one looks more like this hideous thing:

```<code>    SELECT REVERSE(SUBSTRING(REVERSE(s), CHARINDEX('>', REVERSE(s)) + 1, CHARINDEX('>', REVERSE(s),  CHARINDEX('>', REVERSE(s))+1) - CHARINDEX('>', REVERSE(s)) - 1))
    FROM
    (
        SELECT 'Chemicals > Commodity Chemicals > Plastic and Synthetic Resins > Plastic Products' as s
    ) a
</code>```

Title: SQL Server get string

Body:
I have two rows like below, from that I need to fetch the previous string in the select. e.g in the first row I need to fetch 'Auto Components', in the second row I need to fetch 'Plastic and Synthetic Resins'. Please suggest.

Automotive > Auto Components > Auto Parts and Equipment
Chemicals > Commodity Chemicals > Plastic and Synthetic Resins > Plastic Products

Body:
For more info, see my comment:

SELECT REVERSE(SUBSTRING(rs, firstangle + 1, secondangle - firstangle - 1))
FROM
(
  SELECT CHARINDEX('>', rs) as firstangle, CHARINDEX('>', rs,  CHARINDEX('>', rs)+1) as secondangle, rs, s
  FROM
  (
    SELECT REVERSE(s) as rs, s
    FROM
    (
        SELECT 'Chemicals > Commodity Chemicals > Plastic and Synthetic Resins > Plastic Products' as s
    ) a
  ) b
)c

I did this as several subqueries because it makes it a bit neater than trying to do it all in one go..

All in one looks more like this hideous thing:

    SELECT REVERSE(SUBSTRING(REVERSE(s), CHARINDEX('>', REVERSE(s)) + 1, CHARINDEX('>', REVERSE(s),  CHARINDEX('>', REVERSE(s))+1) - CHARINDEX('>', REVERSE(s)) - 1))
    FROM
    (
        SELECT 'Chemicals > Commodity Chemicals > Plastic and Synthetic Resins > Plastic Products' as s
    ) a


问:
make delay after each() function in jQuery
I want to animate each .dot after a 3 seconds delay after previous .dot
Here is the code I used. But it doesn't work.

```<code>var time = 3000;

$(".dot").each(function() {
  setTimeout(function() {
    $(this).addClass("animate");
    $(this).find(".num").addClass("animate");
  }, time)
  time += 3000;
});
</code>```

答:
Try this</p>

```<code>$(".dot").each(function(i) {
  $(this).delay(3000 * i).addClass("animate");
  $(this).find(".num").delay(3000 * i).addClass("animate");
});
</code>```

Body:
I want to animate each .dot after a 3 seconds delay after previous .dot
Here is the code I used. But it doesn't work.

var time = 3000;

$(".dot").each(function() {
  setTimeout(function() {
    $(this).addClass("animate");
    $(this).find(".num").addClass("animate");
  }, time)
  time += 3000;
});

Body:
Try this

$(".dot").each(function(i) {
  $(this).delay(3000 * i).addClass("animate");
  $(this).find(".num").delay(3000 * i).addClass("animate");
});


问:
How to analyze SQL statement execution time fluctuation?
I know this question is not easy to give an actual answer, but I met it sometimes, SQL execution time is high but cannot reproduce 100%, actually very casually.

here, I just want to get the general way to how to find the root cause, which aspects should I pay more attention to? and please note 1 point, I was doing it on HANA DB (from SAP).

Thanks!

答:
Did you try to analyze the script execution with available tools like SAP HANA SQL analyzer app Plan Graph or Timeline

If you know the time when the SQL query took too much time, you can analyze the time range for memory usage with Memory Analysis application as well


问:
Hide Status Bar during a Custom UIViewController Transition
Background: I implemented a Custom UIViewController Transition where the first view controller (VC1) has a visible status bar

```<code>override func prefersStatusBarHidden() -> Bool {
    return false
}
</code>```

while the second presented view controller (VC2) has a hidden status bar:

```<code>override func prefersStatusBarHidden() -> Bool {
    return true
}
</code>```

Transitioning is controlled by the user since I implemented a pull to open transition with gesture controllers.

Objective: I want the status bar to be hidden during appearance transition AND disappearance transition (essentially like the Google Maps Slide Out Menu).

Problem: The status bar is correctly hidden during the entire appearance transition of ViewController VC2. But during the entire disappearance transition the status bar is visible. Any suggestions on how to properly implement this for iOS 9?

答:
You can create an instance var to hold the status bar hidden state and return this boolean from prefersStatusBarHidden(). When this value changes, call setNeedsStatusBarAppearanceUpdate().

For example:

```<code>var statusBarHidden = true {
    didSet {
        if oldValue != statusBarHidden {
            setNeedsStatusBarAppearanceUpdate()
        }
    }
}

override var prefersStatusBarHidden: Bool {
    return statusBarHidden
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    statusBarHidden = false
}
</code>```

Body:
Background: I implemented a Custom UIViewController Transition where the first view controller (VC1) has a visible status bar

override func prefersStatusBarHidden() -> Bool {
    return false
}

while the second presented view controller (VC2) has a hidden status bar:

override func prefersStatusBarHidden() -> Bool {
    return true
}

Transitioning is controlled by the user since I implemented a pull to open transition with gesture controllers.

Objective: I want the status bar to be hidden during appearance transition AND disappearance transition (essentially like the Google Maps Slide Out Menu).

Problem: The status bar is correctly hidden during the entire appearance transition of ViewController VC2. But during the entire disappearance transition the status bar is visible. Any suggestions on how to properly implement this for iOS 9?

Body:
You can create an instance var to hold the status bar hidden state and return this boolean from prefersStatusBarHidden(). When this value changes, call setNeedsStatusBarAppearanceUpdate().

For example:

var statusBarHidden = true {
    didSet {
        if oldValue != statusBarHidden {
            setNeedsStatusBarAppearanceUpdate()
        }
    }
}

override var prefersStatusBarHidden: Bool {
    return statusBarHidden
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    statusBarHidden = false
}


问:
Maintain object references through Serialize/Deserialize
When serializing, I would like to serialize an object only once, then any references to that object should be serialized as a reference to the object. This is because, when I later deserialize the objects, I would like to maintain those references. To illustrate my goal, the code below should output "After Serialization: true".</p>

```<code>class Program
{
    static void Main(string[] args)
    {
        MyObject obj = new MyObject() { Name = "obj" };
        MyObject[] myObjs = new MyObject[]
        {
            obj, obj
        };

        Console.WriteLine("Object Refs Equal?");
        Console.WriteLine(string.Format("Before Serialization: {0}",
            object.ReferenceEquals(myObjs[0], myObjs[1])));

        XmlSerializer toXml = new XmlSerializer(typeof(MyObject[]));
        using (FileStream toFile = File.Create(@"C:\foo.xml"))
        {
            toXml.Serialize(toFile, myObjs);
        }

        XmlSerializer fromXml = new XmlSerializer(typeof(MyObject[]));
        using (FileStream fromFile = File.OpenRead(@"C:\foo.xml"))
        {
            MyObject[] deserialized = (MyObject[])fromXml.Deserialize(fromFile);

            Console.WriteLine(string.Format("After Serialization: {0}",
            object.ReferenceEquals(deserialized[0], deserialized[1])));
        }

        Console.ReadLine();
    }
}

[Serializable]
public class MyObject
{
    public string Name { get; set; }
}
</code>```

答:
your code example won't work simply because the XmlSerializer does not save reference information, during the serialization process it will simply write the data for obj to the stream twice this means that when you deserialize it will read the data for obj as two different instances, it has no way of knowing that they referred to the same instance at serialization time. using the DataContractSerializer mentioned before should give you what you want but note that it uses non standard xml
(see: http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx)</p>

OwnerDisplayName: CodeChef

Body:
When serializing, I would like to serialize an object only once, then any references to that object should be serialized as a reference to the object. This is because, when I later deserialize the objects, I would like to maintain those references. To illustrate my goal, the code below should output "After Serialization: true".

class Program
{
    static void Main(string[] args)
    {
        MyObject obj = new MyObject() { Name = "obj" };
        MyObject[] myObjs = new MyObject[]
        {
            obj, obj
        };

        Console.WriteLine("Object Refs Equal?");
        Console.WriteLine(string.Format("Before Serialization: {0}",
            object.ReferenceEquals(myObjs[0], myObjs[1])));

        XmlSerializer toXml = new XmlSerializer(typeof(MyObject[]));
        using (FileStream toFile = File.Create(@"C:\foo.xml"))
        {
            toXml.Serialize(toFile, myObjs);
        }

        XmlSerializer fromXml = new XmlSerializer(typeof(MyObject[]));
        using (FileStream fromFile = File.OpenRead(@"C:\foo.xml"))
        {
            MyObject[] deserialized = (MyObject[])fromXml.Deserialize(fromFile);

            Console.WriteLine(string.Format("After Serialization: {0}",
            object.ReferenceEquals(deserialized[0], deserialized[1])));
        }

        Console.ReadLine();
    }
}

[Serializable]
public class MyObject
{
    public string Name { get; set; }
}

OwnerDisplayName: SpaceghostAli


问:
pack() in php. Illegal hex digit warning
i am having some problems using pack() in php

```<code>$currencypair = "EUR/USD";
$buy_sell = "buy";
$alert_device_token =array("a","a","b");
$message = "Your " . $currencypair . " " . $buy_sell . " alert price has been reached!";
$payload['aps'] = array (
  'alert' => $message,
  'badge' => 1,
  'sound' => 'default'
);
$payload = json_encode($payload);

foreach ($alert_device_token as $alert_device)
{
  $apnsMessage = chr(0) . chr(0) . chr(32) .
                 pack('H*', str_replace(' ', '', $alert_device)) .
                 chr(0) . chr(strlen($payload)) . $payload;
  echo $apnsMessage;
}
</code>```

Now sometimes i get following warnings running the same code -

```<code>Warning: pack() [function.pack]: Type H: illegal hex digit g in /code/FR2BVl
</code>```

the illegal hex digit keeps varying though. Any ideas about this warning and ways to remove it.

check it live here

答:
pack converts hexadecimal number to binary, e.g.:

```<code>  echo pack("H*", "2133")
</code>```

produces !3, since ! has code 0x21 and 3 has code 0x33. Since g is not hex digit, warning is given. To be useful for pack's H format, the argument must be hex number. If $alert_device isn't - you should use something else, depending on what it is and what you expect as the result.

Body:
i am having some problems using pack() in php

$currencypair = "EUR/USD";
$buy_sell = "buy";
$alert_device_token =array("a","a","b");
$message = "Your " . $currencypair . " " . $buy_sell . " alert price has been reached!";
$payload['aps'] = array (
  'alert' => $message,
  'badge' => 1,
  'sound' => 'default'
);
$payload = json_encode($payload);

foreach ($alert_device_token as $alert_device)
{
  $apnsMessage = chr(0) . chr(0) . chr(32) .
                 pack('H*', str_replace(' ', '', $alert_device)) .
                 chr(0) . chr(strlen($payload)) . $payload;
  echo $apnsMessage;
}

Now sometimes i get following warnings running the same code -

Warning: pack() [function.pack]: Type H: illegal hex digit g in /code/FR2BVl

the illegal hex digit keeps varying though. Any ideas about this warning and ways to remove it.

check it live here

Body:
pack converts hexadecimal number to binary, e.g.:

  echo pack("H*", "2133")

produces !3, since ! has code 0x21 and 3 has code 0x33. Since g is not hex digit, warning is given. To be useful for pack's H format, the argument must be hex number. If $alert_device isn't - you should use something else, depending on what it is and what you expect as the result.


问:
Get the size of each white object in an image python opencv
I am trying to get the size of each separate object in this image so that I can separate them by size.  My aim is to be able to loop through them and separate them by size. I have looked everywhere and can't really find anything anywhere. I have tried connected component analysis but I am unsure of how to retrieve size values from it.

```<code>_, lab = cv2.connectedComponents(img)
</code>```

答:
Use connectedComponentsWithStats.

```<code># Choose 4 or 8 for connectivity type
connectivity = 4
output = cv2.connectedComponentsWithStats(img, connectivity, cv2.CV_32S)

num_labels = output[0]
stats = output[2]

for label in range(1,num_labels):
    blob_area = stats[label, cv2.CC_STAT_AREA]
    blob_width = stats[label, cv2.CC_STAT_WIDTH]
    blob_height = stats[label, cv2.CC_STAT_HEIGHT]
</code>```

num_labels will give the total number of labels. You can use stats matrix to retrieve size of each blob by iterating through each label.

Body:
I am trying to get the size of each separate object in this image so that I can separate them by size.  My aim is to be able to loop through them and separate them by size. I have looked everywhere and can't really find anything anywhere. I have tried connected component analysis but I am unsure of how to retrieve size values from it.

_, lab = cv2.connectedComponents(img)

Body:
Use connectedComponentsWithStats.

# Choose 4 or 8 for connectivity type
connectivity = 4
output = cv2.connectedComponentsWithStats(img, connectivity, cv2.CV_32S)

num_labels = output[0]
stats = output[2]

for label in range(1,num_labels):
    blob_area = stats[label, cv2.CC_STAT_AREA]
    blob_width = stats[label, cv2.CC_STAT_WIDTH]
    blob_height = stats[label, cv2.CC_STAT_HEIGHT]

num_labels will give the total number of labels. You can use stats matrix to retrieve size of each blob by iterating through each label.


问:
Sequelize create function not working as expected
I created an instance function on a Model as per this spec:

```<code>describe('Instance methods', function() {
    var task;

    beforeEach(function() {
      return Task.create({
        name: 'task',
      }).then(function(_task) {
        task = _task;
      });
    });

    describe('addChild', function() {
      it('should return a promise for the new child', function() {
        return task.addChild({ name: 'task2' }).then(function(child) {
          expect(child.name).to.equal('task2');
          expect(child.parentId).to.equal(task.id);
        });
      });
    });
..... more not applicable
  });
</code>```

This is it, but I am not getting zilch back...

```<code>Task.prototype.addChild = function(task) {
  return Task.create(task.name).then(function(task) {
    console.log('task', task);
    return task;
  });
};
</code>```

As mentioned in the spec:

should return a promise for the new child

And as per the console:

Task Instance methods addChild should return a promise for the new
  child:

And this is the error I am getting back:

```<code>SequelizeValidationError: Validation Error
</code>```

So what I am doing wrong to not add this task in the data base?
Am I not using the create method correctly?

Thanks in advance!

UPDATE

I tried this:

```<code>Task.prototype.addChild = function(task) {   var task = Task.build({
name: task['name'] });   return task.save(); };
</code>```

But I am getting back,

```<code>AssertionError: expected null to equal 1
</code>```

答:
they are some error i think in your implementation :

According to your test, a task is describe with a name and a parentId.
but when you create your task you pass at the addChild { name: 'toto' }
and you passed in Task.create directly task.name which can't work, the method attempt to received an object.

So insteadOf that

```<code>Task.prototype.addChild = function(task) {
    return Task.create(task.name).then(function(task) {
        console.log('task', task);
        return task;
    });
};
</code>```

Try this :

```<code>Task.prototype.addChild = function(task) {
    return Task.create(task).then(function(task) {
        console.log('task', task);
        return task;
    });
};

// Than you call like this
await Task.addChild({
    name: 'name',
    parentId: 1
});

// OR

Task.addChild({
    name: 'name',
    parentId: 1
}).then(() => // something);
</code>```

Body:
I created an instance function on a Model as per this spec:

describe('Instance methods', function() {
    var task;

    beforeEach(function() {
      return Task.create({
        name: 'task',
      }).then(function(_task) {
        task = _task;
      });
    });

    describe('addChild', function() {
      it('should return a promise for the new child', function() {
        return task.addChild({ name: 'task2' }).then(function(child) {
          expect(child.name).to.equal('task2');
          expect(child.parentId).to.equal(task.id);
        });
      });
    });
..... more not applicable
  });

This is it, but I am not getting zilch back...

Task.prototype.addChild = function(task) {
  return Task.create(task.name).then(function(task) {
    console.log('task', task);
    return task;
  });
};

As mentioned in the spec:

should return a promise for the new child

And as per the console:

Task Instance methods addChild should return a promise for the new
  child:

And this is the error I am getting back:

SequelizeValidationError: Validation Error

So what I am doing wrong to not add this task in the data base?
Am I not using the create method correctly?

Thanks in advance!

UPDATE

I tried this:

Task.prototype.addChild = function(task) {   var task = Task.build({
name: task['name'] });   return task.save(); };

But I am getting back,

AssertionError: expected null to equal 1

Body:
they are some error i think in your implementation :

According to your test, a task is describe with a name and a parentId.
but when you create your task you pass at the addChild { name: 'toto' }
and you passed in Task.create directly task.name which can't work, the method attempt to received an object.

So insteadOf that

Task.prototype.addChild = function(task) {
    return Task.create(task.name).then(function(task) {
        console.log('task', task);
        return task;
    });
};

Try this :

Task.prototype.addChild = function(task) {
    return Task.create(task).then(function(task) {
        console.log('task', task);
        return task;
    });
};

// Than you call like this
await Task.addChild({
    name: 'name',
    parentId: 1
});

// OR

Task.addChild({
    name: 'name',
    parentId: 1
}).then(() => // something);


问:
Get output column for each Key
I have a database with roughly this fields:

```<code>SELECT [UserId]
  ,[MissionId]
  ,[LevelId]
  ,[Key]
  ,[BooleanAnswer]
  ,[CreationDateTimeUtc]
  ,[QuestionId]
  FROM [Bakman].[dbo].[LevelEntries]
  WHERE LevelId = 2 AND QuestionId = 1 OR QuestionId = 2 OR QuestionId = 3 OR QuestionId = 4 OR QuestionId = 5 OR QuestionId = 6
</code>```

Now I get this kind of output:

```<code>UserId  MissionId   LevelId Key BooleanAnswer   CreationDateTimeUtc QuestionId
0      1            2       1   1               2017-10-07 11:39:26.350 1
0      1            2       2   1               2017-10-07 11:39:26.350 1
0      1            2       3   0               2017-10-07 11:39:26.350 1
0      1            2       4   1               2017-10-07 11:39:26.350 1
0      1            2       5   0               2017-10-07 11:39:26.350 1
0      1            2       6   1               2017-10-07 11:39:26.350 1
</code>```

But now I want to get a column for each QuestionId (which are equal to the [key]).

Like this :

```<code>       UserId   MissionId   LevelId Key1  Key2  Key3   Key4   Key5   Key6       CreationDateTimeUtc     QuestionId
      1         2       1     0     1     1     0      1      1      1          2017-10-07 11:39:26.350 1
</code>```

Where Key[key] has the boolean awnser and the key belonging to that element.
Good to know is that the Userid + MissionId + LevelId + Key are the Composite key for this table.

EDIT:

Trying both given answers I now get something like this

```<code>    UserId  MissionId   LevelId Key1    Key2    Key3    Key4    Key5    Key6
   1    1   2   1   NULL    NULL    NULL    NULL    NULL
    1   1   2   NULL    1   NULL    NULL    NULL    NULL
    1   1   2   NULL    NULL    0   NULL    NULL    NULL
    1   1   2   NULL    NULL    NULL    1   NULL    NULL
    1   1   2   NULL    NULL    NULL    NULL    1   NULL
    1   1   2   NULL    NULL    NULL    NULL    NULL    1
</code>```

Now I want to combine those so I get the level result of the user.

答:
Try the following query

```<code>SELECT
  UserId,
  MissionId,
  LevelId,
  MAX(CASE WHEN [Key]=1 THEN BooleanAnswer END) Key1,
  MAX(CASE WHEN [Key]=2 THEN BooleanAnswer END) Key2,
  MAX(CASE WHEN [Key]=3 THEN BooleanAnswer END) Key3,
  MAX(CASE WHEN [Key]=4 THEN BooleanAnswer END) Key4,
  MAX(CASE WHEN [Key]=5 THEN BooleanAnswer END) Key5,
  MAX(CASE WHEN [Key]=6 THEN BooleanAnswer END) Key6,
  CreationDateTimeUtc,
  QuestionId
FROM LevelEntries
WHERE LevelId=2
  AND QuestionId IN(1,2,3,4,5,6)
GROUP BY UserId,MissionId,LevelId,CreationDateTimeUtc,QuestionId
</code>```

The second variant

```<code>SELECT
  UserId,
  MissionId,
  LevelId,
  MAX(CASE WHEN [Key]=1 THEN BooleanAnswer END) Key1,
  MAX(CASE WHEN [Key]=2 THEN BooleanAnswer END) Key2,
  MAX(CASE WHEN [Key]=3 THEN BooleanAnswer END) Key3,
  MAX(CASE WHEN [Key]=4 THEN BooleanAnswer END) Key4,
  MAX(CASE WHEN [Key]=5 THEN BooleanAnswer END) Key5,
  MAX(CASE WHEN [Key]=6 THEN BooleanAnswer END) Key6,
  MAX(CreationDateTimeUtc) MaxCreationDateTimeUtc,
  QuestionId
FROM LevelEntries
WHERE LevelId=2
  AND QuestionId IN(1,2,3,4,5,6)
GROUP BY UserId,MissionId,LevelId,QuestionId
</code>```

Title: Get output column for each Key

Body:
I have a database with roughly this fields:

SELECT [UserId]
  ,[MissionId]
  ,[LevelId]
  ,[Key]
  ,[BooleanAnswer]
  ,[CreationDateTimeUtc]
  ,[QuestionId]
  FROM [Bakman].[dbo].[LevelEntries]
  WHERE LevelId = 2 AND QuestionId = 1 OR QuestionId = 2 OR QuestionId = 3 OR QuestionId = 4 OR QuestionId = 5 OR QuestionId = 6

Now I get this kind of output:

UserId  MissionId   LevelId Key BooleanAnswer   CreationDateTimeUtc QuestionId
0      1            2       1   1               2017-10-07 11:39:26.350 1
0      1            2       2   1               2017-10-07 11:39:26.350 1
0      1            2       3   0               2017-10-07 11:39:26.350 1
0      1            2       4   1               2017-10-07 11:39:26.350 1
0      1            2       5   0               2017-10-07 11:39:26.350 1
0      1            2       6   1               2017-10-07 11:39:26.350 1

But now I want to get a column for each QuestionId (which are equal to the [key]).

Like this :

       UserId   MissionId   LevelId Key1  Key2  Key3   Key4   Key5   Key6       CreationDateTimeUtc     QuestionId
      1         2       1     0     1     1     0      1      1      1          2017-10-07 11:39:26.350 1

Where Key[key] has the boolean awnser and the key belonging to that element.
Good to know is that the Userid + MissionId + LevelId + Key are the Composite key for this table.

EDIT:

Trying both given answers I now get something like this

    UserId  MissionId   LevelId Key1    Key2    Key3    Key4    Key5    Key6
   1    1   2   1   NULL    NULL    NULL    NULL    NULL
    1   1   2   NULL    1   NULL    NULL    NULL    NULL
    1   1   2   NULL    NULL    0   NULL    NULL    NULL
    1   1   2   NULL    NULL    NULL    1   NULL    NULL
    1   1   2   NULL    NULL    NULL    NULL    1   NULL
    1   1   2   NULL    NULL    NULL    NULL    NULL    1

Now I want to combine those so I get the level result of the user.

Body:
Try the following query

SELECT
  UserId,
  MissionId,
  LevelId,
  MAX(CASE WHEN [Key]=1 THEN BooleanAnswer END) Key1,
  MAX(CASE WHEN [Key]=2 THEN BooleanAnswer END) Key2,
  MAX(CASE WHEN [Key]=3 THEN BooleanAnswer END) Key3,
  MAX(CASE WHEN [Key]=4 THEN BooleanAnswer END) Key4,
  MAX(CASE WHEN [Key]=5 THEN BooleanAnswer END) Key5,
  MAX(CASE WHEN [Key]=6 THEN BooleanAnswer END) Key6,
  CreationDateTimeUtc,
  QuestionId
FROM LevelEntries
WHERE LevelId=2
  AND QuestionId IN(1,2,3,4,5,6)
GROUP BY UserId,MissionId,LevelId,CreationDateTimeUtc,QuestionId

The second variant

SELECT
  UserId,
  MissionId,
  LevelId,
  MAX(CASE WHEN [Key]=1 THEN BooleanAnswer END) Key1,
  MAX(CASE WHEN [Key]=2 THEN BooleanAnswer END) Key2,
  MAX(CASE WHEN [Key]=3 THEN BooleanAnswer END) Key3,
  MAX(CASE WHEN [Key]=4 THEN BooleanAnswer END) Key4,
  MAX(CASE WHEN [Key]=5 THEN BooleanAnswer END) Key5,
  MAX(CASE WHEN [Key]=6 THEN BooleanAnswer END) Key6,
  MAX(CreationDateTimeUtc) MaxCreationDateTimeUtc,
  QuestionId
FROM LevelEntries
WHERE LevelId=2
  AND QuestionId IN(1,2,3,4,5,6)
GROUP BY UserId,MissionId,LevelId,QuestionId


问:
Parsing a Json to a ListView
I have this json form this URL: Website Here

The problem is that I'm trying to retrieve some of the data in the JSON like:  block_height, total, fees and size. I have 2 days trying to make it work but I have no idea why my code is not working. The last I've tried was showing the data in a alert dialog. But this isn't working yet.

JSON:

```<code>{
  "block_hash": "0000000000000397a165d83cc4640321a3b8ff4cce1f8aa2570deabf14ac14e7",
  "block_height": 154598,
  "block_index": 63,
  "hash": "b6f6991d03df0e2e04dafffcd6bc418aac66049e2cd74b80f14ac86db1e3f0da",
  "addresses": [
    "13AMPUTTwryLGX3nrMvumaerSqNXkL3gEV",
    "14pDqB95GWLWCjFxM4t96H2kXH7QMKSsgG",
    "1FwYmGEjXhMtxpWDpUXwLx7ndLNfFQncKq"
  ],
  "total": 100000000,
  "fees": 0,
  "size": 258,
  "preference": "low",
  "confirmed": "2011-11-24T11:45:54Z",
  "received": "2011-11-24T11:45:54Z",
  "ver": 1,
  "double_spend": false,
  "vin_sz": 1,
  "vout_sz": 2,
  "confirmations": 339633,
  "confidence": 1,
  "inputs": [
    {
      "prev_hash": "9fa4e0e33aba41623bc3618827d2a6495e6828ce04f26c97771a1369210e8201",
      "output_index": 2,
      "script": "48304502210098a2851420e4daba656fd79cb60cb565bd7218b6b117fda9a512ffbf17f8f178022005c61f31fef3ce3f906eb672e05b65f506045a65a80431b5eaf28e0999266993014104f0f86fa57c424deb160d0fc7693f13fce5ed6542c29483c51953e4fa87ebf247487ed79b1ddcf3de66b182217fcaf3fcef3fcb44737eb93b1fcb8927ebecea26",
      "output_value": 100000000,
      "sequence": 4294967295,
      "addresses": [
        "1FwYmGEjXhMtxpWDpUXwLx7ndLNfFQncKq"
      ],
      "script_type": "pay-to-pubkey-hash",
      "age": 154567
    }
  ],
  "outputs": [
    {
      "value": 98000000,
      "script": "76a91429d6a3540acfa0a950bef2bfdc75cd51c24390fd88ac",
      "spent_by": "df0f8a4f0988de2875705a79ec826c8b9f8b08c9ffa4e5b4a5ea1b7bf956306c",
      "addresses": [
        "14pDqB95GWLWCjFxM4t96H2kXH7QMKSsgG"
      ],
      "script_type": "pay-to-pubkey-hash"
    },
    {
      "value": 2000000,
      "script": "76a91417b5038a413f5c5ee288caa64cfab35a0c01914e88ac",
      "spent_by": "0c45329983279acf2f9e9c7976774ef11bdb2646d934836c53e6679281e09ac8",
      "addresses": [
        "13AMPUTTwryLGX3nrMvumaerSqNXkL3gEV"
      ],
      "script_type": "pay-to-pubkey-hash"
    }
  ]
}
</code>```

JAVA - Android Studio Fragment

```<code> private void setUpData() {
        // Retrieve the city data from the web service
        // In a worker thread since it's a network operation.
        new Thread(new Runnable() {
            public void run() {
                try {
                    retrieveData();
                } catch (IOException e) {
                    Log.e(LOG_TAG, "Cannot retrive Data", e);
                    return;
                }
            }
        }).start();
    }

    protected void retrieveData() throws IOException {
        HttpURLConnection conn = null;
        final StringBuilder json = new StringBuilder();
        try {
            // Connect to the web service
            URL url = new URL("https://api.blockcypher.com/v1/btc/main/txs/"+TxsHashs);
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(conn.getInputStream());

            // Read the JSON data into the StringBuilder
            int read;
            char[] buff = new char[1024];
            while ((read = in.read(buff)) != -1) {
                json.append(buff, 0, read);
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, "Error connecting to service", e);
            throw new IOException("Error connecting to service", e);
        }
        // Create markers for the city data.
        // Must run this on the UI thread since it's a UI operation.

        getActivity().runOnUiThread(new Runnable() {
            public void run() {
                try {
                    DataAdapter(json.toString());
                } catch (Exception e) {
                    Log.e(LOG_TAG, "Error processing JSON", e);
                }
            }
        });
    }

    private void DataAdapter(String json)
    {
        try
        {
            JSONObject jsonObject = new JSONObject(json);
            String block_height = jsonObject.getString("block_height");
            String total = jsonObject.getString("total");
            String fee = jsonObject.getString("fee");
            String size = jsonObject.getString("size");
            String received = jsonObject.getString("received");
            String confirmations = jsonObject.getString("confirmations");

            showalert(TxsHashs,received);
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }

    }

 private void showalert(String title, String msj)
    {
        AlertDialog.Builder MSGbox = new AlertDialog.Builder(getActivity());
        MSGbox.setTitle(title);
        String mensaje = msj;
        MSGbox.setMessage(mensaje)
                .setPositiveButton("OKEY", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
        AlertDialog alertDialog = MSGbox.create();
        alertDialog.show();
    }
</code>```

Please, someone Help Me

答:
Try below code if you are using Gson library</p>

```<code>private void DataAdapter(String json)
{
        JsonObject jsonObject = gson.fromJson(json, JsonElement.class).getAsJsonObject();

        String block_height = jsonObject.get("block_height").getAsString();
        String total = jsonObject.get("total").getAsString();
        String fee = jsonObject.get("fee").getAsString();
        String size = jsonObject.get("size").getAsString();
        String received = jsonObject.get("received").getAsString();
        String confirmations = jsonObject.get("confirmations").getAsString();

        showalert(TxsHashs,received);
}
</code>```

Title: Parsing a Json to a ListView

Body:
I have this json form this URL: Website Here

The problem is that I'm trying to retrieve some of the data in the JSON like:  block_height, total, fees and size. I have 2 days trying to make it work but I have no idea why my code is not working. The last I've tried was showing the data in a alert dialog. But this isn't working yet.

JSON:

{
  "block_hash": "0000000000000397a165d83cc4640321a3b8ff4cce1f8aa2570deabf14ac14e7",
  "block_height": 154598,
  "block_index": 63,
  "hash": "b6f6991d03df0e2e04dafffcd6bc418aac66049e2cd74b80f14ac86db1e3f0da",
  "addresses": [
    "13AMPUTTwryLGX3nrMvumaerSqNXkL3gEV",
    "14pDqB95GWLWCjFxM4t96H2kXH7QMKSsgG",
    "1FwYmGEjXhMtxpWDpUXwLx7ndLNfFQncKq"
  ],
  "total": 100000000,
  "fees": 0,
  "size": 258,
  "preference": "low",
  "confirmed": "2011-11-24T11:45:54Z",
  "received": "2011-11-24T11:45:54Z",
  "ver": 1,
  "double_spend": false,
  "vin_sz": 1,
  "vout_sz": 2,
  "confirmations": 339633,
  "confidence": 1,
  "inputs": [
    {
      "prev_hash": "9fa4e0e33aba41623bc3618827d2a6495e6828ce04f26c97771a1369210e8201",
      "output_index": 2,
      "script": "48304502210098a2851420e4daba656fd79cb60cb565bd7218b6b117fda9a512ffbf17f8f178022005c61f31fef3ce3f906eb672e05b65f506045a65a80431b5eaf28e0999266993014104f0f86fa57c424deb160d0fc7693f13fce5ed6542c29483c51953e4fa87ebf247487ed79b1ddcf3de66b182217fcaf3fcef3fcb44737eb93b1fcb8927ebecea26",
      "output_value": 100000000,
      "sequence": 4294967295,
      "addresses": [
        "1FwYmGEjXhMtxpWDpUXwLx7ndLNfFQncKq"
      ],
      "script_type": "pay-to-pubkey-hash",
      "age": 154567
    }
  ],
  "outputs": [
    {
      "value": 98000000,
      "script": "76a91429d6a3540acfa0a950bef2bfdc75cd51c24390fd88ac",
      "spent_by": "df0f8a4f0988de2875705a79ec826c8b9f8b08c9ffa4e5b4a5ea1b7bf956306c",
      "addresses": [
        "14pDqB95GWLWCjFxM4t96H2kXH7QMKSsgG"
      ],
      "script_type": "pay-to-pubkey-hash"
    },
    {
      "value": 2000000,
      "script": "76a91417b5038a413f5c5ee288caa64cfab35a0c01914e88ac",
      "spent_by": "0c45329983279acf2f9e9c7976774ef11bdb2646d934836c53e6679281e09ac8",
      "addresses": [
        "13AMPUTTwryLGX3nrMvumaerSqNXkL3gEV"
      ],
      "script_type": "pay-to-pubkey-hash"
    }
  ]
}

JAVA - Android Studio Fragment

 private void setUpData() {
        // Retrieve the city data from the web service
        // In a worker thread since it's a network operation.
        new Thread(new Runnable() {
            public void run() {
                try {
                    retrieveData();
                } catch (IOException e) {
                    Log.e(LOG_TAG, "Cannot retrive Data", e);
                    return;
                }
            }
        }).start();
    }

    protected void retrieveData() throws IOException {
        HttpURLConnection conn = null;
        final StringBuilder json = new StringBuilder();
        try {
            // Connect to the web service
            URL url = new URL("https://api.blockcypher.com/v1/btc/main/txs/"+TxsHashs);
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(conn.getInputStream());

            // Read the JSON data into the StringBuilder
            int read;
            char[] buff = new char[1024];
            while ((read = in.read(buff)) != -1) {
                json.append(buff, 0, read);
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, "Error connecting to service", e);
            throw new IOException("Error connecting to service", e);
        }
        // Create markers for the city data.
        // Must run this on the UI thread since it's a UI operation.

        getActivity().runOnUiThread(new Runnable() {
            public void run() {
                try {
                    DataAdapter(json.toString());
                } catch (Exception e) {
                    Log.e(LOG_TAG, "Error processing JSON", e);
                }
            }
        });
    }

    private void DataAdapter(String json)
    {
        try
        {
            JSONObject jsonObject = new JSONObject(json);
            String block_height = jsonObject.getString("block_height");
            String total = jsonObject.getString("total");
            String fee = jsonObject.getString("fee");
            String size = jsonObject.getString("size");
            String received = jsonObject.getString("received");
            String confirmations = jsonObject.getString("confirmations");

            showalert(TxsHashs,received);
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }

    }

 private void showalert(String title, String msj)
    {
        AlertDialog.Builder MSGbox = new AlertDialog.Builder(getActivity());
        MSGbox.setTitle(title);
        String mensaje = msj;
        MSGbox.setMessage(mensaje)
                .setPositiveButton("OKEY", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
        AlertDialog alertDialog = MSGbox.create();
        alertDialog.show();
    }

Please, someone Help Me

Body:
Try below code if you are using Gson library

private void DataAdapter(String json)
{
        JsonObject jsonObject = gson.fromJson(json, JsonElement.class).getAsJsonObject();

        String block_height = jsonObject.get("block_height").getAsString();
        String total = jsonObject.get("total").getAsString();
        String fee = jsonObject.get("fee").getAsString();
        String size = jsonObject.get("size").getAsString();
        String received = jsonObject.get("received").getAsString();
        String confirmations = jsonObject.get("confirmations").getAsString();

        showalert(TxsHashs,received);
}


问:
PHP Startup: Unable to load dynamic library php_curl.dll
I am having trouble getting cURL working on one of my servers. I have others set up exactly like this and they are working. Here is the error message in the system log:

PHP Fatal error:  Call to undefined function curl_init()

PHP Warning:  PHP Startup: Unable to load dynamic library 'C:\php\ext\php_curl.dll' - The specified module could not be found. in Unknown on line 0

I've been researching this all day and nothing has worked. Here's the current state of the server:

php.ini is in C:\php\

php_curl.dll is in C:\php\ext\

libeay32.dll and ssleay32.dll are in C:\php\

extension=php_curl.dll is uncommented in php.ini

Environment variable PATH = %SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C\php;C:\php\ext;C:\Apache24\bin

phpinfo() shows that C:\php\php.ini is the config file being used

php.ini extension_dir = "C:\php\ext"

Apache is from here

PHP is from here

OS is Windows Server 2008 R2 Datacenter

I've restarted several times. Other extensions are loading from the extension directory. I've also tried re-downloading the PHP zip file and replacing C:\php with the contents of the freshly downloaded zip file. I had this problem on a different server a while back when I was updating PHP and Apache. Replacing C:\php with a new copy of the zip file did fix it, but it is not helping now.

I will be happy to provide any additional information you may need.

Thanks.

phpinfo() configure command

cscript /nologo configure.js "--enable-snapshot-build" "--disable-isapi" "--enable-debug-pack" "--without-mssql" "--without-pdo-mssql" "--without-pi3web" "--with-pdo-oci=c:\php-sdk\oracle\x86\instantclient_12_1\sdk,shared" "--with-oci8-12c=c:\php-sdk\oracle\x86\instantclient_12_1\sdk,shared" "--enable-object-out-dir=../obj/" "--enable-com-dotnet=shared" "--with-mcrypt=static" "--without-analyzer" "--with-pgo".

答:
Unable to load dynamic library 'C:\php\ext\php_curl.dll'

correct answer should workable as environment path for c:\php is missed . so just add

In Control Panel -> Search -> Advanced System Settings and use the button Environment Variables.

Under System Variables find Path add the c:\php folder (or whatever path) and restart Apache.


问:
How to get links from html using regex
Some content was spammed with external links
How do you select both url tag and text in regex

example

```<code>This is a legit content. It was Created by the admin
</code>```

After Spam

```<code>This is a legit <a href="http://www.fakesite.com">Buy shoes</a> content. It was Created by <a href="http://www.veryfakesite.com">Buy Really nice shoes </a> the admin
</code>```

in this case i want to highlight and wipe it so the original content remains

```<code>This is a legit content. It was Created by the admin
</code>```

答:
Depending on the regex engine/tool you are using, the following find and replacement should work:

Find:

```<code>\s*<a href[^>]*>.*?</a>\s*
</code>```

Replace:

```<code>(a single space)
</code>```

This should get you fairly close to what you want.  In addition to matching each anchor spam tag, I also pull in all whitespace on either side, and then replace the entire pattern match with just a single space.

Demo

Title: How to get links from html using regex

Body:
Some content was spammed with external links
How do you select both url tag and text in regex

example

This is a legit content. It was Created by the admin

After Spam

This is a legit Buy shoes content. It was Created by Buy Really nice shoes  the admin

in this case i want to highlight and wipe it so the original content remains

This is a legit content. It was Created by the admin

Body:
Depending on the regex engine/tool you are using, the following find and replacement should work:

Find:

\s*<a href[^>]*>.*?</a>\s*

Replace:

(a single space)

This should get you fairly close to what you want.  In addition to matching each anchor spam tag, I also pull in all whitespace on either side, and then replace the entire pattern match with just a single space.

Demo


问:
HttpWebRequest Timeouts After Ten Consecutive Requests
I'm writing a web crawler for a specific site. The application is a VB.Net Windows Forms application that is not using multiple threads - each web request is consecutive. However, after ten successful page retrievals every successive request times out.

I have reviewed the similar questions already posted here on SO, and have implemented the recommended techniques into my GetPage routine, shown below:

```<code>Public Function GetPage(ByVal url As String) As String
    Dim result As String = String.Empty

    Dim uri As New Uri(url)
    Dim sp As ServicePoint = ServicePointManager.FindServicePoint(uri)
    sp.ConnectionLimit = 100

    Dim request As HttpWebRequest = WebRequest.Create(uri)
    request.KeepAlive = False
    request.Timeout = 15000

    Try
        Using response As HttpWebResponse = DirectCast(request.GetResponse, HttpWebResponse)
            Using dataStream As Stream = response.GetResponseStream()
                Using reader As New StreamReader(dataStream)
                    If response.StatusCode <> HttpStatusCode.OK Then
                        Throw New Exception("Got response status code: " + response.StatusCode)
                    End If
                    result = reader.ReadToEnd()
                End Using
            End Using
            response.Close()
        End Using

    Catch ex As Exception
        Dim msg As String = "Error reading page """ & url & """. " & ex.Message
        Logger.LogMessage(msg, LogOutputLevel.Diagnostics)
    End Try

    Return result

End Function
</code>```

Have I missed something? Am I not closing or disposing of an object that should be? It seems strange that it always happens after ten consecutive requests.

Notes:

In the constructor for the class in which this method resides I have the following:

ServicePointManager.DefaultConnectionLimit = 100

If I set KeepAlive to true, the timeouts begin after five requests.

All the requests are for pages in the same domain.

EDIT

I added a delay between each web request of between two and seven seconds so that I do not appear to be "hammering" the site or attempting a DOS attack. However, the problem still occurs.

答:
myRequest.Connection = "Close";
will make the server close the connection which will make the connection manager close the connection too.</p>

Body:
I'm writing a web crawler for a specific site. The application is a VB.Net Windows Forms application that is not using multiple threads - each web request is consecutive. However, after ten successful page retrievals every successive request times out.

I have reviewed the similar questions already posted here on SO, and have implemented the recommended techniques into my GetPage routine, shown below:

Public Function GetPage(ByVal url As String) As String
    Dim result As String = String.Empty

    Dim uri As New Uri(url)
    Dim sp As ServicePoint = ServicePointManager.FindServicePoint(uri)
    sp.ConnectionLimit = 100

    Dim request As HttpWebRequest = WebRequest.Create(uri)
    request.KeepAlive = False
    request.Timeout = 15000

    Try
        Using response As HttpWebResponse = DirectCast(request.GetResponse, HttpWebResponse)
            Using dataStream As Stream = response.GetResponseStream()
                Using reader As New StreamReader(dataStream)
                    If response.StatusCode <> HttpStatusCode.OK Then
                        Throw New Exception("Got response status code: " + response.StatusCode)
                    End If
                    result = reader.ReadToEnd()
                End Using
            End Using
            response.Close()
        End Using

    Catch ex As Exception
        Dim msg As String = "Error reading page """ & url & """. " & ex.Message
        Logger.LogMessage(msg, LogOutputLevel.Diagnostics)
    End Try

    Return result

End Function

Have I missed something? Am I not closing or disposing of an object that should be? It seems strange that it always happens after ten consecutive requests.

Notes:

In the constructor for the class in which this method resides I have the following:

ServicePointManager.DefaultConnectionLimit = 100

If I set KeepAlive to true, the timeouts begin after five requests.

All the requests are for pages in the same domain.

EDIT

I added a delay between each web request of between two and seven seconds so that I do not appear to be "hammering" the site or attempting a DOS attack. However, the problem still occurs.


问:
HttpClientJava GET JSON not working properly
I'm trying to connect to my server by HTTP and obtain a JSON object, but it seems that I can't do it.

Here's my code:

```<code>import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class Conector {

    public static void main(String[] args) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet("https://falseweb/select_all.php");
            CloseableHttpResponse response1 = httpclient.execute(httpGet);

            try {
                System.out.println(response1.getStatusLine());
                HttpEntity entity1 = response1.getEntity();
                System.out.println(entity1.getContentEncoding());
                EntityUtils.consume(entity1);
            } finally {
                response1.close();
            }

        } finally {
            httpclient.close();
        }
    }

}
</code>```

But instead of the JSON I get a printed null. I already tried the php file and it works, returning a json. Any idea what I'm doing wrong?.

The connection works because i got this message :

```<code> HTTP/1.1 200 OK
</code>```

答:
You seem to be logging out the content encoding as opposed to the actual content of the response which is probably why you aren't having any JSON joy.

Give the following a go (using Apache Commons IOUtils) :

```<code>System.out.println(IOUtils.toString(entity1.getContent(), "UTF8"));
</code>```

If you can't use IOUtils then you can use any method of converting the InputStream into a String. More on that here.

Body:
I'm trying to connect to my server by HTTP and obtain a JSON object, but it seems that I can't do it.

Here's my code:

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class Conector {

    public static void main(String[] args) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet("https://falseweb/select_all.php");
            CloseableHttpResponse response1 = httpclient.execute(httpGet);

            try {
                System.out.println(response1.getStatusLine());
                HttpEntity entity1 = response1.getEntity();
                System.out.println(entity1.getContentEncoding());
                EntityUtils.consume(entity1);
            } finally {
                response1.close();
            }

        } finally {
            httpclient.close();
        }
    }

}

But instead of the JSON I get a printed null. I already tried the php file and it works, returning a json. Any idea what I'm doing wrong?.

The connection works because i got this message :

 HTTP/1.1 200 OK

Body:
You seem to be logging out the content encoding as opposed to the actual content of the response which is probably why you aren't having any JSON joy.

Give the following a go (using Apache Commons IOUtils) :

System.out.println(IOUtils.toString(entity1.getContent(), "UTF8"));

If you can't use IOUtils then you can use any method of converting the InputStream into a String. More on that here.


问:
HTML for list with dashes and custom font colour
I am finalising a Wordpress website, but my last challenge is to create a bullet list with dashes instead of dots - the dashes must also be in white to match the font colour.

I've tried a few answers here but nothing seems to work right!

Text and dashes must be white (as it's on a blue background)

– sustainable growth,

– increase profits,

– expand market share and

– improve efficiency

答:
You can use :before to display a hyphen.

ul {
  margin: 0;
}
ul.hyphen {
  list-style-type: none;
}
ul.hyphen > li {
  text-indent: -10px;
}
ul.hyphen > li:before {
  content: "-";
  text-indent: -10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Some text
<ul class="hyphen">
  <li>list 1</li>
  <li>list 2</li>
  <li>list 3</li>
</ul>
Last text</code>```

Body:
You can use :before to display a hyphen.

ul {
  margin: 0;
}
ul.hyphen {
  list-style-type: none;
}
ul.hyphen > li {
  text-indent: -10px;
}
ul.hyphen > li:before {
  content: "-";
  text-indent: -10px;
}

Some text
<ul class="hyphen">
  <li>list 1</li>
  <li>list 2</li>
  <li>list 3</li>
</ul>
Last text


问:
laravel 5.4 controller middleware construct not working
I have some code :

AController

```<code>class AController extends Controller
{

    public function __construct()
    {

        echo 'outside - AController';
        echo '<br/>';

        $this->middleware(function ($request, $next) {

            echo 'inside - AController';
            echo '<br/>';

            return $next($request);
        });

    }

    public function handle()
    {

        $B = new BController;
        if ( $B->check() ) {
            $controller = BController::class;
            $action = 'index';
        } else {
            $controller = BController::class;
            $action = 'nothing';
        }

        $container = app();
        $route = $container->make(Route::class);
        $controllerInstance = $container->make($controller);

        return (new ControllerDispatcher($container))->dispatch($route, $controllerInstance, $action);

    }

}
</code>```

BController

```<code>class BController extends Controller
{

    public function __construct()
    {

        echo 'outside - BController';
        echo '<br/>';

        $this->middleware(function ($request, $next) {

            echo 'inside - BController';
            echo '<br/>';

            return $next($request);
        });

    }

}
</code>```

When BController is called from AController, in the browser show :

outside - AController

inside - AController

outside - BController

why middleware in BController when called from AController not showing like this?

outside - AController

inside - AController

outside - BController

inside - BController

答:
use Middleware in route instead  of using construct in controller.
here is the laravel docs https://laravel.com/docs/5.5/middleware</p>

Body:
I have some code :

AController

class AController extends Controller
{

    public function __construct()
    {

        echo 'outside - AController';
        echo '
';

        $this->middleware(function ($request, $next) {

            echo 'inside - AController';
            echo '
';

            return $next($request);
        });

    }

    public function handle()
    {

        $B = new BController;
        if ( $B->check() ) {
            $controller = BController::class;
            $action = 'index';
        } else {
            $controller = BController::class;
            $action = 'nothing';
        }

        $container = app();
        $route = $container->make(Route::class);
        $controllerInstance = $container->make($controller);

        return (new ControllerDispatcher($container))->dispatch($route, $controllerInstance, $action);

    }

}

BController

class BController extends Controller
{

    public function __construct()
    {

        echo 'outside - BController';
        echo '
';

        $this->middleware(function ($request, $next) {

            echo 'inside - BController';
            echo '
';

            return $next($request);
        });

    }

}

When BController is called from AController, in the browser show :

outside - AController

inside - AController

outside - BController

why middleware in BController when called from AController not showing like this?

outside - AController

inside - AController

outside - BController

inside - BController


问:
Impala Dateformat error
I have input values of

```<code>161223000001
</code>```

I need to convert into

```<code>2016-12-23 00:00:01
</code>```

I tried

```<code>select cast(161223000001 as timestamp)
7078-12-14 22:40:01
</code>```

I am getting incorrect answers

答:
You can use the to_timestamp function to convert string to timestamp in Impala

```<code>SELECT to_timestamp('161223000001', 'yyMMddHHmmss');
</code>```

By using CAST AS TIMESTAMP in your original attempt, it recognizes the given string as a unix epoch time instead

Title: Impala Dateformat error

Body:
I have input values of

161223000001

I need to convert into

2016-12-23 00:00:01

I tried

select cast(161223000001 as timestamp)
7078-12-14 22:40:01

I am getting incorrect answers

Body:
You can use the to_timestamp function to convert string to timestamp in Impala

SELECT to_timestamp('161223000001', 'yyMMddHHmmss');

By using CAST AS TIMESTAMP in your original attempt, it recognizes the given string as a unix epoch time instead