问:
Dictionary different output than the trial site version

I try to use LIWC dictonary 2015 version in R.

A dummy text for text analysis:

```<code>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc
</code>```

I try this line:

```<code>library("LIWCalike")
library("quanteda")
 liwcalike(data_char_testphrases)
liwc2015dict <- dictionary(file = "~/Dropbox/QUANTESS/dictionaries/LIWC/LIWC2015_English_Flat.dic",
'                            format = "LIWC")
' inaugLIWCanalysis <- liwcalike(data_corpus_inaugural, liwc2015dict)
' inaugLIWCanalysis[1:6, 1:10]
</code>```

I expected to have results like the following which are avaible as reproduced simple example in the official site, of course I believe there are more variables of LIWC these are some examples

```<code>LIWC Dimension  Your
Data    Personal
Texts   Formal
Texts
Self-references (I, me, my) 5.18    11.4    4.2
Social words    2.59    9.5 8.0
Positive emotions   2.35    2.7 2.6
Negative emotions   1.18    2.6 1.6
Overall cognitive words 6.59    7.8 5.4
Articles (a, an, the)   8.71    5.0 7.2
Big words (> 6 letters) 20.24   13.1    19.6
</code>```

But I receive this results:

```<code>output[, c(1:7, ncol(output)-2)]
#>    docname Segment WC WPS Sixltr   Dic LINGUISTIC PROCESSES.FUNCTION WORDS
#> 1    text1       1  8   3  37.50 37.50                               25.00
#> 2    text2       2  6   5  16.67 50.00                               50.00
#> 3    text3       3  4   2   0.00 25.00                                0.00
#> 4    text4       4 18  12  11.11 61.11                               22.22
#> 5    text5       5  4   1   0.00 25.00                                0.00
#> 6    text6       6  7   3  14.29 28.57                               14.29
#> 7    text7       7  7   3   0.00 42.86                               28.57
#> 8    text8       8  5   4   0.00 80.00                               60.00
#> 9    text9       9  9   2  11.11 11.11                               11.11
#> 10  text10      10  9   2  22.22 22.22                               22.22
#>    Apostro
#> 1        0
#> 2        0
#> 3        0
#> 4        0
#> 5        0
#> 6        0
#> 7        0
#> 8        0
#> 9        0
#> 10       0
</code>```

How can I take the results as they are in the example trial site version of LIWC?

答: See this page on how to get almost the same result as LIWC: https://koheiw.net/?p=573</p>

Body:
I try to use LIWC dictonary 2015 version in R.

A dummy text for text analysis:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc

I try this line:

library("LIWCalike")
library("quanteda")
 liwcalike(data_char_testphrases)
