问:
Update value of attribute with count condition requirement
I have a data query result from query

```<code>select count(type_of_vegetation)as count,type_of_vegetation
from tb_patrol
group by type_of_vegetation
</code>```

as shown below:

```<code>count | type of vegetation
1     | Semak Belukar, Pepohonan
2     | Pakis, Sawit, Senduduk
1     | Pakis, Sawit, Ilalang, Akasia
49    | Sawit
15    | Pakis, Karet
17    | Semak Belukar
</code>```

I'd like to update the value of "type of vegetation" which has value of count that is less than 15 into "Others" but with condition group by type of vegetation, as in the example below:

```<code>count | type of vegetation
1     | Others
2     | Others
1     | Others
49    | Sawit
15    | Pakis, Karet
17    | Semak Belukar
</code>```

I use postgres SQL.

答:
Use a subquery and IN operator:

```<code>UPDATE tb_patrol
SET type_of_vegetation = 'Other'
WHERE type_of_vegetation  IN (
   select type_of_vegetation
   from tb_patrol
   group by type_of_vegetation
   having count(type_of_vegetation) < 15
);
</code>```

Body:
I have a data query result from query

select count(type_of_vegetation)as count,type_of_vegetation
from tb_patrol
group by type_of_vegetation

as shown below:

count | type of vegetation
1     | Semak Belukar, Pepohonan
2     | Pakis, Sawit, Senduduk
1     | Pakis, Sawit, Ilalang, Akasia
49    | Sawit
15    | Pakis, Karet
17    | Semak Belukar

I'd like to update the value of "type of vegetation" which has value of count that is less than 15 into "Others" but with condition group by type of vegetation, as in the example below:

count | type of vegetation
1     | Others
2     | Others
1     | Others
49    | Sawit
15    | Pakis, Karet
17    | Semak Belukar

I use postgres SQL.

Body:
Use a subquery and IN operator:

UPDATE tb_patrol
SET type_of_vegetation = 'Other'
WHERE type_of_vegetation  IN (
   select type_of_vegetation
   from tb_patrol
   group by type_of_vegetation
   having count(type_of_vegetation) < 15
);


来源: stackexchange

问:
 within
I have made a simple fragment of html, which contains this:

```<code><a href="#"><div>Something here</div></a>
</code>```

It obviously alert me that div cannot be inside an  tag. I have used a div, because I want the whole box (div in this case) to be a button. So the subclass :hover and a proper button area applies to the whole box, not only a text inside. As far as I remember divs can be used inside  tags in html5. I use XHTML 1.0 Transitional. Is there anything I can replace a div with to avoid errors in the code? or should I change xhtml to html5? will it work good without touching the rest of the code? thank you.

答:
It is way more easier at least</p>

```<code>`<div onclik="window.location.href='url'">
</div>`
</code>```

ContentLicense: CC BY-SA 3.0

Title: <div> within <a>

Body:
I have made a simple fragment of html, which contains this:

Something here

It obviously alert me that div cannot be inside an  tag. I have used a div, because I want the whole box (div in this case) to be a button. So the subclass :hover and a proper button area applies to the whole box, not only a text inside. As far as I remember divs can be used inside  tags in html5. I use XHTML 1.0 Transitional. Is there anything I can replace a div with to avoid errors in the code? or should I change xhtml to html5? will it work good without touching the rest of the code? thank you.

Body:
It is way more easier at least

`<div onclik="window.location.href='url'">
</div>`


问:
How do I use a certain version (or higher) of a perl module in my perl script?
I'm using Term::ANSIColor in my Perl script to do colorization of terminal output, and I am using the colorstrip function, which was only added in Term::ANSIColor version 2.01, according to the changelog. So, is there a way to make my script automatically die with an appropriate error message if it doesn't find at least that version of Term::ANSIcolor?

答:
Simply specify the version you want to use:

```<code>use Some::Module 2.13;
</code>```

If the version is not at least 2.13, the operation will fail.

You can experiment with the version that is available on the command line:

```<code>perl -MSome::Module=9999 -e 'exit 0'
</code>```

This will usually die with the wrong version number shown in the error message (unless the module you're trying to use happens to have a 5 digit or longer version number, or unless the module is like strict and doesn't like being loaded via the command line with a version number or like URI (see the comments for details)).

```<code>$ perl -MFile::Find=999 -e 'exit 0'
File::Find version 999 required--this is only version 1.07 at
/usr/perl5/5.8.4/lib/Exporter/Heavy.pm line 121.
BEGIN failed--compilation aborted.
$ perl -e 'use File::Find 999; exit 0'
File::Find version 999 required--this is only version 1.07 at -e line 1.
BEGIN failed--compilation aborted at -e line 1.
$
</code>```

Run on a machine I don't normally use, hence the antiquated version of Perl.

Body:
Simply specify the version you want to use:

use Some::Module 2.13;

If the version is not at least 2.13, the operation will fail.

You can experiment with the version that is available on the command line:

perl -MSome::Module=9999 -e 'exit 0'

This will usually die with the wrong version number shown in the error message (unless the module you're trying to use happens to have a 5 digit or longer version number, or unless the module is like strict and doesn't like being loaded via the command line with a version number or like URI (see the comments for details)).

$ perl -MFile::Find=999 -e 'exit 0'
File::Find version 999 required--this is only version 1.07 at
/usr/perl5/5.8.4/lib/Exporter/Heavy.pm line 121.
BEGIN failed--compilation aborted.
$ perl -e 'use File::Find 999; exit 0'
File::Find version 999 required--this is only version 1.07 at -e line 1.
BEGIN failed--compilation aborted at -e line 1.
$

Run on a machine I don't normally use, hence the antiquated version of Perl.

ContentLicense: CC BY-SA 2.5


问:
Bootswatch / Bootstrap 4 dropdown and margin mistake
So I was playing around with the new Bootswatch based on Bootstrap 4 but somehow the "Cards" have no margin and the dropdown in the menu doesn't work. Can someone explain to me what I'm doing wrong here? Do I have to add the margin myself? And why doesn't the Dropdown work?

<!DOCTYPE html>

<link rel="stylesheet" href="https://bootswatch.com/4/cosmo/bootstrap.css">

  Navbar
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        Home (current)

        Features

            Dropdown

              Action
              Another action

Card title

Card subtitle

Some quick example text to build on the card title and make
up the bulk of the card's content.

    Card link
    Another link

```

答:
The card margin doesn't have anything to do with this. The problem is with the JS.

I changed tether and Bootstrap alpha 6 JS to PopperJs and Bootstrap beta 2 JS. (see the Bootstrap docs)

I also added the class mt-3 to the container for some margin. Keep that if you want.

<!DOCTYPE html>

  <link rel="stylesheet" href="https://bootswatch.com/4/cosmo/bootstrap.css">

      Navbar
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation">

  </button>

            Home (current)

            Features

          Dropdown link

              Action
              Another action
              Something else here

Card title

Card subtitle

Some quick example text to build on the card title and make
up the bulk of the card's content.

            Card link
            Another link

```

Body:
The card margin doesn't have anything to do with this. The problem is with the JS.

I changed tether and Bootstrap alpha 6 JS to PopperJs and Bootstrap beta 2 JS. (see the Bootstrap docs)

I also added the class mt-3 to the container for some margin. Keep that if you want.

<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="https://bootswatch.com/4/cosmo/bootstrap.css">
</head>

<body>

  <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
    <div class="container">
      <a class="navbar-brand" href="#">Navbar</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
      <div class="collapse navbar-collapse" id="navbarColor01">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item active">
            <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">Features</a>
          </li>
          <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Dropdown link
        </a>
            <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
              <a class="dropdown-item" href="#">Action</a>
              <a class="dropdown-item" href="#">Another action</a>
              <a class="dropdown-item" href="#">Something else here</a>
            </div>
          </li>
        </ul>
      </div>
    </div>
  </nav>

  <div class="container mt-3">
    <div class="row">
      <div class="col">
        <div class="card">
          <div class="card-body">
            <h4 class="card-title">Card title</h4>
            <h6 class="card-subtitle mb-2 text-muted">Card subtitle</h6>
            <p class="card-text">Some quick example text to build on the card title and make <br>up the bulk of the card's content.</p>
            <a href="#" class="card-link">Card link</a>
            <a href="#" class="card-link">Another link</a>
          </div>
        </div>
      </div>
    </div>
  </div>

  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</body>

</html>


问:
Css-Grid: Trouble defining grid rules
Using CSS Grid, I'm trying to create a layout that looks like this:

How do I place the bottom (smaller) elements beyond the first row without using nested elements? The number of smaller elements can be anything. I tried using grid-auto-columns: 2fr; to accomplish my task, but it does not work.

Here's what I've tried so far: Codepen

main {
  display: grid;
  padding: 10px 0 10px 10px;
  grid-template: 1fr/repeat(6, 1fr);
  grid-template-areas: "a a a b b b";
  grid-auto-columns: 2fr;
  grid-column-gap: 10px;
  grid-row-gap: 10px;
}

