答:
use properly Template literals (Template strings)

```<code>str += `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;
</code>```

let typearray=["supermarkets_and_groceries", "churches", "cafes"];
let type = "supermarkets_and_groceries";
function changeType(randomstring){
    console.log('ok');
    type = randomstring;
    console.log(randomstring);
}

let str = '
';
for(let count = 0; count < typearray.length; count++){
    str += `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;
}
str = str + '
' +
'
';
console.log(str);

document.getElementById('navbar').innerHTML = str;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1">
    <meta charset="utf-8">
    <style>
      #map {
        height: 75%;
        width: 75%;
      }
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <script src = getlocation.js></script>
    <!-- this implements the navbar-->
    <div id="navbar"></div>
    <script type = "module" src = navbar.js></script>
    <!-- this implements the map-->
    <div id="map"></div>
    <script src = index.js> </script>
    <!-- this implements the list-->
    <div id="list"></div>
    <script type = "module" src = rankedstores.js></script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD2c7P_IihiITITslXAk-wWy9z067xjFQU
    &callback=initMap"></script>
  </body>
</html></code>```

use properly Template literals (Template strings)

```<code>str += `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;
</code>```

Title: Uncaught Reference Error when trying to pass a function through a button in JavaScript?

Body:
I'm trying to write a navigation bar at the top of my web app to change a parameter in backend, but when I call the function it always return an unexpected end of input or an uncaught reference error that says my function was not defined on click. Can someone please help me figure out what I'm doing wrong?

JS File:

let typearray=["supermarkets_and_groceries", "churches", "cafes"];
let type = "supermarkets_and_groceries";
function changeType(randomstring){
    console.log('ok');
    type = randomstring;
    console.log(type);
}

let str = '
';
for(let count = 0; count < typearray.length; count++){
    str = str +
    '<button onclick ="changeType("'+typearray[count]+'")" title = " '+ typearray[count] + '">' +typearray[count] +'</button>';
}
str = str + '
' +
'
';
console.log(str);

document.getElementById('navbar').innerHTML = str;

HTML File(includes the rest of the program)

    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1">
    <meta charset="utf-8">

Body:
use properly Template literals (Template strings)

str += `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;

let typearray=["supermarkets_and_groceries", "churches", "cafes"];
let type = "supermarkets_and_groceries";
function changeType(randomstring){
    console.log('ok');
    type = randomstring;
    console.log(randomstring);
}

let str = '<div class="topnav" />';
for(let count = 0; count < typearray.length; count++){
    str += `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;
}
str = str + '</div>' +
'</div>';
console.log(str);

document.getElementById('navbar').innerHTML = str;

<html>
  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1">
    <meta charset="utf-8">
    <style>
      #map {
        height: 75%;
        width: 75%;
      }
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <script src = getlocation.js></script>
    <!-- this implements the navbar-->
    <div id="navbar"></div>
    <script type = "module" src = navbar.js></script>
    <!-- this implements the map-->
    <div id="map"></div>
    <script src = index.js> </script>
    <!-- this implements the list-->
    <div id="list"></div>
    <script type = "module" src = rankedstores.js></script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD2c7P_IihiITITslXAk-wWy9z067xjFQU
    &callback=initMap"></script>
  </body>
</html>

use properly Template literals (Template strings)

str += `<button onclick="changeType('${typearray[count]}')" title ="${typearray[count]}"> ${typearray[count]} </button>`;


来源: stackexchange

问:
Is there any way to disconnect a client connection of socket.io in the server.js?
I know the client part may use disconnect method to disconnect a client connection.
but I can't find any way to disconnect from the server part.</p>

```<code>socket.on('connection', function(client) {

    client.on('message', function(message) {
                var sessionId = message.disId;
        socket.disconnect(sessionId);//to disconnect another client
    });

});
</code>```

答:
The server can kick a particular client by using either of these methods:

client._onDisconnect();

(or)

socket.clients[kickedUserSocketId].onDisconnect();

Credit to SeanColombo on GitHub

ContentLicense: CC BY-SA 3.0

Body:
I know the client part may use disconnect method to disconnect a client connection.
but I can't find any way to disconnect from the server part.

socket.on('connection', function(client) {

    client.on('message', function(message) {
                var sessionId = message.disId;
        socket.disconnect(sessionId);//to disconnect another client
    });

});


问:
How to group every other unique value in pandas dataframe outside top 5 values (by size) into an 'Other' category for plotting and tabling?
I have a column Order with over 75 unique values of items (Clothes, Appliances, Electronics, etc.) and over 1000 entries in total. When I try to plot any descriptive statistics on a graph over a period of time (important: not all order items are non-zero in all periods of time), it becomes hard to read the graph because of how small some of the values are in comparison to others.

For that reason I think it would be better for me to just show the values of the top 3-5 order items (by size/count) and then group the rest into a category called Other just for plotting and groupby/pivot tabling purposes.

I guess I could map the values, but that is too time consuming, and it would also require me to change the existing values for the non top 3-5 represented entries - which is not something that I want to do.

How would I do that?

```<code>Sample data
Year    Month        Type          cancelled
2012      1        electronics       yes
2012      10         fiber           yes
2012      9         clothes          no
2013      4        vegetables        yes
2013      5        appliances        no
2016      3        fiber             no
2017      1        clothes           yes
</code>```

答:
Use:

```<code>print (df)
    Year  Month         Type cancelled
0   2012      1  electronics       yes
1   2012      1        fiber       yes
2   2012      3      clothes        no
3   2012      3   vegetables       yes
4   2012      3   appliances        no
5   2012      3        fiber        no
6   2012      1      clothes       yes
7   2012      1  electronics       yes
8   2012      1        fiber       yes
9   2012      1      clothes        no
10  2012      3   vegetables       yes
11  2012      3   appliances        no
12  2012      3        fiber        no
13  2012      1      clothes       yes
14  2012      1  electronics       yes
15  2012      1        fiber       yes
16  2012      1      clothes        no
17  2012      1   vegetables       yes
18  2012      3   appliances        no
19  2012      3        fiber        no
20  2012      1      clothes       yes
</code>```

Idea is create top3 value per groups by Year and Month:

```<code>N = 3
df1 = (df.groupby(['Year', 'Month'])['Type'].value_counts()
         .groupby(level=[0,1]).head(N)
          .reset_index(name='count')
         )
print (df1)
   Year  Month         Type  count
0  2012      1      clothes      5
1  2012      1  electronics      3
2  2012      1        fiber      3
3  2012      3   appliances      3
4  2012      3        fiber      3
5  2012      3   vegetables      2
</code>```

Then merge to original by left join and replace other to values with no in top3 by Series.mask:

```<code>df = df.merge(df1, how='left')
df['Type'] = df['Type'].mask(df.pop('count').isna(), 'other')
print (df)
    Year  Month         Type cancelled
0   2012      1  electronics       yes
1   2012      1        fiber       yes
2   2012      3      clothes        no
3   2012      3   vegetables       yes
4   2012      3   appliances        no
5   2012      3        fiber        no
6   2012      1      clothes       yes
7   2012      1  electronics       yes
8   2012      1        fiber       yes
9   2012      1      clothes        no
10  2012      3   vegetables       yes
11  2012      3   appliances        no
12  2012      3        fiber        no
13  2012      1      clothes       yes
14  2012      1  electronics       yes
15  2012      1        fiber       yes
16  2012      1      clothes        no
17  2012      1   vegetables       yes
18  2012      3   appliances        no
19  2012      3        fiber        no
20  2012      1      clothes       yes
</code>```

If need replace all values without top3 not per groups:

```<code>N = 3
s = df['Type'].value_counts().head(N)
print (s)
clothes       6
fiber         6
appliances    3
Name: Type, dtype: int64

df['Type'] = df['Type'].where(df['Type'].isin(s.index), 'other')
print (df)
    Year  Month        Type cancelled
0   2012      1       other       yes
1   2012      1       fiber       yes
2   2012      3     clothes        no
3   2012      3       other       yes
4   2012      3  appliances        no
5   2012      3       fiber        no
6   2012      1     clothes       yes
7   2012      1       other       yes
8   2012      1       fiber       yes
9   2012      1     clothes        no
10  2012      3       other       yes
11  2012      3  appliances        no
12  2012      3       fiber        no
13  2012      1     clothes       yes
14  2012      1       other       yes
15  2012      1       fiber       yes
16  2012      1     clothes        no
17  2012      1       other       yes
18  2012      3  appliances        no
19  2012      3       fiber        no
20  2012      1     clothes       yes
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a column Order with over 75 unique values of items (Clothes, Appliances, Electronics, etc.) and over 1000 entries in total. When I try to plot any descriptive statistics on a graph over a period of time (important: not all order items are non-zero in all periods of time), it becomes hard to read the graph because of how small some of the values are in comparison to others.

For that reason I think it would be better for me to just show the values of the top 3-5 order items (by size/count) and then group the rest into a category called Other just for plotting and groupby/pivot tabling purposes.

I guess I could map the values, but that is too time consuming, and it would also require me to change the existing values for the non top 3-5 represented entries - which is not something that I want to do.

How would I do that?

Sample data
Year    Month        Type          cancelled
2012      1        electronics       yes
2012      10         fiber           yes
2012      9         clothes          no
2013      4        vegetables        yes
2013      5        appliances        no
2016      3        fiber             no
2017      1        clothes           yes

Body:
Use:

print (df)
    Year  Month         Type cancelled
0   2012      1  electronics       yes
1   2012      1        fiber       yes
2   2012      3      clothes        no
3   2012      3   vegetables       yes
4   2012      3   appliances        no
5   2012      3        fiber        no
6   2012      1      clothes       yes
7   2012      1  electronics       yes
8   2012      1        fiber       yes
9   2012      1      clothes        no
10  2012      3   vegetables       yes
11  2012      3   appliances        no
12  2012      3        fiber        no
13  2012      1      clothes       yes
14  2012      1  electronics       yes
15  2012      1        fiber       yes
16  2012      1      clothes        no
17  2012      1   vegetables       yes
18  2012      3   appliances        no
19  2012      3        fiber        no
20  2012      1      clothes       yes

Idea is create top3 value per groups by Year and Month:

N = 3
df1 = (df.groupby(['Year', 'Month'])['Type'].value_counts()
         .groupby(level=[0,1]).head(N)
          .reset_index(name='count')
         )
print (df1)
   Year  Month         Type  count
0  2012      1      clothes      5
1  2012      1  electronics      3
2  2012      1        fiber      3
3  2012      3   appliances      3
4  2012      3        fiber      3
5  2012      3   vegetables      2

Then merge to original by left join and replace other to values with no in top3 by Series.mask:

df = df.merge(df1, how='left')
df['Type'] = df['Type'].mask(df.pop('count').isna(), 'other')
print (df)
    Year  Month         Type cancelled
0   2012      1  electronics       yes
1   2012      1        fiber       yes
2   2012      3      clothes        no
3   2012      3   vegetables       yes
4   2012      3   appliances        no
5   2012      3        fiber        no
6   2012      1      clothes       yes
7   2012      1  electronics       yes
8   2012      1        fiber       yes
9   2012      1      clothes        no
10  2012      3   vegetables       yes
11  2012      3   appliances        no
12  2012      3        fiber        no
13  2012      1      clothes       yes
14  2012      1  electronics       yes
15  2012      1        fiber       yes
16  2012      1      clothes        no
17  2012      1   vegetables       yes
18  2012      3   appliances        no
19  2012      3        fiber        no
20  2012      1      clothes       yes

If need replace all values without top3 not per groups:

N = 3
s = df['Type'].value_counts().head(N)
print (s)
clothes       6
fiber         6
appliances    3
Name: Type, dtype: int64

df['Type'] = df['Type'].where(df['Type'].isin(s.index), 'other')
print (df)
    Year  Month        Type cancelled
0   2012      1       other       yes
1   2012      1       fiber       yes
2   2012      3     clothes        no
3   2012      3       other       yes
4   2012      3  appliances        no
5   2012      3       fiber        no
6   2012      1     clothes       yes
7   2012      1       other       yes
8   2012      1       fiber       yes
9   2012      1     clothes        no
10  2012      3       other       yes
11  2012      3  appliances        no
12  2012      3       fiber        no
13  2012      1     clothes       yes
14  2012      1       other       yes
15  2012      1       fiber       yes
16  2012      1     clothes        no
17  2012      1       other       yes
18  2012      3  appliances        no
19  2012      3       fiber        no
20  2012      1     clothes       yes


问:
pandas.read_excel parameter "sheet_name" not working
According to pandas doc for 0.21+, pandas.read_excel has a parameter sheet_name that allows specifying which sheet is read. But when I am trying to read the second sheet from an excel file, no matter how I set the parameter (sheet_name = 1, sheet_name = 'Sheet2'), the dataframe always shows the first sheet, and passing a list of indices (sheet_name = [0, 1]) does not return a dictionary of dataframes but still the first sheet. What might be the problem here?

答:
Try at Terminal, type the following first, then re-run your program:

pip install xlrd


问:
How to increment a foor loop within a nested if statement
Im distinguishing 2 players in TicTacToe by utilising MOD, which is used upon an incrementing for loop. Im having trouble incrementing the foor loop within a nested if statement. </p>

```<code>            for i in range (1,10):
                if i % 2==1:
                    #1st row
                    if click[0]<=250 and click[0]>=100 and click[1]<=250 and click[1]>=100:
                        current_game[0][0] = "X"
                        i+=1
                    elif click[0]<=550 and click[0]>=250 and click[1]<=250 and click[1]>=100:
                        current_game[0][1] = "X"
                        i += 1
                    elif click[0]<=700 and click[0]>=550 and click[1]<=250 and click[1]>=100:
                        current_game[0][2] = "X"
                        i += 1
                    #2nd row
                    elif click[0]<=250 and click[0]>=100 and click[1]<= 550and click[1]>=250:
                        current_game[1][0] = "X"
                        i += 1
                    elif click[0]<=550 and click[0]>=250 and click[1]<=550 and click[1]>=250:
                        current_game[1][1] = "X"
                        i += 1
                    elif click[0] <= 700 and click[0] >= 550 and click[1] <= 550 and click[1] >= 250:
                        current_game[1][2] = "X"
                        i += 1
                    #3rd row
                    elif click[0]<=250 and click[0]>=100 and click[1]<= 700and click[1]>=550:
                        current_game[2][0] = "X"
                        i += 1
                    elif click[0] <= 550 and click[0] >= 250 and click[1] <= 700 and click[1] >= 550:
                        current_game[2][1] = "X"
                        i += 1
                    elif click[0] <= 700 and click[0] >= 550 and click[1] <= 700 and click[1] >= 550:
                        current_game[2][2] = "X"
                        i += 1
                elif i % 2==0:
                    # 1st row
                    if click[0] <= 250 and click[0] >= 100 and click[1] <= 250 and click[1] >= 100:
                        current_game[0][0] = "o"
                        i += 1
                    elif click[0] <= 550 and click[0] >= 250 and click[1] <= 250 and click[1] >= 100:
                        current_game[0][1] = "o"
                        i += 1
                    elif click[0] <= 700 and click[0] >= 550 and click[1] <= 250 and click[1] >= 100:
                        current_game[0][2] = "o"
                        i += 1
                    # 2nd row
                    elif click[0] <= 250 and click[0] >= 100 and click[1] <= 550 and click[1] >= 250:
                        current_game[1][0] = "o"
                        i += 1
                    elif click[0] <= 550 and click[0] >= 250 and click[1] <= 550 and click[1] >= 250:
                        current_game[1][1] = "o"
                        i += 1
                    elif click[0] <= 700 and click[0] >= 550 and click[1] <= 550 and click[1] >= 250:
                        current_game[1][2] = "o"
                        i += 1
                    # 3rd row
                    elif click[0] <= 250 and click[0] >= 100 and click[1] <= 700 and click[1] >= 550:
                        current_game[2][0] = "o"
                        i += 1
                    elif click[0] <= 550 and click[0] >= 250 and click[1] <= 700 and click[1] >= 550:
                        current_game[2][1] = "o"
                        i += 1
                    elif click[0] <= 700 and click[0] >= 550 and click[1] <= 700 and click[1] >= 550:
                        current_game[2][2] = "o"
                        i += 1
</code>```

<p>I want to be able to increment the for loop if someone clicks on a certain co-ordinate space. </p>

答:
The expression range(n) is evaluated just once, not on every iteration. You can't set n and expect the range(n) be changed. It doesn't allow this. Check it here for details

You have to use while loop for that.

```<code>i=0
while i<=5:
    #do your tasks
    #do your increment
</code>```

Body:
Im distinguishing 2 players in TicTacToe by utilising MOD, which is used upon an incrementing for loop. Im having trouble incrementing the foor loop within a nested if statement.

            for i in range (1,10):
                if i % 2==1:
                    #1st row
                    if click[0]<=250 and click[0]>=100 and click[1]<=250 and click[1]>=100:
                        current_game[0][0] = "X"
                        i+=1
                    elif click[0]<=550 and click[0]>=250 and click[1]<=250 and click[1]>=100:
                        current_game[0][1] = "X"
                        i += 1
                    elif click[0]<=700 and click[0]>=550 and click[1]<=250 and click[1]>=100:
                        current_game[0][2] = "X"
                        i += 1
                    #2nd row
                    elif click[0]<=250 and click[0]>=100 and click[1]<= 550and click[1]>=250:
                        current_game[1][0] = "X"
                        i += 1
                    elif click[0]<=550 and click[0]>=250 and click[1]<=550 and click[1]>=250:
                        current_game[1][1] = "X"
                        i += 1
                    elif click[0] <= 700 and click[0] >= 550 and click[1] <= 550 and click[1] >= 250:
                        current_game[1][2] = "X"
                        i += 1
                    #3rd row
                    elif click[0]<=250 and click[0]>=100 and click[1]<= 700and click[1]>=550:
                        current_game[2][0] = "X"
                        i += 1
                    elif click[0] <= 550 and click[0] >= 250 and click[1] <= 700 and click[1] >= 550:
                        current_game[2][1] = "X"
                        i += 1
                    elif click[0] <= 700 and click[0] >= 550 and click[1] <= 700 and click[1] >= 550:
                        current_game[2][2] = "X"
                        i += 1
                elif i % 2==0:
                    # 1st row
                    if click[0] <= 250 and click[0] >= 100 and click[1] <= 250 and click[1] >= 100:
                        current_game[0][0] = "o"
                        i += 1
                    elif click[0] <= 550 and click[0] >= 250 and click[1] <= 250 and click[1] >= 100:
                        current_game[0][1] = "o"
                        i += 1
                    elif click[0] <= 700 and click[0] >= 550 and click[1] <= 250 and click[1] >= 100:
                        current_game[0][2] = "o"
                        i += 1
                    # 2nd row
                    elif click[0] <= 250 and click[0] >= 100 and click[1] <= 550 and click[1] >= 250:
                        current_game[1][0] = "o"
                        i += 1
                    elif click[0] <= 550 and click[0] >= 250 and click[1] <= 550 and click[1] >= 250:
                        current_game[1][1] = "o"
                        i += 1
                    elif click[0] <= 700 and click[0] >= 550 and click[1] <= 550 and click[1] >= 250:
                        current_game[1][2] = "o"
                        i += 1
                    # 3rd row
                    elif click[0] <= 250 and click[0] >= 100 and click[1] <= 700 and click[1] >= 550:
                        current_game[2][0] = "o"
                        i += 1
                    elif click[0] <= 550 and click[0] >= 250 and click[1] <= 700 and click[1] >= 550:
                        current_game[2][1] = "o"
                        i += 1
                    elif click[0] <= 700 and click[0] >= 550 and click[1] <= 700 and click[1] >= 550:
                        current_game[2][2] = "o"
                        i += 1

I want to be able to increment the for loop if someone clicks on a certain co-ordinate space.

Body:
The expression range(n) is evaluated just once, not on every iteration. You can't set n and expect the range(n) be changed. It doesn't allow this. Check it here for details

You have to use while loop for that.

i=0
while i<=5:
    #do your tasks
    #do your increment


答:
Try this:

```<code>val dtWindow = Window.partitionBy("dt","A").orderBy("dt")
val aWindow = Window.partitionBy("A").orderBy("dt").rangeBetween(lit(-1),currentRow())
df.withColumn("dt",col("dt").cast("date")).withColumn("sum",sum($"B").over(dtWindow)).withColumn("sum",sum("sum").over(aWindow)).orderBy("dt","A").show

