问:
Cannot sort a range with variables (GAS script on Google Sheets)
My full script offers a sidebar to users, for them to choose the four columns they wish to sort and the sort order of each in a Sheets table called "sortTemp". Their responses are stored in a sheet called "tempVar". All is well until I get to the actual sorting. I gather the variables from tempVar, but when it gets to the sort command, it does nothing. No error. No sorting.

I'm putting here the portion of the code that is failing.

```<code>function testSort() {
  // Sort tempVar
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('A1').activate();
  var currentCell = spreadsheet.getCurrentCell();
  spreadsheet.getActiveRange().getDataRegion().activate();
  currentCell.activateAsCurrentCell();

  // Map tempVar to sortTempColumns
  var col1 = spreadsheet.getRange('tempVar!B5').getValue();
  var col1dir = spreadsheet.getRange('tempVar!B6').getValue();
  var col2 = spreadsheet.getRange('tempVar!B7').getValue();
  var col2dir = spreadsheet.getRange('tempVar!B8').getValue();
  var col3 = spreadsheet.getRange('tempVar!B10').getValue();
  var col3dir = spreadsheet.getRange('tempVar!B11').getValue();
  var col4 = spreadsheet.getRange('tempVar!B12').getValue();
  var col4dir = spreadsheet.getRange('tempVar!B13').getValue();

  spreadsheet.getActiveRange().sort([{column: col1, ascending: col1dir}, {column: col2, ascending: col2dir}, {column: col3, ascending: col3dir}, {column: col4, ascending: col4dir}]);
  spreadsheet.getRange('A1').activate();
}
</code>```

Here is a sample of the data being sorted:
[[table with sample data]][1]

Here is the sheet that the variables are being drawn from:
[tempVar][2]

The user's sort choices are stored in column A and reconfigured for use by the sort script in column B.

The column numbers are being calculated like this:
=VLOOKUP(A5,C$1:D$8,2,false)

The booleans are being calculated with this:
=lower(if(A6<="Ascending",true,false))

What I've Tried

I've tested replacing the variables with real numbers and booleans
for the ascending part, to determine if I had written the code
incorrectly. It works without using variables--breaks with them.

I've tested populating the variables with numbers and booleans as
part of the script here, rather than gathering them from another
sheet in the file. Setting "col1 = 4" for example. It did nothing.

I've tested populating the variables with numbers and booleans as
part of the script here, rather than gathering them from another
sheet in the file. Setting "col1 = 4" for example. It did nothing.

I've used ui alerts to ensure the variables are coming over, and they
are. I've even done math with the variables in the alert to be sure
they're real numbers, and they are.

I've tried putting "Number()" around the script that's populating the
variables, to ensure they're converted to numbers. It didn't
help.

I've let a macro memorize the sort steps, then plugged in
the variables, to ensure I have the code that is supposed to work. No
help.

I am new to GAS script and I'm hoping my error will be obvious to someone who is skilled.

What am I doing wrong?

[1]:  sortTemp table

|12|1|Thomas   |Hannah |Jr.   |              |Spartanburg District|SC|1790|
|13|1|Tom      |Hannah |M.D.  |Smithville    |Spartanburg County  |SC|1800|
|14|1|J. T.    |Hannah |Junior|              |Renfroe             |SC|1810|
|15|1|Robert   |Hanna  |Jr    |              |Spartanburg District|SC|1820|
|16|1|D. C.    |Baker  |      |              |Tuscaloosa County   |AL|1830|
|17|1|Donna Cox|Baker  |      |Birmingham    |Jefferson           |AL|1860|
|18|1|John     |Maloney|      |Eastern Valley|Taylor County       |FL|1860|
```
<p>[2]: tempVar table</p>
<pre class="lang-none prettyprint-override"><code>| Census Worksheet           | GAS Value | Key           |   |
| Copy of Census Worksheet 5 |           | Given Name(s) | 3 |
| 6                          |           | Surname       | 4 |
| 19                         |           | Suffix        | 5 |
| Surname                    | 4         | Community     | 6 |
|                            | true      | County        | 7 |
| Given Name(s)              | 3         | State         | 8 |
|                            | true      | Census Year   | 9 |
|                            |           |               |   |
| State                      | 8         |               |   |
|                            | true      |               |   |
| County                     | 7         |               |   |
|                            | true      |               |   |
| Copy to new sheet          |           |               |
</code>```

答:
The problem turned out to be in the boolean variables. They were coming through as strings and preventing the sort from happening. I have changed the script to convert the "true" and "false" strings to booleans using JSON.parse(), and the script runs fine.

Here is the new code:

```<code>function testSort() {
  // Sort temp
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('A1').activate();
  var currentCell = spreadsheet.getCurrentCell();
  spreadsheet.getActiveRange().getDataRegion().activate();
  currentCell.activateAsCurrentCell();

  // Map tempVar to sortTempColumns
  var col1 = spreadsheet.getRange('tempVar!B5').getValue();
  var col1dir = JSON.parse(spreadsheet.getRange('tempVar!B6').getValue());
  var col2 = spreadsheet.getRange('tempVar!B7').getValue();
  var col2dir = JSON.parse(spreadsheet.getRange('tempVar!B8').getValue());
  var col3 = spreadsheet.getRange('tempVar!B10').getValue();
  var col3dir = JSON.parse(spreadsheet.getRange('tempVar!B11').getValue());
  var col4 = spreadsheet.getRange('tempVar!B12').getValue();
  var col4dir = JSON.parse(spreadsheet.getRange('tempVar!B13').getValue());

  spreadsheet.getActiveRange().sort([{column: col1, ascending: col1dir}, {column: col2, ascending: col2dir}, {column: col3, ascending: col3dir}, {column: col4, ascending: col4dir}]);
  spreadsheet.getRange('A1').activate();
}
</code>```

Body:
My full script offers a sidebar to users, for them to choose the four columns they wish to sort and the sort order of each in a Sheets table called "sortTemp". Their responses are stored in a sheet called "tempVar". All is well until I get to the actual sorting. I gather the variables from tempVar, but when it gets to the sort command, it does nothing. No error. No sorting.

I'm putting here the portion of the code that is failing.

function testSort() {
  // Sort tempVar
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('A1').activate();
  var currentCell = spreadsheet.getCurrentCell();
  spreadsheet.getActiveRange().getDataRegion().activate();
  currentCell.activateAsCurrentCell();

  // Map tempVar to sortTempColumns
  var col1 = spreadsheet.getRange('tempVar!B5').getValue();
  var col1dir = spreadsheet.getRange('tempVar!B6').getValue();
  var col2 = spreadsheet.getRange('tempVar!B7').getValue();
  var col2dir = spreadsheet.getRange('tempVar!B8').getValue();
  var col3 = spreadsheet.getRange('tempVar!B10').getValue();
  var col3dir = spreadsheet.getRange('tempVar!B11').getValue();
  var col4 = spreadsheet.getRange('tempVar!B12').getValue();
  var col4dir = spreadsheet.getRange('tempVar!B13').getValue();

  spreadsheet.getActiveRange().sort([{column: col1, ascending: col1dir}, {column: col2, ascending: col2dir}, {column: col3, ascending: col3dir}, {column: col4, ascending: col4dir}]);
  spreadsheet.getRange('A1').activate();
}

Here is a sample of the data being sorted:
[[table with sample data]][1]

Here is the sheet that the variables are being drawn from:
[tempVar][2]

The user's sort choices are stored in column A and reconfigured for use by the sort script in column B.

The column numbers are being calculated like this:
=VLOOKUP(A5,C$1:D$8,2,false)

The booleans are being calculated with this:
=lower(if(A6<="Ascending",true,false))

What I've Tried

I've tested replacing the variables with real numbers and booleans
for the ascending part, to determine if I had written the code
incorrectly. It works without using variables--breaks with them.

I've tested populating the variables with numbers and booleans as
part of the script here, rather than gathering them from another
sheet in the file. Setting "col1 = 4" for example. It did nothing.

I've tested populating the variables with numbers and booleans as
part of the script here, rather than gathering them from another
sheet in the file. Setting "col1 = 4" for example. It did nothing.

I've used ui alerts to ensure the variables are coming over, and they
are. I've even done math with the variables in the alert to be sure
they're real numbers, and they are.

I've tried putting "Number()" around the script that's populating the
variables, to ensure they're converted to numbers. It didn't
help.

I've let a macro memorize the sort steps, then plugged in
the variables, to ensure I have the code that is supposed to work. No
help.

I am new to GAS script and I'm hoping my error will be obvious to someone who is skilled.

What am I doing wrong?

[1]:  sortTemp table

|12|1|Thomas   |Hannah |Jr.   |              |Spartanburg District|SC|1790|
|13|1|Tom      |Hannah |M.D.  |Smithville    |Spartanburg County  |SC|1800|
|14|1|J. T.    |Hannah |Junior|              |Renfroe             |SC|1810|
|15|1|Robert   |Hanna  |Jr    |              |Spartanburg District|SC|1820|
|16|1|D. C.    |Baker  |      |              |Tuscaloosa County   |AL|1830|
|17|1|Donna Cox|Baker  |      |Birmingham    |Jefferson           |AL|1860|
|18|1|John     |Maloney|      |Eastern Valley|Taylor County       |FL|1860|

[2]: tempVar table

