问:
Handlebars not loading local css file
I'm using handlebars version 4.4.3 in express js application for rendering html. I'm trying to load bootstrap css in style tag. While using cdn link it's working fine. But I want to load from local path. If I'm using local path its not loading. I don't know why it's not working. I tried so many ways to load local css file. But my bad luck nothing helped. Anyone please suggest me how to use local css file in handlebars. Below I mentioned my tried codes everything.

```<code><link rel="stylesheet" href="/css/bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="./css/bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="../css/bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="/assets/css/bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="./assets/css/bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css">
</code>```

These much things i tried in my registration_print.html file. And also in my express.js file i mentioned static path.

```<code>app.use(express.static(__dirname + '/../assets/templates'));
app.use("/assets", express.static(path.join(__dirname, "/../assets")));
</code>```

Below is my folder structure. Please anyone help me to solve this issue.

答:
Hey there here is how i did solve this:

First of all i would recommend you, try using express-hanldebars its an module which is special build for express and handlebars interactions.

Basicly you need to use app.use on the hole folder

app.js

```<code>var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var hbs = require('express-handlebars');
var handlebars = require('./helpers/handlebars.js')(hbs);

var routes = require('./routes/index');

var app = express();

// view engine setup
// Settings for Handlebars moved to ./helpers/handlebars.js
app.engine('hbs', handlebars.engine);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

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

app.use('/', routes);
</code>```

And here is how i used them in the template.

layout.hbs

```<code><!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ title }}</title>
    <link rel="stylesheet" href="/stylesheets/style.css">
    <link rel="stylesheet" href="/stylesheets/navigation.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">
<!-- Google Fonts -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap">
<!-- Bootstrap core CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
<!-- Material Design Bootstrap -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.18.0/css/mdb.min.css" rel="stylesheet">

<!-- JQuery -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Bootstrap tooltips -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.4/umd/popper.min.js"></script>
<!-- Bootstrap core JavaScript -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/js/bootstrap.min.js"></script>
<!-- MDB core JavaScript -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.18.0/js/mdb.min.js"></script>
<!-- Custom JavaScript -->
<script type="text/javascript" src="/javascript/custom-script.js"></script>
<script type="text/javascript" src="/javascript/navigation.js"></script>
</head>
<body>
    {{{ body }}}
</body>
</html>
</code>```

I hope i could give you a hint feel free to ask if anything is unclear

EDIT:
I would try this out, my guess is that express can't see the assets folder:

```<code>app.use(express.static(path.join(__dirname,'..','assets'));
</code>```

And then for your html:

```<code><link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css">
</code>```

Title: Handlebars not loading local css file

Body:
I'm using handlebars version 4.4.3 in express js application for rendering html. I'm trying to load bootstrap css in style tag. While using cdn link it's working fine. But I want to load from local path. If I'm using local path its not loading. I don't know why it's not working. I tried so many ways to load local css file. But my bad luck nothing helped. Anyone please suggest me how to use local css file in handlebars. Below I mentioned my tried codes everything.

<link rel="stylesheet" href="/css/bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="./css/bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="../css/bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="/assets/css/bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="./assets/css/bootstrap.min.css" type="text/css">
<link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css">

These much things i tried in my registration_print.html file. And also in my express.js file i mentioned static path.

app.use(express.static(__dirname + '/../assets/templates'));
app.use("/assets", express.static(path.join(__dirname, "/../assets")));

Below is my folder structure. Please anyone help me to solve this issue.

Body:
Hey there here is how i did solve this:

First of all i would recommend you, try using express-hanldebars its an module which is special build for express and handlebars interactions.

Basicly you need to use app.use on the hole folder

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var hbs = require('express-handlebars');
var handlebars = require('./helpers/handlebars.js')(hbs);

var routes = require('./routes/index');

var app = express();

// view engine setup
// Settings for Handlebars moved to ./helpers/handlebars.js
app.engine('hbs', handlebars.engine);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

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

app.use('/', routes);

And here is how i used them in the template.

layout.hbs

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ title }}</title>
    <link rel="stylesheet" href="/stylesheets/style.css">
    <link rel="stylesheet" href="/stylesheets/navigation.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">
<!-- Google Fonts -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap">
<!-- Bootstrap core CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
<!-- Material Design Bootstrap -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.18.0/css/mdb.min.css" rel="stylesheet">

<!-- JQuery -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Bootstrap tooltips -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.4/umd/popper.min.js"></script>
<!-- Bootstrap core JavaScript -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/js/bootstrap.min.js"></script>
<!-- MDB core JavaScript -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.18.0/js/mdb.min.js"></script>
<!-- Custom JavaScript -->
<script type="text/javascript" src="/javascript/custom-script.js"></script>
<script type="text/javascript" src="/javascript/navigation.js"></script>
</head>
<body>
    {{{ body }}}
</body>
</html>

I hope i could give you a hint feel free to ask if anything is unclear

EDIT:
I would try this out, my guess is that express can't see the assets folder:

app.use(express.static(path.join(__dirname,'..','assets'));

And then for your html:

<link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css">


来源: stackexchange

问:
How can I open a local HTML file in Microsoft Edge browser?
Since time immemorial, most web browsers have been able to open a local file if you ran the web-browser executable, for example just execute iexplore.exe file:/c:/temp/file or via the IShellDocView interfaces.  I am trying to do this from within my own program, in Windows 10, with Microsoft Edge, and am unaware of how to do it.

The executable appears to be completely undocumented, does not respond to /? or /help, and simply crashes no matter what I pass to it, and given that the path appears to be likely to change, is probably not the correct approach to invoke this executable directly:

```<code>  C:\Windows\SystemApps\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\MicrosoftEdge.exe  <whatever>
</code>```

Is there an API in Windows that can be invoked instead, that will open Edge, perhaps even if it is not the current default browser?

If it was the default browser, I believe I could just do what I want via Win32 shell-API ShellExecute. I would like to be able to launch something in Edge even if I have set another browser as my default though, for the purpose of automating certain web-testing tasks.

Are there programmatic interfaces or APIs for Edge? For purposes of this question, let's say I want to write this in C, but this should be the same API no matter what language I'm using so I didn't tag this question C.

If there is no way to do it programmatically, is there a command line argument I could use and pass to a MicrosoftEdge or MicrosoftEdgeCP executable?

UPDATE: In 2022, with the latest Chromium based Edge browser this problem is no longer a problem.

答:
New 2020: This only applies to the new, Chromium-based Edge (green-blue logo). It doesn't work with the legacy, "modern" Edge (darkblue logo).

With the new Chromium-based Edge it now works normally, if you include a full absolute path.

Tested at cmd prompt on my Windows 10 64b PC:

```<code>"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
file:///C:/MyApplications/MyTestApp.htm
</code>```

..that's all on one line, simple space between.

I'm no fan of MS, but here's their (slow) Egde Link for the latest version.

ContentLicense: CC BY-SA 4.0

Body:
Since time immemorial, most web browsers have been able to open a local file if you ran the web-browser executable, for example just execute iexplore.exe file:/c:/temp/file or via the IShellDocView interfaces.  I am trying to do this from within my own program, in Windows 10, with Microsoft Edge, and am unaware of how to do it.

The executable appears to be completely undocumented, does not respond to /? or /help, and simply crashes no matter what I pass to it, and given that the path appears to be likely to change, is probably not the correct approach to invoke this executable directly:

  C:\Windows\SystemApps\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\MicrosoftEdge.exe  <whatever>

Is there an API in Windows that can be invoked instead, that will open Edge, perhaps even if it is not the current default browser?

If it was the default browser, I believe I could just do what I want via Win32 shell-API ShellExecute. I would like to be able to launch something in Edge even if I have set another browser as my default though, for the purpose of automating certain web-testing tasks.

Are there programmatic interfaces or APIs for Edge? For purposes of this question, let's say I want to write this in C, but this should be the same API no matter what language I'm using so I didn't tag this question C.

If there is no way to do it programmatically, is there a command line argument I could use and pass to a MicrosoftEdge or MicrosoftEdgeCP executable?

UPDATE: In 2022, with the latest Chromium based Edge browser this problem is no longer a problem.

Body:
New 2020: This only applies to the new, Chromium-based Edge (green-blue logo). It doesn't work with the legacy, "modern" Edge (darkblue logo).

With the new Chromium-based Edge it now works normally, if you include a full absolute path.

Tested at cmd prompt on my Windows 10 64b PC:

"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"
file:///C:/MyApplications/MyTestApp.htm

..that's all on one line, simple space between.

I'm no fan of MS, but here's their (slow) Egde Link for the latest version.


问:
How do I select rows where I x% of the columns have NaN values in pandas?
I have a pandas df with floats and NaNs.

How do I select rows where >1000 columns have Nan?

I have tried

```<code>df[(df == NaN).sum(axis=1)>1000])
</code>```

but get:

```<code>NameError: name 'NaN' is not defined
</code>```

Thanks

答:
Please Try</p>

```<code> df[(df.isna()).sum(axis=1)>1000]
</code>```

Body:
I have a pandas df with floats and NaNs.

How do I select rows where >1000 columns have Nan?

I have tried

df[(df == NaN).sum(axis=1)>1000])

but get:

NameError: name 'NaN' is not defined

Thanks