+----------+---+---+---+
|        dt|  A|  B|sum|
+----------+---+---+---+
|2020-05-21|  x|  1|  1|
|2020-05-21|  y|  2|  2|
|2020-05-22|  x|  3|  4|
|2020-05-22|  y|  4|  6|
|2020-05-23|  x|  5|  8|
|2020-05-23|  y|  6| 10|
+----------+---+---+---+
</code>```

Points to note:

Convert 'dt' to Date type for correct type comparison while using
rangeBetween.

Use rangeBetween instead of rowsBetween to get sum of    today and
yesterday. If data for yesterday is not available your sum    will be
only of todays data. If you use rowsBetween then the sum will    be
of today and the day immediate lower than today in the data.

Title: Sliding Window operations across groups in Spark DataFrame with multiple columns

Body:
I have a DataFrame as below:

scala> Seq(("2020-05-21","x",1),("2020-05-21","y",2),("2020-05-22","x",3),("2020-05-22","y",4),("2020-05-23","x",5), ("2020-05-23","y",6)).toDF("dt","A","B")
+----------+---+---+
|        dt|  A|  B|
+----------+---+---+
|2020-05-21|  x|  1|
|2020-05-21|  y|  2|
|2020-05-22|  x|  3|
|2020-05-22|  y|  4|
|2020-05-23|  x|  5|
|2020-05-23|  y|  6|
+----------+---+---+

I am trying to find, for the past 2 days(including current day) the sum of B grouped by A.

In other words: group by A & dt(only current & previous dt) find moving sum of B.

Expected Output:

+----------+---+---+----+
|        dt|  A|  B| sum|
+----------+---+---+----+
|2020-05-21|  x|  1|   1|
|2020-05-21|  y|  2|   2|
|2020-05-22|  x|  3|   4|  // (1 + 3) (i.e: for dt = May 21 & 22, A = x)
|2020-05-22|  y|  4|   6|  // (4 + 2) (i.e: for dt = May 21 & 22, A = y)
|2020-05-23|  x|  5|   8|  // (5 + 3) (i.e: for dt = May 22 & 23, A = x)
|2020-05-23|  y|  6|  10|  // (6 + 4) (i.e: for dt = May 22 & 23, A = y)
+----------+---+---+----+

Tried Window functions with .rowsBetween() like:

res0.withColumn("sum", sum($"B").over(Window.partitionBy($"dt",$"A").rowsBetween(-1,0)))

but this approach will not work as grouping both dt & A will result in only 1 row per group.

Body:
Try this:

val dtWindow = Window.partitionBy("dt","A").orderBy("dt")
val aWindow = Window.partitionBy("A").orderBy("dt").rangeBetween(lit(-1),currentRow())
df.withColumn("dt",col("dt").cast("date")).withColumn("sum",sum($"B").over(dtWindow)).withColumn("sum",sum("sum").over(aWindow)).orderBy("dt","A").show

+----------+---+---+---+
|        dt|  A|  B|sum|
+----------+---+---+---+
|2020-05-21|  x|  1|  1|
|2020-05-21|  y|  2|  2|
|2020-05-22|  x|  3|  4|
|2020-05-22|  y|  4|  6|
|2020-05-23|  x|  5|  8|
|2020-05-23|  y|  6| 10|
+----------+---+---+---+

Points to note:

Convert 'dt' to Date type for correct type comparison while using
rangeBetween.

Use rangeBetween instead of rowsBetween to get sum of    today and
yesterday. If data for yesterday is not available your sum    will be
only of todays data. If you use rowsBetween then the sum will    be
of today and the day immediate lower than today in the data.


问:
Why is the font-weight attribute does not work in the span tag?
I tried using a font-weight attribute in my span tag in a html document, but it seems that it does not have any effect.

But, when I used the font-weight in the CSS document, it works just perfectly.

For example, I have a div where I assigned a class to it, inside a div there is a header that I want to bold a few words in it using the span tag, but it does not work.

But, in the CSS document, I tried to use the font-weight attribute using the class selector, and it works.

I'm out of ideas...

Here is my html and CSS document:

.beamember {
    position: relative;
    font-size: 1em;
    letter-spacing: 1px;
}

.membercontent {
    position: absolute;
    z-index: 2;
    top: 90px;
    left: 100px;
    width: 300px;
    padding: 10px;
    border-radius: 10px;
    color: white;
    background-color: rgba(0, 0, 0, 0.3);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="beamember">
    <div class="membercontent">
        <h5><span style="font-weight:bolder;">Sign up</span>to get more benefits !</h5>
        <p>Lorem ipsum dolor sit amet,
            consectetur adipiscing elit. Praesent elit odio,
            venenatis et nunc at,
            fringilla accumsan felis. Sed vestibulum gravida pulvinar. Nullam posuere et orci sed semper. Phasellus ligula leo,
            dignissim sed leo sit amet,
            convallis pretium urna. Etiam diam turpis,
            maximus nec lobortis nec,
            congue nec sem. Phasellus pellentesque purus eros,
            id imperdiet felis venenatis quis. In sit amet odio dolor.</p>Register Now !
    </div>
</div></code>```

答:
First make sure your font support fontweight of 900.

h5 default font-weight is bold which is equivalent of 700.
If you want to use font-weight:bolder on its nested tag it is going to be 900.
Value bolder is relative unit which means it will set font-weight according to your parent tag. Font weight of bolder for 100, 200, 300 is 400, for 400, 500  is 700, for 600, 700, 800, 900 is 900

Body:
I tried using a font-weight attribute in my span tag in a html document, but it seems that it does not have any effect.

But, when I used the font-weight in the CSS document, it works just perfectly.

For example, I have a div where I assigned a class to it, inside a div there is a header that I want to bold a few words in it using the span tag, but it does not work.

But, in the CSS document, I tried to use the font-weight attribute using the class selector, and it works.

I'm out of ideas...

Here is my html and CSS document:

.beamember {
    position: relative;
    font-size: 1em;
    letter-spacing: 1px;
}

.membercontent {
    position: absolute;
    z-index: 2;
    top: 90px;
    left: 100px;
    width: 300px;
    padding: 10px;
    border-radius: 10px;
    color: white;
    background-color: rgba(0, 0, 0, 0.3);
}

Sign upto get more benefits !

Lorem ipsum dolor sit amet,
            consectetur adipiscing elit. Praesent elit odio,
            venenatis et nunc at,
            fringilla accumsan felis. Sed vestibulum gravida pulvinar. Nullam posuere et orci sed semper. Phasellus ligula leo,
            dignissim sed leo sit amet,
            convallis pretium urna. Etiam diam turpis,
            maximus nec lobortis nec,
            congue nec sem. Phasellus pellentesque purus eros,
            id imperdiet felis venenatis quis. In sit amet odio dolor.
Register Now !


问:
Need to accomodate gridView in my flutter
Im building an app that shows diets and also have a search bar to look for the diets.
I cant manage accomodate the search bar correctly like outside the gridviewer. heres the code of my view and how it actually looks. I dont want to be like another card

```<code>body: Container(
          child: GridView.builder(
              padding: EdgeInsets.all(15),
              gridDelegate:
                  SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
              itemCount: dietsForDisplay.length + 1,
              itemBuilder: (BuildContext context, int index) {
                if (diets.length == 0) {
                  return Container(
                    child: Padding(
                      padding: const EdgeInsets.all(60.0),
                      child: Text(
                        "No existen Dietas registradas por la nutrióloga.",
                        style: TextStyle(
                            color: Color(0xFF002D53),
                            fontFamily: 'Montserrat',
                            fontSize: 25,
                            fontWeight: FontWeight.bold),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  );
                } else {
                  return index == 0
                      ? _searchBar()
                      : _listItem(
                          context,
                          index - 1,
                        );
                }
              }),
        ));
  }

</code>```

and the code for the searchBar and listItem are Cards

答:
Wrap your material app inside a Safe Area Widget

https://api.flutter.dev/flutter/widgets/SafeArea-class.html

Body:
Im building an app that shows diets and also have a search bar to look for the diets.
I cant manage accomodate the search bar correctly like outside the gridviewer. heres the code of my view and how it actually looks. I dont want to be like another card

body: Container(
          child: GridView.builder(
              padding: EdgeInsets.all(15),
              gridDelegate:
                  SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
              itemCount: dietsForDisplay.length + 1,
              itemBuilder: (BuildContext context, int index) {
                if (diets.length == 0) {
                  return Container(
                    child: Padding(
                      padding: const EdgeInsets.all(60.0),
                      child: Text(
                        "No existen Dietas registradas por la nutrióloga.",
                        style: TextStyle(
                            color: Color(0xFF002D53),
                            fontFamily: 'Montserrat',
                            fontSize: 25,
                            fontWeight: FontWeight.bold),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  );
                } else {
                  return index == 0
                      ? _searchBar()
                      : _listItem(
                          context,
                          index - 1,
                        );
                }
              }),
        ));
  }

and the code for the searchBar and listItem are Cards


问:
Type-safe navigationHandler with React-Navigation
I have an issue with Typescript and React Navigation for my React Native app.
I've got the following setup in my project, which gives me awesome help and autocompletion when using e.g. navigation.push().

Types

```<code>import { StackNavigationProp } from '@react-navigation/stack';

export type RootStackParamList = {
    Home: undefined;
    Content: undefined;
    List: undefined;
};

export type StackNavigationProps = StackNavigationProp<RootStackParamList>;
</code>```

Usage

```<code>const navigation = useNavigation<StackNavigationProps>();
</code>```

However, I've created a navigation handler function that takes a parameter that gets fed to navigation.push. It works fine as long as the type of the parameter is of type any.

```<code>const navigationHandler = useCallback((targetScreen) => {
    navigation.push(targetScreen);
}, [navigation]);
</code>```

But I am not satisfied with the any type and would prefer that targetScreen could in fact just be one of the screens that were declared in my RootStackParamList type. I have tried in countless ways to satisfy the push method of the navigation object but I'm stuck.

The following attempt has been the most successful but is yet not working exactly as it should. It does give me autocompletion on available screens, but the push is still unhappy.

Type:

```<code>export type NavigationScreen<T extends RootStackParamList> = {
    [K in keyof T]: K;
}[keyof T];
</code>```

Usage:

```<code>const navigationHandler = useCallback(
    <T extends RootStackParamList>(targetScreen: NavigationScreen<T>) => {
        navigation.push(targetScreen);
},[navigation]);
</code>```

Hovering the error I get prompted with the following:

(parameter) targetScreen: { [K in keyof T]: K; }[keyof T] Argument of
  type '[{ [K in keyof T]: K; }[keyof T]]' is not assignable to
  parameter of type '["Home" | "Content" | "List"] | ["Home" | "Content"
  | "List", undefined]'.   Type '[{ [K in keyof T]: K; }[keyof T]]' is
  not assignable to type '["Home" | "Content" | "List"]'.

      Type 'keyof T' is not assignable to type '"Home" | "Content" | "List"'.

        Type 'string | number | symbol' is not assignable to type '"Home" | "Content" | "List"'.

          Type 'string' is not assignable to type '"Home" | "Content" | "List"'.

            Type 'keyof T' is not assignable to type '"List"'.

              Type 'string | number | symbol' is not assignable to type '"List"'.

                Type 'string' is not assignable to type '"List"'.

How to get this working?

答:
If you're just interested in using the name of the screen for your navigationHandler function but not the params, you can do as @artcorpse suggested in his comment to your question and use keyof RootStackParamList:

const navigationHandler = useCallback(
    (targetScreen: keyof RootStackParamList) => {
        navigation.push(targetScreen);
    },
    [navigation]
);
```

<p>If, on the other hand, you want to allow for params, you've got two options:</p>

<h3>Option A: Generic function</h3>

<pre class="lang-js prettyprint-override"><code>const navigationHandler = useCallback(
    <T extends keyof RootStackParamList>(
        targetScreen: T,
        targetScreenParams?: RootStackParamList[T]
    ) => {
        navigation.push(
            targetScreen as keyof RootStackParamList,
            targetScreenParams
        );
    },
    [navigation]
);
</code>```

The upside of this option is that route parameter object shapes are checked against the corresponding routes as defined in the RootStackParamList type. For example,

type RootStackParamList = {
    Default: undefined,
    Home: {a: 'a'};
    Profile: { userId: string };
};

navigationHandler('Home', {a: 'a'}); //OK
navigationHandler('Home', {userId: 'a'}); //ERROR
```

<h3>Option B: Reversing already existing types</h3>

<pre class="lang-js prettyprint-override"><code>const navigationHandler2 = useCallback(
    (
        targetScreen: Parameters<typeof navigation.push>[0],
        targetScreenParams?: Parameters<typeof navigation.push>[1]
    ) => {
        navigation.push(targetScreen, targetScreenParams);
    },
    [navigation]
);
</code>```

This option takes the existing types you've defined and attempts to extract them from the navigation.push method. The downside here is that you won't get the above mentioned check regarding routes and their corresponding parameter object shapes.

Sources:

API documentation for navigation.push

Typescript recommendations for react-navigation

Body:
I have an issue with Typescript and React Navigation for my React Native app.
I've got the following setup in my project, which gives me awesome help and autocompletion when using e.g. navigation.push().

Types

import { StackNavigationProp } from '@react-navigation/stack';

export type RootStackParamList = {
    Home: undefined;
    Content: undefined;
    List: undefined;
};

export type StackNavigationProps = StackNavigationProp<RootStackParamList>;

Usage

const navigation = useNavigation<StackNavigationProps>();

However, I've created a navigation handler function that takes a parameter that gets fed to navigation.push. It works fine as long as the type of the parameter is of type any.

const navigationHandler = useCallback((targetScreen) => {
    navigation.push(targetScreen);
}, [navigation]);