| Census Worksheet           | GAS Value | Key           |   |
| Copy of Census Worksheet 5 |           | Given Name(s) | 3 |
| 6                          |           | Surname       | 4 |
| 19                         |           | Suffix        | 5 |
| Surname                    | 4         | Community     | 6 |
|                            | true      | County        | 7 |
| Given Name(s)              | 3         | State         | 8 |
|                            | true      | Census Year   | 9 |
|                            |           |               |   |
| State                      | 8         |               |   |
|                            | true      |               |   |
| County                     | 7         |               |   |
|                            | true      |               |   |
| Copy to new sheet          |           |               |

Body:
The problem turned out to be in the boolean variables. They were coming through as strings and preventing the sort from happening. I have changed the script to convert the "true" and "false" strings to booleans using JSON.parse(), and the script runs fine.

Here is the new code:

function testSort() {
  // Sort temp
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('A1').activate();
  var currentCell = spreadsheet.getCurrentCell();
  spreadsheet.getActiveRange().getDataRegion().activate();
  currentCell.activateAsCurrentCell();

  // Map tempVar to sortTempColumns
  var col1 = spreadsheet.getRange('tempVar!B5').getValue();
  var col1dir = JSON.parse(spreadsheet.getRange('tempVar!B6').getValue());
  var col2 = spreadsheet.getRange('tempVar!B7').getValue();
  var col2dir = JSON.parse(spreadsheet.getRange('tempVar!B8').getValue());
  var col3 = spreadsheet.getRange('tempVar!B10').getValue();
  var col3dir = JSON.parse(spreadsheet.getRange('tempVar!B11').getValue());
  var col4 = spreadsheet.getRange('tempVar!B12').getValue();
  var col4dir = JSON.parse(spreadsheet.getRange('tempVar!B13').getValue());

  spreadsheet.getActiveRange().sort([{column: col1, ascending: col1dir}, {column: col2, ascending: col2dir}, {column: col3, ascending: col3dir}, {column: col4, ascending: col4dir}]);
  spreadsheet.getRange('A1').activate();
}


来源: stackexchange

问:
Display Image Name in Slide Show
I have been learning to use a slideshow code I saw on a website somewhere. Although I have managed to get it working with the images showing well, but I can't figure out how to show the image name in another table alongside the images when the slide changes.

I have provided the code here. so I need your help. What I'm looking for s that whenever the slideshow changes with another picture, I want the picture name displayed next to it.

Thanks for your asisstance.

Update - Here's the updated code based on Gilly3's suggestion, but I'm still confused on how to get the name displayed

```<code><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<title>JQuery Cycle Plugin - Pager Demo with Prev/Next Controls</title>
<link rel="stylesheet" type="text/css" media="screen" href="../jq.css" />
<link rel="stylesheet" type="text/css" media="screen" href="cycle.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" src="http://malsup.github.com/chili-1.7.pack.js"></script>
<script type="text/javascript" src="http://malsup.github.com/jquery.cycle.all.js"></script>

<style type="text/css">
#main { margin: 20px }
#nav { margin: 10px; position: relative }
#nav li { float: left; list-style: none}
#nav a { margin: 5px; padding: 3px 5px; border: 1px solid #ccc; background: #fc0; text-decoration: none }
#nav li.activeSlide a { background: #faa; color: black }
#nav a:focus { outline: none; }

</style>

<script type="text/javascript">
$(document).ready(function() {
     $('#slideshow').cycle({
          prev:    '.prev', // Setup prev links
          next:    '.next', // Setup next links
          pager:   '.nav',       // Setup pager navs

         before: function () {
        $("#name").text(this.alt);
    }
     });
});
</script>

<style type="text/css">
#left, #slideshow, #right { float: left; width: 200px; }
</style>
</head>
<body>

<!-- left nav bar -->
<div id="left">
    <a href="#"><span class="prev">Prev</span></a>
    <a href="#"><span class="next">Next</span></a>

    <ul class="nav"></ul>
</div>

<!-- slideshow -->
<div id="slideshow">

 <?php
                 mysql_connect("localhost", "root", "")or die("cannot connect");
                 mysql_select_db($db_name)or die("cannot select DB");

                 $data = mysql_query("SELECT * FROM people") or die(mysql_error());
                 while($info = mysql_fetch_array( $data )){
                 echo "<img src=\"http://localhost:8080/about/images/".$info['photo'] . "\" alt=\"".$info['name'] ."\"/>";
  }
?>

</div>

<div id="name">
HELP ME PRINT THE NAME HERE
</div>
<!-- right nav bar -->
<div id="right">
    <a href="#"><span class="prev">Prev</span></a>
    <a href="#"><span class="next">Next</span></a>
    <ul class="nav"></ul>
</div>

</div>

</body>
</html>
</code>```

答:
Use either of the before or after events, depending on when you want the name to change.

```<code>$('#slideshow').cycle({
    prev: '.prev',
    next: '.next',
    pager: '.nav',
    before: function () {
        $("#name").text(this.alt);
    }
});
</code>```

You'll need to populate alt with the name in your php.  If you don't want to add a tooltip, also add title="".

```<code>echo "<img src=\"http://localhost:8080/people/uploads/".$info['pic'] . "\" alt=\"".$info['name'] . "\" title=\"\" />";
</code>```

ContentLicense: CC BY-SA 3.0

Title: Display Image Name in Slide Show

Body:
I have been learning to use a slideshow code I saw on a website somewhere. Although I have managed to get it working with the images showing well, but I can't figure out how to show the image name in another table alongside the images when the slide changes.

I have provided the code here. so I need your help. What I'm looking for s that whenever the slideshow changes with another picture, I want the picture name displayed next to it.

Thanks for your asisstance.

Update - Here's the updated code based on Gilly3's suggestion, but I'm still confused on how to get the name displayed

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<title>JQuery Cycle Plugin - Pager Demo with Prev/Next Controls</title>
<link rel="stylesheet" type="text/css" media="screen" href="../jq.css" />
<link rel="stylesheet" type="text/css" media="screen" href="cycle.css" />

    Prev
    Next

 <?php
                 mysql_connect("localhost", "root", "")or die("cannot connect");
                 mysql_select_db($db_name)or die("cannot select DB");

                 $data = mysql_query("SELECT * FROM people") or die(mysql_error());
                 while($info = mysql_fetch_array( $data )){
                 echo "";
  }
?>

HELP ME PRINT THE NAME HERE

    Prev
    Next

Body:
Use either of the before or after events, depending on when you want the name to change.

$('#slideshow').cycle({
    prev: '.prev',
    next: '.next',
    pager: '.nav',
    before: function () {
        $("#name").text(this.alt);
    }
});

You'll need to populate alt with the name in your php.  If you don't want to add a tooltip, also add title="".

echo "<img src=\"http://localhost:8080/people/uploads/".$info['pic'] . "\" alt=\"".$info['name'] . "\" title=\"\" />";


问:
Heterogeneous vs Homogeneous
I'm little bit confused about heterogeneous and homogeneous list and array. In OOP context, if I define base class and it's derived class, why is array of base class homogeneous, if I can store derived classes as well? It's same principle, as void pointer in C (i.e. https://gist.github.com/rawcoder/9720851 ). Every literature says, that homogeneous structure is of same type (semantically), so can you please explain this to me little bit more further?</p>

答:
The simplest way of putting it is that instances of a derived type are instances of a base type, so can be stored in a collection of the base type.

It has more to do with the type of the collection than what's stored in it. If a collection has type array[B], and D < B (type D derives from B), then storing a D in an array[B] doesn't violate the type of the array or operations on the array/elements of the array. However, if the array were defined to hold only descendants of B but not B itself (e.g. array[ D < B ]; array<D extends B> in Java-speak), then it would be heterogenous, because it's declared to hold multiple types, rather than a single type. Note that in some programming languages, "heterogeneous" means holds any type (e.g. array[Any?], array<*>), not just multiple different types.

Outside of such languages, union types muddy the waters, because they allow disparate types to be treated as one. array[A | B | C] could be viewed as heterogeneous, or as the homogeneous array[U], where U = A | B | C.

The point of a type system in programming is to ensure a certain level of correctness by restricting what is allowed, based on type. Homogeneity strengthens the typing system, while unions weaken typing, as they:

can allow an instance of one type to be treated as another, causing a run-time type violation, and

allow for some types to not be handled, which is potentially another error.

Some type systems avoid these by using the more restricted sum type (aka "variant type"), which includes type information along with instances, instead of using union types. This prevents both the above issues with union types, restoring homogeneity. However, type systems that have sum types are usually so strong that the concepts of homogeneity and heretogeneity aren't as useful (basically, every collection is homogeneous, even the heterogeneous ones, which are collections of the maximal type from which all other types descend; consider the array[Any?] example above).

Storing subtypes in a homogeneous collection is a consequence of the LSP, which states that a property of a type should be true of a subtype (i.e. subtypes should be substitutable in contexts in place of a supertype). If the method (e.g. operator[], add) that adds an element to an array takes type B, it should also take subtypes. If code operates on elements of a collection expecting they're of type B, it should operate just as correctly on subtypes.

Note this is distinct from the matter of subtype relationships between collection types (e.g. if D < B, is array[D] < array[B]?), which is a matter of (type) variance.

Title: Heterogeneous vs Homogeneous

ContentLicense: CC BY-SA 4.0


问:
In for loops, is there a way to execute a module function with attributes assigned by the for loop?
Python 3.10.1