liwc2015dict <- dictionary(file = "~/Dropbox/QUANTESS/dictionaries/LIWC/LIWC2015_English_Flat.dic",
'                            format = "LIWC")
' inaugLIWCanalysis <- liwcalike(data_corpus_inaugural, liwc2015dict)
' inaugLIWCanalysis[1:6, 1:10]

I expected to have results like the following which are avaible as reproduced simple example in the official site, of course I believe there are more variables of LIWC these are some examples

LIWC Dimension  Your
Data    Personal
Texts   Formal
Texts
Self-references (I, me, my) 5.18    11.4    4.2
Social words    2.59    9.5 8.0
Positive emotions   2.35    2.7 2.6
Negative emotions   1.18    2.6 1.6
Overall cognitive words 6.59    7.8 5.4
Articles (a, an, the)   8.71    5.0 7.2
Big words (> 6 letters) 20.24   13.1    19.6

But I receive this results:

output[, c(1:7, ncol(output)-2)]
#>    docname Segment WC WPS Sixltr   Dic LINGUISTIC PROCESSES.FUNCTION WORDS
#> 1    text1       1  8   3  37.50 37.50                               25.00
#> 2    text2       2  6   5  16.67 50.00                               50.00
#> 3    text3       3  4   2   0.00 25.00                                0.00
#> 4    text4       4 18  12  11.11 61.11                               22.22
#> 5    text5       5  4   1   0.00 25.00                                0.00
#> 6    text6       6  7   3  14.29 28.57                               14.29
#> 7    text7       7  7   3   0.00 42.86                               28.57
#> 8    text8       8  5   4   0.00 80.00                               60.00
#> 9    text9       9  9   2  11.11 11.11                               11.11
#> 10  text10      10  9   2  22.22 22.22                               22.22
#>    Apostro
#> 1        0
#> 2        0
#> 3        0
#> 4        0
#> 5        0
#> 6        0
#> 7        0
#> 8        0
#> 9        0
#> 10       0

How can I take the results as they are in the example trial site version of LIWC?


来源: stackexchange

问:
Python Selenium Explict wait doen not raise TimeoutException
```<code>browser = webdriver.PhantomJS()
def get_score(url):
    browser.get(url)
    elements = wait.until(EC.presence_of_all_elements_located((By.XPATH, "//span[@class='shopdsr-score-con']")))
    description_score = float(elements[0].text)
    service_score = float(elements[1].text)
    logistics_score = float(elements[2].text)
</code>```

About is my code. Sometimes this may get stuck for quite long time and I expect there should be TimeOutException if it get stuck for 30 seconds because I have this code wait = WebDriverWait(browser, 30)
But this never happens, the program just wait there...What's the question?

答:
As you mentioned, you have set WebDriverWait(browser, 30) so effectively your code will be looking like :

```<code>browser = webdriver.PhantomJS()
def get_score(url):
    browser.get(url)
    elements = WebDriverWait(browser, 30).until(EC.presence_of_all_elements_located((By.XPATH, "//span[@class='shopdsr-score-con']")))
    description_score = float(elements[0].text)
    service_score = float(elements[1].text)
    logistics_score = float(elements[2].text)
</code>```

Logically, there is no error in your code block but the the program just wait there because when you invoke get(url) the web client i.e. PhantomJS Browser doesn't returns back document.readyState = "complete" so early. The JavaScript and the AJAX Calls still keeps loading. Hence Page Loading gets elongated.

Once the document.readyState = "complete" is returned by the web client i.e. PhantomJS Browser then only Selenium executes the next line of code:

```<code>elements = WebDriverWait(browser, 30).until(EC.presence_of_all_elements_located((By.XPATH, "//span[@class='shopdsr-score-con']")))
</code>```

Hence the program just wait there for some more time.

Update :

As per your comment you need to look at the options of pageLoadStrategy either setting pageLoadStrategy to eager or none as per this QA Don't wait for a page to load using Selenium in Python

ContentLicense: CC BY-SA 3.0

Body:
browser = webdriver.PhantomJS()
def get_score(url):
    browser.get(url)
    elements = wait.until(EC.presence_of_all_elements_located((By.XPATH, "//span[@class='shopdsr-score-con']")))
    description_score = float(elements[0].text)
    service_score = float(elements[1].text)
    logistics_score = float(elements[2].text)

About is my code. Sometimes this may get stuck for quite long time and I expect there should be TimeOutException if it get stuck for 30 seconds because I have this code wait = WebDriverWait(browser, 30)
But this never happens, the program just wait there...What's the question?

Body:
As you mentioned, you have set WebDriverWait(browser, 30) so effectively your code will be looking like :

browser = webdriver.PhantomJS()
def get_score(url):
    browser.get(url)
    elements = WebDriverWait(browser, 30).until(EC.presence_of_all_elements_located((By.XPATH, "//span[@class='shopdsr-score-con']")))
    description_score = float(elements[0].text)
    service_score = float(elements[1].text)
    logistics_score = float(elements[2].text)

Logically, there is no error in your code block but the the program just wait there because when you invoke get(url) the web client i.e. PhantomJS Browser doesn't returns back document.readyState = "complete" so early. The JavaScript and the AJAX Calls still keeps loading. Hence Page Loading gets elongated.

Once the document.readyState = "complete" is returned by the web client i.e. PhantomJS Browser then only Selenium executes the next line of code:

elements = WebDriverWait(browser, 30).until(EC.presence_of_all_elements_located((By.XPATH, "//span[@class='shopdsr-score-con']")))

Hence the program just wait there for some more time.

Update :

As per your comment you need to look at the options of pageLoadStrategy either setting pageLoadStrategy to eager or none as per this QA Don't wait for a page to load using Selenium in Python


问:
Google Maps v3: check if point exists in polygon
I am looking to find a way of checking if a point exists inside a polygon in Google Maps v3 (JavaScript). I've searched everywhere and the only solutions I have found so far have been to do with getting the bounds of the polygon, but the code shown seems to just create a rectangle and keeps expanding its surface area to include all relevant points.

By the way, the reason I can't just use a big square i.e. getting a polygons bounds, is that I have bordering polygons on the map and they can not expand into each other's territory.

EDIT
Following on from the reply below, I have tried implementing the example code using one of my existing polygons but it is just saying that it is not defined and I can't figure out why.

Here is my declaration:

myCoordinates = [
    new google.maps.LatLng(0.457301,-0.597382),
    new google.maps.LatLng(0.475153,-0.569916),
    new google.maps.LatLng(0.494379,-0.563049),
    new google.maps.LatLng(0.506738,-0.553436),
    new google.maps.LatLng(0.520470,-0.541077),
    new google.maps.LatLng(0.531456,-0.536957),
    new google.maps.LatLng(0.556174,-0.552063),
    new google.maps.LatLng(0.536949,-0.596008),
    new google.maps.LatLng(0.503991,-0.612488),
    new google.maps.LatLng(0.473780,-0.612488) ];

polyOptions = {
    path: myCoordinates,
    strokeColor: "#FF0000",
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: "#0000FF",
    fillOpacity: 0.6 };

var rightShoulderFront = new google.maps.Polygon(polyOptions);
rightShoulderFront.setMap(map);
```

<p>and here is where I am checking for the point:</p>

<pre class="lang-js prettyprint-override"><code>var coordinate = selectedmarker.getPosition();
var isWithinPolygon = rightShoulderFront.containsLatLng(coordinate);
console.log(isWithinPolygon);
</code>```

But it keeps coming up with the error: Uncaught ReferenceError: rightShoulderFront is not defined

答:
I have used the same thing and working fine and its offline code I have written this code in PHP you can write it any programming language.

```<code>class pointLocation {
    var $pointOnVertex = true; // Check if the point sits exactly on one of the vertices?

    function pointLocation() {
    }

    function pointInPolygon($point, $polygon, $pointOnVertex = true) {
        $this->pointOnVertex = $pointOnVertex;

        // Transform string coordinates into arrays with x and y values
        $point = $this->pointStringToCoordinates($point);
        $vertices = array();
        foreach ($polygon as $vertex) {
            $vertices[] = $this->pointStringToCoordinates($vertex);
        }

        // Check if the point sits exactly on a vertex
        if ($this->pointOnVertex == true and $this->pointOnVertex($point, $vertices) == true) {
            return "vertex";
        }

        // Check if the point is inside the polygon or on the boundary
        $intersections = 0;
        $vertices_count = count($vertices);

        for ($i=1; $i < $vertices_count; $i++) {
            $vertex1 = $vertices[$i-1];
            $vertex2 = $vertices[$i];
            if ($vertex1['y'] == $vertex2['y'] and $vertex1['y'] == $point['y'] and $point['x'] > min($vertex1['x'], $vertex2['x']) and $point['x'] < max($vertex1['x'], $vertex2['x'])) { // Check if point is on an horizontal polygon boundary
                return "boundary";
            }
            if ($point['y'] > min($vertex1['y'], $vertex2['y']) and $point['y'] <= max($vertex1['y'], $vertex2['y']) and $point['x'] <= max($vertex1['x'], $vertex2['x']) and $vertex1['y'] != $vertex2['y']) {
                $xinters = ($point['y'] - $vertex1['y']) * ($vertex2['x'] - $vertex1['x']) / ($vertex2['y'] - $vertex1['y']) + $vertex1['x'];
                if ($xinters == $point['x']) { // Check if point is on the polygon boundary (other than horizontal)
                    return "boundary";
                }
                if ($vertex1['x'] == $vertex2['x'] || $point['x'] <= $xinters) {
                    $intersections++;
                }
            }
        }
        // If the number of edges we passed through is odd, then it's in the polygon.
        if ($intersections % 2 != 0) {
            return "inside";
        } else {
            return "outside";
        }
    }

    function pointOnVertex($point, $vertices) {
        foreach($vertices as $vertex) {
            if ($point == $vertex) {
                return true;
            }
        }

    }

    function pointStringToCoordinates($pointString) {
        $coordinates = explode(" ", $pointString);
        return array("x" => $coordinates[0], "y" => $coordinates[1]);
    }

}

$pointLocation = new pointLocation();
$points = array("22.732965336387213 75.8609390258789");
$polygon = array("22.73549852921309 75.85424423217773","22.72346544538196 75.85561752319336","22.72346544538196 75.87175369262695","22.732332030848273 75.87295532226562","22.740406456758326 75.8686637878418","22.74198962160603 75.85407257080078");
echo '```';
print_r($polygon);
// The last point's coordinates must be the same as the first one's, to "close the loop"
foreach($points as $key => $point) {
    echo "point " . ($key+1) . " ($point): " . $pointLocation->pointInPolygon($point, $polygon) . "
";
}
```

?>

Body:
I am looking to find a way of checking if a point exists inside a polygon in Google Maps v3 (JavaScript). I've searched everywhere and the only solutions I have found so far have been to do with getting the bounds of the polygon, but the code shown seems to just create a rectangle and keeps expanding its surface area to include all relevant points.

By the way, the reason I can't just use a big square i.e. getting a polygons bounds, is that I have bordering polygons on the map and they can not expand into each other's territory.

EDIT
Following on from the reply below, I have tried implementing the example code using one of my existing polygons but it is just saying that it is not defined and I can't figure out why.

Here is my declaration:

myCoordinates = [
    new google.maps.LatLng(0.457301,-0.597382),
    new google.maps.LatLng(0.475153,-0.569916),
    new google.maps.LatLng(0.494379,-0.563049),
    new google.maps.LatLng(0.506738,-0.553436),
    new google.maps.LatLng(0.520470,-0.541077),
    new google.maps.LatLng(0.531456,-0.536957),
    new google.maps.LatLng(0.556174,-0.552063),
    new google.maps.LatLng(0.536949,-0.596008),
    new google.maps.LatLng(0.503991,-0.612488),
    new google.maps.LatLng(0.473780,-0.612488) ];

polyOptions = {
    path: myCoordinates,
    strokeColor: "#FF0000",
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: "#0000FF",
    fillOpacity: 0.6 };

var rightShoulderFront = new google.maps.Polygon(polyOptions);
rightShoulderFront.setMap(map);

and here is where I am checking for the point:

var coordinate = selectedmarker.getPosition();
var isWithinPolygon = rightShoulderFront.containsLatLng(coordinate);
console.log(isWithinPolygon);

But it keeps coming up with the error: Uncaught ReferenceError: rightShoulderFront is not defined

Body:
I have used the same thing and working fine and its offline code I have written this code in PHP you can write it any programming language.

class pointLocation {
    var $pointOnVertex = true; // Check if the point sits exactly on one of the vertices?

    function pointLocation() {
    }

    function pointInPolygon($point, $polygon, $pointOnVertex = true) {
        $this->pointOnVertex = $pointOnVertex;

        // Transform string coordinates into arrays with x and y values
        $point = $this->pointStringToCoordinates($point);
        $vertices = array();
        foreach ($polygon as $vertex) {
            $vertices[] = $this->pointStringToCoordinates($vertex);
        }

        // Check if the point sits exactly on a vertex
        if ($this->pointOnVertex == true and $this->pointOnVertex($point, $vertices) == true) {
            return "vertex";
        }

        // Check if the point is inside the polygon or on the boundary
        $intersections = 0;
        $vertices_count = count($vertices);

        for ($i=1; $i < $vertices_count; $i++) {
            $vertex1 = $vertices[$i-1];
            $vertex2 = $vertices[$i];
            if ($vertex1['y'] == $vertex2['y'] and $vertex1['y'] == $point['y'] and $point['x'] > min($vertex1['x'], $vertex2['x']) and $point['x'] < max($vertex1['x'], $vertex2['x'])) { // Check if point is on an horizontal polygon boundary
                return "boundary";
            }
            if ($point['y'] > min($vertex1['y'], $vertex2['y']) and $point['y'] <= max($vertex1['y'], $vertex2['y']) and $point['x'] <= max($vertex1['x'], $vertex2['x']) and $vertex1['y'] != $vertex2['y']) {
                $xinters = ($point['y'] - $vertex1['y']) * ($vertex2['x'] - $vertex1['x']) / ($vertex2['y'] - $vertex1['y']) + $vertex1['x'];
                if ($xinters == $point['x']) { // Check if point is on the polygon boundary (other than horizontal)
                    return "boundary";
                }
                if ($vertex1['x'] == $vertex2['x'] || $point['x'] <= $xinters) {
                    $intersections++;
                }
            }
        }
        // If the number of edges we passed through is odd, then it's in the polygon.
        if ($intersections % 2 != 0) {
            return "inside";
        } else {
            return "outside";
        }
    }

    function pointOnVertex($point, $vertices) {
        foreach($vertices as $vertex) {
            if ($point == $vertex) {
                return true;
            }
        }

    }

    function pointStringToCoordinates($pointString) {
        $coordinates = explode(" ", $pointString);
        return array("x" => $coordinates[0], "y" => $coordinates[1]);
    }

}

$pointLocation = new pointLocation();
$points = array("22.732965336387213 75.8609390258789");
$polygon = array("22.73549852921309 75.85424423217773","22.72346544538196 75.85561752319336","22.72346544538196 75.87175369262695","22.732332030848273 75.87295532226562","22.740406456758326 75.8686637878418","22.74198962160603 75.85407257080078");
echo '<pre>';
print_r($polygon);
// The last point's coordinates must be the same as the first one's, to "close the loop"
foreach($points as $key => $point) {
    echo "point " . ($key+1) . " ($point): " . $pointLocation->pointInPolygon($point, $polygon) . "<br>";
}

?>


问:
javascript/angular 4 property is undefined after interval tries to get value
I am trying to build an timer, but it is not working.
What I do is I have a button which starts the timer. It sets the begin time and after that start an interval to count on screen. But the function which is called by the interval fails because the beginning time is undefined. I debuged to see if the beginning time is being set, and it is. But when it is called through the interval it is undefined.

Here is my code
Some properties

```<code> timeBegan = new Date();
  started = null;
</code>```

the start function

```<code>start() {
this.timeBegan = new Date();
document.getElementById('ticker').innerHTML = '00:00:00.000';

this.started = setInterval(this.clockRunning, 10);
  }
</code>```

the clockrunning function

```<code>public clockRunning() {
const currentTime = new Date();
console.log(this.timeBegan);
console.log(currentTime.getTime());
const timeElapsed = new Date(currentTime.getTime() - this.timeBegan.getTime());
const hour = timeElapsed.getUTCHours();
const min = timeElapsed.getUTCMinutes();
const sec = timeElapsed.getUTCSeconds();
const ms = timeElapsed.getUTCMilliseconds();

console.log(currentTime.getSeconds());
console.log(this.timeBegan);
document.getElementById('ticker').innerHTML =
    (hour > 9 ? hour : '0' + hour) + ':' +
    (min > 9 ? min : '0' + min) + ':' +
    (sec > 9 ? sec : '0' + sec) + '.' +
    (ms > 999 ? ms : ms > 9 ? '0' + ms : '000' + ms);

 }
</code>```

What am I doing wrong?

答:
Use it like this in start function:

```<code>this.started = setInterval(this.clockRunning.bind(this), 10);
</code>```

or:

```<code>this.started = setInterval(function(e){
      this.clockRunning();
}.bind(this), 10);
</code>```

It will definitely solve your problem.

Body:
I am trying to build an timer, but it is not working.
What I do is I have a button which starts the timer. It sets the begin time and after that start an interval to count on screen. But the function which is called by the interval fails because the beginning time is undefined. I debuged to see if the beginning time is being set, and it is. But when it is called through the interval it is undefined.

Here is my code
Some properties

 timeBegan = new Date();
  started = null;

the start function

start() {
this.timeBegan = new Date();
document.getElementById('ticker').innerHTML = '00:00:00.000';

this.started = setInterval(this.clockRunning, 10);
  }

the clockrunning function

public clockRunning() {
const currentTime = new Date();
console.log(this.timeBegan);
console.log(currentTime.getTime());
const timeElapsed = new Date(currentTime.getTime() - this.timeBegan.getTime());
const hour = timeElapsed.getUTCHours();
const min = timeElapsed.getUTCMinutes();
const sec = timeElapsed.getUTCSeconds();
const ms = timeElapsed.getUTCMilliseconds();

console.log(currentTime.getSeconds());
console.log(this.timeBegan);
document.getElementById('ticker').innerHTML =
    (hour > 9 ? hour : '0' + hour) + ':' +
    (min > 9 ? min : '0' + min) + ':' +
    (sec > 9 ? sec : '0' + sec) + '.' +
    (ms > 999 ? ms : ms > 9 ? '0' + ms : '000' + ms);

 }

What am I doing wrong?

Body:
Use it like this in start function:

this.started = setInterval(this.clockRunning.bind(this), 10);

or:

this.started = setInterval(function(e){
      this.clockRunning();
}.bind(this), 10);

It will definitely solve your problem.


问:
JavaScript triangle code?
I am very new to programming, so this might be a simple solution that I simply don't know. I have been trying to write a code that takes a specific number, for example "10", and returns a pyramid where the base has the number of asterisks matched by the value you enter. We are supposed to use this in our code:

```<code>function makeLine(length) {
  var line = "";
  for (var j = 1; j <= length; j++) {
    line += "* "
  }
  return line + "\n";
}
</code>```

For example:

image of triangle where the base is matched by the number entered by the programmer

My code so far looks like this. I know it's completely wrong because I am not at all getting the required results. What am I doing wrong??

```<code>function makeLine(length) {
    var line = "";
    for (var j = 1; j <= length; j++) {
        line += "* ";
    }
    return line + "\n";
    function makeTriangle(length) {
        var line = "";
        for (var j = 1; j <= length; j--) {
            line += "* ";
        }
    }
}
console.log(makeTriangle(8));
</code>```

答:
I had this question on a course I was taking and solved it like this:

    function makeLine(length) {
    var line = "";
    for (var j = 1; j <= length; j++) {
        line += "* ";
    }
    return line + "\n";
}

    function buildTriangle(height) {
    var triangle = "";
    for (var i = 1; i <= height; i++) {
        // call makeline function
        triangle += makeLine(i);
    }
    return triangle;
}

    console.log(buildTriangle(10));```

Title: JavaScript triangle code?

Body:
I am very new to programming, so this might be a simple solution that I simply don't know. I have been trying to write a code that takes a specific number, for example "10", and returns a pyramid where the base has the number of asterisks matched by the value you enter. We are supposed to use this in our code:

function makeLine(length) {
  var line = "";
  for (var j = 1; j <= length; j++) {
    line += "* "
  }
  return line + "\n";
}

For example:

image of triangle where the base is matched by the number entered by the programmer

My code so far looks like this. I know it's completely wrong because I am not at all getting the required results. What am I doing wrong??

function makeLine(length) {
    var line = "";
    for (var j = 1; j <= length; j++) {
        line += "* ";
    }
    return line + "\n";
    function makeTriangle(length) {
        var line = "";
        for (var j = 1; j <= length; j--) {
            line += "* ";
        }
    }
}
console.log(makeTriangle(8));


问:
How to do C++ style destructors in C#?
I've got a C# class with a Dispose function via IDisposable. It's intended to be used inside a using block so the expensive resource it handles can be released right away.

The problem is that a bug occurred when an exception was thrown before Dispose was called, and the programmer neglected to use using or finally.

In C++, I never had to worry about this. The call to a class's destructor would be automatically inserted at the end of the object's scope. The only way to avoid that happening would be to use the new operator and hold the object behind a pointer, but that required extra work for the programmer isn't something they would do by accident, like forgetting to use using.

Is there any way to for a using block to be automatically used in C#?

Many thanks.

UPDATE:

I'd like to explain why I'm not accepting the finalizer answers. Those answers are technically correct in themselves, but they are not C++ style destructors.

Here's the bug I found, reduced to the essentials...

```<code>try
{
    PleaseDisposeMe a = new PleaseDisposeMe();
    throw new Exception();
    a.Dispose();
}
catch (Exception ex)
{
    Log(ex);
}

// This next call will throw a time-out exception unless the GC
// runs a.Dispose in time.
PleaseDisposeMe b = new PleaseDisposeMe();
</code>```

Using FXCop is an excellent suggestion, but if that's my only answer, my question would have to become a plea to the C# people, or use C++. Twenty nested using statements anyone?

答:
This is no different from a programmer forgetting to use delete in C++, except that at least here the garbage collector will still eventually catch up with it.

And you never need to use IDisposable if the only resource you're worried about is memory.  The framework will handle that on it's own.  IDisposable is only for unmanaged resources like database connections, filestreams, sockets, and the like.

OwnerDisplayName: billpg

Title: How to do C++ style destructors in C#?

Body:
I've got a C# class with a Dispose function via IDisposable. It's intended to be used inside a using block so the expensive resource it handles can be released right away.

The problem is that a bug occurred when an exception was thrown before Dispose was called, and the programmer neglected to use using or finally.

In C++, I never had to worry about this. The call to a class's destructor would be automatically inserted at the end of the object's scope. The only way to avoid that happening would be to use the new operator and hold the object behind a pointer, but that required extra work for the programmer isn't something they would do by accident, like forgetting to use using.

Is there any way to for a using block to be automatically used in C#?

Many thanks.

UPDATE:

I'd like to explain why I'm not accepting the finalizer answers. Those answers are technically correct in themselves, but they are not C++ style destructors.

Here's the bug I found, reduced to the essentials...

try
{
    PleaseDisposeMe a = new PleaseDisposeMe();
    throw new Exception();
    a.Dispose();
}
catch (Exception ex)
{
    Log(ex);
}

// This next call will throw a time-out exception unless the GC
// runs a.Dispose in time.
PleaseDisposeMe b = new PleaseDisposeMe();

Using FXCop is an excellent suggestion, but if that's my only answer, my question would have to become a plea to the C# people, or use C++. Twenty nested using statements anyone?

LastEditorDisplayName: billpg

OwnerDisplayName: Joel Coehoorn

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Joel Coehoorn


问:
Xpath query and time
Hi, this is the content of my XML file:

```<code><?xml version="1.0" encoding="ISO-8859-1"?>
<mainNode>
    <sub time="08:00">
        <status id="2">On</status>
        <status id="3">Off</status>
    </sub>
    <sub time="13:00">
        <status id="4">On</status>
        <status id="7">On</status>
    </sub>
    <sub time="16:00">
        <status id="5">On</status>
        <status id="6">On</status>
        <status id="7">Off</status>
        <status id="8">On</status>
    </sub>
    <sub time="20:00">
        <status id="4">Off</status>
        <status id="7">On</status>
    </sub>
    <sub time="23:59">
        <status id="4">On</status>
        <status id="7">On</status>
    </sub>
</mainNode>
</code>```

My program gets the current time:
if I get 15.59, I must retrieve all the status id of the next sub time (16.00):

```<code><sub time="16:00">
        <status id="5">On</status>
        <status id="6">On</status>
        <status id="7">Off</status>
        <status id="8">On</status>
    </sub>
</code>```

With a second XPath query I must get all the status id of the previous sub time (13.00).
How to do it? I know SQL but I'm quite new to XPath. I accept urls to serious XPath resources too, if any. Thanks!

答:
Here are two solutions:

I. XPath 1.0

This is one pair of XPath 1.0 expressions that select the required nodes:

```<code>/*/*
    [translate(@time, ':','')
    >
     translate('15:59',':','')
    ][1]
</code>```

selects the first sub node with time later than 15:59.

```<code>/*/*
    [translate(@time, ':','')
    <
     translate('15:59',':','')
    ][last()]
</code>```

selects selects the first sub node with the previous than 15:59 sub time.

We can include these in an XSLT transformation and check that the really wanted result is produced:

```<code><xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output omit-xml-declaration="yes"/>

    <xsl:template match="/">
      First time after 15:59:
      <xsl:copy-of select=
       "/*/*
          [translate(@time, ':','')
         >
           translate('15:59',':','')
          ][1]
      "/>

      First time before 15:59:
      <xsl:copy-of select=
       "/*/*
          [translate(@time, ':','')
         <
           translate('15:59',':','')
          ][last()]
      "/>
  </xsl:template>
</xsl:stylesheet>
</code>```

When the above transformation is applied on the originally provided XML document:

```<code><mainNode>
    <sub time="08:00">
        <status id="2">On</status>
        <status id="3">Off</status>
    </sub>
    <sub time="13:00">
        <status id="4">On</status>
        <status id="7">On</status>
    </sub>
    <sub time="16:00">
        <status id="5">On</status>
        <status id="6">On</status>
        <status id="7">Off</status>
        <status id="8">On</status>
    </sub>
    <sub time="20:00">
        <status id="4">Off</status>
        <status id="7">On</status>
    </sub>
    <sub time="23:59">
        <status id="4">On</status>
        <status id="7">On</status>
    </sub>
</mainNode>
</code>```

the wanted result is produced:

```<code>  First time after 15:59:

<sub time="16:00">
        <status id="5">On</status>
        <status id="6">On</status>
        <status id="7">Off</status>
        <status id="8">On</status>
</sub>

  First time before 15:59:

 <sub time="13:00">
        <status id="4">On</status>
        <status id="7">On</status>
 </sub>
</code>```

Do note the following:

The use of the XPath translate() function to get rid of the colons

The use of the last() function in the second expression

There is no need to convert the time to seconds before the comparison

When used as part of an XML document (such as an XSLT stylesheet, the < operator must be escaped.

II. XPath 2.0

In XPath 2.0 we can use the following two expressions to produce select the desired nodes:

```<code>/*/*[xs:time(concat(@time,':00'))
    gt
     xs:time('15:59:00')
    ][1]
</code>```

selects the first sub node with time later than 15:59.

```<code>/*/*[xs:time(concat(@time,':00'))
   lt
     xs:time('15:59:00')
    ][last()]
</code>```

selects selects the first sub node with the previous than 15:59 sub time.

We can include these in an XSLT 2.0 transformation and check that the really wanted result is produced:

```<code><xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xsl:output omit-xml-declaration="yes"/>

    <xsl:template match="/">
      First time after 15:59:
      <xsl:copy-of select=
       "/*/*[xs:time(concat(@time,':00'))
           gt
             xs:time('15:59:00')
             ][1]
      "/>

      First time before 15:59:
      <xsl:copy-of select=
       "/*/*[xs:time(concat(@time,':00'))
           lt
             xs:time('15:59:00')
          ][last()]
      "/>
    </xsl:template>
</xsl:stylesheet>
</code>```

When the above transformation is applied on the originally provided XML document (the same as in the first solution), the same wanted result is produced.

Do note the following:

In XPath 2.0 xs:time is a native data type. However, in order to construct an xs:time() from the values in the xml document, we have to concat to them the missing seconds part.

In XPath 2.0 xs:time values can be compared with the "atomic-value comarison operators" such as lt or gt.

OwnerDisplayName: vyger

Title: Xpath query and time

Body:
Hi, this is the content of my XML file:

<?xml version="1.0" encoding="ISO-8859-1"?>
<mainNode>

        <status id="2">On</status>
        <status id="3">Off</status>

        <status id="4">On</status>
        <status id="7">On</status>

        <status id="5">On</status>
        <status id="6">On</status>
        <status id="7">Off</status>
        <status id="8">On</status>

        <status id="4">Off</status>
        <status id="7">On</status>

        <status id="4">On</status>
        <status id="7">On</status>

</mainNode>

My program gets the current time:
if I get 15.59, I must retrieve all the status id of the next sub time (16.00):

        <status id="5">On</status>
        <status id="6">On</status>
        <status id="7">Off</status>
        <status id="8">On</status>

With a second XPath query I must get all the status id of the previous sub time (13.00).
How to do it? I know SQL but I'm quite new to XPath. I accept urls to serious XPath resources too, if any. Thanks!

Body:
Here are two solutions:

I. XPath 1.0

This is one pair of XPath 1.0 expressions that select the required nodes:

/*/*
    [translate(@time, ':','')
    >
     translate('15:59',':','')
    ][1]

selects the first sub node with time later than 15:59.

/*/*
    [translate(@time, ':','')
    <
     translate('15:59',':','')
    ][last()]

selects selects the first sub node with the previous than 15:59 sub time.

We can include these in an XSLT transformation and check that the really wanted result is produced:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output omit-xml-declaration="yes"/>

    <xsl:template match="/">
      First time after 15:59:
      <xsl:copy-of select=
       "/*/*
          [translate(@time, ':','')
         >
           translate('15:59',':','')
          ][1]
      "/>

      First time before 15:59:
      <xsl:copy-of select=
       "/*/*
          [translate(@time, ':','')
         &lt;
           translate('15:59',':','')
          ][last()]
      "/>
  </xsl:template>
</xsl:stylesheet>

When the above transformation is applied on the originally provided XML document:

<mainNode>
    <sub time="08:00">
        <status id="2">On</status>
        <status id="3">Off</status>
    </sub>
    <sub time="13:00">
        <status id="4">On</status>
        <status id="7">On</status>
    </sub>
    <sub time="16:00">
        <status id="5">On</status>
        <status id="6">On</status>
        <status id="7">Off</status>
        <status id="8">On</status>
    </sub>
    <sub time="20:00">
        <status id="4">Off</status>
        <status id="7">On</status>
    </sub>
    <sub time="23:59">
        <status id="4">On</status>
        <status id="7">On</status>
    </sub>
</mainNode>

the wanted result is produced:

  First time after 15:59:

<sub time="16:00">
        <status id="5">On</status>
        <status id="6">On</status>
        <status id="7">Off</status>
        <status id="8">On</status>
</sub>

  First time before 15:59:

 <sub time="13:00">
        <status id="4">On</status>
        <status id="7">On</status>
 </sub>

Do note the following:

The use of the XPath translate() function to get rid of the colons

The use of the last() function in the second expression

There is no need to convert the time to seconds before the comparison

When used as part of an XML document (such as an XSLT stylesheet, the < operator must be escaped.

II. XPath 2.0

In XPath 2.0 we can use the following two expressions to produce select the desired nodes:

/*/*[xs:time(concat(@time,':00'))
    gt
     xs:time('15:59:00')
    ][1]

selects the first sub node with time later than 15:59.

/*/*[xs:time(concat(@time,':00'))
   lt
     xs:time('15:59:00')
    ][last()]

selects selects the first sub node with the previous than 15:59 sub time.

We can include these in an XSLT 2.0 transformation and check that the really wanted result is produced:

<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xsl:output omit-xml-declaration="yes"/>

    <xsl:template match="/">
      First time after 15:59:
      <xsl:copy-of select=
       "/*/*[xs:time(concat(@time,':00'))
           gt
             xs:time('15:59:00')
             ][1]
      "/>

      First time before 15:59:
      <xsl:copy-of select=
       "/*/*[xs:time(concat(@time,':00'))
           lt
             xs:time('15:59:00')
          ][last()]
      "/>
    </xsl:template>
</xsl:stylesheet>

When the above transformation is applied on the originally provided XML document (the same as in the first solution), the same wanted result is produced.

Do note the following:

In XPath 2.0 xs:time is a native data type. However, in order to construct an xs:time() from the values in the xml document, we have to concat to them the missing seconds part.

In XPath 2.0 xs:time values can be compared with the "atomic-value comarison operators" such as lt or gt.

OwnerDisplayName: Dimitre Novatchev

LastEditorDisplayName: Dimitre Novatchev


问:
SQL for applying conditions to multiple rows in a join
I think I found the answer to my question, I'm just unsure of the syntax, I keep getting SQL errors.

Basically, I want to do the opposite of IN. Take this example:

```<code>SELECT *
  FROM users INNER JOIN
       tags ON tags.user_id = users.id
 WHERE tags.name IN ('tag1', 'tag2');
</code>```

The above will return ANY users that have 'tag1' OR 'tag2'. I want users that have BOTH. They must have both tags to be returned. I'm assuming the keyword ALL should be used, but can't get it to work.

Thanks for your help.

答:
I would do exactly what you are doing first, because that gets a list of all users with 'tag1' and a list of all users with 'tag2', but in the same response obviously. So, we have to add some more:

Do a group by users (or users.id) and then having count(*) == 2. That will group duplicate users (which means those with both tag1 and tag2) and then the having-part will remove the ones with just one of the two tags.

This solution avoids adding yet another join-statement, but honestly I'm not sure which is faster. People, feel free to comment on the performance-part :)

EDIT: Just to make it easier to try out, here's the whole thing:

```<code>SELECT *
FROM users INNER JOIN
     tags ON tags.user_id = users.id
WHERE tags.name = 'tag1' OR tags.name = 'tag2'
GROUP BY users.id
HAVING COUNT(*) = 2
</code>```

Body:
I think I found the answer to my question, I'm just unsure of the syntax, I keep getting SQL errors.

Basically, I want to do the opposite of IN. Take this example:

SELECT *
  FROM users INNER JOIN
       tags ON tags.user_id = users.id
 WHERE tags.name IN ('tag1', 'tag2');

The above will return ANY users that have 'tag1' OR 'tag2'. I want users that have BOTH. They must have both tags to be returned. I'm assuming the keyword ALL should be used, but can't get it to work.

Thanks for your help.

Body:
I would do exactly what you are doing first, because that gets a list of all users with 'tag1' and a list of all users with 'tag2', but in the same response obviously. So, we have to add some more:

Do a group by users (or users.id) and then having count(*) == 2. That will group duplicate users (which means those with both tag1 and tag2) and then the having-part will remove the ones with just one of the two tags.

This solution avoids adding yet another join-statement, but honestly I'm not sure which is faster. People, feel free to comment on the performance-part :)

EDIT: Just to make it easier to try out, here's the whole thing:

SELECT *
FROM users INNER JOIN
     tags ON tags.user_id = users.id
WHERE tags.name = 'tag1' OR tags.name = 'tag2'
GROUP BY users.id
HAVING COUNT(*) = 2


问:
Unable to reference HTML values in Javascript
I am building a Django app and need to do some Javascript processing in the HTML Template. In order to pass values from Django's templating language into Javascript, I have saved the values into meta tags as below:

```<code><head>
    {% for candidate in candidates %}
        <meta id="cand" data-id="{{candidate.id}}" data-order="{{forloop.counter}}">
        <h3>{{forloop.counter}}</h3>
    {% endfor %}
</head>
</code>```

I then try to access the data here:

```<code><script type="text/javascript">

var metatags = document.getElementsByTagName('meta');
for (var i = 0; i < metatags.length; i++) {
    console.log(metatags[i].data-id)
}

</script>
</code>```

However, an issue is thrown trying to access the data:

```<code>Uncaught ReferenceError: id is not defined
</code>```

In reference to the line console.log(metatags[i].data-id)

Why is this not working, am I attempting something impossible, and is there a better or more elegant way of accessing template values in Javascript?

Thanks in advance.

答:
Try accessing the property like this:</p>

```<code> console.log(metatags[i].getAttribute("data-id"));
</code>```

Body:
I am building a Django app and need to do some Javascript processing in the HTML Template. In order to pass values from Django's templating language into Javascript, I have saved the values into meta tags as below:

    {% for candidate in candidates %}
        <meta id="cand" data-id="{{candidate.id}}" data-order="{{forloop.counter}}">

{{forloop.counter}}

    {% endfor %}

I then try to access the data here:

However, an issue is thrown trying to access the data:

Uncaught ReferenceError: id is not defined

In reference to the line console.log(metatags[i].data-id)

Why is this not working, am I attempting something impossible, and is there a better or more elegant way of accessing template values in Javascript?

Thanks in advance.

Body:
Try accessing the property like this:

 console.log(metatags[i].getAttribute("data-id"));


问:
Hide banner "Update your license key because it will expire in x days"
I am getting this banner on every Page of my Liferay portal:

Update your license key because it will expire in 27 days. Visit your profile page at Liferay.com to upgrade your trial license.

The banner hides vital parts of the page, so I have to close it every time, which takes a substantial amount of time. It is just a matter of time until a new license is ordered, but it could take two weeks if my company's buying department is busy.

How to make Liferay 7 not show this banner?

答:
This is a longstanding open issue. You may want to vote for it, or file it through your EE support. I'd say, a quick fix for it (although it's quite definitive - make sure to revert it when no longer needed) is to identify the CSS for this method and "CSS - display:none" it.

