问:
Javascript method to download generated file without replacing the url
I am working on generating a text & sql file when the user clicks on Download from the query displayed in a text area on the same form. I have written the following code. But the issue is that, the URL is being replaced and the entire page is automatically refreshed after the download. Due to this, continuing operations won't be able to be performed.

Javascript Method

```<code>function download() {
      var element = document.createElement('a');
      var filename = document.getElementById("filenameInput").value;
      var text = document.getElementById("runquerytext").value;
      element.setAttribute('href', 'data:text/plain;charset=utf-8,' + text);
      element.setAttribute('download', filename);

      element.style.display = 'none';
      document.body.appendChild(element);

      element.click();

      document.body.removeChild(element);
}
</code>```

Any suggestions on how I can download the generated file without reloading/ changing the uri will be much appreciated.

答:
If you want someone to download the file without refreshing the page, I would suggest you to use an iframe. The page is redirecting because a  "a" tag redirects the page upon clicking it. So to solve that generate dynamic iframe tag with javascript or an image tag. For example:</p>

```<code>    function download() {
     var element = document.createElement('iframe');
     var filename = document.getElementById("filenameInput").value;
     var text = document.getElementById("runquerytext").value;
     element.setAttribute('src', 'data:application/octet-stream;charset=utf-8,' + text);
     element.setAttribute('download', filename);
     element.style.display = 'none';
     document.body.appendChild(element);
    }
</code>```

Body:
I am working on generating a text & sql file when the user clicks on Download from the query displayed in a text area on the same form. I have written the following code. But the issue is that, the URL is being replaced and the entire page is automatically refreshed after the download. Due to this, continuing operations won't be able to be performed.

Javascript Method

function download() {
      var element = document.createElement('a');
      var filename = document.getElementById("filenameInput").value;
      var text = document.getElementById("runquerytext").value;
      element.setAttribute('href', 'data:text/plain;charset=utf-8,' + text);
      element.setAttribute('download', filename);

      element.style.display = 'none';
      document.body.appendChild(element);

      element.click();

      document.body.removeChild(element);
}

Any suggestions on how I can download the generated file without reloading/ changing the uri will be much appreciated.

Body:
If you want someone to download the file without refreshing the page, I would suggest you to use an iframe. The page is redirecting because a  "a" tag redirects the page upon clicking it. So to solve that generate dynamic iframe tag with javascript or an image tag. For example:

    function download() {
     var element = document.createElement('iframe');
     var filename = document.getElementById("filenameInput").value;
     var text = document.getElementById("runquerytext").value;
     element.setAttribute('src', 'data:application/octet-stream;charset=utf-8,' + text);
     element.setAttribute('download', filename);
     element.style.display = 'none';
     document.body.appendChild(element);
    }


来源: stackexchange

问:
Is there any way to increase the number limit of double type in Swift?
I'm try to filter my array and sum the amount. It works but when the number is above 999.99, it will getting nil. Is there any way to increase the number limit of double type? Is it possible?

largest number: 100,000,000.00

```<code>incomeFilter = record.filter { $0.recordtype!.contains("收入") && $0.createdAt! == recordItem.createdAt!}
let incomeSum = incomeFilter.map{Double($0.amount!.dropFirst()) ?? 0.00}.reduce(0, +)
//[9.99, nil]
</code>```

Other than that, I'm also trying to convert it to Number.

But I found that I can't use the .dropFirst() function. I got this error Cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String' after I delete it, It show another error Cannot invoke 'reduce' with an argument list of type '(Int, _)'

How to fix it?

```<code>let fmt = NumberFormatter()
fmt.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale!
fmt.maximumFractionDigits = 4
fmt.minimumFractionDigits = 4
let incomeSum = incomeFilter.map{fmt.number(from: $0.amount!) ?? 0.00}.reduce(0, +)
</code>```

答:
Actually both dropFirst() and reduce(_:_) are supposed to work with this syntax. Is the code in the question the real code?

This works in a Playground

```<code>let array = ["\n1.2", "\n3.5", "\n6.7"]
let incomeSum = array.map{Double($0.dropFirst()) ?? 0.00}.reduce(0, +)
print(incomeSum) // 11.4
</code>```

To fix the Cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String' error create a new string from the result (e.g. String($0.amount!.dropFirst()))

I don't understand the second error – which indicates a type mismatch – since literal 0 is treated both as Int and Double

ContentLicense: CC BY-SA 3.0

Body:
I'm try to filter my array and sum the amount. It works but when the number is above 999.99, it will getting nil. Is there any way to increase the number limit of double type? Is it possible?

largest number: 100,000,000.00

incomeFilter = record.filter { $0.recordtype!.contains("收入") && $0.createdAt! == recordItem.createdAt!}
let incomeSum = incomeFilter.map{Double($0.amount!.dropFirst()) ?? 0.00}.reduce(0, +)
//[9.99, nil]

Other than that, I'm also trying to convert it to Number.

But I found that I can't use the .dropFirst() function. I got this error Cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String' after I delete it, It show another error Cannot invoke 'reduce' with an argument list of type '(Int, _)'

How to fix it?

let fmt = NumberFormatter()
fmt.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale!
fmt.maximumFractionDigits = 4
fmt.minimumFractionDigits = 4
let incomeSum = incomeFilter.map{fmt.number(from: $0.amount!) ?? 0.00}.reduce(0, +)

Body:
Actually both dropFirst() and reduce(_:_) are supposed to work with this syntax. Is the code in the question the real code?

This works in a Playground

let array = ["\n1.2", "\n3.5", "\n6.7"]
let incomeSum = array.map{Double($0.dropFirst()) ?? 0.00}.reduce(0, +)
print(incomeSum) // 11.4

To fix the Cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String' error create a new string from the result (e.g. String($0.amount!.dropFirst()))

I don't understand the second error – which indicates a type mismatch – since literal 0 is treated both as Int and Double


问:
HTML & CSS - Links doesn't work
I have made a very simple website using HTML and CSS, I have added a few links as well but only one of the links actually work. There are 4 links in total and only the one at the bottom of the code will work. Please help. This is my HTML code:

html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video {  margin: 0;  padding: 0;  border: 0;  font-size: 100%;  font: inherit;  vertical-align: baseline;}

/* HTML5 display-role reset for older browsers */

article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
  display: block;
}

body {
  line-height: 1;
  font: 25px 'Open Sans', Arial, Helvetica, sans-serif;
}

ol,ul {
  list-style: none;
}

blockquote,q {
  quotes: none;
}