Totally new to programming, please be patient.

I want to print a list of all foreground colors available in the colorama module in the color named, like so:

PowerShell Colors

My attempt:

```<code>from colorama import init, Fore, Style
init()

# available foreground colors acquired via dir(Fore)
colors = [
    'BLACK',
    'BLUE',
    'CYAN',
    'GREEN',
    'LIGHTBLACK_EX',
    'LIGHTBLUE_EX',
    'LIGHTCYAN_EX',
    'LIGHTGREEN_EX',
    'LIGHTMAGENTA_EX',
    'LIGHTRED_EX',
    'LIGHTWHITE_EX',
    'LIGHTYELLOW_EX',
    'MAGENTA',
    'RED',
    'WHITE',
    'YELLOW'
]

for col in colors:
    fcol = "Fore." + col
    print(f"  {exec(fcol)}[{col}]{Style.RESET_ALL}")
</code>```

My output (no color changes):

```<code>  None[BLACK]
  None[BLUE]
  None[CYAN]
  None[GREEN]
  None[LIGHTBLACK_EX]
  None[LIGHTBLUE_EX]
  None[LIGHTCYAN_EX]
  None[LIGHTGREEN_EX]
  None[LIGHTMAGENTA_EX]
  None[LIGHTRED_EX]
  None[LIGHTWHITE_EX]
  None[LIGHTYELLOW_EX]
  None[MAGENTA]
  None[RED]
  None[WHITE]
  None[YELLOW]
</code>```

答:
This is how you get your desired output:

```<code>from colorama import Fore

colors = [c for c in dir(Fore) if not c.startswith('__')]

for color in colors:
    print( Fore.__getattribute__(color) + f"[{color}]" )
</code>```

Body:
Python 3.10.1

Totally new to programming, please be patient.

I want to print a list of all foreground colors available in the colorama module in the color named, like so:

PowerShell Colors

My attempt:

from colorama import init, Fore, Style
init()

# available foreground colors acquired via dir(Fore)
colors = [
    'BLACK',
    'BLUE',
    'CYAN',
    'GREEN',
    'LIGHTBLACK_EX',
    'LIGHTBLUE_EX',
    'LIGHTCYAN_EX',
    'LIGHTGREEN_EX',
    'LIGHTMAGENTA_EX',
    'LIGHTRED_EX',
    'LIGHTWHITE_EX',
    'LIGHTYELLOW_EX',
    'MAGENTA',
    'RED',
    'WHITE',
    'YELLOW'
]

for col in colors:
    fcol = "Fore." + col
    print(f"  {exec(fcol)}[{col}]{Style.RESET_ALL}")

My output (no color changes):

  None[BLACK]
  None[BLUE]
  None[CYAN]
  None[GREEN]
  None[LIGHTBLACK_EX]
  None[LIGHTBLUE_EX]
  None[LIGHTCYAN_EX]
  None[LIGHTGREEN_EX]
  None[LIGHTMAGENTA_EX]
  None[LIGHTRED_EX]
  None[LIGHTWHITE_EX]
  None[LIGHTYELLOW_EX]
  None[MAGENTA]
  None[RED]
  None[WHITE]
  None[YELLOW]

Body:
This is how you get your desired output:

from colorama import Fore

colors = [c for c in dir(Fore) if not c.startswith('__')]

for color in colors:
    print( Fore.__getattribute__(color) + f"[{color}]" )


问:
how to reslove wrong username and password error in h2 database and springboot?
Properties used in application.properties

```<code>server.port=8085
spring.datasource.url=jdbc:h2:~/test spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
spring.h2.console.path=/h2
</code>```

Error
how to reslove wrong username and password error in h2 database and springboot?

```<code>org.h2.jdbc.JdbcSQLInvalidAuthorizationSpecException: Wrong user name or password [28000-200]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:461) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:429) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.message.DbException.get(DbException.java:205) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.message.DbException.get(DbException.java:181) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.message.DbException.get(DbException.java:170) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.engine.Engine.validateUserAndPassword(Engine.java:357) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.engine.Engine.createSessionAndValidate(Engine.java:176) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.engine.Engine.createSession(Engine.java:166) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.engine.Engine.createSession(Engine.java:29) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:340) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:173) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:152) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.Driver.connect(Driver.java:69) ~[h2-1.4.200.jar:1.4.200]
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358) ~[HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:477) [HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:560) [HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) [HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) [HikariCP-3.4.5.jar:na]
    at org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration.lambda$h2Console$0(H2ConsoleAutoConfiguration.java:73) [spring-boot-autoconfigure-2.3.0.RELEASE.jar:2.3.0.RELEASE]
</code>```

答:
The following worked for me:

Remove and re-add Saved Setting and Setting Name
[Generic H2(Embedded)] (see screenshot above)

Make sure the JDBC URL, Username, Password match your application properties.

Update, build and restart Spring Boot Application.

Also, delete browser history, cache, etc.,

Sample Application. Properties

```<code>spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:dcbapp
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
</code>```

Body:
Properties used in application.properties

server.port=8085
spring.datasource.url=jdbc:h2:~/test spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
spring.h2.console.path=/h2

Error
how to reslove wrong username and password error in h2 database and springboot?

org.h2.jdbc.JdbcSQLInvalidAuthorizationSpecException: Wrong user name or password [28000-200]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:461) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:429) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.message.DbException.get(DbException.java:205) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.message.DbException.get(DbException.java:181) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.message.DbException.get(DbException.java:170) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.engine.Engine.validateUserAndPassword(Engine.java:357) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.engine.Engine.createSessionAndValidate(Engine.java:176) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.engine.Engine.createSession(Engine.java:166) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.engine.Engine.createSession(Engine.java:29) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:340) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:173) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:152) ~[h2-1.4.200.jar:1.4.200]
    at org.h2.Driver.connect(Driver.java:69) ~[h2-1.4.200.jar:1.4.200]
    at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358) ~[HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:206) ~[HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:477) [HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:560) [HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) [HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) [HikariCP-3.4.5.jar:na]
    at org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration.lambda$h2Console$0(H2ConsoleAutoConfiguration.java:73) [spring-boot-autoconfigure-2.3.0.RELEASE.jar:2.3.0.RELEASE]

Body:
The following worked for me:

Remove and re-add Saved Setting and Setting Name
[Generic H2(Embedded)] (see screenshot above)

Make sure the JDBC URL, Username, Password match your application properties.

Update, build and restart Spring Boot Application.

Also, delete browser history, cache, etc.,

Sample Application. Properties

spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:dcbapp
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect


问:
How to run tests in FitNesse/Slim headless?
we are considering to use FitNesse/Slim.

But is there a way to start all written Tests without browsing the webpage and starting each manually ?

It would be sufficient if there is a one-start-all kind of button somewhere to click.

So either starting all tests from command line (with a report of course) or with on button from the webpage.

Is this doable ?

Thanks in advance

答:
Dan has it correct; but the User Guide is also posted online at:

http://fitnesse.org/FitNesse.UserGuide.ControllingFitNesseFromTheCommandLine


问:
setting windowSoftInputMode:adjustResize does not resize the umano Slideup Panel properly
I am using using slide up panel provided by https://github.com/umano/AndroidSlidingUpPanel

I have set the windowSoftInputMode as resize in activity manifest file as follows (I have only one activity)

```<code>android:windowSoftInputMode="adjustResize"
</code>```

The structure for layout for slideupPanel:

```<code><com.sothree.slidinguppanel.SlidingUpPanelLayout
    xmlns:sothree="http://schemas.android.com/apk/res-auto"
    android:id="@+id/sliding_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="bottom"
    sothree:umanoDragView="@+id/customDragViewId">

    <FrameLayout android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <LinearLayout
        android:id="@+id/customDragViewId"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">

        <include
            android:layout_width="match_parent"
            android:layout_height="55dp"
            layout="@layout/another_layout" />

        <include
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            layout="@layout/yet_another_layout"
            android:layout_weight="1" />

    </LinearLayout>

</com.sothree.slidinguppanel.SlidingUpPanelLayout>
</code>```

When i have inflate an EditText into the container(@+id/container) and get it into focus, the soft keypad is shown. On this, the @+id/sliding_layout is re-sized to fit the screen. But the container height remains same as the sliding_layout when it should be re-sized to end at top of customDragViewId. The container only re-sizes when the bottom sliding panel(@+id/customDragViewId) is dragged.

What should i do so that the container is always re-sized accordingly ?

Also when i set the panel State to hidden (see the following code), the sliding_layout height is not re-sized at all when the keypad shows up. What should i do that sliding_layout is re-sized?

```<code>SlidingUpPanelLayout sliding_layout = (SlidingUpPanelLayout) getActivity().findViewById(R.id.sliding_layout);
sliding_layout.setPanelState(SlidingUpPanelLayout.PanelState.HIDDEN);
</code>```

Note: All the layout elements in bold letters(ex: container) correspond to their ids.

答:
I would love to know if you ever figured this out.

I am having the same issue, I found it leads down to the function that makes the tab bar GONE when the keyboard is opened. If I comment that line it works fine.

Here is that function:

```<code>getActivity().getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {

        Rect r = new Rect();
        getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
        int screenHeight = getActivity().getWindow().getDecorView().getRootView().getHeight();

        int keypadHeight = screenHeight - r.bottom;

        if (keypadHeight > screenHeight * 0.15) {
            //Keyboard is opened
            nav_view.setVisibility(View.GONE); // If I comment this line the resize works
        }
        else {
            // keyboard is closed
            new Handler().postDelayed(new Runnable() { @Override public void run() {
                nav_view.setVisibility(View.VISIBLE);
            }}, 20);
        }
    }
});
</code>```

Body:
I am using using slide up panel provided by https://github.com/umano/AndroidSlidingUpPanel

I have set the windowSoftInputMode as resize in activity manifest file as follows (I have only one activity)

android:windowSoftInputMode="adjustResize"

The structure for layout for slideupPanel:

<com.sothree.slidinguppanel.SlidingUpPanelLayout
    xmlns:sothree="http://schemas.android.com/apk/res-auto"
    android:id="@+id/sliding_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="bottom"
    sothree:umanoDragView="@+id/customDragViewId">

    <FrameLayout android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <LinearLayout
        android:id="@+id/customDragViewId"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">

        <include
            android:layout_width="match_parent"
            android:layout_height="55dp"
            layout="@layout/another_layout" />

        <include
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            layout="@layout/yet_another_layout"
            android:layout_weight="1" />

    </LinearLayout>

</com.sothree.slidinguppanel.SlidingUpPanelLayout>

When i have inflate an EditText into the container(@+id/container) and get it into focus, the soft keypad is shown. On this, the @+id/sliding_layout is re-sized to fit the screen. But the container height remains same as the sliding_layout when it should be re-sized to end at top of customDragViewId. The container only re-sizes when the bottom sliding panel(@+id/customDragViewId) is dragged.

What should i do so that the container is always re-sized accordingly ?

Also when i set the panel State to hidden (see the following code), the sliding_layout height is not re-sized at all when the keypad shows up. What should i do that sliding_layout is re-sized?

SlidingUpPanelLayout sliding_layout = (SlidingUpPanelLayout) getActivity().findViewById(R.id.sliding_layout);
sliding_layout.setPanelState(SlidingUpPanelLayout.PanelState.HIDDEN);

Note: All the layout elements in bold letters(ex: container) correspond to their ids.

Body:
I would love to know if you ever figured this out.

I am having the same issue, I found it leads down to the function that makes the tab bar GONE when the keyboard is opened. If I comment that line it works fine.

Here is that function:

getActivity().getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {

        Rect r = new Rect();
        getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
        int screenHeight = getActivity().getWindow().getDecorView().getRootView().getHeight();

        int keypadHeight = screenHeight - r.bottom;

        if (keypadHeight > screenHeight * 0.15) {
            //Keyboard is opened
            nav_view.setVisibility(View.GONE); // If I comment this line the resize works
        }
        else {
            // keyboard is closed
            new Handler().postDelayed(new Runnable() { @Override public void run() {
                nav_view.setVisibility(View.VISIBLE);
            }}, 20);
        }
    }
});


问:
How to get length of audio file without playing it in Flutter/Dart
I'm trying to display the length of audio files in my Flutter application.  I've used both the flutter_sound and audioplayers plugins but I'm not sure how to get the length of the audio file without playing it and getting the duration (which I want to display the length of each audio file in a list so users know how long it is before playing).  I haven't been able to find anywhere online that shows how to get the audio file length in dart except from using the duration of the playing audio file in one of those plugins. Anyone know how to get audio file length's in dart?</p>

答:
This works for me:

    // We need to play the file in order to get its duration.
    _player = await AudioCache().play(filePath);

    _player.onDurationChanged.listen((Duration duration) {
      // Now that we have the duration, stop the player.
      _player.stop();
      _durationMs = duration.inMilliseconds;
    });
```


问:
How to split a text file without delimiters
I have a homework assignment that involves File IO and 2D arrays. We were given a text file that looks like this:

```<code>10,10
@,-
oxxxxxxxxo
xoxxxxxxox
xxoxxxxoxx
xxxoxxoxxx
xxxxooxxxx
xxxxooxxxx
xxxoxxoxxx
xxoxxxxoxx
xoxxxxxxox
oxxxxxxxxo
</code>```

I was able to load in the text file properly and the first two lines are not a problem, but I am trying to separate each row into separate individual characters so I can put them into the 2D array. I cannot use regex and have spent hours trying to find an answer. Does anyone have any ideas how to do this? Thanks.

答:
```<code>using System;
using System.Linq;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string value = @"10,10
@,-
oxxxxxxxxo
xoxxxxxxox
xxoxxxxoxx
xxxoxxoxxx
xxxxooxxxx
xxxxooxxxx
xxxoxxoxxx
xxoxxxxoxx
xoxxxxxxox
oxxxxxxxxo";

            string[] allLines = value.Split(new string[1] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            string firstLine = allLines[0]; // 10,10
            string secondLine = allLines[1]; // @,-
            string[] rest = Enumerable.Take<string>(allLines, allLines.Length - 2).ToArray<string>();

            // Inconvenient : as we use jagged/multidimensional arrays here, the length must be known in advanceand must be the same in each line we read.
            char[,] valuesAs2DArray = new char[rest.Length,10];

            int i = 0;
            foreach (string s in rest.Skip(2))
            {
                for (int j = 0; j < s.Length;j++)
                {
                    valuesAs2DArray[i,j] = s[j];
                }
                i++;
            }

            Console.ReadKey();
        }
    }
}
</code>```

Body:
I have a homework assignment that involves File IO and 2D arrays. We were given a text file that looks like this:

10,10
@,-
oxxxxxxxxo
xoxxxxxxox
xxoxxxxoxx
xxxoxxoxxx
xxxxooxxxx
xxxxooxxxx
xxxoxxoxxx
xxoxxxxoxx
xoxxxxxxox
oxxxxxxxxo

I was able to load in the text file properly and the first two lines are not a problem, but I am trying to separate each row into separate individual characters so I can put them into the 2D array. I cannot use regex and have spent hours trying to find an answer. Does anyone have any ideas how to do this? Thanks.


问:
How to use linux command "cat" from a script?
Input:A.fasta

```<code>>A
sldkfjslkdcskd
</code>```

Input:B.fasta

```<code>>B
pofnvkweu
</code>```

Expected output:A_B.fasta

```<code>>A
sldkfjslkdcskd
>B
pofnvkweu
</code>```

Code:

```<code>my_model_dir_path='../my_model'
word='.fasta'

for f in os.listdir(my_model_dir_path):
    if word in f:
        subprocess.call(["cat", f"{f}"])
</code>```

Error message:

```<code>No such file or directory
</code>```

I used subprocess to call linux command cat to concatenate fasta files in a fasta format like expected output. However, I got a message like No such file or directory even though the files and the directory exist in right path.

答:
I am uncertain why you'd want to exec a new command (cat) to do this when you can use Python's built-in file operations to do it instead.

Append a text to file in Python

Body:
Input:A.fasta

>A
sldkfjslkdcskd

Input:B.fasta

>B
pofnvkweu

Expected output:A_B.fasta

>A
sldkfjslkdcskd
>B
pofnvkweu

Code:

my_model_dir_path='../my_model'
word='.fasta'

for f in os.listdir(my_model_dir_path):
    if word in f:
        subprocess.call(["cat", f"{f}"])

Error message:

No such file or directory

I used subprocess to call linux command cat to concatenate fasta files in a fasta format like expected output. However, I got a message like No such file or directory even though the files and the directory exist in right path.


问:
How to fix these Typescript errors on the window object of my Vue app?
In a component of my Vue 3 app I need to work with some custom properties on the Window, like this:

```<code>window.ZohoHCAsapSettings = { //<-- ERROR HERE
  ticketsSettings: {
    preFillFields: {
      email: {
        defaultValue: user.value?.email,
      },
    },
  },
};
</code>```

But I get a TypeScript error on ZohoHCAsapSettings:

```<code>Property 'ZohoHCAsapSettings' does not exist on type 'Window & typeof globalThis'. ts(2339)
</code>```

So I tried extending the window like so:

```<code>interface customWindow extends Window {
  ZohoHCAsapSettings?: unknown;
}
declare const window: customWindow; //<-- ERROR HERE
window.ZohoHCAsapSettings = {
  ticketsSettings: {
    preFillFields: {
      email: {
        defaultValue: user.value?.email,
      },
    },
  },
};
</code>```

This removes the error on ZohoHCAsapSettings but generates another error on declare that says:

```<code>Modifiers cannot appear here. ts(1184)
</code>```

I'm new to TypeScript so not sure what's going on here.

I am using Visual Studio Code as my IDE if that matters.

Any ideas?

答:
As @Buszmen pointed out, the global Window interface should be augmented with the new property. Type declarations are usually stored in their own .d.ts file (e.g., src/globals.d.ts for global variables).

And if you're using a project scaffolded from npm init vue, npm init vite, or Vue CLI, the key is to specify the global namespace:

// src/globals.d.ts
declare global {
  interface Window { ZohoHCAsapSettings?: unknown; }
}
```

Body:
In a component of my Vue 3 app I need to work with some custom properties on the Window, like this:

window.ZohoHCAsapSettings = { //<-- ERROR HERE
  ticketsSettings: {
    preFillFields: {
      email: {
        defaultValue: user.value?.email,
      },
    },
  },
};

But I get a TypeScript error on ZohoHCAsapSettings:

Property 'ZohoHCAsapSettings' does not exist on type 'Window & typeof globalThis'. ts(2339)