Body:
Please Try

 df[(df.isna()).sum(axis=1)>1000]


问:
How to select a specific node programmatically?
I have a jstree. I want to select the node which is bound to the object which has a location with id of 158. This works but seems stupid. What's the more idiomatic way of doing this?</p>

```<code>var $tree = $('.jstree', myContext),
    node = $tree.find('li').filter(function() {
        return ( $(this).data().location || {}).id === 158;
    });
$tree.jstree('select_node', n)
</code>```

答:
i think u should write code to select node after jstree initialized, therefore use this code

```<code> $('#jstree')
    .on('ready.jstree', function (e, data) {
       // do function after jstree initialized
      $('#jstree')
        .jstree(true)
        .select_node('nodeid');
    });
</code>```

hope its work :)

ContentLicense: CC BY-SA 3.0

Body:
I have a jstree. I want to select the node which is bound to the object which has a location with id of 158. This works but seems stupid. What's the more idiomatic way of doing this?

var $tree = $('.jstree', myContext),
    node = $tree.find('li').filter(function() {
        return ( $(this).data().location || {}).id === 158;
    });
$tree.jstree('select_node', n)

Body:
i think u should write code to select node after jstree initialized, therefore use this code

 $('#jstree')
    .on('ready.jstree', function (e, data) {
       // do function after jstree initialized
      $('#jstree')
        .jstree(true)
        .select_node('nodeid');
    });

hope its work :)


问:
S4 exports specified in 'NAMESPACE' but not defined in package
I just finished some minor updates to an R package I've had on CRAN for a few years (haven't had to update in a while).  My package passes Check on my local machine and on winbuilder, but it just bounced back from CRAN with the message

```<code>checking whether package 'riverdist' can be installed ... WARNING
Found the following significant warnings:
  Warning: S4 exports specified in 'NAMESPACE' but not defined in package 'riverdist'
</code>```

I use roxygen2 to build my package NAMESPACE and don't have any S4 exports that I'm aware of.

Perhaps this might be related to changes in R version 4.0.0?

If anyone's encountered this error, I'd love to hear how you were able to resolve it.  Thanks!

答:
Resolved. roxygen2's @exportClass adds to NAMESPACE exportClasses() which is intended for S4 classes. S3 classes do not need to be exported, only constructor and method functions should be exported, and this is done using @export. In my case deleting all @exportClass commands solved the problem as my package defines only S3 classes. So, indeed the WARNING message is correct in diagnosing S4 exports. Found answer with the help from a thread in R-package-devel mail list from yesterday.

In the case of my packages, the problem existed in only one package that the other 9 which were also triggering the warning depend on.

The WARNING is triggered only under r-devel (future R 4.1.0).

Body:
I just finished some minor updates to an R package I've had on CRAN for a few years (haven't had to update in a while).  My package passes Check on my local machine and on winbuilder, but it just bounced back from CRAN with the message

checking whether package 'riverdist' can be installed ... WARNING
Found the following significant warnings:
  Warning: S4 exports specified in 'NAMESPACE' but not defined in package 'riverdist'

I use roxygen2 to build my package NAMESPACE and don't have any S4 exports that I'm aware of.

Perhaps this might be related to changes in R version 4.0.0?

If anyone's encountered this error, I'd love to hear how you were able to resolve it.  Thanks!


问:
formatting javascript number to years and month
I get an integer such as 20 from it, I need to calculate how many months and years are in it, in 20 for example 1 year and 8 months
how do i do this in JS?

```<code>   case (props.term === 12):
        setYears(1)
        break;
     case (props.term >12):
        ...
     break;
     default:
        break;
  }
</code>```

Is there another way?

答:
First i would divide the month through 12 (a year) to get the amont of years:

Math.floor(20 / 12) = 1

Then I would take the input modulo the amount of month in a year so you get the dangeling months.

20 % 12 = 8

(Sorry for my English)

Body:
I get an integer such as 20 from it, I need to calculate how many months and years are in it, in 20 for example 1 year and 8 months
how do i do this in JS?

   case (props.term === 12):
        setYears(1)
        break;
     case (props.term >12):
        ...
     break;
     default:
        break;
  }

Is there another way?


问:
Where my application's database is stored
I`m new to Android developement.  I want to know by adding this code where the database physically exists in my application folder.</p>

```<code>SQLiteDatabase myDB = info.this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);
 myDB.execSQL("CREATE TABLE IF NOT EXISTS "
     + TableName
     + " (Field1 VARCHAR, Field2 INT(3));");
 Toast.makeText(this,"Database Created", Toast.LENGTH_SHORT).show();
   /* Insert data to a Table*/
   myDB.execSQL("INSERT INTO "
     + TableName
     + " (Field1, Field2)"
     + " VALUES ('Raj Gaurav', 24);");
</code>```

答:
You can find your database in the folowing path
open file explorer
go to

```<code>data/data/yourprojectpath/databases
</code>```

Thanks
Deepak

Body:
I`m new to Android developement.  I want to know by adding this code where the database physically exists in my application folder.

SQLiteDatabase myDB = info.this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);
 myDB.execSQL("CREATE TABLE IF NOT EXISTS "
     + TableName
     + " (Field1 VARCHAR, Field2 INT(3));");
 Toast.makeText(this,"Database Created", Toast.LENGTH_SHORT).show();
   /* Insert data to a Table*/
   myDB.execSQL("INSERT INTO "
     + TableName
     + " (Field1, Field2)"
     + " VALUES ('Raj Gaurav', 24);");

Body:
You can find your database in the folowing path
open file explorer
go to

data/data/yourprojectpath/databases

Thanks
Deepak


问:
What is the 'criticality' attribute in SimplePagedResultsControl in python-ldap?
I'm using python-ldap for pagination of LDAP search.

I found many similar references online and all of them set:

page_control = SimplePagedResultsControl(True, size={some_size}, cookie='')

For example: https://medium.com/@alpolishchuk/pagination-of-ldap-search-results-with-python-ldap-845de60b90d2

I checked python-ldap's documentation and couldn't find a useful explanation:

https://www.python-ldap.org/en/latest/reference/ldap-controls.html#ldap.controls.libldap.SimplePagedResultsControl

答:
I found my answer: https://www.rfc-editor.org/rfc/rfc2696</p>
```<code>If the server does not support pagedResultsControl,
the server MUST return an error of unsupportedCriticalExtension if the client
requested it as critical, otherwise the server SHOULD ignore the control.
</code>```

Body:
I found my answer: https://www.rfc-editor.org/rfc/rfc2696

If the server does not support pagedResultsControl,
the server MUST return an error of unsupportedCriticalExtension if the client
requested it as critical, otherwise the server SHOULD ignore the control.


问:
In Habanero how would I restrict the number of objects returned from a database
I need to restrict the number of customer bo's returned from the database as I am searching for a partial customer name and at the moment I get over 600 bo's when searching for 'a'.  I would like to restrict this to 20.  My code at the moment is </p>

```<code>    public IEnumerable<Customer> FindCustomers(string partialCustomerName)
    {
        if (string.IsNullOrEmpty(partialCustomerName))
          throw new ArgumentException("partialCustomerName must be at least one character long");
        var criteria = Criteria.Create<Customer, string>(cust =>   cust.CustomerName, Criteria.ComparisonOp.Like, partialCustomerName + "%");
        return Broker.GetBusinessObjectCollection<Customer>(criteria);
    }
</code>```

答:
I cannot test this right now but you should be able to this by using the LoadWithLimit() method. The totalRecords variable will hold the number of total results found in case you want to include some info like "Showing 20 of totalRecords results.".</p>

```<code>public IEnumerable<Customer> FindCustomers(string partialCustomerName)
{
    if (string.IsNullOrEmpty(partialCustomerName))
      throw new ArgumentException("partialCustomerName must be at least one character long");

    var criteria = Criteria.Create<Customer, string>(cust =>   cust.CustomerName, Criteria.ComparisonOp.Like, partialCustomerName + "%");
    int totalRecords;
    return Broker.GetBusinessObjectCollection<Customer>().LoadWithLimit(criteria, 0, 20, ref totalRecords);
}
</code>```

Body:
I need to restrict the number of customer bo's returned from the database as I am searching for a partial customer name and at the moment I get over 600 bo's when searching for 'a'.  I would like to restrict this to 20.  My code at the moment is

    public IEnumerable<Customer> FindCustomers(string partialCustomerName)
    {
        if (string.IsNullOrEmpty(partialCustomerName))
          throw new ArgumentException("partialCustomerName must be at least one character long");
        var criteria = Criteria.Create<Customer, string>(cust =>   cust.CustomerName, Criteria.ComparisonOp.Like, partialCustomerName + "%");
        return Broker.GetBusinessObjectCollection<Customer>(criteria);
    }

Body:
I cannot test this right now but you should be able to this by using the LoadWithLimit() method. The totalRecords variable will hold the number of total results found in case you want to include some info like "Showing 20 of totalRecords results.".

public IEnumerable<Customer> FindCustomers(string partialCustomerName)
{
    if (string.IsNullOrEmpty(partialCustomerName))
      throw new ArgumentException("partialCustomerName must be at least one character long");

    var criteria = Criteria.Create<Customer, string>(cust =>   cust.CustomerName, Criteria.ComparisonOp.Like, partialCustomerName + "%");
    int totalRecords;
    return Broker.GetBusinessObjectCollection<Customer>().LoadWithLimit(criteria, 0, 20, ref totalRecords);
}