I'd hope that the message will soon pop up only once per session and then stay hidden after been acknowledged once.

Another alternative: Do not use an Administrator account to log in, rather a less privileged one, where the message doesn't get shown.


问:
Haskell :: Parsing Line of Text into a List of List

Hi guys,

I'm parsing a text file which look like this:

```<code>114.474998474121 15.7440004348755 25.806999206543 -873 172 182 188
114.46199798584 15.7419996261597 25.8799991607666 -1396 180 192 205
</code>```

And wish it can read as like this:

```<code>[[114.475,15.744,25.807,-873.0,172.0,182.0,188.0],
[114.462,15.742,25.88,-1396.0,180.0,192.0,205.0]]
</code>```

Currently my code for this text parsing doesn't give that. Here is my code:

```<code>main = do
    text <- readFile "mytext.txt"
    let
        pcVal = map read (words text) :: [Float]
    print pcVal
    return ()
</code>```

This code parsed all the text as a single list like this:

```<code>[114.475,15.744,25.807,-873.0,172.0,182.0,188.0,
114.462,15.742,25.88,-1396.0,180.0,192.0,205.0]
</code>```

I couldn't find how to take the whole single line (in text file) as a list, and the second line as another list till end of the file. Appreciate if somebody have experience in this. Thanks.