So I tried extending the window like so:

interface customWindow extends Window {
  ZohoHCAsapSettings?: unknown;
}
declare const window: customWindow; //<-- ERROR HERE
window.ZohoHCAsapSettings = {
  ticketsSettings: {
    preFillFields: {
      email: {
        defaultValue: user.value?.email,
      },
    },
  },
};

This removes the error on ZohoHCAsapSettings but generates another error on declare that says:

Modifiers cannot appear here. ts(1184)

I'm new to TypeScript so not sure what's going on here.

I am using Visual Studio Code as my IDE if that matters.

Any ideas?


问:
display html select (from PHP) via jquery?
So I have a PHP backend that pulls some data from SQL,  let's just say its a list of user ID numbers.

I want to be able to display that list in an html select, via jquery, after a button click.

In an attempt to partially answer my own question, I assume that I could either have a jquery function perform an ajax request, grab the data from PHP/SQL, and then somehow spit out the select with jquery.  Or, I could perhaps do the SQL query via PHP right there on the page, and somehow have the jquery function grab the output from that and put it into a select.

How would you do it?

a fill-in-the-blanks code example follows:

idea 1:

```<code>function button_click() {

               $.ajax({
                url: "PHP_backend.php",  // this does the sql query and returns the results
                type: 'POST',
                data: 'returnquery',

                    success: function(result) {
                    //?????  put the result array or whatever into a submit, perhaps with a foreach or something similar..??

                    }
                }); // end ajax

            }
</code>```

Or idea 2:

```<code>$result = mysql_query("SELECT userIDnumbers FROM users",$db);
while ($row = mysql_fetch_array($result)){
/// throw these results into an array or similar, $userIDarray[]
/// maybe I could have this PHP create hidden html fields for each row, and insert its value, and then get that via jquery
}

function button_click() {
///  create the html select, displaying the values from the sql query
/// get values from hidden html fields?
}
</code>```

答: if you are sure that the button will be clicked always or very most of time, idea2 is better becouse overhead of send/receive Ajax (trafic) and its delay (time) will be removed  </p>

Body:
So I have a PHP backend that pulls some data from SQL,  let's just say its a list of user ID numbers.

I want to be able to display that list in an html select, via jquery, after a button click.

In an attempt to partially answer my own question, I assume that I could either have a jquery function perform an ajax request, grab the data from PHP/SQL, and then somehow spit out the select with jquery.  Or, I could perhaps do the SQL query via PHP right there on the page, and somehow have the jquery function grab the output from that and put it into a select.

How would you do it?

a fill-in-the-blanks code example follows:

idea 1:

function button_click() {

               $.ajax({
                url: "PHP_backend.php",  // this does the sql query and returns the results
                type: 'POST',
                data: 'returnquery',

                    success: function(result) {
                    //?????  put the result array or whatever into a submit, perhaps with a foreach or something similar..??

                    }
                }); // end ajax

            }

Or idea 2:

$result = mysql_query("SELECT userIDnumbers FROM users",$db);
while ($row = mysql_fetch_array($result)){
/// throw these results into an array or similar, $userIDarray[]
/// maybe I could have this PHP create hidden html fields for each row, and insert its value, and then get that via jquery
}

function button_click() {
///  create the html select, displaying the values from the sql query
/// get values from hidden html fields?
}


问:
Motion layout prevents update on recyclerview
I have started using motion layout for some top bar scrolling, and looks like there is an issue that prevents recycler view from showing updated data. Currently I am using 2.0.0-alpha3 of ConstraintLayout. In the view I have toolbar and 2 tabs that act as filter, lets say filterX and filterY those pass some rx stuff that basically just filters list of items based on the type this is not important because data is filtered properly, thread is correct, data is passed to adapter every time, but when I do scroll my motion layout to top or bottom, from time to time the changes are not reflected in recycler view, they reload after I scroll it a little bit or even touch, its not happening in case of standard ConstraitLayout. Have anyone experienced this and know any solution?

Edit: Layout with motion layout:

```<code><androidx.constraintlayout.motion.widget.MotionLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layoutDescription="@xml/scene_month">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navigationIcon="@drawable/ic_back"/>

    <TextView
        android:id="@+id/title"
        style="@style/ActivityTitle"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/toolbar" />

    <com.example.FilterView
        android:id='@+id/filter_view'
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/white"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/title"/>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:clipToPadding="false"
        android:paddingBottom="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/filter_view" />

</androidx.constraintlayout.motion.widget.MotionLayout>
</code>```

And motion scene

```<code><?xml version="1.0" encoding="utf-8"?>
<MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <Transition
        app:constraintSetEnd="@id/end"
        app:constraintSetStart="@id/start">
        <OnSwipe
            app:dragDirection="dragUp"
            app:touchAnchorId="@id/recycler"
            app:touchAnchorSide="top" />
    </Transition>

    <ConstraintSet android:id="@+id/start">
        <Constraint android:id="@id/title"
            android:text="@string/title"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:gravity="center_vertical"
            android:textSize="28sp"
            android:textColor="@color/dark_gray"
            android:fontFamily="@font/rubik_medium"
            android:layout_marginStart="16dp"
            android:layout_marginEnd="16dp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/toolbar">
            <CustomAttribute
                app:attributeName="textSize"
                app:customFloatValue="28"/>
        </Constraint>
    </ConstraintSet>

    <ConstraintSet android:id="@+id/end">
        <Constraint android:id="@id/title"
            android:text="@string/title"
            android:layout_width="match_parent"
            android:layout_height="?actionBarSize"
            android:gravity="center_vertical"
            android:minHeight="?actionBarSize"
            android:textSize="28sp"
            android:textColor="@color/dark_gray"
            android:fontFamily="@font/rubik_regular"
            android:layout_marginStart="72dp"
            android:layout_marginEnd="16dp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">
            <CustomAttribute
                app:attributeName="textSize"
                app:customFloatValue="20"/>
        </Constraint>
    </ConstraintSet>

</MotionScene>
</code>```

答:
None of these workarounds worked for me. I gave up on fixing these and I was fixing other UI bugs I had. I have several views sliding up/down and hiding/showing.

I was using TransitionManager.beginDelayedTransition(...) in my code and it wasn't inside a Runnable. After wrapping it in view.post{} like this the problem disappeared:

```<code>view.post{
    TransitionManager.beginDelayedTransition()
}
</code>```

This may seem irrelevant but I suggest checking your code to see if the problem is somewhere else. Like everyone else I thought this is caused by MotionLayout because when I swapped it with ConstraintLayout it worked fine.

Body:
I have started using motion layout for some top bar scrolling, and looks like there is an issue that prevents recycler view from showing updated data. Currently I am using 2.0.0-alpha3 of ConstraintLayout. In the view I have toolbar and 2 tabs that act as filter, lets say filterX and filterY those pass some rx stuff that basically just filters list of items based on the type this is not important because data is filtered properly, thread is correct, data is passed to adapter every time, but when I do scroll my motion layout to top or bottom, from time to time the changes are not reflected in recycler view, they reload after I scroll it a little bit or even touch, its not happening in case of standard ConstraitLayout. Have anyone experienced this and know any solution?

Edit: Layout with motion layout:

<androidx.constraintlayout.motion.widget.MotionLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layoutDescription="@xml/scene_month">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navigationIcon="@drawable/ic_back"/>

    <TextView
        android:id="@+id/title"
        style="@style/ActivityTitle"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/toolbar" />

    <com.example.FilterView
        android:id='@+id/filter_view'
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/white"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/title"/>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:clipToPadding="false"
        android:paddingBottom="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/filter_view" />

</androidx.constraintlayout.motion.widget.MotionLayout>

And motion scene

<?xml version="1.0" encoding="utf-8"?>
<MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <Transition
        app:constraintSetEnd="@id/end"
        app:constraintSetStart="@id/start">
        <OnSwipe
            app:dragDirection="dragUp"
            app:touchAnchorId="@id/recycler"
            app:touchAnchorSide="top" />
    </Transition>

    <ConstraintSet android:id="@+id/start">
        <Constraint android:id="@id/title"
            android:text="@string/title"
            android:layout_width="match_parent"
            android:layout_height="48dp"
            android:gravity="center_vertical"
            android:textSize="28sp"
            android:textColor="@color/dark_gray"
            android:fontFamily="@font/rubik_medium"
            android:layout_marginStart="16dp"
            android:layout_marginEnd="16dp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/toolbar">
            <CustomAttribute
                app:attributeName="textSize"
                app:customFloatValue="28"/>
        </Constraint>
    </ConstraintSet>

    <ConstraintSet android:id="@+id/end">
        <Constraint android:id="@id/title"
            android:text="@string/title"
            android:layout_width="match_parent"
            android:layout_height="?actionBarSize"
            android:gravity="center_vertical"
            android:minHeight="?actionBarSize"
            android:textSize="28sp"
            android:textColor="@color/dark_gray"
            android:fontFamily="@font/rubik_regular"
            android:layout_marginStart="72dp"
            android:layout_marginEnd="16dp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">
            <CustomAttribute
                app:attributeName="textSize"
                app:customFloatValue="20"/>
        </Constraint>
    </ConstraintSet>

</MotionScene>

Body:
None of these workarounds worked for me. I gave up on fixing these and I was fixing other UI bugs I had. I have several views sliding up/down and hiding/showing.