问:
Image as a href to modal
I have a problem with JS. I mean when user click on the image, modal opens, I must use a href. I don't know how to make that working. I have only modal. I show you my code:

var modal = document.getElementById('myModal');

var btn = document.getElementById("myBtn");

var span = document.getElementsByClassName("close")[0];

btn.onclick = function() {
  modal.style.display = "block";
}

span.onclick = function() {
  modal.style.display = "none";
}

window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.modal {
  display: none;
  /* Hidden by default */
  position: fixed;
  /* Stay in place */
  z-index: 1;
  /* Sit on top */
  padding-top: 100px;
  /* Location of the box */
  left: 0;
  top: 0;
  width: 100%;
  /* Full width */
  height: 100%;
  /* Full height */
  overflow: auto;
  /* Enable scroll if needed */
  background-color: rgb(0, 0, 0);
  /* Fallback color */
  background-color: rgba(0, 0, 0, 0.4);
  /* Black w/ opacity */
}

/* Modal Content */

.modal-content {
  background-color: #fefefe;
  margin: auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}

/* The Close Button */

.close {
  color: #aaaaaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}</code>```

      ×

TEST

```

Thank you for all your help!

答:
I know that the question was posted years ago but I struggled to find proper answer for a while. Actually, you can make this:

```<code><a href="#" data-toggle="modal" data-target="your-modal-id" class="image fit">
  <img src="" id="" alt="" />
</a>
</code>```

Hope someone will find it helpful)

Title: Image as a href to modal

Body:
I have a problem with JS. I mean when user click on the image, modal opens, I must use a href. I don't know how to make that working. I have only modal. I show you my code:

var modal = document.getElementById('myModal');

var btn = document.getElementById("myBtn");

var span = document.getElementsByClassName("close")[0];

btn.onclick = function() {
  modal.style.display = "block";
}

span.onclick = function() {
  modal.style.display = "none";
}

window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

.modal {
  display: none;
  /* Hidden by default */
  position: fixed;
  /* Stay in place */
  z-index: 1;
  /* Sit on top */
  padding-top: 100px;
  /* Location of the box */
  left: 0;
  top: 0;
  width: 100%;
  /* Full width */
  height: 100%;
  /* Full height */
  overflow: auto;
  /* Enable scroll if needed */
  background-color: rgb(0, 0, 0);
  /* Fallback color */
  background-color: rgba(0, 0, 0, 0.4);
  /* Black w/ opacity */
}

/* Modal Content */

.modal-content {
  background-color: #fefefe;
  margin: auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}

/* The Close Button */

.close {
  color: #aaaaaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}

      ×

TEST

Thank you for all your help!

Body:
I know that the question was posted years ago but I struggled to find proper answer for a while. Actually, you can make this:

<a href="#" data-toggle="modal" data-target="your-modal-id" class="image fit">
  <img src="" id="" alt="" />
</a>

Hope someone will find it helpful)


问:
How to hidden Expand after clicking on the content? XAML
Need some help, is anyone know how to make it so that when you click on the contents of Expand - does it hidden?

```<code>        <Expander Header="First Expand">
            <ListBox>
                <ListBox.Items>
                    <CheckBox Content="First"/>
                    <CheckBox Content="Second"/>
                    <CheckBox Content="Third"/>
                </ListBox.Items>
            </ListBox>
        </Expander>
</code>```

Is it possible to use bindings?

答:
I use ToggleButton, and rewrite template (like Expander but Name = Header)

```<code>   <ToggleButton Style="{DynamicResource NewToggle}"
                 Name="First Toggle" Click="Toggle_click">
        <ListBox>
            <ListBox.Items>
                <CheckBox Content="First"/>
                <CheckBox Content="Second"/>
                <CheckBox Content="Third"/>
            </ListBox.Items>
        </ListBox>
    </ToggleButton>
</code>```

Then use codebehind:

```<code>private void Toggle_click(object sender, RoutedEventArgs e)
{
    if (e.OriginalSource.GetType().Name == "CheckBox")
    {
        var myCheck= (CheckBox)e.OriginalSource;
        var MyList = (ListBox)myCheck.Parent;
        var myToogle = (ToggleButton)MyList.Parent;
        myToogle.IsChecked = false;
    }
    return;
}
</code>```

I think it's not a best idea

Body:
Need some help, is anyone know how to make it so that when you click on the contents of Expand - does it hidden?

        <Expander Header="First Expand">
            <ListBox>
                <ListBox.Items>
                    <CheckBox Content="First"/>
                    <CheckBox Content="Second"/>
                    <CheckBox Content="Third"/>
                </ListBox.Items>
            </ListBox>
        </Expander>

Is it possible to use bindings?

Body:
I use ToggleButton, and rewrite template (like Expander but Name = Header)

   <ToggleButton Style="{DynamicResource NewToggle}"
                 Name="First Toggle" Click="Toggle_click">
        <ListBox>
            <ListBox.Items>
                <CheckBox Content="First"/>
                <CheckBox Content="Second"/>
                <CheckBox Content="Third"/>
            </ListBox.Items>
        </ListBox>
    </ToggleButton>

Then use codebehind:

private void Toggle_click(object sender, RoutedEventArgs e)
{
    if (e.OriginalSource.GetType().Name == "CheckBox")
    {
        var myCheck= (CheckBox)e.OriginalSource;
        var MyList = (ListBox)myCheck.Parent;
        var myToogle = (ToggleButton)MyList.Parent;
        myToogle.IsChecked = false;
    }
    return;
}

I think it's not a best idea


问:
Python: Maximum difference between elements in a list
I need to find the maximum difference between elements in an unsorted list if the element to the right of the present element is greater. For eg:

```<code>myList = [2, 3, 8, 0, 7].
</code>```

Function should calculate as follows:

```<code>present element = 2.
is 3 > 2? Yes. Then 3-2 = 1
is 8 > 2? Yes. Then 8-2 = 6
is 0 > 2? No. Go to the next element.
is 7 > 2? Yes. Then 7-2 = 5 and so on

Finally my output = 7
</code>```

My first solution is as follows:

```<code>def maxDiff(a):
l = len(a)
arr = []
for i in range(l-1):
    for j in range(i+1, l):
        if a[j] > a[i]:
            diff = a[j] - a[i]
            arr.append(diff)
return (max(arr))
</code>```

I was said that this is not an optimal solution. I came up with another solution which is as follows:

```<code>def maxDiff(a):
l = len(a)
diffList = []
for i in range(l-1):
    newList = a[i+1:]
    max1 = max(newList)
    difference = max1 - a[i]
    diffList.append(difference)
return (max(diffList))
</code>```

My question is is the second solution correct? If yes, then is it optimal? What is the time complexity of both these functions? Is there any other solution that is more optimal?

答:
There are though many ways to solve a single problem. i would suggest this way as will be a bit faster and is more pythonic.</p>

```<code>mylist = [2, 3, 8, 0, 7]
max_diff = max( [mylist[i+1]-mylist[i] for i in range(len(mylist)-1) if mylist[i]<mylist[i+1]] )

print(max_diff)
</code>```

Body:
I need to find the maximum difference between elements in an unsorted list if the element to the right of the present element is greater. For eg:

myList = [2, 3, 8, 0, 7].

Function should calculate as follows:

present element = 2.
is 3 > 2? Yes. Then 3-2 = 1
is 8 > 2? Yes. Then 8-2 = 6
is 0 > 2? No. Go to the next element.
is 7 > 2? Yes. Then 7-2 = 5 and so on

Finally my output = 7

My first solution is as follows:

def maxDiff(a):
l = len(a)
arr = []
for i in range(l-1):
    for j in range(i+1, l):
        if a[j] > a[i]:
            diff = a[j] - a[i]
            arr.append(diff)
return (max(arr))

I was said that this is not an optimal solution. I came up with another solution which is as follows:

def maxDiff(a):
l = len(a)
diffList = []
for i in range(l-1):
    newList = a[i+1:]
    max1 = max(newList)
    difference = max1 - a[i]
    diffList.append(difference)
return (max(diffList))

My question is is the second solution correct? If yes, then is it optimal? What is the time complexity of both these functions? Is there any other solution that is more optimal?

Body:
There are though many ways to solve a single problem. i would suggest this way as will be a bit faster and is more pythonic.

mylist = [2, 3, 8, 0, 7]
max_diff = max( [mylist[i+1]-mylist[i] for i in range(len(mylist)-1) if mylist[i]<mylist[i+1]] )

print(max_diff)


问:
wrapping JavaScript tracking code
I have following tracking code from Piwik.

```<code><!-- Tracking Code -->
<script type="text/javascript">
var pkBaseURL = (("https:" == document.location.protocol) ? "https://example.com/" : "http://example.com/");
document.write(unescape("%3Cscript src='" + pkBaseURL + "piwik.js' type='text/javascript'%3E%3C/script%3E"));
</script><script type="text/javascript">
try {
  var piwikTracker = Piwik.getTracker(pkBaseURL + "piwik.php", 29);
  piwikTracker.trackPageView();
  piwikTracker.enableLinkTracking();
} catch( err ) {}
</script><noscript><p><img src="http://example.com/piwik.php?idsite=29" style="border:0" alt="" /></p></noscript>
<!-- Tracking Code -->
</code>```

I want to hide following code, so I think I can put this code in some js file, and load it using following code.

But I don't know how can I do it. Help required here.

Secondly, I need to change site id (in above example, is 29), which will be different for different site.

How can I pass site-id to custom file that I will make, and execute above code.

答:
```<code>var pkBaseURL = (
    ( "https:" == document.location.protocol )
    ?
    "https://example.com/"
    :
    "http://example.com/");

var piwik_script = document . createElement ( "script" ) ;
piwik_script . src = pkBaseURL + "piwik.js" ;
document . body . appendChild ( piwik_script ) ;

function track ()
{
  try
  {
    var piwikTracker = Piwik.getTracker(pkBaseURL + "piwik.php", piwik_page_id);
    piwikTracker.trackPageView();
    piwikTracker.enableLinkTracking();
  } catch( err ) {}
}

piwik_script . addEventListener ( "load", track );
</code>```

Title: wrapping JavaScript tracking code

Body:
I have following tracking code from Piwik.

I want to hide following code, so I think I can put this code in some js file, and load it using following code.

But I don't know how can I do it. Help required here.

Secondly, I need to change site id (in above example, is 29), which will be different for different site.

How can I pass site-id to custom file that I will make, and execute above code.


问:
How to search users from database using retrofit in Android studio? SOLVED
Edit: I have found a solution. I have made a search function in Laravel, which was a simple query, then implemented in Android Studio an edittext onquerylistener in which I have called the function from the laravel. And it works perfectly.

I need to implement an invitation function in my Android application but I have no prior knowledge for this. The idea is that I have an Edittext (or maybe another field) where the user can search for other users, who are registered, and by clicking on them they appear below the search field in a listview. And by clicking on the invite button everyone in the listview gets a notification/invitation.
How can this be done using retrofit?
It should be something like for each character written an API request is sent and suggestions are shown.
I am using Laravel and Android(java).
I don't have much code written here because I don't know where and how to start.
Here is the request:

```<code> @GET("users")
 Call<List<User>> getUsers(@Header("Authorization") String token);
</code>```

Here is the getUsers method so far in the activity:

```<code>  private void getUsers(){
    Log.d(TAG, "onResponse: loadData called");
    ApiService service = RetrofitBuilder.getRetrofitInstance().create(ApiService.class);
    Call<List<User>> call = service.getUsers("Bearer "+token);
    call.enqueue(new Callback<List<User>>() {
        @Override
        public void onResponse(@NonNull Call<List<User>> call, @NonNull Response<List<User>> response) {
            try {
                if (response.isSuccessful()){
                    Log.d(TAG, "onResponse: successful loadData called");

                    adapter = new UserAdapter(mContext, arrayList);
                    listView.setAdapter(adapter);
                }
                else{
                    Log.d(TAG, "onResponse: " + response.body());
                }
            }
            catch (Exception e){
                Toast.makeText(TeamAdminActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onFailure(@NonNull Call<List<User>> call, @NonNull Throwable t) {
            Log.d("Response", "onFailure: " + t.toString());
        }
    });
}
</code>```

Also a snippet of my xml file:

```<code> <TextView
            android:id="@+id/invite"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="@dimen/activity_vertical_margin"
            android:layout_marginTop="36dp"
            android:layout_below="@id/team_title"
            android:textSize="24sp"
            android:textColor="@color/colorPrimary"
            android:text="@string/invite_members" />

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/search"
            style="@style/TextInputLayoutAppearance"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/invite"
            android:layout_marginTop="10dp"
            android:layout_marginStart="18dp"
            android:layout_marginEnd="18dp"
            android:hint="@string/search"
            android:textSize="23sp"
            app:boxStrokeColor="@color/colorPrimaryDark">

            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/search_et"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/spinner"
                android:hint="@string/event_name"
                android:textSize="18sp" />
        </com.google.android.material.textfield.TextInputLayout>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/invite"
            android:layout_toEndOf="@+id/search"/>

        <TextView
            android:id="@+id/invited"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="@dimen/activity_vertical_margin"
            android:layout_marginTop="36dp"
            android:layout_below="@id/search"
            android:textSize="24sp"
            android:textColor="@color/colorPrimary"
            android:text="@string/invited" />

        <androidx.core.widget.NestedScrollView
            android:id="@+id/scroll_view"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:layout_below="@id/invited">

            <ListView
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

        </androidx.core.widget.NestedScrollView>

        <Button
            android:id="@+id/create_team_btn"
            android:layout_width="260dp"
            android:layout_height="60dp"
            android:layout_below="@+id/scroll_view"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="18dp"
            android:layout_marginBottom="14dp"
            android:background="@drawable/my_color_button"
            android:text="@string/invite"
            android:textColor="@color/myWhite" />
</code>```

答:
arrayList ? did you add the response's body into the list when the response is successful ? or just pass the response's body into the adapter
Like

adapter = new UserAdapter(mContext, response.body());

Body:
Edit: I have found a solution. I have made a search function in Laravel, which was a simple query, then implemented in Android Studio an edittext onquerylistener in which I have called the function from the laravel. And it works perfectly.

I need to implement an invitation function in my Android application but I have no prior knowledge for this. The idea is that I have an Edittext (or maybe another field) where the user can search for other users, who are registered, and by clicking on them they appear below the search field in a listview. And by clicking on the invite button everyone in the listview gets a notification/invitation.
How can this be done using retrofit?
It should be something like for each character written an API request is sent and suggestions are shown.
I am using Laravel and Android(java).
I don't have much code written here because I don't know where and how to start.
Here is the request:

 @GET("users")
 Call<List<User>> getUsers(@Header("Authorization") String token);

Here is the getUsers method so far in the activity:

  private void getUsers(){
    Log.d(TAG, "onResponse: loadData called");
    ApiService service = RetrofitBuilder.getRetrofitInstance().create(ApiService.class);
    Call<List<User>> call = service.getUsers("Bearer "+token);
    call.enqueue(new Callback<List<User>>() {
        @Override
        public void onResponse(@NonNull Call<List<User>> call, @NonNull Response<List<User>> response) {
            try {
                if (response.isSuccessful()){
                    Log.d(TAG, "onResponse: successful loadData called");

                    adapter = new UserAdapter(mContext, arrayList);
                    listView.setAdapter(adapter);
                }
                else{
                    Log.d(TAG, "onResponse: " + response.body());
                }
            }
            catch (Exception e){
                Toast.makeText(TeamAdminActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onFailure(@NonNull Call<List<User>> call, @NonNull Throwable t) {
            Log.d("Response", "onFailure: " + t.toString());
        }
    });
}

Also a snippet of my xml file:

 <TextView
            android:id="@+id/invite"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="@dimen/activity_vertical_margin"
            android:layout_marginTop="36dp"
            android:layout_below="@id/team_title"
            android:textSize="24sp"
            android:textColor="@color/colorPrimary"
            android:text="@string/invite_members" />

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/search"
            style="@style/TextInputLayoutAppearance"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/invite"
            android:layout_marginTop="10dp"
            android:layout_marginStart="18dp"
            android:layout_marginEnd="18dp"
            android:hint="@string/search"
            android:textSize="23sp"
            app:boxStrokeColor="@color/colorPrimaryDark">

            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/search_et"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/spinner"
                android:hint="@string/event_name"
                android:textSize="18sp" />
        </com.google.android.material.textfield.TextInputLayout>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/invite"
            android:layout_toEndOf="@+id/search"/>

        <TextView
            android:id="@+id/invited"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="@dimen/activity_vertical_margin"
            android:layout_marginTop="36dp"
            android:layout_below="@id/search"
            android:textSize="24sp"
            android:textColor="@color/colorPrimary"
            android:text="@string/invited" />

        <androidx.core.widget.NestedScrollView
            android:id="@+id/scroll_view"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:layout_below="@id/invited">

            <ListView
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

        </androidx.core.widget.NestedScrollView>

        <Button
            android:id="@+id/create_team_btn"
            android:layout_width="260dp"
            android:layout_height="60dp"
            android:layout_below="@+id/scroll_view"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="18dp"
            android:layout_marginBottom="14dp"
            android:background="@drawable/my_color_button"
            android:text="@string/invite"
            android:textColor="@color/myWhite" />


问:
IdentityServer4 response_mode web_message
I am trying to implement IdentityServer4 on .NET Core 3.1, and I have stucked on

```<code>/authorize?response_mode=web_message&...
</code>```

as defined in OAuth 2.0 Web Message Response Mode specification. It is particularly useful when using Silent Authentication.

Has anyone implemented web_message response mode?

答:
Have you checked that this response_mode is supported by IdentityServer4? It's not part of the OIDC spec as far as I know but it may be possible to implement it yourself.

For client side apps OIDC already supports silent authentication. The client uses a hidden iframe to make the authorize call and the callback endpoint itself uses the postMessage API to pass the result to the client application. The oidc-client-js library implements this out of the box.

For serverside applications the typical approach is to use a refresh token to automatically renew the access token as needed.

Body:
I am trying to implement IdentityServer4 on .NET Core 3.1, and I have stucked on

/authorize?response_mode=web_message&...

as defined in OAuth 2.0 Web Message Response Mode specification. It is particularly useful when using Silent Authentication.

Has anyone implemented web_message response mode?


问:
React native TouchableOpacity onPress not working on Android Build (APK)
TouchableOpacity works on the android emulator and on the cell phone, but when I generated the APK, TouchableOpacity didn't work anymore.

what could be happening?

When I click on TouchableOpacity nothing happens, it just makes the opacity animation

the right thing would be to go to the Home screen but it doesn't

does it have something over it like z-index?

Javascript Code Bellow

```<code>import React from 'react';
import {View, Image, Text, TouchableOpacity, TextInput} from 'react-native';
import {useNavigation} from '@react-navigation/native';
import {useField} from '@unform/core';
import {Form} from '@unform/mobile';
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';

import styles from './styles';

import logoImg from '../../assets/logo.png';
import Home from '../Home';

export default function Login() {
  const navigation = useNavigation();

  function navigateToHome() {
    navigation.navigate(Home);
  }

  return (
    <KeyboardAwareScrollView style={styles.scroll}>
      <View style={styles.container}>
        <Image style={styles.logo} source={logoImg} />
        <TextInput style={styles.input} placeholder="Login" />
        <TextInput
          secureTextEntry={true}
          style={styles.inputPassword}
          placeholder="Senha"
        />
        <TouchableOpacity style={styles.button} onPress={navigateToHome}>
          <Text style={styles.buttonText}>Entrar</Text>
        </TouchableOpacity>
      </View>
    </KeyboardAwareScrollView>
  );
}

</code>```

Style Code Bellow

```<code>import {StyleSheet} from 'react-native';

export default StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: '#fff',
  },
  scroll: {
    backgroundColor: '#fff',
  },
  logo: {
    marginTop: 30,
  },
  input: {
    marginTop: 30,
    padding: 10,
    width: 300,
    height: 56,
    backgroundColor: '#f5f5f5',
    fontSize: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#8CC63F',
    borderRadius: 4,
  },
  inputPassword: {
    marginTop: 30,
    padding: 10,
    width: 300,
    height: 56,
    backgroundColor: '#f5f5f5',
    fontSize: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#8CC63F',
    borderRadius: 4,
  },
  button: {
    width: 122,
    height: 66,
    marginTop: 60,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#20565C',
    borderRadius: 4,
  },
  buttonText: {
    fontSize: 16,
    color: '#fff',
    textTransform: 'uppercase',
    fontWeight: 'bold',
  },
});
</code>```

答:
update below code like this:

```<code><TouchableOpacity style={styles.button} onPress={()=>this.navigateToHome}>
      <Text style={styles.buttonText}>Entrar</Text>
    </TouchableOpacity>
</code>```

hope it works for you.

Body:
TouchableOpacity works on the android emulator and on the cell phone, but when I generated the APK, TouchableOpacity didn't work anymore.

what could be happening?

When I click on TouchableOpacity nothing happens, it just makes the opacity animation

the right thing would be to go to the Home screen but it doesn't

does it have something over it like z-index?

Javascript Code Bellow

import React from 'react';
import {View, Image, Text, TouchableOpacity, TextInput} from 'react-native';
import {useNavigation} from '@react-navigation/native';
import {useField} from '@unform/core';
import {Form} from '@unform/mobile';
import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view';

import styles from './styles';

import logoImg from '../../assets/logo.png';
import Home from '../Home';

export default function Login() {
  const navigation = useNavigation();

  function navigateToHome() {
    navigation.navigate(Home);
  }

  return (
    <KeyboardAwareScrollView style={styles.scroll}>
      <View style={styles.container}>
        <Image style={styles.logo} source={logoImg} />
        <TextInput style={styles.input} placeholder="Login" />
        <TextInput
          secureTextEntry={true}
          style={styles.inputPassword}
          placeholder="Senha"
        />
        <TouchableOpacity style={styles.button} onPress={navigateToHome}>
          <Text style={styles.buttonText}>Entrar</Text>
        </TouchableOpacity>
      </View>
    </KeyboardAwareScrollView>
  );
}

Style Code Bellow

import {StyleSheet} from 'react-native';

export default StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: '#fff',
  },
  scroll: {
    backgroundColor: '#fff',
  },
  logo: {
    marginTop: 30,
  },
  input: {
    marginTop: 30,
    padding: 10,
    width: 300,
    height: 56,
    backgroundColor: '#f5f5f5',
    fontSize: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#8CC63F',
    borderRadius: 4,
  },
  inputPassword: {
    marginTop: 30,
    padding: 10,
    width: 300,
    height: 56,
    backgroundColor: '#f5f5f5',
    fontSize: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#8CC63F',
    borderRadius: 4,
  },
  button: {
    width: 122,
    height: 66,
    marginTop: 60,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#20565C',
    borderRadius: 4,
  },
  buttonText: {
    fontSize: 16,
    color: '#fff',
    textTransform: 'uppercase',
    fontWeight: 'bold',
  },
});

Body:
update below code like this:

<TouchableOpacity style={styles.button} onPress={()=>this.navigateToHome}>
      <Text style={styles.buttonText}>Entrar</Text>
    </TouchableOpacity>

hope it works for you.


问:
How do I remove the select option black border in Chrome?
As shown in the picture below,

black border is shown when the select option is hover from the chrome.

how can I remove the border?

The code below didn't work.

```<code>select{

  &:hover,
  &:focus
  {
    outline: 0 !important;
  }
}
</code>```

I'd appreciate it if you could help me solve the problem.

答:
It happen when chrome updated. Actually, it it's a update feature from chromium that update in 2020.
If you interested know about more feature below this link.

https://blog.chromium.org/2020/03/updates-to-form-controls-and-focus.html

#Problem solution:

Just go to below this link

chrome://flags/#form-controls-refresh

and Disabled Web Platform Controls updated UI

Body:
As shown in the picture below,

black border is shown when the select option is hover from the chrome.

how can I remove the border?

The code below didn't work.

select{

  &:hover,
  &:focus
  {
    outline: 0 !important;
  }
}

I'd appreciate it if you could help me solve the problem.


问:
Keeping a POD alive in Kubernetes
I am in the process of migrating an application from Windows server to Kubernetes running on cloud.I was able to launch the application successfully in Kubernetes. Next is restoration and there is a script provided to restore the data to the new instance, but that should be run when the instance of application is shutdown. There is a script called stop.sh to shutdown the instance of that application. Both restore and shutdown script should be run inside the POD. I got into the POD using "Kubectl exec" , and then i tried to shutdown the instance using stop.sh. Then the instance will shutdown, but the POD will also exit along with it and i am not able run the restore.sh script inside the POD. So is there a way where i can keep the POD alive even after my application instance is shutdown to run the restore script.

Regards,
John

答:
A POD is meant to stay alive while the main process is running, when the main process shutdown, the pod will be terminated.

What you want is not how to keep the POD alive, but how to refactor your application to work with Kubernetes properly.

The restore phase you previously had in a script, will likely run as an init container.
Init containers are specialized containers that run before other containers in a Pod, so you could run your restore logic before the main application start.

The next phase is starting the application, the application should start by itself inside the container when the container is created, so the init container shouldn't affect it's lifecycle. The application will assume the init container has done it's work and the environment is setup properly.

The next phase is termination, when a container is started or stopped, Kubernetes will trigger container hooks for PostStart and PreStop. You likely need to use the PreStop hook to execute the custom script.

The scenario above, assumes minimal changes to the application, if you are willing to refactor the application to deploy it to Kubernetes, there are other ways it can be achieved, like using persistent volumes to store the data and re-use it when the container start, so you won't need to do the backup and restore all the time.

Title: Keeping a POD alive in Kubernetes


问:
How can I request pipeline processors in Apache Wicket?
Is there any way to request pipeline processors in Apache Wicket? Possibly with an open-source framework that integrates with Wicket?

I want to check requests before my web pages are rendered.

答: In Wicket 1.4.x (don't know if this has been kept in 1.5) you have  RequestCycle#onBeginRequest() and RequestCycle#onEndRequest() that you can override.


问:
Get consecutive days with momentjs
I have a string containing days of the week:

```<code>Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday
</code>```

It can be also:

```<code>Monday, Tuesday
</code>```

Also:

```<code>Thursday, Friday, Saturday
</code>```

What I want to achieve is if more than 2 days are consecutive to "merge" them and display like:
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday - will be Monday - Sunday;
Monday, Tuesday - will stay like that;
Thursday, Friday, Saturday - Thursday - Saturday.

I want to use only moment.js or javascript without other plugins (like range).
Thanks in advance!

答:
This seems to work just fine.

const weekDaysMap = new Map([
  ["Monday", 0],
  ["Tuesday", 1],
  ["Wednesday", 2],
  ["Thursday", 3],
  ["Friday", 4],
  ["Saturday", 5],
  ["Sunday", 6]
]);

function getDayRanges(days) {
  const ranges = [];
  let range = [days[0]], d = weekDaysMap.get(days[0]);
  for (let i = 1; i < days.length; i++) {
    if (d !== (d = weekDaysMap.get(days[i])) - 1) {
      range.push(days[i-1]);
      ranges.push(range);
      range = [days[i]];
    }
  }
  range.push(days[days.length-1]);
  ranges.push(range);
  return ranges;
}

console.log(getDayRanges(["Monday", "Tuesday", "Wednesday", "Saturday", "Sunday"]).map( r => r.join("–")).join(", "))```

Explanation: First we create a Map that converts the days of the week to their indexes. Then we create a ranges array that will store the start-end days pairs. We also define the current range and the current day index, d. We loop through the provided days of the week in the array and if the previous day in the array isn't the previous day in the order, the previous day in the array is the end of the range and the current day in the array is the start of a new one.

Then the each range is joined using an em dash and the ranges are joined using commas. (From [[Monday, Wednesday], [Saturday, Sunday]] to Monday–Wednesday, Saturday–Sunday.)

Title: Get consecutive days with momentjs

Body:
I have a string containing days of the week:

Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday

It can be also:

Monday, Tuesday

Also:

Thursday, Friday, Saturday

What I want to achieve is if more than 2 days are consecutive to "merge" them and display like:
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday - will be Monday - Sunday;
Monday, Tuesday - will stay like that;
Thursday, Friday, Saturday - Thursday - Saturday.

I want to use only moment.js or javascript without other plugins (like range).
Thanks in advance!

Body:
This seems to work just fine.

const weekDaysMap = new Map([
  ["Monday", 0],
  ["Tuesday", 1],
  ["Wednesday", 2],
  ["Thursday", 3],
  ["Friday", 4],
  ["Saturday", 5],
  ["Sunday", 6]
]);

function getDayRanges(days) {
  const ranges = [];
  let range = [days[0]], d = weekDaysMap.get(days[0]);
  for (let i = 1; i < days.length; i++) {
    if (d !== (d = weekDaysMap.get(days[i])) - 1) {
      range.push(days[i-1]);
      ranges.push(range);
      range = [days[i]];
    }
  }
  range.push(days[days.length-1]);
  ranges.push(range);
  return ranges;
}

console.log(getDayRanges(["Monday", "Tuesday", "Wednesday", "Saturday", "Sunday"]).map( r => r.join("–")).join(", "))

Explanation: First we create a Map that converts the days of the week to their indexes. Then we create a ranges array that will store the start-end days pairs. We also define the current range and the current day index, d. We loop through the provided days of the week in the array and if the previous day in the array isn't the previous day in the order, the previous day in the array is the end of the range and the current day in the array is the start of a new one.

Then the each range is joined using an em dash and the ranges are joined using commas. (From [[Monday, Wednesday], [Saturday, Sunday]] to Monday–Wednesday, Saturday–Sunday.)


问:
How to achieve the functionality described below
I need to do something like this:

```<code>// I have an interface with these two methods defined
type mapper interface {
    ReadMapper(interface{}) interface{}
    WriteMapper(interface{}) interface{}
}
</code>```

then I need to assign ReadMapper and WriteMapper some functions which are defined somewhere else in the project. Is there is a way to do something like this in Go? Assigning functions to them?

```<code>   V1Mapper mapper
   V1Mapper.ReadMapper = functions()....
   V1Mapper.WriteMapper = functions()....
</code>```

Then, I need another map and want the mapper as the value type and want to do something like below.

```<code>mappingFunctions := map[string]mapper

mappingFunctions ["some_string"] = V1Mapper
</code>```

and then from another file, I want to do this:

```<code>mappingFunctions["some_string"].ReadMapper(Data)
</code>```

EDIT: I never asked for syntax in the question. I just wanted to know if there was a better way to do this because I was new to Go. I do agree I am not very much familiar with the syntax of the Go and I will have to go through the documentation (not once but many times).

答:
If you want to compose mappers from the existing functions, you can use structures instead of interfaces:

```<code>type Mapper struct {
    ReadMapper  func(interface{}) interface{}
    WriteMapper func(interface{}) interface{}
}

mappers := map[string]*Mapper{}
mappers["some_name"] = &Mapper{
    ReadMapper: someFunc1,
    WriteMapper: someFunc2,
}
</code>```

or

```<code>m := new(Mapper)
m.ReadMapper = someFunc1
m.WriteMapper = someFunc2
mappers["some_name"] = m
</code>```

Body:
I need to do something like this:

// I have an interface with these two methods defined
type mapper interface {
    ReadMapper(interface{}) interface{}
    WriteMapper(interface{}) interface{}
}

then I need to assign ReadMapper and WriteMapper some functions which are defined somewhere else in the project. Is there is a way to do something like this in Go? Assigning functions to them?

   V1Mapper mapper
   V1Mapper.ReadMapper = functions()....
   V1Mapper.WriteMapper = functions()....

Then, I need another map and want the mapper as the value type and want to do something like below.

mappingFunctions := map[string]mapper

mappingFunctions ["some_string"] = V1Mapper

and then from another file, I want to do this:

mappingFunctions["some_string"].ReadMapper(Data)

EDIT: I never asked for syntax in the question. I just wanted to know if there was a better way to do this because I was new to Go. I do agree I am not very much familiar with the syntax of the Go and I will have to go through the documentation (not once but many times).

Body:
If you want to compose mappers from the existing functions, you can use structures instead of interfaces:

type Mapper struct {
    ReadMapper  func(interface{}) interface{}
    WriteMapper func(interface{}) interface{}
}

mappers := map[string]*Mapper{}
mappers["some_name"] = &Mapper{
    ReadMapper: someFunc1,
    WriteMapper: someFunc2,
}

or

m := new(Mapper)
m.ReadMapper = someFunc1
m.WriteMapper = someFunc2
mappers["some_name"] = m


问:
How can i put two different threads on a single service?
can someone give me the code example that shows how to use two different threads on a single service? i didnt find the way to do it in google, then i need a code example...

one waiting 5 seconds and the other waiting 60 seconds, with different code

答:
You can use the ScheduledExecutorService to create and run scheduled events, then set them up like this:

```<code>private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);

final Runnable r1 = new Runnable() {
    @Override
    public void run() {
        Log.i("TestStuff", "r1 ran at " + new Date());
    }
};

final Runnable r2 = new Runnable() {
    @Override
    public void run() {
        Log.i("TestStuff", "r2 ran " + new Date());
    }
};

scheduler.schedule(r1, 5, TimeUnit.SECONDS);
scheduler.schedule(r2, 60, TimeUnit.SECONDS);
</code>```

Note that the threads can't do anything on the UI, but you did mention a "single service", so i'm assuming you're doing all non-UI things anyway.

Body:
You can use the ScheduledExecutorService to create and run scheduled events, then set them up like this:

private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);

