问:
HTML form data not being sent in Heroku. ENV variable issue
so at the risk of getting more down votes, here goes my question (be nice!): Ive spent hours trying to figure out how to get Heroku to accept the ENV Variables I have just added through (heroku config:set PASS_CODE='password').

I have a simple HTML contact form within an Express app, I am using the npm package nodemailer, added ENV variables in an .env file for use with detenv, and calling them using the code below. Heroku does state to call their ENV variables in the same way, however the form data is not sending, and I am still getting the following error in the Heroku logs: { Error: Invalid login: 535 5.0.0 Authentication Failed. Both dotenv and heroku say to call the ENV variable using .process.env. It works perfectly in my local node.js server, but not when I push to heroku.

Here are my code snippets:

require('dotenv').config();

var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');

router.get('/', function(req, res, next) {
 res.render('contact');
});

router.post('/send', function(req, res, next){

 // create reusable transporter object using the default SMTP transport
 var transporter = nodemailer.createTransport({
     host: 'smtp-mail.outlook.com',
     port: 587,
     secure: false, // secure:true for port 465, secure:false for port 587
     tls: {
      ciphers: 'SSLv3'
     },
     auth: {
         user: 'example.outlook.com',
         pass: process.env.PASS_CODE
     }
 });

 // setup email data with unicode symbols
 var mailOptions = {
     from: '"Fred Foo " <example@outlook.com>', // sender address
     to: 'example.outlook.com', // list of receivers
     subject: ' New message from your website!', // Subject line
     text: ' You have a new message from your website with the following details: Name: ' +req.body.first_name + 'Surname: ' + req.body.last_name + 'Email: ' + req.body.email + 'Phone Number: ' + req.body.number + 'Message: ' + req.body.message, // plain text body
     html: ' You have a new message from your website with the following details:

First Name: ' + req.body.first_name + '

Surname: ' + req.body.last_name + '

Email: ' + req.body.email + '

Phone Number: ' + req.body.number + '

Message: ' + req.body.message + '

' // html body
 };

 // send mail with defined transport object
 transporter.sendMail(mailOptions, function(error, info) {
     if (error) {
         console.log(error);
         res.redirect('/');
     } else {
      console.log('Message sent: ' + info.response);
      res.redirect('/');

     }

 });
});```
</div>
</div>
</p>

<p>I have also declared the ENV variable in a .env file like so: <code>PASS_CODE=password</code>, and you can see I am requiring dotenv. </p>

<p>It works fine when I run locally through the node.js server, but not when I push through to Heroku. I have set the ENV variables in Heroku and checked by typing <code>heroku config</code>. </p>

<p>For completeness, here is a copy of my package.json file:</p>

```{
  "name": "podeg",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www",
    "debug": "node --debug ./bin/www"
  },
  "dependencies": {
    "body-parser": "~1.17.1",
    "cookie-parser": "~1.4.3",
    "debug": "~2.6.3",
    "express": "~4.15.2",
    "jade": "~1.11.0",
    "morgan": "~1.8.1",
    "multer": "^1.3.0",
    "nodemailer": "^4.0.1",
    "serve-favicon": "~2.4.2",
    "dotenv": "^4.0.0"
  },
  "engines": {
    "node": "7.10.0"
  }
}
```

Many thanks indeed!

答:
Im not sure why I got a down arrow, as I think other people in my situation (beginners) will find this an issue too and need help. SO thanks for the help. ANyway, ive managed to find the answer out and it was to do with using outlook.com as my transactional email client. I changed over to sendinblue (this was a completely free service, as opposed to sendgrid etc who only offer a free trial and then charge). I changed the API details in according to my account, and also used a package from npm - heroku-dotenv, which works in conjunction with dotenv to send environmental variables over to heroku for you. </p>

<p>The combination of the two works and I can now receive emails from my contact form via heroku and in development, without changing any of the env coding.  </p>

Body:
so at the risk of getting more down votes, here goes my question (be nice!): Ive spent hours trying to figure out how to get Heroku to accept the ENV Variables I have just added through (heroku config:set PASS_CODE='password').

I have a simple HTML contact form within an Express app, I am using the npm package nodemailer, added ENV variables in an .env file for use with detenv, and calling them using the code below. Heroku does state to call their ENV variables in the same way, however the form data is not sending, and I am still getting the following error in the Heroku logs: { Error: Invalid login: 535 5.0.0 Authentication Failed. Both dotenv and heroku say to call the ENV variable using .process.env. It works perfectly in my local node.js server, but not when I push to heroku.

Here are my code snippets:

require('dotenv').config();

var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');

router.get('/', function(req, res, next) {
 res.render('contact');
});

router.post('/send', function(req, res, next){

 // create reusable transporter object using the default SMTP transport
 var transporter = nodemailer.createTransport({
     host: 'smtp-mail.outlook.com',
     port: 587,
     secure: false, // secure:true for port 465, secure:false for port 587
     tls: {
      ciphers: 'SSLv3'
     },
     auth: {
         user: 'example.outlook.com',
         pass: process.env.PASS_CODE
     }
 });

 // setup email data with unicode symbols
 var mailOptions = {
     from: '"Fred Foo " <example@outlook.com>', // sender address
     to: 'example.outlook.com', // list of receivers
     subject: ' New message from your website!', // Subject line
     text: ' You have a new message from your website with the following details: Name: ' +req.body.first_name + 'Surname: ' + req.body.last_name + 'Email: ' + req.body.email + 'Phone Number: ' + req.body.number + 'Message: ' + req.body.message, // plain text body
     html: ' You have a new message from your website with the following details:

First Name: ' + req.body.first_name + '

Surname: ' + req.body.last_name + '

Email: ' + req.body.email + '

Phone Number: ' + req.body.number + '

Message: ' + req.body.message + '

' // html body
 };

 // send mail with defined transport object
 transporter.sendMail(mailOptions, function(error, info) {
     if (error) {
         console.log(error);
         res.redirect('/');
     } else {
      console.log('Message sent: ' + info.response);
      res.redirect('/');

     }

 });
});

I have also declared the ENV variable in a .env file like so: PASS_CODE=password, and you can see I am requiring dotenv.

It works fine when I run locally through the node.js server, but not when I push through to Heroku. I have set the ENV variables in Heroku and checked by typing heroku config.

For completeness, here is a copy of my package.json file:

{
  "name": "podeg",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www",
    "debug": "node --debug ./bin/www"
  },
  "dependencies": {
    "body-parser": "~1.17.1",
    "cookie-parser": "~1.4.3",
    "debug": "~2.6.3",
    "express": "~4.15.2",
    "jade": "~1.11.0",
    "morgan": "~1.8.1",
    "multer": "^1.3.0",
    "nodemailer": "^4.0.1",
    "serve-favicon": "~2.4.2",
    "dotenv": "^4.0.0"
  },
  "engines": {
    "node": "7.10.0"
  }
}

Many thanks indeed!

Body:
Im not sure why I got a down arrow, as I think other people in my situation (beginners) will find this an issue too and need help. SO thanks for the help. ANyway, ive managed to find the answer out and it was to do with using outlook.com as my transactional email client. I changed over to sendinblue (this was a completely free service, as opposed to sendgrid etc who only offer a free trial and then charge). I changed the API details in according to my account, and also used a package from npm - heroku-dotenv, which works in conjunction with dotenv to send environmental variables over to heroku for you.

The combination of the two works and I can now receive emails from my contact form via heroku and in development, without changing any of the env coding.


来源: stackexchange

问:
How do I optimize parallel calls to a service?

I have a challenge that I am encountering when needing to pull down data from a service.  I'm using the following call to Parallel.ForEach:

Parallel.ForEach(idList, id => GetDetails(id));
```