main .a {
  grid-area: a;
}

main .b {
  grid-area: b;
}

.cat {
  height: 150px;
  background-size: cover;
  background-position: center;
  overflow: hidden;
  position: relative;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  font-size: 20px;
  background-color: green;
  color: #fff;
}

.cat:hover {
  background-color: #004800;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
  <div class="cat a"></div>
  <div class="cat b"></div>
  <div class="cat c"></div>
  <div class="cat d"></div>
  <div class="cat e"></div>
  <div class="cat f"></div>
  <div class="cat g"></div>
  <div class="cat h"></div>
  <div class="cat i"></div>
</main></code>```

答:
The first thing I did is define how many columns the grid should be. Looking at your image, it made sense to me to go with 12 columns.

In the main element, I add the rule:

```<code>grid-template-columns: repeat(12, 1fr);
</code>```

In your .cat rules, I added a few things. By default, each block takes up 4/12 columns.

```<code>grid-column: span 4;
</code>```

The last part was dealing with the first two .cat blocks, a and b. No problem. They each take up 6/12 columns.

```<code> &.a,
 &.b {
   grid-column: span 6;
 }
</code>```

And that's it. Here's a working demo.

main {
  display: grid;
  padding: 10px 0 10px 10px;
  grid-template-columns: repeat(12, 1fr);
  grid-column-gap: 10px;
  grid-row-gap: 10px;
}

.cat {
  height: 150px;
  background-size: cover;
  background-position: center;
  overflow: hidden;
  position: relative;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  font-size: 20px;
  background-color: green;
  color: #fff;
  grid-column: span 4;
}

.cat:hover {
  background-color: #004800;
}

.cat.a,
.cat.b {
  grid-column: span 6;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
  <div class="cat a"></div>
  <div class="cat b"></div>
  <div class="cat c"></div>
  <div class="cat d"></div>
  <div class="cat e"></div>
  <div class="cat f"></div>
  <div class="cat g"></div>
  <div class="cat h"></div>
  <div class="cat i"></div>
</main></code>```

Title: Css-Grid: Trouble defining grid rules

Body:
The first thing I did is define how many columns the grid should be. Looking at your image, it made sense to me to go with 12 columns.

In the main element, I add the rule:

grid-template-columns: repeat(12, 1fr);

In your .cat rules, I added a few things. By default, each block takes up 4/12 columns.

grid-column: span 4;

The last part was dealing with the first two .cat blocks, a and b. No problem. They each take up 6/12 columns.

 &.a,
 &.b {
   grid-column: span 6;
 }

And that's it. Here's a working demo.

main {
  display: grid;
  padding: 10px 0 10px 10px;
  grid-template-columns: repeat(12, 1fr);
  grid-column-gap: 10px;
  grid-row-gap: 10px;
}

.cat {
  height: 150px;
  background-size: cover;
  background-position: center;
  overflow: hidden;
  position: relative;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  font-size: 20px;
  background-color: green;
  color: #fff;
  grid-column: span 4;
}

.cat:hover {
  background-color: #004800;
}

.cat.a,
.cat.b {
  grid-column: span 6;
}

<main>
  <div class="cat a"></div>
  <div class="cat b"></div>
  <div class="cat c"></div>
  <div class="cat d"></div>
  <div class="cat e"></div>
  <div class="cat f"></div>
  <div class="cat g"></div>
  <div class="cat h"></div>
  <div class="cat i"></div>
</main>


问:
PHP How to replace customers text area apostrophes with a escape character
I tried asking this question a week ago but got no answer. Hoping to explain it better this time.

My customer can input anything into a textarea and I am saving that to a MySQL table.

how can I replace all of their apostrophes with a double apostrophe so I don't get a bad query?

I tried the following it didn't work.

```<code>$description = str_replace("''", "'", $description);
</code>```

答:
Hi Landon have you tried this  'mysqli_real_escape_string' function ?

string mysqli_real_escape_string ( mysqli $link , string $escapestr )

exaple like below:

```<code>$link = mysqli_connect("localhost", "my_user", "my_password", "world");

$lastname  = "O'Reilly";
$_lastname =mysqli_real_escape_string($link, $lastname);
</code>```

http://us3.php.net/mysql-real-escape-string

Body:
I tried asking this question a week ago but got no answer. Hoping to explain it better this time.

My customer can input anything into a textarea and I am saving that to a MySQL table.

how can I replace all of their apostrophes with a double apostrophe so I don't get a bad query?

I tried the following it didn't work.

$description = str_replace("''", "'", $description);

Body:
Hi Landon have you tried this  'mysqli_real_escape_string' function ?

string mysqli_real_escape_string ( mysqli $link , string $escapestr )

exaple like below:

$link = mysqli_connect("localhost", "my_user", "my_password", "world");

$lastname  = "O'Reilly";
$_lastname =mysqli_real_escape_string($link, $lastname);

http://us3.php.net/mysql-real-escape-string


问:
HighChartTable.js yAxis integer Only
I am using highcharttable to build my graph, but if the input at yAxis is too small, they will use floating number which is i don't want, i want integer only, how to resolve this? so far i did something like this, but it's not working, it also caused because they lack of documentation for something like this</p>

```<code>$('table.highchart').highchartTable({
yAxis: {
  allowDecimals:false,
  labels: {
    style: {
      fontSize: '9px',
      width: '175px'
      }
    },
  }
});
</code>```

答:
Update your initialization

```<code>$(document).ready(function() {
  $('table.highchart')
    .bind('highchartTable.beforeRender', function(event, highChartConfig) {
      highChartConfig.yAxis = {
        allowDecimals: false,
        title: {
          text: 'Flats'
        }
      }
    })
    .highchartTable();
});
</code>```

Fiddle demo

Reference you can apply same logic for yAxis

Title: HighChartTable.js yAxis integer Only

Body:
I am using highcharttable to build my graph, but if the input at yAxis is too small, they will use floating number which is i don't want, i want integer only, how to resolve this? so far i did something like this, but it's not working, it also caused because they lack of documentation for something like this

$('table.highchart').highchartTable({
yAxis: {
  allowDecimals:false,
  labels: {
    style: {
      fontSize: '9px',
      width: '175px'
      }
    },
  }
});

Body:
Update your initialization

$(document).ready(function() {
  $('table.highchart')
    .bind('highchartTable.beforeRender', function(event, highChartConfig) {
      highChartConfig.yAxis = {
        allowDecimals: false,
        title: {
          text: 'Flats'
        }
      }
    })
    .highchartTable();
});

Fiddle demo

Reference you can apply same logic for yAxis


问:
How can I refresh the jupyter nbextensions SETTINGS on an existing jupyter notebook? New notebooks take on the new settings, but old notebooks don't
I use the Table of Contents (2) package from jupyter nbextensions. This package allows for a table of contents at the top of the document and/or a scalable table of contents panel on the left-hand-side, using the #/##/etc. lines in Markdown cells.

When I configure the extension to have the left-hand panel "off" and the header-table of contents "on" (using the GUI Nbextensions tab), new notebooks take on the new settings, but old notebooks keep the old settings. I've also verified that the new options appear in the main json file .jupyter/nbconfig/notebook.json.

How can I refresh old notebooks to these new Nbextension settings?

答:
This is not an ideal solution, but apparently this can be done by editing the notebook-specific .json metadata. This is under the Edit tab, option Edit Notebook Metadata -- just change the fields manually to match whatever is in your default settings in .jupyter/nbconfig/notebook.json.

Ideally, of course, this should be automated. Hoping someone knows how.


问:
Translating jQuery into Raw Javascript
I have some jQuery code that I would like to change to its raw JavaScript form, and I'm having trouble finding the corresponding elements that make up this jQuery code

```<code>$('.rain').append('<div class="drop" id="drop'+i+'"></div>');
$('#drop'+i).css('left',dropLeft);
$('#drop'+i).css('top',dropTop);
</code>```

I have no idea how to change it back to Javascript, and any help would be greatly appreciated!!

答:
```<code>const dropDiv = document.createElement('div')
dropDiv.className = 'drop'
dropDiv.id = 'drop' + i
dropDiv.style.left = dropLeft
dropDiv.style.top = dropTop
document.querySelector('.rain').appendChild(dropDiv)
</code>```

Title: Translating jQuery into Raw Javascript

Body:
I have some jQuery code that I would like to change to its raw JavaScript form, and I'm having trouble finding the corresponding elements that make up this jQuery code

$('.rain').append('

');
$('#drop'+i).css('left',dropLeft);
$('#drop'+i).css('top',dropTop);

I have no idea how to change it back to Javascript, and any help would be greatly appreciated!!


问:
Deleting from table using PHP and MySQL
Seem to be having an error trying to delete a tuble (usernames) from an SQL table using PHP/SQL queries. My current code is as follows:

```<code><html lang="en" >
<body>
<?php
        $conn = new mysqli('localhost', 'myUsername', 'myPassword', 'dbName') or die ('Cannot connect to db');

        $uname=$_POST['uname'];

        $conn->query("DELETE FROM Account WHERE username = $uname");

        echo '<script type="text/javascript">';
        echo 'alert("-ADMIN-\nRemoved user successfully!");';
        echo 'window.location.href = "admin.php";';
        echo '</script>';
?>
</body>
</html>
</code>```

This exact same code works to delete a post from a website from a differnt table but is not deleting user accounts by username. Any ideas?

答:
Checkout this solution

```<code><?php
$conn = new mysqli('localhost', 'myUsername', 'myPassword', 'dbName') or die ('Cannot connect to db');
 $stmt = $conn->prepare('DELETE FROM Account WHERE username = ?');
 $stmt->bind_param('s', $_POST['uname']);
 $stmt->execute();
</code>```

Title: Deleting from table using PHP and MySQL

Body:
Seem to be having an error trying to delete a tuble (usernames) from an SQL table using PHP/SQL queries. My current code is as follows:

<?php
        $conn = new mysqli('localhost', 'myUsername', 'myPassword', 'dbName') or die ('Cannot connect to db');

        $uname=$_POST['uname'];

        $conn->query("DELETE FROM Account WHERE username = $uname");

        echo '';
?>

This exact same code works to delete a post from a website from a differnt table but is not deleting user accounts by username. Any ideas?

Body:
Checkout this solution

<?php
$conn = new mysqli('localhost', 'myUsername', 'myPassword', 'dbName') or die ('Cannot connect to db');
 $stmt = $conn->prepare('DELETE FROM Account WHERE username = ?');
 $stmt->bind_param('s', $_POST['uname']);
 $stmt->execute();


问:
Counting occurrences of a character in String (consecutive as one)
I am trying to figure out how to count the occurrences of a certain character in String such that the consecutive occurrence is considered as one. Like in string "PPPPAPAAPP" the occurrence of P as 3 and A as 2.</p>

答:
If you have to cound only letters or e.g. limit range of ASCII, then you could avoid using Map:

```<code>public static void main(String... args) {
    int[] letters = calcLetterGroups("PPPPPAAPAP");
    printExistedLetterGroups(letters);
}

public static int[] calcLetterGroups(String str) {
    int[] arr = new int['Z' - 'A' + 1];
    char prv = '\0';

    for (char ch : str.toUpperCase().toCharArray()) {
        if (ch >= 'A' && ch <= 'Z' && prv != ch) {
            arr[ch - 'A']++;
            prv = ch;
        }
    }

    return arr;
}

public static void printExistedLetterGroups(int... letters) {
    for (char ch = 'A'; ch <= 'Z'; ch++)
        if (letters[ch - 'A'] > 0)
            System.out.printf("%s: %d\n", String.valueOf(ch), letters[ch - 'A']);
}
</code>```

Body:
If you have to cound only letters or e.g. limit range of ASCII, then you could avoid using Map:

public static void main(String... args) {
    int[] letters = calcLetterGroups("PPPPPAAPAP");
    printExistedLetterGroups(letters);
}

public static int[] calcLetterGroups(String str) {
    int[] arr = new int['Z' - 'A' + 1];
    char prv = '\0';

    for (char ch : str.toUpperCase().toCharArray()) {
        if (ch >= 'A' && ch <= 'Z' && prv != ch) {
            arr[ch - 'A']++;
            prv = ch;
        }
    }

    return arr;
}

public static void printExistedLetterGroups(int... letters) {
    for (char ch = 'A'; ch <= 'Z'; ch++)
        if (letters[ch - 'A'] > 0)
            System.out.printf("%s: %d\n", String.valueOf(ch), letters[ch - 'A']);
}


问:
Sql MAX DateTime and if clause?
My 2nd Sql question on SO today - I need to brush up my Sql skills!!!!

I have the following three tables....

Diary, Entry, and EntryType

A Diary can have many Entry(ies), each Entry is of a particular EntryType.

Entry has a created DateTime
EntryType has an Id, and SomeOtherValue (int)

EDIT

Sorry Chaps.  Thanks for response so far but I didn't explain it well enough; the requirements have changed a bit.....

I would like the Id of any Diary where its latest Entry that is greater than @lastDateTime AND EntryType.someOthervalue != 0 has a EntryType.someOthervalue == @someValue

Or to put it another way....For all those Entry rows with a created Date time > @lastDateTime, ignore the someOtherValues that equal 0, and if the top 1 left over has a someOtherValue = @someValue, return the Id of the diary!!!!

Does that make sense???  I'm not sure what I should be putting my MAX, WHERE, and HAVING (if anything at all!)

Thanks,

ETFairfax.

答:
Diary, Entry, and EntryType

```<code>SELECT
FROM
   Diary D
   CROSS APPLY (
      SELECT TOP 1 E.EntryID
      FROM
         Entry E
      WHERE
         D.DiaryID = E.DiaryID
         AND E.CreatedDatetime > @LastDateTime
         AND EXISTS (
            SELECT 1 FROM EntryType ET
            WHERE E.EntryTypeID = ET.EntryTypeID
            AND ET.SomeOtherValue <> 0 -- or = @SomeValue ?
         )
      ORDER BY CreatedDatetime DESC
   )
</code>```

An index in Entry on CreatedDatetime would be helpful, but either the table's clustered index should have DiaryID or the index should contain it as one of the indexed columns.

I presume the EntryTypeID table is small compared to the others, so it's most likely going to be a table scan anyway, so indexes won't help much. If your execution plan gets some high number of reads on the EntryType table, please let me know and we'll try to fix it. I'm hoping the engine is smart enough to realize this table is small and only hits it up once, and puts it on the left side of a LOOP join somewhere.

Please let me know how this goes and if it's not working right I'll tweak it. I'm sure we can get a really nicely-performing query going.

Title: Sql MAX DateTime and if clause?

Body:
Diary, Entry, and EntryType

SELECT
FROM
   Diary D
   CROSS APPLY (
      SELECT TOP 1 E.EntryID
      FROM
         Entry E
      WHERE
         D.DiaryID = E.DiaryID
         AND E.CreatedDatetime > @LastDateTime
         AND EXISTS (
            SELECT 1 FROM EntryType ET
            WHERE E.EntryTypeID = ET.EntryTypeID
            AND ET.SomeOtherValue <> 0 -- or = @SomeValue ?
         )
      ORDER BY CreatedDatetime DESC
   )

An index in Entry on CreatedDatetime would be helpful, but either the table's clustered index should have DiaryID or the index should contain it as one of the indexed columns.

I presume the EntryTypeID table is small compared to the others, so it's most likely going to be a table scan anyway, so indexes won't help much. If your execution plan gets some high number of reads on the EntryType table, please let me know and we'll try to fix it. I'm hoping the engine is smart enough to realize this table is small and only hits it up once, and puts it on the left side of a LOOP join somewhere.

Please let me know how this goes and if it's not working right I'll tweak it. I'm sure we can get a really nicely-performing query going.


问:
Python Selenium: Unable to click on a user name field
I am attempting to locate a user name field that does not have an ID or other locator that I can easily find using Selenium Web Driver.

Using Chrome's Inspect Element, the HTML for this object is as follows

```<code><div aria-hidden="true" style="cursor:text" data-bind="text: hintText, css: hintCss" class="placeholder">someone@example.com</div>
</code>```

What would be the best way to locate this page object?

Thanks

答:
First find out is your element is inside different frame. Find the  iframe, first switch to that, after which you will able to locate your user desired object by using any method like find_elemet_by_class_name or find_element_by_css_selector or by xpath.
For switching to frame try below code:

```<code>driver.switch_to.frame(driver.find_element_by_id("ID_OF_YOUR_FRAME"))
</code>```

You can take the reference from this link code also for searching elements:
"https://github.com/PrajinkyaPimpalghare/TimeSheet-Automation/blob/master/time_sheet_automation.py" Refer from line 94 to 108 for accessing elements in different way and also in different frame.

Body:
I am attempting to locate a user name field that does not have an ID or other locator that I can easily find using Selenium Web Driver.

Using Chrome's Inspect Element, the HTML for this object is as follows

someone@example.com

What would be the best way to locate this page object?

Thanks

Body:
First find out is your element is inside different frame. Find the  iframe, first switch to that, after which you will able to locate your user desired object by using any method like find_elemet_by_class_name or find_element_by_css_selector or by xpath.
For switching to frame try below code:

driver.switch_to.frame(driver.find_element_by_id("ID_OF_YOUR_FRAME"))

You can take the reference from this link code also for searching elements:
"https://github.com/PrajinkyaPimpalghare/TimeSheet-Automation/blob/master/time_sheet_automation.py" Refer from line 94 to 108 for accessing elements in different way and also in different frame.


答:
presumably $uname is a string and the column username is also a string so you need to quote the variable within the string

```<code>$conn->query("DELETE FROM Account WHERE username = '$uname'");
</code>```

This does however leave your code open to sql injection so you would be better using a prepared statement

```<code>$stmt=$conn->prepare("DELETE FROM Account WHERE username = ?" );
$stmt->bind_param('s', $uname );
$stmt->execute();
</code>```

Title: Deleting from table using PHP and MySQL

Body:
presumably $uname is a string and the column username is also a string so you need to quote the variable within the string

$conn->query("DELETE FROM Account WHERE username = '$uname'");

This does however leave your code open to sql injection so you would be better using a prepared statement

$stmt=$conn->prepare("DELETE FROM Account WHERE username = ?" );
$stmt->bind_param('s', $uname );
$stmt->execute();


问:
How can I match a dynamic route in the database?
I have a table like this:

```<code>// routes
+----+-----------------------------+
| id |           route             |
+----+-----------------------------+
| 1  | /tracking_code/expire/{id}  |
| 2  | /tracking_code/list         |
+----+-----------------------------+
</code>```

{} means a dynamic value. And I need to match the first row for this entry value: /tracking_code/expire/2. I guess I need to use regexp. Any idea how can I do that?

My current workaround is using LIKE clause like this:

```<code>SELECT * FROM routes WHERE route LIKE :entry%
</code>```

Also I should remove that number of the end of entry like /tracking_code/expire/.

Sadly my approach won't work for complicated routes like this: /tracking_code/expire/{id}/temp. Anyway, how should I use regexp for this?

答:
You can use RLIKE like this

```<code>SELECT * FROM routes WHERE route RLIKE '^.*[0-9]+.*$'
</code>```

to replace using regex i don't think this is possible, but there are some sneaky way, read this post here How to do a regular expression replace in MySQL?

MySql demo

Regex demo

Body:
I have a table like this:

// routes
+----+-----------------------------+
| id |           route             |
+----+-----------------------------+
| 1  | /tracking_code/expire/{id}  |
| 2  | /tracking_code/list         |
+----+-----------------------------+

{} means a dynamic value. And I need to match the first row for this entry value: /tracking_code/expire/2. I guess I need to use regexp. Any idea how can I do that?

My current workaround is using LIKE clause like this:

SELECT * FROM routes WHERE route LIKE :entry%

Also I should remove that number of the end of entry like /tracking_code/expire/.

Sadly my approach won't work for complicated routes like this: /tracking_code/expire/{id}/temp. Anyway, how should I use regexp for this?

Body:
You can use RLIKE like this

SELECT * FROM routes WHERE route RLIKE '^.*[0-9]+.*$'

to replace using regex i don't think this is possible, but there are some sneaky way, read this post here How to do a regular expression replace in MySQL?

MySql demo

Regex demo


问:
How to upload image on aws server using node
I am trying to upload the image on the AWS server using the multer using the following code:

```<code>//post request
var multer = require('multer');
var upload = multer({  dest: path.resolve('./public/uploads/'), });

/* POST saveblog router. */
router.post('/uploadMedia', upload.any(), function(req, res, next) {

 //console.log("res",res);
 console.log(req.body, 'Body');
 console.log(req.files, 'files');

  var myJSON = JSON.stringify(req.files[0].filename);
  console.log("file name "+myJSON);

  if (typeof myJSON != 'undefined'){
    var obj= new Object();
    obj.status=true;
    obj.message="File Uploaded Successfully";
    obj.type= req.files[0].mimetype;

    var fileExtensionArray=(req.files[0].mimetype).split("/");
    var fileExtension=fileExtensionArray[1];

    res.json(obj);
  }else {
     var obj= new Object();
     obj.status=false;
     obj.message="Error while uploading file try again";

     res.json(obj);
   }

  res.end();
});
</code>```

It is working fine on the local. But when I upload that code to the server and try to hit through the API. The server stops with following logs

```<code>Change detected on path public/uploads/b690b296bfde62eb8ff527328bc8b463 for app www - restarting
PM2        | Stopping app:www id:0
</code>```

As log says change detected but I am not able to find any image.

As I have searched on StackOverflow and google, I am not able to find tutorial or help to do the same.
I am getting help regarding the s3 but I don't want to upload on it.

Is it not possible to upload the image to AWS server like that and I have to use S3 or something wrong with my code?

Edit: Now I am able to get the image to the destination folder but still not able to return the response.

答:
You're likely running PM2 in Watch mode, which is a feature intended to be used in development, to restart your application upon changes to its files. This is not intended to be used in production.

To fix this, if you're starting pm2 from the cli use the option

--no-autorestart

or the yaml config;

autorestart: false

Body:
I am trying to upload the image on the AWS server using the multer using the following code:

//post request
var multer = require('multer');
var upload = multer({  dest: path.resolve('./public/uploads/'), });

/* POST saveblog router. */
router.post('/uploadMedia', upload.any(), function(req, res, next) {

 //console.log("res",res);
 console.log(req.body, 'Body');
 console.log(req.files, 'files');

  var myJSON = JSON.stringify(req.files[0].filename);
  console.log("file name "+myJSON);

  if (typeof myJSON != 'undefined'){
    var obj= new Object();
    obj.status=true;
    obj.message="File Uploaded Successfully";
    obj.type= req.files[0].mimetype;

    var fileExtensionArray=(req.files[0].mimetype).split("/");
    var fileExtension=fileExtensionArray[1];

    res.json(obj);
  }else {
     var obj= new Object();
     obj.status=false;
     obj.message="Error while uploading file try again";

     res.json(obj);
   }

  res.end();
});

It is working fine on the local. But when I upload that code to the server and try to hit through the API. The server stops with following logs

Change detected on path public/uploads/b690b296bfde62eb8ff527328bc8b463 for app www - restarting
PM2        | Stopping app:www id:0

As log says change detected but I am not able to find any image.

As I have searched on StackOverflow and google, I am not able to find tutorial or help to do the same.
I am getting help regarding the s3 but I don't want to upload on it.

Is it not possible to upload the image to AWS server like that and I have to use S3 or something wrong with my code?

Edit: Now I am able to get the image to the destination folder but still not able to return the response.


问:
Keep :hover color on mouse click via Jquery
What I want to achieve is when users clicks on a link is for the button clicked to stay the color and not fade out when the mouse moves out of hover state.

If possible only one button receive the click color at a time.

Any help is appreciated! There is a link to JS Fiddle at the bottom.

HTML

```<code><ul>
<li><a href="#" class="slide">1</a></li>
<li><a href="#" class="slide">2</a></li>
<li><a href="#" class="slide">3</a></li>
<li><a href="#" class="slide">4</a></li>
</ul>
</code>```

CSS

```<code>.slide {
  padding:20px 20px 20px 20px;
  margin:20px;
  background-color:#999;
 }

ul li {
  float:left;
 }
</code>```

Jquery

```<code>$('.slide').click(function() {
    $(this).css("background-color", "#f09");
});

$('.slide').hover(function() {

    $(this).animate({
        backgroundColor: '#000'
    }, 300);

}, function() {
    $(this).animate({
        backgroundColor: '#999'
    }, 200);

});
</code>```

JS Fiddle Link

http://jsfiddle.net/coltanious/wNTs7/9/

答:
This version for on mouse over:

http://jsfiddle.net/L2hy67ga/1/

JS:

```<code>    $('.line1 ul li > a').mouseover(function() {
       $(this).attr('keephover','yes');
       $('.line1 li > a').each(function(){
          if($(this).attr('keephover')=='yes'){
              $(this).css('background-color', '#3399CC');
          } else {
              $(this).css('background-color', '#fff');
          }
          $(this).attr('keephover','');
       });
    });
</code>```

HTML:

```<code><div class="col-md-3 col-sm-3 line1">
<ul><li>
<a href="/a">URL A</a>
</li><li>
<a href="/b">URL A</a>
</li><li>
<a href="/c">URL C</a>
</li><li>
<a href="/d">URL D</a>
</li>
</ul>
</div>
</code>```

Body:
What I want to achieve is when users clicks on a link is for the button clicked to stay the color and not fade out when the mouse moves out of hover state.

If possible only one button receive the click color at a time.

Any help is appreciated! There is a link to JS Fiddle at the bottom.

HTML

1

2

3

4

CSS

.slide {
  padding:20px 20px 20px 20px;
  margin:20px;
  background-color:#999;
 }

ul li {
  float:left;
 }

Jquery

$('.slide').click(function() {
    $(this).css("background-color", "#f09");
});

$('.slide').hover(function() {

    $(this).animate({
        backgroundColor: '#000'
    }, 300);

}, function() {
    $(this).animate({
        backgroundColor: '#999'
    }, 200);

});

JS Fiddle Link

http://jsfiddle.net/coltanious/wNTs7/9/

Body:
This version for on mouse over:

http://jsfiddle.net/L2hy67ga/1/

JS:

    $('.line1 ul li > a').mouseover(function() {
       $(this).attr('keephover','yes');
       $('.line1 li > a').each(function(){
          if($(this).attr('keephover')=='yes'){
              $(this).css('background-color', '#3399CC');
          } else {
              $(this).css('background-color', '#fff');
          }
          $(this).attr('keephover','');
       });
    });

HTML:

<div class="col-md-3 col-sm-3 line1">
<ul><li>
<a href="/a">URL A</a>
</li><li>
<a href="/b">URL A</a>
</li><li>
<a href="/c">URL C</a>
</li><li>
<a href="/d">URL D</a>
</li>
</ul>
</div>


问:
Node js authentication in cross domain
I am working on a MEAN application, I am using Angular 4 for my project. For authentication, I have implemented the Passport js Local-strategy. And I am maintaining persistent session using Express-session. Things are working fine till here.

The Problem

In the same domain session works fine and I am able to authenticate the user. But in cross-domain, I am not able to maintain the session. It generates a new session id for each new request in cross-domain.

I then tried Passport-jwt but the problem with it is I don't have the control over user session. I mean I can't logout the user from the server if he is inactive or even on server re-start also the token don't get invalid.

So in simple words, I am looking for an authentication solution in Node js (Express js) in which I can manage authentication in cross-domain.

I have already seen some blog post and SO questions like this, but it doesn't help.

Thank you.

EDIT

Should I write my own code to achieve this? If so I have a plan.

My basic plan is:

The user will send credentials with the login request.

I will check for the credentials in the database. If credentials are valid, I will generate a random token and save it to the database, in the user table and the same token I will provide to the user with success response.

Now, with each request user will send the token and I will check the token for each request in the database. If the token is valid then I will allow the user to access the API otherwise I will generate an error with 401 status code.

I am using Mongoose (MongoDB) so I will be ok to check the token in each request (performance point of view).

I think this is also a good idea. I just want some suggestions, whether I am thinking in right direction or not.

What I will get with this:

The number of logged in user in the application (active sessions).

I can logout a user if he is idle for a certain interval of time.

I can manage multiple login session of the same user (by doing an entry in the database).

I can allow the end user to clear all other login sessions (like Facebook and Gmail offers).

Any customization related to authorization.

EDIT 2

Here I am shareing my app.js code

```<code>var express = require('express');
var helmet = require('helmet');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var dotenv = require('dotenv');
var env = dotenv.load();
var mongoose = require('mongoose');
var passport = require('passport');
var flash    = require('connect-flash');
var session      = require('express-session');
var cors = require('cors');

var databaseUrl = require('./config/database.js')[process.env.NODE_ENV || 'development'];
// configuration
mongoose.connect(databaseUrl); // connect to our database

var app = express();

// app.use(helmet());

// required for passport

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Origin', req.headers.origin);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
  if ('OPTIONS' == req.method) {
       res.send(200);
   } else {
       next();
   }
});

app.use(cookieParser());

app.use(session({
    secret: 'ilovescotchscotchyscotchscotch', // session secret
    resave: true,
    saveUninitialized: true,
    name: 'Session-Id',
    cookie: {
      secure: false,
      httpOnly: false
    }
}));

require('./config/passport')(passport); // pass passport for configuration

var index = require('./routes/index');
var users = require('./routes/user.route');
var seeders = require('./routes/seeder.route');
var branches = require('./routes/branch.route');
var companies = require('./routes/company.route');
var dashboard = require('./routes/dashboard.route');
var navigation = require('./routes/navigation.route');
var roles = require('./routes/role.route');
var services = require('./routes/services.route');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

require('./routes/auth.route')(app, passport);
app.use('/', index);
app.use('/users', users);
app.use('/seed', seeders);
app.use('/branches', branches);
app.use('/companies', companies);
app.use('/dashboard', dashboard);
app.use('/navigation', navigation);
app.use('/roles', roles);
app.use('/services', services);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  res.status(404).send({ status: 'NOT_FOUND', message: 'This resource is not available.'});
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  let errorObj = {
    status: 'INTERNAL_SERVER_ERROR',
    message: 'Something went wrong.',
    error: err.message
  };
  res.status(err.status || 500).send(errorObj);
});

module.exports = app;
</code>```

EDIT 3

For those who don't understand my problem. Explaining the problem in
  simple words:

My Express server is running on port 3000.

In order to consume any API from the server, a user must be logged in.

When a user gets logged in from localhost:3000, the server checks the credentials(using Passport-local) and returns a token in the response header.

Now after login, when a user hits any API from localhost:3000, a predefined Header comes with passport-session and then passport verifies the user session using req.isAuthenticated() and all the things works as expected.

When a user gets logged in from localhost:4000 and the server send a token in response header (same as localhost:3000).

When after successful login, the user hits any API from localhost:4000 the passport js function req.isAuthenticated() returns false.

This was happening because in cross-domain the cookie doesn't go to the server we need to set withCredentials header to true at the client side.

I have set withCredentials header to true but still at the server the req.isAuthenticated() is returning false.

答:
One possible solution to get around CORS/cookie/same-domain problems is to create proxy server that will mirror all requests from localhost:3000/api to localhost:4000, and then use localhost:3000/api to access the API instead of localhost:4000.

Best way for production deployment is to do it on your web server (nginx/apache).

You can also do it in node via express and request modules, or use some ready made middleware like this one:

https://github.com/villadora/express-http-proxy

Solution with this middleware is pretty straightforward:

```<code>var proxy = require('express-http-proxy');
var app = require('express')();

app.use('/api', proxy('localhost:4000'));
</code>```

Title: Node js authentication in cross domain

Body:
I am working on a MEAN application, I am using Angular 4 for my project. For authentication, I have implemented the Passport js Local-strategy. And I am maintaining persistent session using Express-session. Things are working fine till here.

The Problem

In the same domain session works fine and I am able to authenticate the user. But in cross-domain, I am not able to maintain the session. It generates a new session id for each new request in cross-domain.

I then tried Passport-jwt but the problem with it is I don't have the control over user session. I mean I can't logout the user from the server if he is inactive or even on server re-start also the token don't get invalid.

So in simple words, I am looking for an authentication solution in Node js (Express js) in which I can manage authentication in cross-domain.

I have already seen some blog post and SO questions like this, but it doesn't help.

Thank you.

EDIT

Should I write my own code to achieve this? If so I have a plan.

My basic plan is:

The user will send credentials with the login request.

I will check for the credentials in the database. If credentials are valid, I will generate a random token and save it to the database, in the user table and the same token I will provide to the user with success response.

Now, with each request user will send the token and I will check the token for each request in the database. If the token is valid then I will allow the user to access the API otherwise I will generate an error with 401 status code.

I am using Mongoose (MongoDB) so I will be ok to check the token in each request (performance point of view).

I think this is also a good idea. I just want some suggestions, whether I am thinking in right direction or not.

What I will get with this:

The number of logged in user in the application (active sessions).

I can logout a user if he is idle for a certain interval of time.

I can manage multiple login session of the same user (by doing an entry in the database).

I can allow the end user to clear all other login sessions (like Facebook and Gmail offers).

Any customization related to authorization.

EDIT 2

Here I am shareing my app.js code

var express = require('express');
var helmet = require('helmet');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var dotenv = require('dotenv');
var env = dotenv.load();
var mongoose = require('mongoose');
var passport = require('passport');
var flash    = require('connect-flash');
var session      = require('express-session');
var cors = require('cors');

var databaseUrl = require('./config/database.js')[process.env.NODE_ENV || 'development'];
// configuration
mongoose.connect(databaseUrl); // connect to our database

var app = express();

// app.use(helmet());

// required for passport

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Origin', req.headers.origin);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
  if ('OPTIONS' == req.method) {
       res.send(200);
   } else {
       next();
   }
});