final Runnable r1 = new Runnable() {
    @Override
    public void run() {
        Log.i("TestStuff", "r1 ran at " + new Date());
    }
};

final Runnable r2 = new Runnable() {
    @Override
    public void run() {
        Log.i("TestStuff", "r2 ran " + new Date());
    }
};

scheduler.schedule(r1, 5, TimeUnit.SECONDS);
scheduler.schedule(r2, 60, TimeUnit.SECONDS);

Note that the threads can't do anything on the UI, but you did mention a "single service", so i'm assuming you're doing all non-UI things anyway.


问:
Why Stream.of(1, 2, 3).max(Comparator::comparingInt) can not be compiled?
```<code>1: Stream.of(1, 2, 3).max(Comparator::comparingInt)
2: Stream.of(1, 2, 3).max(Integer::compare)
</code>```

why the second line can be used, but the first way can not ?

答:
Comparator::comparingInt is a method reference to the method:

```<code>public static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor)
</code>```

So you can only pass a Comparator::comparingInt to methods that accept a functional interface with a signature similar to

```<code>Function<ToIntFunction<T>, Comparator<T>>
</code>```

which Stream.max is not.

You most likely wanted to call the method comparingInt, instead of using a method reference:

```<code>Stream.of(1, 2, 3).max(Comparator.comparingInt(x -> x))
</code>```

