问:
should this example not alter the memory address rather than the value at that memory address?
In a book I am reading, C++ from scratch, on page 113 the writer creates a char array:

```<code>myString[80];
</code>```

then he uses a function that copies some charectars:

```<code>strcpy(myString,"Hello there");
</code>```

then he creates a pointer to the array:

```<code>*p1 = myString;
</code>```

then he uses an offset and assings a value at that offset:

```<code>p1[4]='c';
</code>```

my question is, p1 is a pointer so it is a memory address, and the offset of 4 gives him the memory address 4 spaces in front, so that means he is assingning the letter 'c' to the memory address rather than at the value stored at that address. Shouldnt it be:

```<code>*(p1[4])='c';
</code>```

basically, how come *(p1 + 4) needs dereferencing but p1[4] does not?

I tried to understand this and the only thing that could make sense to me was if the square brackets act as an asterisk to dereference the pointer. Is this correct or is there another reason why p1[4] does not need to be dereferenced?

答:
p1 + 4 would be the memory address 4 places beyond.

The expression p1[4] (exactly equivalent to *(p1+4)) is called an lvalue expression.  We say that an lvalue expression designates a memory location.  Or in other words, the lvalue expression is synonymous with the memory location itself.  You can always use the & address-of operator on an lvalue expression, and that gives you a pointer to the memory location.

The lvalue expression will go on to be used in one of three possible ways:

Store a value in the designated memory location, or

Retrieve a value from the designated memory location, or

Neither of those.

There is no special syntax to distinguish between these three cases; rather it depends on the larger expression of which the lvalue expression is a part of.  For example, applying the & operator is case 3;  appearing on the left-hand side of the assignment operator = is case 1.  Most other usages fall under case 2.

Body:
In a book I am reading, C++ from scratch, on page 113 the writer creates a char array:

myString[80];

then he uses a function that copies some charectars:

strcpy(myString,"Hello there");

then he creates a pointer to the array:

*p1 = myString;

then he uses an offset and assings a value at that offset:

p1[4]='c';

my question is, p1 is a pointer so it is a memory address, and the offset of 4 gives him the memory address 4 spaces in front, so that means he is assingning the letter 'c' to the memory address rather than at the value stored at that address. Shouldnt it be:

*(p1[4])='c';

basically, how come *(p1 + 4) needs dereferencing but p1[4] does not?

I tried to understand this and the only thing that could make sense to me was if the square brackets act as an asterisk to dereference the pointer. Is this correct or is there another reason why p1[4] does not need to be dereferenced?


来源: stackexchange

问:
Polylines from csv - different behaviour than from string literal
I read a lot of SO topics about encoding to get an idea what's wrong with my code, but I'm still stucked.

I want to decode Google polylines which I have in csv file. I am using polyline library which works fine. The problem is that some lines from csv can't be processed when I read them from csv, but when I just pass that polyline as string literal it works okay. I presume it's some encoding issue, because polylines that make problem have two consecutive backslashes and/or backticks.

```<code>import csv
import polyline

INPUT_FILE = 'sample_input.csv'

csv.register_dialect(
    'mydialect',
    delimiter = ',',
    quotechar = '"',
    doublequote = True,
    skipinitialspace = True,
    quoting = csv.QUOTE_ALL)

with open(INPUT_FILE, 'r', encoding="utf-8") as csv_file:

    read = csv.reader(csv_file, dialect='mydialect')

    header = next(read, [])

    for row in read:

        site_id = row[0]
        encoded_polyline = row[1]

        print(site_id)

        try:
            decoded = polyline.decode(encoded_polyline)
            print(decoded)
        except:
            print(encoded_polyline)

        print()
</code>```

Sample polyline is:

```<code>"dk`mEg}jx[STEFGJKRONUVSTkAtAiAlAsA~Ag@p@[^[`@e@p@KTSVU\\GHGNEHEHCFAFAFAFAPAP?N?B@T@V@R@F"
</code>```

Please pay attention that here it also appears with only one backslash and no backtick - probably similar encoding issue?

Any help would be appreciated, especially explanation why behaviour with string literal is not the same as with string variable.

答:
This should solve your problem</p>

```<code>decoded = polyline.decode(encoded_polyline.replace('\\\\','\\'))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I read a lot of SO topics about encoding to get an idea what's wrong with my code, but I'm still stucked.

I want to decode Google polylines which I have in csv file. I am using polyline library which works fine. The problem is that some lines from csv can't be processed when I read them from csv, but when I just pass that polyline as string literal it works okay. I presume it's some encoding issue, because polylines that make problem have two consecutive backslashes and/or backticks.

import csv
import polyline

INPUT_FILE = 'sample_input.csv'

csv.register_dialect(
    'mydialect',
    delimiter = ',',
    quotechar = '"',
    doublequote = True,
    skipinitialspace = True,
    quoting = csv.QUOTE_ALL)

with open(INPUT_FILE, 'r', encoding="utf-8") as csv_file:

    read = csv.reader(csv_file, dialect='mydialect')

    header = next(read, [])

    for row in read:

        site_id = row[0]
        encoded_polyline = row[1]

        print(site_id)

        try:
            decoded = polyline.decode(encoded_polyline)
            print(decoded)
        except:
            print(encoded_polyline)

        print()

Sample polyline is:

"dk`mEg}jx[STEFGJKRONUVSTkAtAiAlAsA~Ag@p@[^[`@e@p@KTSVU\\GHGNEHEHCFAFAFAFAPAP?N?B@T@V@R@F"

Please pay attention that here it also appears with only one backslash and no backtick - probably similar encoding issue?

Any help would be appreciated, especially explanation why behaviour with string literal is not the same as with string variable.

Body:
This should solve your problem

decoded = polyline.decode(encoded_polyline.replace('\\\\','\\'))


问:
bubble sort for linked list in c++
i tried to implement buble sort for my university project and i have some problems.
i will be happy if you can help me with it.

```<code>void TrainManagerLinkedList:: Swap(TrainManager & x,TrainManager & y)
 {
  TrainManager temp;
  temp =x;
  x = y;
  y = temp;
 }

void TrainManagerLinkedList::BubbleSort()
 {
  TrainManagerLink* outerCurr = this->m_head;
  TrainManagerLink* curr = NULL;

  while(outerCurr != NULL)
  {
   curr = this->m_head;
   while(curr != NULL && curr->m_next != NULL)
   {
    /*if the current link greater then the next swap between them*/
    if (curr->m_data->GetDate() > curr->m_next->m_data->GetDate())
    {
     Swap(&(curr->m_data),&(curr->m_next->m_data));
    }
    else if((curr->m_data->GetDate() == curr->m_next->m_data->GetDate())&(curr->m_data->GetTime() > curr->m_next->m_data->GetTime()))
    {
      Swap(&(curr->m_data),&(curr->m_next->m_data));
    }
    curr = curr->m_next;
   }
   outerCurr = outerCurr->m_next;
  }
  /*now the list is sorted :)*/

 }
</code>```

my data types

```<code>TrainManagerLink *m_head;
 TrainManagerLink *m_tail;
 int m_numOfElements;

class TrainManager
{
 char * m_firstStation;
 char *m_lastStation;
 char * m_origin;
 char * m_destination;
 int m_timeBetweenStations;
 Hour m_releaseTime;
 Hour m_arriveTime;
 Hour m_firstHour;
 Date m_Date;
 int m_standInstation;
 DelayersLinkedList delay;
}
</code>```

the linked list should be sorted by date and hour.
but i have some compile problems.
i relly need your help
thank you,:)

答:
In general there are issues I would address as follows:

Your class TrainManager has char* members not std::string, and you are not managing the memory. Not to mention that all the members are private, which may give you issues when you try comparing its members.

You would do better to swap the "links" rather than swap the actual data inside them.

ContentLicense: CC BY-SA 2.5

Title: bubble sort for linked list in c++

Body:
i tried to implement buble sort for my university project and i have some problems.
i will be happy if you can help me with it.

void TrainManagerLinkedList:: Swap(TrainManager & x,TrainManager & y)
 {
  TrainManager temp;
  temp =x;
  x = y;
  y = temp;
 }

void TrainManagerLinkedList::BubbleSort()
 {
  TrainManagerLink* outerCurr = this->m_head;
  TrainManagerLink* curr = NULL;

  while(outerCurr != NULL)
  {
   curr = this->m_head;
   while(curr != NULL && curr->m_next != NULL)
   {
    /*if the current link greater then the next swap between them*/
    if (curr->m_data->GetDate() > curr->m_next->m_data->GetDate())
    {
     Swap(&(curr->m_data),&(curr->m_next->m_data));
    }
    else if((curr->m_data->GetDate() == curr->m_next->m_data->GetDate())&(curr->m_data->GetTime() > curr->m_next->m_data->GetTime()))
    {
      Swap(&(curr->m_data),&(curr->m_next->m_data));
    }
    curr = curr->m_next;
   }
   outerCurr = outerCurr->m_next;
  }
  /*now the list is sorted :)*/

 }

my data types

TrainManagerLink *m_head;
 TrainManagerLink *m_tail;
 int m_numOfElements;

class TrainManager
{
 char * m_firstStation;
 char *m_lastStation;
 char * m_origin;
 char * m_destination;
 int m_timeBetweenStations;
 Hour m_releaseTime;
 Hour m_arriveTime;
 Hour m_firstHour;
 Date m_Date;
 int m_standInstation;
 DelayersLinkedList delay;
}

the linked list should be sorted by date and hour.
but i have some compile problems.
i relly need your help
thank you,:)


问:
Error message while opening exported excel file
I'm exporting my grid to excel with a normal onRequestStart function in JS (here is the function)

```<code> <script type="text/javascript">
            function onRequestStart(sender, args) {
                if (args.get_eventTarget().indexOf("ExportToExcelButton") >= 0 ||
                 args.get_eventTarget().indexOf("ExportToWordButton") >= 0 ||
                 args.get_eventTarget().indexOf("ExportToCsvButton") >= 0) {
                    args.set_enableAjax(false);
                }
            }
</script>
</code>```

then I'm calling on Grid_ItemCommand  an checking if it is a excel export word or csv then im calling my method doExport()

```<code> private void doExport()
        {
            this.UserGrid.ExportSettings.ExportOnlyData = true;
            this.UserGrid.ExportSettings.IgnorePaging = true;
            this.UserGrid.ExportSettings.OpenInNewWindow = true;
            this.UserGrid.ExportSettings.FileName = String.Format("YearReport_{0}_{1}", this.selectedYear, this.rcbDepartments.SelectedValue);
        }
</code>```

And everything is working perfectly so far , but after finish downloading the file and opening in excel a strange  > "Warring Message" arrived is there a solution how to disable this message ?

Thanks for help and fast answer

PS:If you need something more feel free to ask

答:
I'm currently working on a programmatic way of doing this with c#. Outside of c# if you're just trying to open the file from your file system on windows you can modify the registry to ignore it.

https://support.microsoft.com/en-us/help/948615/error-opening-file-the-file-format-differs-from-the-format-that-the-fi

I'll follow up with my programmatic solution, if I get it.

Body:
I'm exporting my grid to excel with a normal onRequestStart function in JS (here is the function)

then I'm calling on Grid_ItemCommand  an checking if it is a excel export word or csv then im calling my method doExport()

 private void doExport()
        {
            this.UserGrid.ExportSettings.ExportOnlyData = true;
            this.UserGrid.ExportSettings.IgnorePaging = true;
            this.UserGrid.ExportSettings.OpenInNewWindow = true;
            this.UserGrid.ExportSettings.FileName = String.Format("YearReport_{0}_{1}", this.selectedYear, this.rcbDepartments.SelectedValue);
        }

And everything is working perfectly so far , but after finish downloading the file and opening in excel a strange  > "Warring Message" arrived is there a solution how to disable this message ?

Thanks for help and fast answer

PS:If you need something more feel free to ask


问:
How can you fill between a curve and anything other than zmin in an splot in gnuplot?
I am looking to acceive creating a 3D plot similar to this:

```<code>         z ^  **
           |     *
           |       ***                   **
           |           *               *###*
           |             *           *######**  * ***
           |               *    ****###########*#####
           |               ###*######################
           ,-----------------------------------------> y
          /   /   /   /   /   /   /   /   /   /   /
         /---0---0---0---1---1---1---0---0---0---0    1
        /   /   /   /   /   /   /   /   /   /   /
       /---0---0---0---0---1---1---1---0---0---0    2
      /   /   /   /   /   /   /   /   /   /   /
     /---0---0---0---0---0---1---1---1---1---0    3
    /   /   /   /   /   /   /   /   /   /   /
   /---0---0---0---0---0---0---0---1---1---1    4
x v   1   2   3   4   5   6   7   8   9   10
</code>```

I.e. a 3D plot of an x-y-dependent surface/contour plot of a function g(x,y) and a 2D function f(y) in the y-z plane which is filled if g(x,y) > 0...

My approach was using the filledcurves option in gnuplot, but I can't quite manage to get it right.

In a 2D plot what you can do is (e.g. with f = sin(x), g = -0.5) this:

```<code>plot '+' u 1:(($1)>0?sin($1):-1/0) w filledcurves above y1=-0.5
</code>```

resulting in:
In the 3D plot however, when I try something similar:

```<code>xMIN = -1.5
xMAX = 0.5
yMIN = -0.5
yMAX = 1.5
zMIN = -4
zMAX = 8
set isosamples 100
set xyplane at 0
set xrange [xMIN:xMAX]
set yrange [yMIN:yMAX]
set zrange [zMIN:zMAX]
f(x) = 3*sin(3*x)+x**2
g(x,y) = -6*x**2 -12*y**2 - 8*x*y + 6*y+ 2
max(a,b) = a>b?a:1/0
set hidden
set view 45
splot max(g(x,y),0), \
      '++'   u 1:(1.5):(f($1)) w l, \
      ''   u 1:(1.5):(g(($1),($2)) > 0 ? f($1) : -1/0) w filledcurves
</code>```

results in:

This is almost what I want, but the filling is always done until zMIN, but I would like to specify e.g. that it shades until 0 or a curve:
  Adding above y1=0 after the last line gives me:

```<code>      "3D.gpl", line 22: unexpected or unrecognized token
</code>```

Also, specifying a fourth datafield like

```<code>      ...:(-0) w filledcurves
</code>```

as would work in the 2D case, just changes the color here, so setting a second curve until which to fill does not seem possible...

I did see this question as well as this blog post on gnuplotting, but both answers and the post seem to have the same issue: They are all filling until zmin by default.

What I did manage to acceive after some tinkering is this:

Here I am using the fact that there are points in the domain for which g(x,y\') > 0 and others g(x,y\'\') ≤ 0 for any x.
This results in a very hacky solution, but:

To make it dense enough, you have to modify the sampling rate, affecting the surface plot of g as well... In fact simply setting a really high sampling rate appears to crash the splot entirely and I will only see part of it!

Since the 'filling' now effectively is a surface plot squished into a 2D plane you see it's bottom in a different color, of course you can prevent this by setting set hidden3d offset 0 but than this option is global and holds for any other surface where you might not actually want it...

It would be interesting to see if there's a more rigorous solution!

答:
Replacing the last line of your gnuplot script with

```<code>  ''   u 1:(1.5):(g(($1),($2)) > 0 ? f($1) : -1/0) w impulse lw 5
</code>```

gives the following. Does that help?

Body:
I am looking to acceive creating a 3D plot similar to this:

         z ^  **
           |     *
           |       ***                   **
           |           *               *###*
           |             *           *######**  * ***
           |               *    ****###########*#####
           |               ###*######################
           ,-----------------------------------------> y
          /   /   /   /   /   /   /   /   /   /   /
         /---0---0---0---1---1---1---0---0---0---0    1
        /   /   /   /   /   /   /   /   /   /   /
       /---0---0---0---0---1---1---1---0---0---0    2
      /   /   /   /   /   /   /   /   /   /   /
     /---0---0---0---0---0---1---1---1---1---0    3
    /   /   /   /   /   /   /   /   /   /   /
   /---0---0---0---0---0---0---0---1---1---1    4
x v   1   2   3   4   5   6   7   8   9   10

I.e. a 3D plot of an x-y-dependent surface/contour plot of a function g(x,y) and a 2D function f(y) in the y-z plane which is filled if g(x,y) > 0...

My approach was using the filledcurves option in gnuplot, but I can't quite manage to get it right.

In a 2D plot what you can do is (e.g. with f = sin(x), g = -0.5) this:

plot '+' u 1:(($1)>0?sin($1):-1/0) w filledcurves above y1=-0.5

resulting in:
In the 3D plot however, when I try something similar:

xMIN = -1.5
xMAX = 0.5
yMIN = -0.5
yMAX = 1.5
zMIN = -4
zMAX = 8
set isosamples 100
set xyplane at 0
set xrange [xMIN:xMAX]
set yrange [yMIN:yMAX]
set zrange [zMIN:zMAX]
f(x) = 3*sin(3*x)+x**2
g(x,y) = -6*x**2 -12*y**2 - 8*x*y + 6*y+ 2
max(a,b) = a>b?a:1/0
set hidden
set view 45
splot max(g(x,y),0), \
      '++'   u 1:(1.5):(f($1)) w l, \
      ''   u 1:(1.5):(g(($1),($2)) > 0 ? f($1) : -1/0) w filledcurves

results in:

This is almost what I want, but the filling is always done until zMIN, but I would like to specify e.g. that it shades until 0 or a curve:
  Adding above y1=0 after the last line gives me:

      "3D.gpl", line 22: unexpected or unrecognized token

Also, specifying a fourth datafield like

      ...:(-0) w filledcurves

as would work in the 2D case, just changes the color here, so setting a second curve until which to fill does not seem possible...

I did see this question as well as this blog post on gnuplotting, but both answers and the post seem to have the same issue: They are all filling until zmin by default.

What I did manage to acceive after some tinkering is this:

Here I am using the fact that there are points in the domain for which g(x,y\') > 0 and others g(x,y\'\') ≤ 0 for any x.
This results in a very hacky solution, but:

To make it dense enough, you have to modify the sampling rate, affecting the surface plot of g as well... In fact simply setting a really high sampling rate appears to crash the splot entirely and I will only see part of it!

Since the 'filling' now effectively is a surface plot squished into a 2D plane you see it's bottom in a different color, of course you can prevent this by setting set hidden3d offset 0 but than this option is global and holds for any other surface where you might not actually want it...

It would be interesting to see if there's a more rigorous solution!

Body:
Replacing the last line of your gnuplot script with

  ''   u 1:(1.5):(g(($1),($2)) > 0 ? f($1) : -1/0) w impulse lw 5

gives the following. Does that help?


问:
nginx : access.log and error.log file empty
I have just installed nginx on Ubuntu 14.04 using the command

```<code>sudo apt-get install nginx
</code>```

Now, when I open my browser and type in the address localhost then I am correctly shown the "Welcome to nginx" page. Also, I checked the config file located in /etc/nginx/nginx.conf and found the following log settings:

```<code>access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
</code>```

However, when I check these two files, both are empty. I have opened the localhost page multiple times but still the log files are empty. What might be wrong with my setup ?

答:
It looks like by default they are set to go to stdout and stderr.

```<code>lrwxrwxrwx  1 root root   11 Apr 27  2016 access.log -> /dev/stdout
lrwxrwxrwx  1 root root   11 Apr 27  2016 error.log -> /dev/stderr
</code>```

So you can remove the symlinks and should be fine.

```<code>rm -f /var/log/nginx/*
</code>```

Body:
I have just installed nginx on Ubuntu 14.04 using the command

sudo apt-get install nginx

Now, when I open my browser and type in the address localhost then I am correctly shown the "Welcome to nginx" page. Also, I checked the config file located in /etc/nginx/nginx.conf and found the following log settings:

access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;

However, when I check these two files, both are empty. I have opened the localhost page multiple times but still the log files are empty. What might be wrong with my setup ?

Body:
It looks like by default they are set to go to stdout and stderr.

lrwxrwxrwx  1 root root   11 Apr 27  2016 access.log -> /dev/stdout
lrwxrwxrwx  1 root root   11 Apr 27  2016 error.log -> /dev/stderr

So you can remove the symlinks and should be fine.

rm -f /var/log/nginx/*


问:
String interpretation in Swift
I have a struct that looks like this:

```<code>struct colorShapeSize{
    let color: String!
    let shape: String!
    let size: UIImage!
}
</code>```

and I have a string that looks something like this:

"color:{Blue}shape:{round}size:{medium}"

All of the strings will be in the same format (i.e. color will always come first, shape second, and size third).

How would I extract the data from the string and put it into a colorShapeSize struct?

答:
How about this?</p>

```<code>struct ColorShapeSize {
    let color: String
    let shape: String
    let size: String

    init(rawValue: String) {
        var dictionary: [String: String] = [:]
        var sorted = rawValue.components(separatedBy: "}").filter({ return $0.components(separatedBy: ":{").count == 2 })
        for s in sorted {
            let kv = s.components(separatedBy: ":{")
            let key = kv[0]
            let value = kv[1]
            dictionary[key] = value
        }

        color = dictionary["color"] ?? ""
        shape = dictionary["shape"] ?? ""
        size = dictionary["size"] ?? ""
    }
}

let str = "color:{Blue}shape:{round}size:{medium}"
let css = ColorShapeSize(rawValue: str)
print(css.color, css.shape, css.size)
</code>```

Title: String interpretation in Swift

Body:
I have a struct that looks like this:

struct colorShapeSize{
    let color: String!
    let shape: String!
    let size: UIImage!
}

and I have a string that looks something like this:

"color:{Blue}shape:{round}size:{medium}"

All of the strings will be in the same format (i.e. color will always come first, shape second, and size third).

How would I extract the data from the string and put it into a colorShapeSize struct?

Body:
How about this?

struct ColorShapeSize {
    let color: String
    let shape: String
    let size: String

    init(rawValue: String) {
        var dictionary: [String: String] = [:]
        var sorted = rawValue.components(separatedBy: "}").filter({ return $0.components(separatedBy: ":{").count == 2 })
        for s in sorted {
            let kv = s.components(separatedBy: ":{")
            let key = kv[0]
            let value = kv[1]
            dictionary[key] = value
        }

        color = dictionary["color"] ?? ""
        shape = dictionary["shape"] ?? ""
        size = dictionary["size"] ?? ""
    }
}

let str = "color:{Blue}shape:{round}size:{medium}"
let css = ColorShapeSize(rawValue: str)
print(css.color, css.shape, css.size)


问:
Powershell email attachement
I am trying to create a script to automatically send an email with various attachments. I am having an issue of the of it saying the file is not found. I can confirm that the file is present in the folder. I am unsure why I am getting this error and have tried running the script on various platforms thinking that it may be an issue of where the code is running but nothing has worked as of yet. Any help would be greatly appreciated.</p>

```<code>Param (
    $Path = "\\cottonwood\users\Shared\Pool Acquisitions",
    $SMTPServer = "mail.genericmail.com",
    $From = "address@genericmail.com",
   #The below commented out line is used to test with just one individual. Be sure to comment out the one with all individuals before troubleshooting.
    #$To = @("lt@genericmail.com"),
    $SMTPport = "587",
    $To = @("address@genericmail.com"),
    $Subject = "Folders Added in",
    $logname = "\\cottonwood\users\Shared\Loan Documents - Active\logs\New Folders$date.txt",
    $date = (Get-Date -Format MMddyyyy),
    $SMTPBody = "body",
    $files = (Get-ChildItem "\\cottonwood\users\IT\Missing Folder Location")

 )

 $SMTPMessage = @{
    To = $To
    From = $From
    Subject = "$Subject $Path"
    Smtpserver = $SMTPServer
    Port = $SMTPport

}

  $attachment = $files

    $SMTPBody = "`nThe following folders have been found to be non-existant in the last 24 hours:`n`n"
Send-MailMessage @SMTPMessage -Body $SMTPBody -Attachments $attachment
</code>```

答:
Send-MailMessage is unable to locate the files as the variable     $files does not include the full file path

Change:

```<code>$files = (Get-ChildItem "\\cottonwood\users\IT\Missing Folder Location")
</code>```

To:

```<code>$files = (Get-ChildItem "\\cottonwood\users\IT\Missing Folder Location").fullname
</code>```

Title: Powershell email attachement

Body:
I am trying to create a script to automatically send an email with various attachments. I am having an issue of the of it saying the file is not found. I can confirm that the file is present in the folder. I am unsure why I am getting this error and have tried running the script on various platforms thinking that it may be an issue of where the code is running but nothing has worked as of yet. Any help would be greatly appreciated.

Param (
    $Path = "\\cottonwood\users\Shared\Pool Acquisitions",
    $SMTPServer = "mail.genericmail.com",
    $From = "address@genericmail.com",
   #The below commented out line is used to test with just one individual. Be sure to comment out the one with all individuals before troubleshooting.
    #$To = @("lt@genericmail.com"),
    $SMTPport = "587",
    $To = @("address@genericmail.com"),
    $Subject = "Folders Added in",
    $logname = "\\cottonwood\users\Shared\Loan Documents - Active\logs\New Folders$date.txt",
    $date = (Get-Date -Format MMddyyyy),
    $SMTPBody = "body",
    $files = (Get-ChildItem "\\cottonwood\users\IT\Missing Folder Location")

 )

 $SMTPMessage = @{
    To = $To
    From = $From
    Subject = "$Subject $Path"
    Smtpserver = $SMTPServer
    Port = $SMTPport

}

  $attachment = $files

    $SMTPBody = "`nThe following folders have been found to be non-existant in the last 24 hours:`n`n"
Send-MailMessage @SMTPMessage -Body $SMTPBody -Attachments $attachment

Body:
Send-MailMessage is unable to locate the files as the variable     $files does not include the full file path

Change:

$files = (Get-ChildItem "\\cottonwood\users\IT\Missing Folder Location")

To:

$files = (Get-ChildItem "\\cottonwood\users\IT\Missing Folder Location").fullname


问:
How can I create a class instance from a list Python
I'm making a program for a school project. It's a Model United Nations.

```<code>countries = ['Australia', 'Brazil', 'Canada']

class delegate(object):
   def __init__(self, country):
     self.country = country
</code>```

I have a list with countries and a class called delegate. So, each delegate object must have a country. Normally I would do it like this:

```<code>mexico = delegate('Mexico')
</code>```

And that would be it. But I would like to loop over the country list and create class instances for each. I mean:

```<code>australia = delegate('Australia')
brazil = delegate('Brazil')
canada = delegate('Canada')
</code>```

and so on.
How can I make this?
Thank you very much!!

答:
```<code>[delegate(c) for c in countries]
</code>```

Body:
I'm making a program for a school project. It's a Model United Nations.

countries = ['Australia', 'Brazil', 'Canada']

class delegate(object):
   def __init__(self, country):
     self.country = country

I have a list with countries and a class called delegate. So, each delegate object must have a country. Normally I would do it like this:

mexico = delegate('Mexico')

And that would be it. But I would like to loop over the country list and create class instances for each. I mean:

australia = delegate('Australia')
brazil = delegate('Brazil')
canada = delegate('Canada')

and so on.
How can I make this?
Thank you very much!!

Body: [delegate(c) for c in countries]


问:
Finding all cycles/enclosed shapes in a 2D grid
I have an "infinite" 2D grid and I want to detect closed/complete "structures" - areas of any shape which are enclosed on all sides. However, I need to identify each individual closed circuit - including the larger shape, if any.

In researching this, I've discovered the cycle detection algorithm, but I don't see a clean/efficient way to separate the larger circuit from the smaller ones.

For example given the following two "complete" structures:

```<code>0 1 1 1 0
0 1 0 1 0
0 1 1 1 0
0 0 0 0 0
0 1 1 1 1 1
0 1 0 1 0 1
0 1 1 1 1 1
</code>```

The first is a single cell enclosed by 8 "walls". The cycle detection makes it trivial to detect this.

The second example consists of two copies of example one but they share a wall. There are three separate circuits I care about - the left room, the right room, and the overall structure.

Multiple passes of a cycle algorithm might work, but I'd have to be sure I'm not retracing an already-found shape.

I've also looked at the flood fill algorithm, but it seems like it makes the assumption you already know a point inside the bounded area. With an infinite 2D grid I'd need a size limit to force it to give up if it's not in a valid structure.

Are there solutions I'm missing or have I missed something with my thinking?

I will only do this "check" when a boundary value is added. Using the example above, if I change any 0 -> 1, a new cycle has potentially been created and I'll run the logic. I do not care about identifying separate structures and will always have an origin coordinate.

I've been studying the solutions posted here but they're all based on already knowing which nodes are connected to other nodes. I've already toyed with logic that identifies each individual "line" and I can keep going from there, but it feels redundant.

答:
Coming from a graph-theoretic view of the problem, you can interpret every 0 of your map as a node, neighboring 0s are connected with an edge. It sounds to me like what you want to do is compute the connected components of this graph (and maybe their connectivity by 1 values, to find 'neighboring rooms' of the same structure)

If you only want to compute this information once, a straightforward approach using a union-find data structure should suffice, where you apply union once per edge.

If you want to edit your map dynamically, the best approach based on the graph model would probably be some dynamic data structure that supports split or de-union operations, see for example here or here

Body:
I have an "infinite" 2D grid and I want to detect closed/complete "structures" - areas of any shape which are enclosed on all sides. However, I need to identify each individual closed circuit - including the larger shape, if any.

In researching this, I've discovered the cycle detection algorithm, but I don't see a clean/efficient way to separate the larger circuit from the smaller ones.

For example given the following two "complete" structures:

0 1 1 1 0
0 1 0 1 0
0 1 1 1 0
0 0 0 0 0
0 1 1 1 1 1
0 1 0 1 0 1
0 1 1 1 1 1

The first is a single cell enclosed by 8 "walls". The cycle detection makes it trivial to detect this.

The second example consists of two copies of example one but they share a wall. There are three separate circuits I care about - the left room, the right room, and the overall structure.

Multiple passes of a cycle algorithm might work, but I'd have to be sure I'm not retracing an already-found shape.

I've also looked at the flood fill algorithm, but it seems like it makes the assumption you already know a point inside the bounded area. With an infinite 2D grid I'd need a size limit to force it to give up if it's not in a valid structure.

Are there solutions I'm missing or have I missed something with my thinking?

I will only do this "check" when a boundary value is added. Using the example above, if I change any 0 -> 1, a new cycle has potentially been created and I'll run the logic. I do not care about identifying separate structures and will always have an origin coordinate.

I've been studying the solutions posted here but they're all based on already knowing which nodes are connected to other nodes. I've already toyed with logic that identifies each individual "line" and I can keep going from there, but it feels redundant.


问:
AmazonCognitoIdentityProviderClient Signup throwing exception in Xamarin
I tried the following code and I am getting an exception when I call "providerClient.SignUpAsync" with a message

Unable to store key CognitoIdentity:IdentityId:us-east-1:d8dce20b-7e3a-454a-afe5-xxxxxxxxxxxx, got error: -34018

I am not able to find a way to specify the "userpool id" in the code and I am not able to understand what am I doing wrong here. I would really appreciate if anyone can help me here to tell me what am I doing wrong here.

```<code>CognitoAWSCredentials credentials = new CognitoAWSCredentials(
"us-east-1:d8dce20b-7e3a-454a-afe5-xxxxxxxxxxxx",
RegionEndpoint.USEast1
);
AmazonCognitoIdentityProviderClient providerClient = new AmazonCognitoIdentityProviderClient(credentials,RegionEndpoint.USEast1);

    SignUpRequest sr = new SignUpRequest();

    sr.ClientId = "71tu9de9v6murgolfxxxxxxxxx";
    sr.Username = email;
    sr.Password = password;
    sr.SecretHash = "1b7i7kdjcdij03309j0354d8tubo62it33gj4ulkxxxxxxxxxxxx";
    sr.UserAttributes = new List<AttributeType> {
        new AttributeType
        {
            Name = "email",
            Value = email,
        },
         new AttributeType
            {
                Name = "phone_number",
                Value = phone,
            }
    };
    try{

        SignUpResponse result = await providerClient.SignUpAsync(sr);
    }
</code>```

答: Have you added the keychain sharing entitlement to your app?  -34018 is a keychain related error.  https://github.com/xamarin/Xamarin.Auth/issues/139</p>

Body:
I tried the following code and I am getting an exception when I call "providerClient.SignUpAsync" with a message

Unable to store key CognitoIdentity:IdentityId:us-east-1:d8dce20b-7e3a-454a-afe5-xxxxxxxxxxxx, got error: -34018

I am not able to find a way to specify the "userpool id" in the code and I am not able to understand what am I doing wrong here. I would really appreciate if anyone can help me here to tell me what am I doing wrong here.

CognitoAWSCredentials credentials = new CognitoAWSCredentials(
"us-east-1:d8dce20b-7e3a-454a-afe5-xxxxxxxxxxxx",
RegionEndpoint.USEast1
);
AmazonCognitoIdentityProviderClient providerClient = new AmazonCognitoIdentityProviderClient(credentials,RegionEndpoint.USEast1);

    SignUpRequest sr = new SignUpRequest();

    sr.ClientId = "71tu9de9v6murgolfxxxxxxxxx";
    sr.Username = email;
    sr.Password = password;
    sr.SecretHash = "1b7i7kdjcdij03309j0354d8tubo62it33gj4ulkxxxxxxxxxxxx";
    sr.UserAttributes = new List<AttributeType> {
        new AttributeType
        {
            Name = "email",
            Value = email,
        },
         new AttributeType
            {
                Name = "phone_number",
                Value = phone,
            }
    };
    try{

        SignUpResponse result = await providerClient.SignUpAsync(sr);
    }


答:
Creating named variables from a list is usually a bad idea. Maybe you could try

```<code>countries = ['Australia', 'Brazil', 'Canada']

class Delegate(object):    # according to PEP8, class names should be title-case
    def __init__(self, country):
        self.country = country

# create a dict
delegates = {country: Delegate(country) for country in countries}
</code>```

Edit: as per @SethMMorton, Python 2.6 does not understand dictionary comprehensions (ie what I used above). You can get the same result using

```<code>delegates = dict([(country, Delegate(country)) for country in countries])
</code>```

Title: How can I create a class instance from a list Python

Body:
Creating named variables from a list is usually a bad idea. Maybe you could try

countries = ['Australia', 'Brazil', 'Canada']

class Delegate(object):    # according to PEP8, class names should be title-case
    def __init__(self, country):
        self.country = country

# create a dict
delegates = {country: Delegate(country) for country in countries}

Edit: as per @SethMMorton, Python 2.6 does not understand dictionary comprehensions (ie what I used above). You can get the same result using

delegates = dict([(country, Delegate(country)) for country in countries])


问:
Reading a hash from a file on disk
Here is a hash that I save to a file to later be read.

```<code>my_hash = {-1 => 20, -2 => 30, -3 => 40}
File.open("my_file.txt", "w") { |f| f.write my_hash }
#how it looks opening the text file
{-1 => 20, -2 => 30, -3 => 40}
</code>```

When I go to read it, is where my problem is. (following code is separate from top)

```<code>my_hash = File.foreach("my_file.txt") { |f| print f }
p my_hash
#=> {-1 => 20, -2 => 30, -3 => 40}nil
</code>```

that nil messes up the rest of my code..not sure how to get rid of if. Just for clarity the rest of the code...

```<code>back_up_hash = {-1 => 20}
if my_hash.nil?
  my_hash = back_up_hash
end
</code>```

That little nil always makes my_hash equal to back_up_hash. I need that .nil? just in case the file is doesn't have the hash, otherwise the problem just gets pushed further down.

I also tried to read (slurp?..it's a small file) the file like this....

```<code>my_hash = File.read("my_file.txt") { |f| print f }
p my_hash
=> "{-1 => 20, -2 => 30, -3 => 40}"
# not sure how to get it out of string form...and I have searched for it.
</code>```

答:
If you want to take a file on disk whose contents are {-1 => 20, -2 => 30, -3 => 40} and make a hash from it, you want:

```<code>hash_str = File.read('my_file.txt')
my_hash  = eval(hash_str) # Treat a string like Ruby code and evaluate it

# or, as a one-liner
my_hash  = eval(File.read('my_file.txt'))
</code>```

What you were doing is reading in the file and printing it to the screen, one line at a time. The 'print' command does not transform the data, and the foreach method does not map the data it yields to your block into any result. This is why you get nil for your my_hash.

As I recommended in a comment, if you have a Ruby object (like a Hash) and you need to save it to disk and load it later, you may want to use the Marshal module (built into Ruby):

```<code>$ irb
irb(main):001:0> h = {-1 => 20, -2 => 30, -3 => 40}
#=> {-1=>20, -2=>30, -3=>40}
irb(main):002:0> File.open('test.marshal','wb'){ |f| Marshal.dump(h, f) }
#=> #<File:test.marshal (closed)>

$ irb     # later, a new irb session with no knowledge of h
irb(main):001:0> h = File.open('test.marshal'){ |f| Marshal.load(f) }
#=> {-1=>20, -2=>30, -3=>40}
</code>```

Title: Reading a hash from a file on disk

Body:
Here is a hash that I save to a file to later be read.

my_hash = {-1 => 20, -2 => 30, -3 => 40}
File.open("my_file.txt", "w") { |f| f.write my_hash }
#how it looks opening the text file
{-1 => 20, -2 => 30, -3 => 40}

When I go to read it, is where my problem is. (following code is separate from top)

my_hash = File.foreach("my_file.txt") { |f| print f }
p my_hash
#=> {-1 => 20, -2 => 30, -3 => 40}nil

that nil messes up the rest of my code..not sure how to get rid of if. Just for clarity the rest of the code...

back_up_hash = {-1 => 20}
if my_hash.nil?
  my_hash = back_up_hash
end

That little nil always makes my_hash equal to back_up_hash. I need that .nil? just in case the file is doesn't have the hash, otherwise the problem just gets pushed further down.

I also tried to read (slurp?..it's a small file) the file like this....

my_hash = File.read("my_file.txt") { |f| print f }
p my_hash
=> "{-1 => 20, -2 => 30, -3 => 40}"
# not sure how to get it out of string form...and I have searched for it.

Body:
If you want to take a file on disk whose contents are {-1 => 20, -2 => 30, -3 => 40} and make a hash from it, you want:

hash_str = File.read('my_file.txt')
my_hash  = eval(hash_str) # Treat a string like Ruby code and evaluate it

# or, as a one-liner
my_hash  = eval(File.read('my_file.txt'))

What you were doing is reading in the file and printing it to the screen, one line at a time. The 'print' command does not transform the data, and the foreach method does not map the data it yields to your block into any result. This is why you get nil for your my_hash.

As I recommended in a comment, if you have a Ruby object (like a Hash) and you need to save it to disk and load it later, you may want to use the Marshal module (built into Ruby):

$ irb
irb(main):001:0> h = {-1 => 20, -2 => 30, -3 => 40}
#=> {-1=>20, -2=>30, -3=>40}
irb(main):002:0> File.open('test.marshal','wb'){ |f| Marshal.dump(h, f) }
#=> #<File:test.marshal (closed)>

$ irb     # later, a new irb session with no knowledge of h
irb(main):001:0> h = File.open('test.marshal'){ |f| Marshal.load(f) }
#=> {-1=>20, -2=>30, -3=>40}


问:
Jekyll theme error
Tried to change the default theme. First tried the hacker theme, then the primer theme. Got the same error both times:

jekyll 3.5.0 | Error:  Could not locate the included file 'head.html' in any of ["/home/david/Sites/dwmclaughlin.com/_includes"]. Ensure it exists in one of those directories and, if it is a symlink, does not point outside your site source.

I created head.html, then ran jekyll serve. Got the same error but this time it was header.html that was missing. I kept going and created the missing files. Got to the CSS file and got this error:

jekyll 3.5.0 | Error:  Invalid US-ASCII character "\xE2" on line 5

What am I doing wrong?

答:
As you are including _head.html you probably have a _layouts directory which would prevent the hacker theme to load properly, remove the _layouts directory (or copy that directory from the jekyll-theme-hacker folder) and then it should work.

You probably would have to fix the layout used in posts to use the default layout (they probably has the post layout now)

Title: Jekyll theme error


问:
Return duplicate min values
See the table below for reference. I need to return duplicate rows containing the min value.

In this example I want to show only the 2 rows that have SLAT_LEN = 30 or rather the min SLAT_LEN. I tried rank but when I do it does a consecutive rank.  I want the duplicate sizes to have the same rank and to rank consecutively by size.

The sizes change so I can't just use a condition like SLAT_LEN = 30.

Or is there a different approach that I should take?

```<code>   select *
   from(
    select lg.wd_demand_id,wm.slat_len, wm.prof_size, wm.wd_material_id, wm.color, rank() over ( partition by wm.slat_len order by lg.wd_demand_id) as rank
    from wd_demand_log lg, wd_bins wb, wd_material wm, wd_bins_material wbm
    where lg.wd_bins_id = wb.wd_bins_id
    and lg.wd_material_id = wm.wd_material_id
    and lg.wd_bins_id = wbm.wd_bins_id
    and lg.wd_material_id = wbm.wd_material_id
    AND lg.plant_id = 44 AND lg.dept_id = 220 AND wb.plant_id = 44 AND wb.dept_id = 220
    AND NOT EXISTS(SELECT dmpln.wd_demand_id  FROM wd_demnd_pln_inv dmpln WHERE dmpln.wd_demand_id = lg.wd_demand_id)
    AND wm.prof_size = '2' AND wm.color = 450
    AND lg.wd_po_error is null)
</code>```

答:
You'd use PARTITION BY to give the range in which to rank. The ORDER BY specifies the ranking. So in your case you'll need something like

```<code>rank() over (order by wm.slat_len)
</code>```

In case you have Oracle 12c you can limit your results with FETCH FIRST:

```<code>ORDER BY wm.slat_len
FETCH FIRST 1 ROW WITH TIES;
</code>```

Title: Return duplicate min values

Body:
See the table below for reference. I need to return duplicate rows containing the min value.

In this example I want to show only the 2 rows that have SLAT_LEN = 30 or rather the min SLAT_LEN. I tried rank but when I do it does a consecutive rank.  I want the duplicate sizes to have the same rank and to rank consecutively by size.

The sizes change so I can't just use a condition like SLAT_LEN = 30.

Or is there a different approach that I should take?

   select *
   from(
    select lg.wd_demand_id,wm.slat_len, wm.prof_size, wm.wd_material_id, wm.color, rank() over ( partition by wm.slat_len order by lg.wd_demand_id) as rank
    from wd_demand_log lg, wd_bins wb, wd_material wm, wd_bins_material wbm
    where lg.wd_bins_id = wb.wd_bins_id
    and lg.wd_material_id = wm.wd_material_id
    and lg.wd_bins_id = wbm.wd_bins_id
    and lg.wd_material_id = wbm.wd_material_id
    AND lg.plant_id = 44 AND lg.dept_id = 220 AND wb.plant_id = 44 AND wb.dept_id = 220
    AND NOT EXISTS(SELECT dmpln.wd_demand_id  FROM wd_demnd_pln_inv dmpln WHERE dmpln.wd_demand_id = lg.wd_demand_id)
    AND wm.prof_size = '2' AND wm.color = 450
    AND lg.wd_po_error is null)

Body:
You'd use PARTITION BY to give the range in which to rank. The ORDER BY specifies the ranking. So in your case you'll need something like

rank() over (order by wm.slat_len)

In case you have Oracle 12c you can limit your results with FETCH FIRST:

ORDER BY wm.slat_len
FETCH FIRST 1 ROW WITH TIES;


问:
extract NAL units bitstream from an MP4 video
Is it possible to extract every NAL units bitstream? (the actual bitstream)

for example extract them like this:

(4byte length + the remaining bytes till the end of the unit) and do this for all the units in a MP4 video? actually i want to check the occurrence of the 2 bytes after the 4byte length in a MP4 video (coded with H.264 codec).
can i use FFmpeg for this?

Thanks!

答: Sure. Just do 'ffmpeg -I my.mp4 -an -vcodec copy out.264' then look for start codes in the resulting stream. </p>


答:
I believe you're looking for what's called an anonymous class. This means you're making a class without assigning it to a variable. For example:

```<code>country_delegates = []
for country in countries:
    country_delegates.append(delegate(country))
</code>```

This creates a list of delegate objects, one for each country. If you want to get the delegate belonging to a specific country, you could write a function that searches that list and returns the delegate object for the correct country.

Body:
I believe you're looking for what's called an anonymous class. This means you're making a class without assigning it to a variable. For example:

country_delegates = []
for country in countries:
    country_delegates.append(delegate(country))

This creates a list of delegate objects, one for each country. If you want to get the delegate belonging to a specific country, you could write a function that searches that list and returns the delegate object for the correct country.


问:
Required class is missing: org/codehaus/gmaven/mojo/GroovyMojo when tried to run to generate report and send an email in the Maven Project
I have Maven JUnit Project, which compiles, builds and tests successfully. Also when I do the mvn site all the tests run successfully and generates the surefire-report at ..\target\site.. directory.

Now, I need to send an email this report to given recipients.

Here is my POM:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>
<groupId>xxxx</groupId>
<artifactId>EmailReportMaven</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name></name>
<description></description>
 <dependencies>
  <dependency>
     <groupId>junit</groupId>
     <artifactId>junit</artifactId>
     <version>4.12</version>
  </dependency>
  <dependency>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-surefire-report-plugin</artifactId>
     <version>2.18.1</version>
  </dependency>
  <dependency>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-site-plugin</artifactId>
     <version>3.6</version>
  </dependency>
  <dependency>
     <groupId>org.apache.maven.doxia</groupId>
     <artifactId>doxia-core</artifactId>
     <version>1.7</version>
  </dependency>
  <dependency>
     <groupId>ch.fortysix</groupId>
     <artifactId>maven-postman-plugin</artifactId>
     <version>0.1.6</version>
  </dependency>
 </dependencies>
<build>
  <plugins>
     <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
           <source>1.7</source>
           <target>1.7</target>
        </configuration>
     </plugin>
     <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <version>1.10</version>
        <executions>
           <execution>
              <id>add-source</id>
              <phase>generate-sources</phase>
              <goals>
                 <goal>add-source</goal>
              </goals>
              <configuration>
                 <sources>
                    <source>appmodels</source>
                 </sources>
              </configuration>
           </execution>
        </executions>
     </plugin>
     <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
           <testFailureIgnore>false</testFailureIgnore>
        </configuration>
        <version>2.7.2</version>
     </plugin>
     <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-report-plugin</artifactId>
        <version>2.18.1</version>
     </plugin>
     <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-site-plugin</artifactId>
        <version>3.6</version>
        <configuration>
           <generateSitemap>true</generateSitemap>
           <generateReports>true</generateReports>
        </configuration>
     </plugin>
     <plugin>
        <groupId>ch.fortysix</groupId>
        <artifactId>maven-postman-plugin</artifactId>
        <version>0.1.6</version>
        <executions>
           <execution>
              <id>send_an_mail</id>
              <goals>
                 <goal>send-mail</goal>
              </goals>
              <inherited>false</inherited>
              <phase>test</phase>
              <configuration>
                 <from>mailID</from>
                 <subject>this is a test auto email sent from Eclipse using Maven</subject>
                 <htmlMessage><![CDATA[<p>Hi, Please find attached.</p>]]></htmlMessage>
                 <failonerror>true</failonerror>
                 <mailhost>host</mailhost>
                 <mailport>port</mailport>
                 <mailssl>true</mailssl>
                 <mailAltConfig>true</mailAltConfig>
                 <mailuser>emailID</mailuser>
                 <mailpassword>password</mailpassword>
                 <receivers>
                    <receiver>emailID</receiver>
                 </receivers>
                 <fileSets>
                    <fileSet>
                       <directory>${basedir}/target/site</directory>
                       <includes>
                          <include>**/surefire-report.html</include>
                       </includes>
                    </fileSet>
                 </fileSets>
              </configuration>
           </execution>
        </executions>
     </plugin>
  </plugins>
  <pluginManagement>
      <plugins>
        <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.-->
        <plugin>
           <groupId>org.eclipse.m2e</groupId>
           <artifactId>lifecycle-mapping</artifactId>
           <version>1.0.0</version>
           <configuration>
              <lifecycleMappingMetadata>
                 <pluginExecutions>
                    <pluginExecution>
                       <pluginExecutionFilter>
                          <groupId>org.codehaus.mojo</groupId>
                          <artifactId>build-helper-maven-plugin</artifactId>
                          <versionRange>[1.10,)</versionRange>
                          <goals>
                             <goal>add-source</goal>
                          </goals>
                       </pluginExecutionFilter>
                       <action>
                          <ignore />
                       </action>
                    </pluginExecution>
                 </pluginExecutions>
              </lifecycleMappingMetadata>
           </configuration>
        </plugin>
     </plugins>
  </pluginManagement>
 </build>
  <reporting>
  <plugins>
     <!-- Include the unit test reports in the site -->
     <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-report-plugin</artifactId>
        <version>2.18.1</version>
     </plugin>
  </plugins>
</code>```

Below errors are thrown when mvn surefire-report:report postman:send-mail is run:

```<code>[INFO] --- maven-postman-plugin:0.1.6:send-mail (Report Generation) @ EmailReportMaven ---
[WARNING] Error injecting: ch.fortysix.maven.plugin.postaman.MailSenderMojo
java.lang.TypeNotPresentException: Type
ch.fortysix.maven.plugin.postaman.MailSenderMojo not present
    at org.eclipse.sisu.space.URLClassSpace.loadClass(URLClassSpace.java:147)
    at org.eclipse.sisu.space.NamedClass.load(NamedClass.java:46)
    at org.eclipse.sisu.space.AbstractDeferredClass.get(AbstractDeferredClass.java:48)
    at com.google.inject.internal.ProviderInternalFactory.provision(ProviderInternalFactory.java:81)
    at com.google.inject.internal.InternalFactoryToInitializableAdapter.provision(InternalFactoryToInitializableAdapter.java:53)
    at com.google.inject.internal.ProviderInternalFactory$1.call(ProviderInternalFactory.java:65)
    at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:115)
    at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:133)
    at com.google.inject.internal.ProvisionListenerStackCallback.provision(ProvisionListenerStackCallback.java:68)
    at com.google.inject.internal.ProviderInternalFactory.circularGet(ProviderInternalFactory.java:63)
    at com.google.inject.internal.InternalFactoryToInitializableAdapter.get(InternalFactoryToInitializableAdapter.java:45)
    at com.google.inject.internal.InjectorImpl$2$1.call(InjectorImpl.java:1016)
    at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1092)
    at com.google.inject.internal.InjectorImpl$2.get(InjectorImpl.java:1012)
    at org.eclipse.sisu.inject.Guice4$1.get(Guice4.java:162)
    at org.eclipse.sisu.inject.LazyBeanEntry.getValue(LazyBeanEntry.java:81)
    at org.eclipse.sisu.plexus.LazyPlexusBean.getValue(LazyPlexusBean.java:51)
    at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:263)
    at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:255)
    at org.apache.maven.plugin.internal.DefaultMavenPluginManager.getConfiguredMojo(DefaultMavenPluginManager.java:519)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:121)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:154)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:146)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:309)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:194)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:107)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:993)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:345)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:191)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: java.lang.NoClassDefFoundError: org/codehaus/gmaven/mojo/GroovyMojo
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClassFromSelf(ClassRealm.java:401)
    at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:42)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.unsynchronizedLoadClass(ClassRealm.java:271)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:247)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:239)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClassFromSelf(ClassRealm.java:401)
    at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:42)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.unsynchronizedLoadClass(ClassRealm.java:271)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:247)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:239)
    at org.eclipse.sisu.space.URLClassSpace.loadClass(URLClassSpace.java:139)
    ... 41 more