app.use(cookieParser());

app.use(session({
    secret: 'ilovescotchscotchyscotchscotch', // session secret
    resave: true,
    saveUninitialized: true,
    name: 'Session-Id',
    cookie: {
      secure: false,
      httpOnly: false
    }
}));

require('./config/passport')(passport); // pass passport for configuration

var index = require('./routes/index');
var users = require('./routes/user.route');
var seeders = require('./routes/seeder.route');
var branches = require('./routes/branch.route');
var companies = require('./routes/company.route');
var dashboard = require('./routes/dashboard.route');
var navigation = require('./routes/navigation.route');
var roles = require('./routes/role.route');
var services = require('./routes/services.route');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

require('./routes/auth.route')(app, passport);
app.use('/', index);
app.use('/users', users);
app.use('/seed', seeders);
app.use('/branches', branches);
app.use('/companies', companies);
app.use('/dashboard', dashboard);
app.use('/navigation', navigation);
app.use('/roles', roles);
app.use('/services', services);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  res.status(404).send({ status: 'NOT_FOUND', message: 'This resource is not available.'});
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  let errorObj = {
    status: 'INTERNAL_SERVER_ERROR',
    message: 'Something went wrong.',
    error: err.message
  };
  res.status(err.status || 500).send(errorObj);
});