Integer::compare on the other hand is a method reference to the method:

```<code>public static int compare(int x, int y)
</code>```

Which matches the signature of the functional interface that max needs - Comparator<Integer>.

Body:
1: Stream.of(1, 2, 3).max(Comparator::comparingInt)
2: Stream.of(1, 2, 3).max(Integer::compare)

why the second line can be used, but the first way can not ?

Body:
Comparator::comparingInt is a method reference to the method:

public static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor)

So you can only pass a Comparator::comparingInt to methods that accept a functional interface with a signature similar to

Function<ToIntFunction<T>, Comparator<T>>

which Stream.max is not.

You most likely wanted to call the method comparingInt, instead of using a method reference:

Stream.of(1, 2, 3).max(Comparator.comparingInt(x -> x))

Integer::compare on the other hand is a method reference to the method:

public static int compare(int x, int y)

Which matches the signature of the functional interface that max needs - Comparator<Integer>.


问:
How to add additional styles to a window which is already using a style template
How to add additional styles to window style when it already using a style like in below?

```<code>    <Style x:Key="MyWindowStyle" TargetType="Window">
        <Setter Property="Control.Background" Value="PaleGreen"/>
        <Setter Property="Window.Title" Value="Styled Window"/>
    </Style>
</code>```

My main window is:

```<code><Window x:Class="Binding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Binding"
        mc:Ignorable="d"
        Style="{StaticResource MyWindowStyle}"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>
        <Label  Content="Test Window" />
    </StackPanel>
</Window>
</code>```

So I want to use MyWindowStyle but say I also want to add additional styles like adding the following:

```<code>        <Setter Property="BorderThickness" Value="3"/>
        <Setter Property="BorderBrush" Value="Red"/>
</code>```

How do I do that? I can't figure out the syntax.

答:
Problem is that when you use StaticResouce the resource has to be initialized before the usage.

In your case you have the resource inside the window therefor it is not initialized before the window is initialized.

Use DynamicResource instead and it will work:

```<code><Window x:Class="Binding.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Binding"
    mc:Ignorable="d"
    Style="{DynamicResource MyWindowStyle}"
    Title="MainWindow" Height="450" Width="800">

<Window.Resources>
    <Style x:Key="MyWindowStyle" TargetType="{x:Type Window}">
        <Setter Property="Control.Background" Value="PaleGreen"/>
        <Setter Property="Window.Title" Value="Styled Window"/>
        <Setter Property="BorderThickness" Value="3"/>
        <Setter Property="BorderBrush" Value="Red"/>
    </Style>
</Window.Resources>

   <StackPanel>
      <Label  Content="Test Window" />
   </StackPanel>
</Window>
</code>```