I was using TransitionManager.beginDelayedTransition(...) in my code and it wasn't inside a Runnable. After wrapping it in view.post{} like this the problem disappeared:

view.post{
    TransitionManager.beginDelayedTransition()
}

This may seem irrelevant but I suggest checking your code to see if the problem is somewhere else. Like everyone else I thought this is caused by MotionLayout because when I swapped it with ConstraintLayout it worked fine.


问:
discord.js instagram account scrape
i am trying to fix this code to show stats about a instagram account (followers, user, following, posts, etc) but the code is broken, and im not sure what to do.

the code:

```<code>const axios = require('axios')
const { MessageEmbed } = require('discord.js');
const instagram = require("instagram-api.js");
module.exports = {
    name: "ig (in development)",
    category: "search",
    run: async (client, message, args) => {
        if (!args[0]) {
            return message.channel.send(`Please Enter a Channel Name`)
        }
        let url, response, account, details;
        try {
            url = `https://instagram.com/${args[0]}`;
            response = await axios.get(url)
            account = response.data
            details = account.graphql.user
        } catch (error) {
            return message.channel.send(`Not An Account`)
        }

        const embed = new MessageEmbed()
            .setTitle(`${details.is_verified ? `${details.username} <a:verified:727820439497211994>` : ` ${details.username}`} ${details.is_private ? '' : ''} `)
            .setDescription(details.biography)
            .setThumbnail(details.profile_pic_url)
            .addFields(
                {
                    name: "Total Posts:",
                    value: details.edge_owner_to_timeline_media.count.toLocaleString(),
                    inline: true
                },
                {
                    name: "Followers:",
                    value: details.edge_followed_by.count.toLocaleString(),
                    inline: true
                },
                {
                    name: "Following:",
                    value: details.edge_follow.count.toLocaleString(),
                    inline: true
                }
            )
        await message.channel.send(embed)

    }
}

module.exports.help = {
name: "insta",
description: "This Command Allows You To Search For instagram Accounts!",
usage: "b!insta <instagram user>",
accessableby: "Everyone",
aliases: []
};
</code>```

the error:

```<code>(node:7872) UnhandledPromiseRejectionWarning: /home/runner/DraconianJSBot-1/node_modules/@sapphire/fetch/dist/index.js:76
    return __privateGet(this, _json) ?? __privateSet(this, _json, JSON.parse(this.body));
                                      ^

SyntaxError: Unexpected token '?'
    at wrapSafe (internal/modules/cjs/loader.js:915:16)
    at Module._compile (internal/modules/cjs/loader.js:963:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Module.require (internal/modules/cjs/loader.js:887:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/home/runner/DraconianJSBot-1/node_modules/instagram-api.js/dist/index.js:4:17)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
(node:7872) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:7872) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
</code>```

im not quite sure what to do so any help would be amazing! you dont have to though ofc, im just new to this stuff so i need a little bit of assistance

答:
Seems like you're using a outdated version of Node.js, where the Nullish coalescing operator (??) isn't available yet.

In order to be able to use it, you have to upgrade to at least version 14.* as you can see from the official documentation.

Downloads

16.13.2 - Long Term Support (LTS) - Recommended for most users

17.4.0 - Latest features

Title: discord.js instagram account scrape

Body:
i am trying to fix this code to show stats about a instagram account (followers, user, following, posts, etc) but the code is broken, and im not sure what to do.

the code:

const axios = require('axios')
const { MessageEmbed } = require('discord.js');
const instagram = require("instagram-api.js");
module.exports = {
    name: "ig (in development)",
    category: "search",
    run: async (client, message, args) => {
        if (!args[0]) {
            return message.channel.send(`Please Enter a Channel Name`)
        }
        let url, response, account, details;
        try {
            url = `https://instagram.com/${args[0]}`;
            response = await axios.get(url)
            account = response.data
            details = account.graphql.user
        } catch (error) {
            return message.channel.send(`Not An Account`)
        }

        const embed = new MessageEmbed()
            .setTitle(`${details.is_verified ? `${details.username} ` : ` ${details.username}`} ${details.is_private ? '' : ''} `)
            .setDescription(details.biography)
            .setThumbnail(details.profile_pic_url)
            .addFields(
                {
                    name: "Total Posts:",
                    value: details.edge_owner_to_timeline_media.count.toLocaleString(),
                    inline: true
                },
                {
                    name: "Followers:",
                    value: details.edge_followed_by.count.toLocaleString(),
                    inline: true
                },
                {
                    name: "Following:",
                    value: details.edge_follow.count.toLocaleString(),
                    inline: true
                }
            )
        await message.channel.send(embed)

    }
}

module.exports.help = {
name: "insta",
description: "This Command Allows You To Search For instagram Accounts!",
usage: "b!insta <instagram user>",
accessableby: "Everyone",
aliases: []
};

the error:

(node:7872) UnhandledPromiseRejectionWarning: /home/runner/DraconianJSBot-1/node_modules/@sapphire/fetch/dist/index.js:76
    return __privateGet(this, _json) ?? __privateSet(this, _json, JSON.parse(this.body));
                                      ^

SyntaxError: Unexpected token '?'
    at wrapSafe (internal/modules/cjs/loader.js:915:16)
    at Module._compile (internal/modules/cjs/loader.js:963:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Module.require (internal/modules/cjs/loader.js:887:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/home/runner/DraconianJSBot-1/node_modules/instagram-api.js/dist/index.js:4:17)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
(node:7872) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:7872) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

im not quite sure what to do so any help would be amazing! you dont have to though ofc, im just new to this stuff so i need a little bit of assistance


问:
How to change navbar background on Scrollling in bootstrap 5
I like my navbar to change background color when scrolling. am using bootstrap 5. please I need help</p>
```<code>$(document).ready(function(){
  $(window).scroll(function(){
   var scroll = $(window).scrollTop();
    if (scroll > 100) {
     $(".navbar").css("background" , "blue");
     }else{
       $(".navbar").css("background" , "#000");
     }
    });
   });
</code>```

答:
You need to remove class bg-dark if you want to change background color.