module.exports = app;

EDIT 3

For those who don't understand my problem. Explaining the problem in
  simple words:

My Express server is running on port 3000.

In order to consume any API from the server, a user must be logged in.

When a user gets logged in from localhost:3000, the server checks the credentials(using Passport-local) and returns a token in the response header.

Now after login, when a user hits any API from localhost:3000, a predefined Header comes with passport-session and then passport verifies the user session using req.isAuthenticated() and all the things works as expected.

When a user gets logged in from localhost:4000 and the server send a token in response header (same as localhost:3000).

When after successful login, the user hits any API from localhost:4000 the passport js function req.isAuthenticated() returns false.

This was happening because in cross-domain the cookie doesn't go to the server we need to set withCredentials header to true at the client side.

I have set withCredentials header to true but still at the server the req.isAuthenticated() is returning false.

Body:
One possible solution to get around CORS/cookie/same-domain problems is to create proxy server that will mirror all requests from localhost:3000/api to localhost:4000, and then use localhost:3000/api to access the API instead of localhost:4000.

Best way for production deployment is to do it on your web server (nginx/apache).

You can also do it in node via express and request modules, or use some ready made middleware like this one:

https://github.com/villadora/express-http-proxy

Solution with this middleware is pretty straightforward:

var proxy = require('express-http-proxy');
var app = require('express')();