Caused by: java.lang.ClassNotFoundException: org.codehaus.gmaven.mojo.GroovyMojo
    at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:50)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.unsynchronizedLoadClass(ClassRealm.java:271)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:247)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:239)
    ... 70 more
 [INFO] ------------------------------------------------------------------------
 [INFO] BUILD FAILURE
 [INFO] ------------------------------------------------------------------------
 [INFO] Total time: 24.073 s [INFO] Finished at:
 2017-07-05T18:47:50-05:00 [INFO] Final Memory: 28M/226M
 [INFO] ------------------------------------------------------------------------
 [ERROR] Failed to execute goal
 ch.fortysix:maven-postman-plugin:0.1.6:send-mail (Report Generation)
 on project EmailReportMaven: Execution Report Generation of goal
 ch.fortysix:maven-postman-plugin:0.1.6:send-mail failed: Unable to
 load the mojo 'send-mail' in the plugin
 'ch.fortysix:maven-postman-plugin:0.1.6'. A required class is missing:
 org/codehaus/gmaven/mojo/GroovyMojo
 [ERROR] -----------------------------------------------------
 [ERROR] realm =    plugin>ch.fortysix:maven-postman-plugin:0.1.6
 [ERROR] strategy = org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy
 [ERROR] urls[0] =
 file:/C:/Development/Maven_Repo/ch/fortysix/maven-postman-plugin/0.1.6/maven-postman-plugin-0.1.6.jar
 [ERROR] urls[1] =
 file:/C:/Development/Maven_Repo/org/codehaus/plexus/plexus-utils/1.1/plexus-utils-1.1.jar
 [ERROR] Number of foreign imports: 1
 [ERROR] import: Entry[import from realm ClassRealm[maven.api, parent: null]]
 [ERROR]
 [ERROR] -----------------------------------------------------
 [ERROR] : org.codehaus.gmaven.mojo.GroovyMojo
 [ERROR] -> [Help 1]
 [ERROR]
 [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
 [ERROR] Re-run Maven using the -X switch to enable full debug logging.
 [ERROR]
 [ERROR] For more information about the errors and possible solutions, please read the following articles:
 [ERROR] [Help 1]
</code>```

答:
I was able to resolve this issue. I did the following things:

Deleted the contents of the  ../org/apache/maven folder.

Deleted the contents of the ../ch/ folder (this was the turning point, I thought so)

Re-built the Maven project.

Ran mvn site command.

Successfully e-mail sent with surefire-report.html as attachment.

Body:
I have Maven JUnit Project, which compiles, builds and tests successfully. Also when I do the mvn site all the tests run successfully and generates the surefire-report at ..\target\site.. directory.

Now, I need to send an email this report to given recipients.

Here is my POM:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>
<groupId>xxxx</groupId>
<artifactId>EmailReportMaven</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name></name>
<description></description>
 <dependencies>
  <dependency>
     <groupId>junit</groupId>
     <artifactId>junit</artifactId>
     <version>4.12</version>
  </dependency>
  <dependency>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-surefire-report-plugin</artifactId>
     <version>2.18.1</version>
  </dependency>
  <dependency>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-site-plugin</artifactId>
     <version>3.6</version>
  </dependency>
  <dependency>
     <groupId>org.apache.maven.doxia</groupId>
     <artifactId>doxia-core</artifactId>
     <version>1.7</version>
  </dependency>
  <dependency>
     <groupId>ch.fortysix</groupId>
     <artifactId>maven-postman-plugin</artifactId>
     <version>0.1.6</version>
  </dependency>
 </dependencies>
<build>
  <plugins>
     <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
           <source>1.7</source>
           <target>1.7</target>
        </configuration>
     </plugin>
     <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <version>1.10</version>
        <executions>
           <execution>
              <id>add-source</id>
              <phase>generate-sources</phase>
              <goals>
                 <goal>add-source</goal>
              </goals>
              <configuration>
                 <sources>
                    <source>appmodels</source>
                 </sources>
              </configuration>
           </execution>
        </executions>
     </plugin>
     <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
           <testFailureIgnore>false</testFailureIgnore>
        </configuration>
        <version>2.7.2</version>
     </plugin>
     <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-report-plugin</artifactId>
        <version>2.18.1</version>
     </plugin>
     <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-site-plugin</artifactId>
        <version>3.6</version>
        <configuration>
           <generateSitemap>true</generateSitemap>
           <generateReports>true</generateReports>
        </configuration>
     </plugin>
     <plugin>
        <groupId>ch.fortysix</groupId>
        <artifactId>maven-postman-plugin</artifactId>
        <version>0.1.6</version>
        <executions>
           <execution>
              <id>send_an_mail</id>
              <goals>
                 <goal>send-mail</goal>
              </goals>
              <inherited>false</inherited>
              <phase>test</phase>
              <configuration>
                 <from>mailID</from>
                 <subject>this is a test auto email sent from Eclipse using Maven</subject>
                 <htmlMessage><![CDATA[
Hi, Please find attached.
]]></htmlMessage>
                 <failonerror>true</failonerror>
                 <mailhost>host</mailhost>
                 <mailport>port</mailport>
                 <mailssl>true</mailssl>
                 <mailAltConfig>true</mailAltConfig>
                 <mailuser>emailID</mailuser>
                 <mailpassword>password</mailpassword>
                 <receivers>
                    <receiver>emailID</receiver>
                 </receivers>
                 <fileSets>
                    <fileSet>
                       <directory>${basedir}/target/site</directory>
                       <includes>
                          <include>**/surefire-report.html</include>
                       </includes>
                    </fileSet>
                 </fileSets>
              </configuration>
           </execution>
        </executions>
     </plugin>
  </plugins>
  <pluginManagement>
      <plugins>

        <plugin>
           <groupId>org.eclipse.m2e</groupId>
           <artifactId>lifecycle-mapping</artifactId>
           <version>1.0.0</version>
           <configuration>
              <lifecycleMappingMetadata>
                 <pluginExecutions>
                    <pluginExecution>
                       <pluginExecutionFilter>
                          <groupId>org.codehaus.mojo</groupId>
                          <artifactId>build-helper-maven-plugin</artifactId>
                          <versionRange>[1.10,)</versionRange>
                          <goals>
                             <goal>add-source</goal>
                          </goals>
                       </pluginExecutionFilter>
                       <action>
                          <ignore />
                       </action>
                    </pluginExecution>
                 </pluginExecutions>
              </lifecycleMappingMetadata>
           </configuration>
        </plugin>
     </plugins>
  </pluginManagement>
 </build>
  <reporting>
  <plugins>

     <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-report-plugin</artifactId>
        <version>2.18.1</version>
     </plugin>
  </plugins>

Below errors are thrown when mvn surefire-report:report postman:send-mail is run:

[INFO] --- maven-postman-plugin:0.1.6:send-mail (Report Generation) @ EmailReportMaven ---
[WARNING] Error injecting: ch.fortysix.maven.plugin.postaman.MailSenderMojo
java.lang.TypeNotPresentException: Type
ch.fortysix.maven.plugin.postaman.MailSenderMojo not present
    at org.eclipse.sisu.space.URLClassSpace.loadClass(URLClassSpace.java:147)
    at org.eclipse.sisu.space.NamedClass.load(NamedClass.java:46)
    at org.eclipse.sisu.space.AbstractDeferredClass.get(AbstractDeferredClass.java:48)
    at com.google.inject.internal.ProviderInternalFactory.provision(ProviderInternalFactory.java:81)
    at com.google.inject.internal.InternalFactoryToInitializableAdapter.provision(InternalFactoryToInitializableAdapter.java:53)
    at com.google.inject.internal.ProviderInternalFactory$1.call(ProviderInternalFactory.java:65)
    at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:115)
    at com.google.inject.internal.ProvisionListenerStackCallback$Provision.provision(ProvisionListenerStackCallback.java:133)
    at com.google.inject.internal.ProvisionListenerStackCallback.provision(ProvisionListenerStackCallback.java:68)
    at com.google.inject.internal.ProviderInternalFactory.circularGet(ProviderInternalFactory.java:63)
    at com.google.inject.internal.InternalFactoryToInitializableAdapter.get(InternalFactoryToInitializableAdapter.java:45)
    at com.google.inject.internal.InjectorImpl$2$1.call(InjectorImpl.java:1016)
    at com.google.inject.internal.InjectorImpl.callInContext(InjectorImpl.java:1092)
    at com.google.inject.internal.InjectorImpl$2.get(InjectorImpl.java:1012)
    at org.eclipse.sisu.inject.Guice4$1.get(Guice4.java:162)
    at org.eclipse.sisu.inject.LazyBeanEntry.getValue(LazyBeanEntry.java:81)
    at org.eclipse.sisu.plexus.LazyPlexusBean.getValue(LazyPlexusBean.java:51)
    at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:263)
    at org.codehaus.plexus.DefaultPlexusContainer.lookup(DefaultPlexusContainer.java:255)
    at org.apache.maven.plugin.internal.DefaultMavenPluginManager.getConfiguredMojo(DefaultMavenPluginManager.java:519)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:121)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:154)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:146)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:309)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:194)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:107)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:993)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:345)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:191)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: java.lang.NoClassDefFoundError: org/codehaus/gmaven/mojo/GroovyMojo
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClassFromSelf(ClassRealm.java:401)
    at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:42)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.unsynchronizedLoadClass(ClassRealm.java:271)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:247)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:239)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClassFromSelf(ClassRealm.java:401)
    at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:42)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.unsynchronizedLoadClass(ClassRealm.java:271)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:247)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:239)
    at org.eclipse.sisu.space.URLClassSpace.loadClass(URLClassSpace.java:139)
    ... 41 more
Caused by: java.lang.ClassNotFoundException: org.codehaus.gmaven.mojo.GroovyMojo
    at org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy.loadClass(SelfFirstStrategy.java:50)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.unsynchronizedLoadClass(ClassRealm.java:271)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:247)
    at org.codehaus.plexus.classworlds.realm.ClassRealm.loadClass(ClassRealm.java:239)
    ... 70 more
 [INFO] ------------------------------------------------------------------------
 [INFO] BUILD FAILURE
 [INFO] ------------------------------------------------------------------------
 [INFO] Total time: 24.073 s [INFO] Finished at:
 2017-07-05T18:47:50-05:00 [INFO] Final Memory: 28M/226M
 [INFO] ------------------------------------------------------------------------
 [ERROR] Failed to execute goal
 ch.fortysix:maven-postman-plugin:0.1.6:send-mail (Report Generation)
 on project EmailReportMaven: Execution Report Generation of goal
 ch.fortysix:maven-postman-plugin:0.1.6:send-mail failed: Unable to
 load the mojo 'send-mail' in the plugin
 'ch.fortysix:maven-postman-plugin:0.1.6'. A required class is missing:
 org/codehaus/gmaven/mojo/GroovyMojo
 [ERROR] -----------------------------------------------------
 [ERROR] realm =    plugin>ch.fortysix:maven-postman-plugin:0.1.6
 [ERROR] strategy = org.codehaus.plexus.classworlds.strategy.SelfFirstStrategy
 [ERROR] urls[0] =
 file:/C:/Development/Maven_Repo/ch/fortysix/maven-postman-plugin/0.1.6/maven-postman-plugin-0.1.6.jar
 [ERROR] urls[1] =
 file:/C:/Development/Maven_Repo/org/codehaus/plexus/plexus-utils/1.1/plexus-utils-1.1.jar
 [ERROR] Number of foreign imports: 1
 [ERROR] import: Entry[import from realm ClassRealm[maven.api, parent: null]]
 [ERROR]
 [ERROR] -----------------------------------------------------
 [ERROR] : org.codehaus.gmaven.mojo.GroovyMojo
 [ERROR] -> [Help 1]
 [ERROR]
 [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
 [ERROR] Re-run Maven using the -X switch to enable full debug logging.
 [ERROR]
 [ERROR] For more information about the errors and possible solutions, please read the following articles:
 [ERROR] [Help 1]


问:
Importing JSON into Pandas
I have to following JSON that is coming from an API (e.g. my_json). The array of entities is stored in a key called entities:

```<code>{
    "action" : "get",
    "application" : "4d97323f-ac0f-11e6-b1d4-0eec2415f3df",
    "params" : {
      "limit" : [ "2" ]
    },
    "path" : "/businesses",
    "entities" : [
        {
            "uuid" : "508d56f1-636b-11e7-9928-122e0737977d",
            "type" : "business",
            "size" : 730 },
        {
            "uuid" : "2f3bd4dc-636b-11e7-b937-0ad881f403bf",
            "type" : "business",
            "size" : 730
        } ],
  "timestamp" : 1499469891059,
  "duration" : 244,
  "count" : 2
}
</code>```

I am trying to load them into a data frame as follows:

```<code>import pandas as pd

pd.read_json(my_json['entities'], orient='split')
</code>```

I get the following error:

```<code>ValueError: Invalid file path or buffer object type: <type 'list'>
</code>```

I have tried records orientation and still doesn't work.

答:
The way you are using my_json['entities'] makes it look like it is a Python dict.

According to the pandas documentation, read_json takes in "a valid JSON string or file-like". You can convert a dict into a json string with the following:

```<code>import json
json_str = json.dumps(my_json["entities"])
</code>```

The data under the key "entities" as you have described it does not fit the formatting strategy for orient="split". It looks like you will need to use orient="list":

```<code>import pandas as pd

my_json = """{
    "entities": [
            {
                "type": "business",
                "uuid": "199bca3e-baf6-11e6-861b-0ad881f403bf",
                "size": 918
            },
            {
                "type": "business",
                "uuid": "054a7650-b36a-11e6-a734-122e0737977d",
                "size": 984
            }
        ]
}"""

print pd.read_json(my_json, orient='list')
</code>```

yielding:

```<code>                                              entity
0  {u'type': u'business', u'uuid': u'199bca3e-baf...
1  {u'type': u'business', u'uuid': u'054a7650-b36...
</code>```

or

```<code>import pandas as pd

my_json = """[
    {
        "type": "business",
        "uuid": "199bca3e-baf6-11e6-861b-0ad881f403bf",
        "size": 918
    },
    {
        "type": "business",
        "uuid": "054a7650-b36a-11e6-a734-122e0737977d",
        "size": 984
    }
]"""

print pd.read_json(my_json, orient='list')
</code>```

yielding:

```<code>   size      type                                  uuid
0   918  business  199bca3e-baf6-11e6-861b-0ad881f403bf
1   984  business  054a7650-b36a-11e6-a734-122e0737977d
</code>```

Title: Importing JSON into Pandas

Body:
I have to following JSON that is coming from an API (e.g. my_json). The array of entities is stored in a key called entities:

{
    "action" : "get",
    "application" : "4d97323f-ac0f-11e6-b1d4-0eec2415f3df",
    "params" : {
      "limit" : [ "2" ]
    },
    "path" : "/businesses",
    "entities" : [
        {
            "uuid" : "508d56f1-636b-11e7-9928-122e0737977d",
            "type" : "business",
            "size" : 730 },
        {
            "uuid" : "2f3bd4dc-636b-11e7-b937-0ad881f403bf",
            "type" : "business",
            "size" : 730
        } ],
  "timestamp" : 1499469891059,
  "duration" : 244,
  "count" : 2
}

I am trying to load them into a data frame as follows:

import pandas as pd

pd.read_json(my_json['entities'], orient='split')

I get the following error:

ValueError: Invalid file path or buffer object type: <type 'list'>

I have tried records orientation and still doesn't work.

Body:
The way you are using my_json['entities'] makes it look like it is a Python dict.

According to the pandas documentation, read_json takes in "a valid JSON string or file-like". You can convert a dict into a json string with the following:

import json
json_str = json.dumps(my_json["entities"])

The data under the key "entities" as you have described it does not fit the formatting strategy for orient="split". It looks like you will need to use orient="list":

import pandas as pd

my_json = """{
    "entities": [
            {
                "type": "business",
                "uuid": "199bca3e-baf6-11e6-861b-0ad881f403bf",
                "size": 918
            },
            {
                "type": "business",
                "uuid": "054a7650-b36a-11e6-a734-122e0737977d",
                "size": 984
            }
        ]
}"""

print pd.read_json(my_json, orient='list')

yielding:

                                              entity
0  {u'type': u'business', u'uuid': u'199bca3e-baf...
1  {u'type': u'business', u'uuid': u'054a7650-b36...

or

import pandas as pd

my_json = """[
    {
        "type": "business",
        "uuid": "199bca3e-baf6-11e6-861b-0ad881f403bf",
        "size": 918
    },
    {
        "type": "business",
        "uuid": "054a7650-b36a-11e6-a734-122e0737977d",
        "size": 984
    }
]"""

print pd.read_json(my_json, orient='list')

yielding:

   size      type                                  uuid
0   918  business  199bca3e-baf6-11e6-861b-0ad881f403bf
1   984  business  054a7650-b36a-11e6-a734-122e0737977d

ContentLicense: CC BY-SA 4.0


问:
How can I drop all the tables in a PostgreSQL database?
How can I drop all tables in PostgreSQL, working from the command line?

I don't want to drop the database itself, just all tables and all the data in them.

答:
I modified Pablo's answer slightly for the convenience of having the generated SQL commands returned as one single string:</p>

```<code>select string_agg('drop table "' || tablename || '" cascade', '; ')
from pg_tables where schemaname = 'public'
</code>```

Body:
I modified Pablo's answer slightly for the convenience of having the generated SQL commands returned as one single string:

select string_agg('drop table "' || tablename || '" cascade', '; ')
from pg_tables where schemaname = 'public'