<p><code>GetDetails(id)</code> calls a web service that takes roughly half a second and adds the resulting details to a list.</p>

<pre class="lang-cs prettyprint-override"><code>static void GetDetails(string id)
{
    var details = WebService.GetDetails(Key, Secret, id);
    AllDetails.Add(id, details);
}
</code>```

The problem is, I know the service can handle more calls, but I can't seem to figure out how to get my process to ramp up more calls, UNLESS I split my list and open the process multiple times.  In other words, if I open this app GetDetails.exe 4 times and split the number of IDs into each, I cut the run time down to 25% of the original.  This tells me that the possibility is there but I am unsure how to achieve it without ramping up the console app multiple times.

Hopefully this is a pretty simple issue for folks that are more familiar with parallelism, but in my research I've yet to solve it without running multiple instances.

答:
A few possibilities:

There's a chance that WebService.GetDetails(...) is using some kind of mechanism to ensure that only one web request actually happens at a time.

.NET itself may be limiting the number of connections, either to a given host or in general see this question's answers for details about these kinds of problems

If WebService.GetDetails(...) reuses some kind of identifier like a session key, the server may be limiting the number of concurrent requests that it accepts for that one session.

It's generally a bad idea to try to solve performance issues by hammering the server with more concurrent requests. If you control the server, then you're causing your own server to do way more work than it needs to. If not, you run the risk of getting IP-banned or something for abusing their service. It's worth checking to see if the service you're accessing has some options to batch your requests or something.

As Scott Chamberlain mentioned in comments, you need to be careful with parallel processes because accessing structures like Dictionary<> from multiple threads concurrently can cause sporadic, hard-to-track-down bugs. You'd probably be better off using async requests rather than parallel threads. If you're careful about your awaits, you can have multiple requests be active concurrently while still using just a single thread at a time.

ContentLicense: CC BY-SA 3.0

Body:
I have a challenge that I am encountering when needing to pull down data from a service.  I'm using the following call to Parallel.ForEach:

Parallel.ForEach(idList, id => GetDetails(id));

GetDetails(id) calls a web service that takes roughly half a second and adds the resulting details to a list.

static void GetDetails(string id)
{
    var details = WebService.GetDetails(Key, Secret, id);
    AllDetails.Add(id, details);
}

The problem is, I know the service can handle more calls, but I can't seem to figure out how to get my process to ramp up more calls, UNLESS I split my list and open the process multiple times.  In other words, if I open this app GetDetails.exe 4 times and split the number of IDs into each, I cut the run time down to 25% of the original.  This tells me that the possibility is there but I am unsure how to achieve it without ramping up the console app multiple times.

Hopefully this is a pretty simple issue for folks that are more familiar with parallelism, but in my research I've yet to solve it without running multiple instances.


问:
function that removes spaces and tabs
im trying to make a function that removes spaces and tabs from a given string except for the first tab or space in the string. when im using my function it removes the spaces and tabs except for the first one but it also removes the first letter after the first space or tab.
for example > "ad ad  ad"> "ad dad" instead of "ad adad"
why is that?</p>

```<code>void RemoveSpacetab(char* source) {
    char* i = source;
    char* j = source;
    int spcflg = 0;

    while(*j != 0) {
        *i = *j++;

        if((*i != ' ') && (*i != '\t'))
            i++;
        if(((*i == ' ') || (*i == '\t')) && (spcflg == 0)) {
            i++;
            spcflg = 1;
        }
    }
    *i = 0;
}
</code>```

答:
The problem caused by two if statements one after the other. Your i precedes j when you detect a space for first time.

Explanation:

In first cycle the i points to position 0 and j too. The 'a' at position 0 will be overwritten with itself then j moves onwards to position 1. Your first if block finds out that the character at position 0 is not a space and not a tab, so moves the i to position 1.

In second cycle the 'b' will be overwritten with itself then j moves to position 2 which is a space. The first if finds out that 'b' at position 1 is not a space and not a tab so moves the i to position 2. Now the second if finds out that the i points to a space for first time and moves it to the position 3 while j is still points to the position 2.

In third cycle the 'a' at position 3 will be overwritten with the space at position 2 and j catches up with i.

A possible fix to your code:

```<code>#include <stdio.h>

void RemoveSpacetab(char* source) {
    char* i = source;
    char* j = source;
    char spcflg = 0;

    while(*j != 0) {
        *i = *j++;
        if(*i == ' ' || *i == '\t') {
            if(!spcflg) {
                i++;
                spcflg = 1;
            }
        }
        else {
            i++;
        }
    }
    *i = 0;
}

int main() {
    char my_string[] = "ad ad ad";
    RemoveSpacetab(my_string);

    printf("%s\n", my_string);
    return 0;
}
</code>```

Title: function that removes spaces and tabs

Body:
im trying to make a function that removes spaces and tabs from a given string except for the first tab or space in the string. when im using my function it removes the spaces and tabs except for the first one but it also removes the first letter after the first space or tab.
for example > "ad ad  ad"> "ad dad" instead of "ad adad"
why is that?

void RemoveSpacetab(char* source) {
    char* i = source;
    char* j = source;
    int spcflg = 0;

    while(*j != 0) {
        *i = *j++;

        if((*i != ' ') && (*i != '\t'))
            i++;
        if(((*i == ' ') || (*i == '\t')) && (spcflg == 0)) {
            i++;
            spcflg = 1;
        }
    }
    *i = 0;
}

Body:
The problem caused by two if statements one after the other. Your i precedes j when you detect a space for first time.

Explanation:

In first cycle the i points to position 0 and j too. The 'a' at position 0 will be overwritten with itself then j moves onwards to position 1. Your first if block finds out that the character at position 0 is not a space and not a tab, so moves the i to position 1.

In second cycle the 'b' will be overwritten with itself then j moves to position 2 which is a space. The first if finds out that 'b' at position 1 is not a space and not a tab so moves the i to position 2. Now the second if finds out that the i points to a space for first time and moves it to the position 3 while j is still points to the position 2.

In third cycle the 'a' at position 3 will be overwritten with the space at position 2 and j catches up with i.

A possible fix to your code:

#include <stdio.h>

void RemoveSpacetab(char* source) {
    char* i = source;
    char* j = source;
    char spcflg = 0;

    while(*j != 0) {
        *i = *j++;
        if(*i == ' ' || *i == '\t') {
            if(!spcflg) {
                i++;
                spcflg = 1;
            }
        }
        else {
            i++;
        }
    }
    *i = 0;
}

int main() {
    char my_string[] = "ad ad ad";
    RemoveSpacetab(my_string);

    printf("%s\n", my_string);
    return 0;
}


问:
How can i pass list to template at Golang
I want to use a query which looks like

```<code>rows:= db.Query("SELECT * FROM names")