答:
Thanks Dan for suggesting lines as the solution. Here is the code that works fine with my question:

```<code>main = do
    text <- readFile "mytext.txt"
    let
        readparse txtLines = map read txtLines :: [Float]
        parse txtLines = map (words) (lines txtLines)
        pcval = map readparse (parse text)
    print pcVal
    return ()
</code>```

Hope it help others too. Thanks and cheers!

Body:
Hi guys,

I'm parsing a text file which look like this:

114.474998474121 15.7440004348755 25.806999206543 -873 172 182 188
114.46199798584 15.7419996261597 25.8799991607666 -1396 180 192 205

And wish it can read as like this:

[[114.475,15.744,25.807,-873.0,172.0,182.0,188.0],
[114.462,15.742,25.88,-1396.0,180.0,192.0,205.0]]

Currently my code for this text parsing doesn't give that. Here is my code:

main = do
    text <- readFile "mytext.txt"
    let
        pcVal = map read (words text) :: [Float]
    print pcVal
    return ()

This code parsed all the text as a single list like this:

[114.475,15.744,25.807,-873.0,172.0,182.0,188.0,
114.462,15.742,25.88,-1396.0,180.0,192.0,205.0]

I couldn't find how to take the whole single line (in text file) as a list, and the second line as another list till end of the file. Appreciate if somebody have experience in this. Thanks.

Body:
Thanks Dan for suggesting lines as the solution. Here is the code that works fine with my question:

main = do
    text <- readFile "mytext.txt"
    let
        readparse txtLines = map read txtLines :: [Float]
        parse txtLines = map (words) (lines txtLines)
        pcval = map readparse (parse text)
    print pcVal
    return ()

Hope it help others too. Thanks and cheers!


问:
Change keras class_weight during training
I want to make use of the class_weight parameter of the fit function in Keras to deal with unbalanced datasets.

The key inhere is that i want to specify the class_weights through a function based on the epoch that is running.

I though to use a callback function but I'm unable to change the class_weight parameter from there. Any help?

答:
At this moment it is unfortunately not possible to change the class_weight parameter in a callback function. The parameter is not saved as an instance variable in the model, so you won't be able to access it.

You can however adjust the class weight parameter for each batch, if you use model.train_on_batch. You will be able to calculate the epoch number from the batch number. This only works for this particular fit method, though. So you will need to create a batch generator and modify the class weight parameter before passing on the batch of data to the fit function.


问:
How to make animated toggle menu with effect only on mobile devices?
I am new here and forgive me if this question has already been asked before, but I couldn't find that kind of problem. And at the beginning, sorry for my grammar ;) .

The thing is, that I would like to get toggle menu that slides in from right side, after a click on the "hamburger" icon, but only when the width of the screen is smaller than 576 px. On larger screens, i have a fixed-top navbar, without any effects and that's fine. I am using Bootstrap 4 to build my site. Is it possible to do?