See more here about WPF Resources.

Body:
How to add additional styles to window style when it already using a style like in below?

My main window is:

<Window x:Class="Binding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Binding"
        mc:Ignorable="d"
        Style="{StaticResource MyWindowStyle}"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>

    </StackPanel>
</Window>

So I want to use MyWindowStyle but say I also want to add additional styles like adding the following:

        <Setter Property="BorderThickness" Value="3"/>
        <Setter Property="BorderBrush" Value="Red"/>

How do I do that? I can't figure out the syntax.

Body:
Problem is that when you use StaticResouce the resource has to be initialized before the usage.

In your case you have the resource inside the window therefor it is not initialized before the window is initialized.

Use DynamicResource instead and it will work:

<Window x:Class="Binding.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Binding"
    mc:Ignorable="d"
    Style="{DynamicResource MyWindowStyle}"
    Title="MainWindow" Height="450" Width="800">

<Window.Resources>
    <Style x:Key="MyWindowStyle" TargetType="{x:Type Window}">
        <Setter Property="Control.Background" Value="PaleGreen"/>
        <Setter Property="Window.Title" Value="Styled Window"/>
        <Setter Property="BorderThickness" Value="3"/>
        <Setter Property="BorderBrush" Value="Red"/>
    </Style>
</Window.Resources>

   <StackPanel>
      <Label  Content="Test Window" />
   </StackPanel>
</Window>

See more here about WPF Resources.


问:
Haskell : Possible cause: ‘(:)’ is applied to too many arguments
I‘ve created a nested function which fails at the third nesting. I fail to understand why this pattern holds up for the previous two nests but not the third. I'm attempting to recursively work through the list to add the items in the list together

```<code>module Nests
(nest1,nest2,nest3) where

nest1 :: (Num a) => [a] -> [a] -> [a]
nest1 _ [] = []
nest1 [] _ = []
nest1 (xs:ls1) (xt:ls2) = (xs+xt):nest1 ls1 ls2

nest2 :: (Num a) => [[a]] -> [[a]] -> [[a]]
nest2 _ [] = []
nest2 [] _ = []
nest2 (xs:ls1) (xt:ls2) = (nest1 xs xt):nest2 ls1 ls2

nest3 :: (Num a) => [[[a]]] -> [[[a]]] -> [[[a]]]
nest3 (xs:xt:ls)
    | length ls <= 0 = []
    | otherwise = (nest2 xs xt):nest3 ls
</code>```

where compiled:

```<code>nests.hs:17:19: error:
    • Couldn't match expected type ‘[[[a]]] -> [[[a]]]’
                  with actual type ‘[[[a]]]’
    • Possible cause: ‘(:)’ is applied to too many arguments
      In the expression: (nest2 xs xt) : nest3 ls
      In an equation for ‘nest3’:
          nest3 (xs : xt : ls)
            | length ls <= 0 = []
            | otherwise = (nest2 xs xt) : nest3 ls
    • Relevant bindings include
        ls :: [[[a]]] (bound at nests.hs:15:14)
        xt :: [[a]] (bound at nests.hs:15:11)
        xs :: [[a]] (bound at nests.hs:15:8)
        nest3 :: [[[a]]] -> [[[a]]] -> [[[a]]] (bound at nests.hs:15:1)
   |
17 |     | otherwise = (nest2 xs xt):nest3 ls
   |                   ^^^^^^^^^^^^^^^^^^^^^^

nests.hs:17:33: error:
    • Couldn't match expected type ‘[[[a]]]’
                  with actual type ‘[[[a]]] -> [[[a]]]’
    • Probable cause: ‘nest3’ is applied to too few arguments
      In the second argument of ‘(:)’, namely ‘nest3 ls’
      In the expression: (nest2 xs xt) : nest3 ls
      In an equation for ‘nest3’:
          nest3 (xs : xt : ls)
            | length ls <= 0 = []
            | otherwise = (nest2 xs xt) : nest3 ls
    • Relevant bindings include
        ls :: [[[a]]] (bound at nests.hs:15:14)
        xt :: [[a]] (bound at nests.hs:15:11)
        xs :: [[a]] (bound at nests.hs:15:8)
        nest3 :: [[[a]]] -> [[[a]]] -> [[[a]]] (bound at nests.hs:15:1)
   |
17 |     | otherwise = (nest2 xs xt):nest3 ls
</code>```

答:
Regarding the question of why it says ‘(:)’ is applied to too many arguments:

Since your type signature tells Haskell that the function takes two arguments, but you only match for one, it will interpret it as a function returning a function, kind of like in point free style

For example like this

```<code>plus :: Int -> Int -> Int
plus x = (+) x
</code>```

which is equivalent to these

```<code>plus' :: Int -> Int -> Int
plus' x y = (+) x y
plus'' :: Int -> Int -> Int
plus'' = (+)

</code>```

So, in this case, your function is equivalent to

```<code>nest3 :: (Num a) => [[[a]]] -> [[[a]]] -> [[[a]]]
nest3 (xs:xt:ls) z
    | length ls <= 0 = [] z
    | otherwise = ((nest2 xs xt):nest3 ls) z
-- or
--  | otherwise = (:) (nest2 xs xt) (nest3 ls) z
</code>```

Which explains why it thinks (:) might be applied to too many arguments.

Body:
I‘ve created a nested function which fails at the third nesting. I fail to understand why this pattern holds up for the previous two nests but not the third. I'm attempting to recursively work through the list to add the items in the list together

module Nests
(nest1,nest2,nest3) where

nest1 :: (Num a) => [a] -> [a] -> [a]
nest1 _ [] = []
nest1 [] _ = []
nest1 (xs:ls1) (xt:ls2) = (xs+xt):nest1 ls1 ls2

nest2 :: (Num a) => [[a]] -> [[a]] -> [[a]]
nest2 _ [] = []
nest2 [] _ = []
nest2 (xs:ls1) (xt:ls2) = (nest1 xs xt):nest2 ls1 ls2

nest3 :: (Num a) => [[[a]]] -> [[[a]]] -> [[[a]]]
nest3 (xs:xt:ls)
    | length ls <= 0 = []
    | otherwise = (nest2 xs xt):nest3 ls

where compiled:

nests.hs:17:19: error:
    • Couldn't match expected type ‘[[[a]]] -> [[[a]]]’
                  with actual type ‘[[[a]]]’
    • Possible cause: ‘(:)’ is applied to too many arguments
      In the expression: (nest2 xs xt) : nest3 ls
      In an equation for ‘nest3’:
          nest3 (xs : xt : ls)
            | length ls <= 0 = []
            | otherwise = (nest2 xs xt) : nest3 ls
    • Relevant bindings include
        ls :: [[[a]]] (bound at nests.hs:15:14)
        xt :: [[a]] (bound at nests.hs:15:11)
        xs :: [[a]] (bound at nests.hs:15:8)
        nest3 :: [[[a]]] -> [[[a]]] -> [[[a]]] (bound at nests.hs:15:1)
   |
17 |     | otherwise = (nest2 xs xt):nest3 ls
   |                   ^^^^^^^^^^^^^^^^^^^^^^

nests.hs:17:33: error:
    • Couldn't match expected type ‘[[[a]]]’
                  with actual type ‘[[[a]]] -> [[[a]]]’
    • Probable cause: ‘nest3’ is applied to too few arguments
      In the second argument of ‘(:)’, namely ‘nest3 ls’
      In the expression: (nest2 xs xt) : nest3 ls
      In an equation for ‘nest3’:
          nest3 (xs : xt : ls)
            | length ls <= 0 = []
            | otherwise = (nest2 xs xt) : nest3 ls
    • Relevant bindings include
        ls :: [[[a]]] (bound at nests.hs:15:14)
        xt :: [[a]] (bound at nests.hs:15:11)
        xs :: [[a]] (bound at nests.hs:15:8)
        nest3 :: [[[a]]] -> [[[a]]] -> [[[a]]] (bound at nests.hs:15:1)
   |
17 |     | otherwise = (nest2 xs xt):nest3 ls