var name string

for rows.Next() {
    rows.Scan(&name)
}

//There should be a map

t.Execute(w,p)
</code>```

I want to shape up this to list all names in template like

```<code>{{range .name}}
{{.}}
{{end}}
</code>```

How can i exactly do that?

答:
Something Like This?

```<code>rows, err := db.Query("SELECT name FROM names")
if err != nil {
    // Handle error
}

names := make([]string, 0)

for rows.Next() {
    var name string

    err := rows.Scan(&name)
    if err != nil {
        // Handle error
        continue
    }

    names = append(names, name)
}

t := template.New("index")
t, _ = t.Parse(`{{range .}}{{.}} {{end}}`)
t.Execute(w, names)
</code>```

Things to Note

You should generally avoid using * in your sql queries to make it clear what fields are being selected

If any fields in your database table can be NULL, then use sql.NullBool, sql.NullFloat64, sql.NullInt64 or sql.NullString to avoid possible errors

Possible Output

```<code>Bob Jim David Henry Jerry
</code>```

Body:
I want to use a query which looks like

rows:= db.Query("SELECT * FROM names")

var name string

for rows.Next() {
    rows.Scan(&name)
}

//There should be a map

t.Execute(w,p)

I want to shape up this to list all names in template like

{{range .name}}
{{.}}
{{end}}

How can i exactly do that?

Body:
Something Like This?

rows, err := db.Query("SELECT name FROM names")
if err != nil {
    // Handle error
}

names := make([]string, 0)

for rows.Next() {
    var name string

    err := rows.Scan(&name)
    if err != nil {
        // Handle error
        continue
    }

    names = append(names, name)
}

t := template.New("index")
t, _ = t.Parse(`{{range .}}{{.}} {{end}}`)
t.Execute(w, names)

Things to Note

You should generally avoid using * in your sql queries to make it clear what fields are being selected

If any fields in your database table can be NULL, then use sql.NullBool, sql.NullFloat64, sql.NullInt64 or sql.NullString to avoid possible errors

Possible Output

Bob Jim David Henry Jerry


问:
How to make text in  tag wordwrap
I want to make text in  tag fit in a fixed div, but it breaks the div and displays ugly.

答:
You can wrap text in a tag through the below css.

```<code>a {

  /* These are technically the same, but use both */
  overflow-wrap: break-word;
  word-wrap: break-word;

  -ms-word-break: break-all;
  /* This is the dangerous one in WebKit, as it breaks things wherever */
  word-break: break-all;
  /* Instead use this non-standard one: */
  word-break: break-word;

  /* Adds a hyphen where the word breaks, if supported (No Blink) */
  -ms-hyphens: auto;
  -moz-hyphens: auto;
  -webkit-hyphens: auto;
  hyphens: auto;

}
</code>```

Title: How to make text in <a> tag wordwrap

Body:
You can wrap text in a tag through the below css.

a {

  /* These are technically the same, but use both */
  overflow-wrap: break-word;
  word-wrap: break-word;

  -ms-word-break: break-all;
  /* This is the dangerous one in WebKit, as it breaks things wherever */
  word-break: break-all;
  /* Instead use this non-standard one: */
  word-break: break-word;

  /* Adds a hyphen where the word breaks, if supported (No Blink) */
  -ms-hyphens: auto;
  -moz-hyphens: auto;
  -webkit-hyphens: auto;
  hyphens: auto;

}


问:
Unable to Install phppgadmin on ubuntu 16.04 server
I am trying to install phppgadmin on my ec2 instance which have ubuntu 16.04 and apache. The steps which I followed are :

sudo apt-get -y install postgresql-contrib phppgadmin

Edit /etc/apache2/conf-available/phppgadmin.conf and replace the line "Require local" with "allow from all".

sudo ln -s /etc/apache2/conf-available/phppgadmin.conf /etc/apache2/sites-enabled/phppgadmin.conf

I have created vhost in my 000-default.conf

```<code><VirtualHost *:80>
        ServerName abc.domain.com
        ServerAlias www.abc.domain.com

        ServerAdmin webmaster@localhost

        ProxyPreserveHost On

        # setup the proxy
        <Proxy *>
                Order allow,deny
                Allow from all
        </Proxy>
        ProxyPass / http://localhost:3000/
        ProxyPassReverse / http://localhost:3000/
</VirtualHost>
</code>```

As another application is running on my server so I have created vhost for that application. But Whenever I go to http://myserverip/phppgadmin it goes to my application running on port 3000. How to solve this issue, I don't know where I am doing wrong?

答:
apache will only react to the ServerName and ServerAliases in the HTTP header therefor entering http://myserverip/phppgadmin will return the default Vhost.

If you enter http://abc.domain.com/phppgadmin should lead to your application at http://localhost:3000

EDIT:
The reason why apache proxies your other requests is the vhost finding process.
Apache will go through all of Vhosts to find a fitting one, if this fails, it will choose the first one in an alphanumeric order, which is in this case 000-default.conf. Therefore every request not fitting to phppgadmin is proxied to localhost:3000.

See https://httpd.apache.org/docs/2.4/vhosts/details.html   for more informations.

Body:
I am trying to install phppgadmin on my ec2 instance which have ubuntu 16.04 and apache. The steps which I followed are :

sudo apt-get -y install postgresql-contrib phppgadmin

Edit /etc/apache2/conf-available/phppgadmin.conf and replace the line "Require local" with "allow from all".

sudo ln -s /etc/apache2/conf-available/phppgadmin.conf /etc/apache2/sites-enabled/phppgadmin.conf

I have created vhost in my 000-default.conf

<VirtualHost *:80>
        ServerName abc.domain.com
        ServerAlias www.abc.domain.com

        ServerAdmin webmaster@localhost

        ProxyPreserveHost On

        # setup the proxy
        <Proxy *>
                Order allow,deny
                Allow from all
        </Proxy>
        ProxyPass / http://localhost:3000/
        ProxyPassReverse / http://localhost:3000/
</VirtualHost>

As another application is running on my server so I have created vhost for that application. But Whenever I go to http://myserverip/phppgadmin it goes to my application running on port 3000. How to solve this issue, I don't know where I am doing wrong?


问:
How do I set Min Date in Datepicker from another Datepicker?
I am currently adding validation to my date pickers and am having trouble setting the min date in the to date picker to be whatever was chosen in the from date picker. I.e if 12-3-15 is selected then the minimum date in the to date picker is 12-3-15. Here is the code I am using:

```<code>$("#from").datepicker({
            defaultDate: new Date(),
            minDate: new Date(),
            onSelect: function(dateStr)
            {
            fromDate = new Date(dateStr);
            }
        });