$(document).ready(function(){
  $(window).scroll(function(){
    var scroll = $(window).scrollTop();
    if (scroll > 100) {
      $(".navbar").removeClass('bg-dark').css("background" , "blue");
    }else{
      $(".navbar").css("background" , "").addClass('bg-dark');
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap core CSS -->
<link href="https://getbootstrap.com/docs/5.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <style>
      .bd-placeholder-img {
        font-size: 1.125rem;
        text-anchor: middle;
        -webkit-user-select: none;
        -moz-user-select: none;
        user-select: none;
      }

      @media (min-width: 768px) {
        .bd-placeholder-img-lg {
          font-size: 3.5rem;
        }
      }
    </style>

    <!-- Custom styles for this template -->
    <link href="https://getbootstrap.com/docs/5.0/examples/navbar-fixed/navbar-top-fixed.css" rel="stylesheet">
  </head>
  <body>

<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
  <div class="container-fluid">
    Fixed navbar
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarCollapse">
      <ul class="navbar-nav me-auto mb-2 mb-md-0">
        <li class="nav-item">
          Home
        </li>
        <li class="nav-item">
          Link
        </li>
        <li class="nav-item">
          Disabled
        </li>
      </ul>
      <form class="d-flex">
        <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
        <button class="btn btn-outline-success" type="submit">Search</button>
      </form>
    </div>
  </div>
</nav>

<main class="container">
  <div class="bg-light p-5 rounded">
    <h1>Navbar example</h1>
    <p class="lead">This example is a quick exercise to illustrate how fixed to top navbar works. As you scroll, it will remain fixed to the top of your browser’s viewport.</p>
    View navbar docs »
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
  </div>
</main>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <script src="https://getbootstrap.com/docs/5.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

  </body>
</html></code>```

Body:
I like my navbar to change background color when scrolling. am using bootstrap 5. please I need help

$(document).ready(function(){
  $(window).scroll(function(){
   var scroll = $(window).scrollTop();
    if (scroll > 100) {
     $(".navbar").css("background" , "blue");
     }else{
       $(".navbar").css("background" , "#000");
     }
    });
   });

Body:
You need to remove class bg-dark if you want to change background color.

$(document).ready(function(){
  $(window).scroll(function(){
    var scroll = $(window).scrollTop();
    if (scroll > 100) {
      $(".navbar").removeClass('bg-dark').css("background" , "blue");
    }else{
      $(".navbar").css("background" , "").addClass('bg-dark');
    }
  });
});

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap core CSS -->
<link href="https://getbootstrap.com/docs/5.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <style>
      .bd-placeholder-img {
        font-size: 1.125rem;
        text-anchor: middle;
        -webkit-user-select: none;
        -moz-user-select: none;
        user-select: none;
      }

      @media (min-width: 768px) {
        .bd-placeholder-img-lg {
          font-size: 3.5rem;
        }
      }
    </style>

    <!-- Custom styles for this template -->
    <link href="https://getbootstrap.com/docs/5.0/examples/navbar-fixed/navbar-top-fixed.css" rel="stylesheet">
  </head>
  <body>

<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">Fixed navbar</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarCollapse">
      <ul class="navbar-nav me-auto mb-2 mb-md-0">
        <li class="nav-item">
          <a class="nav-link active" aria-current="page" href="#">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Link</a>
        </li>
        <li class="nav-item">
          <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
        </li>
      </ul>
      <form class="d-flex">
        <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
        <button class="btn btn-outline-success" type="submit">Search</button>
      </form>
    </div>
  </div>
</nav>

<main class="container">
  <div class="bg-light p-5 rounded">
    <h1>Navbar example</h1>
    <p class="lead">This example is a quick exercise to illustrate how fixed to top navbar works. As you scroll, it will remain fixed to the top of your browser’s viewport.</p>
    <a class="btn btn-lg btn-primary" href="/docs/5.0/components/navbar/" role="button">View navbar docs &raquo;</a>
    <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
  </div>
</main>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <script src="https://getbootstrap.com/docs/5.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

  </body>
</html>


问:
ICE candidates not generating on Android 11 Chrome in some devices
While trying out WebRTC, I found out that it is creating issues in some Android devices having Android 11 (mostly Samsung, Vivo) in Chrome. However, it is working fine in Firefox on the same device. I tested on Samsung Galaxy A03s (SM-A037F).

I tried this - https://webrtc.github.io/samples/src/content/peerconnection/trickle-ice/
In Chrome, candidates are not gathered but in Firefox, candidates are gathering.

I found a similar bug in the Chromium bug tracker - https://bugs.chromium.org/p/chromium/issues/detail?id=1115498
Still issue doesn't seem to be fixed.

How can we make it work in the Chrome browser? Please help.

答:
Same problem. If you try to set iceCandidatePoolSize = 10 in the configuration for RTCPeerConnection, then onicecandidate fires once with an empty candidate, iceConnectionState changes to the connected state.

Then I watch transceivers
pc.getTransceivers()[0].sender.transport.iceTransport

gatheringState: "complete"
state: "connected"

pc.getTransceivers()[0].sender.transport.iceTransport.getSelectedCandidatePair()
Success! There is a selected pair!

But pc.connectionState still has a connecting state and hangs in it endlessly...

Tried on wifi and gsm connections... I don't understand anything!

Checked on other devices in the same network (wifi):

Android 11 - Samsung Galaxy M12 - Success

Android 11 - Samsung Galaxy TAB A (2019) - Success

Android 11 - Samsung Galaxy A22 (my) - FAIL

Workarround for me:

```<code>let pc = new RTCPeerConnection({iceCandidatePoolSize: 1}) //any > 0
pc.oniceconnectionstatechange = function(){

   if(pc.iceConnectionState === "connected") {
      for (let tr of pc.getTransceivers()) {

          let selected = tr.sender.transport.iceTransport.getSelectedCandidatePair();
          if (selected) {
              //send selected.local to you server...
          }
      }
    }
}
</code>```

Bug chromium:

https://bugs.chromium.org/p/chromium/issues/detail?id=1240237

Body:
Same problem. If you try to set iceCandidatePoolSize = 10 in the configuration for RTCPeerConnection, then onicecandidate fires once with an empty candidate, iceConnectionState changes to the connected state.

Then I watch transceivers
pc.getTransceivers()[0].sender.transport.iceTransport

gatheringState: "complete"
state: "connected"

pc.getTransceivers()[0].sender.transport.iceTransport.getSelectedCandidatePair()
Success! There is a selected pair!

But pc.connectionState still has a connecting state and hangs in it endlessly...

Tried on wifi and gsm connections... I don't understand anything!

Checked on other devices in the same network (wifi):

Android 11 - Samsung Galaxy M12 - Success

Android 11 - Samsung Galaxy TAB A (2019) - Success

Android 11 - Samsung Galaxy A22 (my) - FAIL

Workarround for me:

let pc = new RTCPeerConnection({iceCandidatePoolSize: 1}) //any > 0
pc.oniceconnectionstatechange = function(){

   if(pc.iceConnectionState === "connected") {
      for (let tr of pc.getTransceivers()) {

          let selected = tr.sender.transport.iceTransport.getSelectedCandidatePair();
          if (selected) {
              //send selected.local to you server...
          }
      }
    }
}

Bug chromium:

https://bugs.chromium.org/p/chromium/issues/detail?id=1240237


问:
How to color text in Markdown/Gitlab
I'm trying color text in markdown. In preview all looks good, but when i push it to repository the text is not colored. How can I color text?

```<code>In his beard lived three <span style="color:red">cardinals</span>.
</code>```

答:
Unfortunately most of the HTML hacks for doing color in Markdown will be nullified by GitLab's presentation layer.

GitLab's inline diffs will work for Markdown displayed by GitLab in Issues, Wikis, and by the Markdown Preview.

It supports [- red text -] and [+ green text +] but no others.

Title: How to color text in Markdown/Gitlab

Body:
I'm trying color text in markdown. In preview all looks good, but when i push it to repository the text is not colored. How can I color text?

In his beard lived three cardinals.


问:
Any way to spoof original webrtc ip address?
Is there any way to spoof original WebRTC ip address on regular browsers like chrome, firefox and opera?

For example: I using some proxy and would like to spoof my WebRTC ip address same like proxy ip address. I don't need to disable it.

答:
Running a TURN server is the best way. A TURN server acts as a proxy, you can can send and receive all your traffic through a remote host first.

You can then set iceTransportPolicy to relay in your RTCConfiguration. The PeerConnection will then only connect through that TURN server.


问:
PHP - Filter error messages
I have found a PHP system that have a interesting feature.

If there is a error on the code, the default error message is not showed, the programmer have created a way to filter those messages and create a log to show those error messages as simple alerts on the administrator view.

How do I do that?

Thanks in advance

MORE DETAILS

Server: Apache

The system is from a company in Brazil and do not have access to it, it was just presented to me

答:
PHP allows you to configure error reporting via the following directives in the php.ini file:

display_errors - "...determines whether errors should be printed to the screen as part of the output or if they should be hidden from the user."

error_reporting - "Set the error reporting level."

log_errors - "Tells whether script error messages should be logged to the server's error log" or a custom log file.

Note: If you change the php.ini file, you need to restart Apache for the changes to become effective.

You can also use set_error_handler to create a custom error-handling function.

Title: PHP - Filter error messages


问:
The point within the range of rectangle
In easy English can someone please explain to me this line of code.</p>
```<code>public bool IsAt(Point2D pt)
    {
        return (pt.X > Width && pt.X < Width + X && pt.Y > Height && pt.Y < Height + Y);
    }
</code>```

答: Return true if the coordinates pt.X, pt.Y are outside a rectangle with width: WIDTH and height: HEIGHT with an origin at coordinates X, Y.</p>

Title: The point within the range of rectangle

Body:
In easy English can someone please explain to me this line of code.

public bool IsAt(Point2D pt)
    {
        return (pt.X > Width && pt.X < Width + X && pt.Y > Height && pt.Y < Height + Y);
    }


问:
How to mass remove files that contain special characters in file name
Google Drive went a little crazy and create multiple iterations of files by appending multiples of  "(1)", "(1) (1)" to the file names. So far I've been able to get a decent list of them with their path by using:

tree -f -ifpugDs $PWD | grep -e '(1) (1)' | cut -d "]" -f 2 > output.txt

Now I'm having trouble on how to delete them with the rm command. I Don't mind deleting a few of them by hand that the filter didn't pick up ( like "(2) (1)" ), but there are around 45K of them that the filter matched with.

答:
This will delete every file whose name ends in (1), recursively:

```<code>find . -name '*(1)' -exec rm {} +
</code>```

-name '*(1) (1)' to only delete files ending with a double 1.

-name '*([0-9])' will match any single digit.

find . -mindepth 1 -maxdepth 1 -name '*(1)' -exec rm {} + for no recursion.

I would do find . -name '*(1)' -exec echo rm {} \; to print a neat list of the rm commands to be executed. Review it, then remove echo to run for real.

Changing \; back to + is optional, + is more efficient.

Body:
This will delete every file whose name ends in (1), recursively:

find . -name '*(1)' -exec rm {} +

-name '*(1) (1)' to only delete files ending with a double 1.

-name '*([0-9])' will match any single digit.

find . -mindepth 1 -maxdepth 1 -name '*(1)' -exec rm {} + for no recursion.

I would do find . -name '*(1)' -exec echo rm {} \; to print a neat list of the rm commands to be executed. Review it, then remove echo to run for real.

Changing \; back to + is optional, + is more efficient.


问:
How can I put different legends to subplots in plotly?
I am still designing what kind of plot with subplots I want to do but when we see the example in the documentation Multiple Subplots with Titles we have

```<code>from plotly.subplots import make_subplots
import plotly.graph_objects as go

fig = make_subplots(
    rows=2, cols=2,
    subplot_titles=("Plot 1", "Plot 2", "Plot 3", "Plot 4"))

fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]),
              row=1, col=1)

fig.add_trace(go.Scatter(x=[20, 30, 40], y=[50, 60, 70]),
              row=1, col=2)

fig.add_trace(go.Scatter(x=[300, 400, 500], y=[600, 700, 800]),
              row=2, col=1)

fig.add_trace(go.Scatter(x=[4000, 5000, 6000], y=[7000, 8000, 9000]),
              row=2, col=2)

fig.update_layout(height=500, width=700,
                  title_text="Multiple Subplots with Titles")

fig.show()
</code>```

which gives

which is fine but notice that there is only one place for the legends.(trace 0, trace 1.etc)

In my design the upper left plot has one legend and the other three share some other legend . Is there a way to individualize or customize the legends of subplots?

答:
This topic was discussed on the plotly forum here, and it seems that multiple legends aren't possible in plotly. However, in the same thread @Jaydeep Mistry gives a partial workaround.

He uses legend groups to group traces together, then uses the parameter legend_tracegroupgap in the update_layout method to give the legend the appearance of being more than one legend. However, this spacing only works vertically so your multiple legends will still be vertically spaced apart on the right side of the plot. For example:

```<code>from plotly.subplots import make_subplots
import plotly.graph_objects as go

fig = make_subplots(
    rows=2, cols=2,
    subplot_titles=("Plot 1", "Plot 2", "Plot 3", "Plot 4"))

fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6], legendgroup = '1'),
              row=1, col=1)