But I am not satisfied with the any type and would prefer that targetScreen could in fact just be one of the screens that were declared in my RootStackParamList type. I have tried in countless ways to satisfy the push method of the navigation object but I'm stuck.

The following attempt has been the most successful but is yet not working exactly as it should. It does give me autocompletion on available screens, but the push is still unhappy.

Type:

export type NavigationScreen<T extends RootStackParamList> = {
    [K in keyof T]: K;
}[keyof T];

Usage:

const navigationHandler = useCallback(
    <T extends RootStackParamList>(targetScreen: NavigationScreen<T>) => {
        navigation.push(targetScreen);
},[navigation]);

Hovering the error I get prompted with the following:

(parameter) targetScreen: { [K in keyof T]: K; }[keyof T] Argument of
  type '[{ [K in keyof T]: K; }[keyof T]]' is not assignable to
  parameter of type '["Home" | "Content" | "List"] | ["Home" | "Content"
  | "List", undefined]'.   Type '[{ [K in keyof T]: K; }[keyof T]]' is
  not assignable to type '["Home" | "Content" | "List"]'.

      Type 'keyof T' is not assignable to type '"Home" | "Content" | "List"'.

        Type 'string | number | symbol' is not assignable to type '"Home" | "Content" | "List"'.

          Type 'string' is not assignable to type '"Home" | "Content" | "List"'.

            Type 'keyof T' is not assignable to type '"List"'.

              Type 'string | number | symbol' is not assignable to type '"List"'.

                Type 'string' is not assignable to type '"List"'.

How to get this working?

Body:
If you're just interested in using the name of the screen for your navigationHandler function but not the params, you can do as @artcorpse suggested in his comment to your question and use keyof RootStackParamList:

const navigationHandler = useCallback(
    (targetScreen: keyof RootStackParamList) => {
        navigation.push(targetScreen);
    },
    [navigation]
);

If, on the other hand, you want to allow for params, you've got two options:

Option A: Generic function

const navigationHandler = useCallback(
    <T extends keyof RootStackParamList>(
        targetScreen: T,
        targetScreenParams?: RootStackParamList[T]
    ) => {
        navigation.push(
            targetScreen as keyof RootStackParamList,
            targetScreenParams
        );
    },
    [navigation]
);

The upside of this option is that route parameter object shapes are checked against the corresponding routes as defined in the RootStackParamList type. For example,

type RootStackParamList = {
    Default: undefined,
    Home: {a: 'a'};
    Profile: { userId: string };
};

navigationHandler('Home', {a: 'a'}); //OK
navigationHandler('Home', {userId: 'a'}); //ERROR

Option B: Reversing already existing types

const navigationHandler2 = useCallback(
    (
        targetScreen: Parameters<typeof navigation.push>[0],
        targetScreenParams?: Parameters<typeof navigation.push>[1]
    ) => {
        navigation.push(targetScreen, targetScreenParams);
    },
    [navigation]
);

This option takes the existing types you've defined and attempts to extract them from the navigation.push method. The downside here is that you won't get the above mentioned check regarding routes and their corresponding parameter object shapes.

Sources:

API documentation for navigation.push

Typescript recommendations for react-navigation


问:
Get back to a fragment from an Activity
I have three fragment in an Activity C. they are behaving as tabs. I have to go from a fragment to a new Activity X. Now i want to come back to fragment from Activity X.

I have override onBackPressed but don't know how to go back to fragment/not fragmentActivity from an Activity.

if i want to go back to an Activity to another activity i override on back pressed and using intent call that actvity..

i want to do some thing like this .. this code is for coming back to previous activity

```<code>@Override
public void onBackPressed()
{

    Intent intent = new Intent(CurrentActivity.this,ActivityYouLikeToGo.class);

    intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

    startActivity(intent);
}
</code>```

thanks in Advance..

答:
enter image description here

```<code>@Override
public void onBackPressed() {
  //Here "digiM" is an Actionbar Title
    if(getTitle().equals("digiM") || getSupportActionBar().getTitle().equals("digiM"))
    {
        //reload the activity if you want to open it again as your need
        Intent intent = new Intent(Your_Current_Activity.this,Your_Current_Activity.class);
        startActivity(intent);
    }
}
</code>```

If you have action bar in that fragment, then you can check action bar title on onBackPressed() in Activity which contains method like.

Title: Get back to a fragment from an Activity

Body:
I have three fragment in an Activity C. they are behaving as tabs. I have to go from a fragment to a new Activity X. Now i want to come back to fragment from Activity X.

I have override onBackPressed but don't know how to go back to fragment/not fragmentActivity from an Activity.

if i want to go back to an Activity to another activity i override on back pressed and using intent call that actvity..

i want to do some thing like this .. this code is for coming back to previous activity

@Override
public void onBackPressed()
{

    Intent intent = new Intent(CurrentActivity.this,ActivityYouLikeToGo.class);

    intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

    startActivity(intent);
}

thanks in Advance..

Body:
enter image description here

@Override
public void onBackPressed() {
  //Here "digiM" is an Actionbar Title
    if(getTitle().equals("digiM") || getSupportActionBar().getTitle().equals("digiM"))
    {
        //reload the activity if you want to open it again as your need
        Intent intent = new Intent(Your_Current_Activity.this,Your_Current_Activity.class);
        startActivity(intent);
    }
}

If you have action bar in that fragment, then you can check action bar title on onBackPressed() in Activity which contains method like.


问:
Can I get CherryPy to find its own available port?
I'm running many web servers on the same machine for test purposes. Instead of dealing with server port conflicts, I'd like to have the servers simply ask the OS for an available port, and then tell me what they got.

I may communicate the port back to the invoker by logging to console, or writing to a specified temp file (not sure yet), but knowing the port number is the tricky part.

Currently, the WSGI based server is being launched with:

```<code>  cherrypy.quickstart(dev_server, config=_GetConfig(options))
</code>```

The config will contain the following:

```<code>{ 'global':
                  { <snip>
                    'server.socket_host': '0.0.0.0',
                    'server.socket_port': int(options.port)
                  },
   <snip>
}
</code>```

Is there any way to do this with CherryPy?

I assume I can set the port to '0' to have it auto-selected, but that doesn't give me a way to report it.

答:
If you're using CherryPy's built-in server, you can check what port it's actually listening on using cherrypy.server.bound_addr.

The docs say:

property bound_addr

The bind address, or if it’s an ephemeral port and the socket has been
      bound, return the actual port bound.

An example of using this:

def start():
    cherrypy.config.update({
        'server.socket_port': 0,
    })
    cherrypy.tree.mount(MyApp(), '', {})

    cherrypy.engine.signals.subscribe()
    cherrypy.engine.start()
    _host, port = cherrypy.server.bound_addr

    # Do something with the port here
    ...

    cherrypy.engine.block()

```

Body:
I'm running many web servers on the same machine for test purposes. Instead of dealing with server port conflicts, I'd like to have the servers simply ask the OS for an available port, and then tell me what they got.

I may communicate the port back to the invoker by logging to console, or writing to a specified temp file (not sure yet), but knowing the port number is the tricky part.

Currently, the WSGI based server is being launched with:

  cherrypy.quickstart(dev_server, config=_GetConfig(options))

The config will contain the following:

{ 'global':
                  { <snip>
                    'server.socket_host': '0.0.0.0',
                    'server.socket_port': int(options.port)
                  },
   <snip>
}

Is there any way to do this with CherryPy?

I assume I can set the port to '0' to have it auto-selected, but that doesn't give me a way to report it.


问:
Child component doesn't update correctly with state update in parent component
Simply i have a list item, that contain a list of names, clicking any list item change the color of that item, this is my logic:

```<code>const App = () => {

    const items = [
        {
            name: 'peter',
            id: 1
        },
        {
            name: 'Mark',
            id: 2
        },
        {
            name: 'john',
            id: 3
        }
    ]

    const [id, setId] = useState(null);
    const [names, setNames] = useState(items)

    const setClickedItemId = (id) => {
        setId(id)
    }

    const turnItemRed = () => {
        setNames(prev =>  prev.map(i => i.id === id ? {...i, color: 'red' } : i))

    }

    return (
        <div className="app">
            <ul className="items">
                {
                    names.map(i => {
                        return (
                            <Item
                               item={i}
                                setClickedItemId={setClickedItemId}
                                turnItemRed={turnItemRed}
                            />
                        )
                    })
                }
            </ul>
        </div>
    )
}

function Item({item, ...props}) {
    const { name, id} = item;
    const { setClickedItemId, turnItemRed } = props;
    return (
        <li
            className={`${item.color === 'red' ? 'red' : ''}`}
            onClick={() => {
                setClickedItemId(id);
                turnItemRed()

            }}
        >{name}</li>
    )
}

ReactDOM.render(<App />, document.getElementById('root'))

</code>```

This renders a list of items, i need two clicks to have an item turning into red, which means the child component doesn't catch the most recent version of state, but:

Just adding that line of code before the return statement in parent components,

```<code>const showingItems = names.map(i => i.id === id ? {...i, color: 'red'} : i)
</code>```

and then using that variable showingItems to render the list instead of state variable names make it right and don't know why

So, why the child components Items doesn't get the most recent version of the state while storing the state in a variable makes it work??

答:
State updates are batched and your onClick triggers 2 functions which does state updates. The second function doesn't receive updated value due to the async behaviour.

Just pass the id to turnItemRed function instead of grabbing it from state.

App

    const turnItemRed = (id) => { //<----take the id
        setNames(prev =>  prev.map(i => i.id === id ? {...i, color: 'red' } : i))

    }

```

<p><strong>Item</strong></p>

<pre class="lang-js prettyprint-override"><code>function Item({item, ...props}) {
    const { name, id} = item;
    const { setClickedItemId, turnItemRed } = props;
    return (
        <li
            className={`${item.color === 'red' ? 'red' : ''}`}
            onClick={() => {
                setClickedItemId(id);
                turnItemRed(id) //<---- pass the id

            }}
        >{name}</li>
    )
}
</code>```

Edit
A quick demo of the above issue and the fix is here in the demo. . Just adding this so it might help other readers in future.

Body:
Simply i have a list item, that contain a list of names, clicking any list item change the color of that item, this is my logic:

const App = () => {

    const items = [
        {
            name: 'peter',
            id: 1
        },
        {
            name: 'Mark',
            id: 2
        },
        {
            name: 'john',
            id: 3
        }
    ]

    const [id, setId] = useState(null);
    const [names, setNames] = useState(items)

    const setClickedItemId = (id) => {
        setId(id)
    }

    const turnItemRed = () => {
        setNames(prev =>  prev.map(i => i.id === id ? {...i, color: 'red' } : i))

    }

    return (

                {
                    names.map(i => {
                        return (
                            <Item
                               item={i}
                                setClickedItemId={setClickedItemId}
                                turnItemRed={turnItemRed}
                            />
                        )
                    })
                }

    )
}

function Item({item, ...props}) {
    const { name, id} = item;
    const { setClickedItemId, turnItemRed } = props;
    return (
        <li
            className={`${item.color === 'red' ? 'red' : ''}`}
            onClick={() => {
                setClickedItemId(id);
                turnItemRed()

            }}
        >{name}

    )
}

ReactDOM.render(<App />, document.getElementById('root'))

This renders a list of items, i need two clicks to have an item turning into red, which means the child component doesn't catch the most recent version of state, but:

Just adding that line of code before the return statement in parent components,

const showingItems = names.map(i => i.id === id ? {...i, color: 'red'} : i)

and then using that variable showingItems to render the list instead of state variable names make it right and don't know why

So, why the child components Items doesn't get the most recent version of the state while storing the state in a variable makes it work??

Body:
State updates are batched and your onClick triggers 2 functions which does state updates. The second function doesn't receive updated value due to the async behaviour.

Just pass the id to turnItemRed function instead of grabbing it from state.

App

    const turnItemRed = (id) => { //<----take the id
        setNames(prev =>  prev.map(i => i.id === id ? {...i, color: 'red' } : i))

    }

Item

function Item({item, ...props}) {
    const { name, id} = item;
    const { setClickedItemId, turnItemRed } = props;
    return (
        <li
            className={`${item.color === 'red' ? 'red' : ''}`}
            onClick={() => {
                setClickedItemId(id);
                turnItemRed(id) //<---- pass the id

            }}
        >{name}</li>
    )
}

Edit
A quick demo of the above issue and the fix is here in the demo. . Just adding this so it might help other readers in future.


问:
Mediapipe: How to implement real time gesture recognition in multi hand tracking module
How can we modify mediapipe code to get real time gesture recognition of a basic set of gestures. I ran multi hand tracking apk but it could not recognise basic gestures as promised in https://ai.googleblog.com/2019/08/on-device-real-time-hand-tracking-with.html . </p>

答:
So far, I see two ways:

Use a pre-trained model wrapped within a calculator.

Train a model using the 21 landmarks by collecting points for each gesture and normalizing the landmarks' x, y, z values.


问:
<f:ajax> multiple call of Java method - how to do it only once?
I'm using ajax to call java method bean.findDetail(). If the method finds detailItem object in database, the rest of inputTexts is rendered.

```<code><h:inputText id="worker" value="#{bean.item.id}">
 <f:ajax event="change" render="name" listener="#{bean.findDetail}"/>
 <f:ajax event="change" render="surname"/>
 <f:ajax event="change" render="age"/>