```<code><nav class="navbar navbar-expand-lg navbar-light fixed-top">
    <div class="container-fluid">
        <a class="navbar-brand pl-md-4" href="index.html">Logo</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarResponsive">
            <ul class="navbar-nav mr-auto">
                <li class="nav-item">
                    <a class="nav-link" href="#">Link 1</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Link 2</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Link 3</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Link 4</a>
                </li>
            </ul>
            <ul class="navbar-nav pr-md-4">
                <li class="nav-item px-md-3">
                    <a class="nav-link" href="#">link 5</a>
                </li>
                <li class="nav-item px-md-3">
                    <a class="nav-link" href="#">link 6</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">link 7</a>
                </li>
            </ul>
        </div>
    </div>
</nav>
</code>```

答:
Best way to do it is create two different navs one for the Bigger screens and one more for smaller screens.And give different functionality based on the ID through JS</p>

```<code><!-- Hide the for large Screen -->
  <nav id="jsIdentifer1" class="hidden-md hidden-lg">
   your navigation code
  </nav>
<!-- Hide the for small Screen -->
  <nav id="jsIdentifer2" class="hidden-sm hidden-xs">
    your navigation code
  </nav>
</code>```

Body:
I am new here and forgive me if this question has already been asked before, but I couldn't find that kind of problem. And at the beginning, sorry for my grammar ;) .

The thing is, that I would like to get toggle menu that slides in from right side, after a click on the "hamburger" icon, but only when the width of the screen is smaller than 576 px. On larger screens, i have a fixed-top navbar, without any effects and that's fine. I am using Bootstrap 4 to build my site. Is it possible to do?

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

        </button>

                    Link 1

                    Link 2

                    Link 3

                    Link 4

                    link 5

                    link 6

                    link 7

Body:
Best way to do it is create two different navs one for the Bigger screens and one more for smaller screens.And give different functionality based on the ID through JS

<!-- Hide the for large Screen -->
  <nav id="jsIdentifer1" class="hidden-md hidden-lg">
   your navigation code
  </nav>
<!-- Hide the for small Screen -->
  <nav id="jsIdentifer2" class="hidden-sm hidden-xs">
    your navigation code
  </nav>


问:
React: 'this.state' is undefined inside a component function
I'm having trouble accessing this.state in functions inside my component. I already found this question on SO and added the suggested code to my constructor:

```<code>class Game extends React.Component {

  constructor(props){
    super(props);
    ...
    this.state = {uid: '', currentTable : '', currentRound : 10, deck : sortedDeck};
    this.dealNewHand = this.dealNewHand.bind(this);
    this.getCardsForRound = this.getCardsForRound.bind(this);
    this.shuffle = this.shuffle.bind(this);
  }

  // error thrown in this function
  dealNewHand(){
    var allCardsForThisRound = this.getCardsForRound(this.state.currentRound);
  }

  getCardsForRound(cardsPerPerson){
    var shuffledDeck = this.shuffle(sortedDeck);
    var cardsForThisRound = [];
    for(var i = 0; i < cardsPerPerson * 4; i++){
      cardsForThisRound.push(shuffledDeck[i]);
    }
    return cardsForThisRound;
  }

  shuffle(array) {
    ...
  }

  ...
  ...
</code>```

It still does not work. this.state.currentRound is undefined. What is the problem?

答:
Write your functions this way:

```<code>dealNewHand = () => {
    var allCardsForThisRound =
    this.getCardsForRound(this.state.currentRound);
}
getCardsForRound = (cardsPerPerson) => {
    var shuffledDeck = this.shuffle(sortedDeck);
    var cardsForThisRound = [];
    for(var i = 0; i < cardsPerPerson * 4; i++){
        cardsForThisRound.push(shuffledDeck[i]);
    }
    return cardsForThisRound;
}
</code>```

http://www.react.express/fat_arrow_functions

the binding for the keyword this is the same outside and inside the fat arrow function. This is different than functions declared with function, which can bind this to another object upon invocation. Maintaining the this binding is very convenient for operations like mapping: this.items.map(x => this.doSomethingWith(x)).

Body:
I'm having trouble accessing this.state in functions inside my component. I already found this question on SO and added the suggested code to my constructor:

class Game extends React.Component {

  constructor(props){
    super(props);
    ...
    this.state = {uid: '', currentTable : '', currentRound : 10, deck : sortedDeck};
    this.dealNewHand = this.dealNewHand.bind(this);
    this.getCardsForRound = this.getCardsForRound.bind(this);
    this.shuffle = this.shuffle.bind(this);
  }

  // error thrown in this function
  dealNewHand(){
    var allCardsForThisRound = this.getCardsForRound(this.state.currentRound);
  }

  getCardsForRound(cardsPerPerson){
    var shuffledDeck = this.shuffle(sortedDeck);
    var cardsForThisRound = [];
    for(var i = 0; i < cardsPerPerson * 4; i++){
      cardsForThisRound.push(shuffledDeck[i]);
    }
    return cardsForThisRound;
  }

  shuffle(array) {
    ...
  }

  ...
  ...

It still does not work. this.state.currentRound is undefined. What is the problem?

Body:
Write your functions this way:

dealNewHand = () => {
    var allCardsForThisRound =
    this.getCardsForRound(this.state.currentRound);
}
getCardsForRound = (cardsPerPerson) => {
    var shuffledDeck = this.shuffle(sortedDeck);
    var cardsForThisRound = [];
    for(var i = 0; i < cardsPerPerson * 4; i++){
        cardsForThisRound.push(shuffledDeck[i]);
    }
    return cardsForThisRound;
}

http://www.react.express/fat_arrow_functions

the binding for the keyword this is the same outside and inside the fat arrow function. This is different than functions declared with function, which can bind this to another object upon invocation. Maintaining the this binding is very convenient for operations like mapping: this.items.map(x => this.doSomethingWith(x)).


问:
Pandas: Join Date and Time into one datetime column
I have a dataframe with 13 columns, where two columns are "Date" and "Time".

I would like to
1) join "Date" and "Time" and
2) format the result correctly (DD.MM.YYYY HH:MM:SS)

```<code>        Date    Time
0   2012-09-27  00:40:20
1   2012-09-27  07:24:37
2   2012-09-27  07:25:08
3   2012-09-27  07:43:48
4   2012-09-27  07:44:27
5   2012-09-27  07:55:16
6   2012-09-27  08:04:19
7   2012-09-27  08:08:21
8   2012-09-27  08:09:08
9   2012-09-27  08:15:30
10  2012-09-27  08:15:35
</code>```

So I try:

```<code>>type(df["Date"])
pandas.core.series.Series
</code>```

And I think to myself "Why not convert them both in to string representations and manipulate them that way?"

```<code>>g = df["Time"].astype(str)
>type(g)
pandas.core.series.Series
</code>```

"What?! It's still a Series?!"

So I try to be creative:

```<code>>f = df["Date"].astype(str) + " " + df["Time"].astype(str)
>f
0     2012-09-27 00:40:20
1     2012-09-27 07:24:37
2     2012-09-27 07:25:08
3     2012-09-27 07:43:48
</code>```

"Hey! That works! No let's just get the format right (DD.MM.YYYY HH:MM:SS)"

```<code>>#dt.strptime(f, '%Y-%m-%d %H:%M:%S')
TypeError: strptime() argument 1 must be str, not Series
</code>```

"Still a Series...hmmm....Obviously it won't let itself be converted. Let's try something else"

```<code>>f = p.concat([df["Date"], df["Time"]], axis=1)
>f
        Date    Time
0   2012-09-27  00:40:20
1   2012-09-27  07:24:37
2   2012-09-27  07:25:08
</code>```

"Nice! But.... Isn't this TWO columns still...?"

```<code>>f.shape
(100,2)
</code>```

"Right...back to square one...."

I'm out of ideas....

Anyone?

Body:
I have a dataframe with 13 columns, where two columns are "Date" and "Time".

I would like to
1) join "Date" and "Time" and
2) format the result correctly (DD.MM.YYYY HH:MM:SS)

        Date    Time
0   2012-09-27  00:40:20
1   2012-09-27  07:24:37
2   2012-09-27  07:25:08
3   2012-09-27  07:43:48
4   2012-09-27  07:44:27
5   2012-09-27  07:55:16
6   2012-09-27  08:04:19
7   2012-09-27  08:08:21
8   2012-09-27  08:09:08
9   2012-09-27  08:15:30
10  2012-09-27  08:15:35

So I try:

>type(df["Date"])
pandas.core.series.Series

And I think to myself "Why not convert them both in to string representations and manipulate them that way?"

>g = df["Time"].astype(str)
>type(g)
pandas.core.series.Series

"What?! It's still a Series?!"

So I try to be creative:

>f = df["Date"].astype(str) + " " + df["Time"].astype(str)
>f
0     2012-09-27 00:40:20
1     2012-09-27 07:24:37
2     2012-09-27 07:25:08
3     2012-09-27 07:43:48

"Hey! That works! No let's just get the format right (DD.MM.YYYY HH:MM:SS)"

>#dt.strptime(f, '%Y-%m-%d %H:%M:%S')
TypeError: strptime() argument 1 must be str, not Series

"Still a Series...hmmm....Obviously it won't let itself be converted. Let's try something else"

>f = p.concat([df["Date"], df["Time"]], axis=1)
>f
        Date    Time
0   2012-09-27  00:40:20
1   2012-09-27  07:24:37
2   2012-09-27  07:25:08

"Nice! But.... Isn't this TWO columns still...?"

>f.shape
(100,2)

"Right...back to square one...."

I'm out of ideas....

Anyone?

Body:
I think you need join columns with to_datetime:

print (type(df.loc[0, 'Date']))
<class 'str'>
print (type(df.loc[0, 'Time']))
<class 'str'>

df['datetime'] = pd.to_datetime(df['Date'] + " " + df['Time'])

If there is datetime with strings:

print (type(df.loc[0, 'Date']))
<class 'pandas._libs.tslib.Timestamp'>
print (type(df.loc[0, 'Time']))
<class 'str'>

df['datetime'] = df['Date']  + pd.to_timedelta(df['Time'])

If there is datetime with times:

print (type(df.loc[0, 'Date']))
<class 'pandas._libs.tslib.Timestamp'>

print (type(df.loc[0, 'Time']))
<class 'datetime.time'>

df['datetime'] = df['Date']  + pd.to_timedelta(df['Time'].astype(str))

And if there are dates with times:

print (type(df.loc[0, 'Date']))
<class 'datetime.date'>

print (type(df.loc[0, 'Time']))
<class 'datetime.time'>

df['datetime'] = pd.to_datetime(df["Date"].astype(str) + " " + df["Time"].astype(str))

print (df)
          Date      Time            datetime
0   2012-09-27  00:40:20 2012-09-27 00:40:20
1   2012-09-27  07:24:37 2012-09-27 07:24:37
2   2012-09-27  07:25:08 2012-09-27 07:25:08
3   2012-09-27  07:43:48 2012-09-27 07:43:48
4   2012-09-27  07:44:27 2012-09-27 07:44:27
5   2012-09-27  07:55:16 2012-09-27 07:55:16
6   2012-09-27  08:04:19 2012-09-27 08:04:19
7   2012-09-27  08:08:21 2012-09-27 08:08:21
8   2012-09-27  08:09:08 2012-09-27 08:09:08
9   2012-09-27  08:15:30 2012-09-27 08:15:30
10  2012-09-27  08:15:35 2012-09-27 08:15:35