$('#to').datepicker({
            defaultDate: new Date(),
            minDate: ("#from" + "1D"), (<- HERE)
            onSelect: function(dateStr) {
            toDate = new Date(dateStr);

                // Converts date objects to appropriate strings
                fromDate = ConvertDateToShortDateString(fromDate);
                toDate = ConvertDateToShortDateString(toDate);
        });
</code>```

Does anybody know how I could achieve this?

答:
The answer is good but you need to destroy the datepicker of the $to because if not the $to datepicker have still the first date what you select, and remove the option in $to datepicker, this work for me, you not need to make other function for $to.</p>

```<code>$("#from").datepicker({
    defaultDate: new Date(),
    minDate: new Date(),
    onSelect: function(dateStr)
    {
        $("#to").datepicker("destroy");
        $("#to").val(dateStr);
        $("#to").datepicker({ minDate: new Date(dateStr)})
    }
});
</code>```

Body:
I am currently adding validation to my date pickers and am having trouble setting the min date in the to date picker to be whatever was chosen in the from date picker. I.e if 12-3-15 is selected then the minimum date in the to date picker is 12-3-15. Here is the code I am using:

$("#from").datepicker({
            defaultDate: new Date(),
            minDate: new Date(),
            onSelect: function(dateStr)
            {
            fromDate = new Date(dateStr);
            }
        });

$('#to').datepicker({
            defaultDate: new Date(),
            minDate: ("#from" + "1D"), (<- HERE)
            onSelect: function(dateStr) {
            toDate = new Date(dateStr);

                // Converts date objects to appropriate strings
                fromDate = ConvertDateToShortDateString(fromDate);
                toDate = ConvertDateToShortDateString(toDate);
        });

Does anybody know how I could achieve this?

Body:
The answer is good but you need to destroy the datepicker of the $to because if not the $to datepicker have still the first date what you select, and remove the option in $to datepicker, this work for me, you not need to make other function for $to.

$("#from").datepicker({
    defaultDate: new Date(),
    minDate: new Date(),
    onSelect: function(dateStr)
    {
        $("#to").datepicker("destroy");
        $("#to").val(dateStr);
        $("#to").datepicker({ minDate: new Date(dateStr)})
    }
});


问:
Java: Parsed XML but some things are missing
Somehow the parsed XML file seems to be wrong or am I doing something wrong?

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<root>
    <quests>
       <quest id="test">
           <question>Just a little sentence.</question>
        </quest>
    </quests>
</root>
</code>```

I parse it like that:

```<code>File file = new File("file.xml");

DocumentBuilderFactory dF = DocumentBuilderFactory.newInstance();
dF.setNamespaceAware(true);
DocumentBuilder dB = dF.newDocumentBuilder();

Document XML = dB.parse(file);

// ------------------------------------------
Element doc = XML.getDocumentElement();
System.out.println(doc.getChildNodes());

Element dx = (Element) doc.getElementsByTagName("quest").item(0);
System.out.println(dx.getAttribute("id"));
System.out.println(dx.getAttribute("id").length());
System.out.println(dx.getAttributes().getLength());
</code>```

And this is what I get:

```<code>[root: null]

0
0
</code>```

How could that be? How could I parse attributes of elements/tags/nodes?

答:
Weird I just copy-pasted your code and this is what I got for output

```<code>[root: null]
test
4
1
</code>```

All that I can see wrong is that you should be doing doc.getTagName() but that is just minor...

java version "1.6.0_21"

ContentLicense: CC BY-SA 2.5

Body:
Somehow the parsed XML file seems to be wrong or am I doing something wrong?

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<root>
    <quests>
       <quest id="test">
           <question>Just a little sentence.</question>
        </quest>
    </quests>
</root>

I parse it like that:

File file = new File("file.xml");

DocumentBuilderFactory dF = DocumentBuilderFactory.newInstance();
dF.setNamespaceAware(true);
DocumentBuilder dB = dF.newDocumentBuilder();

Document XML = dB.parse(file);

// ------------------------------------------
Element doc = XML.getDocumentElement();
System.out.println(doc.getChildNodes());

Element dx = (Element) doc.getElementsByTagName("quest").item(0);
System.out.println(dx.getAttribute("id"));
System.out.println(dx.getAttribute("id").length());
System.out.println(dx.getAttributes().getLength());

And this is what I get:

[root: null]

0
0

How could that be? How could I parse attributes of elements/tags/nodes?

Body:
Weird I just copy-pasted your code and this is what I got for output

[root: null]
test
4
1

All that I can see wrong is that you should be doing doc.getTagName() but that is just minor...

java version "1.6.0_21"


问:
How to merge two rows from a table into one in Oracle?
I have a table with the following columns and values.

```<code>Name Rate Kind NoOfItems TotalAmount
---- ---- ---- --------- -----------
ABC     1 O           50          50
ABC     2 A           10          20
</code>```

(*) Table will have N names and the kind will be either O or A

I have to output the above table data as follows into a single row for each and every name.

```<code>Name O_Rate A_Rate O_Items A_Items O_Amount A_Amount TotalItems TotalAmount
---- ------ ------ ------- ------- -------- -------- ---------- -----------
ABC       1      2      50      10       50       20         60          70
</code>```

How to convert the above mentioned table data as per the expected output using a single query. I have tried with Case and Decode but in both cases I am getting two rows only.

Thanks in advance.

答:
I like to do this with conditional aggregation, but you can also use join:

```<code>select o.name, o.Rate as o_Rate, a.Rate as a_Rate,
       o.Kind as o_Kind, a.Kind as a_Kind,
       o.NoOfItems as o_NoOfItems, a.NoOfItems as a_NoOfItems,
       o.TotalAmount as o_TotalAmount, a.TotalAmount as a_TotalAmount,
      (o.NoOfItems + a.NoOfItems) as TotalItems,
      (o.TotalAmount + a.TotalAmount) as TotalAmount
from t o join
     t a
     on o.name = a.name and o.rate = 'O' and a.rate = 'A';
</code>```

Body:
I have a table with the following columns and values.

Name Rate Kind NoOfItems TotalAmount
---- ---- ---- --------- -----------
ABC     1 O           50          50
ABC     2 A           10          20

(*) Table will have N names and the kind will be either O or A

I have to output the above table data as follows into a single row for each and every name.

Name O_Rate A_Rate O_Items A_Items O_Amount A_Amount TotalItems TotalAmount
---- ------ ------ ------- ------- -------- -------- ---------- -----------
ABC       1      2      50      10       50       20         60          70

How to convert the above mentioned table data as per the expected output using a single query. I have tried with Case and Decode but in both cases I am getting two rows only.

Thanks in advance.

Body:
I like to do this with conditional aggregation, but you can also use join:

select o.name, o.Rate as o_Rate, a.Rate as a_Rate,
       o.Kind as o_Kind, a.Kind as a_Kind,
       o.NoOfItems as o_NoOfItems, a.NoOfItems as a_NoOfItems,
       o.TotalAmount as o_TotalAmount, a.TotalAmount as a_TotalAmount,
      (o.NoOfItems + a.NoOfItems) as TotalItems,
      (o.TotalAmount + a.TotalAmount) as TotalAmount
from t o join
     t a
     on o.name = a.name and o.rate = 'O' and a.rate = 'A';


问:
Relative path for Folder.Files
I have an Excel file, and in the same folder I have a folder with CSV files I want to include. Using the From Folder query thing, the first step will give the following query:

```<code>= Folder.Files("D:\OneDrive\Documents\Health\Concept2")
</code>```

Now, this path will not be the same on my laptop for example, but the Excel file will always be in the Health directory...

I get an error if I try to just pass a relative path to Folder.Files, but is there a way to work around this? A fancy function? Some variable or thing I don't know about because I'm a total newb in this area?

Attempt 1

```<code>= Folder.Files(".\Concept2")
= Folder.Files("Concept2")
</code>```

❌DataFormat.Error: The supplied folder path must be a valid absolute path.

Attempt 2

```<code>= Folder.Files(Activeworkbook.Path & "\Concept2")
</code>```

❌ Expression.Error: The name 'Activeworkbook.Path' wasn't recognized.  Make sure it's spelled correctly.

答:
As far as I know you can't make a relative path reference entirely inside Power Query itself. What you CAN do however is setup a relative path reference inside your excel file, then load this into Power Query.

So setup a tab in your Excel file and make a one cell table with the formula

```<code>=LEFT(CELL("filename"),FIND("[",CELL("filename"))-1)&"Concept2\"
</code>```

To get your relative directory reference. Add this table into Power Query, and then you can get the relative directory for you file query like

```<code>Folder.Files(DirectoryQuery{0}[ColumnName])
</code>```

Where "DirectoryQuery" is the name of the query created from your table and "ColumnName" is the name of the column in the table ({0} references the first row in the table).

Title: Relative path for Folder.Files

Body:
I have an Excel file, and in the same folder I have a folder with CSV files I want to include. Using the From Folder query thing, the first step will give the following query:

= Folder.Files("D:\OneDrive\Documents\Health\Concept2")

Now, this path will not be the same on my laptop for example, but the Excel file will always be in the Health directory...

I get an error if I try to just pass a relative path to Folder.Files, but is there a way to work around this? A fancy function? Some variable or thing I don't know about because I'm a total newb in this area?

Attempt 1

= Folder.Files(".\Concept2")
= Folder.Files("Concept2")

❌DataFormat.Error: The supplied folder path must be a valid absolute path.

Attempt 2

= Folder.Files(Activeworkbook.Path & "\Concept2")

❌ Expression.Error: The name 'Activeworkbook.Path' wasn't recognized.  Make sure it's spelled correctly.

Body:
As far as I know you can't make a relative path reference entirely inside Power Query itself. What you CAN do however is setup a relative path reference inside your excel file, then load this into Power Query.

So setup a tab in your Excel file and make a one cell table with the formula

=LEFT(CELL("filename"),FIND("[",CELL("filename"))-1)&"Concept2\"

To get your relative directory reference. Add this table into Power Query, and then you can get the relative directory for you file query like

Folder.Files(DirectoryQuery{0}[ColumnName])

Where "DirectoryQuery" is the name of the query created from your table and "ColumnName" is the name of the column in the table ({0} references the first row in the table).


问:
laravel database pass data blade
I'm new to Laravel and trying to figure out why one of my pages is not pulling data from the database. Running locally using a setup based on the project in Laracasts. I'm on Laravel 5.4 running PHP 7 and MySQL on OS X Sierra.

I'm getting this error: Undefined Variable: hashtags (in my hashtags.blade.php file)

I have this code hashtags.blade.php, designed to pull entries from a database:

```<code><h2>Your Hashtags</h2>

    <table>
        <tr>
            <th>Hashtag</th>
            <th>List Name</th>
            <th>List Members Added</th>
        </tr>

    @foreach($hashtags as $hashtag)

        <tr>
            <td>{{ $hashtag -> tagname }}</td>
            <td>{{ $hashtag -> listname }}</td>
            <td>Count</td>
        </tr>

    @endforeach

    </table>
</code>```

In my web.php routes file:

```<code>Route::get('/hashtags', function () {

    $hashtags = DB::table('hashtags')->get();
    return view('hashtags');
});
</code>```

I have the database connected through the .env file and the overall connection in Laravel seems to be working, just not on this page. I was under the impression that the code in web.php defines the variable $hashtags and passes it to hashtags.blade.php. Apparently I'm missing something here.

I searched and found some other questions about passing data to the blade files, but nothing quite like this issue. Thanks!

答:
You can pass data in blade in 3 ways</p>

```<code>1.  return view('hashtags', ['hashtags' => $hashtags]);
2   return view('hashtags')->with('hashtags', $hashtags);
3.  return view('hashtags', compact('hashtags'));
</code>```

Title: laravel database pass data blade

Body:
I'm new to Laravel and trying to figure out why one of my pages is not pulling data from the database. Running locally using a setup based on the project in Laracasts. I'm on Laravel 5.4 running PHP 7 and MySQL on OS X Sierra.

I'm getting this error: Undefined Variable: hashtags (in my hashtags.blade.php file)

I have this code hashtags.blade.php, designed to pull entries from a database:

Your Hashtags

            Hashtag
            List Name
            List Members Added

    @foreach($hashtags as $hashtag)

            {{ $hashtag -> tagname }}
            {{ $hashtag -> listname }}
            Count

    @endforeach

In my web.php routes file:

Route::get('/hashtags', function () {

    $hashtags = DB::table('hashtags')->get();
    return view('hashtags');
});

I have the database connected through the .env file and the overall connection in Laravel seems to be working, just not on this page. I was under the impression that the code in web.php defines the variable $hashtags and passes it to hashtags.blade.php. Apparently I'm missing something here.

I searched and found some other questions about passing data to the blade files, but nothing quite like this issue. Thanks!

Body:
You can pass data in blade in 3 ways

1.  return view('hashtags', ['hashtags' => $hashtags]);
2   return view('hashtags')->with('hashtags', $hashtags);
3.  return view('hashtags', compact('hashtags'));


问:
BASH: how to filter arguments' source file for different functions
I have a bash script which gets the arguments from external 'source.txt' file.
Sources file includes 10 rows of arguments for instance (mixed files and directories).
One function should use the source file entirely. I achieved this with $(<source.txt) and it works OK.

Whereas the second function should use the same 'source.txt' file partially, filtering the arguments with regex or something else.

Source file:

```<code>/etc/sysconfig/network-scripts/
/etc/ntp.conf
/etc/localtime
/etc/sysconfig/iptables-config
/etc/resolv.conf
/sbin/ifup-local
/sbin/ifdown-local
/usr/local/sbin
/var/spool/cron/
/boot
</code>```

Second function must take only '^/etc/[a-z][A-Z]*' sources with all the content recursively.

How do i do it?

答:
You can simply grep it, like this:

```<code>$(grep '^/etc/[a-z][A-Z]*'<source.txt)
</code>```

Take a note through, that if your arguments happen to contain some spaces or quotes, the subshell approach (command substitution) might fail for you.

To workaround this you can use readarray (mapfile) instead:

```<code>readarray -t args < <(grep '^/etc/[a-z][A-Z]*' source.txt)
your_function "${args[@]}"
</code>```

Body:
I have a bash script which gets the arguments from external 'source.txt' file.
Sources file includes 10 rows of arguments for instance (mixed files and directories).
One function should use the source file entirely. I achieved this with $(<source.txt) and it works OK.

Whereas the second function should use the same 'source.txt' file partially, filtering the arguments with regex or something else.

Source file:

/etc/sysconfig/network-scripts/
/etc/ntp.conf
/etc/localtime
/etc/sysconfig/iptables-config
/etc/resolv.conf
/sbin/ifup-local
/sbin/ifdown-local
/usr/local/sbin
/var/spool/cron/
/boot

Second function must take only '^/etc/[a-z][A-Z]*' sources with all the content recursively.

How do i do it?

Body:
You can simply grep it, like this:

$(grep '^/etc/[a-z][A-Z]*'<source.txt)

Take a note through, that if your arguments happen to contain some spaces or quotes, the subshell approach (command substitution) might fail for you.

To workaround this you can use readarray (mapfile) instead:

readarray -t args < <(grep '^/etc/[a-z][A-Z]*' source.txt)
your_function "${args[@]}"


问:
Convert a Byte array to Image in c# after modifying the array
I'm trying to convert a byte[] to an image in C#. I know this question has been asked on different forums. But none of the answers given on them helped me. To give some context=
I open an image, convert it to a byte[]. I encrypt the byte[]. In the end I still have the byte[] but it has been modified ofc. Now I want to display this again. The byte[] itself consists of 6559 bytes. I try to convert it by doing :

```<code> public Image byteArrayToImage(byte[] byteArrayIn)
    {
        MemoryStream ms = new MemoryStream(byteArrayIn);
        Image returnImage = Image.FromStream(ms);
        return returnImage;
    }
</code>```

and I get this error: Parameter is not valid.

The byte array is constructed by using the .toArray() on a List

```<code>List<byte> encryptedText = new List<byte>();
pbEncrypted.Image = iConverter.byteArrayToImage(encryptedText.ToArray())
</code>```

;

Can anyone help me? Am I forgetting some kind of format or something ?

The byte that has to be converted to an image :

```<code> private void executeAlgoritm(byte[] plainText)
    {

        // Empty list of bytes
        List<byte> encryptedText = new List<byte>();

        // loop over all the bytes in the original byte array gotten from the image
        foreach (byte value in plainText)
        {
            // convert it to a bitarray
            BitArray myBits = new BitArray(8); //define the size

            for (byte x = 0; x < myBits.Count; x++)
            {
                myBits[x] = (((value >> x) & 0x01) == 0x01) ? true : false;
            }

            // encrypt the bitarray and return a byte
            byte bcipher = ConvertToByte( sdes.IPInvers(sdes.FK(sdes.Shift(sdes.FK(sdes.IP(myBits),keygen.P8(keygen.shift(keygen.P10(txtKey.Text))))),keygen.P8(keygen.shift(keygen.shift(keygen.shift(keygen.P10(txtKey.Text))))))));

            // add the byte to the list
            encryptedText.Add(bcipher);

        }
        // show the image by converting the list to an array and the array to an image
        pbEncrypted.Image = iConverter.byteArrayToImage(encryptedText.ToArray());
    }
</code>```

答:
Try something like this.  When working with images and memory streams, be sure to wrap everything in using statements to make sure your objects are disposed properly.</p>

```<code>public static Image CreateImage(byte[] imageData)
{
    Image image;
    using (MemoryStream inStream = new MemoryStream())
    {
        inStream.Write(imageData, 0, imageData.Length);

        image = Bitmap.FromStream(inStream);
    }

    return image;
}
</code>```

Body:
I'm trying to convert a byte[] to an image in C#. I know this question has been asked on different forums. But none of the answers given on them helped me. To give some context=
I open an image, convert it to a byte[]. I encrypt the byte[]. In the end I still have the byte[] but it has been modified ofc. Now I want to display this again. The byte[] itself consists of 6559 bytes. I try to convert it by doing :

 public Image byteArrayToImage(byte[] byteArrayIn)
    {
        MemoryStream ms = new MemoryStream(byteArrayIn);
        Image returnImage = Image.FromStream(ms);
        return returnImage;
    }

and I get this error: Parameter is not valid.

The byte array is constructed by using the .toArray() on a List

List<byte> encryptedText = new List<byte>();
pbEncrypted.Image = iConverter.byteArrayToImage(encryptedText.ToArray())

;

Can anyone help me? Am I forgetting some kind of format or something ?

The byte that has to be converted to an image :

 private void executeAlgoritm(byte[] plainText)
    {

        // Empty list of bytes
        List<byte> encryptedText = new List<byte>();

        // loop over all the bytes in the original byte array gotten from the image
        foreach (byte value in plainText)
        {
            // convert it to a bitarray
            BitArray myBits = new BitArray(8); //define the size

            for (byte x = 0; x < myBits.Count; x++)
            {
                myBits[x] = (((value >> x) & 0x01) == 0x01) ? true : false;
            }

            // encrypt the bitarray and return a byte
            byte bcipher = ConvertToByte( sdes.IPInvers(sdes.FK(sdes.Shift(sdes.FK(sdes.IP(myBits),keygen.P8(keygen.shift(keygen.P10(txtKey.Text))))),keygen.P8(keygen.shift(keygen.shift(keygen.shift(keygen.P10(txtKey.Text))))))));

            // add the byte to the list
            encryptedText.Add(bcipher);

        }
        // show the image by converting the list to an array and the array to an image
        pbEncrypted.Image = iConverter.byteArrayToImage(encryptedText.ToArray());
    }

Body:
Try something like this.  When working with images and memory streams, be sure to wrap everything in using statements to make sure your objects are disposed properly.

public static Image CreateImage(byte[] imageData)
{
    Image image;
    using (MemoryStream inStream = new MemoryStream())
    {
        inStream.Write(imageData, 0, imageData.Length);

        image = Bitmap.FromStream(inStream);
    }

    return image;
}


问:
Show alert from shared class in swift
I am trying to make a alert function to be used by all the view controllers:

```<code>import UIKit
class MyFuncs: NSObject {

    static let shared: MyFuncs = MyFuncs()

    func MsgBox(msg: string)
    {
        let alert = UIAlertController(title: "Test", message:msg, preferredStyle: UIAlertControllerStyle.alert)

// add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))

// show the alert
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController?.present(alert, animated: true, completion: nil)

    }
}
</code>```

However, it works from (view controllers).swift but not from the didFinishLaunchingWithOptions function in AppDelegate.swift.  What am I missing? Thanks.

答:
I had trouble figuring out how to call an alert from an arbitrary class (I was using an extension originally, but like you I ran into problems when I needed to call it outside of a view controller), so instead I wrote a function to create a new window to display the alert in:

```<code>extension UIWindow {
    static func makeWindow () -> UIWindow {
        let window = UIWindow(frame: UIScreen.main.bounds)
        window.rootViewController = UIViewController()
        window.windowLevel = (UIApplication.shared.windows.last?.windowLevel ?? 0) + 1
        window.makeKeyAndVisible()

        return window
    }
}
</code>```

And made an alert subclass with all the logic to call it:

```<code>class MyAlertController: UIAlertController {
    let alertWindow = UIWindow.makeWindow()

    static func doAlert (_ title: String, alertMessage: String) {
        let alert = MyAlertController(title: title, message: alertMessage, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
        alert.alertWindow.rootViewController?.present(alert, animated: true, completion: nil)
    }
}
</code>```

Then just call MyAlertController.doAlert whenever you need to use it.

Title: Show alert from shared class in swift

Body:
I am trying to make a alert function to be used by all the view controllers:

import UIKit
class MyFuncs: NSObject {

    static let shared: MyFuncs = MyFuncs()

    func MsgBox(msg: string)
    {
        let alert = UIAlertController(title: "Test", message:msg, preferredStyle: UIAlertControllerStyle.alert)

// add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))

// show the alert
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController?.present(alert, animated: true, completion: nil)

    }
}

However, it works from (view controllers).swift but not from the didFinishLaunchingWithOptions function in AppDelegate.swift.  What am I missing? Thanks.

Body:
I had trouble figuring out how to call an alert from an arbitrary class (I was using an extension originally, but like you I ran into problems when I needed to call it outside of a view controller), so instead I wrote a function to create a new window to display the alert in:

extension UIWindow {
    static func makeWindow () -> UIWindow {
        let window = UIWindow(frame: UIScreen.main.bounds)
        window.rootViewController = UIViewController()
        window.windowLevel = (UIApplication.shared.windows.last?.windowLevel ?? 0) + 1
        window.makeKeyAndVisible()

        return window
    }
}

And made an alert subclass with all the logic to call it:

class MyAlertController: UIAlertController {
    let alertWindow = UIWindow.makeWindow()

    static func doAlert (_ title: String, alertMessage: String) {
        let alert = MyAlertController(title: title, message: alertMessage, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
        alert.alertWindow.rootViewController?.present(alert, animated: true, completion: nil)
    }
}

Then just call MyAlertController.doAlert whenever you need to use it.


问:
Where is function err_sys() defined?
I am getting an error related to err_sys() in this code:

```<code>#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main()
{
    int sockfd;

    if ((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
        err_sys("can't create socket");

    close(sockfd);
    return 0;
}
</code>```

I am getting the linker error:

```<code>/tmp/cciuUVhz.o: In function `main':
getsockopt.c:(.text+0x38): undefined reference to `err_sys'
collect2: ld returned 1 exit status
</code>```

Where is the function err_sys() defined?

答: As others have said, this code looks like examples from Stevens: Unix Network Programming. If you have the book, look in appendix D: miscellaneous source code for the text book definition (as well as the unp.h header that is used pervasively in examples). The file is too much to type into a SO answer, but a quick internet search for Stevens "standard error functions" returns a lot of google books results with implementations.</p>

Title: Where is function err_sys() defined?

Body:
I am getting an error related to err_sys() in this code:

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main()
{
    int sockfd;

    if ((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
        err_sys("can't create socket");

    close(sockfd);
    return 0;
}

I am getting the linker error:

/tmp/cciuUVhz.o: In function `main':
getsockopt.c:(.text+0x38): undefined reference to `err_sys'
collect2: ld returned 1 exit status

Where is the function err_sys() defined?


问:
@Patch decorator is not compatible with pytest fixture
I have encountered something mysterious, when using patch decorator from mock package integrated with pytest fixture.

I have two modules:

```<code>    -----test folder
          -------func.py
          -------test_test.py
</code>```

in func.py:

```<code>    def a():
        return 1

    def b():
        return a()
</code>```

in test_test.py:

```<code>    import pytest
    from func import a,b
    from mock import patch,Mock

    @pytest.fixture(scope="module")
    def brands():
        return 1

    mock_b=Mock()

    @patch('test_test.b',mock_b)
    def test_compute_scores(brands):
         a()
</code>```

It seems that patch decorate is not compatible with pytest fixture. Does anyone have a insight on that? Thanks

答:
Hopefully this answer on an old question will help someone.

First off, the question doesn't include the error, so we don't really know what's up. But I'll try to provide something that helped me.

If you want a test decorated with a patched object, then in order for it to work with pytest you could just do this:

```<code>@mock.patch('mocked.module')
def test_me(*args):
    mocked_module = args[0]
</code>```

Or for multiple patches:

```<code>@mock.patch('mocked.module1')
@mock.patch('mocked.module')
def test_me(*args):
    mocked_module1, mocked_module2 = args
</code>```

pytest is looking for the names of the fixtures to look up in the test function/method. Providing the *args argument gives us a good workaround the lookup phase. So, to include a fixture with patches, you could do this:

```<code># from question
@pytest.fixture(scope="module")
def brands():
    return 1

@mock.patch('mocked.module1')
def test_me(brands, *args):
    mocked_module1 = args[0]
</code>```

This worked for me running python 3.6 and pytest 3.0.6.

ContentLicense: CC BY-SA 4.0

Body:
I have encountered something mysterious, when using patch decorator from mock package integrated with pytest fixture.

I have two modules:

    -----test folder
          -------func.py
          -------test_test.py

in func.py:

    def a():
        return 1

    def b():
        return a()

in test_test.py:

    import pytest
    from func import a,b
    from mock import patch,Mock

    @pytest.fixture(scope="module")
    def brands():
        return 1

    mock_b=Mock()

    @patch('test_test.b',mock_b)
    def test_compute_scores(brands):
         a()

It seems that patch decorate is not compatible with pytest fixture. Does anyone have a insight on that? Thanks

Body:
Hopefully this answer on an old question will help someone.

First off, the question doesn't include the error, so we don't really know what's up. But I'll try to provide something that helped me.

If you want a test decorated with a patched object, then in order for it to work with pytest you could just do this:

@mock.patch('mocked.module')
def test_me(*args):
    mocked_module = args[0]

Or for multiple patches:

@mock.patch('mocked.module1')
@mock.patch('mocked.module')
def test_me(*args):
    mocked_module1, mocked_module2 = args

pytest is looking for the names of the fixtures to look up in the test function/method. Providing the *args argument gives us a good workaround the lookup phase. So, to include a fixture with patches, you could do this:

# from question
@pytest.fixture(scope="module")
def brands():
    return 1

@mock.patch('mocked.module1')
def test_me(brands, *args):
    mocked_module1 = args[0]

This worked for me running python 3.6 and pytest 3.0.6.


问:
Adding Simple Content to Dynamic Cell Range VBA
I am fairly new to programming and even newer to VBA.

I am attempting to add a column to the beginning of a spreadsheet with "retailer" in "A1" and "RetailerName" in "A2:Last_Relevant_Cell_In_A".

Here is what I have so far:

```<code>Sub AddRetailerName()

Dim WS_Target As Worksheet
Dim WS_Target_Lastrow As Long

Set WS_Target = Worksheets("Sheet1")

'Find last row of WS_Target
WS_Target_Lastrow = WS_Target.Cells.Find("*", [A1], , , _
xlByRows, xlPrevious).Row

'find last column of WS_Target
WS_Target_Lastcol = WS_Target.Cells.Find("*", [A1], , , _
xlByColumns, xlPrevious).Column

Range("A:A").EntireColumn.Insert
Range("A1").FormulaR1C1 = "Retailer"
Range(Cells(2, 1), Cells(WS_Target_Lastcol, 1)).FormulaR1C1 = "RetailerName"

End Sub
</code>```

This is only inserting content into "A1:A6".  The information inserted is correct, but it should be inserting dynamically with how many rows are found in the spreadsheet (in this example, 950).

Any ideas as to how I can fix this?

Note: While this operation is simple to complete with a few clicks (without VBA), I plan to use it on around 20 spreadsheets at once.

答:
You should change

```<code>Range(Cells(2, 1), Cells(WS_Target_Lastcol, 1)).FormulaR1C1 = "RetailerName"
</code>```

to

```<code>Range(Cells(2, 1), Cells(WS_Target_Lastrow, 1)).FormulaR1C1 = "RetailerName"
</code>```

(I assume your last used cell was in column F?  That would explain your code populating to row 6.)

It is also a good idea to qualify your Range and Cells (etc) methods with the worksheet that they refer to, so I recommend changing your code to:

```<code>Sub AddRetailerName()

    Dim WS_Target As Worksheet
    Dim WS_Target_Lastrow As Long
    Dim WS_Target_Lastcol As Long

    Set WS_Target = Worksheets("Sheet1")

    With WS_Target  ' allows us to use "." instead of "WS_Target."
        'Find last row of WS_Target
        WS_Target_Lastrow = .Cells.Find("*", [A1], , , _
                                        xlByRows, xlPrevious).Row

        'find last column of WS_Target
        WS_Target_Lastcol = .Cells.Find("*", [A1], , , _
                                        xlByColumns, xlPrevious).Column

        .Range("A:A").EntireColumn.Insert
        'Use "Value" rather than "FormulaR1C1" to set a value
        '.Range("A1").FormulaR1C1 = "Retailer"
        '.Range(.Cells(2, 1), .Cells(WS_Target_Lastrow, 1)).FormulaR1C1 = "RetailerName"
        .Range("A1").Value = "Retailer"
        .Range(.Cells(2, 1), .Cells(WS_Target_Lastrow, 1)).Value = "RetailerName"
    End With
End Sub
</code>```

And just FYI

```<code>.Range(.Cells(2, 1), .Cells(WS_Target_Lastrow, 1)).Value = "RetailerName"
</code>```

could also be written as either

```<code>.Range(.Cells(2, "A"), .Cells(WS_Target_Lastrow, "A")).Value = "RetailerName"
</code>```

or

```<code>.Range("A2:A" & WS_Target_Lastrow).Value = "RetailerName"
</code>```

They each achieve the same thing, but different people prefer different styles of coding.

Body:
I am fairly new to programming and even newer to VBA.

I am attempting to add a column to the beginning of a spreadsheet with "retailer" in "A1" and "RetailerName" in "A2:Last_Relevant_Cell_In_A".

Here is what I have so far:

Sub AddRetailerName()

Dim WS_Target As Worksheet
Dim WS_Target_Lastrow As Long

Set WS_Target = Worksheets("Sheet1")

'Find last row of WS_Target
WS_Target_Lastrow = WS_Target.Cells.Find("*", [A1], , , _
xlByRows, xlPrevious).Row

'find last column of WS_Target
WS_Target_Lastcol = WS_Target.Cells.Find("*", [A1], , , _
xlByColumns, xlPrevious).Column

Range("A:A").EntireColumn.Insert
Range("A1").FormulaR1C1 = "Retailer"
Range(Cells(2, 1), Cells(WS_Target_Lastcol, 1)).FormulaR1C1 = "RetailerName"

End Sub

This is only inserting content into "A1:A6".  The information inserted is correct, but it should be inserting dynamically with how many rows are found in the spreadsheet (in this example, 950).

Any ideas as to how I can fix this?

Note: While this operation is simple to complete with a few clicks (without VBA), I plan to use it on around 20 spreadsheets at once.

Body:
You should change

Range(Cells(2, 1), Cells(WS_Target_Lastcol, 1)).FormulaR1C1 = "RetailerName"

to

Range(Cells(2, 1), Cells(WS_Target_Lastrow, 1)).FormulaR1C1 = "RetailerName"

(I assume your last used cell was in column F?  That would explain your code populating to row 6.)

It is also a good idea to qualify your Range and Cells (etc) methods with the worksheet that they refer to, so I recommend changing your code to:

Sub AddRetailerName()

    Dim WS_Target As Worksheet
    Dim WS_Target_Lastrow As Long
    Dim WS_Target_Lastcol As Long

    Set WS_Target = Worksheets("Sheet1")

    With WS_Target  ' allows us to use "." instead of "WS_Target."
        'Find last row of WS_Target
        WS_Target_Lastrow = .Cells.Find("*", [A1], , , _
                                        xlByRows, xlPrevious).Row

        'find last column of WS_Target
        WS_Target_Lastcol = .Cells.Find("*", [A1], , , _
                                        xlByColumns, xlPrevious).Column

        .Range("A:A").EntireColumn.Insert
        'Use "Value" rather than "FormulaR1C1" to set a value
        '.Range("A1").FormulaR1C1 = "Retailer"
        '.Range(.Cells(2, 1), .Cells(WS_Target_Lastrow, 1)).FormulaR1C1 = "RetailerName"
        .Range("A1").Value = "Retailer"
        .Range(.Cells(2, 1), .Cells(WS_Target_Lastrow, 1)).Value = "RetailerName"
    End With
End Sub

And just FYI

.Range(.Cells(2, 1), .Cells(WS_Target_Lastrow, 1)).Value = "RetailerName"

could also be written as either

.Range(.Cells(2, "A"), .Cells(WS_Target_Lastrow, "A")).Value = "RetailerName"

or

.Range("A2:A" & WS_Target_Lastrow).Value = "RetailerName"

They each achieve the same thing, but different people prefer different styles of coding.