</h:inputText>

<h:panelGroup>
 <h:inputText id="name" value="#{bean.detailItem.name}" disabled="true"/>
 <h:inputText id="surname" value="#{bean.detailItem.surname}" disabled="true"/>
 <h:inputText id="age" value="#{bean.detailItem.age}" disabled="true"/>
</h:panelGroup>
</code>```

Everything is working fine, but method is called three times!

Is there some way to render all three inputText at once?

答:
Yes, just place space seperated values in render element</p>

```<code><h:inputText id="worker" value="#{bean.item.id}">
 <f:ajax event="change" render="name surname age" listener="#{bean.findDetail}"/>
</h:inputText>
</code>```

Body:
I'm using ajax to call java method bean.findDetail(). If the method finds detailItem object in database, the rest of inputTexts is rendered.

<h:inputText id="worker" value="#{bean.item.id}">
 <f:ajax event="change" render="name" listener="#{bean.findDetail}"/>
 <f:ajax event="change" render="surname"/>
 <f:ajax event="change" render="age"/>
</h:inputText>

<h:panelGroup>
 <h:inputText id="name" value="#{bean.detailItem.name}" disabled="true"/>
 <h:inputText id="surname" value="#{bean.detailItem.surname}" disabled="true"/>
 <h:inputText id="age" value="#{bean.detailItem.age}" disabled="true"/>
</h:panelGroup>

Everything is working fine, but method is called three times!

Is there some way to render all three inputText at once?

Body:
Yes, just place space seperated values in render element

<h:inputText id="worker" value="#{bean.item.id}">
 <f:ajax event="change" render="name surname age" listener="#{bean.findDetail}"/>
</h:inputText>


问:
Can't able to perform $lookup in mongodb replica set
I want the fetch post from the collection 'posts' with the details of the users stored in the collection 'users'.The posts collection have ID as the (_id)userId of the users collection. I was using $lookup to retrieve the data from two collections.

```<code>const data = await db.collection('posts').aggregate([ { $lookup: { from: "users", localField: "ID", foreignField: "_id", as: "det"}}]);
</code>```

On consoling the data, it returns an AggregationCursor object as below

```<code>AggregationCursor {

 _readableState: ReadableState {
    objectMode: true,
    highWaterMark: 16,
    buffer: BufferList { head: null, tail: null, length: 0 },
    length: 0,
    pipes: null,
    pipesCount: 0,
    flowing: null,
    ended: false,
    endEmitted: false,
    reading: false,
    sync: true,
    needReadable: false,
    emittedReadable: false,
    readableListening: false,
    resumeScheduled: false,
    emitClose: true,
    autoDestroy: false,
    destroyed: false,
    defaultEncoding: 'utf8',
    awaitDrain: 0,
    readingMore: false,
    decoder: null,
    encoding: null,
    [Symbol(kPaused)]: null
  },
  readable: true,
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  operation: AggregateOperation {
    options: { readPreference: [ReadPreference] },
    ns: MongoDBNamespace { db: 'alumni-portal', collection: '$cmd' },
    readPreference: ReadPreference { mode: 'primary', tags: undefined },
    readConcern: undefined,
    writeConcern: undefined,
    explain: false,
    fullResponse: true,
    target: 'posts',
    pipeline: [ [Object] ],
    hasWriteStage: false,
    cursorState: {
      cursorId: null,
      cmd: {},
      documents: [],
      cursorIndex: 0,
      dead: false,
      killed: false,
      init: false,
      notified: false,
      limit: 0,
      skip: 0,
      batchSize: 1000,
      currentLimit: 0,
      transforms: undefined,
      raw: undefined
    }
  },
  pool: null,
  server: null,
  disconnectHandler: undefined,
  bson: BSON {},
  ns: 'alumni-portal.$cmd',
  namespace: MongoDBNamespace { db: 'alumni-portal', collection: '$cmd' },
  cmd: {},
  options: {
    readPreference: ReadPreference { mode: 'primary', tags: undefined }
  },
  topology: NativeTopology {
    _events: [Object: null prototype] {
      authenticated: [Function],
      error: [Array],
      timeout: [Array],
      close: [Array],
      parseError: [Array],
      fullsetup: [Array],
      all: [Array],
      reconnect: [Array],
      commandStarted: [Function],
      commandSucceeded: [Function],
      commandFailed: [Function],
      serverOpening: [Function],
      serverClosed: [Function],
      serverDescriptionChanged: [Function],
      serverHeartbeatStarted: [Function],
      serverHeartbeatSucceeded: [Function],
      serverHeartbeatFailed: [Function],
      topologyOpening: [Function],
      topologyClosed: [Function],
      topologyDescriptionChanged: [Function],
      joined: [Function],
      left: [Function],
      ping: [Function],
      ha: [Function],
      connectionPoolCreated: [Function],
      connectionPoolClosed: [Function],
      connectionCreated: [Function],
      connectionReady: [Function],
      connectionClosed: [Function],
      connectionCheckOutStarted: [Function],
      connectionCheckOutFailed: [Function],
      connectionCheckedOut: [Function],
      connectionCheckedIn: [Function],
      connectionPoolCleared: [Function],
      open: [Function]
    },
    _eventsCount: 35,
    _maxListeners: Infinity,
    s: {
      id: 0,
      options: [Object],
      seedlist: [Array],
      state: 'connected',
      description: [TopologyDescription],
      serverSelectionTimeoutMS: 30000,
      heartbeatFrequencyMS: 10000,
      minHeartbeatFrequencyMS: 500,
      Cursor: [Function: Cursor],
      bson: BSON {},
      servers: [Map],
      sessionPool: [ServerSessionPool],
      sessions: Set {},
      promiseLibrary: [Function: Promise],
      credentials: [MongoCredentials],
      clusterTime: [Object],
      connectionTimers: Set {},
      sCapabilities: [ServerCapabilities]
    },
    [Symbol(kCapture)]: false,
    [Symbol(waitQueue)]: Denque { _head: 3, _tail: 3, _capacityMask: 3, _list: [Array] }
  },
  cursorState: {
    cursorId: null,
    cmd: {},
    documents: [],
    cursorIndex: 0,
    dead: false,
    killed: false,
    init: false,
    notified: false,
    limit: 0,
    skip: 0,
    batchSize: 1000,
    currentLimit: 0,
    transforms: undefined,
    raw: undefined
  },
  logger: Logger { className: 'Cursor' },
  s: {
    numberOfRetries: 5,
    tailableRetryInterval: 500,
    currentNumberOfRetries: 5,
    state: 0,
    promiseLibrary: [Function: Promise],
    explicitlyIgnoreSession: false
  },
  [Symbol(kCapture)]: false
}
</code>```

But the same code returns desired output in mongoshell. I am not getting why data is returning an AggregationCursor Object.
 Thank You in advance.

PS- I am using replica set of 3 nodes.

答:
I only need to add .toArray() at the end of the code statement. So, The answer above code statement should be as below.

```<code>const data = await db.collection('posts').aggregate([ { $lookup: { from: "users", localField: "ID", foreignField: "_id", as: "det"}}]).toArray();
</code>```

Body:
I want the fetch post from the collection 'posts' with the details of the users stored in the collection 'users'.The posts collection have ID as the (_id)userId of the users collection. I was using $lookup to retrieve the data from two collections.

const data = await db.collection('posts').aggregate([ { $lookup: { from: "users", localField: "ID", foreignField: "_id", as: "det"}}]);

On consoling the data, it returns an AggregationCursor object as below

AggregationCursor {

 _readableState: ReadableState {
    objectMode: true,
    highWaterMark: 16,
    buffer: BufferList { head: null, tail: null, length: 0 },
    length: 0,
    pipes: null,
    pipesCount: 0,
    flowing: null,
    ended: false,
    endEmitted: false,
    reading: false,
    sync: true,
    needReadable: false,
    emittedReadable: false,
    readableListening: false,
    resumeScheduled: false,
    emitClose: true,
    autoDestroy: false,
    destroyed: false,
    defaultEncoding: 'utf8',
    awaitDrain: 0,
    readingMore: false,
    decoder: null,
    encoding: null,
    [Symbol(kPaused)]: null
  },
  readable: true,
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  operation: AggregateOperation {
    options: { readPreference: [ReadPreference] },
    ns: MongoDBNamespace { db: 'alumni-portal', collection: '$cmd' },
    readPreference: ReadPreference { mode: 'primary', tags: undefined },
    readConcern: undefined,
    writeConcern: undefined,
    explain: false,
    fullResponse: true,
    target: 'posts',
    pipeline: [ [Object] ],
    hasWriteStage: false,
    cursorState: {
      cursorId: null,
      cmd: {},
      documents: [],
      cursorIndex: 0,
      dead: false,
      killed: false,
      init: false,
      notified: false,
      limit: 0,
      skip: 0,
      batchSize: 1000,
      currentLimit: 0,
      transforms: undefined,
      raw: undefined
    }
  },
  pool: null,
  server: null,
  disconnectHandler: undefined,
  bson: BSON {},
  ns: 'alumni-portal.$cmd',
  namespace: MongoDBNamespace { db: 'alumni-portal', collection: '$cmd' },
  cmd: {},
  options: {
    readPreference: ReadPreference { mode: 'primary', tags: undefined }
  },
  topology: NativeTopology {
    _events: [Object: null prototype] {
      authenticated: [Function],
      error: [Array],
      timeout: [Array],
      close: [Array],
      parseError: [Array],
      fullsetup: [Array],
      all: [Array],
      reconnect: [Array],
      commandStarted: [Function],
      commandSucceeded: [Function],
      commandFailed: [Function],
      serverOpening: [Function],
      serverClosed: [Function],
      serverDescriptionChanged: [Function],
      serverHeartbeatStarted: [Function],
      serverHeartbeatSucceeded: [Function],
      serverHeartbeatFailed: [Function],
      topologyOpening: [Function],
      topologyClosed: [Function],
      topologyDescriptionChanged: [Function],
      joined: [Function],
      left: [Function],
      ping: [Function],
      ha: [Function],
      connectionPoolCreated: [Function],
      connectionPoolClosed: [Function],
      connectionCreated: [Function],
      connectionReady: [Function],
      connectionClosed: [Function],
      connectionCheckOutStarted: [Function],
      connectionCheckOutFailed: [Function],
      connectionCheckedOut: [Function],
      connectionCheckedIn: [Function],
      connectionPoolCleared: [Function],
      open: [Function]
    },
    _eventsCount: 35,
    _maxListeners: Infinity,
    s: {
      id: 0,
      options: [Object],
      seedlist: [Array],
      state: 'connected',
      description: [TopologyDescription],
      serverSelectionTimeoutMS: 30000,
      heartbeatFrequencyMS: 10000,
      minHeartbeatFrequencyMS: 500,
      Cursor: [Function: Cursor],
      bson: BSON {},
      servers: [Map],
      sessionPool: [ServerSessionPool],
      sessions: Set {},
      promiseLibrary: [Function: Promise],
      credentials: [MongoCredentials],
      clusterTime: [Object],
      connectionTimers: Set {},
      sCapabilities: [ServerCapabilities]
    },
    [Symbol(kCapture)]: false,
    [Symbol(waitQueue)]: Denque { _head: 3, _tail: 3, _capacityMask: 3, _list: [Array] }
  },
  cursorState: {
    cursorId: null,
    cmd: {},
    documents: [],
    cursorIndex: 0,
    dead: false,
    killed: false,
    init: false,
    notified: false,
    limit: 0,
    skip: 0,
    batchSize: 1000,
    currentLimit: 0,
    transforms: undefined,
    raw: undefined
  },
  logger: Logger { className: 'Cursor' },
  s: {
    numberOfRetries: 5,
    tailableRetryInterval: 500,
    currentNumberOfRetries: 5,
    state: 0,
    promiseLibrary: [Function: Promise],
    explicitlyIgnoreSession: false
  },
  [Symbol(kCapture)]: false
}

But the same code returns desired output in mongoshell. I am not getting why data is returning an AggregationCursor Object.
 Thank You in advance.

PS- I am using replica set of 3 nodes.

Body:
I only need to add .toArray() at the end of the code statement. So, The answer above code statement should be as below.

const data = await db.collection('posts').aggregate([ { $lookup: { from: "users", localField: "ID", foreignField: "_id", as: "det"}}]).toArray();


问:
Connecting laravel to postgres db
I am working on a project where I need to connect Laravel to a postgres db.  First time doing this, in the past just used mysql. I am getting this error  PDOException::("SQLSTATE[08006] [7] FATAL:  no pg_hba.conf entry for host when I try to run php artisan migrate.  I am on a mac so I used brew install postgresql.  This is a db that already has tables in it.

In my .env file I changed my db to

```<code>DB_CONNECTION=pgsql
DB_HOST=<host name>
DB_PORT=5432
DB_DATABASE=<db name>
DB_USERNAME=<user name>
DB_PASSWORD=<password>
</code>```

What else am I missing?

答:
It seems like your config is missing in pg_hba.conf file.

Suppose you are on localhost, have you tried adding host  all  all 0.0.0.0/0 md5 entry in your pg_hba.conf? Remember to restart your postgresql services after that.

Title: Connecting laravel to postgres db

Body:
I am working on a project where I need to connect Laravel to a postgres db.  First time doing this, in the past just used mysql. I am getting this error  PDOException::("SQLSTATE[08006] [7] FATAL:  no pg_hba.conf entry for host when I try to run php artisan migrate.  I am on a mac so I used brew install postgresql.  This is a db that already has tables in it.

In my .env file I changed my db to

DB_CONNECTION=pgsql
DB_HOST=<host name>
DB_PORT=5432
DB_DATABASE=<db name>
DB_USERNAME=<user name>
DB_PASSWORD=<password>

What else am I missing?


问:
I have a problem with uploading my images with ckeditor
I have tried to upload images with ckeditor but  my problem is that the images upload to the server folders but ddoesnt show in my ckeditor text area , it show server response error , any help please ?
This is my code :

```<code> router.post('/upload&responseType=json', function(req, res) {
        var fs = require('fs');

        var tmpPath = req.files.upload.name;
        l = tmpPath.split('/').length;`enter code here`
        var fileName = tmpPath.split('/')[l - 1] + "_" + "s";
            var buf = new Buffer.from(req.files["upload"].data);
            var newPath ='public/uploads/'+tmpPath;
            console.log(newPath);
            console.log(tmpPath);
            console.log(fileName);
                fs.writeFile(newPath,buf, function (err) {
                if (err) console.log({err: err});
                else {

             html = "uploaded";
             html += "<script type='text/javascript'>";
             html += "    var funcNum = " + req.query.CKEditorFuncNum + ";";
             html += "    var url     = \"/uploads/" + fileName;
             html += "    var message = \"Uploaded file successfully\";";
             html += "";
             html += "    window.parent.CKEDITOR.tools.callFunction(funcNum, url, message);";
             html += "</script>";

            res.send(html);
                }

        });
             });