问:
How do I make the "action" of this card game keep executing until a winner is found?
I created this card game that asks the user for an action. "attack" and "swap". they both work fine on the first execution, but how do I make it so that the system keeps asking the user for an action until one of the player wins?

This contains my code for the class GameMaster that the GameConsole will reference. It has links to two other classes I have called Player and Card.

```<code>import java.util.*;
public class GameMaster
{
private int turnCounter = 0;
private ArrayList<Card> deck;
private boolean isThereWinner;
private Player player1;
private Player player2;
public GameMaster (Player a, Player b) //initializes values
{
    turnCounter = turnCounter + 1;
    player1 = a;
    player2 = b;
    deck = new ArrayList<Card>();
    assembleDeck();
    dealCard();
}
private void assembleDeck() //given order of cards
{
    deck.add( new Card( "Dragon", "Aquira", 174, 26 ) );
    deck.add( new Card( "Ghost", "Brawn", 130, 48 ) );
    deck.add( new Card( "Fairy", "Cerulea", 162, 29 ) );
    deck.add( new Card( "Dragon", "Demi", 147, 28 ) );
    deck.add( new Card( "Ghost", "Elba", 155, 37 ) );
    deck.add( new Card( "Fairy", "Fye", 159, 42 ) );
    deck.add( new Card( "Dragon", "Glyede", 129, 26 ) );
    deck.add( new Card( "Ghost", "Hydran", 163, 35 ) );
    deck.add( new Card( "Fairy", "Ivy", 146, 45 ) );
    deck.add( new Card( "Dragon", "Jet", 170, 24 ) );
    deck.add( new Card( "Ghost", "Kineti", 139, 21 ) );
    deck.add( new Card( "Fairy", "Levi", 160, 43 ) );
    deck.add( new Card( "Dragon", "Meadow", 134, 29 ) );
    deck.add( new Card( "Ghost", "Naidem", 165, 26 ) );
    deck.add( new Card( "Fairy", "Omi", 145, 21 ) );
    deck.add( new Card( "Dragon", "Puddles", 170, 34 ) );
    deck.add( new Card( "Ghost", "Quarrel", 151, 29 ) );
    deck.add( new Card( "Fairy", "Raven", 168, 32 ) );
    deck.add( new Card( "Dragon", "Surge", 128, 27 ) );
    deck.add( new Card( "Ghost", "Takiru", 140, 26 ) );
    deck.add( new Card( "Fairy", "Ustelia", 163, 47 ) );
    deck.add( new Card( "Dragon", "Verwyn", 145, 25 ) );
    deck.add( new Card( "Ghost", "Wyverin", 158, 32 ) );
    deck.add( new Card( "Fairy", "Xios", 155, 27 ) );
    deck.add( new Card( "Dragon", "Yora", 159, 44 ) );
    deck.add( new Card( "Ghost", "Zulu", 125, 46 ) );
}
public java.lang.String play (java.lang.String action) // lets player enter action swap or attack
{
   if (turnCounter%2==1) //player 1's turn
   {
        if (action.equals("swap")) // if player one enters "swap"
        {
            turnCounter = turnCounter + 1;
            System.out.println("   "+player1.getName() + " swaps out " + player1.getActiveCard().getName()+".");
            player1.swap();

        }
        else if (action.equals("attack")) // if player one enter "attack"
        {
            turnCounter = turnCounter + 1;
            System.out.println("   "+player1.getName() + " attacks with " + player1.getActiveCard().getName()+".");
            dealDamage(player1.getActiveCard(), player2.getActiveCard());

            if (player2.getActiveCard().getHealth()<1) //if player 2's health goes below 1
            {
                player2.discard();
                System.out.println("   "+player2.getName() + " discards " + player2.getActiveCard().getName());
                player2.drawCard(deck.get(0));
                System.out.println(player2.getName() + " draws " + deck.get(0)+".");
                if (deck.size()==0) // if there are no more cards in the deck
                {
                    System.out.println("The deck is empty.");
                }
                player1.claimToken();
                System.out.println("   "+player1.getName() + " gets a token!");
                if (player1.getTokens()==3) //if player1 kills three of player2's cards = 3 tokens
                {
                    hasWinner();
                    System.out.println(player1.getName() + " wins!");
                }
            }
        }
    }
    else if (turnCounter%2==0) //player 2's turn
    {
        if (action.equals("swap")) //if player 2 chooses "swap"
        {
            turnCounter = turnCounter + 1;
            System.out.println("   "+player2.getActiveCard().getName() + " swaps out " + player2.getActiveCard().getName());
            player2.swap();

        }
        else if (action.equals("attack")) //if player two chooses "attack"
        {
            turnCounter = turnCounter + 1;
            System.out.println("   "+player2.getName() + " attacks with " + player2.getActiveCard());
            dealDamage(player2.getActiveCard(), player1.getActiveCard());
            if (player1.getActiveCard().getHealth()<1) //if player 1's health drops below 1
            {
                player1.discard();
                System.out.println("   "+player1.getName() + " discards " + player1.getActiveCard().getName());
                player1.drawCard(deck.get(0));
                System.out.println("   "+player1.getName() + " draws " + deck.get(0)+".");
                if (deck.size()==0) //if there are no more cards in the deck
                {
                    System.out.println("The deck is empty.");
                }
                player2.claimToken();
                System.out.println("   "+player2.getName() + " gets a token!");
                if (player2.getTokens()==3) //if player 2 kills 3 of player1's cards = get three tokens
                {
                    hasWinner();
                    System.out.println(player2.getName() + " wins!");
                }
            }

        }

   }
   return "";
}
public boolean checkResistance(java.lang.String type1, java.lang.String type2) //checks for resistance
{
    if (type1.equals("Dragon")&&type2.equals("Ghost"))
        return true;
    else if (type1.equals("Ghost")&&type2.equals("Fairy"))
        return true;
    else if (type1.equals("Fairy")&&type2.equals("Dragon"))
        return true;
    else
        return false;
}
public boolean checkWeakness(java.lang.String type1, java.lang.String type2) //checks for weakness
{
    if (type1.equals("Dragon")&&type2.equals("Fairy"))
        return true;
    else if (type1.equals("Fairy")&&type2.equals("Ghost"))
        return true;
    else if (type1.equals("Ghost")&&type2.equals("Dragon"))
        return true;
    else
        return false;
}
public java.lang.String dealCard() //altertately deals cards to each player at the start of the game
{
    if (turnCounter==1)
    {
        for (int i=0; i<5; i++)
        {
            player1.playerHand.add(deck.get(0));
            deck.remove(0);
            System.out.println(player1.getName() + " draws " + player1.playerHand.get(i).getName()+".");
            player2.playerHand.add(deck.get(0));
            deck.remove(0);
            System.out.println(player2.getName() + " draws " + player2.playerHand.get(i).getName()+".");
        }
    }
    else if (turnCounter%2==1) //odd turns = player 1
    {
        if (player1.playerHand.size()==5)
        {
            System.out.println(player1.getName() + "'s hand is full.");
        }
        else if (player1.playerHand.size()<5)
        {
            turnCounter = turnCounter + 1;
            player1.playerHand.add(deck.get(0));
            deck.remove(0);
            System.out.println(player1.getName() + " draws " + player1.playerHand.get(0).getName()+".");
        }
        turnCounter = turnCounter + 1;
    }
    else if (turnCounter%2==0) //even turns = player2
    {
        if (player2.playerHand.size()==5)
        {
            System.out.println(player2.getName() + "'s hand is full.");
        }
        else if (player2.playerHand.size()<5)
        {
            turnCounter = turnCounter + 1;
            player2.playerHand.add(deck.get(0));
            deck.remove(0);
            System.out.println(player2.getName() + " draws " + player2.playerHand.get(0).getName()+".");
        }
        turnCounter = turnCounter;
    }

    return "";
}
public java.lang.String dealDamage(Card inPlay, Card target) //calculates how much damage a card receives, taking into account weakness and resistance
{
    if (checkResistance(target.getType(),inPlay.getType())==true) //if there is resistance
    {
        System.out.println("      "+target.getType() +" is resistant to "+inPlay.getType()+".");
        target.takeHalfDamage(inPlay.getPower());
        checkResistance(inPlay.getType(),target.getType());
        System.out.println("   "+inPlay.getName()+" deals "+inPlay.getPower()/2+" damage on "+target.getName()+".");
        System.out.println("   "+target.getName()+" has "+target.getHealth()+" left.");
    }
    else if (checkWeakness(target.getType(),inPlay.getType())==true) //if there is weakness
    {
        System.out.println("      "+target.getType() +" is weak to "+inPlay.getType()+".");
        target.takeDoubleDamage(inPlay.getPower());
        System.out.println("   "+inPlay.getName()+" deals "+inPlay.getPower()*2+" damage on "+target.getName()+".");
        System.out.println("   "+target.getName()+" has "+target.getHealth()+" left.");
    }
    else //if it does normal damage
    {
        target.takeDamage(inPlay.getPower());
        System.out.println("   "+inPlay.getName()+" deals "+inPlay.getPower()+" damage on "+target.getName()+".");
        System.out.println("   "+target.getName()+" has "+target.getHealth()+" left.");
    }
    return "";
}
public boolean hasWinner() //as long as there is no winner, it is false
{
    return true;
}
public java.lang.String gameReport() //prints out a summary of a game as well as each player's stats
{
    System.out.println("___=== GAME SUMMARY ===___");
    System.out.println("This game lasted "+turnCounter+" turns.");
    System.out.println();
    System.out.println(player1.getName());
    System.out.println("        "+player1.statusReport());
    System.out.println();
    System.out.println(player2.getName());
    System.out.println("        "+player2.statusReport());
    return "";

}
</code>```

This is the runner I currently have called GameConsole.

```<code>import java.util.Scanner;
public class GameConsole
{
    public static void main (String[] args)
    {
    Scanner player = new Scanner(System.in);
    System.out.print("Player 1: ");
    String player1String = player.next(); // input player1 name
    System.out.print("Player 2: ");
    String player2String = player.next(); // input player2 name
    System.out.println("Welcome, "+player1String+" and "+player2String+"!");
    System.out.println("The game begins.");
    Player player1 = new Player(player1String); // turns player1's String name into an object
    Player player2 = new Player(player2String); // turns player2's Strign name into an object
    System.out.println();
    GameMaster game = new GameMaster(player1,player2); // uses the player1 and player2 objects as objects for the GameMAster
    System.out.println();
    Scanner move = new Scanner(System.in);
    System.out.print("Attack or Swap? ");
    String whatMove = move.next(); //input for action

    //i tried putting this in a while-loop but the action won't even execute once
    game.play(whatMove); // executes play for action
    }
}
</code>```

When I run it, this is what happens //user input is in ALL CAPS

```<code>Player 1: ADAM
Player 2: BOB
Welcome, ADAM and BOB!
The game begins.
//space
ADAM draws Aquira.
BOB draws Brawn.
ADAM draws Cerulea.
BOB draws Demi.
ADAM draws Elba.
BOB draws Fye.
ADAM draws Glyede.
BOB draws Hydran.
ADAM draws Ivy.
BOB draws Jet.
//space
Attack or Swap? ATTACK    //SWAP works fine too
   ADAM attacks with Aquira.
      Ghost is weak to Dragon.
   Aquira deals 52 damage on Brawn.
   Brawn has 78 left.
//and then it just stops
</code>```