app.use('/api', proxy('localhost:4000'));


问:
How to create modal type in Angular 4?
How to create model type for the below value (interface) in angular 4,

```<code>          [{ "id": "CC", "value": "Connect Orlando" },
           {"id": "CB", "value": "Connect Bengaluru"},
           {"id": "CS", "value": "Connect Mumbai" }]
</code>```

i tried something like below

```<code>export class DropdownModel {
    public options: DropdownOptionsModel[];
}

export class DropdownOptionsModel {
    public id: any;
    public value: any;
}
</code>```

but getting error "property option is missing" in the below line

```<code>this.mergedList= <DropdownModel> this.mergeValue(this.serviceCall.list1 ,this.serviceCall.list2 );

 private mergeValue(list1, list2) {
        let merged = [];
        for (let list of list1) {
            merged.push(list);
        }
        for (let list of list2) {
            merged.push(list);
        }
        return merged;
    }
</code>```

i was trying to merge two arrays and storing it inside mergedList variable.

答:
It should simply be this

```<code>export class DropdownOptionsModel {
    public id: any;
    public value: any;
}
</code>```

Your result is an array of DropdownOptionsModel => DropdownOptionsModel[]

What you're saying here is:

```<code>export class DropdownModel {
    public options: DropdownOptionsModel[];
}
</code>```