</code>```

This is my ckeditor

```<code>CKEDITOR.config.customConfig = '/js/ckeditor_config.js';
CKEDITOR.replace(editor2,{ filebrowserUploadUrl: '/upload', });
</code>```

And this my ckeditor config file :

```<code>CKEDITOR.editorConfig = function( config )
{

config.filebrowserUploadMethod = 'form';
    config.toolbar = 'MyToolbar';

    config.toolbar_MyToolbar =
    [
        ['Source','Templates'],
        ['Cut','Copy','Paste','SpellChecker','-','Scayt'],
        ['Undo','Redo','-','Find','Replace'],
        ['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],
      ['Maximize','-','About'],
        '/',
       ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
        ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote','SelectAll','RemoveFormat'],
        ['Link','Unlink','Anchor'],
      ['Styles','Format','Font','FontSize'],
       ['TextColor','BGColor']

    ];
};
</code>```

答:
You do not have to send the whole HTML in the newer versions of ckeditor..
You are just supposed to send the URL as shown below:

```<code>res.send({
    url: "<SERVER_URL>/public/uploads/" + fileName,
})
</code>```

If you are working on localhost
replace SERVER_URL with something like http://localhost:3000

Another thing, you have to set

```<code>app.use(express.static('public/uploads'));
</code>```

If you want to access the image using the URL mentioned above.

Body:
I have tried to upload images with ckeditor but  my problem is that the images upload to the server folders but ddoesnt show in my ckeditor text area , it show server response error , any help please ?
This is my code :

 router.post('/upload&responseType=json', function(req, res) {
        var fs = require('fs');

        var tmpPath = req.files.upload.name;
        l = tmpPath.split('/').length;`enter code here`
        var fileName = tmpPath.split('/')[l - 1] + "_" + "s";
            var buf = new Buffer.from(req.files["upload"].data);
            var newPath ='public/uploads/'+tmpPath;
            console.log(newPath);
            console.log(tmpPath);
            console.log(fileName);
                fs.writeFile(newPath,buf, function (err) {
                if (err) console.log({err: err});
                else {

             html = "uploaded";
             html += "";

            res.send(html);
                }

        });
             });

This is my ckeditor

CKEDITOR.config.customConfig = '/js/ckeditor_config.js';
CKEDITOR.replace(editor2,{ filebrowserUploadUrl: '/upload', });

And this my ckeditor config file :

CKEDITOR.editorConfig = function( config )
{

config.filebrowserUploadMethod = 'form';
    config.toolbar = 'MyToolbar';

    config.toolbar_MyToolbar =
    [
        ['Source','Templates'],
        ['Cut','Copy','Paste','SpellChecker','-','Scayt'],
        ['Undo','Redo','-','Find','Replace'],
        ['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],
      ['Maximize','-','About'],
        '/',
       ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
        ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote','SelectAll','RemoveFormat'],
        ['Link','Unlink','Anchor'],
      ['Styles','Format','Font','FontSize'],
       ['TextColor','BGColor']

    ];
};

Body:
You do not have to send the whole HTML in the newer versions of ckeditor..
You are just supposed to send the URL as shown below:

res.send({
    url: "<SERVER_URL>/public/uploads/" + fileName,
})

If you are working on localhost
replace SERVER_URL with something like http://localhost:3000

Another thing, you have to set

app.use(express.static('public/uploads'));

If you want to access the image using the URL mentioned above.


问:
GitHub pages returning error 304 for react app
I have a very simple app where I am React Router in React, which is then getting deployed on GitHub Pages but I am noticing the following error: You need to enable JavaScript to run this app (Error: 304). I noticed that if I take out the Router component and just display <HomePage/> then everything works fine.

What could be the reason behind this happening?

Thanks in advance.!

```<code>import React, { useState } from "react";
import "./App.css";
import Homepage from "./components/Homepage";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";

function App() {
  const [userData, setUserData] = useState(null);

  return (
    <div className="App">
      <Router>
        <Switch>
          <Route exact path="/">
            <Homepage setUserData={setUserData} />
          </Route>
        </Switch>
      </Router>

    </div>
  );
}

export default App;
</code>```

答:
GitHub Pages don't work with <BrowserRouter>. I think if you replace it with <HashRouter>,  the component will be rendered without an error.

import { HashRouter as Router, Switch, Route } from "react-router-dom";
```

Body:
I have a very simple app where I am React Router in React, which is then getting deployed on GitHub Pages but I am noticing the following error: You need to enable JavaScript to run this app (Error: 304). I noticed that if I take out the Router component and just display <HomePage/> then everything works fine.

What could be the reason behind this happening?

Thanks in advance.!

import React, { useState } from "react";
import "./App.css";
import Homepage from "./components/Homepage";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";

function App() {
  const [userData, setUserData] = useState(null);

  return (

      <Router>
        <Switch>
          <Route exact path="/">
            <Homepage setUserData={setUserData} />
          </Route>
        </Switch>
      </Router>

  );
}

export default App;


问:
_rails_command:10: command not found: rails after installing through gem
I installed rails using gem install rails and it showed installed successfully. But on doing rails --version I get _rails_command:10: command not found.

Here is what I get on doing gem env

```<code>    RubyGems Environment:
  - RUBYGEMS VERSION: 3.1.2
  - RUBY VERSION: 2.7.1 (2020-03-31 patchlevel 83) [x86_64-linux]
  - INSTALLATION DIRECTORY: /home/linuxbrew/.linuxbrew/lib/ruby/gems/2.7.0
  - USER INSTALLATION DIRECTORY: /home/rohanlekhwani/.gem/ruby/2.7.0
  - RUBY EXECUTABLE: /home/linuxbrew/.linuxbrew/opt/ruby/bin/ruby
  - GIT EXECUTABLE: /usr/bin/git
  - EXECUTABLE DIRECTORY: /home/linuxbrew/.linuxbrew/lib/ruby/gems/2.7.0/bin
  - SPEC CACHE DIRECTORY: /home/rohanlekhwani/.gem/specs
  - SYSTEM CONFIGURATION DIRECTORY: /home/linuxbrew/.linuxbrew/Cellar/ruby/2.7.1_3/etc
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-linux
  - GEM PATHS:
     - /home/linuxbrew/.linuxbrew/lib/ruby/gems/2.7.0
     - /home/rohanlekhwani/.gem/ruby/2.7.0
     - /home/linuxbrew/.linuxbrew/Cellar/ruby/2.7.1_3/lib/ruby/gems/2.7.0
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - https://rubygems.org/
  - SHELL PATH:
     - /home/rohanlekhwani/.rbenv/shims
     - /home/linuxbrew/.linuxbrew/bin
     - /home/linuxbrew/.linuxbrew/sbin
     - /home/linuxbrew/.linuxbrew/bin
     - /home/linuxbrew/.linuxbrew/sbin
     - /home/rohanlekhwani/.local/bin
     - /usr/local/sbin
     - /usr/local/bin
     - /usr/sbin
     - /usr/bin
     - /sbin
     - /bin
     - /usr/games
     - /usr/local/games
     - /snap/bin
</code>```

On doing gem list, rails is clearly visible:

```<code>actioncable (6.0.3.1)
actionmailbox (6.0.3.1)
actionmailer (6.0.3.1)
actionpack (6.0.3.1)
actiontext (6.0.3.1)
actionview (6.0.3.1)
activejob (6.0.3.1)
activemodel (6.0.3.1)
activerecord (6.0.3.1)
activestorage (6.0.3.1)
activesupport (6.0.3.1)
benchmark (default: 0.1.0)
bigdecimal (default: 2.0.0)
bond (0.5.1)
builder (3.2.4)
bundler (2.1.4, default: 2.1.2)
cgi (default: 0.1.0)
concurrent-ruby (1.1.6)
crass (1.0.6)
csv (default: 3.1.2)
data_uri (0.1.0)
date (default: 3.0.0)
delegate (default: 0.1.0)
did_you_mean (default: 1.4.0)
erubi (1.9.0)
etc (default: 1.1.0)
fcntl (default: 1.0.0)
fiddle (default: 1.0.0)
fileutils (default: 1.4.1)
forwardable (default: 1.3.1)
getoptlong (default: 0.1.0)
globalid (0.4.2)
i18n (1.8.2)
io-console (default: 0.5.6)
ipaddr (default: 1.2.2)
irb (default: 1.2.3)
iruby (0.4.0)
json (default: 2.3.0)
logger (default: 1.4.2)
loofah (2.5.0)
mail (2.7.1)
marcel (0.3.3)
matrix (default: 0.2.0)
method_source (1.0.0)
mimemagic (0.3.5)
mini_mime (1.0.2)
mini_portile2 (2.4.0)
minitest (5.13.0)
multi_json (1.14.1)
mutex_m (default: 0.1.0)
net-pop (default: 0.1.0)
net-smtp (default: 0.1.0)
net-telnet (0.2.0)
nio4r (2.5.2)
nokogiri (1.10.9)
observer (default: 0.1.0)
open3 (default: 0.1.0)
openssl (default: 2.1.2)
ostruct (default: 0.2.0)
power_assert (1.1.7)
prime (default: 0.1.1)
pstore (default: 0.1.0)
psych (default: 3.1.0)
racc (default: 1.4.16)
rack (2.2.2)
rack-test (1.1.0)
rails (6.0.3.1)
rails-dom-testing (2.0.3)
rails-html-sanitizer (1.3.0)
railties (6.0.3.1)
rake (13.0.1)
rdoc (default: 6.2.1)
readline (default: 0.0.2)
readline-ext (default: 0.1.0)
reline (default: 0.1.3)
rexml (default: 3.2.3)
rss (default: 0.2.8)
sdbm (default: 1.0.0)
singleton (default: 0.1.0)
sprockets (4.0.0)
sprockets-rails (3.2.1)
stringio (default: 0.1.0)
strscan (default: 1.0.3)
test-unit (3.3.4)
thor (1.0.1)
thread_safe (0.3.6)
timeout (default: 0.1.0)
tracer (default: 0.1.0)
tzinfo (1.2.7)
uri (default: 0.10.0)
webrick (default: 1.6.0)
websocket-driver (0.7.2)
websocket-extensions (0.1.4)
xmlrpc (0.3.0)
yaml (default: 0.1.0)
zeitwerk (2.3.0)
zlib (default: 1.1.0)
</code>```

Just a heads up, as you can see by the difference in INSTALLATION DIRECTORY and USER INSTALLATION DIRECTORY ruby is installed through Homebrew, so not sure if that might be causing a problem.

PS: When I go into /home/linuxbrew/.linuxbrew/lib/ruby/gems/2.7.0/gems/rails-6.0.3.1 all I see is a README.md file

答:
Figured it out. As supposed it was a path problem, caused due to installing ruby with brew and trying to access rails outside the brew environment.

Solution

Either add rails inside the linuxbrew environment to PATH

Install using sudo apt-get install ruby-full which automatically adds rails to path.

Body:
I installed rails using gem install rails and it showed installed successfully. But on doing rails --version I get _rails_command:10: command not found.

Here is what I get on doing gem env

    RubyGems Environment:
  - RUBYGEMS VERSION: 3.1.2
  - RUBY VERSION: 2.7.1 (2020-03-31 patchlevel 83) [x86_64-linux]
  - INSTALLATION DIRECTORY: /home/linuxbrew/.linuxbrew/lib/ruby/gems/2.7.0
  - USER INSTALLATION DIRECTORY: /home/rohanlekhwani/.gem/ruby/2.7.0
  - RUBY EXECUTABLE: /home/linuxbrew/.linuxbrew/opt/ruby/bin/ruby
  - GIT EXECUTABLE: /usr/bin/git
  - EXECUTABLE DIRECTORY: /home/linuxbrew/.linuxbrew/lib/ruby/gems/2.7.0/bin
  - SPEC CACHE DIRECTORY: /home/rohanlekhwani/.gem/specs
  - SYSTEM CONFIGURATION DIRECTORY: /home/linuxbrew/.linuxbrew/Cellar/ruby/2.7.1_3/etc
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-linux
  - GEM PATHS:
     - /home/linuxbrew/.linuxbrew/lib/ruby/gems/2.7.0
     - /home/rohanlekhwani/.gem/ruby/2.7.0
     - /home/linuxbrew/.linuxbrew/Cellar/ruby/2.7.1_3/lib/ruby/gems/2.7.0
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - https://rubygems.org/
  - SHELL PATH:
     - /home/rohanlekhwani/.rbenv/shims
     - /home/linuxbrew/.linuxbrew/bin
     - /home/linuxbrew/.linuxbrew/sbin
     - /home/linuxbrew/.linuxbrew/bin
     - /home/linuxbrew/.linuxbrew/sbin
     - /home/rohanlekhwani/.local/bin
     - /usr/local/sbin
     - /usr/local/bin
     - /usr/sbin
     - /usr/bin
     - /sbin
     - /bin
     - /usr/games
     - /usr/local/games
     - /snap/bin

On doing gem list, rails is clearly visible:

actioncable (6.0.3.1)
actionmailbox (6.0.3.1)
actionmailer (6.0.3.1)
actionpack (6.0.3.1)
actiontext (6.0.3.1)
actionview (6.0.3.1)
activejob (6.0.3.1)
activemodel (6.0.3.1)
activerecord (6.0.3.1)
activestorage (6.0.3.1)
activesupport (6.0.3.1)
benchmark (default: 0.1.0)
bigdecimal (default: 2.0.0)
bond (0.5.1)
builder (3.2.4)
bundler (2.1.4, default: 2.1.2)
cgi (default: 0.1.0)
concurrent-ruby (1.1.6)
crass (1.0.6)
csv (default: 3.1.2)
data_uri (0.1.0)
date (default: 3.0.0)
delegate (default: 0.1.0)
did_you_mean (default: 1.4.0)
erubi (1.9.0)
etc (default: 1.1.0)
fcntl (default: 1.0.0)
fiddle (default: 1.0.0)
fileutils (default: 1.4.1)
forwardable (default: 1.3.1)
getoptlong (default: 0.1.0)
globalid (0.4.2)
i18n (1.8.2)
io-console (default: 0.5.6)
ipaddr (default: 1.2.2)
irb (default: 1.2.3)
iruby (0.4.0)
json (default: 2.3.0)
logger (default: 1.4.2)
loofah (2.5.0)
mail (2.7.1)
marcel (0.3.3)
matrix (default: 0.2.0)
method_source (1.0.0)
mimemagic (0.3.5)
mini_mime (1.0.2)
mini_portile2 (2.4.0)
minitest (5.13.0)
multi_json (1.14.1)
mutex_m (default: 0.1.0)
net-pop (default: 0.1.0)
net-smtp (default: 0.1.0)
net-telnet (0.2.0)
nio4r (2.5.2)
nokogiri (1.10.9)
observer (default: 0.1.0)
open3 (default: 0.1.0)
openssl (default: 2.1.2)
ostruct (default: 0.2.0)
power_assert (1.1.7)
prime (default: 0.1.1)
pstore (default: 0.1.0)
psych (default: 3.1.0)
racc (default: 1.4.16)
rack (2.2.2)
rack-test (1.1.0)
rails (6.0.3.1)
rails-dom-testing (2.0.3)
rails-html-sanitizer (1.3.0)
railties (6.0.3.1)
rake (13.0.1)
rdoc (default: 6.2.1)
readline (default: 0.0.2)
readline-ext (default: 0.1.0)
reline (default: 0.1.3)
rexml (default: 3.2.3)
rss (default: 0.2.8)
sdbm (default: 1.0.0)
singleton (default: 0.1.0)
sprockets (4.0.0)
sprockets-rails (3.2.1)
stringio (default: 0.1.0)
strscan (default: 1.0.3)
test-unit (3.3.4)
thor (1.0.1)
thread_safe (0.3.6)
timeout (default: 0.1.0)
tracer (default: 0.1.0)
tzinfo (1.2.7)
uri (default: 0.10.0)
webrick (default: 1.6.0)
websocket-driver (0.7.2)
websocket-extensions (0.1.4)
xmlrpc (0.3.0)
yaml (default: 0.1.0)
zeitwerk (2.3.0)
zlib (default: 1.1.0)

Just a heads up, as you can see by the difference in INSTALLATION DIRECTORY and USER INSTALLATION DIRECTORY ruby is installed through Homebrew, so not sure if that might be causing a problem.

PS: When I go into /home/linuxbrew/.linuxbrew/lib/ruby/gems/2.7.0/gems/rails-6.0.3.1 all I see is a README.md file


问:
C++ Vectors adding and subtracting throwing out "expression: vector subscript out of range." error
I'm having a tad bit of trouble with my code. I've made a 10x10 grid, in which a player can move around. In this grid are enemies and certain events. I've used a vector to store these events in. For example, if a player hits the tile "e" in the 10x10 grid array, the player would run into an enemy, and the "e" in the vector would be reducted so that wouldn't happen again on that tile, instead, displaying "corridor". This works for the "e" tile (line 147), but when I try to replicate the code for the "i" (line 133) tile, it breaks and comes out with the error "expression: vector subscript out of range.". I have no idea why it's doing this, I'm quite new to coding. If you start the game, and move to X:10 Y4, you will see the error. I'd really appreciate any feedback or advice. Apologies if the code is long as well, I've tried to condense it as much as I can. </p>

```<code>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <Windows.h>
#include <stdlib.h>
#include <time.h>

int nextX;
int nextY;
int playerX = 1;
int playerY = 1;

std::string name;
std::string move;

bool win = false;

std::vector<std::string> playerPrivInv;

void movePlayer(int prevX, int prevY);
void location(int X, int Y);
void game();

char dungeon[12][12] = {
{ 'w','w','w','w','w','w','w','w','w','w','w','w'},
{ 'w','s','c','c','c','c','w','c','c','c','r','w'},
{ 'w','c','w','w','w','c','w','c','w','w','w','w'},
{ 'w','D','w','c','w','c','w','c','w','w','w','w'},
{ 'w','R','w','c','w','c','d','e','c','c','i','w'},
{ 'w','w','w','c','w','c','w','w','w','w','w','w'},
{ 'w','w','c','c','c','c','c','c','c','w','r','w'},
{ 'w','w','c','w','w','w','w','c','w','c','c','w'},
{ 'w','w','c','w','i','c','c','c','c','c','b','w'},
{ 'w','w','w','w','w','w','w','c','w','w','w','w'},
{ 'w','f','c','c','c','c','G','c','w','w','w','w'},
{ 'w','w','w','w','w','w','w','w','w','w','w','w'}

};
int main()
{

    playerPrivInv.push_back("e"); // 0
    playerPrivInv.push_back("x"); // 1
    playerPrivInv.push_back("k"); // 2
    playerPrivInv.push_back("i"); // 3

    game();

}

void game() {

    do {

        location(playerX, playerY);
        movePlayer(playerX, playerY);

    } while (win == false);

}

void movePlayer(int prevX, int prevY) {

    std::cout << "You're coordinates are X: " << prevX << " Y: " << prevY << std::endl;

    std::cin >> move;

    if (move == "n" || move == "north") {
        nextY = playerY - 1;
        if ((nextY >= 0) && (nextY < 12)) {
            playerY = nextY;
        }
        else {
            std::cout << "Can't move there" << std::endl;
        }
    }
    else if (move == "e") {
        nextX = playerX + 1;
        if ((nextX >= 0) && (nextX < 12)) {
            playerX = nextX;
        }
        else {
            std::cout << "Can't move there" << std::endl;
        }
    }
    else if (move == "w") {
        nextX = playerX - 1;
        if ((nextX >= 0) && (nextX < 12)) {
            playerX = nextX;
        }
        else {
            std::cout << "Can't move there" << std::endl;
        }
    }
    else if (move == "s") {
        nextY = playerY + 1;
        if ((nextY >= 0) && (nextY < 12)) {
            playerY = nextY;
        }
        else {
            std::cout << "Can't move there" << std::endl;
        }
    }

    system("CLS");

}

void location(int X, int Y) {

    char local = dungeon[Y][X];

    // S: Starter Room
    // F: Final Room
    // D: Door
    // C: Corridor
    // R: Room
    // W: Wall
    // E: Enemy
    // X: Enemy
    // K: Enemy

    switch (local) {

    case 'i':

        if (playerPrivInv[3] == "i") {

            playerPrivInv.erase(playerPrivInv.begin() + 3);
            std::cout << "Interogated!" << std::endl;
        }
        else {

            std::cout << "Corridor" << std::endl;
        }

        break;
    case 'r':
        std::cout << "Room" << std::endl;
        break;
    case 'e':

        if (playerPrivInv[0] == "e") {

            playerPrivInv.erase(playerPrivInv.begin() + 0);

            std::cout << "Enemy" << std::endl;

        }
        else {

            std::cout << "Corridor" << std::endl;
        }
        break;
    case 's':
        std::cout << "Starter Room" << std::endl;
        break;
    case 'f':
        std::cout << "Godrik's Finale" << std::endl;
        break;
    case 'd':
        std::cout << "There's a door in the way, its unlocked..." << std::endl;
        break;
    case 'D':

        if (move == "s" || move == "south") {

            nextY = playerY - 1;

            if ((nextY >= 0) && (nextY < 12)) {

                playerY = nextY;
            }

        }

        std::cout << "There's a door in the way, its locked..." << std::endl;
        std::cout << "You need to find a key..." << std::endl;
        std::cout << std::endl;
        break;
    case 'c':
        std::cout << "Corridor" << std::endl;
        break;
    case 'R':
        std::cout << "You enter a dark office..." << std::endl;
        std::cout << "Room" << std::endl;
        break;
    case 'w':

        if (move == "e" || move == "east") {

            std::cout << "That's a Wall" << std::endl;
            nextX = playerX - 1;

            if ((nextX >= 0) && (nextX < 12)) {

                playerX = nextX;

            }
        }
        else if (move == "w" || move == "west") {

            std::cout << "That's a Wall" << std::endl;
            nextX = playerX + 1;

            if ((nextX >= 0) && (nextX < 12)) {

                playerX = nextX;

            }
        }
        else if (move == "s" || move == "south") {

            std::cout << "That's a Wall" << std::endl;
            nextY = playerY - 1;

            if ((nextY >= 0) && (nextY < 12)) {

                playerY = nextY;

            }
        }
        else if (move == "n" || move == "north") {

            std::cout << "That's a Wall" << std::endl;
            nextY = playerY + 1;

            if ((nextY >= 0) && (nextY < 12)) {

                playerY = nextY;

            }
        }
    }
}
</code>```

答:
When you handle the case for 'e', you remove one of the elements from playerPrivInv, leaving it with 3 elements. Later when you try to process the case for 'i', your attempt to access playerPrivInv[3] results in the out of bounds runtime error because that vector only has 3 elements in it, not four.

Possible solutions include changing the element in playerPrivInv to something else (like an empty string) rather than erasing it from the vector, or searching the vector for the matching string rather than assuming it lies at a particular place.

Body:
I'm having a tad bit of trouble with my code. I've made a 10x10 grid, in which a player can move around. In this grid are enemies and certain events. I've used a vector to store these events in. For example, if a player hits the tile "e" in the 10x10 grid array, the player would run into an enemy, and the "e" in the vector would be reducted so that wouldn't happen again on that tile, instead, displaying "corridor". This works for the "e" tile (line 147), but when I try to replicate the code for the "i" (line 133) tile, it breaks and comes out with the error "expression: vector subscript out of range.". I have no idea why it's doing this, I'm quite new to coding. If you start the game, and move to X:10 Y4, you will see the error. I'd really appreciate any feedback or advice. Apologies if the code is long as well, I've tried to condense it as much as I can.

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <Windows.h>
#include <stdlib.h>
#include <time.h>

int nextX;
int nextY;
int playerX = 1;
int playerY = 1;

std::string name;
std::string move;

bool win = false;

std::vector<std::string> playerPrivInv;

void movePlayer(int prevX, int prevY);
void location(int X, int Y);
void game();

char dungeon[12][12] = {
{ 'w','w','w','w','w','w','w','w','w','w','w','w'},
{ 'w','s','c','c','c','c','w','c','c','c','r','w'},
{ 'w','c','w','w','w','c','w','c','w','w','w','w'},
{ 'w','D','w','c','w','c','w','c','w','w','w','w'},
{ 'w','R','w','c','w','c','d','e','c','c','i','w'},
{ 'w','w','w','c','w','c','w','w','w','w','w','w'},
{ 'w','w','c','c','c','c','c','c','c','w','r','w'},
{ 'w','w','c','w','w','w','w','c','w','c','c','w'},
{ 'w','w','c','w','i','c','c','c','c','c','b','w'},
{ 'w','w','w','w','w','w','w','c','w','w','w','w'},
{ 'w','f','c','c','c','c','G','c','w','w','w','w'},
{ 'w','w','w','w','w','w','w','w','w','w','w','w'}

};
int main()
{

    playerPrivInv.push_back("e"); // 0
    playerPrivInv.push_back("x"); // 1
    playerPrivInv.push_back("k"); // 2
    playerPrivInv.push_back("i"); // 3

    game();

}

void game() {

    do {

        location(playerX, playerY);
        movePlayer(playerX, playerY);

    } while (win == false);

}

void movePlayer(int prevX, int prevY) {

    std::cout << "You're coordinates are X: " << prevX << " Y: " << prevY << std::endl;

    std::cin >> move;

    if (move == "n" || move == "north") {
        nextY = playerY - 1;
        if ((nextY >= 0) && (nextY < 12)) {
            playerY = nextY;
        }
        else {
            std::cout << "Can't move there" << std::endl;
        }
    }
    else if (move == "e") {
        nextX = playerX + 1;
        if ((nextX >= 0) && (nextX < 12)) {
            playerX = nextX;
        }
        else {
            std::cout << "Can't move there" << std::endl;
        }
    }
    else if (move == "w") {
        nextX = playerX - 1;
        if ((nextX >= 0) && (nextX < 12)) {
            playerX = nextX;
        }
        else {
            std::cout << "Can't move there" << std::endl;
        }
    }
    else if (move == "s") {
        nextY = playerY + 1;
        if ((nextY >= 0) && (nextY < 12)) {
            playerY = nextY;
        }
        else {
            std::cout << "Can't move there" << std::endl;
        }
    }

    system("CLS");

}

void location(int X, int Y) {

    char local = dungeon[Y][X];

    // S: Starter Room
    // F: Final Room
    // D: Door
    // C: Corridor
    // R: Room
    // W: Wall
    // E: Enemy
    // X: Enemy
    // K: Enemy

    switch (local) {

    case 'i':

        if (playerPrivInv[3] == "i") {

            playerPrivInv.erase(playerPrivInv.begin() + 3);
            std::cout << "Interogated!" << std::endl;
        }
        else {

            std::cout << "Corridor" << std::endl;
        }

        break;
    case 'r':
        std::cout << "Room" << std::endl;
        break;
    case 'e':

        if (playerPrivInv[0] == "e") {

            playerPrivInv.erase(playerPrivInv.begin() + 0);

            std::cout << "Enemy" << std::endl;

        }
        else {

            std::cout << "Corridor" << std::endl;
        }
        break;
    case 's':
        std::cout << "Starter Room" << std::endl;
        break;
    case 'f':
        std::cout << "Godrik's Finale" << std::endl;
        break;
    case 'd':
        std::cout << "There's a door in the way, its unlocked..." << std::endl;
        break;
    case 'D':

        if (move == "s" || move == "south") {

            nextY = playerY - 1;

            if ((nextY >= 0) && (nextY < 12)) {

                playerY = nextY;
            }

        }

        std::cout << "There's a door in the way, its locked..." << std::endl;
        std::cout << "You need to find a key..." << std::endl;
        std::cout << std::endl;
        break;
    case 'c':
        std::cout << "Corridor" << std::endl;
        break;
    case 'R':
        std::cout << "You enter a dark office..." << std::endl;
        std::cout << "Room" << std::endl;
        break;
    case 'w':

        if (move == "e" || move == "east") {

            std::cout << "That's a Wall" << std::endl;
            nextX = playerX - 1;

            if ((nextX >= 0) && (nextX < 12)) {

                playerX = nextX;

            }
        }
        else if (move == "w" || move == "west") {

            std::cout << "That's a Wall" << std::endl;
            nextX = playerX + 1;

            if ((nextX >= 0) && (nextX < 12)) {

                playerX = nextX;

            }
        }
        else if (move == "s" || move == "south") {

            std::cout << "That's a Wall" << std::endl;
            nextY = playerY - 1;

            if ((nextY >= 0) && (nextY < 12)) {

                playerY = nextY;

            }
        }
        else if (move == "n" || move == "north") {

            std::cout << "That's a Wall" << std::endl;
            nextY = playerY + 1;

            if ((nextY >= 0) && (nextY < 12)) {

                playerY = nextY;

            }
        }
    }
}