Body:
Regarding the question of why it says ‘(:)’ is applied to too many arguments:

Since your type signature tells Haskell that the function takes two arguments, but you only match for one, it will interpret it as a function returning a function, kind of like in point free style

For example like this

plus :: Int -> Int -> Int
plus x = (+) x

which is equivalent to these

plus' :: Int -> Int -> Int
plus' x y = (+) x y
plus'' :: Int -> Int -> Int
plus'' = (+)

So, in this case, your function is equivalent to

nest3 :: (Num a) => [[[a]]] -> [[[a]]] -> [[[a]]]
nest3 (xs:xt:ls) z
    | length ls <= 0 = [] z
    | otherwise = ((nest2 xs xt):nest3 ls) z
-- or
--  | otherwise = (:) (nest2 xs xt) (nest3 ls) z

Which explains why it thinks (:) might be applied to too many arguments.


问:
Is it possible to run a particular line of Python code instead of the whole script in Thonny?
I just installed Thonny and took a look at some beginner guides. I can easily run whole script by pressing "play" button (or pressing F5). However I could not figure out how to run only some particular lines in the script.</p>

答: In Thonny there is a ‘de-bugger’ button at the top (or f6) and if you press that you run through your code one line at a time. It is extremely useful for when you are trying to find out where your code goes wrong. I hope you find this helpful :).</p>


问:
Sorting an array of objects based on string property in Typescript
I have an array of objects like so:

```<code>0: {id: "743", name: "F"}
1: {id: "786", name: "S"}
2: {id: "903", name: "B"}
3: {id: "988", name: "L"}
4: {id: "1202", name: "S"}
5: {id: "1355", name: "H"}
6: {id: "1374", name: "R"}
</code>```

And I need to sort the array of objects based on the 'name' property.

I have searched around for the answer and have tried each of them out but with no joy.
The two main answers I came across were:

```<code>Array.sort((leftSide, rightSide): number => {
            if (leftSide.name.toLowerCase() < rightSide.name.toLowerCase()) return -1;
            if (leftSide.name.toLowerCase() > rightSide.name.toLowerCase()) return 1;
            return 0;
        });
</code>```

and

```<code>Array.sort((a, b) => a.name.localeCompare(b.name))
</code>```

both of these just give me the same unsorted array output. Is there any other way to do this? I am using Angular 7.

Full code:

```<code>getDeviceBrands(): void {
        this.deviceBrands = new Array<DeviceBrand>();
        const parentNodeId = 0;

        this.chartsService.getCatalogNodes(parentNodeId, this.catalogName).subscribe(catalogNodes => {
            catalogNodes.forEach(n => {
                this.deviceBrands.push({
                    id: n.CatalogNodeId.toString(),
                    name: n.Name
                });
            });
        });

        console.log(this.deviceBrands);

        const sorted = this.deviceBrands.sort((a, b) => a.name < b.name ? -1 : 1);

        console.log(sorted);
    }
</code>```

答:
I'm not sure why the above doesn't work for you; but the following works for me:

const x = [
  { id: "743", name: "F" },
  { id: "786", name: "S" },
  { id: "903", name: "B" },
  { id: "988", name: "L" },
  { id: "1202", name: "S" },
  { id: "1355", name: "H" },
  { id: "1374", name: "R" },
];

const sorted = x.sort((a, b) => a.name < b.name ? -1 : 1);

console.log(sorted);
```

<p>From running your code, it seems like it ought to work as well. I'm guessing from the example you've shown that you're using the array in a variable named <code>Array</code>, which is not a good idea, as <code>Array</code> is already used in javascript.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const Array = [
  { id: "743", name: "F" },
  { id: "786", name: "S" },
  { id: "903", name: "B" },
  { id: "988", name: "L" },
  { id: "1202", name: "S" },
  { id: "1355", name: "H" },
  { id: "1374", name: "R" },
];

const sorted = Array.sort((leftSide, rightSide) => {
    if (leftSide.name.toLowerCase() < rightSide.name.toLowerCase()) return -1;
    if (leftSide.name.toLowerCase() > rightSide.name.toLowerCase()) return 1;
    return 0;
});

console.log(sorted);</code>```

Body:
I have an array of objects like so:

0: {id: "743", name: "F"}
1: {id: "786", name: "S"}
2: {id: "903", name: "B"}
3: {id: "988", name: "L"}
4: {id: "1202", name: "S"}
5: {id: "1355", name: "H"}
6: {id: "1374", name: "R"}

And I need to sort the array of objects based on the 'name' property.

I have searched around for the answer and have tried each of them out but with no joy.
The two main answers I came across were:

Array.sort((leftSide, rightSide): number => {
            if (leftSide.name.toLowerCase() < rightSide.name.toLowerCase()) return -1;
            if (leftSide.name.toLowerCase() > rightSide.name.toLowerCase()) return 1;
            return 0;
        });

and

Array.sort((a, b) => a.name.localeCompare(b.name))

both of these just give me the same unsorted array output. Is there any other way to do this? I am using Angular 7.

Full code:

getDeviceBrands(): void {
        this.deviceBrands = new Array<DeviceBrand>();
        const parentNodeId = 0;

        this.chartsService.getCatalogNodes(parentNodeId, this.catalogName).subscribe(catalogNodes => {
            catalogNodes.forEach(n => {
                this.deviceBrands.push({
                    id: n.CatalogNodeId.toString(),
                    name: n.Name
                });
            });
        });

        console.log(this.deviceBrands);

        const sorted = this.deviceBrands.sort((a, b) => a.name < b.name ? -1 : 1);

        console.log(sorted);
    }

Body:
I'm not sure why the above doesn't work for you; but the following works for me:

const x = [
  { id: "743", name: "F" },
  { id: "786", name: "S" },
  { id: "903", name: "B" },
  { id: "988", name: "L" },
  { id: "1202", name: "S" },
  { id: "1355", name: "H" },
  { id: "1374", name: "R" },
];

const sorted = x.sort((a, b) => a.name < b.name ? -1 : 1);

console.log(sorted);

From running your code, it seems like it ought to work as well. I'm guessing from the example you've shown that you're using the array in a variable named Array, which is not a good idea, as Array is already used in javascript.

const Array = [
  { id: "743", name: "F" },
  { id: "786", name: "S" },
  { id: "903", name: "B" },
  { id: "988", name: "L" },
  { id: "1202", name: "S" },
  { id: "1355", name: "H" },
  { id: "1374", name: "R" },
];

const sorted = Array.sort((leftSide, rightSide) => {
    if (leftSide.name.toLowerCase() < rightSide.name.toLowerCase()) return -1;
    if (leftSide.name.toLowerCase() > rightSide.name.toLowerCase()) return 1;
    return 0;
});

console.log(sorted);


问:
Laravel replicate multiple rows didn't work
I want to replicate multiple relational rows to the same table with the diff job id.
But it doesn't work.

Here is my code

```<code>$parentJobUnits = Unit::where('job_id',$jobId)->get();  //may be single or multiple rows for units.

$JobCopy = $job->replicate()->save();    //main job copied for new units.

$partsCopy = array_map(function(Unit $unit) use($JobCopy)
{

     $newUnit = $unit->replicate();
     $newUnit->job_id = $JobCopy->id;
     return $newUnit->save();

}, $parentJobUnits);
</code>```

The above code is not working for multiple row replication.

答:
replicate() function does not work on get() function. It only works with find() function.

```<code>$parentJobUnits = Unit::where('job_id',$jobId)->get();

foreach($parentJobUnits as $key => $value)
{
    $new_unit = Unit::find($value->id)->replicate(); // $value->id is your primary key
    $new_unit->save();
}
</code>```

It will replicate the multiple rows.

Body:
I want to replicate multiple relational rows to the same table with the diff job id.
But it doesn't work.

Here is my code

$parentJobUnits = Unit::where('job_id',$jobId)->get();  //may be single or multiple rows for units.

$JobCopy = $job->replicate()->save();    //main job copied for new units.

$partsCopy = array_map(function(Unit $unit) use($JobCopy)
{

     $newUnit = $unit->replicate();
     $newUnit->job_id = $JobCopy->id;
     return $newUnit->save();

}, $parentJobUnits);

The above code is not working for multiple row replication.

Body:
replicate() function does not work on get() function. It only works with find() function.

$parentJobUnits = Unit::where('job_id',$jobId)->get();

foreach($parentJobUnits as $key => $value)
{
    $new_unit = Unit::find($value->id)->replicate(); // $value->id is your primary key
    $new_unit->save();
}

It will replicate the multiple rows.


问:
Will the thread exit automatically when `func` finishes?
Is calling pthread_exit explicitly from the thread routine required?

Example code:

```<code>pthread_create(&pth, NULL, (void *)func, parg);

... func() {
   ...
   //do I have to call pthread_exit() here?
   return 0;
}
</code>```

答:
The pthread_create documentation says:

If the start_routine returns, the effect is as if there was an implicit call to pthread_exit() using the return value of start_routine as the exit status.

So no, no need to call it explicitly.

Body:
Is calling pthread_exit explicitly from the thread routine required?

Example code:

pthread_create(&pth, NULL, (void *)func, parg);

... func() {
   ...
   //do I have to call pthread_exit() here?
   return 0;
}