I have an object that has an options property that stores an array of { id, value }

Title: How to create modal type in Angular 4?

Body:
How to create model type for the below value (interface) in angular 4,

          [{ "id": "CC", "value": "Connect Orlando" },
           {"id": "CB", "value": "Connect Bengaluru"},
           {"id": "CS", "value": "Connect Mumbai" }]

i tried something like below

export class DropdownModel {
    public options: DropdownOptionsModel[];
}

export class DropdownOptionsModel {
    public id: any;
    public value: any;
}

but getting error "property option is missing" in the below line

this.mergedList= <DropdownModel> this.mergeValue(this.serviceCall.list1 ,this.serviceCall.list2 );

 private mergeValue(list1, list2) {
        let merged = [];
        for (let list of list1) {
            merged.push(list);
        }
        for (let list of list2) {
            merged.push(list);
        }
        return merged;
    }

i was trying to merge two arrays and storing it inside mergedList variable.

Body:
It should simply be this

export class DropdownOptionsModel {
    public id: any;
    public value: any;
}

Your result is an array of DropdownOptionsModel => DropdownOptionsModel[]

What you're saying here is:

export class DropdownModel {
    public options: DropdownOptionsModel[];
}

I have an object that has an options property that stores an array of { id, value }


问:
Problems parsing XML with XSL in it
When trying to read my xml from a webpage i get: "Error: At line 8, column 23: unbound prefix"
Below is my xml:

```<code><?xml version="1.0"?>
<outertag>
<innertag sampleattribute="innertagAttribute">
    <Retailer>
        RetailerName:
        <xsl:template match="link">
            <a href="LinkGoesHere">Link</a>
        </xsl:template>
    </Retailer>
</innertag>
</code>```

Any ideas as to what is wrong? Can I not use xsl:template within my xml? Any help is greatly appreciated.

答:
When trying to read my xml from a
  webpage i get: "Error: At line 8,
  column 23: unbound prefix" Below is my
  xml:

```<code><?xml version="1.0"?>
<outertag>
  <innertag sampleattribute="innertagAttribute">
      <Retailer>RetailerName:
          <xsl:template match="link">
              <a href="LinkGoesHere">Link</a>
          </xsl:template>
      </Retailer>
  </innertag>
</outertag>
</code>```

Any ideas as to what is wrong? Can I
  not use xsl:template within my xml?

The provided document is not well-formed and the error message very well says what is the reason:

There is an element named xsl:template, however there is no namespace declaration in the whole document that binds the prefix xsl: to any namespace.

Solution:

Correct the non-well-formed text to a well-formed XML document by providing a namespace declaration for the XSLT namespace:

```<code><outertag>
    <innertag sampleattribute="innertagAttribute">
        <Retailer>RetailerName:
            <xsl:template match="link"
             xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
                <a href="LinkGoesHere">Link</a>
            </xsl:template>
        </Retailer>
    </innertag>
</outertag>
</code>```

Title: Problems parsing XML with XSL in it

Body:
When trying to read my xml from a webpage i get: "Error: At line 8, column 23: unbound prefix"
Below is my xml:

<?xml version="1.0"?>
<outertag>
<innertag sampleattribute="innertagAttribute">
    <Retailer>
        RetailerName:
        <xsl:template match="link">
            Link
        </xsl:template>
    </Retailer>
</innertag>

Any ideas as to what is wrong? Can I not use xsl:template within my xml? Any help is greatly appreciated.

Body:
When trying to read my xml from a
  webpage i get: "Error: At line 8,
  column 23: unbound prefix" Below is my
  xml:

<?xml version="1.0"?>
<outertag>
  <innertag sampleattribute="innertagAttribute">
      <Retailer>RetailerName:
          <xsl:template match="link">
              <a href="LinkGoesHere">Link</a>
          </xsl:template>
      </Retailer>
  </innertag>
</outertag>

Any ideas as to what is wrong? Can I
  not use xsl:template within my xml?

The provided document is not well-formed and the error message very well says what is the reason:

There is an element named xsl:template, however there is no namespace declaration in the whole document that binds the prefix xsl: to any namespace.

Solution:

Correct the non-well-formed text to a well-formed XML document by providing a namespace declaration for the XSLT namespace:

<outertag>
    <innertag sampleattribute="innertagAttribute">
        <Retailer>RetailerName:
            <xsl:template match="link"
             xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
                <a href="LinkGoesHere">Link</a>
            </xsl:template>
        </Retailer>
    </innertag>
</outertag>


问:
Ancestor-or-self issue at top level
With the following XML, the top level is returning the nodes of all levels. There are no ancestors for the top level, so why am I getting it’s children?

```<code>XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<WBSs>
<WBS GUID="2">
<Name>work</Name>
<WBSs>
<WBS GUID="1">
<Name>Wall</Name>
<ParentWBS>2</ParentWBS>
</WBS>
<WBS GUID="2">
<Name>South Wall</Name>
<ParentWBS>2</ParentWBS>
</WBS>
<WBS GUID="3">
<Name>North Wall</Name>
<ParentWBS>2</ParentWBS>
</WBS>
</WBSs>
</WBS>
</WBSs>
</code>```

XPATH
Note: Apply template is on .//WBS

```<code><xsl:variable name="wbsCode" select=".//ancestor-or-self::WBS/@GUID[1]"/>
</code>```

Note: I have an xslt instruction immediately following the xpath expression to strinify the nodes and include ‘.’.

Result

2.1.2.3

2.1

2.2

2.3

Desired result

2

2.1

2.2

2.3

XSLT

```<code><xsl:variable name="WBS_ELEMENT_TABLE">
   <xsl:apply-templates select=".//WBS" mode="I_WBS_ELEMENT">
     <xsl:with-param name="ProjectId" select="$ProjectId"/>
   </xsl:apply-templates>
</xsl:variable>

<xsl:template match="WBS" mode="I_WBS_ELEMENT">
   <xsl:param name="ProjectId"/>

<xsl:variable name="wbsCode" select=".//ancestor-or-self::WBS/@GUID[1]"/>

<xsl:variable name="temp2" select="string-join(($wbsCode), '.')"/>

<WBS_ELEMENT>
    <xsl:value-of select="$temp2"/>
</WBS_ELEMENT>

</xsl:template>
</code>```