blockquote:before,blockquote:after,q:before,q:after {
  content: '';
  content: none;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

.nav {
  float: left;
}

.home {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 1200px;
}

.faq {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 900px;
}

.shop {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 580px;
}

.contact {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 200px;
}

html {
  box-sizing: border-box;
}

*,
*:before,*:after {
  box-sizing: inherit;
}

a {
  text-decoration: none;
}

.header {
  text-align: center;
}

.hemsidan {
  background: #ffffff url(../images/hemsidan.png)no-repeat 50% 50%;
  height: 1389px;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header class="header">
  <div class="container">
    <div class="hemsidan"><img src="images/hemsidan.png" height="1389" width="1366" alt=""></div>
    <div class="centered">Centered</div>
    <nav>
      <ul class="nav">
        <li class="home">Home</li>
        <li class="faq">FAQ</li>
        <li class="shop">Shop</li>
        <li class="contact">Contact us</li>
      </ul>
    </nav>
  </div>
</header></code>```

I am very new to HTML and CSS so forgive me for the horrible coding, I just want the links to work.

答:
I think there isn't any problem with the links. I suppose as you're positioning them as absolute in the container they are overlapping one over the other and what you are actually clicking is some div or element blank area.

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
font: 25px 'Open Sans', Arial, Helvetica, sans-serif;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
.nav {
float: left;
}
.home {
//position: absolute;
//top: 173px;
width: 100%;
padding-right: 1200px;
}
.faq{
//position: absolute;
//top: 173px;
width: 100%;
padding-right: 900px;
}
.shop{
//position: absolute;
//top: 173px;
width: 100%;
padding-right: 580px;
}
.contact{
//position: absolute;
//top: 173px;
width: 100%;
padding-right: 200px;
}
html {
box-sizing: border-box;
}
*, *:before, *:after {
 box-sizing: inherit;
}
a {
text-decoration: none;
}
.header {
text-align: center;
}
.hemsidan{
background: #ffffff url(../images/hemsidan.png)no-repeat 50% 50%;
height: 1389px;
width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hemsidan</title>
<link rel="stylesheet" href="css/style.css">
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>

<body>
<header class="header">
<div class="container">
<div class="hemsidan"><img src="images/hemsidan.png" height="1389" width="1366" alt=""></div>
<div class="centered">Centered</div>
<nav>
<ul class="nav">
<li class="home">Home</li>
<li class="faq">FAQ</li>
<li class="shop">Shop</li>
<li class="contact">Contact us</li>

</ul>
</nav>
</div>
</header>

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

Title: HTML & CSS - Links doesn't work

Body:
I have made a very simple website using HTML and CSS, I have added a few links as well but only one of the links actually work. There are 4 links in total and only the one at the bottom of the code will work. Please help. This is my HTML code:

html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video {  margin: 0;  padding: 0;  border: 0;  font-size: 100%;  font: inherit;  vertical-align: baseline;}

/* HTML5 display-role reset for older browsers */

article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
  display: block;
}

body {
  line-height: 1;
  font: 25px 'Open Sans', Arial, Helvetica, sans-serif;
}

ol,ul {
  list-style: none;
}

blockquote,q {
  quotes: none;
}

blockquote:before,blockquote:after,q:before,q:after {
  content: '';
  content: none;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

.nav {
  float: left;
}

.home {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 1200px;
}

.faq {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 900px;
}

.shop {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 580px;
}

.contact {
  position: absolute;
  top: 173px;
  width: 100%;
  padding-right: 200px;
}

html {
  box-sizing: border-box;
}

*,
*:before,*:after {
  box-sizing: inherit;
}

a {
  text-decoration: none;
}

.header {
  text-align: center;
}

.hemsidan {
  background: #ffffff url(../images/hemsidan.png)no-repeat 50% 50%;
  height: 1389px;
  width: 100%;
}

Centered

Home

FAQ

Shop

Contact us

I am very new to HTML and CSS so forgive me for the horrible coding, I just want the links to work.

Body:
I think there isn't any problem with the links. I suppose as you're positioning them as absolute in the container they are overlapping one over the other and what you are actually clicking is some div or element blank area.

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
font: 25px 'Open Sans', Arial, Helvetica, sans-serif;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
.nav {
float: left;
}
.home {
//position: absolute;
//top: 173px;
width: 100%;
padding-right: 1200px;
}
.faq{
//position: absolute;
//top: 173px;
width: 100%;
padding-right: 900px;
}
.shop{
//position: absolute;
//top: 173px;
width: 100%;
padding-right: 580px;
}
.contact{
//position: absolute;
//top: 173px;
width: 100%;
padding-right: 200px;
}
html {
box-sizing: border-box;
}
*, *:before, *:after {
 box-sizing: inherit;
}
a {
text-decoration: none;
}
.header {
text-align: center;
}
.hemsidan{
background: #ffffff url(../images/hemsidan.png)no-repeat 50% 50%;
height: 1389px;
width: 100%;
}

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hemsidan</title>
<link rel="stylesheet" href="css/style.css">
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>

<body>
<header class="header">
<div class="container">
<div class="hemsidan"><img src="images/hemsidan.png" height="1389" width="1366" alt=""></div>
<div class="centered">Centered</div>
<nav>
<ul class="nav">
<li class="home"><a  href="#">Home</a></li>
<li class="faq"><a href="http://pages.ebay.com/seller-center/faq/index.html">FAQ</a></li>
<li class="shop"><a href="https://www.blocket.se/">Shop</a></li>
<li class="contact"><a href="https://twitter.com/realdonaldtrump">Contact us</a></li>

</ul>
</nav>
</div>
</header>

</body>
</html>


问:
Printing very large BigIntegers to a file in Java
I'm trying to print a very large BigInteger to a .txt file, but when the number reaches a certain size, it prints nothing. Code:

```<code>BigInteger bi = new BigInteger("16777216");
int exponent = 1000000;
bi = bi.pow(exponent);

String txtToPrint = bi.toString();
sendToFile(txtToPrint, "output.txt");

private static void sendToFile(String txtToPrint, String fileName) {

        try {

            FileWriter fileWriter = new FileWriter(fileName);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(txtToPrint);

            bufferedWriter.close();
        }
        catch(IOException e) {
            System.out.println("Error writing to file '" + fileName + "'");
        }

}
</code>```

Whenever the exponent is greater than 566 the output file is empty, instead of containing the number. The goal is to have an exponent of 1 000 000, or even greater.

I thought BigInteger did not have a size limit, so my question is: What limit am I exceeding and is there a way to solve this problem?

EDIT: When trying to flush and close the filewriter, I got this exception:

```<code>java.io.IOException: Stream closed
at sun.nio.cs.StreamEncoder.ensureOpen(Unknown Source)
at sun.nio.cs.StreamEncoder.flush(Unknown Source)
at java.io.OutputStreamWriter.flush(Unknown Source)
at PrintInt.main(PrintInt.java:4
</code>```

EDIT: The problem only occurs when running the program in Eclipse, I tried exporting it to an external jar, and everything worked just fine. I am using Eclipse Mars.1 Release (4.5.1) and Java jre1.8.0_131 and Cp1252 encoding.

答: Yes its used when we need very big numbers with arbitrary precision. It's important to note that "arbitrary" precision or number of digits does not mean "unlimited": it means that the number of digits in a number or number of digits of precision in a calculation is limited by memory and/or defined limits to precision that we specify.</p>

Body:
I'm trying to print a very large BigInteger to a .txt file, but when the number reaches a certain size, it prints nothing. Code:

BigInteger bi = new BigInteger("16777216");
int exponent = 1000000;
bi = bi.pow(exponent);

String txtToPrint = bi.toString();
sendToFile(txtToPrint, "output.txt");

private static void sendToFile(String txtToPrint, String fileName) {

        try {

            FileWriter fileWriter = new FileWriter(fileName);
            BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(txtToPrint);

            bufferedWriter.close();
        }
        catch(IOException e) {
            System.out.println("Error writing to file '" + fileName + "'");
        }

}

Whenever the exponent is greater than 566 the output file is empty, instead of containing the number. The goal is to have an exponent of 1 000 000, or even greater.

I thought BigInteger did not have a size limit, so my question is: What limit am I exceeding and is there a way to solve this problem?

EDIT: When trying to flush and close the filewriter, I got this exception:

java.io.IOException: Stream closed
at sun.nio.cs.StreamEncoder.ensureOpen(Unknown Source)
at sun.nio.cs.StreamEncoder.flush(Unknown Source)
at java.io.OutputStreamWriter.flush(Unknown Source)
at PrintInt.main(PrintInt.java:4

EDIT: The problem only occurs when running the program in Eclipse, I tried exporting it to an external jar, and everything worked just fine. I am using Eclipse Mars.1 Release (4.5.1) and Java jre1.8.0_131 and Cp1252 encoding.


问:
Bootstrap 4 navbar doesn't show Toggler
I created an Angular 5 application and included Bootstrap 4 via index.html. I made a basic navbar component and tried to include it in my app. But in responsive mode, I am not able to see the toggler, it appears white but when inspecting I can see it as well as clicking on it also shows the menu. Why is it not being displayed properly?

I am using a simple navbar like below:

```<code><nav class="navbar navbar-expand-lg shift">
  <a class="navbar-brand" href="#">
    <img src="logo.png" alt="Brand Logo" />
  </a>
  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown"
    aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNavDropdown">
    <ul class="nav nav-pills ml-auto">
      <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Exams</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Contact</a>
      </li>
    </ul>
  </div>
</nav>
</code>```

Here is my fiddle: jsfiddle

答:
In responsive mode, Toggler icon not showing because this icon class has some dependency. If you change code like this then it will be show:

```<code><nav class="navbar navbar-light">
</code>```

navbar-toggler-icon class have parent class. so, you should add parent class
navbar-light, navbar-dark

Title: Bootstrap 4 navbar doesn't show Toggler

Body:
I created an Angular 5 application and included Bootstrap 4 via index.html. I made a basic navbar component and tried to include it in my app. But in responsive mode, I am not able to see the toggler, it appears white but when inspecting I can see it as well as clicking on it also shows the menu. Why is it not being displayed properly?

I am using a simple navbar like below:

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

  </button>

        Features

        Exams

        Contact

Here is my fiddle: jsfiddle

Body:
In responsive mode, Toggler icon not showing because this icon class has some dependency. If you change code like this then it will be show:

<nav class="navbar navbar-light">

navbar-toggler-icon class have parent class. so, you should add parent class
navbar-light, navbar-dark


问:
JavaScript inside Ruby code
I have a question. Maybe little stupid but I want to be sure.
I know, how to hand on code from Ruby to JS and work on it. I mean js.erb file.

Simple example:

```<code><% ruby_var = 15 %>
var jsVar = <%= ruby_var %>;
// jsVar => 15
</code>```

It works.

On the same js.erb file I would like to do it reverse:

```<code>var jsVar = 15;
<% ruby_var = jsVar %>
</code>```

I have no idea how I can do it. Is it possible?

Please advice.

答:
You can't do this at all and it's never needed.

Javascript is a client side code, that will be executed in client's browser. This code will NOT be executed on server, so you can't get anything in your ruby variable. When JavsScript will be executed on client side, there will be no ruby at all (all ruby scripts will be already turned into plain HTML/CSS/JS

Title: JavaScript inside Ruby code

Body:
I have a question. Maybe little stupid but I want to be sure.
I know, how to hand on code from Ruby to JS and work on it. I mean js.erb file.

Simple example:

<% ruby_var = 15 %>
var jsVar = <%= ruby_var %>;
// jsVar => 15

It works.

On the same js.erb file I would like to do it reverse:

var jsVar = 15;
<% ruby_var = jsVar %>

I have no idea how I can do it. Is it possible?

Please advice.


问:
No certificate is generated in .hfc-key-store
I'm using an AWS Ubuntu 16.04 LTS following Hyperledger Fabric readthedocs tutorial. I followed steps in "Writing Your First Applications". When I ran "node enrollAdmin.js", a eCert and key material is expected to be generated in a hfc-key-store directory, but nothing is generated in this folder, which means the folder is still empty after running the command. I looked into the code in this js file, in lines 54-55, only two arguments are provided, but from the API from this link:https://jimthematrix.github.io/FabricCAClient.html#enroll__anchor, the fabric_ca_client.enroll function should receive three arguments, which means the third argument 'csr' is not given in the js file. Strangely, no error information is shown after running the command, and the only information i got from the terminal is "store path: $mypath/hfc-key-store".

Any one knows what the problem occurs?

Thanks

答: After I switch node version from 6.12.0 to 6.9.5, this issue is resolved. Looks like the node version has to be 6.9.x</p>


问:
how to avoid cyclic dependency whle using constructor injection
I am using autowired annotation for the dependency injection in my app.
How can I avoid cyclic dependency while using constructor injection.</p>

```<code>public interface CustomUserRepository {
 void myCustom();
}

public interface UserRepository extends CustomUserRepository {
 ----
}

public class UserRepositoryImpl implements CustomUserRepository {

@Autowired UserRepository self;  //Here I have the Cyclic dependency

}
</code>```

答:
Spring does not support cyclic dependencies with constructor injection. The rationale is that an object must be fully initialized before it can be injected. </p>

<p>To resolve the issue make your circular dependency into a property. </p>

Body:
I am using autowired annotation for the dependency injection in my app.
How can I avoid cyclic dependency while using constructor injection.

public interface CustomUserRepository {
 void myCustom();
}

public interface UserRepository extends CustomUserRepository {
 ----
}

public class UserRepositoryImpl implements CustomUserRepository {

@Autowired UserRepository self;  //Here I have the Cyclic dependency

}

Body:
Spring does not support cyclic dependencies with constructor injection. The rationale is that an object must be fully initialized before it can be injected.

To resolve the issue make your circular dependency into a property.


问:
jsf databinding does not work
I am trying to create a page using richfaces, I created the following field

```<code><h:inputText value="#{petTest.pet.name}"/>
</code>```

faces-config:

```<code><managed-bean>
    <managed-bean-name>petTest</managed-bean-name>
    <managed-bean-class>petstore.PetTest</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
</managed-bean>
</code>```

managed bean:

```<code>package petstore;

public class PetTest {
    private Pet pet;

    public Pet getPet(){
        return pet;
    }

    public void setPet(Pet pet){
        this.pet = pet;
    }
}
</code>```

But I get a field and within it the literal value #{petTest.pet.name} instead of the value of the field. What am I doing wrong?

答:
Is your h:inputText part of a h:form like this:

```<code><h:form id="formId">
   ..
   <h:inputText value="#{petTest.pet.name}"/>
   ..
</h:form>
</code>```

Without a form h:inputText is not working.

ContentLicense: CC BY-SA 2.5

Title: jsf databinding does not work

Body:
I am trying to create a page using richfaces, I created the following field

<h:inputText value="#{petTest.pet.name}"/>

faces-config:

<managed-bean>
    <managed-bean-name>petTest</managed-bean-name>
    <managed-bean-class>petstore.PetTest</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
</managed-bean>

managed bean:

package petstore;

public class PetTest {
    private Pet pet;

    public Pet getPet(){
        return pet;
    }

    public void setPet(Pet pet){
        this.pet = pet;
    }
}

But I get a field and within it the literal value #{petTest.pet.name} instead of the value of the field. What am I doing wrong?

Body:
Is your h:inputText part of a h:form like this:

<h:form id="formId">
   ..
   <h:inputText value="#{petTest.pet.name}"/>
   ..
</h:form>

Without a form h:inputText is not working.


问:
Passing 3 textbox values to a javascript function from ASPX
I want to pass three textbox values to a javascript function. However its not working.Any help is really appreciated.This is what I have tried.</p>

```<code><asp:ImageButton ID="ibut_cheque2" runat="server" target="_blank"
OnClientClick='<%# string.Format("window.open(\"Product.aspx?pid=\" +
document.getElementById(\"{0}\").value & chdate=\" +
document.getElementById(\"{1}\").value & pname=\" +
document.getElementById(\"{2}\").value,
null,\"scrollbars=yes,top=10,left=10\", \"true\");",
Form.FindControl("txt_voucher").ClientID,
Form.FindControl("txtbox_chqdate").ClientID,
Form.FindControl("txtbox_chprovider").ClientID)%>'
AlternateText="Print" CssClass="btn5" ForeColor="White" ToolTip="Print Cheque" />
</code>```

答:
```<code>     <asp:Button ID="PrintCheck" runat="server" target="_blank"
     OnClientClick='openWindow()'   Text="Print Cheque" CssClass="btn5"
     ForeColor="White" Width="120px" ToolTip="Print Cheque" />

     <script type="text/javascript">
     function openWindow() {
     var payname = document.getElementById('<%=txtbox_chprovider.ClientID
      %>').value;
      var chdate = document.getElementById('<%=txtbox_chqdate.ClientID
      %>').value;
      var chamount = document.getElementById('<%=txt_chamount.ClientID
      %>').value;
    window.open("Product.aspx?payname=" + payname + "&chdate= " + chdate + "
    &chamount= " + chamount + "", "_blank",
    "toolbar=yes,scrollbars=yes,top=10,left=10", "true");
          };
</script>
</code>```

Body:
I want to pass three textbox values to a javascript function. However its not working.Any help is really appreciated.This is what I have tried.

<asp:ImageButton ID="ibut_cheque2" runat="server" target="_blank"
OnClientClick='<%# string.Format("window.open(\"Product.aspx?pid=\" +
document.getElementById(\"{0}\").value & chdate=\" +
document.getElementById(\"{1}\").value & pname=\" +
document.getElementById(\"{2}\").value,
null,\"scrollbars=yes,top=10,left=10\", \"true\");",
Form.FindControl("txt_voucher").ClientID,
Form.FindControl("txtbox_chqdate").ClientID,
Form.FindControl("txtbox_chprovider").ClientID)%>'
AlternateText="Print" CssClass="btn5" ForeColor="White" ToolTip="Print Cheque" />


问:
to which class does object belong
I wrote following in Scala REPL. I do not understand what REPL has created for me. Is c object of class Any? How can I find to which class c belongs to?

```<code>scala> object c
defined object c
</code>```

答: The class (type) of object c is c.type. By declaring an object in Scala you implicitly define both class and singleton object (Scala will generate those for you). Since class is not explicitly defined in source code, special object member called type exist to refer to object's class.

Title: to which class does object belong

Body:
I wrote following in Scala REPL. I do not understand what REPL has created for me. Is c object of class Any? How can I find to which class c belongs to?

scala> object c
defined object c


问:
android int to hex converting
I have to convert an int to an hex value. This is for example the int value:

```<code>int_value = -13516;
</code>```

To convert to a hex value i do:

```<code>hex_value = Integer.toHexString(int_value);
</code>```

The value that I should get is : -34CC (I don't know if i should make it positive).

The thing is that doing the conversion that way, the value that I get is: ffff cb34

Can't I use this function to make this conversion?

答:
```<code>String.format("#%06X", (0xFFFFFF & colorYellow));
</code>```

Output: #FFC107

Title: android int to hex converting

Body:
I have to convert an int to an hex value. This is for example the int value:

int_value = -13516;

To convert to a hex value i do:

hex_value = Integer.toHexString(int_value);

The value that I should get is : -34CC (I don't know if i should make it positive).

The thing is that doing the conversion that way, the value that I get is: ffff cb34

Can't I use this function to make this conversion?

Body:
String.format("#%06X", (0xFFFFFF & colorYellow));

Output: #FFC107


问:
Uploading to S3 using Python Requests
I'd like to upload xml's directly to S3 without the use of modules like boto, boto3, or tinys3.

So far I have written:

```<code> url = "https://my-test-s3.s3.amazonaws.com"
 with open(xml_file,'rb') as data:
     requests.put(url, data=data)
</code>```

and I've gone and head and set the AllowedOrigin on my S3 bucket to accept my server's address.

This does not error when running, however, it also does not seem to be uploading anything.

Any help would be appreciated --- I'd like to (a) get the thing to upload and (b) figure out how to apply AWSAccessKey and AWSSecretAccessKey to the request

答:
you need to install awscli following this documentation.
Then in a commandline shell, execute aws configure and follow the instruction.

to upload file, its much easier using boto

```<code>import boto3
s3 = boto3.resource('s3')
s3.meta.client.upload_file(xml_file, 'yourbucket', 'yours3filepath')
</code>```

Alternatively, you can use aws s3 cp command combined with python subprocess.

```<code>subprocess.call(["aws", "s3", "cp", xml_file, "yours3destination"])
</code>```

Title: Uploading to S3 using Python Requests

Body:
I'd like to upload xml's directly to S3 without the use of modules like boto, boto3, or tinys3.

So far I have written:

 url = "https://my-test-s3.s3.amazonaws.com"
 with open(xml_file,'rb') as data:
     requests.put(url, data=data)

and I've gone and head and set the AllowedOrigin on my S3 bucket to accept my server's address.

This does not error when running, however, it also does not seem to be uploading anything.

Any help would be appreciated --- I'd like to (a) get the thing to upload and (b) figure out how to apply AWSAccessKey and AWSSecretAccessKey to the request

Body:
you need to install awscli following this documentation.
Then in a commandline shell, execute aws configure and follow the instruction.

to upload file, its much easier using boto

import boto3
s3 = boto3.resource('s3')
s3.meta.client.upload_file(xml_file, 'yourbucket', 'yours3filepath')

Alternatively, you can use aws s3 cp command combined with python subprocess.

subprocess.call(["aws", "s3", "cp", xml_file, "yours3destination"])


问:
Vaadin Chart: How to use Global configuration
There is a Global configuration object, however I am not able to see how it can be used.

This is needed, for example, to set the timezoneOffset.

Since it does not apply for any specific chart, I would expect a static setting/getter somewhere, but I couldn't find a reference which uses it.

答:
It looks like something is missing and that class is not used at the moment. Can you create an issue in github.com/vaadin/charts/issues/new ?
Other global settings like Lang or Theme can be set as shown in this example

As a workaround you can execute javascript snippet shown in Global javadoc.
Check vaadin docs for executing javascript https://vaadin.com/docs/v8/framework/advanced/advanced-javascript.html

```<code>JavaScript.getCurrent().execute(
            "Highcharts.setOptions({"
            + "  global: {"
            + "    timezoneOffset:60"
            + "  }"
            + "});");
</code>```

Remember that timezoneOffset is in minutes

Body:
It looks like something is missing and that class is not used at the moment. Can you create an issue in github.com/vaadin/charts/issues/new ?
Other global settings like Lang or Theme can be set as shown in this example

As a workaround you can execute javascript snippet shown in Global javadoc.
Check vaadin docs for executing javascript https://vaadin.com/docs/v8/framework/advanced/advanced-javascript.html

JavaScript.getCurrent().execute(
            "Highcharts.setOptions({"
            + "  global: {"
            + "    timezoneOffset:60"
            + "  }"
            + "});");

Remember that timezoneOffset is in minutes


问:
Laravel: Eloquent 'more than' and 'lesser than'
I want a Database Query like this in query builder:

SELECT * FROM posts WHERE active = 1 AND published <= '{$now}' LIMIT 5

What I made:

```<code>$now = new Carbon;
$feed = Post::where([
        ['active' => 1],
        ['published' => $now]
    ])
    -> take(5)
    -> get()
    -> toArray();
</code>```

But it's like:

SELECT * FROM posts WHERE active = 1 AND published = '{$now}' LIMIT 5

How to make <, <=, >, >=, <> and LIKE statements with ::where method?

答:
use this

```<code>$feed = Post::where('active',1)
->where('published','<=',$now)
->take(5)
->get()
->toArray();
</code>```

Please see the manual :https://laravel.com/docs/master/queries#raw-expressions

Body:
I want a Database Query like this in query builder:

SELECT * FROM posts WHERE active = 1 AND published <= '{$now}' LIMIT 5

What I made:

$now = new Carbon;
$feed = Post::where([
        ['active' => 1],
        ['published' => $now]
    ])
    -> take(5)
    -> get()
    -> toArray();

But it's like:

SELECT * FROM posts WHERE active = 1 AND published = '{$now}' LIMIT 5

How to make <, <=, >, >=, <> and LIKE statements with ::where method?

Body:
use this

$feed = Post::where('active',1)
->where('published','<=',$now)
->take(5)
->get()
->toArray();

Please see the manual :https://laravel.com/docs/master/queries#raw-expressions


问:
Mysql query to retrieve single image from an array of images?
Table to store array of Images:

```<code>`products` and  `products_photos`

`products` includes only `id` field
`products_photos` includes `product_id` and `filename`
</code>```

Table values:

```<code>products
--------
id-6

id-7

products_photos
---------------
6 - filename1

6 - filename2

7 - filename3
</code>```

In these two table id 6 includes 2 images but i need to fetch only one image from that. How to write a query for that in mysql or laravel.

答:
If you want to get the latest (last added) image of the product then you can do the following way

NOTE : Instead of *, use the precise columns so that your query performs faster.

```<code>SELECT * FROM products_photos WHERE product_id = 6 ORDER BY products_photos.id DESC LIMIT 1;
</code>```

If you want to get the first (old added) image of the product then you can do the following way

```<code>SELECT * FROM products_photos WHERE product_id = 6 ORDER BY products_photos.id ASC LIMIT 1;
</code>```

Updated :  Query to get the list of all the records group

```<code>SELECT MAX(id) as id, photo_name FROM products_photos GROUP BY photo_name
</code>```

In case if you have more than one columns and want to get the latest record for that too then go for this

Eg. Considering that your having description column and want to get the MAX (latest) content than use MAX, if you need oldest use MIN

```<code>SELECT MAX(id) as id, photo_name, MAX(description) as description FROM products_photos GROUP BY photo_name
</code>```

Body:
Table to store array of Images:

`products` and  `products_photos`

`products` includes only `id` field
`products_photos` includes `product_id` and `filename`

Table values:

products
--------
id-6

id-7

products_photos
---------------
6 - filename1

6 - filename2

7 - filename3

In these two table id 6 includes 2 images but i need to fetch only one image from that. How to write a query for that in mysql or laravel.

Body:
If you want to get the latest (last added) image of the product then you can do the following way

NOTE : Instead of *, use the precise columns so that your query performs faster.

SELECT * FROM products_photos WHERE product_id = 6 ORDER BY products_photos.id DESC LIMIT 1;

If you want to get the first (old added) image of the product then you can do the following way

SELECT * FROM products_photos WHERE product_id = 6 ORDER BY products_photos.id ASC LIMIT 1;

Updated :  Query to get the list of all the records group

SELECT MAX(id) as id, photo_name FROM products_photos GROUP BY photo_name

In case if you have more than one columns and want to get the latest record for that too then go for this

Eg. Considering that your having description column and want to get the MAX (latest) content than use MAX, if you need oldest use MIN

SELECT MAX(id) as id, photo_name, MAX(description) as description FROM products_photos GROUP BY photo_name


问:
How to combine separated Koa-Routers with Typescript
I decided to split my routers by their purpose, so they look like this:

routers/homeRouter.ts

```<code>import * as Router from 'koa-router';

const router: Router = new Router();

router
    .get('/', async (ctx, next) => {
        ctx.body = 'hello world';
    });

export = router;
</code>```

routers/userRouter.ts

```<code>import * as Router from 'koa-router';
import UserController = require('../controller/userController');

const router: Router = new Router(
    {
        prefix: 'users'
    }
);

var userController = new UserController();

router
    .post('/user/:email/:password', userController.signUp);

export = router;
</code>```

With this, my app.ts has to import each of the routers one by one like this:

app.ts

```<code>import * as Koa from 'koa';
import * as homeRouter from './routers/homeRouter';
import * as userRouter from './routers/userRouter';
const app: Koa = new Koa();
app
    .use(homeRouter.routes())
    .use(homeRouter.allowedMethods());
app
    .use(userRouter.routes())
    .use(userRouter.allowedMethods());
app.listen(3000);
</code>```

But what I want is this:

app.ts

```<code>import * as Koa from 'koa';
import * as routers from './routers';
const app: Koa = new Koa();
app
    .use(routers.routes())
    .use(routers.allowedMethods());
app.listen(3000);
</code>```

I do not know how to export the routers to achieve this. Can anyone help?

答:
Meseret is a nice typescript library I wrote that can help you manage your Koa server routers, middleware and much more.

E.g. You can replace your app.ts with this.

```<code>import { ServerApp } from 'meseret'

import HomeRouter from './routers/homeRouter'
import UserRouter from './routers/userRouter'

new ServerApp({
  name: 'Your App Name',
  httpServers: [
    { port: 3000 }
  ],
  routers: [
    HomeRouter,
    UserRouter
  ]
}).start() // returns a Promise
</code>```

All you have to do is just import your koa-router Routers and add them to the list of routers in the ServerApp.

Meseret helps you do much more than manage routers. It has built in support for Koa sessions, static caching, public directory serving, response compression and more. There's also, as expected, an option that lets you add your own Koa middleware to the app.

Plus, it can connect to MongoDB and help manage your Mongoose models (even by adding static type support to your mongoose models--the paths, methods and statics--if you use the ModelFactory).

Socket.IO web sockets are also supported in the config.

All these features are managed in a single ServerApp instance.

Find out more at meseret's Github page.

I hope it helps you manage your distributed node server project.

Body:
I decided to split my routers by their purpose, so they look like this:

routers/homeRouter.ts

import * as Router from 'koa-router';

const router: Router = new Router();

router
    .get('/', async (ctx, next) => {
        ctx.body = 'hello world';
    });

export = router;

routers/userRouter.ts

import * as Router from 'koa-router';
import UserController = require('../controller/userController');

const router: Router = new Router(
    {
        prefix: 'users'
    }
);

var userController = new UserController();

router
    .post('/user/:email/:password', userController.signUp);

export = router;

With this, my app.ts has to import each of the routers one by one like this:

app.ts

import * as Koa from 'koa';
import * as homeRouter from './routers/homeRouter';
import * as userRouter from './routers/userRouter';
const app: Koa = new Koa();
app
    .use(homeRouter.routes())
    .use(homeRouter.allowedMethods());
app
    .use(userRouter.routes())
    .use(userRouter.allowedMethods());
app.listen(3000);

But what I want is this:

app.ts

import * as Koa from 'koa';
import * as routers from './routers';
const app: Koa = new Koa();
app
    .use(routers.routes())
    .use(routers.allowedMethods());
app.listen(3000);

I do not know how to export the routers to achieve this. Can anyone help?

Body:
Meseret is a nice typescript library I wrote that can help you manage your Koa server routers, middleware and much more.

E.g. You can replace your app.ts with this.

import { ServerApp } from 'meseret'

import HomeRouter from './routers/homeRouter'
import UserRouter from './routers/userRouter'

new ServerApp({
  name: 'Your App Name',
  httpServers: [
    { port: 3000 }
  ],
  routers: [
    HomeRouter,
    UserRouter
  ]
}).start() // returns a Promise

All you have to do is just import your koa-router Routers and add them to the list of routers in the ServerApp.

Meseret helps you do much more than manage routers. It has built in support for Koa sessions, static caching, public directory serving, response compression and more. There's also, as expected, an option that lets you add your own Koa middleware to the app.

Plus, it can connect to MongoDB and help manage your Mongoose models (even by adding static type support to your mongoose models--the paths, methods and statics--if you use the ModelFactory).

Socket.IO web sockets are also supported in the config.

All these features are managed in a single ServerApp instance.

Find out more at meseret's Github page.

I hope it helps you manage your distributed node server project.


问:
Pass int to webapi
I know this has been asked a thousand times. But I can't find my error. I narrowed it down by testing it without a parameter, which worked and then tried various things. Like, get or post, [FromBody] or not. etc.
Perhaps I should just show my code or I should stop for today and just celebrate that it is almost weekend.

```<code>[HttpGet] // also tried post instead of get
public HttpResponseMessage Get(int id)
{
    return Request.CreateResponse(HttpStatusCode.OK); // breakpoint set, not hit
}
</code>```

My Js code:

```<code>var myObj = {};
myObj["id"] = parseInt(id);

var json = JSON.stringify(myObj);
alert(json);  // display: { id = 2134 }, seems fine to me

$.ajax({
    type: "GET", // also tried post
    dataType: "json",
    url: '/api/CheckPossible/Get',
    data: json,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function () {
        alert('success');
    },
    error: function () {
        alert('failure');
    }
});
</code>```

I have received a lot of bad requests (400) and I did got it to work without a parameter. So it is not a routing issue.

edit

```<code>$.ajax({
    type: "GET",
    dataType: "json",
    url: '/api/CheckPossible/Get/?id=1234', // also tried Get?id=1234
    contentType: "application/json; charset=utf-8",
    success: function () {
        alert('success');
    },
    error: function () {
        alert('failure');
    }
});
</code>```

Did not work. Perhaps I am missing something else too

答:
You can't pass a http message body to a GET method, you have to pass parameters either in the URL or in the header. For a web api you should pass them in the URL and you can do this as a query string or as part of the URL.

To get it to work with the query string change the url to

```<code>url: '/api/CheckPossible/?id=' + myObj["id"],
</code>```

leave out the data as this won't do anything with get.

If you want to make the parameter a part of the URL then change your route to include it. I prefer the Route attribute for flexible routing, you can also change the global routing scheme.

```<code>[HttpGet] // also tried post instead of get
[Route("api/CheckPossible/{id:int}"]
public HttpResponseMessage Get(int id)
{
}
</code>```

and change your url to

```<code>url: '/api/CheckPossible/' + myObj["id"]
</code>```

Title: Pass int to webapi

Body:
I know this has been asked a thousand times. But I can't find my error. I narrowed it down by testing it without a parameter, which worked and then tried various things. Like, get or post, [FromBody] or not. etc.
Perhaps I should just show my code or I should stop for today and just celebrate that it is almost weekend.

[HttpGet] // also tried post instead of get
public HttpResponseMessage Get(int id)
{
    return Request.CreateResponse(HttpStatusCode.OK); // breakpoint set, not hit
}

My Js code:

var myObj = {};
myObj["id"] = parseInt(id);

var json = JSON.stringify(myObj);
alert(json);  // display: { id = 2134 }, seems fine to me

$.ajax({
    type: "GET", // also tried post
    dataType: "json",
    url: '/api/CheckPossible/Get',
    data: json,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function () {
        alert('success');
    },
    error: function () {
        alert('failure');
    }
});

I have received a lot of bad requests (400) and I did got it to work without a parameter. So it is not a routing issue.

edit

$.ajax({
    type: "GET",
    dataType: "json",
    url: '/api/CheckPossible/Get/?id=1234', // also tried Get?id=1234
    contentType: "application/json; charset=utf-8",
    success: function () {
        alert('success');
    },
    error: function () {
        alert('failure');
    }
});

Did not work. Perhaps I am missing something else too

Body:
You can't pass a http message body to a GET method, you have to pass parameters either in the URL or in the header. For a web api you should pass them in the URL and you can do this as a query string or as part of the URL.

To get it to work with the query string change the url to

url: '/api/CheckPossible/?id=' + myObj["id"],

leave out the data as this won't do anything with get.

If you want to make the parameter a part of the URL then change your route to include it. I prefer the Route attribute for flexible routing, you can also change the global routing scheme.

[HttpGet] // also tried post instead of get
[Route("api/CheckPossible/{id:int}"]
public HttpResponseMessage Get(int id)
{
}

and change your url to

url: '/api/CheckPossible/' + myObj["id"]


问:
why value types are declared (instantiated) without 'new' keyword in (vb or C#).net
why  value  types are declared (instantiated) without 'new' keyword in (vb or C#).net</p>

答:
Basically any primitive CLR type with the exception of Object does not require new.

There are ways to apply this to any (blittable) valuetype too, by going unsafe, pretty much similar too how things are done in C specifically in the embedded world.

Update:

You changed your question. It seems you have been misinformed. Unless you are talking about default values that happens at class initialization, which is still 'using' new under the covers.

Example:

```<code>class Foo
{
  Point foo;
}
</code>```

When doing new Foo(), foo's value is initialized to its default value, which implies new Point().

The above code is effectively:

```<code>class Foo
{
  Point foo;
  Foo()
  {
    foo = default(Point); // which is new Point()
  }
}
</code>```

Body:
Basically any primitive CLR type with the exception of Object does not require new.

There are ways to apply this to any (blittable) valuetype too, by going unsafe, pretty much similar too how things are done in C specifically in the embedded world.

Update:

You changed your question. It seems you have been misinformed. Unless you are talking about default values that happens at class initialization, which is still 'using' new under the covers.

Example:

class Foo
{
  Point foo;
}

When doing new Foo(), foo's value is initialized to its default value, which implies new Point().

The above code is effectively:

class Foo
{
  Point foo;
  Foo()
  {
    foo = default(Point); // which is new Point()
  }
}


问:
How to avoid wrapping inline tags in PhpStorm 2016.3 when reformatting HTML?
I've got this line of code:

```<code><p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum velit esse cillum <strong>dolore eu fugiat.</strong></p>
</code>```

Every time I press Strg + Alt + L to reformat HTML according to my settings, PhpStorm sets a newline before inline tags like  or , so the text above becomes

```<code><p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum velit esse cillum
<strong>dolore eu fugiat.</strong>
</p>
</code>```

I want to keep certain tags inline - like those usually used in simple paragraphs, but I can't figure out how to resolve this simple problem.

I've already added the e.g. anchor tag to "Remove newline before", "Inline elements" and "Don't break if inline content" in Settings > Editor > Code Style > HTML, but still no effect.

答:
This happens when you don't "Wrap text". Since a tag is no plain text, it gets wrapped.

I don't think there is a solution to this as of PhpStorm 2017.2.4.

I suggest using "Wrap text" to avoid inconsistencies.

Body:
I've got this line of code:

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum velit esse cillum dolore eu fugiat.

Every time I press Strg + Alt + L to reformat HTML according to my settings, PhpStorm sets a newline before inline tags like  or , so the text above becomes

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum velit esse cillum
dolore eu fugiat.

I want to keep certain tags inline - like those usually used in simple paragraphs, but I can't figure out how to resolve this simple problem.

I've already added the e.g. anchor tag to "Remove newline before", "Inline elements" and "Don't break if inline content" in Settings > Editor > Code Style > HTML, but still no effect.


问:
Webpack not rewriting asset urls (stylus)
I am trying to rewrite my assets paths from a certain path (~assets/myimage.png) to the correct directory (in my case /assets/).

I told my webpack to write all images to a folder inside public. The images are correctly written, however the url in the build css is not adjusted accordingly.

This is the rule i am using for my stylus files

```<code>use: ExtractTextPlugin.extract({
  fallback: {
    loader: require.resolve("style-loader"),
    options: {
      hmr: false
    }
  },
  use: [
    {
      loader: require.resolve("css-loader")
    },
    {
      loader: require.resolve("stylus-loader")
    }
  ]
})
</code>```

and the one i am using for the assets

```<code>{
    test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
    loader: require.resolve("url-loader"),
    options: {
      limit: 100,
      name: "static/media/[name].[hash:8].[ext]"
    }
},
</code>```

My alias that resolves to the correct directory:

```<code>assets: path.resolve(__dirname, "../public")
</code>```

and the public path is set as /assets/

```<code>publicPath: publicPath + "assets/",
</code>```

Since i use ExtractTextPlugin, the style loader can not be used. When using style loader only it works, however in my use case i need a css file as /style.css

Any ideas on this?

答:
It's just a thought, but might your alias be wrong? You wrote

```<code>assets: path.resolve(__dirname, "../public")
</code>```

but regarding that your project structure looks something like this

```<code>--project_root/
 |--public
 |--src
 |--webpack.conf.js
</code>```

it should be

```<code>assets: path.resolve(__dirname, "public") //without the "folder up" operator
</code>```

Body:
I am trying to rewrite my assets paths from a certain path (~assets/myimage.png) to the correct directory (in my case /assets/).

I told my webpack to write all images to a folder inside public. The images are correctly written, however the url in the build css is not adjusted accordingly.

This is the rule i am using for my stylus files

use: ExtractTextPlugin.extract({
  fallback: {
    loader: require.resolve("style-loader"),
    options: {
      hmr: false
    }
  },
  use: [
    {
      loader: require.resolve("css-loader")
    },
    {
      loader: require.resolve("stylus-loader")
    }
  ]
})

and the one i am using for the assets

{
    test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
    loader: require.resolve("url-loader"),
    options: {
      limit: 100,
      name: "static/media/[name].[hash:8].[ext]"
    }
},

My alias that resolves to the correct directory:

assets: path.resolve(__dirname, "../public")

and the public path is set as /assets/

publicPath: publicPath + "assets/",

Since i use ExtractTextPlugin, the style loader can not be used. When using style loader only it works, however in my use case i need a css file as /style.css

Any ideas on this?

Body:
It's just a thought, but might your alias be wrong? You wrote

assets: path.resolve(__dirname, "../public")

but regarding that your project structure looks something like this

--project_root/
 |--public
 |--src
 |--webpack.conf.js

it should be

assets: path.resolve(__dirname, "public") //without the "folder up" operator


问:
How to set .mk file location path in Android Studio
I am not new to Android development but I am to adding native build. I would like to set the .mk file location manually in Android studio but I couldn't figure it out. I tried this'

```<code>    externalNativeBuild {
        ndkBuild {
            path 'jni/Android.mk'
        }
}
</code>```

but that simply is ignored by gradle build. Can someone tell me how? Following is my full gradle file.

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

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"
    defaultConfig {
        applicationId "my application full name"
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        ndk {
            moduleName "nativeegl"
            ldLibs "log", "android", "EGL", "GLESv1_CM"
        }
    }

    externalNativeBuild {
        ndkBuild {
            path 'jni/Android.mk'
        }
    }

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

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile files('libs/Vuforia.jar')
}
</code>```

答:
Delete directory C:\Users\project_path\app\.externalNativeBuild and force Sync Gradle in the Tools menu. If this is not enough, I have more radical measures in stock.

By the way, this block is obsolete:

```<code>ndk {
     moduleName "nativeegl"
     ldLibs "log", "android", "EGL", "GLESv1_CM"
}
</code>```

Could it cause problems? Maybe.

Body:
I am not new to Android development but I am to adding native build. I would like to set the .mk file location manually in Android studio but I couldn't figure it out. I tried this'

    externalNativeBuild {
        ndkBuild {
            path 'jni/Android.mk'
        }
}

but that simply is ignored by gradle build. Can someone tell me how? Following is my full gradle file.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"
    defaultConfig {
        applicationId "my application full name"
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        ndk {
            moduleName "nativeegl"
            ldLibs "log", "android", "EGL", "GLESv1_CM"
        }
    }

    externalNativeBuild {
        ndkBuild {
            path 'jni/Android.mk'
        }
    }

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

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile files('libs/Vuforia.jar')
}

Body:
Delete directory C:\Users\project_path\app\.externalNativeBuild and force Sync Gradle in the Tools menu. If this is not enough, I have more radical measures in stock.

By the way, this block is obsolete:

ndk {
     moduleName "nativeegl"
     ldLibs "log", "android", "EGL", "GLESv1_CM"
}

Could it cause problems? Maybe.


问:
What's the best way to get device locale in react native (iOS)?
Something similar to [NSLocale currentLocale] in Objective-C.</p>

答:
```<code>import { Platform, NativeModules } from 'react-native'

const deviceLanguage =
      Platform.OS === 'ios'
        ? NativeModules.SettingsManager.settings.AppleLocale ||
          NativeModules.SettingsManager.settings.AppleLanguages[0] //iOS 13
        : NativeModules.I18nManager.localeIdentifier;

console.log(deviceLanguage); //en_US
</code>```

ContentLicense: CC BY-SA 4.0


问:
How to pass Excel Array Formula to VBA UDF?
I have already looked at a similar solution here but somehow I still could not make my code work.

I want to pass an output of an Array Formula as Input to UDF, process it and return a single value from it. Say just add all items in an array and return the value as an example. My main question is how to pass an output of an Array Formula to UDF and process it inside the UDF.

```<code>'Public Function Test1(ParamArray Parm1() As Variant) As Integer
'Dim i, j
'i = 0
'For j = LBound(Parm1) To UBound(Parm1)
'
'    i = i + Parm1(j)
'
'Next j
'Test1 = i
'End Function

Public Function Test1(Parm1 As Variant) As Integer
Dim i, j
Dim tmparray() As Variant
tmparray = Parm1
For j = LBound(tmparray, 1) To UBound(tmparray, 2)
   i = i + tmparray(j)
Next j
Test1 = i
End Function
</code>```

Above commented code did not work. I tried to modify it by referring the mentioned solution as pasted just below it, but still I could not make it work.

In Excel Spreadsheet I am passing {=Test1(ROW(C1:C4))} as an Array Formula to this but it returns #VALUE!

In above code (The commented one) if I test and debug thru below sub it works fine but when called from an Excel Array Formula like {=Test1(ROW(C1:C4))}it returns #VALUE!

```<code>Sub check()

j = Test1(1, 2)

End Sub
</code>```

Could someone help me further please?

答:
This is how to make a UDF, summing all your numbers in a range:

```<code>Public Function AlternativeSum(Parm1 As Range) As Long

    Dim myCell  As Range
    Dim result  As Long

    For Each myCell In Parm1
        result = myCell.Value + result
    Next myCell

    AlternativeSum = result

End Function
</code>```

You may consider changing the output to double or returning some specific info, if the input range does not consist of numbers. But in general it works:

In order to make it "your way", you should learn how to transfer range to array Array from Range in Excel VBA. It is a bit tricky. With a single line range, try like this:

```<code>Public Function Test1(Parm1 As Variant) As Integer

    Dim i           As Long
    Dim j           As Long
    Dim tmparray    As Variant

    tmparray = Parm1

    For j = 1 To 3
        i = i + Parm1(1, j)
    Next

    Test1 = i

End Function
</code>```

Body:
I have already looked at a similar solution here but somehow I still could not make my code work.

I want to pass an output of an Array Formula as Input to UDF, process it and return a single value from it. Say just add all items in an array and return the value as an example. My main question is how to pass an output of an Array Formula to UDF and process it inside the UDF.

'Public Function Test1(ParamArray Parm1() As Variant) As Integer
'Dim i, j
'i = 0
'For j = LBound(Parm1) To UBound(Parm1)
'
'    i = i + Parm1(j)
'
'Next j
'Test1 = i
'End Function

Public Function Test1(Parm1 As Variant) As Integer
Dim i, j
Dim tmparray() As Variant
tmparray = Parm1
For j = LBound(tmparray, 1) To UBound(tmparray, 2)
   i = i + tmparray(j)
Next j
Test1 = i
End Function

Above commented code did not work. I tried to modify it by referring the mentioned solution as pasted just below it, but still I could not make it work.

In Excel Spreadsheet I am passing {=Test1(ROW(C1:C4))} as an Array Formula to this but it returns #VALUE!

In above code (The commented one) if I test and debug thru below sub it works fine but when called from an Excel Array Formula like {=Test1(ROW(C1:C4))}it returns #VALUE!

Sub check()

j = Test1(1, 2)

End Sub

Could someone help me further please?

Body:
This is how to make a UDF, summing all your numbers in a range:

Public Function AlternativeSum(Parm1 As Range) As Long

    Dim myCell  As Range
    Dim result  As Long

    For Each myCell In Parm1
        result = myCell.Value + result
    Next myCell

    AlternativeSum = result

End Function

You may consider changing the output to double or returning some specific info, if the input range does not consist of numbers. But in general it works:

In order to make it "your way", you should learn how to transfer range to array Array from Range in Excel VBA. It is a bit tricky. With a single line range, try like this:

Public Function Test1(Parm1 As Variant) As Integer

    Dim i           As Long
    Dim j           As Long
    Dim tmparray    As Variant

    tmparray = Parm1

    For j = 1 To 3
        i = i + Parm1(1, j)
    Next

    Test1 = i

End Function


问:
How can I generate database tables from C# classes?
Does anyone know a way to auto-generate database tables for a given class?  I'm not looking for an entire persistence layer - I already have a data access solution I'm using, but I suddenly have to store a lot of information from a large number of classes and I really don't want to have to create all these tables by hand.  For example, given the following class:

```<code>class Foo
{
    private string property1;
    public string Property1
    {
        get { return property1; }
        set { property1 = value; }
    }

    private int property2;
    public int Property2
    {
        get { return property2; }
        set { property2 = value; }
    }
}
</code>```

I'd expect the following SQL:

```<code>CREATE TABLE Foo
(
    Property1 VARCHAR(500),
    Property2 INT
)
</code>```

I'm also wondering how you could handle complex types.  For example, in the previously cited class, if we changed that to be :

```<code>class Foo
{
    private string property1;
    public string Property1
    {
        get { return property1; }
        set { property1 = value; }
    }

    private System.Management.ManagementObject property2;
    public System.Management.ManagementObject Property2
    {
        get { return property2; }
        set { property2 = value; }
    }
}
</code>```

How could I handle this?

I've looked at trying to auto-generate the database scripts by myself using reflection to enumerate through each class' properties, but it's clunky and the complex data types have me stumped.

答:
I know you're looking for an entire persistence layer, but NHibernate's hbm2ddl task can do this almost as a one-liner.

There is a NAnt task available to call it which may well be of interest.

OwnerDisplayName: VanOrman

Body:
Does anyone know a way to auto-generate database tables for a given class?  I'm not looking for an entire persistence layer - I already have a data access solution I'm using, but I suddenly have to store a lot of information from a large number of classes and I really don't want to have to create all these tables by hand.  For example, given the following class:

class Foo
{
    private string property1;
    public string Property1
    {
        get { return property1; }
        set { property1 = value; }
    }

    private int property2;
    public int Property2
    {
        get { return property2; }
        set { property2 = value; }
    }
}

I'd expect the following SQL:

CREATE TABLE Foo
(
    Property1 VARCHAR(500),
    Property2 INT
)

I'm also wondering how you could handle complex types.  For example, in the previously cited class, if we changed that to be :

class Foo
{
    private string property1;
    public string Property1
    {
        get { return property1; }
        set { property1 = value; }
    }

    private System.Management.ManagementObject property2;
    public System.Management.ManagementObject Property2
    {
        get { return property2; }
        set { property2 = value; }
    }
}

How could I handle this?

I've looked at trying to auto-generate the database scripts by myself using reflection to enumerate through each class' properties, but it's clunky and the complex data types have me stumped.

OwnerDisplayName: Cheekysoft


问:
Refering to environment variable in oracle sql files on Linux and Windows
We have an sql build script, with oracle 10.2. At the end of the script we have this:

```<code>@$ORACLE_HOME/rdbms/admin/utlrp.sql
</code>```

Which works on Linux but not on Windows. So we created a second file with this line:

```<code>@%ORACLE_HOME%/rdbms/admin/utlrp.sql
</code>```

Surely there is a better way. How can I refer to an environment variable in a cross-platform way? Or alternatively, is it possible to do OS detection in the sql file to guard each of the statements with an IF clause?

答:
I believe this syntax is what you need:

@?/rdbms/admin/utlrp.sql

However, this is just for the ORACLE_HOME variable. I don't know about others...

Edit:

It's a bit awkward, but you could look into setting SQLPATH environment variable as well. It's to SQL scripts in oracle as PATH is to executables in Unix/Windows.

OwnerDisplayName: Yoni

Body:
We have an sql build script, with oracle 10.2. At the end of the script we have this:

@$ORACLE_HOME/rdbms/admin/utlrp.sql

Which works on Linux but not on Windows. So we created a second file with this line:

@%ORACLE_HOME%/rdbms/admin/utlrp.sql

Surely there is a better way. How can I refer to an environment variable in a cross-platform way? Or alternatively, is it possible to do OS detection in the sql file to guard each of the statements with an IF clause?

OwnerDisplayName: DCookie

LastEditorDisplayName: DCookie


问:
/deep/ combinator in CSS is deprecated and will be removed in M63
I updated my angular to 4.0.0 and chrome to to 62.0.3202.94 and I got this error:

[Deprecation] /deep/ combinator in CSS is deprecated and will be removed in M63, around December 2017. See https://www.chromestatus.com/features/4964279606312960 for more details.

And is refer to clientWidth or clientHeight in my code:

```<code>document.getElementById(this.ID).clientWidth;
</code>```

or here:

```<code>document.documentElement.scrollTop = parseInt(sessionStorage.getItem('scrollPosition'), 10);
</code>```

Is this error misinterpreted by the browser? How to fix this?

答:
update

::slotted is now supported by all new browsers and can be used with `ViewEncapsulation.ShadowDom

https://developer.mozilla.org/en-US/docs/Web/CSS/::slotted

original

/deep/ being deprecated in any browser is entirely irrelevant to Angular.

Angular rewrites the selector so that it doesn't use /deep/ or it's newer replacement ::ng-deep when the application is loaded.

/deep/ and ::ng-deep are just hints for Angular to not include the unique class (like _ngcontent-1), Angular adds to each component host element, in the CSS selector.

See also https://blog.thoughtram.io/angular/2015/06/29/shadow-dom-strategies-in-angular2.html

Body:
I updated my angular to 4.0.0 and chrome to to 62.0.3202.94 and I got this error:

[Deprecation] /deep/ combinator in CSS is deprecated and will be removed in M63, around December 2017. See https://www.chromestatus.com/features/4964279606312960 for more details.

And is refer to clientWidth or clientHeight in my code:

document.getElementById(this.ID).clientWidth;

or here:

document.documentElement.scrollTop = parseInt(sessionStorage.getItem('scrollPosition'), 10);

Is this error misinterpreted by the browser? How to fix this?


问:
jQuery: Target ONLY Safari
I'm using this bit of jQuery code to target Safari:

```<code>if ($.browser.safari) {
    $('#div1').css({'margin-top': '-22px'});
    $('#div2').css({'margin-top': '-17px'});
}
</code>```

Oddly, it also targets Chrome (at least Mac version). What jQuery code can I use that would ignore Chrome and target only Safari?

I would be grateful for expert advice.

答:
This Works Fine to know whether browser is Safari.</p>

```<code>if(navigator.userAgent.indexOf('Safari') !=-1 && navigator.userAgent.indexOf('Chrome') == -1)
{
    alert('its safari');
}else{
    alert('its not safari');
}
</code>```

Title: jQuery: Target ONLY Safari

Body:
I'm using this bit of jQuery code to target Safari:

if ($.browser.safari) {
    $('#div1').css({'margin-top': '-22px'});
    $('#div2').css({'margin-top': '-17px'});
}

Oddly, it also targets Chrome (at least Mac version). What jQuery code can I use that would ignore Chrome and target only Safari?

I would be grateful for expert advice.

Body:
This Works Fine to know whether browser is Safari.

if(navigator.userAgent.indexOf('Safari') !=-1 && navigator.userAgent.indexOf('Chrome') == -1)
{
    alert('its safari');
}else{
    alert('its not safari');
}


问:
How to set epic link in Jira using Groovy
I need to set epic link using groovy if a condition is true.
I'm using the following script:

```<code>import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.ComponentManager
import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.issue.Issue;
def customFieldManager = ComponentAccessor.getCustomFieldManager()
IssueManager issueManager = ComponentAccessor.getOSGiComponentInstanceOfType(IssueManager.class)
def epiclink = CustomFieldManager.getCustomFieldObject("customfield_10101")
issue.setCustomFieldValue(epiclink,"TS-14")
</code>```

If I set the epic link to null it works,

```<code>    issue.setCustomFieldValue(epiclink, null)
</code>```

but setting it to an issue key doesn't work.

Any help is appreciated.

答:
I'm not sure why you aren't using ComponentAccessor.getIssueManager(), but that is a different question.

Epic Link is an Issue Object, not the Key

```<code>import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.ComponentManager
import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.issue.Issue;
def customFieldManager = ComponentAccessor.getCustomFieldManager()
IssueManager issueManager = ComponentAccessor.getOSGiComponentInstanceOfType(IssueManager.class)
def epiclink = CustomFieldManager.getCustomFieldObject("customfield_10101")

issue.setCustomFieldValue(epiclink,IssueManager.getIssueObject("TS-14"))
</code>```

Body:
I need to set epic link using groovy if a condition is true.
I'm using the following script:

import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.ComponentManager
import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.issue.Issue;
def customFieldManager = ComponentAccessor.getCustomFieldManager()
IssueManager issueManager = ComponentAccessor.getOSGiComponentInstanceOfType(IssueManager.class)
def epiclink = CustomFieldManager.getCustomFieldObject("customfield_10101")
issue.setCustomFieldValue(epiclink,"TS-14")

If I set the epic link to null it works,

    issue.setCustomFieldValue(epiclink, null)

but setting it to an issue key doesn't work.

Any help is appreciated.

Body:
I'm not sure why you aren't using ComponentAccessor.getIssueManager(), but that is a different question.

Epic Link is an Issue Object, not the Key

import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.ComponentManager
import com.atlassian.jira.issue.IssueManager
import com.atlassian.jira.issue.Issue;
def customFieldManager = ComponentAccessor.getCustomFieldManager()
IssueManager issueManager = ComponentAccessor.getOSGiComponentInstanceOfType(IssueManager.class)
def epiclink = CustomFieldManager.getCustomFieldObject("customfield_10101")

issue.setCustomFieldValue(epiclink,IssueManager.getIssueObject("TS-14"))


问:
Display SQLserv result as text in PHP array
I have a query where I'm already pulling back the results from a Sql query via an array as below.

```<code><?php

$sql = "SELECT inc.STATUS as STATUS,
FROM dbo.HELP_DESK as inc";

$result = sqlsrv_query($conn, $sql);

$status=(
'1' => "Request For Authorization",
'3' => "Pending",
'4' => "Scheduled For Review",
'5' => "Scheduled For Approval",
'8' => "Pending",
);

echo "<table><tr id=\"header\"><td><center>Status</center></td><tr>";

while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {

echo "<tr><td><b><center> " . $row["STATUS"] . "</center></b></td></tr>";
}

echo "</table>";

sqlsrv_close( $conn );
?>
</code>```

The $row fetches back a number from the database. However, I'm wanting to display the text from my $status array.

I've tried several methods but end up with a blank screen returned.

Any suggestions? Appreciate the help.

答:
Is the the blank screen caused by a PHP error? You should check your logs.
Because, in your example, your wrote the array like this:

```<code>    $status=(
'1' => "Request For Authorization",
'3' => "Pending",
'4' => "Scheduled For Review",
'5' => "Scheduled For Approval",
'8' => "Pending",
);
</code>```

But you have to use brackets instead:

```<code>$status=[
'1' => "Request For Authorization",
'3' => "Pending",
'4' => "Scheduled For Review",
'5' => "Scheduled For Approval",
'8' => "Pending",
];
</code>```

Then you will have to display the the label by something like this:

```<code>echo $status[$row['STATUS']];
</code>```

BTW, you should use a (micro) framework to develop, because you should (or must) not write a query in your DB and display the resuslts in the same file.

HTH.

Body:
I have a query where I'm already pulling back the results from a Sql query via an array as below.

<?php

$sql = "SELECT inc.STATUS as STATUS,
FROM dbo.HELP_DESK as inc";

$result = sqlsrv_query($conn, $sql);

$status=(
'1' => "Request For Authorization",
'3' => "Pending",
'4' => "Scheduled For Review",
'5' => "Scheduled For Approval",
'8' => "Pending",
);

echo "

Status
";

while($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {

echo "
 " . $row["STATUS"] . "
";
}

echo "
";

sqlsrv_close( $conn );
?>

The $row fetches back a number from the database. However, I'm wanting to display the text from my $status array.

I've tried several methods but end up with a blank screen returned.

Any suggestions? Appreciate the help.

Body:
Is the the blank screen caused by a PHP error? You should check your logs.
Because, in your example, your wrote the array like this:

    $status=(
'1' => "Request For Authorization",
'3' => "Pending",
'4' => "Scheduled For Review",
'5' => "Scheduled For Approval",
'8' => "Pending",
);

But you have to use brackets instead:

$status=[
'1' => "Request For Authorization",
'3' => "Pending",
'4' => "Scheduled For Review",
'5' => "Scheduled For Approval",
'8' => "Pending",
];

Then you will have to display the the label by something like this:

echo $status[$row['STATUS']];

BTW, you should use a (micro) framework to develop, because you should (or must) not write a query in your DB and display the resuslts in the same file.

HTH.


问:
How to add values/names of checkbox to a variable on form submit?
I have a set of checkboxes in a form that has a submit button.

```<code><form name="form" method="POST">
    <input type="checkbox" name="3" value="3">
    <input type="checkbox" name="7" value="7">
    <input type="checkbox" name="5" value="5">
    <input type="checkbox" name="12" value="12">
    <input type="submit" name="submit-form">
</form>

<?php
if (isset($_REQUEST['submit-form'])) {

}
?>
...
</code>```

The names/values that are currently in the code are dynamically generated and need to be kept (either in name or value will do).

When the form is submitted, I want to add the values or names of the checked checkboxes to a PHP variable, separated by commas, as a string.

Any help with the code that I should put in the if brackets would be much appreciated.

Thanks in advance.

答:
A lot of good answers here, but just to answer your question as it stands, in case modifying the HTML isn't an option for you.</p>

```<code><?php

  if (isset($_REQUEST['submit-form'])) {

    unset($_POST['submit-form']);
    echo implode( ',', $_POST );

  }
</code>```

Body:
I have a set of checkboxes in a form that has a submit button.

<form name="form" method="POST">
    <input type="checkbox" name="3" value="3">
    <input type="checkbox" name="7" value="7">
    <input type="checkbox" name="5" value="5">
    <input type="checkbox" name="12" value="12">
    <input type="submit" name="submit-form">
</form>

<?php
if (isset($_REQUEST['submit-form'])) {

}
?>
...

The names/values that are currently in the code are dynamically generated and need to be kept (either in name or value will do).

When the form is submitted, I want to add the values or names of the checked checkboxes to a PHP variable, separated by commas, as a string.

Any help with the code that I should put in the if brackets would be much appreciated.

Thanks in advance.

Body:
A lot of good answers here, but just to answer your question as it stands, in case modifying the HTML isn't an option for you.

<?php

  if (isset($_REQUEST['submit-form'])) {

    unset($_POST['submit-form']);
    echo implode( ',', $_POST );

  }


问:
How to calculate multiplication of numbers in a html table below specific headings - IONIC
Explanation: I have a html table with 3 columns namely Price , Quantity and Total. Numers are written below them.

Requirement: I need to multiply price with Quantity and bring that value in Total. I want to do this while leaving the quantity field or on a key press [as i am typing].

Image and code of my form are shared below

Image:

code of invoice.html

```<code><div style="margin-top:15px">
    <table>
       <tr>
         <th></th>
         <th>Price</th>
         <th>Quantity</th>
         <th>Total</th>

         <th></th>
       </tr>
       <tr *ngFor="let items of inVoiceItems2;let i=index;">
         <td>{{i+1}}</td>
         <td style="width:198px"><input type="text" name="price" [(ngModel)]="inVoiceItems2[i].price" style="width:198px;border:0px"/></td>
         <td><input type="text" name="quantity" [(ngModel)]="inVoiceItems2[i].quantity" style="width:198px;border:0px"/></td>
         <td><input type="text" name="total" [(ngModel)]="inVoiceItems2[i].total" style="width:198px;border:0px"/></td>
       </tr>
   </table>

   <br>
   <input type="button" value="Add New Row" (click)="addRow2()" style="margin-top:5px"/>
   <br>
   <input type="button" value="Calculate Bill" (click)="calculate_bill()" style="margin-top:5px"/>

 </div>
</code>```

code of invoice.ts

```<code>  addRow2(){
    this.inVoiceItems2.push({'debit':'','credit':''});
  }

  calculate_bill(){

  }
</code>```

答:
To do the calculation when typing in the quantity field, you will need to use the blur event.

```<code><td><input type="text" name="quantity" [(ngModel)]="inVoiceItems2[i].quantity" style="width:198px;border:0px" (blur)="calculateRowTotal(i)"/></td>
</code>```

the function would be something like this:

```<code>calculateRowTotal(i: number) {
    this.inVoiceItems2[i].total = +this.inVoiceItems2[i].price* +this.inVoiceItems2[i].quantity
}
</code>```

NOTE: this will fail if the value being inserted cannot be converted to a number

Body:
Explanation: I have a html table with 3 columns namely Price , Quantity and Total. Numers are written below them.

Requirement: I need to multiply price with Quantity and bring that value in Total. I want to do this while leaving the quantity field or on a key press [as i am typing].

Image and code of my form are shared below

Image:

code of invoice.html

         Price
         Quantity
         Total

         {{i+1}}
         <input type="text" name="price" [(ngModel)]="inVoiceItems2[i].price" style="width:198px;border:0px"/>
         <input type="text" name="quantity" [(ngModel)]="inVoiceItems2[i].quantity" style="width:198px;border:0px"/>
         <input type="text" name="total" [(ngModel)]="inVoiceItems2[i].total" style="width:198px;border:0px"/>

   <input type="button" value="Add New Row" (click)="addRow2()" style="margin-top:5px"/>

   <input type="button" value="Calculate Bill" (click)="calculate_bill()" style="margin-top:5px"/>

code of invoice.ts

  addRow2(){
    this.inVoiceItems2.push({'debit':'','credit':''});
  }

  calculate_bill(){

  }

Body:
To do the calculation when typing in the quantity field, you will need to use the blur event.

<td><input type="text" name="quantity" [(ngModel)]="inVoiceItems2[i].quantity" style="width:198px;border:0px" (blur)="calculateRowTotal(i)"/></td>

the function would be something like this:

calculateRowTotal(i: number) {
    this.inVoiceItems2[i].total = +this.inVoiceItems2[i].price* +this.inVoiceItems2[i].quantity
}

NOTE: this will fail if the value being inserted cannot be converted to a number


问:
How to submit a form on page load without clicking submit button?
Is there a way to make a form submit "onload" without clicking a
submit button with PHP? i saw some ways to make it with Javascript, but i love php and id like to make it with php.

For example:

```<code><form action="https://xxxxxx.com/yyy.php" method="post" id="foo">
<input type="hidden" name="LoginEmail" value="user [at] domain.com">
<input type="hidden" name="LoginPassword" value="mycleartextpassword">
<input type="submit" name="Authenticate" value="Login">
<input type="hidden" name="Action" value="1" >
</form>
</code>```

I can make it with javascript:

```<code><form id="foo"> .... < /form>

<script type="text/javascript">
    function myfunc () {
        var frm = document.getElementById("foo");
        frm.submit();
    }
    window.onload = myfunc;
</script>
</code>```

Well, Can we make same thing with PHP? Could you please kindly share your ideas and advices?

Thank you.

答:
If you want to auto-submit form after page load (IMHO it's pointless) I assume you generated its values by yourself (by PHP code) and you want to send them to another page, right? If so redirect page to the another by header() passing values through POST:</p>

```<code>$post_data = 'LoginEmail=username [at] domain.com&LoginPassword=...';
$content_length = strlen($post_data);

header('POST /another_page.php HTTP/1.1');
header('Host: fancyhost');
header('Connection: close');
header('Content-type: application/x-www-form-urlencoded');
header('Content-length: ' . $content_length);
header('');
header($post_data);

exit();
</code>```

Body:
Is there a way to make a form submit "onload" without clicking a
submit button with PHP? i saw some ways to make it with Javascript, but i love php and id like to make it with php.

For example:

<form action="https://xxxxxx.com/yyy.php" method="post" id="foo">
<input type="hidden" name="LoginEmail" value="user [at] domain.com">
<input type="hidden" name="LoginPassword" value="mycleartextpassword">
<input type="submit" name="Authenticate" value="Login">
<input type="hidden" name="Action" value="1" >
</form>

I can make it with javascript:

<form id="foo"> .... < /form>

Well, Can we make same thing with PHP? Could you please kindly share your ideas and advices?

Thank you.

Body:
If you want to auto-submit form after page load (IMHO it's pointless) I assume you generated its values by yourself (by PHP code) and you want to send them to another page, right? If so redirect page to the another by header() passing values through POST:

$post_data = 'LoginEmail=username [at] domain.com&LoginPassword=...';
$content_length = strlen($post_data);

header('POST /another_page.php HTTP/1.1');
header('Host: fancyhost');
header('Connection: close');
header('Content-type: application/x-www-form-urlencoded');
header('Content-length: ' . $content_length);
header('');
header($post_data);

exit();


问:
Background color for the last second row of the table
I want red color as the background for the last second row of the table.

But it is not changing.

I tried:

```<code>    $i = 0;
    $total = 0;
    $stmttr = $user_home->runQuery("SELECT * FROM invoice WHERE BRN = :inv"); // Your query
    $stmttr->bindParam(':inv',$irn);
    $allRows = $stmttr->rowCount(); // Count Total rows available in result
    $tri = 0; // initiate variable to check <tr> status
        while($rowc)
        {
            extract($rowc);
            $i++;

?>

    <tr  <?php if(++$tri==$allRows) { ?> style="background-color: red;"<?php } ?>   >
      <td style="border-top:none !important; border-bottom:none !important;">
</code>```

See the full code:

```<code><?php
    $i = 0;
    $total = 0;
    $stmttr = $user_home->runQuery("SELECT * FROM invoice WHERE BRN = :inv"); // Your query
    $stmttr->bindParam(':inv',$irn);
    $allRows = $stmttr->rowCount(); // Count Total rows available in result
    $tri = 0; // initiate variable to check <tr> status
        while($rowc)
        {
            extract($rowc);
            $i++;

?>

    <tr  <?php if(++$tri==$allRows) { ?> style="background-color: red;"<?php } ?>   >
      <td style="border-top:none !important; border-bottom:none !important;">
        <?php echo $i; ?>
      </td>
      <td style="border-top:none !important; border-bottom:none !important;">
        <?php
        $itm = $IRN;
        $stmti = $user_home->runQuery('SELECT * FROM item WHERE IRN = :iinv ');
        $stmti->bindParam(':iinv',$itm);
        $stmti->execute();
        $rowci = $stmti->fetch(PDO::FETCH_ASSOC);
        echo $rowci['Name'];
        $srv = $SRN;
        $stmts = $user_home->runQuery('SELECT * FROM service WHERE SRN = :sinv ');
        $stmts->bindParam(':sinv',$srv);
        $stmts->execute();
        $rowcs = $stmts->fetch(PDO::FETCH_ASSOC);
        ?>
         (<?php echo $rowcs['Name']; ?>)
      </td>
      <td style="border-top:none !important; border-bottom:none !important;">
        <?php echo $Quantity; ?>
      </td>
      <td style="border-top:none !important; border-bottom:none !important;">
        <?php echo $Amnt; ?>
      </td>
    </tr>
</code>```

答:
The error is at: $allRows = $stmttr->rowCount(); // Count Total rows available in result

It is not counting the rows available in MySQL

The updated code:

```<code>$i = 0;
    $total = 0;
    $stmttr = $user_home->runQuery("SELECT COUNT(*) As rows FROM invoice WHERE BRN = :inv"); // Your query
    $stmttr->bindParam(':inv',$irn);
    $stmttr->execute();
$cresult = $stmttr->fetch(PDO::FETCH_ASSOC);
$tf= ($cresult['rows']);
        while($rowc)
        {
            extract($rowc);
            $i++;

?>

    <tr  <?php if($i == $tf) { ?> style="background-color: red;"<?php } ?>   >
      <td style="border-top:none !important; border-bottom:none !important;">
</code>```

Hope it helps you. Good Luck!!

Body:
I want red color as the background for the last second row of the table.

But it is not changing.

I tried:

    $i = 0;
    $total = 0;
    $stmttr = $user_home->runQuery("SELECT * FROM invoice WHERE BRN = :inv"); // Your query
    $stmttr->bindParam(':inv',$irn);
    $allRows = $stmttr->rowCount(); // Count Total rows available in result
    $tri = 0; // initiate variable to check
 status
        while($rowc)
        {
            extract($rowc);
            $i++;

?>

    <tr  <?php if(++$tri==$allRows) { ?> style="background-color: red;"<?php } ?>   >

See the full code:

<?php
    $i = 0;
    $total = 0;
    $stmttr = $user_home->runQuery("SELECT * FROM invoice WHERE BRN = :inv"); // Your query
    $stmttr->bindParam(':inv',$irn);
    $allRows = $stmttr->rowCount(); // Count Total rows available in result
    $tri = 0; // initiate variable to check
 status
        while($rowc)
        {
            extract($rowc);
            $i++;

?>

    <tr  <?php if(++$tri==$allRows) { ?> style="background-color: red;"<?php } ?>   >

        <?php echo $i; ?>

        <?php
        $itm = $IRN;
        $stmti = $user_home->runQuery('SELECT * FROM item WHERE IRN = :iinv ');
        $stmti->bindParam(':iinv',$itm);
        $stmti->execute();
        $rowci = $stmti->fetch(PDO::FETCH_ASSOC);
        echo $rowci['Name'];
        $srv = $SRN;
        $stmts = $user_home->runQuery('SELECT * FROM service WHERE SRN = :sinv ');
        $stmts->bindParam(':sinv',$srv);
        $stmts->execute();
        $rowcs = $stmts->fetch(PDO::FETCH_ASSOC);
        ?>
         (<?php echo $rowcs['Name']; ?>)

        <?php echo $Quantity; ?>

        <?php echo $Amnt; ?>

Body:
The error is at: $allRows = $stmttr->rowCount(); // Count Total rows available in result

It is not counting the rows available in MySQL

The updated code:

$i = 0;
    $total = 0;
    $stmttr = $user_home->runQuery("SELECT COUNT(*) As rows FROM invoice WHERE BRN = :inv"); // Your query
    $stmttr->bindParam(':inv',$irn);
    $stmttr->execute();
$cresult = $stmttr->fetch(PDO::FETCH_ASSOC);
$tf= ($cresult['rows']);
        while($rowc)
        {
            extract($rowc);
            $i++;

?>

    <tr  <?php if($i == $tf) { ?> style="background-color: red;"<?php } ?>   >
      <td style="border-top:none !important; border-bottom:none !important;">

Hope it helps you. Good Luck!!


问:
How can i calculate the sum of numbers written in a html table below specific headings - IONIC
Explanation: I have a html table with 2 columns namely Debit and Credit. Numers are written below them.

Requirement: I need to sum the number written below Debit and Credit

Please open about page in the repo.........
  Please find the stackblitz repo

On the about page you will find 2 buttons , 1. Total Debit   2. Total Credit

I want to calculate the total amount under debit and credit once that specific button is clicked.

Adding image for your reference below:

答:
Screenshot open it here

Declare Module

```<code>var app = angular.module('myApp', [
  'ngRoute' ,
]);
</code>```

Create Filter

create a filter to the addition of all value which is coming from an array.
it will add all value and it will return a total of value.

```<code>app.filter('totalAdditon', function() {
      return function(array_numbers) {
          var AmountTotal = 0;
          for (i=0; i<array_numbers.length; i++) {
              AmountTotal = AmountTotal + array_numbers[i];
                          };
          return AmountTotal;
      };

  });
</code>```

Controller

```<code>app.controller('myController', function($scope, $filter) {
      $scope.array_numbers = [1,2,3,4,6,7,8];   //values in array
      $scope.CreditTotal = function() {
      var AmountTotal = $filter('totalAdditon')($scope.array_numbers);
      $scope.CreditTotal = AmountTotal; //bind the total value to HTML
    };
 });
</code>```

HTML

Everytime you click on Total Credit Button, It will call a function Creditotal() to get the total value.

```<code><div lan="eng" ng-app="myApp">
<table ng-controller="myController">
<tr ng-repeat="group in array_numbers">
<td>{{group}}</td>
 </tr>
 <tr class="total-rows" ><td>{{CreditTotal}} </td></tr>
 <tr><td><button ng-click="CreditTotal()">Total Credit</button><td></tr>
 </table>
 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
 <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

 <!-- Vendor: Angular, followed by our custom Javascripts -->
 <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.min.js"></script>
 <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular-route.min.js"></script>
    <script type="text/javascript" src="js/simplePagination.js"></script>
 </div>
</code>```

This is the process of addition of Credit value from table you can do the same to get a total of Debit.
I hope it helps you.

Body:
Screenshot open it here

Declare Module

var app = angular.module('myApp', [
  'ngRoute' ,
]);

Create Filter

create a filter to the addition of all value which is coming from an array.
it will add all value and it will return a total of value.

app.filter('totalAdditon', function() {
      return function(array_numbers) {
          var AmountTotal = 0;
          for (i=0; i<array_numbers.length; i++) {
              AmountTotal = AmountTotal + array_numbers[i];
                          };
          return AmountTotal;
      };

  });

Controller

app.controller('myController', function($scope, $filter) {
      $scope.array_numbers = [1,2,3,4,6,7,8];   //values in array
      $scope.CreditTotal = function() {
      var AmountTotal = $filter('totalAdditon')($scope.array_numbers);
      $scope.CreditTotal = AmountTotal; //bind the total value to HTML
    };
 });

HTML

Everytime you click on Total Credit Button, It will call a function Creditotal() to get the total value.

<div lan="eng" ng-app="myApp">
<table ng-controller="myController">
<tr ng-repeat="group in array_numbers">
<td>{{group}}</td>
 </tr>
 <tr class="total-rows" ><td>{{CreditTotal}} </td></tr>
 <tr><td><button ng-click="CreditTotal()">Total Credit</button><td></tr>
 </table>
 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
 <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

 <!-- Vendor: Angular, followed by our custom Javascripts -->
 <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.min.js"></script>
 <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular-route.min.js"></script>
    <script type="text/javascript" src="js/simplePagination.js"></script>
 </div>

This is the process of addition of Credit value from table you can do the same to get a total of Debit.
I hope it helps you.