fig.add_trace(go.Scatter(x=[20, 30, 40], y=[50, 60, 70], legendgroup = '2'),
              row=1, col=2)

fig.add_trace(go.Scatter(x=[300, 400, 500], y=[600, 700, 800], legendgroup = '2'),
              row=2, col=1)

fig.add_trace(go.Scatter(x=[4000, 5000, 6000], y=[7000, 8000, 9000], legendgroup = '2'),
              row=2, col=2)

fig.update_layout(height=500, width=700,
                  title_text="Multiple Subplots with Titles",
                  legend_tracegroupgap=180)

fig.show()
</code>```

Alternatively, you could add another legend by using an annotation to draw a box with the accompanying text, but it wouldn't have any functionality.

Body:
I am still designing what kind of plot with subplots I want to do but when we see the example in the documentation Multiple Subplots with Titles we have

from plotly.subplots import make_subplots
import plotly.graph_objects as go

fig = make_subplots(
    rows=2, cols=2,
    subplot_titles=("Plot 1", "Plot 2", "Plot 3", "Plot 4"))

fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]),
              row=1, col=1)

fig.add_trace(go.Scatter(x=[20, 30, 40], y=[50, 60, 70]),
              row=1, col=2)

fig.add_trace(go.Scatter(x=[300, 400, 500], y=[600, 700, 800]),
              row=2, col=1)

fig.add_trace(go.Scatter(x=[4000, 5000, 6000], y=[7000, 8000, 9000]),
              row=2, col=2)

fig.update_layout(height=500, width=700,
                  title_text="Multiple Subplots with Titles")

fig.show()

which gives

which is fine but notice that there is only one place for the legends.(trace 0, trace 1.etc)

In my design the upper left plot has one legend and the other three share some other legend . Is there a way to individualize or customize the legends of subplots?

Body:
This topic was discussed on the plotly forum here, and it seems that multiple legends aren't possible in plotly. However, in the same thread @Jaydeep Mistry gives a partial workaround.

He uses legend groups to group traces together, then uses the parameter legend_tracegroupgap in the update_layout method to give the legend the appearance of being more than one legend. However, this spacing only works vertically so your multiple legends will still be vertically spaced apart on the right side of the plot. For example:

from plotly.subplots import make_subplots
import plotly.graph_objects as go

fig = make_subplots(
    rows=2, cols=2,
    subplot_titles=("Plot 1", "Plot 2", "Plot 3", "Plot 4"))

fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6], legendgroup = '1'),
              row=1, col=1)

fig.add_trace(go.Scatter(x=[20, 30, 40], y=[50, 60, 70], legendgroup = '2'),
              row=1, col=2)

fig.add_trace(go.Scatter(x=[300, 400, 500], y=[600, 700, 800], legendgroup = '2'),
              row=2, col=1)

fig.add_trace(go.Scatter(x=[4000, 5000, 6000], y=[7000, 8000, 9000], legendgroup = '2'),
              row=2, col=2)

fig.update_layout(height=500, width=700,
                  title_text="Multiple Subplots with Titles",
                  legend_tracegroupgap=180)

fig.show()

Alternatively, you could add another legend by using an annotation to draw a box with the accompanying text, but it wouldn't have any functionality.


问:
How to handle labels in a scripting language I'm writing?
So I've been stewing over this for a long time, thinking about it. Here's a code example first, and then I'll explain it.

```<code>:main
    dostuff
    otherlabel

:otherlabel
    dostuff
</code>```

Alright so in this example, main is where the code starts, and it 'calls' the label 'otherlabel'. This is really just a shortcut for a jump command that changes execution to a different location in memory. My problem though is, how do I handle these labels so that they don't have to be declared before they are called?

At the moment, I'm doing a single step compilation reading straight from the source and outputting the bytecode. I am simply handling labels and adding them to a dictionary when I find them. And then I replace 'otherlabel' with a jump command to the correct location in code. But in this case that code wouldn't compile.

I've thought of a few ways to do this:

First is handling labels before anything else but this requires me to do everything in two steps and I have to deal with the same code twice, this slows down the process and just seems like a mess.

Second is queueing up the label calls until AFTER I've gone through the entire file and compiled everything else and then dealing with them, this seems much cleaner.

I'm writing this in C so I'd rather not implement complex data structures, I'm looking for the most straight forward way to handle this.

答:
Use multiple passes. One pass isn't going to suffice for a scripting language, especially when you are getting to the more complex structures.

In a first pass, before compiling, construct your dictionary of labels.
In a later pass, when the compiling happens, just use that dictionary.

Body:
So I've been stewing over this for a long time, thinking about it. Here's a code example first, and then I'll explain it.

:main
    dostuff
    otherlabel

:otherlabel
    dostuff

Alright so in this example, main is where the code starts, and it 'calls' the label 'otherlabel'. This is really just a shortcut for a jump command that changes execution to a different location in memory. My problem though is, how do I handle these labels so that they don't have to be declared before they are called?

At the moment, I'm doing a single step compilation reading straight from the source and outputting the bytecode. I am simply handling labels and adding them to a dictionary when I find them. And then I replace 'otherlabel' with a jump command to the correct location in code. But in this case that code wouldn't compile.

I've thought of a few ways to do this:

First is handling labels before anything else but this requires me to do everything in two steps and I have to deal with the same code twice, this slows down the process and just seems like a mess.

Second is queueing up the label calls until AFTER I've gone through the entire file and compiled everything else and then dealing with them, this seems much cleaner.

I'm writing this in C so I'd rather not implement complex data structures, I'm looking for the most straight forward way to handle this.


问:
No such file or directory: 'geckodriver' for a simple Selenium application in Python
I'm running a simple example of selenium on Linux:

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("something")
</code>```

and get an error:

```<code>FileNotFoundError: [Errno 2] No such file or directory: 'geckodriver'
</code>```

How to fix it?

```<code>$ python
Python 3.5.2 (default, Jun 28 2016, 08:46:01)
[GCC 6.1.1 20160602] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import selenium
>>> from selenium.webdriver.common.keys import Keys
>>>
</code>```

答: There is a python package that autoinstalls it crossplattform, no need for users to manually install it: https://pypi.org/project/geckodriver-autoinstaller/</p>

Body:
I'm running a simple example of selenium on Linux:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("something")

and get an error:

FileNotFoundError: [Errno 2] No such file or directory: 'geckodriver'

How to fix it?

$ python
Python 3.5.2 (default, Jun 28 2016, 08:46:01)
[GCC 6.1.1 20160602] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import selenium
>>> from selenium.webdriver.common.keys import Keys
>>>


答:
os.listdir returns a path relative to the given directory.
So, you are try to cat a file at ./A.fasta instead of ../my_model/A.fasta.

Try this:

for f in os.listdir(my_model_dir_path):
    if word in f:
        subprocess.call(["cat", f"{my_model_dir_path}/{f}"])
```
<p>If you are using python3, pathlib is useful.</p>
<pre class="lang-py prettyprint-override"><code>from pathlib import Path

for f in Path(my_model_dir_path).glob("*.fasta"):
    subprocess.call(["cat", f"{f}"])
</code>```

Title: How to use linux command "cat" from a script?

Body:
os.listdir returns a path relative to the given directory.
So, you are try to cat a file at ./A.fasta instead of ../my_model/A.fasta.

Try this:

for f in os.listdir(my_model_dir_path):
    if word in f:
        subprocess.call(["cat", f"{my_model_dir_path}/{f}"])

If you are using python3, pathlib is useful.

from pathlib import Path

for f in Path(my_model_dir_path).glob("*.fasta"):
    subprocess.call(["cat", f"{f}"])


问:
checking if list contains same element in straight row
so,I have a list [5. 5. 5. 5. 0. 0.] I want to check if it contains same elements in straight row (atleast 4 )

I came up with this

```<code>for i in list:
    w = []
    for x in range(len(i)-4):
        if (i[x] == i[x+1] == i[x+2] == i[x+3] != 0) :
            print(i[x])
            break
</code>```

I gives me desired output,

but , what would the efficient way to achieving the same result ,without much looping ?

答:
Try this:

lst = [3, 5, 5, 5, 5, 0, 0]

for i in range(4, len(lst)):
    if len(set(lst[i-4:i]))==1:
        print(lst[i-4])
```

Body:
so,I have a list [5. 5. 5. 5. 0. 0.] I want to check if it contains same elements in straight row (atleast 4 )

I came up with this

for i in list:
    w = []
    for x in range(len(i)-4):
        if (i[x] == i[x+1] == i[x+2] == i[x+3] != 0) :
            print(i[x])
            break

I gives me desired output,

but , what would the efficient way to achieving the same result ,without much looping ?