答:
// means /descendant-or-self::node()/, so //ancestor::* means ./descendant-or-self::node()/ancestor::x which finds all ancestors of all descendants, i.e. everything.

Get out of that habit of using // without thinking about what it means!

Title: Ancestor-or-self issue at top level

Body:
With the following XML, the top level is returning the nodes of all levels. There are no ancestors for the top level, so why am I getting it’s children?

XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<WBSs>
<WBS GUID="2">
<Name>work</Name>
<WBSs>
<WBS GUID="1">
<Name>Wall</Name>
<ParentWBS>2</ParentWBS>
</WBS>
<WBS GUID="2">
<Name>South Wall</Name>
<ParentWBS>2</ParentWBS>
</WBS>
<WBS GUID="3">
<Name>North Wall</Name>
<ParentWBS>2</ParentWBS>
</WBS>
</WBSs>
</WBS>
</WBSs>

XPATH
Note: Apply template is on .//WBS

<xsl:variable name="wbsCode" select=".//ancestor-or-self::WBS/@GUID[1]"/>

Note: I have an xslt instruction immediately following the xpath expression to strinify the nodes and include ‘.’.

Result

2.1.2.3

2.1

2.2

2.3

Desired result

2

2.1

2.2

2.3

XSLT

<xsl:variable name="WBS_ELEMENT_TABLE">
   <xsl:apply-templates select=".//WBS" mode="I_WBS_ELEMENT">
     <xsl:with-param name="ProjectId" select="$ProjectId"/>
   </xsl:apply-templates>
</xsl:variable>

<xsl:template match="WBS" mode="I_WBS_ELEMENT">
   <xsl:param name="ProjectId"/>

<xsl:variable name="wbsCode" select=".//ancestor-or-self::WBS/@GUID[1]"/>

<xsl:variable name="temp2" select="string-join(($wbsCode), '.')"/>

<WBS_ELEMENT>
    <xsl:value-of select="$temp2"/>
</WBS_ELEMENT>

</xsl:template>


问:
how to delete email address from table in phpmyadmin
I wanted to delete the email address of the customer in phpmyadmin, using php and html. The delete button is working, but it doesn't delete the email address at all.

I'm still new in learning php language. So, there might be some parts I might have done wrong.

I made 3 pages; account.php, deleteemail.php and delete.php

This is the php code for account.php

```<code><?php

        mysql_connect("localhost", "root","") or die(mysql_error());
        mysql_select_db("eib_clicks") or die("Cannot connect to database");
        $query = mysql_query("SELECT * FROM customer_ai WHERE username='$user' LIMIT 1");
        while($row = mysql_fetch_array($query))
        {
            Print "<tr>";

                Print '<td align="center">'. $row['username'] . "</td>";
                Print '<td align="center">'. $row['name'] . "</td>";
                Print '<td align="center">'. $row['address'] . "</td>";
                Print '<td align="center">'. $row['secondaddress'] . "</td>";
                Print '<td align="center"><a href="addaddress.php?username='. $row['username'] .'">add</a> </td>';
                Print '<td align="center">'. $row['email'] . "</td>";
                Print '<td align="center"><a href="editemail.php?username='. $row['username'] .'">edit</a> </td>';
                Print '<td align="center"><a href="deleteemail.php?username='. $row['username'] .'">delete</a> </td>';
                Print '<td align="center">'. $row['type'] . "</td>";
                Print '<td align="center">'. $row['public'] . "</td>";
                Print '<td align="center"><a href="editpublic.php?username='. $row['username'] .'">edit</a> </td>';
            Print "</tr>";
        }
    ?>
</code>```

This one works just fine.

Php code for deleteemail.php

```<code><?php
session_start();
if($_SESSION['user']){
}
else{
    header("location:account.php");
}
$user = $_SESSION['user'];
$id_exists = false;
?>
</code>```

Second part of the code;

```<code><?php

                mysql_connect("localhost", "root", "") or die(mysql_error());
                mysql_select_db("eib_clicks") or die("Cannot connect to database");
                $query = mysql_query("Select * from customer_ai Where username='$user'");
                $count = mysql_num_rows($query);
                if($count > 0)
                {
                    while($row = mysql_fetch_array($query))
                    {
                        Print "<tr>";
                            Print '<td align="center">'. $row['email'] . "</td>";

                        Print "</tr>";
                    }
                }

            ?>
</code>```

Third part of the code;

```<code><?php

        Print '
        <a href="delete.php" class="btn btn-sm btn-danger" role="button" onclick="myFunction('.$row['username'] .')">Delete</a>

        ';

        ?>
</code>```

I add script in this page too;

```<code><script>
    function myFunction(username)
    {
    var r=confirm("Are you sure you want to delete this email?");
    if(r==true)
        {
            window.location.assign("deleteemail.php?username=" + username);
        }
    }
</script>
</code>```

Lastly php code for delete.php

```<code><?php
    session_start();
    if($_SESSION['user']){
    }
    else{
        header("location:homepage.php");
    }

    if($_SERVER['REQUEST_METHOD'] == "GET")
    {
        mysql_connect("localhost", "root","") or die(mysql_error());
        mysql_select_db("eib_clicks") or die("Cannot connect to database");

        mysql_query("DELETE FROM account_ai WHERE $email=['email']");

        header("location: account.php");
    }
?>
</code>```

I tried everything on the delete.php but nothing works. The rest of the codes works fine. I used $row['id'] but it deletes the whole row. I only wanted to delete the email address not the whole row. Please help me.

This is how my customer_ai table looks like;

table for customer_ai

答:
in delete.php you could try like below:</p>

```<code>$email_address =!empty($_GET['username'])?$_GET['username']:false;

if($email_address){

    mysql_query("DELETE FROM account_ai WHERE email='{$email_address}'  ");
 }
</code>```

Body:
I wanted to delete the email address of the customer in phpmyadmin, using php and html. The delete button is working, but it doesn't delete the email address at all.

I'm still new in learning php language. So, there might be some parts I might have done wrong.

I made 3 pages; account.php, deleteemail.php and delete.php

This is the php code for account.php

<?php

        mysql_connect("localhost", "root","") or die(mysql_error());
        mysql_select_db("eib_clicks") or die("Cannot connect to database");
        $query = mysql_query("SELECT * FROM customer_ai WHERE username='$user' LIMIT 1");
        while($row = mysql_fetch_array($query))
        {
            Print "
";

                Print ''. $row['username'] . "	";
                Print ''. $row['name'] . "	";
                Print ''. $row['address'] . "	";
                Print ''. $row['secondaddress'] . "	";
                Print 'add 	';
                Print ''. $row['email'] . "	";
                Print 'edit 	';
                Print 'delete 	';
                Print ''. $row['type'] . "	";
                Print ''. $row['public'] . "	";
                Print 'edit 	';
            Print "
";
        }
    ?>

This one works just fine.

Php code for deleteemail.php

<?php
session_start();
if($_SESSION['user']){
}
else{
    header("location:account.php");
}
$user = $_SESSION['user'];
$id_exists = false;
?>

Second part of the code;

<?php

                mysql_connect("localhost", "root", "") or die(mysql_error());
                mysql_select_db("eib_clicks") or die("Cannot connect to database");
                $query = mysql_query("Select * from customer_ai Where username='$user'");
                $count = mysql_num_rows($query);
                if($count > 0)
                {
                    while($row = mysql_fetch_array($query))
                    {
                        Print "
";
                            Print ''. $row['email'] . "	";

                        Print "
";
                    }
                }

            ?>

Third part of the code;

<?php

        Print '
        Delete

        ';

        ?>

I add script in this page too;

Lastly php code for delete.php

<?php
    session_start();
    if($_SESSION['user']){
    }
    else{
        header("location:homepage.php");
    }

    if($_SERVER['REQUEST_METHOD'] == "GET")
    {
        mysql_connect("localhost", "root","") or die(mysql_error());
        mysql_select_db("eib_clicks") or die("Cannot connect to database");

        mysql_query("DELETE FROM account_ai WHERE $email=['email']");

        header("location: account.php");
    }
?>

I tried everything on the delete.php but nothing works. The rest of the codes works fine. I used $row['id'] but it deletes the whole row. I only wanted to delete the email address not the whole row. Please help me.

This is how my customer_ai table looks like;

table for customer_ai

Body:
in delete.php you could try like below:

$email_address =!empty($_GET['username'])?$_GET['username']:false;

if($email_address){

    mysql_query("DELETE FROM account_ai WHERE email='{$email_address}'  ");
 }


问:
AWS Lambda making video thumbnails
I want make thumbnails from videos uploaded to S3, I know how to make it with Node.js and ffmpeg.

According to this forum post I can add libraries:

ImageMagick is the only external library that is currently provided by
  default, but you can include any additional dependencies in the zip
  file you provide when you create a Lambda function. Note that if this
  is a native library or executable, you will need to ensure that it
  runs on Amazon Linux.