tbh I'm not completely sure if my code works, but because I don't know how to repeat the action, I wouldn't know...I hope what I said made sense...I'm new to CS so I would appreciate any amount of help.

答:
You are going to need some sort of loop. I'd recommend a while loop around the code that stands for 1 round. (I assume that 1 round is played in the main method)

It depends on when your game has to end as well, for example if your game has to end after 10 rounds you could do something like:

```<code>while(game.turnCounter <= 10) { // Code for one round goes here };
</code>```

Else you could make a boolean that checks if the game is finished.

```<code>while(!game.gameIsFinshed) { // Code for one round goes here };
</code>```

Body:
I created this card game that asks the user for an action. "attack" and "swap". they both work fine on the first execution, but how do I make it so that the system keeps asking the user for an action until one of the player wins?

This contains my code for the class GameMaster that the GameConsole will reference. It has links to two other classes I have called Player and Card.

import java.util.*;
public class GameMaster
{
private int turnCounter = 0;
private ArrayList<Card> deck;
private boolean isThereWinner;
private Player player1;
private Player player2;
public GameMaster (Player a, Player b) //initializes values
{
    turnCounter = turnCounter + 1;
    player1 = a;
    player2 = b;
    deck = new ArrayList<Card>();
    assembleDeck();
    dealCard();
}
private void assembleDeck() //given order of cards
{
    deck.add( new Card( "Dragon", "Aquira", 174, 26 ) );
    deck.add( new Card( "Ghost", "Brawn", 130, 48 ) );
    deck.add( new Card( "Fairy", "Cerulea", 162, 29 ) );
    deck.add( new Card( "Dragon", "Demi", 147, 28 ) );
    deck.add( new Card( "Ghost", "Elba", 155, 37 ) );
    deck.add( new Card( "Fairy", "Fye", 159, 42 ) );
    deck.add( new Card( "Dragon", "Glyede", 129, 26 ) );
    deck.add( new Card( "Ghost", "Hydran", 163, 35 ) );
    deck.add( new Card( "Fairy", "Ivy", 146, 45 ) );
    deck.add( new Card( "Dragon", "Jet", 170, 24 ) );
    deck.add( new Card( "Ghost", "Kineti", 139, 21 ) );
    deck.add( new Card( "Fairy", "Levi", 160, 43 ) );
    deck.add( new Card( "Dragon", "Meadow", 134, 29 ) );
    deck.add( new Card( "Ghost", "Naidem", 165, 26 ) );
    deck.add( new Card( "Fairy", "Omi", 145, 21 ) );
    deck.add( new Card( "Dragon", "Puddles", 170, 34 ) );
    deck.add( new Card( "Ghost", "Quarrel", 151, 29 ) );
    deck.add( new Card( "Fairy", "Raven", 168, 32 ) );
    deck.add( new Card( "Dragon", "Surge", 128, 27 ) );
    deck.add( new Card( "Ghost", "Takiru", 140, 26 ) );
    deck.add( new Card( "Fairy", "Ustelia", 163, 47 ) );
    deck.add( new Card( "Dragon", "Verwyn", 145, 25 ) );
    deck.add( new Card( "Ghost", "Wyverin", 158, 32 ) );
    deck.add( new Card( "Fairy", "Xios", 155, 27 ) );
    deck.add( new Card( "Dragon", "Yora", 159, 44 ) );
    deck.add( new Card( "Ghost", "Zulu", 125, 46 ) );
}
public java.lang.String play (java.lang.String action) // lets player enter action swap or attack
{
   if (turnCounter%2==1) //player 1's turn
   {
        if (action.equals("swap")) // if player one enters "swap"
        {
            turnCounter = turnCounter + 1;
            System.out.println("   "+player1.getName() + " swaps out " + player1.getActiveCard().getName()+".");
            player1.swap();

        }
        else if (action.equals("attack")) // if player one enter "attack"
        {
            turnCounter = turnCounter + 1;
            System.out.println("   "+player1.getName() + " attacks with " + player1.getActiveCard().getName()+".");
            dealDamage(player1.getActiveCard(), player2.getActiveCard());

            if (player2.getActiveCard().getHealth()<1) //if player 2's health goes below 1
            {
                player2.discard();
                System.out.println("   "+player2.getName() + " discards " + player2.getActiveCard().getName());
                player2.drawCard(deck.get(0));
                System.out.println(player2.getName() + " draws " + deck.get(0)+".");
                if (deck.size()==0) // if there are no more cards in the deck
                {
                    System.out.println("The deck is empty.");
                }
                player1.claimToken();
                System.out.println("   "+player1.getName() + " gets a token!");
                if (player1.getTokens()==3) //if player1 kills three of player2's cards = 3 tokens
                {
                    hasWinner();
                    System.out.println(player1.getName() + " wins!");
                }
            }
        }
    }
    else if (turnCounter%2==0) //player 2's turn
    {
        if (action.equals("swap")) //if player 2 chooses "swap"
        {
            turnCounter = turnCounter + 1;
            System.out.println("   "+player2.getActiveCard().getName() + " swaps out " + player2.getActiveCard().getName());
            player2.swap();

        }
        else if (action.equals("attack")) //if player two chooses "attack"
        {
            turnCounter = turnCounter + 1;
            System.out.println("   "+player2.getName() + " attacks with " + player2.getActiveCard());
            dealDamage(player2.getActiveCard(), player1.getActiveCard());
            if (player1.getActiveCard().getHealth()<1) //if player 1's health drops below 1
            {
                player1.discard();
                System.out.println("   "+player1.getName() + " discards " + player1.getActiveCard().getName());
                player1.drawCard(deck.get(0));
                System.out.println("   "+player1.getName() + " draws " + deck.get(0)+".");
                if (deck.size()==0) //if there are no more cards in the deck
                {
                    System.out.println("The deck is empty.");
                }
                player2.claimToken();
                System.out.println("   "+player2.getName() + " gets a token!");
                if (player2.getTokens()==3) //if player 2 kills 3 of player1's cards = get three tokens
                {
                    hasWinner();
                    System.out.println(player2.getName() + " wins!");
                }
            }

        }

   }
   return "";
}
public boolean checkResistance(java.lang.String type1, java.lang.String type2) //checks for resistance
{
    if (type1.equals("Dragon")&&type2.equals("Ghost"))
        return true;
    else if (type1.equals("Ghost")&&type2.equals("Fairy"))
        return true;
    else if (type1.equals("Fairy")&&type2.equals("Dragon"))
        return true;
    else
        return false;
}
public boolean checkWeakness(java.lang.String type1, java.lang.String type2) //checks for weakness
{
    if (type1.equals("Dragon")&&type2.equals("Fairy"))
        return true;
    else if (type1.equals("Fairy")&&type2.equals("Ghost"))
        return true;
    else if (type1.equals("Ghost")&&type2.equals("Dragon"))
        return true;
    else
        return false;
}
public java.lang.String dealCard() //altertately deals cards to each player at the start of the game
{
    if (turnCounter==1)
    {
        for (int i=0; i<5; i++)
        {
            player1.playerHand.add(deck.get(0));
            deck.remove(0);
            System.out.println(player1.getName() + " draws " + player1.playerHand.get(i).getName()+".");
            player2.playerHand.add(deck.get(0));
            deck.remove(0);
            System.out.println(player2.getName() + " draws " + player2.playerHand.get(i).getName()+".");
        }
    }
    else if (turnCounter%2==1) //odd turns = player 1
    {
        if (player1.playerHand.size()==5)
        {
            System.out.println(player1.getName() + "'s hand is full.");
        }
        else if (player1.playerHand.size()<5)
        {
            turnCounter = turnCounter + 1;
            player1.playerHand.add(deck.get(0));
            deck.remove(0);
            System.out.println(player1.getName() + " draws " + player1.playerHand.get(0).getName()+".");
        }
        turnCounter = turnCounter + 1;
    }
    else if (turnCounter%2==0) //even turns = player2
    {
        if (player2.playerHand.size()==5)
        {
            System.out.println(player2.getName() + "'s hand is full.");
        }
        else if (player2.playerHand.size()<5)
        {
            turnCounter = turnCounter + 1;
            player2.playerHand.add(deck.get(0));
            deck.remove(0);
            System.out.println(player2.getName() + " draws " + player2.playerHand.get(0).getName()+".");
        }
        turnCounter = turnCounter;
    }

    return "";
}
public java.lang.String dealDamage(Card inPlay, Card target) //calculates how much damage a card receives, taking into account weakness and resistance
{
    if (checkResistance(target.getType(),inPlay.getType())==true) //if there is resistance
    {
        System.out.println("      "+target.getType() +" is resistant to "+inPlay.getType()+".");
        target.takeHalfDamage(inPlay.getPower());
        checkResistance(inPlay.getType(),target.getType());
        System.out.println("   "+inPlay.getName()+" deals "+inPlay.getPower()/2+" damage on "+target.getName()+".");
        System.out.println("   "+target.getName()+" has "+target.getHealth()+" left.");
    }
    else if (checkWeakness(target.getType(),inPlay.getType())==true) //if there is weakness
    {
        System.out.println("      "+target.getType() +" is weak to "+inPlay.getType()+".");
        target.takeDoubleDamage(inPlay.getPower());
        System.out.println("   "+inPlay.getName()+" deals "+inPlay.getPower()*2+" damage on "+target.getName()+".");
        System.out.println("   "+target.getName()+" has "+target.getHealth()+" left.");
    }
    else //if it does normal damage
    {
        target.takeDamage(inPlay.getPower());
        System.out.println("   "+inPlay.getName()+" deals "+inPlay.getPower()+" damage on "+target.getName()+".");
        System.out.println("   "+target.getName()+" has "+target.getHealth()+" left.");
    }
    return "";
}
public boolean hasWinner() //as long as there is no winner, it is false
{
    return true;
}
public java.lang.String gameReport() //prints out a summary of a game as well as each player's stats
{
    System.out.println("___=== GAME SUMMARY ===___");
    System.out.println("This game lasted "+turnCounter+" turns.");
    System.out.println();
    System.out.println(player1.getName());
    System.out.println("        "+player1.statusReport());
    System.out.println();
    System.out.println(player2.getName());
    System.out.println("        "+player2.statusReport());
    return "";

}

This is the runner I currently have called GameConsole.

import java.util.Scanner;
public class GameConsole
{
    public static void main (String[] args)
    {
    Scanner player = new Scanner(System.in);
    System.out.print("Player 1: ");
    String player1String = player.next(); // input player1 name
    System.out.print("Player 2: ");
    String player2String = player.next(); // input player2 name
    System.out.println("Welcome, "+player1String+" and "+player2String+"!");
    System.out.println("The game begins.");
    Player player1 = new Player(player1String); // turns player1's String name into an object
    Player player2 = new Player(player2String); // turns player2's Strign name into an object
    System.out.println();
    GameMaster game = new GameMaster(player1,player2); // uses the player1 and player2 objects as objects for the GameMAster
    System.out.println();
    Scanner move = new Scanner(System.in);
    System.out.print("Attack or Swap? ");
    String whatMove = move.next(); //input for action

    //i tried putting this in a while-loop but the action won't even execute once
    game.play(whatMove); // executes play for action
    }
}

When I run it, this is what happens //user input is in ALL CAPS

Player 1: ADAM
Player 2: BOB
Welcome, ADAM and BOB!
The game begins.
//space
ADAM draws Aquira.
BOB draws Brawn.
ADAM draws Cerulea.
BOB draws Demi.
ADAM draws Elba.
BOB draws Fye.
ADAM draws Glyede.
BOB draws Hydran.
ADAM draws Ivy.
BOB draws Jet.
//space
Attack or Swap? ATTACK    //SWAP works fine too
   ADAM attacks with Aquira.
      Ghost is weak to Dragon.
   Aquira deals 52 damage on Brawn.
   Brawn has 78 left.
//and then it just stops

tbh I'm not completely sure if my code works, but because I don't know how to repeat the action, I wouldn't know...I hope what I said made sense...I'm new to CS so I would appreciate any amount of help.

Body:
You are going to need some sort of loop. I'd recommend a while loop around the code that stands for 1 round. (I assume that 1 round is played in the main method)

It depends on when your game has to end as well, for example if your game has to end after 10 rounds you could do something like:

while(game.turnCounter <= 10) { // Code for one round goes here };

Else you could make a boolean that checks if the game is finished.

while(!game.gameIsFinshed) { // Code for one round goes here };


问:
SQL Query to query data hierarchically in the same table
I have the following table, which has a list of subjects and objects related with the same relationship.

```
    |---------------------------------------|
    |Subject    |Relationship    |Object    |
    |---------------------------------------|
    |A          |x               |B         |
    |B          |x               |C         |
    |B          |x               |D         |
    |C          |x               |E         |
    |D          |x               |F         |
    |P          |x               |G         |
    |---------------------------------------|
```

My need is to write a SQL to get all the related Subjects and Objects given an initial subject.

For example:

If "C" is given as the initial subject, output should be "C" and "E" (because "C" related to "E" with "x")

If "A" is given as the initial subject, output should be "A", "B", "C", "D", "E" and "F". Explanation,

"A" is related to "B"

"B" is related to "C" and "D"

"C" is related to "E"

"D" is related to "F"

答:
Use recursive query

```<code>with rcte as
(
  select *
  from data
  where subject = 'a'
  union all
  select d.*
  from data d
  join rcte r on r.object = d.subject
)
select r.subject from rcte r
union
select r.object from rcte r
</code>```

demo

Body:
I have the following table, which has a list of subjects and objects related with the same relationship.

    |---------------------------------------|
    |Subject    |Relationship    |Object    |
    |---------------------------------------|
    |A          |x               |B         |
    |B          |x               |C         |
    |B          |x               |D         |
    |C          |x               |E         |
    |D          |x               |F         |
    |P          |x               |G         |
    |---------------------------------------|

My need is to write a SQL to get all the related Subjects and Objects given an initial subject.

For example:

If "C" is given as the initial subject, output should be "C" and "E" (because "C" related to "E" with "x")

If "A" is given as the initial subject, output should be "A", "B", "C", "D", "E" and "F". Explanation,

"A" is related to "B"

"B" is related to "C" and "D"

"C" is related to "E"

"D" is related to "F"

Body:
Use recursive query

with rcte as
(
  select *
  from data
  where subject = 'a'
  union all
  select d.*
  from data d
  join rcte r on r.object = d.subject
)
select r.subject from rcte r
union
select r.object from rcte r

demo


问:
Include attachment where the name matches recipient name
I have code in Excel which sends email to a list of recipients:

```<code>Sub SendEMail()
    Dim xEmail As String
    Dim xSubj As String
    Dim xMsg As String
    Dim xURL As String
    Dim i As Integer
    Dim k As Double
    Dim xCell As Range
    Dim xRg As Range
    Dim xTxt As String
    On Error Resume Next
    xTxt = ActiveWindow.RangeSelection.Address
    Set xRg = Application.InputBox("Please select the data range:", "Send emails to:", xTxt, , , , , 8)
    If xRg Is Nothing Then Exit Sub
    If xRg.Columns.Count <> 3 Then
        MsgBox "Incorrect number of columns: You have to choose Name, Email address, Account no.!"
        Exit Sub
    End If
    For i = 1 To xRg.Rows.Count
    '   Get the email address
        xEmail = xRg.Cells(i, 2)
    '   Message subject
        xSubj = "Your customer's account is on hold"
    '   Compose the message
        xMsg = ""
        xMsg = xMsg & "Dear client" & "," & vbCrLf & vbCrLf
        xMsg = xMsg & "We would like to inform you, that Your account has been put on hold - "
        xMsg = xMsg & xRg.Cells(i, 3).Text & "." & vbCrLf & vbCrLf
        xMsg = xMsg & "If you have any queries, please contact us on uk.ar@bodycote.com." & vbCrLf & vbCrLf
        xMsg = xMsg & "Kind regards," & vbCrLf
        xMsg = xMsg & "Jon and Martina"
    '   Replace spaces with %20 (hex)
        xSubj = Application.WorksheetFunction.Substitute(xSubj, " ", "%20")
        xMsg = Application.WorksheetFunction.Substitute(xMsg, " ", "%20")
    '   Replace carriage returns with %0D%0A (hex)
        xMsg = Application.WorksheetFunction.Substitute(xMsg, vbCrLf, "%0D%0A")
    '   Create the URL
        xURL = "mailto:" & xEmail & "?subject=" & xSubj & "&body=" & xMsg
    '   Execute the URL (start the email client)
        ShellExecute 0&, vbNullString, xURL, vbNullString, vbNullString, vbNormalFocus
    '   Wait two seconds before sending keystrokes
        Application.Wait (Now + TimeValue("0:00:02"))
        Application.SendKeys "%s"
    Next
End Sub
</code>```

I would like to add variable attachments. It will be a pdf file and its name will be the same as the name of customer (which is placed in column A). Basically it should look for "Name.pdf" in "S:\All Team\AX OTI\test\"

The source table looks like:

答:
Please try to use the below code.</p>

```<code>        xMsg = xMsg & "Dear client" & xRg.Cells(i, 1)  & "," & vbCrLf & vbCrLf 'Added the client Name (optional) you can remove it
        xMsg = xMsg & "We would like to inform you, that Your account has been put on hold - "
        xMsg = xMsg & xRg.Cells(i, 3).Text & "." & vbCrLf & vbCrLf
        xMsg = xMsg & "If you have any queries, please contact us on uk.ar@bodycote.com." & vbCrLf & vbCrLf
        xMsg = xMsg & "Kind regards," & vbCrLf

        xMsg = xMsg & "Jon and Martina" & vbCrLf & vbCrLf 'Added two break point

        '       Replace spaces with %20 (hex)
        xSubj = Application.WorksheetFunction.Substitute(xSubj, " ", "%20")
        xMsg = Application.WorksheetFunction.Substitute(xMsg, " ", "%20")
'       Replace carriage returns with %0D%0A (hex)
        xMsg = Application.WorksheetFunction.Substitute(xMsg, vbCrLf, "%0D%0A")
'       Create the URL
        xURL = "mailto:" & xEmail & "?subject=" & xSubj & "&body=" & xMsg &"&attachment=S:\All Team\AX OTI\test\" & Cells(i,1) & ".pdf" 'Changed to this
'       Execute the URL (start the email client)
        ShellExecute 0&, vbNullString, xURL, vbNullString, vbNullString, vbNormalFocus
'       Wait two seconds before sending keystrokes
        Application.Wait (Now + TimeValue("0:00:02"))
        Application.SendKeys "%s"
</code>```

Body:
I have code in Excel which sends email to a list of recipients:

Sub SendEMail()
    Dim xEmail As String
    Dim xSubj As String
    Dim xMsg As String
    Dim xURL As String
    Dim i As Integer
    Dim k As Double
    Dim xCell As Range
    Dim xRg As Range
    Dim xTxt As String
    On Error Resume Next
    xTxt = ActiveWindow.RangeSelection.Address
    Set xRg = Application.InputBox("Please select the data range:", "Send emails to:", xTxt, , , , , 8)
    If xRg Is Nothing Then Exit Sub
    If xRg.Columns.Count <> 3 Then
        MsgBox "Incorrect number of columns: You have to choose Name, Email address, Account no.!"
        Exit Sub
    End If
    For i = 1 To xRg.Rows.Count
    '   Get the email address
        xEmail = xRg.Cells(i, 2)
    '   Message subject
        xSubj = "Your customer's account is on hold"
    '   Compose the message
        xMsg = ""
        xMsg = xMsg & "Dear client" & "," & vbCrLf & vbCrLf
        xMsg = xMsg & "We would like to inform you, that Your account has been put on hold - "
        xMsg = xMsg & xRg.Cells(i, 3).Text & "." & vbCrLf & vbCrLf
        xMsg = xMsg & "If you have any queries, please contact us on uk.ar@bodycote.com." & vbCrLf & vbCrLf
        xMsg = xMsg & "Kind regards," & vbCrLf
        xMsg = xMsg & "Jon and Martina"
    '   Replace spaces with %20 (hex)
        xSubj = Application.WorksheetFunction.Substitute(xSubj, " ", "%20")
        xMsg = Application.WorksheetFunction.Substitute(xMsg, " ", "%20")
    '   Replace carriage returns with %0D%0A (hex)
        xMsg = Application.WorksheetFunction.Substitute(xMsg, vbCrLf, "%0D%0A")
    '   Create the URL
        xURL = "mailto:" & xEmail & "?subject=" & xSubj & "&body=" & xMsg
    '   Execute the URL (start the email client)
        ShellExecute 0&, vbNullString, xURL, vbNullString, vbNullString, vbNormalFocus
    '   Wait two seconds before sending keystrokes
        Application.Wait (Now + TimeValue("0:00:02"))
        Application.SendKeys "%s"
    Next
End Sub

I would like to add variable attachments. It will be a pdf file and its name will be the same as the name of customer (which is placed in column A). Basically it should look for "Name.pdf" in "S:\All Team\AX OTI\test\"

The source table looks like:

Body:
Please try to use the below code.

        xMsg = xMsg & "Dear client" & xRg.Cells(i, 1)  & "," & vbCrLf & vbCrLf 'Added the client Name (optional) you can remove it
        xMsg = xMsg & "We would like to inform you, that Your account has been put on hold - "
        xMsg = xMsg & xRg.Cells(i, 3).Text & "." & vbCrLf & vbCrLf
        xMsg = xMsg & "If you have any queries, please contact us on uk.ar@bodycote.com." & vbCrLf & vbCrLf
        xMsg = xMsg & "Kind regards," & vbCrLf

        xMsg = xMsg & "Jon and Martina" & vbCrLf & vbCrLf 'Added two break point

        '       Replace spaces with %20 (hex)
        xSubj = Application.WorksheetFunction.Substitute(xSubj, " ", "%20")
        xMsg = Application.WorksheetFunction.Substitute(xMsg, " ", "%20")
'       Replace carriage returns with %0D%0A (hex)
        xMsg = Application.WorksheetFunction.Substitute(xMsg, vbCrLf, "%0D%0A")
'       Create the URL
        xURL = "mailto:" & xEmail & "?subject=" & xSubj & "&body=" & xMsg &"&attachment=S:\All Team\AX OTI\test\" & Cells(i,1) & ".pdf" 'Changed to this
'       Execute the URL (start the email client)
        ShellExecute 0&, vbNullString, xURL, vbNullString, vbNullString, vbNormalFocus
'       Wait two seconds before sending keystrokes
        Application.Wait (Now + TimeValue("0:00:02"))
        Application.SendKeys "%s"