问:
How does the web server locate a file on server through URL?
Has anyone ever tried to implement a web server? Or know something about the underhood of a working web server program? I am wondering what happens exactly from when a URL is received by the web server to a file on the web server is located and sent back as response.

Does the server just keep an internal table to remember the mapping between the URLs it supports and the corresponding local paths? Or is there anything more tricky?

Thanks!

Update

Thanks for your replies. Here's my understanding for now.

I checked with the Microsoft IIS (Internet Information Service), I noticed that IIS can host multiple sites, and foreach site IIS memorize its root path on the local file system. Different sites on the same host share the same host name or IP, and they are differentiated by separate ports. For example:

```<code>http://www.myServer.com:1111/folderA/pageA.htm
</code>```

The web server will use www.myServer.com:1111 part of the URL string to locate which path on its local file system will be used, and then in that local path, it searches for subfolder folderA and then the file pageA.htm.

The web server only need to memorize the following mapping between 2 plain strings:

```<code>"http://www.myServer.com:1111/" <---> "D:\myWebRoot"
</code>```

I don't know where this kind of mapping info is stored, maybe some config files for the Web Server Program in question.

But the result of this mapping granularity is that we could only access content within that mapped local folder. We couldn't do arbitray mapping.

Update - 2 -

I found where the IIS keep the mapping, here's some quotes from applicationHost.config:

```<code><sites>
    <site name="Default Web Site" id="1" serverAutoStart="false">
        <application path="/">
            <virtualDirectory path="/" physicalPath="%SystemDrive%\inetpub\wwwroot" />
        </application>
        <bindings>
            <binding protocol="http" bindingInformation="*:80:" />
            <binding protocol="net.tcp" bindingInformation="808:*" />
            <binding protocol="net.pipe" bindingInformation="*" />
            <binding protocol="net.msmq" bindingInformation="localhost" />
            <binding protocol="msmq.formatname" bindingInformation="localhost" />
        </bindings>
    </site>
    <site name="myIISService" id="2" serverAutoStart="true">
        <application path="/" applicationPool="myIISService">
            <virtualDirectory path="/" physicalPath="D:\MySites\MyIISService" />
        </application>
        <bindings>
            <binding protocol="http" bindingInformation="*:8022:" />
        </bindings>
    </site>
    <siteDefaults>
        <logFile logFormat="W3C" directory="%SystemDrive%\inetpub\logs\LogFiles" />
        <traceFailedRequestsLogging directory="%SystemDrive%\inetpub\logs\FailedReqLogFiles" />
    </siteDefaults>
    <applicationDefaults applicationPool="DefaultAppPool" />
    <virtualDirectoryDefaults allowSubDirConfig="true" />
</sites>
</code>```

Update - 3 -

After I read foo's reply, my undersanding of a "server" is enlarged. I want to make some comment based on my recent learning of WCF.

No matter what kind of server it is, we could always send messages to them by specifying the protocol, URL, port. For example:

```<code>[http://www.myserver.com:1111/]page.htm

[net.tcp://www.myserver.com/]someService.svc/someMethod

[net.msmq://www.myserver.com/]someService.svc

[net.pipe://localhost/]
</code>```

After the messages arrives at the server program using the parts in square bracket of above URLs, the rest part of the url will send to the server program as input for further processing. And the following behaviour could be as simple as static content feeding or as complex as dynamic content generating.

答: For servers that serve "files", a typical approach is to treat the path portion of the URL as a relative path starting at a "web root" directory defined in the server's configuration.  However, a URL doesn't have to correspond to a file on disk at all; it could correspond to an object or method in a running web application, or a database record, or anything else.</p>

Body:
Has anyone ever tried to implement a web server? Or know something about the underhood of a working web server program? I am wondering what happens exactly from when a URL is received by the web server to a file on the web server is located and sent back as response.

Does the server just keep an internal table to remember the mapping between the URLs it supports and the corresponding local paths? Or is there anything more tricky?

Thanks!

Update

Thanks for your replies. Here's my understanding for now.

I checked with the Microsoft IIS (Internet Information Service), I noticed that IIS can host multiple sites, and foreach site IIS memorize its root path on the local file system. Different sites on the same host share the same host name or IP, and they are differentiated by separate ports. For example:

http://www.myServer.com:1111/folderA/pageA.htm

The web server will use www.myServer.com:1111 part of the URL string to locate which path on its local file system will be used, and then in that local path, it searches for subfolder folderA and then the file pageA.htm.

The web server only need to memorize the following mapping between 2 plain strings:

"http://www.myServer.com:1111/" <---> "D:\myWebRoot"

I don't know where this kind of mapping info is stored, maybe some config files for the Web Server Program in question.

But the result of this mapping granularity is that we could only access content within that mapped local folder. We couldn't do arbitray mapping.

Update - 2 -

I found where the IIS keep the mapping, here's some quotes from applicationHost.config:

<sites>
    <site name="Default Web Site" id="1" serverAutoStart="false">
        <application path="/">
            <virtualDirectory path="/" physicalPath="%SystemDrive%\inetpub\wwwroot" />
        </application>
        <bindings>
            <binding protocol="http" bindingInformation="*:80:" />
            <binding protocol="net.tcp" bindingInformation="808:*" />
            <binding protocol="net.pipe" bindingInformation="*" />
            <binding protocol="net.msmq" bindingInformation="localhost" />
            <binding protocol="msmq.formatname" bindingInformation="localhost" />
        </bindings>
    </site>
    <site name="myIISService" id="2" serverAutoStart="true">
        <application path="/" applicationPool="myIISService">
            <virtualDirectory path="/" physicalPath="D:\MySites\MyIISService" />
        </application>
        <bindings>
            <binding protocol="http" bindingInformation="*:8022:" />
        </bindings>
    </site>
    <siteDefaults>
        <logFile logFormat="W3C" directory="%SystemDrive%\inetpub\logs\LogFiles" />
        <traceFailedRequestsLogging directory="%SystemDrive%\inetpub\logs\FailedReqLogFiles" />
    </siteDefaults>
    <applicationDefaults applicationPool="DefaultAppPool" />
    <virtualDirectoryDefaults allowSubDirConfig="true" />
</sites>

Update - 3 -

After I read foo's reply, my undersanding of a "server" is enlarged. I want to make some comment based on my recent learning of WCF.

No matter what kind of server it is, we could always send messages to them by specifying the protocol, URL, port. For example:

[http://www.myserver.com:1111/]page.htm

[net.tcp://www.myserver.com/]someService.svc/someMethod

[net.msmq://www.myserver.com/]someService.svc

[net.pipe://localhost/]

After the messages arrives at the server program using the parts in square bracket of above URLs, the rest part of the url will send to the server program as input for further processing. And the following behaviour could be as simple as static content feeding or as complex as dynamic content generating.


来源: stackexchange

问:
Function for table mathematical calculation
```<code>SNP Ind_1   Ind_2   Ind_3   Ind_4   Ind_5
SNP1     0       0       1       2       0
SNP2     2       0       1       2       1
SNP3     2       0       0       2       1
SNP4     1       1       2       2       2
</code>```

I want to do these following steps

Step 1. Add all SNP row values for Ind_1 and then subtract it by 10 and create a new rowname with score. Ex: Ind_1 = 0 + 2 + 2.....  = 5 and then 10-5=5

Step 2 Repeat the same analysis for Ind_2 to Ind_5`

There are more than 1000 Ind rows and more than 50 SNP columns. Thus a function for that will be a great help. Actual values are not 0, 1 or 2. They are like 1.5, 0.05, 0.001., means between 0 and 2. I just provided this table to look easier

Results should look like this

```<code>SNP Ind_1   Ind_2   Ind_3   Ind_4   Ind_5
SNP1      0       0      1       2       0
SNP2      2       0      1       2       0
SNP3      2       0      0       2       0
SNP4      1       1      2       2       0
SNP5      0       0      0       2       0
Score     5       9      6       0      10
</code>```

`

答:
A solution using base R. dt2 is the final output.

```<code>result <- as.data.frame(t(10 - colSums(dt[, 2:ncol(dt)])))
result$SNP <- "Score"
dt2 <- rbind(dt, result)
dt2

#     SNP Ind_1 Ind_2 Ind_3 Ind_4 Ind_5
# 1  SNP1     0     0     1     2     0
# 2  SNP2     2     0     1     2     1
# 3  SNP3     2     0     0     2     1
# 4  SNP4     1     1     2     2     2
# 5 Score     5     9     6     2     6
</code>```

DATA

```<code>dt <- read.table(text = "SNP Ind_1   Ind_2   Ind_3   Ind_4   Ind_5
SNP1     0       0       1       2       0
                 SNP2     2       0       1       2       1
                 SNP3     2       0       0       2       1
                 SNP4     1       1       2       2       2",
                 header = TRUE, stringsAsFactors = FALSE)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
SNP Ind_1   Ind_2   Ind_3   Ind_4   Ind_5
SNP1     0       0       1       2       0
SNP2     2       0       1       2       1
SNP3     2       0       0       2       1
SNP4     1       1       2       2       2

I want to do these following steps

Step 1. Add all SNP row values for Ind_1 and then subtract it by 10 and create a new rowname with score. Ex: Ind_1 = 0 + 2 + 2.....  = 5 and then 10-5=5

Step 2 Repeat the same analysis for Ind_2 to Ind_5`

There are more than 1000 Ind rows and more than 50 SNP columns. Thus a function for that will be a great help. Actual values are not 0, 1 or 2. They are like 1.5, 0.05, 0.001., means between 0 and 2. I just provided this table to look easier

Results should look like this

SNP Ind_1   Ind_2   Ind_3   Ind_4   Ind_5
SNP1      0       0      1       2       0
SNP2      2       0      1       2       0
SNP3      2       0      0       2       0
SNP4      1       1      2       2       0
SNP5      0       0      0       2       0
Score     5       9      6       0      10

`

Body:
A solution using base R. dt2 is the final output.

result <- as.data.frame(t(10 - colSums(dt[, 2:ncol(dt)])))
result$SNP <- "Score"
dt2 <- rbind(dt, result)
dt2

#     SNP Ind_1 Ind_2 Ind_3 Ind_4 Ind_5
# 1  SNP1     0     0     1     2     0
# 2  SNP2     2     0     1     2     1
# 3  SNP3     2     0     0     2     1
# 4  SNP4     1     1     2     2     2
# 5 Score     5     9     6     2     6

DATA

dt <- read.table(text = "SNP Ind_1   Ind_2   Ind_3   Ind_4   Ind_5
SNP1     0       0       1       2       0
                 SNP2     2       0       1       2       1
                 SNP3     2       0       0       2       1
                 SNP4     1       1       2       2       2",
                 header = TRUE, stringsAsFactors = FALSE)


问:
How to assign the value of a tag through javascript?
So I'm working on an application with a custom tag that formats long strings. I need to update the html inside a div tag with a string. I also need to assign the value of the custom tag with that string, store that html snippet in a variable, and then update the div.

I get this error when running the code below:

```<code>com.caucho.jsp.JspLineParseException: expected '>' at ''$''
(for tag '<customTag>' at line 511).  The XML tag syntax is: <tag
attr1='value1'>
</code>```

HTML:

```<code><div class='floatLeft clearFix bAllNoTop ' id="newText">
</div>
</code>```

Javascript:

```<code>function updateText(text){

outputText = "<customTag value=" + "$" +"{" + text + "}" + "convertNewLinesToBreaks='true'/>";

$("#newText").text(outputText);
    }
</code>```

答:
you have some formatting issues with your outputText value. Also in your example, you aren't declaring outputText anywhere so I'm going to assume it's not declared outside the method. If it is you can remove my var.

```<code>function updateText(text){
    var outputText = "<customTag value='${" + text + "}' convertNewLinesToBreaks='true'/>";

    $("#newText").html(outputText);
}
</code>```

Body:
So I'm working on an application with a custom tag that formats long strings. I need to update the html inside a div tag with a string. I also need to assign the value of the custom tag with that string, store that html snippet in a variable, and then update the div.

I get this error when running the code below:

com.caucho.jsp.JspLineParseException: expected '>' at ''$''
(for tag '<customTag>' at line 511).  The XML tag syntax is: <tag
attr1='value1'>

HTML:

Javascript:

function updateText(text){

outputText = "<customTag value=" + "$" +"{" + text + "}" + "convertNewLinesToBreaks='true'/>";

$("#newText").text(outputText);
    }

Body:
you have some formatting issues with your outputText value. Also in your example, you aren't declaring outputText anywhere so I'm going to assume it's not declared outside the method. If it is you can remove my var.

function updateText(text){
    var outputText = "<customTag value='${" + text + "}' convertNewLinesToBreaks='true'/>";

    $("#newText").html(outputText);
}


问:
How to search for a variable name in PostgreSQL?
I want to search for a particular variable name in ‘PostgreSQL’ database. Similar to the following ‘Teradata’ query

```<code>Select TableName, ColumnName from
DBC.Columns
Where ColumnName like (‘%profile%’)
</code>```

Is there a similar query in PostgreSQL?

答:
Postgres documentation</p>

```<code>SELECT table_name,column_name
FROM information_schema.columns
WHERE column_name  like '%profile%'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to search for a particular variable name in ‘PostgreSQL’ database. Similar to the following ‘Teradata’ query

Select TableName, ColumnName from
DBC.Columns
Where ColumnName like (‘%profile%’)

Is there a similar query in PostgreSQL?

Body:
Postgres documentation

SELECT table_name,column_name
FROM information_schema.columns
WHERE column_name  like '%profile%'


问:
Cross platform 2D graphics/game library
I'm looking for suggestions for a 2d game engine or library. I'm not picky about the language used but more about the capabilities of the library and the platforms it works on.

I would like to write one code base that would work on iOS, OSX, Android, Win and *nix. I understand there would be some platform specific code but I would like the bulk to be useable on all platforms.

I have looked around and I have some ideas but I'm looking for other opinions. Anyone have any ideas?

答:
I truly do not know if such a engine/framework exists. I think you are going to have to sacrifice a platform or two.

PyGame will run on everything you mentioned besides iOS.
http://www.pygame.org/news.html

That would be where I would start.

ContentLicense: CC BY-SA 2.5

Title: Cross platform 2D graphics/game library


问:
Why is my sequence generating incorrectly?
The goal of the code is to generate a sequence that operates as follows:
The first number is given, 2. To find the next number in the sequence: multiply all numbers in the sequence together than add 1. The smallest prime divisor of that number is the next number in the sequence. The first three number are [2, 3, 7]. So 237 + 1 = 43. The smallest prime factor is 43. So 43 is the next number. However when my code reaches the 5th number in the sequence it generates 139, instead of 13. 237*43 + 1 = 1807. 1807/13 = 139. So 13 should be next.

Problem: When my code reaches the 5th number in the sequence it generates 139

Note: Using BigInteger because reaching the 8th, 9th,... do not work with Int

```<code>    import java.math.BigInteger;
    import java.util.Scanner;
    import java.util.ArrayList;

    public class LPMSeq {

    public static BigInteger spd(BigInteger y) {

        ArrayList<BigInteger> primes = new ArrayList<BigInteger>();

        int retval = 0;
        int Nth_prime = 25200;
        BigInteger TWO = new BigInteger("2");
        BigInteger bi = new BigInteger("1");

        primes.add(TWO);

        int i = 1;

    //generates N prime numbers using isProbablePrime
        while (i < Nth_prime) {
            bi = bi.add(TWO);
            if (bi.isProbablePrime(80)) {
                i++;
                primes.add(bi);

            }
        }

        BigInteger zero = new BigInteger("0");

        // finds smallest prime divisor
        for (int n = 0; n < Nth_prime; n++) {
            BigInteger modded = y.mod(primes.get(n));
            if (modded.equals(zero)) {
                retval = primes.get(n).intValue();
            }
        }

        return BigInteger.valueOf(retval);
    }

    public static  ArrayList<BigInteger> LpmSeq(int k) {
            //ArrayList holding the sequence
        ArrayList<BigInteger> Seq = new ArrayList<BigInteger>();

        BigInteger two = new BigInteger ("2");
        //Add two to sequence (first number in sequence)
        Seq.add(two);
        while (Seq.size() < k) {
            BigInteger x = new BigInteger ("1");
            for (int i = 0; i < Seq.size(); i++) {
             x = x.multiply(Seq.get(i));
              }
            BigInteger y = x.add(BigInteger.ONE);
            BigInteger spd = spd(y);
            Seq.add(spd);
        }

        return Seq;
    }

        public static void main(String[] args) {

        //Create Scanner
        Scanner userinput = new Scanner(System.in);

        // Variables
        int k = 0;

        //Prompt user and get input
        System.out.println("How many elements would you like in the sequence? (Please enter an integer)");
        k = userinput.nextInt();

        System.out.println(LpmSeq(k));

        }

    }
</code>```

答:
Your loop that finds the smallest prime factor doesn't work if y isn't prime:

```<code>// finds smallest prime divisor
for (int n = 0; n < Nth_prime; n++) {
    BigInteger modded = y.mod(primes.get(n));
    if (modded.equals(zero)) {
        retval = primes.get(n).intValue();
    }
}
</code>```

It finds the largest prime factor, because it doesn't stop when it finds the first prime factor.  Because the factorization of 1807 is 13 x 139, it skips 13 and returns 139.

Place a break after you assign retval:

```<code>for (int n = 0; n < Nth_prime; n++) {
    BigInteger modded = y.mod(primes.get(n));
    if (modded.equals(zero)) {
        retval = primes.get(n).intValue();
        break;
    }
}
</code>```

Also, I find it curious that you're checking all primes through the 25,200th (and re-calculating all 25,200 of them each call).  You only need to check primes through the square root of y.

Body:
The goal of the code is to generate a sequence that operates as follows:
The first number is given, 2. To find the next number in the sequence: multiply all numbers in the sequence together than add 1. The smallest prime divisor of that number is the next number in the sequence. The first three number are [2, 3, 7]. So 237 + 1 = 43. The smallest prime factor is 43. So 43 is the next number. However when my code reaches the 5th number in the sequence it generates 139, instead of 13. 237*43 + 1 = 1807. 1807/13 = 139. So 13 should be next.

Problem: When my code reaches the 5th number in the sequence it generates 139

Note: Using BigInteger because reaching the 8th, 9th,... do not work with Int

    import java.math.BigInteger;
    import java.util.Scanner;
    import java.util.ArrayList;

    public class LPMSeq {

    public static BigInteger spd(BigInteger y) {

        ArrayList<BigInteger> primes = new ArrayList<BigInteger>();

        int retval = 0;
        int Nth_prime = 25200;
        BigInteger TWO = new BigInteger("2");
        BigInteger bi = new BigInteger("1");

        primes.add(TWO);

        int i = 1;

    //generates N prime numbers using isProbablePrime
        while (i < Nth_prime) {
            bi = bi.add(TWO);
            if (bi.isProbablePrime(80)) {
                i++;
                primes.add(bi);

            }
        }

        BigInteger zero = new BigInteger("0");

        // finds smallest prime divisor
        for (int n = 0; n < Nth_prime; n++) {
            BigInteger modded = y.mod(primes.get(n));
            if (modded.equals(zero)) {
                retval = primes.get(n).intValue();
            }
        }

        return BigInteger.valueOf(retval);
    }

    public static  ArrayList<BigInteger> LpmSeq(int k) {
            //ArrayList holding the sequence
        ArrayList<BigInteger> Seq = new ArrayList<BigInteger>();

        BigInteger two = new BigInteger ("2");
        //Add two to sequence (first number in sequence)
        Seq.add(two);
        while (Seq.size() < k) {
            BigInteger x = new BigInteger ("1");
            for (int i = 0; i < Seq.size(); i++) {
             x = x.multiply(Seq.get(i));
              }
            BigInteger y = x.add(BigInteger.ONE);
            BigInteger spd = spd(y);
            Seq.add(spd);
        }

        return Seq;
    }

        public static void main(String[] args) {

        //Create Scanner
        Scanner userinput = new Scanner(System.in);

        // Variables
        int k = 0;

        //Prompt user and get input
        System.out.println("How many elements would you like in the sequence? (Please enter an integer)");
        k = userinput.nextInt();

        System.out.println(LpmSeq(k));

        }

    }

Body:
Your loop that finds the smallest prime factor doesn't work if y isn't prime:

// finds smallest prime divisor
for (int n = 0; n < Nth_prime; n++) {
    BigInteger modded = y.mod(primes.get(n));
    if (modded.equals(zero)) {
        retval = primes.get(n).intValue();
    }
}

It finds the largest prime factor, because it doesn't stop when it finds the first prime factor.  Because the factorization of 1807 is 13 x 139, it skips 13 and returns 139.

Place a break after you assign retval:

for (int n = 0; n < Nth_prime; n++) {
    BigInteger modded = y.mod(primes.get(n));
    if (modded.equals(zero)) {
        retval = primes.get(n).intValue();
        break;
    }
}

Also, I find it curious that you're checking all primes through the 25,200th (and re-calculating all 25,200 of them each call).  You only need to check primes through the square root of y.


问:
Dropdown values lost after page reload ,
Javascript code for sending value to server through ajax

In my code , status  value can be different for different vulnerable name .

Upon choosing one status value among  different options , stored it in database by sending value to server through ajax,but after refreshing  webpage, selected value is lost , I want to see  last selected option value even after page reloads,

please visit sample image link once.  sample Image

< script >
  function statusval(value, vulname, vul_id) {
    var sv = value;
    var vn = vulname;
    var vi = vul_id;
    if (window.XMLHttpRequest) {
      xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    var data = "s_name=" + sv + "&v_name=" + vn + "&v_id=" + vi;
    xmlhttp.open("POST", "status.php", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send(data);
  } <
  /script>```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form method='post' action='status.php' id='status'>
  <select name='status' id='status' onchange='statusval(this.value,\"$_vulname\",\"$_vul_id\")'>
   <option value=''>Status</option>
  <option value='Open'>Open</option>
  <option value='closed'>Closed</option>
  <option value='Partially Fixed'>Partially Fixed</option>
</select>
  <input type='hidden' name='vulname' value='$_vulname' id='vulname'>
  <input type='hidden' name='vul_id' value='$_vul_id' id='vul_id'>
</form></code>```

答:
I assume you are able to retrieve the status from the database together with $_vulname and $_vul_id. Let's say you store the value in $_status. Then you can simply check for each option, if the status matches the value and set the selected attribute:

```<code><option value=''>Status</option>
<option value='Open'" . (($_status === 'Open') ? ' selected' : '') . ">Open</option>
<option value='closed'" . (($_status === 'closed') ? ' selected' : '') . ">Closed</option>
</code>```

Body:
Javascript code for sending value to server through ajax

In my code , status  value can be different for different vulnerable name .

Upon choosing one status value among  different options , stored it in database by sending value to server through ajax,but after refreshing  webpage, selected value is lost , I want to see  last selected option value even after page reloads,

please visit sample image link once.  sample Image

< script >
  function statusval(value, vulname, vul_id) {
    var sv = value;
    var vn = vulname;
    var vi = vul_id;
    if (window.XMLHttpRequest) {
      xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    var data = "s_name=" + sv + "&v_name=" + vn + "&v_id=" + vi;
    xmlhttp.open("POST", "status.php", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send(data);
  } <
  /script>

<form method='post' action='status.php' id='status'>
  <select name='status' id='status' onchange='statusval(this.value,\"$_vulname\",\"$_vul_id\")'>
   <option value=''>Status</option>
  <option value='Open'>Open</option>
  <option value='closed'>Closed</option>
  <option value='Partially Fixed'>Partially Fixed</option>
</select>
  <input type='hidden' name='vulname' value='$_vulname' id='vulname'>
  <input type='hidden' name='vul_id' value='$_vul_id' id='vul_id'>
</form>

Body:
I assume you are able to retrieve the status from the database together with $_vulname and $_vul_id. Let's say you store the value in $_status. Then you can simply check for each option, if the status matches the value and set the selected attribute:

<option value=''>Status</option>
<option value='Open'" . (($_status === 'Open') ? ' selected' : '') . ">Open</option>
<option value='closed'" . (($_status === 'closed') ? ' selected' : '') . ">Closed</option>


问:
How to store (string, double, int) data from file to 3 parallel arrays?
I just need help to see how to populate 3 separate arrays based on the formatting of the input file...

I know if its on a single array and if the data in the file is of one type all you need to do is a for loop. However with 3 I don't know

This is the code I have so far,
int netIDArray is for storing the first set of numbers
string majorArray is for storing the next column, of letters.
double gpaArray is for storing the next column of decimal numbers.

```<code>#include <iostream>
#include <fstream>

using namespace std;

int netIDArray[15];
string majorArray[15];
double gpaArray[15];

int main()
{
    ifstream file;
    file.open ("studentData1.txt");
    // If error in opening file then return
    if (!file)
    {
      cout << "Error opening file" << endl;
    }

    if(file.is_open())
    {
        string majorArray[15];

        for(int i = 0; i < 5; ++i)
        {
            file >> majorArray[i];
        }
    }

    return 0;
}
</code>```

答:
What you probably want to do is

```<code>struct MyData {
    int netID;
    std::string major;
    double gpa;
};

std::ostream& operator<<(std::ostream& os, const MyData& myData) {
    os << "netId = " << myData.netId
       << ", major = " << myData.major
       << ", gpa = " << myData.gpa;
    return os;
};

int main() {
    std::ifstream file("studentData1.txt");
    // If error in opening file then return
    if (!file) {
        std::cout << "Error opening file" << endl;
        exit(1);
    }

    std::vector<MyData> majorArray;
    std::string line;
    while(std::getline(file,line)) {
        std::istringstream iss(line);
        MyData myData;
        if(!(iss >> myData.netID >> myData.major >> myData.gpa)) {
            // Handle parsing errors
        }
        else {
            majorArray.push_back(myData);
        }
    }

    for(const auto& major : majorArray) {
        std::cout << major << std::endl;
    }
    return 0;
}
</code>```

As you seem to have a restriction not letting you use a struct and single vector as mentioned above, here's a slightly refactored example:

```<code>int main() {
    std::ifstream file("studentData1.txt");
    // If error in opening file then return
    if (!file) {
        std::cout << "Error opening file" << endl;
        exit(1);
    }

    std::vector<int> netIDArray;
    std::vector<std:string> majorArray;
    std::vector<double> gpaArray;
    std::string line;
    while(std::getline(file,line)) {
        std::istringstream iss(line);
        int netId;
        std::string major;
        double gpa;
        if(!(iss >> netID >> major >> gpa)) {
            // Handle parsing errors
        }
        else {
            netIDArray.push_back(netId);
            majorArray.push_back(major);
            gpaArray.push_back(gpa);
        }
    }

    for(auto itNetId = std::begin(netIDArray),
             itMajor = std::begin(majorArray),
             itGpa = std::begin(gpaArray);
        itNetId != std::end(netIdArray)) &&
        itMajor != std::end(majorArray) &&
        itGpa != std::end(gpaArray);
        ++itNetId, ++itMajor, ++itGpa) {
           std::cout << "netId = " << *itNetId
                     << ", major = " << *itMajor
                     << ", gpa = " << *itGpa;
    }

    return 0;
}
</code>```

And here's the raw array variant as you seem to be restricted to also:

```<code>int main() {
    std::ifstream file("studentData1.txt");
    // If error in opening file then return
    if (!file) {
        std::cout << "Error opening file" << endl;
        exit(1);
    }

    const std::size_t InputSize = 15;
    int netIDArray[InputSize ];
    std:string majorArray[InputSize];
    double gpaArray[InputSize];
    std::string line;
    for(std::size_t index = 0;
        index < InputSize && std::getline(file,line);
        ++index) {
        std::istringstream iss(line);
        int netId;
        std::string major;
        double gpa;
        if(!(iss >> netID >> major >> gpa)) {
            // Handle parsing errors
        }
        else {
            netIDArray[index] = netId;
            majorArray[index] = major;
            gpaArray[index] = gpa;
        }
    }

    for(auto itNetId = std::begin(netIDArray),
             itMajor = std::begin(majorArray),
             itGpa = std::begin(gpaArray);
        itNetId != std::end(netIdArray)) &&
        itMajor != std::end(majorArray) &&
        itGpa != std::end(gpaArray);
        ++itNetId, ++itMajor, ++itGpa) {
           std::cout << "netId = " << *itNetId
                     << ", major = " << *itMajor
                     << ", gpa = " << *itGpa;
    }

    return 0;
}
</code>```

Body:
I just need help to see how to populate 3 separate arrays based on the formatting of the input file...

I know if its on a single array and if the data in the file is of one type all you need to do is a for loop. However with 3 I don't know

This is the code I have so far,
int netIDArray is for storing the first set of numbers
string majorArray is for storing the next column, of letters.
double gpaArray is for storing the next column of decimal numbers.

#include <iostream>
#include <fstream>

using namespace std;

int netIDArray[15];
string majorArray[15];
double gpaArray[15];

int main()
{
    ifstream file;
    file.open ("studentData1.txt");
    // If error in opening file then return
    if (!file)
    {
      cout << "Error opening file" << endl;
    }

    if(file.is_open())
    {
        string majorArray[15];

        for(int i = 0; i < 5; ++i)
        {
            file >> majorArray[i];
        }
    }

    return 0;
}

Body:
What you probably want to do is

struct MyData {
    int netID;
    std::string major;
    double gpa;
};

std::ostream& operator<<(std::ostream& os, const MyData& myData) {
    os << "netId = " << myData.netId
       << ", major = " << myData.major
       << ", gpa = " << myData.gpa;
    return os;
};

int main() {
    std::ifstream file("studentData1.txt");
    // If error in opening file then return
    if (!file) {
        std::cout << "Error opening file" << endl;
        exit(1);
    }

    std::vector<MyData> majorArray;
    std::string line;
    while(std::getline(file,line)) {
        std::istringstream iss(line);
        MyData myData;
        if(!(iss >> myData.netID >> myData.major >> myData.gpa)) {
            // Handle parsing errors
        }
        else {
            majorArray.push_back(myData);
        }
    }

    for(const auto& major : majorArray) {
        std::cout << major << std::endl;
    }
    return 0;
}

As you seem to have a restriction not letting you use a struct and single vector as mentioned above, here's a slightly refactored example:

int main() {
    std::ifstream file("studentData1.txt");
    // If error in opening file then return
    if (!file) {
        std::cout << "Error opening file" << endl;
        exit(1);
    }

    std::vector<int> netIDArray;
    std::vector<std:string> majorArray;
    std::vector<double> gpaArray;
    std::string line;
    while(std::getline(file,line)) {
        std::istringstream iss(line);
        int netId;
        std::string major;
        double gpa;
        if(!(iss >> netID >> major >> gpa)) {
            // Handle parsing errors
        }
        else {
            netIDArray.push_back(netId);
            majorArray.push_back(major);
            gpaArray.push_back(gpa);
        }
    }

    for(auto itNetId = std::begin(netIDArray),
             itMajor = std::begin(majorArray),
             itGpa = std::begin(gpaArray);
        itNetId != std::end(netIdArray)) &&
        itMajor != std::end(majorArray) &&
        itGpa != std::end(gpaArray);
        ++itNetId, ++itMajor, ++itGpa) {
           std::cout << "netId = " << *itNetId
                     << ", major = " << *itMajor
                     << ", gpa = " << *itGpa;
    }

    return 0;
}

And here's the raw array variant as you seem to be restricted to also:

int main() {
    std::ifstream file("studentData1.txt");
    // If error in opening file then return
    if (!file) {
        std::cout << "Error opening file" << endl;
        exit(1);
    }

    const std::size_t InputSize = 15;
    int netIDArray[InputSize ];
    std:string majorArray[InputSize];
    double gpaArray[InputSize];
    std::string line;
    for(std::size_t index = 0;
        index < InputSize && std::getline(file,line);
        ++index) {
        std::istringstream iss(line);
        int netId;
        std::string major;
        double gpa;
        if(!(iss >> netID >> major >> gpa)) {
            // Handle parsing errors
        }
        else {
            netIDArray[index] = netId;
            majorArray[index] = major;
            gpaArray[index] = gpa;
        }
    }

    for(auto itNetId = std::begin(netIDArray),
             itMajor = std::begin(majorArray),
             itGpa = std::begin(gpaArray);
        itNetId != std::end(netIdArray)) &&
        itMajor != std::end(majorArray) &&
        itGpa != std::end(gpaArray);
        ++itNetId, ++itMajor, ++itGpa) {
           std::cout << "netId = " << *itNetId
                     << ", major = " << *itMajor
                     << ", gpa = " << *itGpa;
    }

    return 0;
}


问:
How can I check if a value is a JSON object?
My server side code returns a value which is a JSON object on success and a string 'false' on failure. Now how can I check whether the returned value is a JSON object?</p>

答:
I don't really like the accepted answer. First and foremost it requires jQuery, which is not always available or required. Secondly, it does a full stringification of the object which to me is overkill. Here's a simple function that thoroughly detects whether a value is JSON-like, using nothing more than a few parts of the lodash library for genericity.

```<code>import * as isNull from 'lodash/isNull'
import * as isPlainObject from 'lodash/isPlainObject'
import * as isNumber from 'lodash/isNumber'
import * as isBoolean from 'lodash/isBoolean'
import * as isString from 'lodash/isString'
import * as isArray from 'lodash/isArray'

function isJSON(val) {
  if (isNull(val)
   || isBoolean(val)
   || isString(val))
    return true;
  if (isNumber(val))
     return !isNaN(val) && isFinite(val)
  if (isArray(val))
    return Array.prototype.every.call(val, isJSON)
  if (isPlainObject(val)) {
    for (const key of Object.keys(val)) {
      if (!isJSON(val[key]))
        return false
    }
    return true
  }
  return false
}
</code>```

I've even taken the time to put it up in npm as a package: https://npmjs.com/package/is-json-object. Use it together with something like Webpack to get it in the browser.

Hope this helps someone!

Body:
I don't really like the accepted answer. First and foremost it requires jQuery, which is not always available or required. Secondly, it does a full stringification of the object which to me is overkill. Here's a simple function that thoroughly detects whether a value is JSON-like, using nothing more than a few parts of the lodash library for genericity.

import * as isNull from 'lodash/isNull'
import * as isPlainObject from 'lodash/isPlainObject'
import * as isNumber from 'lodash/isNumber'
import * as isBoolean from 'lodash/isBoolean'
import * as isString from 'lodash/isString'
import * as isArray from 'lodash/isArray'

function isJSON(val) {
  if (isNull(val)
   || isBoolean(val)
   || isString(val))
    return true;
  if (isNumber(val))
     return !isNaN(val) && isFinite(val)
  if (isArray(val))
    return Array.prototype.every.call(val, isJSON)
  if (isPlainObject(val)) {
    for (const key of Object.keys(val)) {
      if (!isJSON(val[key]))
        return false
    }
    return true
  }
  return false
}

I've even taken the time to put it up in npm as a package: https://npmjs.com/package/is-json-object. Use it together with something like Webpack to get it in the browser.

Hope this helps someone!


问:
Vue2.js and Firebase looping with v-for and :key can't get value

Looping through a Firebase project using v-for and having a devil of a time trying to get one value (imgurl) for each item. Here are a couple rows form the firebase object:

firebase data

Here is my script code in App.vue.

```<code><script>
import Firebase from "firebase";
let config = {
   …all correct blah blah…
};
let app = Firebase.initializeApp(config);
let db = app.database();
let itemsRef = db.ref("tblItems");
export default {
  name: "app",
  firebase: {
    items: itemsRef
  },
  data() {
    return {
      styleObject: {
        backgroundImage: "" //RIGHT IN HERE I NEED item.imgname BUT CAN'T FIGURE OUT SYNTAX.
           }
    };
  }
};
</code>```

Here is where I loop through using v-for and key and I call StyleObject.

```<code><template>
  <div id="app">
      <div v-for="item in items" :key="item.id" v-bind:style="styleObject">
         <h1>{{ item.title }}</h1>
         <h2>{{ item.author }}</h2>
    </div>
    <router-view/>
  </div>
</template>
</code>```

Everything works fine, except I can't figure you how to get item.imgname where the RIGHT IN HERE comment is so I can use it for a background image in a style= attribute (each div has its own background image). Any help much appreciated.

答:
In my opinion the easiest way to do that is to make de div into a new component and to pass the image name as a prop into it. Your component will then look like this:

```<code>Vue.component('exampleDiv', {
  props: ['imgname','title','author'],
  template: '<div :style="styleObject">
     <h1>{{ title }}</h1>
     <h2>{{ author }}</h2>
     </div> ',
    data() {
        return {
            styleObject: {
                backgroundImage: this.imgname
            }
         }
})
</code>```

You can then call the component in your code like this:

```<code><template>
      <div id="app">
          <exampleDiv v-for="item in items"
               :key="item.id" :title="item.title"
               :author="item.author" :imgname = "item.imgname">
        </exampleDiv>
        <router-view/>
    </div>
</template>
</code>```

Body:
In my opinion the easiest way to do that is to make de div into a new component and to pass the image name as a prop into it. Your component will then look like this:

Vue.component('exampleDiv', {
  props: ['imgname','title','author'],
  template: '<div :style="styleObject">
     <h1>{{ title }}</h1>
     <h2>{{ author }}</h2>
     </div> ',
    data() {
        return {
            styleObject: {
                backgroundImage: this.imgname
            }
         }
})

You can then call the component in your code like this:

<template>
      <div id="app">
          <exampleDiv v-for="item in items"
               :key="item.id" :title="item.title"
               :author="item.author" :imgname = "item.imgname">
        </exampleDiv>
        <router-view/>
    </div>
</template>


问:
Saving title of NSSegmentedControl in User defaults
Thanks for the help:

I manually set the title of a segController segment from a textField input like this:

```<code>NSString  *labelString = [textField stringValue];
(textField.stringValue = labelString);
[segControl setLabel: labelString forSegment:8];
</code>```

I loose the new label when quitting. How can I save the edited segController label string in NSUserDefaults as I would with a text string, like this:

```<code>    [[NSUserDefaults standardUserDefaults] setObject: [textField objectValue] forKey: @"newDefault"];
</code>```

My action needs to occasionally set a new title. Point is the label string is not permanently fixed.

thanks.

Paul.

答:
Assuming you know the segment number, You can do the following:

```<code>NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
if(defaults) {
    [defaults setValue: [segControl labelForSegment:8] forKey: @"segmentLabel"];
}
else {
    // handle error
}
</code>```

Alternatively you can just save the string to NSUserDefaults whenever you set the label like in your above example.

Body:
Thanks for the help:

I manually set the title of a segController segment from a textField input like this:

NSString  *labelString = [textField stringValue];
(textField.stringValue = labelString);
[segControl setLabel: labelString forSegment:8];

I loose the new label when quitting. How can I save the edited segController label string in NSUserDefaults as I would with a text string, like this:

    [[NSUserDefaults standardUserDefaults] setObject: [textField objectValue] forKey: @"newDefault"];

My action needs to occasionally set a new title. Point is the label string is not permanently fixed.

thanks.

Paul.

Body:
Assuming you know the segment number, You can do the following:

NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
if(defaults) {
    [defaults setValue: [segControl labelForSegment:8] forKey: @"segmentLabel"];
}
else {
    // handle error
}

Alternatively you can just save the string to NSUserDefaults whenever you set the label like in your above example.


问:
Relay access denied when sending email from client - Postfix misconfiguration?
I have built an email server using Postfix and Dovecot. I got it working using Roundcube, it sends and receives emails as it should.
But when I try to send an email from an external client (ex: default Android mail client), the email gets rejected and I get this error in the logs:
NOQUEUE: reject: RCPT from staticline-my-public-ip.toya.net.pl[my-public-ip]: 554 5.7.1 <someuser@yahoo.com>: Relay access denied; from=<someuser@mydomain.ro> to=<someuser@yahoo.com> proto=ESMTP helo=<[10.3.177.176]>

I think it might be a Postfix misconfiguration, this is the first time I'm building an email server.

postconf -n returns this:

```<code>alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
append_dot_mydomain = no
biff = no
home_mailbox = Maildir/
inet_interfaces = all
inet_protocols = ipv4
mailbox_size_limit = 0
mydestination = $myhostname localhost.$mydomain localhost $mydomain laiancu.ro
mydomain = luckypizza.ro
myhostname = mail.luckypizza.ro
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mynetworks_style = class
myorigin = $mydomain
recipient_delimiter = +
smtp_tls_mandatory_protocols = !SSLv2,!SSLv3
smtp_tls_protocols = !SSLv2,!SSLv3
smtp_tls_security_level = may
smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu/GNU)
smtpd_recipient_restrictions = permit_sasl_authenticated
smtpd_relay_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination
smtpd_sasl_auth_enable = yes
smtpd_sasl_path = private/auth
smtpd_sasl_security_options = noplaintext,noanonymous
smtpd_sasl_type = dovecot
smtpd_tls_auth_only = yes
smtpd_tls_cert_file = /etc/letsencrypt/live/mail.luckypizza.ro/fullchain.pem
smtpd_tls_key_file = /etc/letsencrypt/live/mail.luckypizza.ro/privkey.pem
smtpd_tls_mandatory_ciphers = high
smtpd_tls_mandatory_protocols = !SSLv2,!SSLv3
smtpd_tls_protocols = !SSLv2,!SSLv3
smtpd_use_tls = yes
tls_high_cipherlist = ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:DHE-DSS-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA256:ADH-AES256-GCM-SHA384:ADH-AES256-SHA256:ECDH-RSA-AES256-GCM-SHA384:ECDH-ECDSA-AES256-GCM-SHA384:ECDH-RSA-AES256-SHA384:ECDH-ECDSA-AES256-SHA384:AES256-GCM-SHA384:AES256-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:DHE-DSS-AES128-GCM-SHA256:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES128-SHA256:DHE-DSS-AES128-SHA256:ADH-AES128-GCM-SHA256:ADH-AES128-SHA256:ECDH-RSA-AES128-GCM-SHA256:ECDH-ECDSA-AES128-GCM-SHA256:ECDH-RSA-AES128-SHA256:ECDH-ECDSA-AES128-SHA256:AES128-GCM-SHA256:AES128-SHA256:NULL-SHA256
tls_preempt_cipherlist = yes
virtual_gid_maps = static:5000
virtual_mailbox_base = /home/vmail
virtual_mailbox_domains = /etc/postfix/vhosts
virtual_mailbox_maps = hash:/etc/postfix/vmaps
virtual_minimum_uid = 1000
virtual_uid_maps = static:5000
</code>```

And my master.cf

```<code>#
# Postfix master process configuration file.  For details on the format
# of the file, see the master(5) manual page (command: "man 5 master" or
# on-line: http://www.postfix.org/master.5.html).
#
# Do not forget to execute "postfix reload" after editing this file.
#
# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (no)    (never) (100)
# ==========================================================================
smtp      inet  n       -       y       -       -       smtpd
#smtp      inet  n       -       y       -       1       postscreen
#smtpd     pass  -       -       y       -       -       smtpd
#dnsblog   unix  -       -       y       -       0       dnsblog
#tlsproxy  unix  -       -       y       -       0       tlsproxy
submission inet n       -       -       -       -       smtpd
  -o syslog_name=postfix/submission
  -o smtpd_tls_wrappermode=no
  -o smtpd_tls_security_level=encrypt
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_recipient_restrictions=permit_mynetworks,permit_sasl_authenticated,reject
  -o milter_macro_daemon_name=ORIGINATING
  -o smtpd_sasl_type=dovecot
  -o smtpd_sasl_path=private/auth
smtps     inet  n       -       y       -       -       smtpd
  -o syslog_name=postfix/smtps
  -o smtpd_tls_wrappermode=yes
  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_reject_unlisted_recipient=no
#  -o smtpd_client_restrictions=$mua_client_restrictions
#  -o smtpd_helo_restrictions=$mua_helo_restrictions
#  -o smtpd_sender_restrictions=$mua_sender_restrictions
#  -o smtpd_recipient_restrictions=
#  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
#628       inet  n       -       y       -       -       qmqpd
pickup    unix  n       -       y       60      1       pickup
cleanup   unix  n       -       y       -       0       cleanup
qmgr      unix  n       -       n       300     1       qmgr
#qmgr     unix  n       -       n       300     1       oqmgr
tlsmgr    unix  -       -       y       1000?   1       tlsmgr
rewrite   unix  -       -       y       -       -       trivial-rewrite
bounce    unix  -       -       y       -       0       bounce
defer     unix  -       -       y       -       0       bounce
trace     unix  -       -       y       -       0       bounce
verify    unix  -       -       y       -       1       verify
flush     unix  n       -       y       1000?   0       flush
proxymap  unix  -       -       n       -       -       proxymap
proxywrite unix -       -       n       -       1       proxymap
smtp      unix  -       -       y       -       -       smtp
relay     unix  -       -       y       -       -       smtp
#       -o smtp_helo_timeout=5 -o smtp_connect_timeout=5
showq     unix  n       -       y       -       -       showq
error     unix  -       -       y       -       -       error
retry     unix  -       -       y       -       -       error
discard   unix  -       -       y       -       -       discard
local     unix  -       n       n       -       -       local
virtual   unix  -       n       n       -       -       virtual
lmtp      unix  -       -       y       -       -       lmtp
anvil     unix  -       -       y       -       1       anvil
scache    unix  -       -       y       -       1       scache
#
# ====================================================================
# Interfaces to non-Postfix software. Be sure to examine the manual
# pages of the non-Postfix software to find out what options it wants.
#
# Many of the following services use the Postfix pipe(8) delivery
# agent.  See the pipe(8) man page for information about ${recipient}
# and other message envelope options.
# ====================================================================
#
# maildrop. See the Postfix MAILDROP_README file for details.
# Also specify in main.cf: maildrop_destination_recipient_limit=1
#
maildrop  unix  -       n       n       -       -       pipe
  flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}
#
# ====================================================================
#
# Recent Cyrus versions can use the existing "lmtp" master.cf entry.
#
# Specify in cyrus.conf:
#   lmtp    cmd="lmtpd -a" listen="localhost:lmtp" proto=tcp4
#
# Specify in main.cf one or more of the following:
#  mailbox_transport = lmtp:inet:localhost
#  virtual_transport = lmtp:inet:localhost
#
# ====================================================================
#
# Cyrus 2.1.5 (Amos Gouaux)
# Also specify in main.cf: cyrus_destination_recipient_limit=1
#
#cyrus     unix  -       n       n       -       -       pipe
#  user=cyrus argv=/cyrus/bin/deliver -e -r ${sender} -m ${extension} ${user}
#
# ====================================================================
# Old example of delivery via Cyrus.
#
#old-cyrus unix  -       n       n       -       -       pipe
#  flags=R user=cyrus argv=/cyrus/bin/deliver -e -m ${extension} ${user}
#
# ====================================================================
#
# See the Postfix UUCP_README file for configuration details.
#
uucp      unix  -       n       n       -       -       pipe
  flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)
#
# Other external delivery methods.
#
ifmail    unix  -       n       n       -       -       pipe
  flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient)
bsmtp     unix  -       n       n       -       -       pipe
  flags=Fq. user=bsmtp argv=/usr/lib/bsmtp/bsmtp -t$nexthop -f$sender $recipient
scalemail-backend unix  -   n   n   -   2   pipe
  flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store ${nexthop} ${user} ${extension}
mailman   unix  -       n       n       -       -       pipe
  flags=FR user=list argv=/usr/lib/mailman/bin/postfix-to-mailman.py
  ${nexthop} ${user}
</code>```

My raw main.cf file:

```<code>smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu/GNU)
biff = no

# appending .domain is the MUA's job.
append_dot_mydomain = no

# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h

myhostname = mail.luckypizza.ro
mydomain = luckypizza.ro
myorigin = $mydomain
mydestination = $myhostname localhost.$mydomain localhost $mydomain laiancu.ro

alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mynetworks_style = class

mailbox_size_limit = 0
home_mailbox = Maildir/

virtual_mailbox_domains = /etc/postfix/vhosts
virtual_mailbox_base = /home/vmail
virtual_mailbox_maps = hash:/etc/postfix/vmaps
virtual_minimum_uid = 1000
virtual_uid_maps = static:5000
virtual_gid_maps = static:5000

recipient_delimiter = +

inet_interfaces = all
inet_protocols = ipv4

# TLS parameters
smtpd_use_tls=yes
smtpd_tls_auth_only = yes
smtpd_tls_cert_file = /etc/letsencrypt/live/mail.luckypizza.ro/fullchain.pem
smtpd_tls_key_file = /etc/letsencrypt/live/mail.luckypizza.ro/privkey.pem
smtp_tls_security_level = may
smtpd_tls_mandatory_protocols=!SSLv2,!SSLv3
smtp_tls_mandatory_protocols=!SSLv2,!SSLv3
smtpd_tls_protocols=!SSLv2,!SSLv3
smtp_tls_protocols=!SSLv2,!SSLv3

tls_preempt_cipherlist = yes
smtpd_tls_mandatory_ciphers = high
tls_high_cipherlist = ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:DHE-DSS-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA256:ADH-AES256-GCM-SHA384:ADH-AES256-SHA256:ECDH-RSA-AES256-GCM-SHA384:ECDH-ECDSA-AES256-GCM-SHA384:ECDH-RSA-AES256-SHA384:ECDH-ECDSA-AES256-SHA384:AES256-GCM-SHA384:AES256-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:DHE-DSS-AES128-GCM-SHA256:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES128-SHA256:DHE-DSS-AES128-SHA256:ADH-AES128-GCM-SHA256:ADH-AES128-SHA256:ECDH-RSA-AES128-GCM-SHA256:ECDH-ECDSA-AES128-GCM-SHA256:ECDH-RSA-AES128-SHA256:ECDH-ECDSA-AES128-SHA256:AES128-GCM-SHA256:AES128-SHA256:NULL-SHA256
smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noplaintext,noanonymous

smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth

smtpd_relay_restrictions =
  permit_mynetworks,
  permit_sasl_authenticated,
  reject_unauth_destination

smtpd_recipient_restrictions = permit_sasl_authenticated
</code>```

What I have tried so far:

Removing the smtpd_recipient_restrictions

Connect from the client both with and without TLS

Changing mydomain and/or myhostname with 'localhost'

I think Roundcube works because of the smtpd_relay_restrictions = permit_mynetworks line, because it's on the same host, so the external clients might fail because they don't meet the permit_sasl_authenticated rule in smtpd_relay_restrictions. However, I don't understand why it does not.

答:
Solved!
It looks like the problem was on this line:

smtpd_sasl_security_options = noplaintext,noanonymous

I am using Dovecot to create the virtual mailboxes and its configuration requires plaintext authentication, so I had to change it to:

smtpd_sasl_security_options = noanonymous

(the declaration can also be completely removed from the main.cf file, since noanonymous is the default value for this variable.

Body:
I have built an email server using Postfix and Dovecot. I got it working using Roundcube, it sends and receives emails as it should.
But when I try to send an email from an external client (ex: default Android mail client), the email gets rejected and I get this error in the logs:
NOQUEUE: reject: RCPT from staticline-my-public-ip.toya.net.pl[my-public-ip]: 554 5.7.1 <someuser@yahoo.com>: Relay access denied; from=<someuser@mydomain.ro> to=<someuser@yahoo.com> proto=ESMTP helo=<[10.3.177.176]>

I think it might be a Postfix misconfiguration, this is the first time I'm building an email server.

postconf -n returns this:

alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
append_dot_mydomain = no
biff = no
home_mailbox = Maildir/
inet_interfaces = all
inet_protocols = ipv4
mailbox_size_limit = 0
mydestination = $myhostname localhost.$mydomain localhost $mydomain laiancu.ro
mydomain = luckypizza.ro
myhostname = mail.luckypizza.ro
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mynetworks_style = class
myorigin = $mydomain
recipient_delimiter = +
smtp_tls_mandatory_protocols = !SSLv2,!SSLv3
smtp_tls_protocols = !SSLv2,!SSLv3
smtp_tls_security_level = may
smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu/GNU)
smtpd_recipient_restrictions = permit_sasl_authenticated
smtpd_relay_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination
smtpd_sasl_auth_enable = yes
smtpd_sasl_path = private/auth
smtpd_sasl_security_options = noplaintext,noanonymous
smtpd_sasl_type = dovecot
smtpd_tls_auth_only = yes
smtpd_tls_cert_file = /etc/letsencrypt/live/mail.luckypizza.ro/fullchain.pem
smtpd_tls_key_file = /etc/letsencrypt/live/mail.luckypizza.ro/privkey.pem
smtpd_tls_mandatory_ciphers = high
smtpd_tls_mandatory_protocols = !SSLv2,!SSLv3
smtpd_tls_protocols = !SSLv2,!SSLv3
smtpd_use_tls = yes
tls_high_cipherlist = ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:DHE-DSS-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA256:ADH-AES256-GCM-SHA384:ADH-AES256-SHA256:ECDH-RSA-AES256-GCM-SHA384:ECDH-ECDSA-AES256-GCM-SHA384:ECDH-RSA-AES256-SHA384:ECDH-ECDSA-AES256-SHA384:AES256-GCM-SHA384:AES256-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:DHE-DSS-AES128-GCM-SHA256:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES128-SHA256:DHE-DSS-AES128-SHA256:ADH-AES128-GCM-SHA256:ADH-AES128-SHA256:ECDH-RSA-AES128-GCM-SHA256:ECDH-ECDSA-AES128-GCM-SHA256:ECDH-RSA-AES128-SHA256:ECDH-ECDSA-AES128-SHA256:AES128-GCM-SHA256:AES128-SHA256:NULL-SHA256
tls_preempt_cipherlist = yes
virtual_gid_maps = static:5000
virtual_mailbox_base = /home/vmail
virtual_mailbox_domains = /etc/postfix/vhosts
virtual_mailbox_maps = hash:/etc/postfix/vmaps
virtual_minimum_uid = 1000
virtual_uid_maps = static:5000

And my master.cf

#
# Postfix master process configuration file.  For details on the format
# of the file, see the master(5) manual page (command: "man 5 master" or
# on-line: http://www.postfix.org/master.5.html).
#
# Do not forget to execute "postfix reload" after editing this file.
#
# ==========================================================================
# service type  private unpriv  chroot  wakeup  maxproc command + args
#               (yes)   (yes)   (no)    (never) (100)
# ==========================================================================
smtp      inet  n       -       y       -       -       smtpd
#smtp      inet  n       -       y       -       1       postscreen
#smtpd     pass  -       -       y       -       -       smtpd
#dnsblog   unix  -       -       y       -       0       dnsblog
#tlsproxy  unix  -       -       y       -       0       tlsproxy
submission inet n       -       -       -       -       smtpd
  -o syslog_name=postfix/submission
  -o smtpd_tls_wrappermode=no
  -o smtpd_tls_security_level=encrypt
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_recipient_restrictions=permit_mynetworks,permit_sasl_authenticated,reject
  -o milter_macro_daemon_name=ORIGINATING
  -o smtpd_sasl_type=dovecot
  -o smtpd_sasl_path=private/auth
smtps     inet  n       -       y       -       -       smtpd
  -o syslog_name=postfix/smtps
  -o smtpd_tls_wrappermode=yes
  -o smtpd_sasl_auth_enable=yes
#  -o smtpd_reject_unlisted_recipient=no
#  -o smtpd_client_restrictions=$mua_client_restrictions
#  -o smtpd_helo_restrictions=$mua_helo_restrictions
#  -o smtpd_sender_restrictions=$mua_sender_restrictions
#  -o smtpd_recipient_restrictions=
#  -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
#  -o milter_macro_daemon_name=ORIGINATING
#628       inet  n       -       y       -       -       qmqpd
pickup    unix  n       -       y       60      1       pickup
cleanup   unix  n       -       y       -       0       cleanup
qmgr      unix  n       -       n       300     1       qmgr
#qmgr     unix  n       -       n       300     1       oqmgr
tlsmgr    unix  -       -       y       1000?   1       tlsmgr
rewrite   unix  -       -       y       -       -       trivial-rewrite
bounce    unix  -       -       y       -       0       bounce
defer     unix  -       -       y       -       0       bounce
trace     unix  -       -       y       -       0       bounce
verify    unix  -       -       y       -       1       verify
flush     unix  n       -       y       1000?   0       flush
proxymap  unix  -       -       n       -       -       proxymap
proxywrite unix -       -       n       -       1       proxymap
smtp      unix  -       -       y       -       -       smtp
relay     unix  -       -       y       -       -       smtp
#       -o smtp_helo_timeout=5 -o smtp_connect_timeout=5
showq     unix  n       -       y       -       -       showq
error     unix  -       -       y       -       -       error
retry     unix  -       -       y       -       -       error
discard   unix  -       -       y       -       -       discard
local     unix  -       n       n       -       -       local
virtual   unix  -       n       n       -       -       virtual
lmtp      unix  -       -       y       -       -       lmtp
anvil     unix  -       -       y       -       1       anvil
scache    unix  -       -       y       -       1       scache
#
# ====================================================================
# Interfaces to non-Postfix software. Be sure to examine the manual
# pages of the non-Postfix software to find out what options it wants.
#
# Many of the following services use the Postfix pipe(8) delivery
# agent.  See the pipe(8) man page for information about ${recipient}
# and other message envelope options.
# ====================================================================
#
# maildrop. See the Postfix MAILDROP_README file for details.
# Also specify in main.cf: maildrop_destination_recipient_limit=1
#
maildrop  unix  -       n       n       -       -       pipe
  flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}
#
# ====================================================================
#
# Recent Cyrus versions can use the existing "lmtp" master.cf entry.
#
# Specify in cyrus.conf:
#   lmtp    cmd="lmtpd -a" listen="localhost:lmtp" proto=tcp4
#
# Specify in main.cf one or more of the following:
#  mailbox_transport = lmtp:inet:localhost
#  virtual_transport = lmtp:inet:localhost
#
# ====================================================================
#
# Cyrus 2.1.5 (Amos Gouaux)
# Also specify in main.cf: cyrus_destination_recipient_limit=1
#
#cyrus     unix  -       n       n       -       -       pipe
#  user=cyrus argv=/cyrus/bin/deliver -e -r ${sender} -m ${extension} ${user}
#
# ====================================================================
# Old example of delivery via Cyrus.
#
#old-cyrus unix  -       n       n       -       -       pipe
#  flags=R user=cyrus argv=/cyrus/bin/deliver -e -m ${extension} ${user}
#
# ====================================================================
#
# See the Postfix UUCP_README file for configuration details.
#
uucp      unix  -       n       n       -       -       pipe
  flags=Fqhu user=uucp argv=uux -r -n -z -a$sender - $nexthop!rmail ($recipient)
#
# Other external delivery methods.
#
ifmail    unix  -       n       n       -       -       pipe
  flags=F user=ftn argv=/usr/lib/ifmail/ifmail -r $nexthop ($recipient)
bsmtp     unix  -       n       n       -       -       pipe
  flags=Fq. user=bsmtp argv=/usr/lib/bsmtp/bsmtp -t$nexthop -f$sender $recipient
scalemail-backend unix  -   n   n   -   2   pipe
  flags=R user=scalemail argv=/usr/lib/scalemail/bin/scalemail-store ${nexthop} ${user} ${extension}
mailman   unix  -       n       n       -       -       pipe
  flags=FR user=list argv=/usr/lib/mailman/bin/postfix-to-mailman.py
  ${nexthop} ${user}

My raw main.cf file:

smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu/GNU)
biff = no

# appending .domain is the MUA's job.
append_dot_mydomain = no

# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h

myhostname = mail.luckypizza.ro
mydomain = luckypizza.ro
myorigin = $mydomain
mydestination = $myhostname localhost.$mydomain localhost $mydomain laiancu.ro

alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mynetworks_style = class

mailbox_size_limit = 0
home_mailbox = Maildir/

virtual_mailbox_domains = /etc/postfix/vhosts
virtual_mailbox_base = /home/vmail
virtual_mailbox_maps = hash:/etc/postfix/vmaps
virtual_minimum_uid = 1000
virtual_uid_maps = static:5000
virtual_gid_maps = static:5000

recipient_delimiter = +

inet_interfaces = all
inet_protocols = ipv4

# TLS parameters
smtpd_use_tls=yes
smtpd_tls_auth_only = yes
smtpd_tls_cert_file = /etc/letsencrypt/live/mail.luckypizza.ro/fullchain.pem
smtpd_tls_key_file = /etc/letsencrypt/live/mail.luckypizza.ro/privkey.pem
smtp_tls_security_level = may
smtpd_tls_mandatory_protocols=!SSLv2,!SSLv3
smtp_tls_mandatory_protocols=!SSLv2,!SSLv3
smtpd_tls_protocols=!SSLv2,!SSLv3
smtp_tls_protocols=!SSLv2,!SSLv3

tls_preempt_cipherlist = yes
smtpd_tls_mandatory_ciphers = high
tls_high_cipherlist = ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:DHE-DSS-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA256:ADH-AES256-GCM-SHA384:ADH-AES256-SHA256:ECDH-RSA-AES256-GCM-SHA384:ECDH-ECDSA-AES256-GCM-SHA384:ECDH-RSA-AES256-SHA384:ECDH-ECDSA-AES256-SHA384:AES256-GCM-SHA384:AES256-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:DHE-DSS-AES128-GCM-SHA256:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES128-SHA256:DHE-DSS-AES128-SHA256:ADH-AES128-GCM-SHA256:ADH-AES128-SHA256:ECDH-RSA-AES128-GCM-SHA256:ECDH-ECDSA-AES128-GCM-SHA256:ECDH-RSA-AES128-SHA256:ECDH-ECDSA-AES128-SHA256:AES128-GCM-SHA256:AES128-SHA256:NULL-SHA256
smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noplaintext,noanonymous

smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth

smtpd_relay_restrictions =
  permit_mynetworks,
  permit_sasl_authenticated,
  reject_unauth_destination

smtpd_recipient_restrictions = permit_sasl_authenticated

What I have tried so far:

Removing the smtpd_recipient_restrictions

Connect from the client both with and without TLS

Changing mydomain and/or myhostname with 'localhost'

I think Roundcube works because of the smtpd_relay_restrictions = permit_mynetworks line, because it's on the same host, so the external clients might fail because they don't meet the permit_sasl_authenticated rule in smtpd_relay_restrictions. However, I don't understand why it does not.


问:
Using copy constructors on iterators
I'm trying to make iterator. As a constructor I have:

```<code>iterator(Node* node)
{
    it = node;
}
</code>```

and copy constructor:

```<code>iterator(const iterator& x)
{
    it = x.it;
}
</code>```

I was told that using first one is not a good idea while having second one(which is better)

I'm not sure how to use second approach in methods like this:

```<code>typedef iterator<Key, Info> ringIterator;

ringIterator begin()
{
    return ringIterator(any);
}
</code>```

答:
A copy constructor is a constructor, that accepts a (usually, but not necessarily, constant) reference to the same type.

Therefore, iterator(Node *) is not a copy constructor. It is a constructor from some internal entity of your collection.

You do need that constructor in the implementation of the begin() (and end() and other methods returning iterators) of the collection. However:

It should be marked explicit so it won't be used for implicit conversion.

It should preferably not be visible outside the two classes. Probably by making it private and using suitable friend declaration. You should probably nest the iterator and the internal Node type in the collection; that way the Node itself can be private (but you don't show the complete structure of the collection you are writing, so I can't say for sure how to put this together).

Title: Using copy constructors on iterators

Body:
I'm trying to make iterator. As a constructor I have:

iterator(Node* node)
{
    it = node;
}

and copy constructor:

iterator(const iterator& x)
{
    it = x.it;
}

I was told that using first one is not a good idea while having second one(which is better)

I'm not sure how to use second approach in methods like this:

typedef iterator<Key, Info> ringIterator;

ringIterator begin()
{
    return ringIterator(any);
}


问:
complex query in mysql?
```<code> -table : events
 [id=>1 , data_id =>1 , events_reference =>5 , g_id=>0
  id=>5  , data_id=>1 , events_reference =>NULL , g_id=>1,
  id=>6 . , data_id=>3, events_reference => 5 ,g_id=>0 ]

 - table : data
 [id=> 0 , name=>test1,
  id=>1 , name=>test2,
  id=>3 , name=>tes3 ]
</code>```

I want to get column name g_id_1 including the data name if g_id_1 equal to data.id in data table(not the data_id column), and also I want to get column name g_id_2 that show the data name based on the events reference

ALSO, I want only bring the data that the data.id = 1 for example so event.id =6 will not appear

expected result: (get all events and + new columns calls "g_id_1" + "g_id_2")

```<code>{
 "id"=>1,
 events_reference => 5,
 "g_id_1" = > "test 1"
 "g_id_2" => "test 2"
},
{
 "id"=>5,
 events_reference => NULL,
 "g_id_1" = > "test 2"
 "g_id_2" => NULL
}
</code>```

How can I do that, I tried with sub select but I manage to get the first level but not the second level because the events_reference is reference to another row in the same table

```<code>select id,events_reference , (SELECT name from data as d where events.events_reference = d.id) as g_id_1,
(SELECT name from data as d,events as e where e.events_reference = d.id) as g_id_1
</code>```

答:
Im not a mySQL wiz but pretty good is MSSQL and it looks like you are wanting to do a LEFT join.
So what that will do is return another table IF the data exists.

```<code>SELECT events.id, events.events_reference, data.g_id_1, data.g_id_2
FROM events
LEFT JOIN data ON events.events_reference = eventtable.events_reference
LEFT JOIN data data2 ON eventtable.g_id_2 = eventtable2.g_id_1;
</code>```

Pretty sure that is what your asking for, let me know if its not and I will have another look.

Caz

Title: complex query in mysql?

Body:
 -table : events
 [id=>1 , data_id =>1 , events_reference =>5 , g_id=>0
  id=>5  , data_id=>1 , events_reference =>NULL , g_id=>1,
  id=>6 . , data_id=>3, events_reference => 5 ,g_id=>0 ]

 - table : data
 [id=> 0 , name=>test1,
  id=>1 , name=>test2,
  id=>3 , name=>tes3 ]

I want to get column name g_id_1 including the data name if g_id_1 equal to data.id in data table(not the data_id column), and also I want to get column name g_id_2 that show the data name based on the events reference

ALSO, I want only bring the data that the data.id = 1 for example so event.id =6 will not appear

expected result: (get all events and + new columns calls "g_id_1" + "g_id_2")

{
 "id"=>1,
 events_reference => 5,
 "g_id_1" = > "test 1"
 "g_id_2" => "test 2"
},
{
 "id"=>5,
 events_reference => NULL,
 "g_id_1" = > "test 2"
 "g_id_2" => NULL
}

How can I do that, I tried with sub select but I manage to get the first level but not the second level because the events_reference is reference to another row in the same table

select id,events_reference , (SELECT name from data as d where events.events_reference = d.id) as g_id_1,
(SELECT name from data as d,events as e where e.events_reference = d.id) as g_id_1

Body:
Im not a mySQL wiz but pretty good is MSSQL and it looks like you are wanting to do a LEFT join.
So what that will do is return another table IF the data exists.

SELECT events.id, events.events_reference, data.g_id_1, data.g_id_2
FROM events
LEFT JOIN data ON events.events_reference = eventtable.events_reference
LEFT JOIN data data2 ON eventtable.g_id_2 = eventtable2.g_id_1;

Pretty sure that is what your asking for, let me know if its not and I will have another look.

Caz


问:
How To Include Text File With Netbeans
I'm very new to Java.  I want to read from a file, but I keep getting my "file not found" exception message.  I learned that my .txt file had to be in the same directory as my Java program.  On netbeans, how do I place my .txt file in the same directory as my Java program.  Sorry this question is so basic, I'm in my first few weeks of java</p>

答:
Create the text file and you have to put the file in the folder of project like in my case:

C:\Users\UsmanYaqoob\Documents\NetBeansProjects\BookQuestions

BookQuestions is my project

Title: How To Include Text File With Netbeans


问:
PHP Cron Manager Script stops page load

I'm trying to make a script that schedules a cron job that sends e-mails on a specific date. I followed this tutorial for making a php cron manager, and it loaded with no problem. But when I tried to make a SSH connection with the script just to see if it would raise any errors, the page stops loading where I place the code, no errors are shown and no error_log file is created anywhere, I really don't understand why the page stops loading.

```<code>$crontab = new Ssh2_crontab_manager('xxxxxxxxxxx.xxx', '22', 'xxxxxxx', 'xxxxxxxxxxx');
</code>```

I only expect it to connect and continue the page or that it at least give me an error that I can search for the solution

Nothing, just a page that's partially loaded and no error, it just stops there.

答:
Your approach above totally over complicates what you are trying to do. You have a php script you want to run at certain intervals throughout the day, sending a few emails each time to people in your database.

Obviously I have no idea what your database looks like, but here's a basic concept.

Add a column to your email addresses database called sent with
default value set to 0

Write your php script and in your database query use LIMIT = 10 or
whatever to only retrieve a few email addresses each time it runs,
use WHERE sent = 0 to only retrieve email addresses you havent sent
to yet

Then UPDATE each row to SET sent = 1 after the script has run to
mark those users as having already been emailed. Include some conditional code so that if there are no more email
addresses for that day WHERE sent = 0 then script just exits.

Create a cron job to run at your chosen interval which runs your php
script and just leave it.

There is no need to delete the cron job, if there are no emails to send it will just run briefly and quit. The whole point of cron jobs is to automate repetitive tasks, you set once and forget. The filters are flexible enough to give you a lot of control over when they run.

For example 0 9-17/2 * * 1-5 php /path/to/script.php would run a script every other hour between 0900 and 1700, Monday to Friday

Title: PHP Cron Manager Script stops page load

Body:
I'm trying to make a script that schedules a cron job that sends e-mails on a specific date. I followed this tutorial for making a php cron manager, and it loaded with no problem. But when I tried to make a SSH connection with the script just to see if it would raise any errors, the page stops loading where I place the code, no errors are shown and no error_log file is created anywhere, I really don't understand why the page stops loading.

$crontab = new Ssh2_crontab_manager('xxxxxxxxxxx.xxx', '22', 'xxxxxxx', 'xxxxxxxxxxx');

I only expect it to connect and continue the page or that it at least give me an error that I can search for the solution

Nothing, just a page that's partially loaded and no error, it just stops there.


问:
Programming style of method declaration of get/set method variables in C++?
Should you declare the getters/setters of the class inside the .h file and then define them in .cpp Or do both in .h file. Which style do you prefer and why? I personally like the latter wherein all of them are in .h and only methods which have logic associated with it other than setters/getters in .cpp. </p>

答: I use next rule: header for declaration, code file for realization. It becomes for actual when your header would be use outside of project - than more lightweight your header is, then it's more comfort in use</p>

LastEditorDisplayName: Eddie Parker

OwnerDisplayName: abatishchev


问:
How to duplicate directory in git, tracking new files?
Is there a simple way to create a copy of a folder in a local repository, keeping track of exactly the same files (do not care about commit history, or untracked files)? </p>

<p>Folder contains a hierarchy of both tracked and untracked (but not ignored) files and directories. I basically want to recursively replicate the tracked structure. Is there a way apart of copying everything, then manually adding only the relevant files (there are a lot of them)? </p>

答:
If you don't care about the history, you could just copy the directory and then git add it:

```<code>$ cp -R old_dir new_dir

$ git add new_dir

$ git commit -m "first revision of new_dir's copied files"
</code>```

Body:
Is there a simple way to create a copy of a folder in a local repository, keeping track of exactly the same files (do not care about commit history, or untracked files)?

Folder contains a hierarchy of both tracked and untracked (but not ignored) files and directories. I basically want to recursively replicate the tracked structure. Is there a way apart of copying everything, then manually adding only the relevant files (there are a lot of them)?

Body:
If you don't care about the history, you could just copy the directory and then git add it:

$ cp -R old_dir new_dir

$ git add new_dir

$ git commit -m "first revision of new_dir's copied files"


问:
Java: trying to convert an int value to a String
In my method format(int n) I am simply trying to return the passed int value as a string. using the toString() method.

```<code>public String format(int n) {

    return n.toString();
}
</code>```

However, I keep getting the error int cannot be dereferenced. From what I understand, this is happening because I am treating a primitive int value as if it were an object, but I do not know how to fix it. I would appreciate any help with this.

答:
You cannot invoke methods on primitives.

You could box int to Integer and invoke toString() on that :

```<code>return ((Integer)n).toString();
</code>```

Thanks to autoboxing you could even directly rewrite your method by replacing int with Integer :

```<code>public String format(Integer n) {
    return n.toString();
}
</code>```

And invoking it in this way (the compiler will box int for you  to Integer as the parameter is passed) :

```<code>int x = ...;
format(x);
</code>```

But a simpler way is using the String.valueOf(int) method :

```<code>public String format(int n) {
    return String.valueOf(n);
}
</code>```

In this case, is it really needed to create a method that just delegates to String.valueOf() ?

Body:
In my method format(int n) I am simply trying to return the passed int value as a string. using the toString() method.

public String format(int n) {

    return n.toString();
}

However, I keep getting the error int cannot be dereferenced. From what I understand, this is happening because I am treating a primitive int value as if it were an object, but I do not know how to fix it. I would appreciate any help with this.

Body:
You cannot invoke methods on primitives.

You could box int to Integer and invoke toString() on that :

return ((Integer)n).toString();

Thanks to autoboxing you could even directly rewrite your method by replacing int with Integer :

public String format(Integer n) {
    return n.toString();
}

And invoking it in this way (the compiler will box int for you  to Integer as the parameter is passed) :

int x = ...;
format(x);

But a simpler way is using the String.valueOf(int) method :

public String format(int n) {
    return String.valueOf(n);
}

In this case, is it really needed to create a method that just delegates to String.valueOf() ?


问:
How to append data to a google spreadsheet?
I have checked various SO questions, and I see that there should be an append method available on service().spreadsheet().values() but that method does not exist on this object for me unlike other SO questions. How do I append data to a google spreadsheet instead of writing over the whole document?

This is the code that I am using which writes over the current document instead of appending to it.

```<code>    public static Sheets getSheetsService() throws IOException {
        Credential credential = authorize();
        return new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME)
                .build();
    }

...

    public static boolean writeToPersistedGoogleDoc(List<FlightBookingRow> rows) throws IOException {

        Sheets service = getSheetsService();

        String valueInputOption = "USER_ENTERED";

        List<List<Object>> values = new ArrayList<>();

        for(FlightBookingRow row: rows){
            List<Object> list = new ArrayList<>();
            list.add(row.getTimeBooked());
            list.add(row.getPaidStatus());
            list.add(row.getCostOfTicket());
            list.add(row.getFlightPlan());
            list.add(row.getNumberOfPeople().toString());
            list.add(row.getDepartureDate().toString());
            list.add(row.getReturnDate().toString());
            list.add(row.getCompanyBookedWith());
            values.add(list);
        }

        ValueRange body = new ValueRange()
                .setValues(values);
        UpdateValuesResponse result =
                service.spreadsheets().values().update(PERSISTED_FLIGHT_SHEET, RANGE, body)
                        .setValueInputOption(valueInputOption)
                        .execute();
        System.out.printf("%d cells updated.", result.getUpdatedCells());

        return true;
    }
</code>```

答:
I had a slightly out dated dependency in my pom file.

I added this, and then I got access to the append method.

```<code><dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-sheets</artifactId>
    <version>v4-rev494-1.23.0</version>
</dependency>
</code>```

Body:
I have checked various SO questions, and I see that there should be an append method available on service().spreadsheet().values() but that method does not exist on this object for me unlike other SO questions. How do I append data to a google spreadsheet instead of writing over the whole document?

This is the code that I am using which writes over the current document instead of appending to it.

    public static Sheets getSheetsService() throws IOException {
        Credential credential = authorize();
        return new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME)
                .build();
    }

...

    public static boolean writeToPersistedGoogleDoc(List<FlightBookingRow> rows) throws IOException {

        Sheets service = getSheetsService();

        String valueInputOption = "USER_ENTERED";

        List<List<Object>> values = new ArrayList<>();

        for(FlightBookingRow row: rows){
            List<Object> list = new ArrayList<>();
            list.add(row.getTimeBooked());
            list.add(row.getPaidStatus());
            list.add(row.getCostOfTicket());
            list.add(row.getFlightPlan());
            list.add(row.getNumberOfPeople().toString());
            list.add(row.getDepartureDate().toString());
            list.add(row.getReturnDate().toString());
            list.add(row.getCompanyBookedWith());
            values.add(list);
        }

        ValueRange body = new ValueRange()
                .setValues(values);
        UpdateValuesResponse result =
                service.spreadsheets().values().update(PERSISTED_FLIGHT_SHEET, RANGE, body)
                        .setValueInputOption(valueInputOption)
                        .execute();
        System.out.printf("%d cells updated.", result.getUpdatedCells());

        return true;
    }

Body:
I had a slightly out dated dependency in my pom file.

I added this, and then I got access to the append method.

<dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-sheets</artifactId>
    <version>v4-rev494-1.23.0</version>
</dependency>


问:
Don't know where to start with selecting a row in php
Ok guys I know this might not be the correct way to ask a question but I have looked as far as I could go. I am a bit stuck on how to go about this problem, probably why I can't find a solution to it. I have a form that the info gets inserted to a db, then you are able to view the info from the database on another page that list everything inserted. My question is how would I go about selecting a row from the table that displays all the info from a row on the db and redirect to another page to edit it? I want to redirect to another page to view/edit all the info.

What I think would work is in the table that shows the info I could put a radio box and have a button at the top to click to edit that row. I don't really know how to assign that radio button to the actual row however.

Here is my table:

```<code><?php
                $sql = "SELECT * FROM employees ORDER BY LastName";
                $result = $mysqli -> query($sql);

                if ($result->num_rows > 0) {
                    echo "
                    <table class='table table-hover table-responsive'>
                        <thead class='thead-dark'>
                            <tr>
                                <th class='table-primary' scope='col'>#</th>
                                <th class='table-primary' scope='col'>First Name</th>
                                <th class='table-primary' scope='col-1'>M.I.</th>
                                <th class='table-primary' scope='col'>Last Name</th>
                                <th class='table-primary' scope='col'>Phone</th>
                                <th class='table-primary' scope='col'>Address</th>
                                <th class='table-primary' scope='col'>Email</th>
                                <th class='table-primary' scope='col'>Birth Date</th>
                                <th class='table-primary' scope='col'>EID</th>
                                <th class='table-primary' scope='col'>Gender</th>
                                <th class='table-primary' scope='col'>Ethnicity</th>
                                <th class='table-primary' scope='col'>Status</th>
                                <th class='table-primary' scope='col'>Hours</th>
                                <th class='table-primary' scope='col'>EAP Access</th>
                            </tr>
                          </thead>";
                    // output data of each row
                    while ($row = $result->fetch_assoc()) {
                        echo "
                        <tbody>
                            <tr class='table-dark'>
                                <td>" . $row['UserID']. "</td>
                              <td>" . $row['FirstName']. "</td>
                              <td>" . $row['Middle']. "</td>
                              <td>" . $row['LastName']. "</td>
                                <td>" . $row['PrimaryPhone']. "</td>
                                <td>" . $row['Address'] . $row['City'] . $row['State'] . $row['Zipcode']. "</td>
                                <td>" . $row['Email']. "</td>
                                <td>" . $row['DateOfBirth']. "</td>
                                <td>" . $row['EID']. "</td>
                                <td>" . $row['Gender']. "</td>
                                <td>" . $row['Ethnicity']." </td>
                                <td>" . $row['Status']. "</td>
                                <td>" . $row['Hours']. "</td>
                                <td>" . $row['eapAccess']. "</td>
                            </tr>
                        </tbody>";
                    }
                    echo "</table>";
                } else {
                    echo "0 results";
                }
            ?>
</code>```

If I added a <input type="radio" name="selected"> before the userID column like and had a button to select that row, how would I be able to have that row display on a seperate page?

I am still new to php, but this is beyond me and can't find anything remotely close to an answer.

答:
Few steps to be done:

add the input radio before before the user ID

wrap whole table with the <form> elements with defined method and action attributes

add the submit button inside the form to send the values

on next script you will receive the value within $_GET or $_POST

process all what you need with received user ID

Study more about (search internet for more info):

HTML forms

PHP Form Handling

PHP GET and POST Method Tutorials

Body:
Ok guys I know this might not be the correct way to ask a question but I have looked as far as I could go. I am a bit stuck on how to go about this problem, probably why I can't find a solution to it. I have a form that the info gets inserted to a db, then you are able to view the info from the database on another page that list everything inserted. My question is how would I go about selecting a row from the table that displays all the info from a row on the db and redirect to another page to edit it? I want to redirect to another page to view/edit all the info.

What I think would work is in the table that shows the info I could put a radio box and have a button at the top to click to edit that row. I don't really know how to assign that radio button to the actual row however.

Here is my table:

<?php
                $sql = "SELECT * FROM employees ORDER BY LastName";
                $result = $mysqli -> query($sql);

                if ($result->num_rows > 0) {
                    echo "

                                #
                                First Name
                                M.I.
                                Last Name
                                Phone
                                Address
                                Email
                                Birth Date
                                EID
                                Gender
                                Ethnicity
                                Status
                                Hours
                                EAP Access

";
                    // output data of each row
                    while ($row = $result->fetch_assoc()) {
                        echo "

                                " . $row['UserID']. "
                              " . $row['FirstName']. "
                              " . $row['Middle']. "
                              " . $row['LastName']. "
                                " . $row['PrimaryPhone']. "
                                " . $row['Address'] . $row['City'] . $row['State'] . $row['Zipcode']. "
                                " . $row['Email']. "
                                " . $row['DateOfBirth']. "
                                " . $row['EID']. "
                                " . $row['Gender']. "
                                " . $row['Ethnicity']."
                                " . $row['Status']. "
                                " . $row['Hours']. "
                                " . $row['eapAccess']. "

";
                    }
                    echo "
";
                } else {
                    echo "0 results";
                }
            ?>

If I added a <input type="radio" name="selected"> before the userID column like and had a button to select that row, how would I be able to have that row display on a seperate page?

I am still new to php, but this is beyond me and can't find anything remotely close to an answer.


问:
Log4Net SmtpAppender not working in .netCore
I'm trying to send log messages to my gmail account but it keeps not working. I've tried changing ports and changing threshold value but it's not working. When I try writing logs in file everything is ok, so I think the problem is in log4net.config file.

My log4net configuration file contains:

```<code>    <log4net>
     <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
      <to value="mymail@gmail.com" />
      <from value="mysendermail@gmail.com" />
      <subject value="Crash log" />
      <smtpHost value="smtp.gmail.com" />
      <authentication value="Basic" />
      <port value="465" />
      <username value="myusername" />
      <password value="mypass" />
      <bufferSize value="1" />
      <EnableSsl value="true"/>
      <lossy value="true" />
     <evaluator type="log4net.Core.LevelEvaluator">
       <threshold value="DEBUG"/>
     </evaluator>
     <layout type="log4net.Layout.PatternLayout">
       <conversionPattern value="%-5p %d{hh:mm:ss} %message%newline" />
     </layout>
   </appender>
   <root>
     <level value="DEBUG"/>
     <appender-ref ref="SmtpAppender"/>
   </root>
   </log4net>
</code>```

In my Startup.cs file I have:

```<code>var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
            XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));
</code>```

And my example code is:

```<code>public class HomeController : Controller
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(HomeController));

        public HomeController()
        {

        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult About()
        {

            ViewData["Message"] = "Your application description page.";
            ViewData["Title"] = "title";
            log.Warn("test test", new NullReferenceException("missing"));
            log.Debug("test test", new NullReferenceException("missing"));
            log.Error("test test", new NullReferenceException("missing"));
            log.Fatal("test test", new NullReferenceException("missing"));
            return View();
        }
    }
</code>```

Am I making something wrong. I tried everything

答:
log4net's SmtpAppender is not supported in .net core yet.

Supported frameworks: https://logging.apache.org/log4net/release/framework-support.html

Body:
I'm trying to send log messages to my gmail account but it keeps not working. I've tried changing ports and changing threshold value but it's not working. When I try writing logs in file everything is ok, so I think the problem is in log4net.config file.

My log4net configuration file contains:

    <log4net>
     <appender name="SmtpAppender" type="log4net.Appender.SmtpAppender">
      <to value="mymail@gmail.com" />
      <from value="mysendermail@gmail.com" />
      <subject value="Crash log" />
      <smtpHost value="smtp.gmail.com" />
      <authentication value="Basic" />
      <port value="465" />
      <username value="myusername" />
      <password value="mypass" />
      <bufferSize value="1" />
      <EnableSsl value="true"/>
      <lossy value="true" />
     <evaluator type="log4net.Core.LevelEvaluator">
       <threshold value="DEBUG"/>
     </evaluator>
     <layout type="log4net.Layout.PatternLayout">
       <conversionPattern value="%-5p %d{hh:mm:ss} %message%newline" />
     </layout>
   </appender>
   <root>
     <level value="DEBUG"/>
     <appender-ref ref="SmtpAppender"/>
   </root>
   </log4net>

In my Startup.cs file I have:

var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
            XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));

And my example code is:

public class HomeController : Controller
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(HomeController));

        public HomeController()
        {

        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult About()
        {

            ViewData["Message"] = "Your application description page.";
            ViewData["Title"] = "title";
            log.Warn("test test", new NullReferenceException("missing"));
            log.Debug("test test", new NullReferenceException("missing"));
            log.Error("test test", new NullReferenceException("missing"));
            log.Fatal("test test", new NullReferenceException("missing"));
            return View();
        }
    }

Am I making something wrong. I tried everything


问:
Cross platform 2D graphics/game library
I'm looking for suggestions for a 2d game engine or library. I'm not picky about the language used but more about the capabilities of the library and the platforms it works on.

I would like to write one code base that would work on iOS, OSX, Android, Win and *nix. I understand there would be some platform specific code but I would like the bulk to be useable on all platforms.

I have looked around and I have some ideas but I'm looking for other opinions. Anyone have any ideas?

答: SDL(Simple DirectMedia Layer) http://www.libsdl.org/</p>

Title: Cross platform 2D graphics/game library


问:
Difference between HFP 1.7 and HFP 1.6?
Can someone please tell me the difference between HFP 1.7 and HFP 1.6 ? I am looking for differences in addition to what already mentioned in Wikipedia. Any link or document would be highly appreciated.</p>

答:
Refer to the official specification overview page.

HFP 1.5 Specification

HFP 1.6 Specification

HFP 1.7 Specification

Title: Difference between HFP 1.7 and HFP 1.6?