But how can I put static ffmpeg binary on aws lambda?

And how can I call from Node.js this static binary (ffmpeg) with AWS Lambda?

I'm newbie with amazon AWS and Linux

Can anyone help me?

答:
In order for the binary to be directly executable on AWS Lambda (without first having to copy to /tmp and chmod), you need to ensure the binary has executable permission when it is added to the ZIP file.

This is problematic on Windows because Windows doesn't recognize Linux binaries.  If you're using Windows 10, use the Ubuntu Bash shell to create the package.

I created a Node.js function template specifically for this purpose here.  It allows you to deploy one or more binaries to Lambda, then execute an arbitrary shell command and capture the output.

Title: AWS Lambda making video thumbnails


问:
Regex to capture the useragent from the citrix logs
Need help in capturing the user agent details from the citrix logs. The log format of the citrix is quite different for the successful and denied. The samples are given below

For Successful authentication the user agent details are enclosed within  "". Details are after the keyword Browser_type ""

For Denied traffic , useragent details are not present within the "". It is present after the keyword Browser

Denied

Dec  8 05:20:53 netscaler02  12/08/2017:05:20:53  netscaler02 0-PPE-0 : AAA LOGIN_FAILED -adasd92 0 :  User renju - Client_ip X.X.X.X - Failure_reason "External authentication server denied access" - Browser Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36

Success

Dec  8 05:54:06 netscaler02  12/08/2017:11:54:06 GMT netscaler02 0-PPE-0 : SSLVPN LOGIN -78342434122 0 : Context renjus@1X.X.X.X - SessionId: xxx- User renju - Client_ip X.X.X.X - Nat_ip "Mapped Ip" - Vserver X.X.X.X:443 - Browser_type "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36" - SSLVPN_asdasdat_type ICA - Group(s) "N/A"

I do have a regex to capture the browser agent within ""

(?P(?<=Browser_type\s\").?(?=\s(?:\w+=|\")))"

Bud need a regex that capture the user agent from all the format.

Thanks in advance.

答:
Got the initial push from The fourth bird and did some work around on it.

Browser((?:_type)?\s\"*)(?P(.+\"-|[^\"]+))


问:
I installed Android Studio 3.0.1 and created a blank project. I can't proceed because I receive the following:
Failed to resolve: junit:junit:4.12

I have attempted numerous solutions from the previous time this question was asked but none of them seem to be working. I tried deleting the entire line Failed to resolve: junit:junit:4.12.

my build.gradle top file:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        // Gradle 4.1 and higher include support for Google's Maven repo using
        // the google() method. And you need to include this repo to download
        // Android plugin 3.0.0 or higher.
        google()
        maven { url "https://maven.google.com" }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}
</code>```

my module app build.gradle

```<code>apply plugin: 'com.android.application'

repositories {
    maven { url "https://maven.google.com" }
    google()
}

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"
    defaultConfig {
        applicationId "ru.foodrobot.myapplication"
        minSdkVersion 17
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        //google()
        //jcenter()
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
</code>```

finally  this is what I have in my build.gradle app file:

```<code>apply plugin: 'com.android.application'

repositories {
    maven { url 'http://repo1.maven.org/maven2' }
    jcenter { url "http://jcenter.bintray.com/" }
}

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"

    defaultConfig {
        applicationId "com.example.application"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
    }
    buildTypes {

        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
}
</code>```

答:
In your build.gradle top file try replacing this part:

```<code>repositories {
        // Gradle 4.1 and higher include support for Google's Maven repo using
        // the google() method. And you need to include this repo to download
        // Android plugin 3.0.0 or higher.
        google()
        maven { url "https://maven.google.com" }
    }
</code>```

With this:

```<code>repositories {
        // Gradle 4.1 and higher include support for Google's Maven repo using
        // the google() method. And you need to include this repo to download
        // Android plugin 3.0.0 or higher.
        google()
        maven { url "http://repo1.maven.org/maven2" }
    }
</code>```

Body:
Failed to resolve: junit:junit:4.12

I have attempted numerous solutions from the previous time this question was asked but none of them seem to be working. I tried deleting the entire line Failed to resolve: junit:junit:4.12.

my build.gradle top file:

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        // Gradle 4.1 and higher include support for Google's Maven repo using
        // the google() method. And you need to include this repo to download
        // Android plugin 3.0.0 or higher.
        google()
        maven { url "https://maven.google.com" }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}

my module app build.gradle

apply plugin: 'com.android.application'

repositories {
    maven { url "https://maven.google.com" }
    google()
}

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"
    defaultConfig {
        applicationId "ru.foodrobot.myapplication"
        minSdkVersion 17
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        //google()
        //jcenter()
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

finally  this is what I have in my build.gradle app file:

apply plugin: 'com.android.application'

repositories {
    maven { url 'http://repo1.maven.org/maven2' }
    jcenter { url "http://jcenter.bintray.com/" }
}

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"

    defaultConfig {
        applicationId "com.example.application"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
    }
    buildTypes {

        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
}

Body:
In your build.gradle top file try replacing this part:

repositories {
        // Gradle 4.1 and higher include support for Google's Maven repo using
        // the google() method. And you need to include this repo to download
        // Android plugin 3.0.0 or higher.
        google()
        maven { url "https://maven.google.com" }
    }

With this:

repositories {
        // Gradle 4.1 and higher include support for Google's Maven repo using
        // the google() method. And you need to include this repo to download
        // Android plugin 3.0.0 or higher.
        google()
        maven { url "http://repo1.maven.org/maven2" }
    }


问:
ans ns =[(j, k) for j, k in (self.x_values, self.y_values) ] NameError: name 'self' is not defined
I want use pygal to paint random rambled points

and stored a svg file
  in  run.py i are try use loop , every loop 1 times make some data, and assignment a variables

my code:
random_walk.py

```<code>from random import choice
class RandomWalk():
    def __init__(self, num_points=10240):
        self.num_points = num_points
        self.x_values = [0]
        self.y_values = [0]

    def fill_walk(self):
        while len(self.x_values) < self.num_points:
            x_direction = choice([1, -1])
            x_distance = choice([0, 1, 2, 3, 4])
            x_step = x_direction * x_distance
            y_direction = choice([1, -1])
            y_distance = choice([0, 1, 2, 3, 4])
            y_step = y_direction * y_distance

            next_x = self.x_values[-1] + x_step
            next_y = self.y_values[-1] + y_step

            self.x_values.append(next_x)
            self.y_values.append(next_y)
</code>```

run.py

```<code>import pygal
from random_walk import RandomWalk

xy_sjmb = pygal.XY(stroke=False)
xy_sjmb.title = "random rambled"

a, b, c, d = [], [], [], []
all =[a, b, c, d]
for i in range(len(all)):
    rw = RandomWalk()
    rw.fill_walk()
    ns =[(j, k)  for j, k in (self.x_values, self.y_values) ]
    all[i-1] = ns

xy_sjmb.add('a', a)
xy_sjmb.add('b', b)
xy_sjmb.add('c', c)
xy_sjmb.add('d', d)
xy_sjmb.render_to_file('sjmb.svg')
</code>```

but have  error :
NameError: name 'self' is not defined

答:
Change ns =[(j, k)  for j, k in (self.x_values, self.y_values) ] to ns =[(j, k)  for j, k in (rw.x_values, rw.y_values) ].

self is used to refer to an object from inside that object. But externally you need to refer to the object with a variable that points to it.

Body:
I want use pygal to paint random rambled points

and stored a svg file
  in  run.py i are try use loop , every loop 1 times make some data, and assignment a variables

my code:
random_walk.py

from random import choice
class RandomWalk():
    def __init__(self, num_points=10240):
        self.num_points = num_points
        self.x_values = [0]
        self.y_values = [0]

    def fill_walk(self):
        while len(self.x_values) < self.num_points:
            x_direction = choice([1, -1])
            x_distance = choice([0, 1, 2, 3, 4])
            x_step = x_direction * x_distance
            y_direction = choice([1, -1])
            y_distance = choice([0, 1, 2, 3, 4])
            y_step = y_direction * y_distance

            next_x = self.x_values[-1] + x_step
            next_y = self.y_values[-1] + y_step

            self.x_values.append(next_x)
            self.y_values.append(next_y)

run.py

import pygal
from random_walk import RandomWalk

xy_sjmb = pygal.XY(stroke=False)
xy_sjmb.title = "random rambled"

a, b, c, d = [], [], [], []
all =[a, b, c, d]
for i in range(len(all)):
    rw = RandomWalk()
    rw.fill_walk()
    ns =[(j, k)  for j, k in (self.x_values, self.y_values) ]
    all[i-1] = ns

xy_sjmb.add('a', a)
xy_sjmb.add('b', b)
xy_sjmb.add('c', c)
xy_sjmb.add('d', d)
xy_sjmb.render_to_file('sjmb.svg')

but have  error :
NameError: name 'self' is not defined