问:
Transposing a part of the rdd row
I have a requirement where I need to transpose only certain elements of each RDD row element. I have below input file.

```<code>sno|fname |lname |f1 |f2  |f3  |f4
1  |sunil |kumar |500|1000|2000|3000
2  |mahesh|kalani|600|700 |800 |1000
</code>```

I need the oputput as below.

```<code>1|sunil |kumar |f1|500
1|sunil |kumar |f2|1000
1|sunil |kumar |f3|2000
1|sunil |kumar |f4|3000
2|mahesh|kalani|f1|600
2|mahesh|kalani|f2|700
2|mahesh|kalani|f3|800
2|mahesh|kalani|f4|1000
</code>```

How can I write a mapper function on the RDD to get the output?

答:
You can use flatMap:

```<code>rdd.flatMap {
  case (sno, fname, name, f1, f2, f3, f4) =>
    List("f1", "f2", "f3", "f4").zip(List(f1, f2, f3, f4)).map {
      case (k, v) => (sno, fname, name, k, v)
    }
}
</code>```

This is assuming you already have removed the header row, and parsed each other row as a tuple.

EDIT

To parse each row as a tuple, you can do as follow:

```<code>rawRdd.map(row => row.split("|") match {
  case Array(sno, fname, name, f1, f2, f3, f4) => (sno, fname, name, f1, f2, f3, f4)
}
</code>```

Note that you might as well merge the two steps into one, using only flatMap.

Title: Transposing a part of the rdd row

Body:
I have a requirement where I need to transpose only certain elements of each RDD row element. I have below input file.

sno|fname |lname |f1 |f2  |f3  |f4
1  |sunil |kumar |500|1000|2000|3000
2  |mahesh|kalani|600|700 |800 |1000

I need the oputput as below.

1|sunil |kumar |f1|500
1|sunil |kumar |f2|1000
1|sunil |kumar |f3|2000
1|sunil |kumar |f4|3000
2|mahesh|kalani|f1|600
2|mahesh|kalani|f2|700
2|mahesh|kalani|f3|800
2|mahesh|kalani|f4|1000

How can I write a mapper function on the RDD to get the output?

Body:
You can use flatMap:

rdd.flatMap {
  case (sno, fname, name, f1, f2, f3, f4) =>
    List("f1", "f2", "f3", "f4").zip(List(f1, f2, f3, f4)).map {
      case (k, v) => (sno, fname, name, k, v)
    }
}

This is assuming you already have removed the header row, and parsed each other row as a tuple.

EDIT

To parse each row as a tuple, you can do as follow:

rawRdd.map(row => row.split("|") match {
  case Array(sno, fname, name, f1, f2, f3, f4) => (sno, fname, name, f1, f2, f3, f4)
}

Note that you might as well merge the two steps into one, using only flatMap.


来源: stackexchange

问:
Active Users SQL query
I'm trying to graph active users in a webapp. My database consists of two main tables, user and task. task has a user_id.

My definition of active users: is a user who has created more than 2 tasks within two weeks of a given end date.

So, I need an SQL query that gives me the number of active users between a given start and end date. I was able to do this by putting the query inside a loop, pulling the results each time, but I'd love to be able to do it in a single query.

The returned data should be something like:

```<code>Date         Count
2010-01-01   4
2010-01-02   3
2010-01-03   5
</code>```

Edit to clarify desired dataset.

答:
A GROUP BY with a HAVING clause should be sufficient to get all users

```<code>SELECT u.user_id
FROM   user u
       INNER JOIN task t ON t.user_id = u.user_id
WHERE  date BETWEEN DATEADD(week, -2, <EndDate>) AND <EndDate>

GROUP BY
       u.user_id
HAVING COUNT(*) > 1
</code>```

and to get the total count wrap it up in an another statement

```<code>SELECT COUNT(*)
FROM   (
         SELECT u.user_id
         FROM   user u
                INNER JOIN task t ON t.user_id = u.user_id
         WHERE  date BETWEEN DATEADD(week, -2, <EndDate>) AND <EndDate>
         GROUP BY
                u.user_id
         HAVING COUNT(*) > 1
       ) u
</code>```

Edit

Fixed the 2 week requirement using the code posted by Joe.

ContentLicense: CC BY-SA 2.5

Title: Active Users SQL query

Body:
I'm trying to graph active users in a webapp. My database consists of two main tables, user and task. task has a user_id.

My definition of active users: is a user who has created more than 2 tasks within two weeks of a given end date.

So, I need an SQL query that gives me the number of active users between a given start and end date. I was able to do this by putting the query inside a loop, pulling the results each time, but I'd love to be able to do it in a single query.

The returned data should be something like:

Date         Count
2010-01-01   4
2010-01-02   3
2010-01-03   5

Edit to clarify desired dataset.

Body:
A GROUP BY with a HAVING clause should be sufficient to get all users

SELECT u.user_id
FROM   user u
       INNER JOIN task t ON t.user_id = u.user_id
WHERE  date BETWEEN DATEADD(week, -2, <EndDate>) AND <EndDate>

GROUP BY
       u.user_id
HAVING COUNT(*) > 1

and to get the total count wrap it up in an another statement

SELECT COUNT(*)
FROM   (
         SELECT u.user_id
         FROM   user u
                INNER JOIN task t ON t.user_id = u.user_id
         WHERE  date BETWEEN DATEADD(week, -2, <EndDate>) AND <EndDate>
         GROUP BY
                u.user_id
         HAVING COUNT(*) > 1
       ) u

Edit

Fixed the 2 week requirement using the code posted by Joe.


问:
C++ equivalent of fgets for reading from popen
I need to process some data from standard output. Here is the code I am using:

```<code>FILE* in;
in = popen("ls -a", "r");
char line[256]
while (fgets(line, sizeof(line), in) != NULL) {
    // do something with line
}
</code>```

Which works fine but there is a problem if the line is longer than 256 bytes. So now I tried the following but it is not a good solution:

```<code>FILE* in;
in = popen("ls -a", "r");
char line[100000000] // Wow
while (fgets(line, sizeof(line), in) != NULL) {
    // do something with line
}
</code>```

How do I use c++ to avoid having to specify the line size? I.e. be able to handle a line of any length?

Edit, getline doesn't work! :=[[

```<code>FILE *in;
std::string line;
while(std::getline(in, line))
{
   // Says no matching function =((((
}
</code>```

答:
You can't.

The C++ standard library functions can't hook into arbitrary FILE*s (at least, not without hacks).

The typical approach here is to read in chunks of, say, 512 bytes. Then, iff you need the entire result in a single buffer, append into a std::string or std::vector<char> inside that loop. Yes, it'll result in a bit of data copying, but your computer can handle it. And you'd always have had to do this anyway.

ContentLicense: CC BY-SA 3.0

Body:
I need to process some data from standard output. Here is the code I am using:

FILE* in;
in = popen("ls -a", "r");
char line[256]
while (fgets(line, sizeof(line), in) != NULL) {
    // do something with line
}

Which works fine but there is a problem if the line is longer than 256 bytes. So now I tried the following but it is not a good solution:

FILE* in;
in = popen("ls -a", "r");
char line[100000000] // Wow
while (fgets(line, sizeof(line), in) != NULL) {
    // do something with line
}

How do I use c++ to avoid having to specify the line size? I.e. be able to handle a line of any length?

Edit, getline doesn't work! :=[[

FILE *in;
std::string line;
while(std::getline(in, line))
{
   // Says no matching function =((((
}


问:
error after running a job in google cloud ML
I tried running a word-RNN model from github on Google Cloud ML . After submitting the job,I am getting errors in log file.

This is what i submitted for training

```<code>gcloud ml-engine jobs submit training word_pred_7 \
    --package-path trainer \
    --module-name trainer.train \
    --runtime-version 1.0 \
    --job-dir $JOB_DIR \
    --region $REGION \
    -- \
    --data_dir gs://model-development/arpit/word-rnn-tensorflow-master/data/tinyshakespeare/real1.txt \
    --save_dir gs://model-development/arpit/word-rnn-tensorflow-master/save
</code>```

This is what I get in the log file.

答:
Finally, after submitting 77 jobs to cloud ML I am able to run the job and problem was not with the arguments while submitting the job. It was about the IO errors generated by files .npy which have to stores using file_io.FileIo and read as StringIO. </p>

<p>These IO Errors have not been mentioned anywhere and one should check for them if they find any errors where it says no such file or directory. </p>

ContentLicense: CC BY-SA 4.0

Body:
I tried running a word-RNN model from github on Google Cloud ML . After submitting the job,I am getting errors in log file.

This is what i submitted for training

gcloud ml-engine jobs submit training word_pred_7 \
    --package-path trainer \
    --module-name trainer.train \
    --runtime-version 1.0 \
    --job-dir $JOB_DIR \
    --region $REGION \
    -- \
    --data_dir gs://model-development/arpit/word-rnn-tensorflow-master/data/tinyshakespeare/real1.txt \
    --save_dir gs://model-development/arpit/word-rnn-tensorflow-master/save

This is what I get in the log file.

Body:
Finally, after submitting 77 jobs to cloud ML I am able to run the job and problem was not with the arguments while submitting the job. It was about the IO errors generated by files .npy which have to stores using file_io.FileIo and read as StringIO.

These IO Errors have not been mentioned anywhere and one should check for them if they find any errors where it says no such file or directory.


问:
dotnet pack - How do you specify the name of the package?
I am trying to pack a library as a NuGet package in powershell, like so:

```<code>function Create-NuGetPackages($projects) {

    if (!(Test-Path $NuGetPackageDirectory)) {
        New-Item $NuGetPackageDirectory -ItemType Directory
    }

    foreach ($project in $projects) {
        pushd $project.DirectoryName

        & dotnet.exe pack --configuration $Configuration --output $NuGetPackageDirectory --no-build

        popd
    }

    return $NuGetPackageDirectory
}
</code>```

The project is using a project.json and a .xproj file (there is also a .csproj file for working on the project in .NET 4.5.1). The above command functions, but I end up with a NuGet package name MyProject.Core and I need it to be MyProject to match the legacy packages.

The project is a port and the most sensible thing to do is name the folder after the Java package, which is MyProject.Core, but I can't seem to figure out how to make it generate a NuGet package with a different name.

I have tried using this command on the CLI:

```<code>dotnet pack "src\MyProject.Core\MyProject.csproj" --output NuGetPackages\ --configuration "Release"
</code>```

but it gives the error:

```<code>Unable to find a project.json in src\MyProject.Core\MyProject.csproj\project.json
</code>```

According to this page:

PROJECT

The project to pack. It's either a path to a csproj file or to a directory. If omitted, it defaults to the current directory.

So why if I specify the path of the csproj does it look for a project.json file?

I was able to work around this issue for the name of the assembly by specifying:

```<code>"buildOptions": { "outputName": "MyProject" },
</code>```

But the pack command totally ignores this. There also doesn't seem to be an option to specify the name of the NuGet package in the packOptions section.

I had a look at this old question but it looks like they are talking about the nuget tool, not the dotnet tool.

Is my only option to rename the folder (which will likely cause a lot of other stuff to break now), or is there another way to specify the NuGet package name for the dotnet pack command?

On a side note, I have read in several places that project.json is going away and we are going back to .csproj, but it is unclear when that will take effect. Should I be aiming to eliminate the project.json file or is it too early for that?

答:
Since Lex Li pointed out that the tooling is still a work in progress, I came up with a hackish solution that doesn't force me to have to resort to .nuspec files again (and much rearranging of the project) just to get it working.

```<code># Hack because dotnet pack doesn't provide a way to override the directory
# name for the NuGet package name when using project.json.
# So, we copy MyProject.Core to a new directory
# MyProject to work around this.
function Copy-MyProject() {
    Copy-Item -Recurse -Force "$root\src\MyProject.Core" "$ReleaseDirectory\MyProject"
}

function Delete-MyProject-Copy() {
    Remove-Item "$ReleaseDirectory\MyProject" -Force -Recurse -ErrorAction SilentlyContinue
}

function Create-NuGetPackages($projects) {

    try
    {
        Copy-MyProject
        $projects = $projects += Get-ChildItem -Path "$ReleaseDirectory\MyProject\project.json"
        $projects = $projects | ? { !$_.Directory.Name.Equals("MyProject.Core") }

        if (!(Test-Path $NuGetPackageDirectory)) {
            New-Item $NuGetPackageDirectory -ItemType Directory
        }

        foreach ($project in $projects) {
            pushd $project.DirectoryName

            Write-Host "Creating NuGet package for $project..." -ForegroundColor Magenta

            & dotnet.exe pack --configuration $Configuration --output $NuGetPackageDirectory --no-build

            popd
        }
    } finally {
        Delete-MyProject-Copy
    }

    return $NuGetPackageDirectory
}
</code>```

Body:
I am trying to pack a library as a NuGet package in powershell, like so:

function Create-NuGetPackages($projects) {

    if (!(Test-Path $NuGetPackageDirectory)) {
        New-Item $NuGetPackageDirectory -ItemType Directory
    }

    foreach ($project in $projects) {
        pushd $project.DirectoryName

        & dotnet.exe pack --configuration $Configuration --output $NuGetPackageDirectory --no-build

        popd
    }

    return $NuGetPackageDirectory
}

The project is using a project.json and a .xproj file (there is also a .csproj file for working on the project in .NET 4.5.1). The above command functions, but I end up with a NuGet package name MyProject.Core and I need it to be MyProject to match the legacy packages.

The project is a port and the most sensible thing to do is name the folder after the Java package, which is MyProject.Core, but I can't seem to figure out how to make it generate a NuGet package with a different name.

I have tried using this command on the CLI:

dotnet pack "src\MyProject.Core\MyProject.csproj" --output NuGetPackages\ --configuration "Release"

but it gives the error:

Unable to find a project.json in src\MyProject.Core\MyProject.csproj\project.json

According to this page:

PROJECT

The project to pack. It's either a path to a csproj file or to a directory. If omitted, it defaults to the current directory.

So why if I specify the path of the csproj does it look for a project.json file?

I was able to work around this issue for the name of the assembly by specifying:

"buildOptions": { "outputName": "MyProject" },

But the pack command totally ignores this. There also doesn't seem to be an option to specify the name of the NuGet package in the packOptions section.

I had a look at this old question but it looks like they are talking about the nuget tool, not the dotnet tool.

Is my only option to rename the folder (which will likely cause a lot of other stuff to break now), or is there another way to specify the NuGet package name for the dotnet pack command?

On a side note, I have read in several places that project.json is going away and we are going back to .csproj, but it is unclear when that will take effect. Should I be aiming to eliminate the project.json file or is it too early for that?

Body:
Since Lex Li pointed out that the tooling is still a work in progress, I came up with a hackish solution that doesn't force me to have to resort to .nuspec files again (and much rearranging of the project) just to get it working.

# Hack because dotnet pack doesn't provide a way to override the directory
# name for the NuGet package name when using project.json.
# So, we copy MyProject.Core to a new directory
# MyProject to work around this.
function Copy-MyProject() {
    Copy-Item -Recurse -Force "$root\src\MyProject.Core" "$ReleaseDirectory\MyProject"
}

function Delete-MyProject-Copy() {
    Remove-Item "$ReleaseDirectory\MyProject" -Force -Recurse -ErrorAction SilentlyContinue
}

function Create-NuGetPackages($projects) {

    try
    {
        Copy-MyProject
        $projects = $projects += Get-ChildItem -Path "$ReleaseDirectory\MyProject\project.json"
        $projects = $projects | ? { !$_.Directory.Name.Equals("MyProject.Core") }

        if (!(Test-Path $NuGetPackageDirectory)) {
            New-Item $NuGetPackageDirectory -ItemType Directory
        }

        foreach ($project in $projects) {
            pushd $project.DirectoryName

            Write-Host "Creating NuGet package for $project..." -ForegroundColor Magenta

            & dotnet.exe pack --configuration $Configuration --output $NuGetPackageDirectory --no-build

            popd
        }
    } finally {
        Delete-MyProject-Copy
    }

    return $NuGetPackageDirectory
}


问:
How to use phpmailer from sh service framework
I am really stuck in email concept. I used sh service framework for past 3 days i am searching all the way to find how email concept works in sh service especially php mailer.

Thanks and help needed

答:
Use this command :

composer require phpmailer/phpmailer

Follow below procedure:

require 'vendor/autoload.php';

$app->get('/contactus',function($app){

```<code> $mail = new PHPMailer;
 $mail->isSMTP();
$mail->Host = 'smtp1.example.com;smtp2.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'user@example.com';
$mail->Password = 'secret';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('joe@example.net', 'Joe User');
$mail->addAddress('ellen@example.com');
$mail->addReplyTo('info@example.com', 'Information');
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');

$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
$mail->isHTML(true);       // Set email format to HTML

$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';

if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}    // Set mailer to
</code>```

});
it is working fine.

Thanks

Body:
Use this command :

composer require phpmailer/phpmailer

Follow below procedure:

require 'vendor/autoload.php';

$app->get('/contactus',function($app){

 $mail = new PHPMailer;
 $mail->isSMTP();
$mail->Host = 'smtp1.example.com;smtp2.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'user@example.com';
$mail->Password = 'secret';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('joe@example.net', 'Joe User');
$mail->addAddress('ellen@example.com');
$mail->addReplyTo('info@example.com', 'Information');
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');

$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
$mail->isHTML(true);       // Set email format to HTML

$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';

if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}    // Set mailer to

});
it is working fine.

Thanks


问:
Quicksort with insertion Sort finish - where am I going wrong?
I am working on a project for a class. We are to write a quick-sort that transitions to a insertion sort at the specified value. Thats no problem, where I am now having difficulty is figuring out why I am not getting the performance I expect.

One of the requirements is that it must sort an array of 5,00,000 ints in under 1,300 ms (this is on standard machines, so CPU speed is not an issue). First of all, I can't get it to work on 5,000,000 because of a stack overflow error (too many recursive calls...). If I increase the heap size, I am still getting a lot slower than that.

Below is the code. Any hints anyone?

Thanks in advance

```<code>public class MyQuickSort {

    public static void sort(int [] toSort, int moveToInsertion)
    {
        sort(toSort, 0, toSort.length - 1, moveToInsertion);
    }

    private static void sort(int[] toSort, int first, int last, int moveToInsertion)
    {
        if (first < last)
        {
            if ((last - first) < moveToInsertion)
            {
                insertionSort(toSort, first, last);
            }
            else
            {
                int split = quickHelper(toSort, first, last);
                sort(toSort, first, split - 1, moveToInsertion);
                sort(toSort, split + 1, last, moveToInsertion);
            }
        }
    }

    private static int quickHelper(int[] toSort, int first, int last)
    {
        sortPivot(toSort, first, last);
        swap(toSort, first, first + (last - first)/2);
        int left = first;
        int right = last;
        int pivotVal = toSort[first];
        do
        {
            while ( (left < last) && (toSort[left] <= pivotVal))
            {
                left++;
            }

            while (toSort[right] > pivotVal)
            {
                right--;
            }

            if (left < right)
            {
                swap(toSort, left, right);
            }

        } while (left < right);

        swap(toSort, first, right);

        return right;
    }

    private static void sortPivot(int[] toSort, int first, int last)
    {
        int middle = first + (last - first)/2;

        if (toSort[middle] < toSort[first]) swap(toSort, first, middle);

        if (toSort[last] < toSort[middle]) swap(toSort, middle, last);

        if (toSort[middle] < toSort[first]) swap(toSort, first, middle);

    }

    private static void insertionSort(int [] toSort, int first, int last)
    {
         for (int nextVal = first + 1; nextVal <= last; nextVal++)
            {
                int toInsert = toSort[nextVal];
                int j = nextVal - 1;
                while (j >= 0 && toInsert < toSort[j])
                {
                    toSort[j + 1] = toSort[j];
                    j--;
                }
                toSort[j + 1] = toInsert;
            }
    }

    private static void swap(int[] toSort, int i, int j)
    {
        int temp = toSort[i];
        toSort[i] = toSort[j];
        toSort[j] = temp;
    }

}
</code>```

答:
I haven't tested this with your algorithm, and I don't know what kind of data set you're running with, but consider choosing a better pivot than the leftmost element.  From Wikipedia on Quicksort:

Choice of pivot In very early versions
  of quicksort, the leftmost element of
  the partition would often be chosen as
  the pivot element. Unfortunately, this
  causes worst-case behavior on already
  sorted arrays, which is a rather
  common use-case. The problem was
  easily solved by choosing either a
  random index for the pivot, choosing
  the middle index of the partition or
  (especially for longer partitions)
  choosing the median of the first,
  middle and last element of the
  partition for the pivot

Body:
I am working on a project for a class. We are to write a quick-sort that transitions to a insertion sort at the specified value. Thats no problem, where I am now having difficulty is figuring out why I am not getting the performance I expect.

One of the requirements is that it must sort an array of 5,00,000 ints in under 1,300 ms (this is on standard machines, so CPU speed is not an issue). First of all, I can't get it to work on 5,000,000 because of a stack overflow error (too many recursive calls...). If I increase the heap size, I am still getting a lot slower than that.

Below is the code. Any hints anyone?

Thanks in advance

public class MyQuickSort {

    public static void sort(int [] toSort, int moveToInsertion)
    {
        sort(toSort, 0, toSort.length - 1, moveToInsertion);
    }

    private static void sort(int[] toSort, int first, int last, int moveToInsertion)
    {
        if (first < last)
        {
            if ((last - first) < moveToInsertion)
            {
                insertionSort(toSort, first, last);
            }
            else
            {
                int split = quickHelper(toSort, first, last);
                sort(toSort, first, split - 1, moveToInsertion);
                sort(toSort, split + 1, last, moveToInsertion);
            }
        }
    }

    private static int quickHelper(int[] toSort, int first, int last)
    {
        sortPivot(toSort, first, last);
        swap(toSort, first, first + (last - first)/2);
        int left = first;
        int right = last;
        int pivotVal = toSort[first];
        do
        {
            while ( (left < last) && (toSort[left] <= pivotVal))
            {
                left++;
            }

            while (toSort[right] > pivotVal)
            {
                right--;
            }

            if (left < right)
            {
                swap(toSort, left, right);
            }

        } while (left < right);

        swap(toSort, first, right);

        return right;
    }

    private static void sortPivot(int[] toSort, int first, int last)
    {
        int middle = first + (last - first)/2;

        if (toSort[middle] < toSort[first]) swap(toSort, first, middle);

        if (toSort[last] < toSort[middle]) swap(toSort, middle, last);

        if (toSort[middle] < toSort[first]) swap(toSort, first, middle);

    }

    private static void insertionSort(int [] toSort, int first, int last)
    {
         for (int nextVal = first + 1; nextVal <= last; nextVal++)
            {
                int toInsert = toSort[nextVal];
                int j = nextVal - 1;
                while (j >= 0 && toInsert < toSort[j])
                {
                    toSort[j + 1] = toSort[j];
                    j--;
                }
                toSort[j + 1] = toInsert;
            }
    }

    private static void swap(int[] toSort, int i, int j)
    {
        int temp = toSort[i];
        toSort[i] = toSort[j];
        toSort[j] = temp;
    }

}


问:
Mongodb $addToSet duplicates
I'm building an app with mongodb and node js. It is about creating polls, and I want to add new options on database and increase the number of votes for each submit. All works fine but on the first search it duplicates the option rather than just update the vote here is the code:

```<code>let newChoice = function(option) { this.option = choice; this.votes = 0; };        let New = new newChoice(choice);
poll.update({_id: id}, {$addToSet: {"options": New, $exists: false}}, function(err, doc){
  if (err) {
    console.log(err);
  }
  else {
      console.log(doc)
  }
});
poll.update({_id: id, "options.option": choice}, {$inc: {"options.$.votes": 1}}, function(err, vote) { if (err) { console.log( err); } });
    res.redirect("/show/"+id);
});
</code>```

and here is the way that I store on db "options":

```<code>[ { "option": " pizza", "votes": 0 }, { "option": "burger ", "votes": 0 }
</code>```

Any idea how to prevent duplicates?

答:
You may conditionally insert if the option with your choice and votes=0 doesn't exist already

```<code>db.coll.update(
    {_id: id, 'options.option': {$ne: my_choice}},
    {$push: {options: {'option': my_choice, 'votes': 0}}});
</code>```

After this operation, your update command for incrementing the count will work as expected.

Title: Mongodb $addToSet duplicates

Body:
I'm building an app with mongodb and node js. It is about creating polls, and I want to add new options on database and increase the number of votes for each submit. All works fine but on the first search it duplicates the option rather than just update the vote here is the code:

let newChoice = function(option) { this.option = choice; this.votes = 0; };        let New = new newChoice(choice);
poll.update({_id: id}, {$addToSet: {"options": New, $exists: false}}, function(err, doc){
  if (err) {
    console.log(err);
  }
  else {
      console.log(doc)
  }
});
poll.update({_id: id, "options.option": choice}, {$inc: {"options.$.votes": 1}}, function(err, vote) { if (err) { console.log( err); } });
    res.redirect("/show/"+id);
});

and here is the way that I store on db "options":

[ { "option": " pizza", "votes": 0 }, { "option": "burger ", "votes": 0 }

Any idea how to prevent duplicates?

Body:
You may conditionally insert if the option with your choice and votes=0 doesn't exist already

db.coll.update(
    {_id: id, 'options.option': {$ne: my_choice}},
    {$push: {options: {'option': my_choice, 'votes': 0}}});

After this operation, your update command for incrementing the count will work as expected.


问:
Elasticsearch config with log4j2.xml
I'm iniatilizing the elasticsearch client with new PreBuiltTransportClient(Settings.EMPTY); and I have the following config:

pom.xml

```<code><dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.8.1</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.25</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.8.1</version>
</dependency>
</code>```

since log4j2 takes the xml file ==> log4j2.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">

    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
        </Console>

        <RollingFile name="RollingFile" filename="log/rolling.log"
            filepattern="${logPath}/%d{YYYYMMddHHmmss}-rolling.log">
            <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
            <Policies>
                <SizeBasedTriggeringPolicy size="100 MB" />
            </Policies>
            <DefaultRolloverStrategy max="20" />
        </RollingFile>

    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console" />
            <AppenderRef ref="RollingFile" />
        </Root>
        <logger name="org.springframework.web">
            <level value="info" />
            <appender-ref ref="Console" />
        </logger>
    </Loggers>
</Configuration>
</code>```

but the initialization throws nasty config exceptions, namely

```<code>Error while converting string [] to type [class.org.apache.logging.log4j.Level]. Using default value [null]. java.lang.IllegalArgumentException: Unknown level constant [].
</code>```

I would have expected some config is missing for the logging. Searching for proper config I found only hints for the log4j.properties files - which I don't want to use. I guess I need to configure an appropriate logger name - but don't know which. org.elasticsearch.common.logging did not help.

How to configure it properly?

答:
I think the error lies in your xml file. Inside your loggers tag you have defined a logger incorrectly. Could you try the following?

```<code><Loggers>
    <Root level="INFO">
      <AppenderRef ref="Console"/>
      <AppenderRef ref="RollingFile" />
    </Root>
    <Logger name="corg.springframework.web" level="INFO">
      <AppenderRef ref="Console"/>
    </Logger>
</Loggers>
</code>```

The level needs to be inside the logger line, instead of a separate level line

Source: log4j

Title: Elasticsearch config with log4j2.xml

Body:
I'm iniatilizing the elasticsearch client with new PreBuiltTransportClient(Settings.EMPTY); and I have the following config:

pom.xml

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.8.1</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.25</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.8.1</version>
</dependency>

since log4j2 takes the xml file ==> log4j2.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">

    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
        </Console>

        <RollingFile name="RollingFile" filename="log/rolling.log"
            filepattern="${logPath}/%d{YYYYMMddHHmmss}-rolling.log">
            <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
            <Policies>
                <SizeBasedTriggeringPolicy size="100 MB" />
            </Policies>
            <DefaultRolloverStrategy max="20" />
        </RollingFile>

    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console" />
            <AppenderRef ref="RollingFile" />
        </Root>
        <logger name="org.springframework.web">
            <level value="info" />
            <appender-ref ref="Console" />
        </logger>
    </Loggers>
</Configuration>

but the initialization throws nasty config exceptions, namely

Error while converting string [] to type [class.org.apache.logging.log4j.Level]. Using default value [null]. java.lang.IllegalArgumentException: Unknown level constant [].

I would have expected some config is missing for the logging. Searching for proper config I found only hints for the log4j.properties files - which I don't want to use. I guess I need to configure an appropriate logger name - but don't know which. org.elasticsearch.common.logging did not help.

How to configure it properly?

Body:
I think the error lies in your xml file. Inside your loggers tag you have defined a logger incorrectly. Could you try the following?

<Loggers>
    <Root level="INFO">
      <AppenderRef ref="Console"/>
      <AppenderRef ref="RollingFile" />
    </Root>
    <Logger name="corg.springframework.web" level="INFO">
      <AppenderRef ref="Console"/>
    </Logger>
</Loggers>

The level needs to be inside the logger line, instead of a separate level line

Source: log4j


问:
I am not able to figure out how to pass Bundle in mapview.onCreate() in custom viewholder class
i have a generic viewholder class for  recyclerview which uses MapView inside that row, and the viewholder class is extending my base viewholder abstract class which has populateData(TO to), i am initializing map in the constructor of my viewholder class and passing null to mapview.onCreate(null).

my classes are look like this

```<code>public class MyViewHolder extends BaseViewHolder implements OnReadyMapCallBack{

   private MapView mapView;
   public MyViewHolder(View view){

       mapView = view.findViewById(R.id.map);
       mapView.onCreate(null); //here i should pass Bundle instead

      }
// this method is declared in parent class abstract class

@override
public void populateData(TO to){
     mapView.getAsync(this);
}
 public void onMapReady(GoogleMap googleMap) {
}
}
</code>```

答:
You trued this:

```<code>    Bundle args = new Bundle();
    args.putString("key",value);

    mapView.onCreate(args);
</code>```

?

Body:
i have a generic viewholder class for  recyclerview which uses MapView inside that row, and the viewholder class is extending my base viewholder abstract class which has populateData(TO to), i am initializing map in the constructor of my viewholder class and passing null to mapview.onCreate(null).

my classes are look like this

public class MyViewHolder extends BaseViewHolder implements OnReadyMapCallBack{

   private MapView mapView;
   public MyViewHolder(View view){

       mapView = view.findViewById(R.id.map);
       mapView.onCreate(null); //here i should pass Bundle instead

      }
// this method is declared in parent class abstract class

@override
public void populateData(TO to){
     mapView.getAsync(this);
}
 public void onMapReady(GoogleMap googleMap) {
}
}

Body:
You trued this:

    Bundle args = new Bundle();
    args.putString("key",value);

    mapView.onCreate(args);

?


问:
What is the difference between forEachAsync vs forEachPartitionAsync in Apache Spark?
What is the difference between forEachAsync vs forEachPartitionAsync?

If I were to guess here is  I would say the following but please correct me if I am wrong.forEachAsync just iterate through values from all partitions one by one in an Async Manner

forEachPartitionAsync: Fan out each partition and run the lambda for each partition in parallel across different workers. The lambda here will Iterate through values from that partition one by one in Async manner

but wait, rdd operations should infact execute in parallel right? so if I call rdd.forEachAsync that should execute in parallel too isn't it? I guess I am a little confused what the difference really is now between forEachAsync vs forEachPartitionAsync? besides passing in Tuple vs  Iterator of Tuples to the lambda respectively.

答:
I believe you are already aware of the fact of Async, and asking for the difference between forEach and forEachPartition,

And the difference is, ForEachPartition will allow you to run per partition custom code which you can't do with ForEach.

For Example, You want to save your result to database. Now as you know that opening closing DB connections are costly, one connection(or pool) per executor will be best. So you code would be

```<code>rdd.forEachPartition(part => {
    db= mysql..blablabla
    part.forEach(record=> {
    db.save(record)
   })
   db.close()
})
</code>```

You can't do this in ForEach, in foreach it will iterate for each record.

Remember, One partition will always run on one executor. So if you have any costly pre-work to do before start processing the data use forEachParition. If not just use forEach. Both are parallel. One gives you flexibility other gives simplicity.

Body:
I believe you are already aware of the fact of Async, and asking for the difference between forEach and forEachPartition,

And the difference is, ForEachPartition will allow you to run per partition custom code which you can't do with ForEach.

For Example, You want to save your result to database. Now as you know that opening closing DB connections are costly, one connection(or pool) per executor will be best. So you code would be

rdd.forEachPartition(part => {
    db= mysql..blablabla
    part.forEach(record=> {
    db.save(record)
   })
   db.close()
})

You can't do this in ForEach, in foreach it will iterate for each record.

Remember, One partition will always run on one executor. So if you have any costly pre-work to do before start processing the data use forEachParition. If not just use forEach. Both are parallel. One gives you flexibility other gives simplicity.


问:
Meteor/Angular2 Application freeze when loading 2nd Component
I got a Problem with my Meteor/Angular2 application. I got a start Component (AppComponent) and I can load this just fine everything works as I want. But now I added the tag 'map' to my AppComponent template and created the component MapComponent. Now everytime i try to open the application (on localhost:3000) the App freezes and crashes. I can't open the developer tool nothing.

Here i send you my Files:
app.module.ts:

```<code>import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { AppComponent } from "./app.component";
import { MapComponent } from './map/map.component';

@NgModule({
  // Components, Pipes, Directive
  declarations: [
    AppComponent,
    MapComponent

  ],
  // Providers
  providers: [],
  // Modules
  imports: [
    BrowserModule
  ],
  // Main Component
  bootstrap: [AppComponent]
})
export class AppModule {
}
</code>```

app.component.ts

```<code>import { Component } from "@angular/core";
import template from "./app.component.html";
import style from "./app.component.scss";

@Component({
  selector: "app",
  template: `<nav class="navbar">Navbar</nav>
<div class="mapbox">
    <map></map>
</div>
<footer class="footer">Footer</footer>`,
  styles: [ style ]
})
export class AppComponent {
}
</code>```

map.component.ts

```<code>import { Component } from '@angular/core';
@Component({
    selector: 'map',
    template: `<div class="container">
    Test
</div>`,
    styleUrls: ['../app.component.scss']
})
export class MapComponent {

}
</code>```

I hope you can help me.
Thanks in advance
Tim

答:
When you use styleUrls from Angular (instead of import style from './path/to/stylesheet' from angular2-meteor), remember that:

The URL is relative to the application root, which is usually the location of the index.html web page that hosts the application. The style file URL is not relative to the component file.

Reference: https://angular.io/docs/ts/latest/guide/component-styles.html#!#style-urls-in-metadata

Therefore in your case, you would write in your map.component.ts file:

import { Component } from '@angular/core';
@Component({
    selector: 'map',
    template: `

    Test

`,
    styleUrls: ['app/app.component.scss'] // From location of index.html
})
export class MapComponent {}
```

<p>Demo: https://plnkr.co/edit/K0NW0g8UVRI1EsyRMIe6?p=preview</p>

<hr>

<p>There is however a way to request Angular to use relative path.</p>

<blockquote>
  <p>You can use a relative URL by prefixing your filenames with <code>./</code>:</p>
</blockquote>

<pre class="lang-ts prettyprint-override"><code>import { Component } from '@angular/core';
@Component({
    selector: 'map',
    template: `<div class="container">
    Test
</div>`,
    styleUrls: ['./../app.component.scss'] // From location of map.component.ts
})
export class MapComponent {}
</code>```

Demo2: https://plnkr.co/edit/5x0qFBii2VIQOCtpxLfL?p=preview

Note: you must start with ./, not directly ../, otherwise Angular still uses absolute path URL.

That being said, if you use that code within Meteor, all your files will be bundled during compilation, and you cannot use the Angular way of lazily loading external files (whether HTML or stylesheets).

Therefore you should either write those inline, or use the angular2-meteor importing recommended way, i.e.:

import { Component } from '@angular/core';
import style from '../app.component.scss';
@Component({
    selector: 'map',
    template: `

    Test

`,
    styles: [style]
})
export class MapComponent {}
```

Body:
I got a Problem with my Meteor/Angular2 application. I got a start Component (AppComponent) and I can load this just fine everything works as I want. But now I added the tag 'map' to my AppComponent template and created the component MapComponent. Now everytime i try to open the application (on localhost:3000) the App freezes and crashes. I can't open the developer tool nothing.

Here i send you my Files:
app.module.ts:

import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { AppComponent } from "./app.component";
import { MapComponent } from './map/map.component';

@NgModule({
  // Components, Pipes, Directive
  declarations: [
    AppComponent,
    MapComponent

  ],
  // Providers
  providers: [],
  // Modules
  imports: [
    BrowserModule
  ],
  // Main Component
  bootstrap: [AppComponent]
})
export class AppModule {
}

app.component.ts

import { Component } from "@angular/core";
import template from "./app.component.html";
import style from "./app.component.scss";

@Component({
  selector: "app",
  template: `Navbar

    <map></map>

Footer`,
  styles: [ style ]
})
export class AppComponent {
}

map.component.ts

import { Component } from '@angular/core';
@Component({
    selector: 'map',
    template: `

    Test

`,
    styleUrls: ['../app.component.scss']
})
export class MapComponent {

}

I hope you can help me.
Thanks in advance
Tim

Body:
When you use styleUrls from Angular (instead of import style from './path/to/stylesheet' from angular2-meteor), remember that:

The URL is relative to the application root, which is usually the location of the index.html web page that hosts the application. The style file URL is not relative to the component file.

Reference: https://angular.io/docs/ts/latest/guide/component-styles.html#!#style-urls-in-metadata

Therefore in your case, you would write in your map.component.ts file:

import { Component } from '@angular/core';
@Component({
    selector: 'map',
    template: `<div class="container">
    Test
</div>`,
    styleUrls: ['app/app.component.scss'] // From location of index.html
})
export class MapComponent {}

Demo: https://plnkr.co/edit/K0NW0g8UVRI1EsyRMIe6?p=preview

There is however a way to request Angular to use relative path.

You can use a relative URL by prefixing your filenames with ./:

import { Component } from '@angular/core';
@Component({
    selector: 'map',
    template: `<div class="container">
    Test
</div>`,
    styleUrls: ['./../app.component.scss'] // From location of map.component.ts
})
export class MapComponent {}

Demo2: https://plnkr.co/edit/5x0qFBii2VIQOCtpxLfL?p=preview

Note: you must start with ./, not directly ../, otherwise Angular still uses absolute path URL.

That being said, if you use that code within Meteor, all your files will be bundled during compilation, and you cannot use the Angular way of lazily loading external files (whether HTML or stylesheets).

Therefore you should either write those inline, or use the angular2-meteor importing recommended way, i.e.:

import { Component } from '@angular/core';
import style from '../app.component.scss';
@Component({
    selector: 'map',
    template: `<div class="container">
    Test
</div>`,
    styles: [style]
})
export class MapComponent {}


问:
delayed_job and method from the helper
I have problem in my application with using helpers in email templates. In my application I have implemented "money-rails" to handle payment in other currencies.I have the following helper:

```<code>module CurrencyHelper

  # overriding std rails helper to use 'money' gem methods
  def number_to_currency(money, options = {})
    return '-' unless money
    currency = options.fetch(:currency, current_currency)
    date = options.fetch(:date, nil)
    should_reload = if date && !money.currency.eql?(currency)
                      ExchangeRatesManager.new(date: date).call
                    end

    money_in_currency = money.exchange_to(currency)
    ExchangeRatesManager.new.call if should_reload # should rollback to current exchange rates

    humanized_money_with_symbol(money_in_currency)
  end

end
</code>```

And now I use it in my email mailers templates. When I send mail not through delayed_job everything is ok:

```<code>UserMailer.reservation_confirmation_link(@reservation).deliver
</code>```

but when I send email through delayed_job:
RentalOfficeMailer.delay.reservation_summary(@reservation) it not load this overwrited number_to_currency method and it not shows me proper currency.
Thank's in advance for any help.

答:
I had the same problem where helpers are not loading in background, I solved this by calling helper method this way, in your case u can do:</p>

```<code>Class.new.extend(CurrencyHelper).number_to_currency(money, {})
</code>```

Title: delayed_job and method from the helper

Body:
I have problem in my application with using helpers in email templates. In my application I have implemented "money-rails" to handle payment in other currencies.I have the following helper:

module CurrencyHelper

  # overriding std rails helper to use 'money' gem methods
  def number_to_currency(money, options = {})
    return '-' unless money
    currency = options.fetch(:currency, current_currency)
    date = options.fetch(:date, nil)
    should_reload = if date && !money.currency.eql?(currency)
                      ExchangeRatesManager.new(date: date).call
                    end

    money_in_currency = money.exchange_to(currency)
    ExchangeRatesManager.new.call if should_reload # should rollback to current exchange rates

    humanized_money_with_symbol(money_in_currency)
  end

end

And now I use it in my email mailers templates. When I send mail not through delayed_job everything is ok:

UserMailer.reservation_confirmation_link(@reservation).deliver

but when I send email through delayed_job:
RentalOfficeMailer.delay.reservation_summary(@reservation) it not load this overwrited number_to_currency method and it not shows me proper currency.
Thank's in advance for any help.

Body:
I had the same problem where helpers are not loading in background, I solved this by calling helper method this way, in your case u can do:

Class.new.extend(CurrencyHelper).number_to_currency(money, {})


问:
c# Assembly.LoadFrom with dynamic AssemblyResolve
I'm kind of stuck with dynamically loading plugins:

Theory: (Plugin) Dlls in a specific folder:

```<code>foreach(string path in Directory.GetFiles(...))
{
    Assembly myPlugin = Assembly.LoadFrom(path);
    foreach(Type type in myPlugin.GetTypes().Where(t => typeof(myPluginBaseClass).isAssignableFrom(t)))
    {
        Activator.CreateInstance(type);
    }
}
</code>```

So far so good.
Now there are issues with additional references in those assemblies, which can be solved by catch(ReflectionTypeLoadException) (to removed all null Types) and AppDomain.CurrentDomain.AssemblyResolve += ... (to manually look for those missing dlls)

Now here is the issue: The referenced missing assemblies are specific for each implemented Plugin, so I need a individual search behavior implemented in each Plugin. My ideas / solutions so far:

Having a global list of all possible DLL directories in my main application -> stupid because this won't allow to add further plugins without changing the main application code

Having a (non static) dictionary of specific dll paths in each plugin -> can be forced by the myPluginBaseClass using virtual/abstract; But can't be accessed before creation of the instance (where those AssemblyResolveEvents are fired), so not helpful

Having a (static) dictionary of specific dll paths in each plugin -> can be read before instantiation by using Reflection, but I can't add this to my myPluginBaseClass as a defined template, so errors possible

Creating a individual Domain for each plugin and let them handle their own AssemblyResolveEvent -> But how?

I hope you can help!

Thanks in advance!
Robin

答:
Create domain seems to be adequat solution for plugin pattern.

You don't really need to define AssemblyResolve, you can simply configure the directory where AppDomain can find dependencies.

https://msdn.microsoft.com/fr-fr/library/system.appdomainsetup.applicationbase(v=vs.110).aspx

Body:
I'm kind of stuck with dynamically loading plugins:

Theory: (Plugin) Dlls in a specific folder:

foreach(string path in Directory.GetFiles(...))
{
    Assembly myPlugin = Assembly.LoadFrom(path);
    foreach(Type type in myPlugin.GetTypes().Where(t => typeof(myPluginBaseClass).isAssignableFrom(t)))
    {
        Activator.CreateInstance(type);
    }
}

So far so good.
Now there are issues with additional references in those assemblies, which can be solved by catch(ReflectionTypeLoadException) (to removed all null Types) and AppDomain.CurrentDomain.AssemblyResolve += ... (to manually look for those missing dlls)

Now here is the issue: The referenced missing assemblies are specific for each implemented Plugin, so I need a individual search behavior implemented in each Plugin. My ideas / solutions so far:

Having a global list of all possible DLL directories in my main application -> stupid because this won't allow to add further plugins without changing the main application code

Having a (non static) dictionary of specific dll paths in each plugin -> can be forced by the myPluginBaseClass using virtual/abstract; But can't be accessed before creation of the instance (where those AssemblyResolveEvents are fired), so not helpful

Having a (static) dictionary of specific dll paths in each plugin -> can be read before instantiation by using Reflection, but I can't add this to my myPluginBaseClass as a defined template, so errors possible

Creating a individual Domain for each plugin and let them handle their own AssemblyResolveEvent -> But how?

I hope you can help!

Thanks in advance!
Robin


问:
Highlighting section(s) of surface
I have analytically verified that a local min of x^2+y^2-x*y lies at the point (1,1) on the condition x+y=2. Using wxMaxima, can plot the surface

```<code>plot3d(x^2+y^2-x*y, [x,-2,2],[y,-2,2],[grid, 100,100], [mesh_lines_color,false]);
</code>```

What I would like to do now is highlight all the points z on the surface that satisfy the condition x+y=2. In other words, I'd like to highlight the section of the surface given by the condition. How do I achieve this?

答:
Since your question is tagged with gnuplot, here is a way how one could do that in Gnuplot using a parametric plot:

```<code>set terminal pngcairo
set output 'fig.png'

unset key

set isosamples 40
set parametric

set ur [-2:2]
set vr [-2:2]
set zr [0:12]

set xr [-2:2]
set yr [-2:2]

fn(u) = 2-u

splot \
    u,v,u**2 + v**2 - u*v, \
    u,fn(u),u**2 + fn(u)**2 - u*fn(u) w l lc rgb 'red'
</code>```

The output is then:

Title: Highlighting section(s) of surface

Body:
I have analytically verified that a local min of x^2+y^2-x*y lies at the point (1,1) on the condition x+y=2. Using wxMaxima, can plot the surface

plot3d(x^2+y^2-x*y, [x,-2,2],[y,-2,2],[grid, 100,100], [mesh_lines_color,false]);

What I would like to do now is highlight all the points z on the surface that satisfy the condition x+y=2. In other words, I'd like to highlight the section of the surface given by the condition. How do I achieve this?

Body:
Since your question is tagged with gnuplot, here is a way how one could do that in Gnuplot using a parametric plot:

set terminal pngcairo
set output 'fig.png'

unset key

set isosamples 40
set parametric

set ur [-2:2]
set vr [-2:2]
set zr [0:12]

set xr [-2:2]
set yr [-2:2]

fn(u) = 2-u

splot \
    u,v,u**2 + v**2 - u*v, \
    u,fn(u),u**2 + fn(u)**2 - u*fn(u) w l lc rgb 'red'

The output is then:


问:
how to escape form filtering for certain fields using codeigniter
I am using codeigniter form validation and i have set some rules for my form fields. When i type %50 or %test% , I don't get the rest of the texts posted  after the first occurrence of % character.
Please help how to solve this. </p>

答:
Codeigniter validation library for v3.1.4. Click here

Also use second parameter "true" for input filter:

```<code>$this->input->post('data', true);

$this->input->get('data', true);
</code>```

Body:
Codeigniter validation library for v3.1.4. Click here

Also use second parameter "true" for input filter:

$this->input->post('data', true);

$this->input->get('data', true);


问:
android studio 2.3 instant run not working
I have updated android studio from 2.2 to 2.3,then I found Instant run not working.

Error while executing: am startservice com.example.codingmaster.testcc/com.android.tools.fd.runtime.InstantRunService
      Starting service: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.example.codingmaster.testcc/com.android.tools.fd.runtime.InstantRunService }
      Error: Not found; no service started.

I also try reinstall android studio 2.3 but not work.

答:
Goto File-settings, "Build, Execution, Deployment"

click on instantRun

Uncheck Enable instant run Checkbox

then apply and ok will solve your problem


问:
How can I move all files and directories from disk to the folder on this disk?
I have disk D with the files and directories. I want to move all files and directories including the root of disk D to the new folder saving the tree.

For example, I have file D:\1.txt. I want to move it to D:\new_folder\1.txt

The second example. I have file D:\1\1\1.txt. I want to move it to D:\new_folder\1\1\1.txt

As you can see, I want to move all contents of disk D to the folder  D:\new_folder\.

I tried robocopy, but it can't move from root of disk.

答:
Why not simply using the robocopy command?

robocopy "D:\." "D:\new_folder" /E /MOVE /XD "D:\new_folder"
```

Note that you cannot specify the root "D:\", because the backslash escapes the closing quotation mark. To work around that, specify either "D:\." or "D:\\", which actually point to D:\ both.

Body:
Why not simply using the robocopy command?

robocopy "D:\." "D:\new_folder" /E /MOVE /XD "D:\new_folder"

Note that you cannot specify the root "D:\", because the backslash escapes the closing quotation mark. To work around that, specify either "D:\." or "D:\\", which actually point to D:\ both.


问:
Best way to change UIViewController view NIB programmatically
I have this iPad application with different NIBs and views.
Each view has two NIBs, one for potrait orientation and one for landscape, so i'm searching for a method to programmatically switch NIB for a given UIViewController .

Right now i have this function that i'm using in the willRotateToInterfaceOrientation method of each controller :

```<code>void UIHandleRotation( UIViewController *controller, NSString *nibName, UIInterfaceOrientation orientation, BOOL transform ){
    double angle = 0.0;

    if( orientation == UIInterfaceOrientationPortrait ) {
        angle = PI * 2 /* 360° */;
    }
    else if( orientation == UIInterfaceOrientationLandscapeLeft ){
        angle   = PI + PI/2 /* 270 ° */;
        // Each landscape nib is [nib-name]L
        nibName = [NSString stringWithFormat:@"%@L", nibName];
    }

    [[NSBundle mainBundle] loadNibNamed:nibName owner:controller options:nil];
    if( transform ) {
        controller.view.transform = CGAffineTransformMakeRotation( angle );
    }
}
</code>```

But it's giving me strange behaviour (ui controls position messed, the outlets are not associated as in interface builder, and so forth).

Am i doing something wrong or there's just a better way to implement this ?
Thanks

NOTE: I'm not using a navigation controller, so i can't use this solution Easiest way to support multiple orientations? How do I load a custom NIB when the application is in Landscape?

答: you need to have one view per nib, so your UIViewController will have two UIViews. one for portrait, and one for landscape.</p>

Body:
I have this iPad application with different NIBs and views.
Each view has two NIBs, one for potrait orientation and one for landscape, so i'm searching for a method to programmatically switch NIB for a given UIViewController .

Right now i have this function that i'm using in the willRotateToInterfaceOrientation method of each controller :

void UIHandleRotation( UIViewController *controller, NSString *nibName, UIInterfaceOrientation orientation, BOOL transform ){
    double angle = 0.0;

    if( orientation == UIInterfaceOrientationPortrait ) {
        angle = PI * 2 /* 360° */;
    }
    else if( orientation == UIInterfaceOrientationLandscapeLeft ){
        angle   = PI + PI/2 /* 270 ° */;
        // Each landscape nib is [nib-name]L
        nibName = [NSString stringWithFormat:@"%@L", nibName];
    }

    [[NSBundle mainBundle] loadNibNamed:nibName owner:controller options:nil];
    if( transform ) {
        controller.view.transform = CGAffineTransformMakeRotation( angle );
    }
}

But it's giving me strange behaviour (ui controls position messed, the outlets are not associated as in interface builder, and so forth).

Am i doing something wrong or there's just a better way to implement this ?
Thanks

NOTE: I'm not using a navigation controller, so i can't use this solution Easiest way to support multiple orientations? How do I load a custom NIB when the application is in Landscape?


问:
PHPMailer ERROR USING GMAIL: Mailer Error: SMTP connect()
I tried to send email from my localhost using my gmail account.
I also tried to find answers in the web and even in this website but nothing helped me. I am using XAMPP.

This is the code:

```<code>require 'PHPMailer-master/PHPMailerAutoload.php';

$mail = new PHPMailer();         // create a new object
$mail->IsSMTP();                 // enable SMTP
$mail->SMTPDebug = 2;            // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true;          // authentication enabled
$mail->SMTPSecure = 'ssl';       // secure transfer enabled REQUIRED for Gmail
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;               // or 587
$mail->IsHTML(true);
$mail->Username = "myUser@gmail.com";
$mail->Password = "myUserPass";
$mail->SetFrom("myUser@gmail.com");
$mail->Subject = "Test";
$mail->Body = "hello";
$mail->AddAddress("OtherUser@gmail.com");

if(!$mail->Send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message has been sent";
}
</code>```

The full error which I got:

2017-04-03 10:33:15   SERVER -> CLIENT: 220 smtp.gmail.com ESMTP
  p7sm17594308wrc.19 - gsmtp 2017-04-03 10:33:15    CLIENT -> SERVER: EHLO
  localhost 2017-04-03 10:33:15 SERVER -> CLIENT: 250-smtp.gmail.com at
  your service, [46.117.89.127] 250-SIZE 35882577 250-8BITMIME 250-AUTH
  LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
  250-ENHANCEDSTATUSCODES 250-PIPELINING 250-CHUNKING 250 SMTPUTF8
  2017-04-03 10:33:15   CLIENT -> SERVER: AUTH LOGIN 2017-04-03
  10:33:15  SERVER -> CLIENT: 334 VXNlcm5hbWU6 2017-04-03 10:33:15  CLIENT
  -> SERVER: bXlVc2VyQGdtYWlsLmNvbQ== 2017-04-03 10:33:15   SERVER -> CLIENT: 334 UGFzc3dvcmQ6 2017-04-03 10:33:15  CLIENT -> SERVER:
  bXlVc2VyUGFzcw== 2017-04-03 10:33:15  SERVER -> CLIENT: 535-5.7.8
  Username and Password not accepted. Learn more at 535 5.7.8
  https://support.google.com/mail/?p=BadCredentials p7sm17594308wrc.19 -
  gsmtp 2017-04-03 10:33:15 SMTP ERROR: Password command failed:
  535-5.7.8 Username and Password not accepted. Learn more at 535 5.7.8
  https://support.google.com/mail/?p=BadCredentials p7sm17594308wrc.19 -
  gsmtp 2017-04-03 10:33:15 SMTP Error: Could not authenticate.
  2017-04-03 10:33:15   CLIENT -> SERVER: QUIT 2017-04-03 10:33:16  SERVER
  -> CLIENT: 221 2.0.0 closing connection p7sm17594308wrc.19 - gsmtp 2017-04-03 10:33:16    SMTP connect() failed.
  https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting Mailer
  Error: SMTP connect() failed.
  https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

I tried to delete that:

```<code>$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
</code>```

Or changing the port to 25/587 but it did not help.
Does someone know how to fix that?

答:
Assuming that your username and password entered is correct, you need to authorize the external application use of gmail.

Follow the next steps and authorize to make it:

First, go to your Google Account Management page

Under the Connected apps & sites, click Allow less secure apps: ON

In case it does not work, if your gmail account has 2-step verification enabled, use an auto-generated password.

Update:

Although turning Allow less secure apps: ON might solve your problem, it should be taken as a troubleshooting tip and not as the final solution.

Body:
I tried to send email from my localhost using my gmail account.
I also tried to find answers in the web and even in this website but nothing helped me. I am using XAMPP.

This is the code:

require 'PHPMailer-master/PHPMailerAutoload.php';

$mail = new PHPMailer();         // create a new object
$mail->IsSMTP();                 // enable SMTP
$mail->SMTPDebug = 2;            // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true;          // authentication enabled
$mail->SMTPSecure = 'ssl';       // secure transfer enabled REQUIRED for Gmail
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;               // or 587
$mail->IsHTML(true);
$mail->Username = "myUser@gmail.com";
$mail->Password = "myUserPass";
$mail->SetFrom("myUser@gmail.com");
$mail->Subject = "Test";
$mail->Body = "hello";
$mail->AddAddress("OtherUser@gmail.com");

if(!$mail->Send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
} else {
    echo "Message has been sent";
}

The full error which I got:

2017-04-03 10:33:15   SERVER -> CLIENT: 220 smtp.gmail.com ESMTP
  p7sm17594308wrc.19 - gsmtp 2017-04-03 10:33:15    CLIENT -> SERVER: EHLO
  localhost 2017-04-03 10:33:15 SERVER -> CLIENT: 250-smtp.gmail.com at
  your service, [46.117.89.127] 250-SIZE 35882577 250-8BITMIME 250-AUTH
  LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
  250-ENHANCEDSTATUSCODES 250-PIPELINING 250-CHUNKING 250 SMTPUTF8
  2017-04-03 10:33:15   CLIENT -> SERVER: AUTH LOGIN 2017-04-03
  10:33:15  SERVER -> CLIENT: 334 VXNlcm5hbWU6 2017-04-03 10:33:15  CLIENT
  -> SERVER: bXlVc2VyQGdtYWlsLmNvbQ== 2017-04-03 10:33:15   SERVER -> CLIENT: 334 UGFzc3dvcmQ6 2017-04-03 10:33:15  CLIENT -> SERVER:
  bXlVc2VyUGFzcw== 2017-04-03 10:33:15  SERVER -> CLIENT: 535-5.7.8
  Username and Password not accepted. Learn more at 535 5.7.8
  https://support.google.com/mail/?p=BadCredentials p7sm17594308wrc.19 -
  gsmtp 2017-04-03 10:33:15 SMTP ERROR: Password command failed:
  535-5.7.8 Username and Password not accepted. Learn more at 535 5.7.8
  https://support.google.com/mail/?p=BadCredentials p7sm17594308wrc.19 -
  gsmtp 2017-04-03 10:33:15 SMTP Error: Could not authenticate.
  2017-04-03 10:33:15   CLIENT -> SERVER: QUIT 2017-04-03 10:33:16  SERVER
  -> CLIENT: 221 2.0.0 closing connection p7sm17594308wrc.19 - gsmtp 2017-04-03 10:33:16    SMTP connect() failed.
  https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting Mailer
  Error: SMTP connect() failed.
  https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting

I tried to delete that:

$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail

Or changing the port to 25/587 but it did not help.
Does someone know how to fix that?


问:
visualize line-break and paragraph break with symbols in html similar to word
Is it anyhow possible to visualize line break and paragraph breaks symbols in html, like in word?

答:
As far as I know, the answer is yes and no for CSS only, yes for CSS & JavaScript.

For the end of the paragraph, the ::after selector comes to the rescue:

p::after {
  content: "¶";
  color: #6495ED;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>This is a pragraph.</p>
<p>Here goes another paragraph.</p></code>```

However, this does not reliably work on
, unless you want to use JavaScript (see below).

Check these questions for further details on the issue:

"Can you target
 with css?"

"Line break (like
) using only css"

CSS only (not cross browser compatible)

This CSS only solution works for me on the following browsers (Windows 10):

Chrome 56 and Opera 43. It does not work on Firefox 51, IE 11 or Edge 38.

br {
  content: " ";
}

br::after {
  content: "↵\a";
  white-space: pre;
  color: #6495ED;
}

p::after {
  content: "¶";
  color: #6495ED;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>This is a pragraph with two sentences.<br>This is the second sentence, it follows a line break.</p>
<p>Here goes another paragraph.</p></code>```

CSS & JavaScript solution (cross browser)

If you are okay with using JavaScript, here is my vanilla approach.

Disclaimer: I'm not experienced with JS, maybe there is a better way.

For me, this works with all of the browsers mentioned above.

var spanbr = document.createElement("span");
spanbr.className = "br";

var brs = document.getElementsByTagName("br");

for (var i = 0; i < brs.length; ++i) {
  brs[i].parentElement.insertBefore(spanbr, brs[i]);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.br::after {
  content: "↵";
  color: #6495ED;
}

p::after {
  content: "¶";
  color: #6495ED;
}</code>```

This is a pragraph with two sentences.
This is the second sentence, it follows a line break.

Here goes another paragraph.
```

Body:
As far as I know, the answer is yes and no for CSS only, yes for CSS & JavaScript.

For the end of the paragraph, the ::after selector comes to the rescue:

p::after {
  content: "¶";
  color: #6495ED;
}

<p>This is a pragraph.</p>
<p>Here goes another paragraph.</p>

However, this does not reliably work on <br>, unless you want to use JavaScript (see below).

Check these questions for further details on the issue:

"Can you target <br \> with css?"

"Line break (like <br>) using only css"

CSS only (not cross browser compatible)

This CSS only solution works for me on the following browsers (Windows 10):

Chrome 56 and Opera 43. It does not work on Firefox 51, IE 11 or Edge 38.

br {
  content: " ";
}

br::after {
  content: "↵\a";
  white-space: pre;
  color: #6495ED;
}

p::after {
  content: "¶";
  color: #6495ED;
}

<p>This is a pragraph with two sentences.<br>This is the second sentence, it follows a line break.</p>
<p>Here goes another paragraph.</p>

CSS & JavaScript solution (cross browser)

If you are okay with using JavaScript, here is my vanilla approach.

Disclaimer: I'm not experienced with JS, maybe there is a better way.

For me, this works with all of the browsers mentioned above.

var spanbr = document.createElement("span");
spanbr.className = "br";

var brs = document.getElementsByTagName("br");

for (var i = 0; i < brs.length; ++i) {
  brs[i].parentElement.insertBefore(spanbr, brs[i]);
}

.br::after {
  content: "↵";
  color: #6495ED;
}

p::after {
  content: "¶";
  color: #6495ED;
}

<p>This is a pragraph with two sentences.<br>This is the second sentence, it follows a line break.</p>
<p>Here goes another paragraph.</p>


问:
Mapping through an array of objects in javascript
i have an array of objects like this:

```<code>[{side: Buy, price: 100}, {side: Buy, price: 110}, {side: Sell, price: 200}, {side: Buy, price: 150} ]
</code>```

Now i want to calculate for this array the total sum of the Buy and Sell side and for each side the average sum of the prices. To be more specific i want my output to be something like this:
Buy = 3  AvgPrice for Buy = 120
Sell = 1 AvgPrice for Sell = 200
I'm new to javascript and react so i have some difficulties. Thanks !:)

答:
You can do it like this: </p>

```<code>let arr = [{side: "Buy", price: 100}, {side: "Buy", price: 110}, {side:     "Sell", price: 200}, {side: "Buy", price: 150} ];
let buyPrices = [];
let sellPrices = [];
arr.forEach((item, index) => {
  if (item.side === 'Buy') {
    buyPrices.push(item.price);
  } else if (item.side === 'Sell') {
    sellPrices.push(item.price);
  }
});

let avgBuy = buyPrices.reduce((a, b) => a + b)/buyPrices.length;
console.log(`Buy -> ${buyPrices.length}
AvgBuyPrices -> ${avgBuy}`);
let avgSell = sellPrices.reduce((a, b) => a + b)/sellPrices.length;
console.log(`Sell -> ${sellPrices.length}
AvgSellPrices -> ${avgSell}`);
</code>```

Body:
i have an array of objects like this:

[{side: Buy, price: 100}, {side: Buy, price: 110}, {side: Sell, price: 200}, {side: Buy, price: 150} ]

Now i want to calculate for this array the total sum of the Buy and Sell side and for each side the average sum of the prices. To be more specific i want my output to be something like this:
Buy = 3  AvgPrice for Buy = 120
Sell = 1 AvgPrice for Sell = 200
I'm new to javascript and react so i have some difficulties. Thanks !:)

Body:
You can do it like this:

let arr = [{side: "Buy", price: 100}, {side: "Buy", price: 110}, {side:     "Sell", price: 200}, {side: "Buy", price: 150} ];
let buyPrices = [];
let sellPrices = [];
arr.forEach((item, index) => {
  if (item.side === 'Buy') {
    buyPrices.push(item.price);
  } else if (item.side === 'Sell') {
    sellPrices.push(item.price);
  }
});

let avgBuy = buyPrices.reduce((a, b) => a + b)/buyPrices.length;
console.log(`Buy -> ${buyPrices.length}
AvgBuyPrices -> ${avgBuy}`);
let avgSell = sellPrices.reduce((a, b) => a + b)/sellPrices.length;
console.log(`Sell -> ${sellPrices.length}
AvgSellPrices -> ${avgSell}`);


问:
How to print 0 to 9 digits without using any digit in our code?
Recently, I found a problem on hackerearth that is how to print 726 without any digits. This is the link to question :https://www.hackerearth.com/challenge/college/r1/golf/726/

I have solved this with this:

```<code>#include <stdio.h>
main()
{
    printf("%d",('\e'*'\e')-('\r'-'\n'));

}
</code>```

but since I found this question interesting, I would love to print every single digit without use of any digit. So, I want to print 0 to 9 all in a new line without using any digit with the help of unicodes. How could I do that?

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

#define ZERO ('a' - 'a')
#define ONE ((int)(sizeof (char)))
#define TWO (ONE + ONE)
#define THREE (TWO + ONE)
#define SIX (TWO * THREE)
#define SEVEN (SIX + ONE)

int main(void) {
    printf("%d%d%d\n", SEVEN, TWO, SIX);
    /* Assume C99 and implicit return 0; */
}
</code>```

Body:
Recently, I found a problem on hackerearth that is how to print 726 without any digits. This is the link to question :https://www.hackerearth.com/challenge/college/r1/golf/726/

I have solved this with this:

#include <stdio.h>
main()
{
    printf("%d",('\e'*'\e')-('\r'-'\n'));

}

but since I found this question interesting, I would love to print every single digit without use of any digit. So, I want to print 0 to 9 all in a new line without using any digit with the help of unicodes. How could I do that?


问:
Windows 10 exe file's imagebase doesn't change
I am a student who studies reverse engineering. After I studied ASLR on Windows, I was going to check it. following capture:

the image base of notepad are same on first and second time. Whenever I restart notepad on ollydbg, imagebase is same. I checked ASLR attributes on file via PEView and registry value on Windows 10 too. they are normal. is there any reason not be changed imagebase of notepad ?

答:
Base address will change on PC's restart. It will not change on app's restart.

Writing Secure Code for Windows Vista by Michael Howard - Senior Security Program Manager at Microsoft


问:
Compilation errors in simple Java program with Scanner
```<code>import java.util.*;
public class strings {
    public static void main (String [] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = keyboard.next();
        System.out.print("Type your seconds integer : ");
        int second = keyboard.next();
        System.out.print("The sum of your two integers are:");
    }
}
</code>```

<p>I dont know why im getting 2 errors on strings cannot converted to int. </p>

答: keyboard.next() will return the next complete token from the scanner ,i think of string type so it needs to be typecast to integer and better option is to use keyboard.nextInt() method to take the integer input .</p>

Body:
import java.util.*;
public class strings {
    public static void main (String [] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = keyboard.next();
        System.out.print("Type your seconds integer : ");
        int second = keyboard.next();
        System.out.print("The sum of your two integers are:");
    }
}

I dont know why im getting 2 errors on strings cannot converted to int.


问:
Using labels in Alertmanager webhook
My alert configure as follows.

```<code>ALERT PoDHighCPUUsage
  IF sum(rate(container_cpu_usage_seconds_total{container_label_io_kubernetes_pod_namespace!=""}[2m])) BY (kubernetes_pod_name, kubernetes_io_hostname, container_label_io_kubernetes_pod_namespace) >= 0.2
  FOR 2m
  LABELS {severity="criticalup"}
  ANNOTATIONS {summary="CPU usage of POD {{ $labels.kubernetes_pod_name }} {{ $labels.container_label_io_kubernetes_pod_namespace }} utilization is  >= 0.4 cores (current value: {{ $value }}%)"}
</code>```

My webhooks as follows ..

```<code>- name: 'email-n-webhookup'
  email_configs:
  - to: 'mail-id'
    send_resolved: true

  webhook_configs:
  - url: http://<webhook_ip>:9000/hooks/ose-webhook?in1={{.Labels.container_label_io_kubernetes_pod_namespace}}&in2={{.Labels.kubernetes_pod_name}}&in3=plus

- name: 'email-n-webhookdn'
  email_configs:
  - to: 'mail-id'
    send_resolved: true

  webhook_configs:
  - url: http://<webhook_ip>:9000/hooks/ose-webhook?in1=tomi&in2=chat&in3=minus
</code>```

I am not able to pass the value/data "labels.kubernetes_pod_name" & "labels.container_label_io_kubernetes_pod_namespace" in webhook_configs.

Statically it worked as per "email-n-webhookdn"

答: Not all fields are templatable, and the webhook URL is one of those. It's expected that the code receiving the webhook will look inside the json it receives in the POST to get all the alerts and their labels.</p>

Title: Using labels in Alertmanager webhook

Body:
My alert configure as follows.

ALERT PoDHighCPUUsage
  IF sum(rate(container_cpu_usage_seconds_total{container_label_io_kubernetes_pod_namespace!=""}[2m])) BY (kubernetes_pod_name, kubernetes_io_hostname, container_label_io_kubernetes_pod_namespace) >= 0.2
  FOR 2m
  LABELS {severity="criticalup"}
  ANNOTATIONS {summary="CPU usage of POD {{ $labels.kubernetes_pod_name }} {{ $labels.container_label_io_kubernetes_pod_namespace }} utilization is  >= 0.4 cores (current value: {{ $value }}%)"}

My webhooks as follows ..

- name: 'email-n-webhookup'
  email_configs:
  - to: 'mail-id'
    send_resolved: true

  webhook_configs:
  - url: http://<webhook_ip>:9000/hooks/ose-webhook?in1={{.Labels.container_label_io_kubernetes_pod_namespace}}&in2={{.Labels.kubernetes_pod_name}}&in3=plus

- name: 'email-n-webhookdn'
  email_configs:
  - to: 'mail-id'
    send_resolved: true

  webhook_configs:
  - url: http://<webhook_ip>:9000/hooks/ose-webhook?in1=tomi&in2=chat&in3=minus

I am not able to pass the value/data "labels.kubernetes_pod_name" & "labels.container_label_io_kubernetes_pod_namespace" in webhook_configs.

Statically it worked as per "email-n-webhookdn"


问:
C# class parameter
```<code> namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            B b = new B(a);
            C c = new C(a);

            Console.WriteLine(a.intval + " " +a.strval);
            Console.ReadLine();
        }
    }

    class A
    {
        public int intval { get; set; }
        public string strval { get; set; }
    }
    class B
    {
        public A _a;
        public B(A a)
        {
            _a = a;
            _a.intval += 100;
            _a.strval += "From B;";
        }
    }
    class C
    {
        A _a;
        public C(A a)
        {
            _a = a;
            _a.intval += 1000;
            _a.strval += "From C;";
        }
    }
}
</code>```

In above code, why the instance "b" and “c” could set value to instance "a"?

In my guess, the Class B and C have their own variables "a", when we call "B b = new B(a);" or "C c = new C(a);", the value should be changed on their own fields and the variable "a" in Main would be impacted?

But, i'm wrong. Could you please help me understand the result? Thank you very much.

答:
Your class A is a reference type, so any changes to any instance of an A object will be shared across all other references of that same object.

Think of your variables as addresses to a place like, say, a park. When you create an instance of a reference type like so:

```<code>Foo a = new Foo();
</code>```

then that is like writing the address to the park on a piece of paper. Then when you assign another variable to be equal to the first variable:

```<code>Foo b = a;
</code>```

That is essentially copying the address onto another piece of paper. You now have two pieces of paper that are pointing to the same place (the park).

Then if someone were to use one of the pieces of paper to go to the park and change it somehow (like, say, build a new fountain):

```<code>b.Bar = 5;
</code>```

that change would be reflected across all existing objects. Or in terms of the metaphor, anyone going to the park at that address would see the change:

```<code>Console.WriteLine(a.Bar);
// Console Output: 5
</code>```

So when you are doing what you are doing in your code:

```<code>A a = new A();
B b = new B(a);
C c = new C(a);
</code>```

Because A is a reference type, a, b._a, and c._a are all references to the same object. (They are all different pieces of paper, all with the same address to the same park.)

Title: C# class parameter

Body:
 namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            B b = new B(a);
            C c = new C(a);

            Console.WriteLine(a.intval + " " +a.strval);
            Console.ReadLine();
        }
    }

    class A
    {
        public int intval { get; set; }
        public string strval { get; set; }
    }
    class B
    {
        public A _a;
        public B(A a)
        {
            _a = a;
            _a.intval += 100;
            _a.strval += "From B;";
        }
    }
    class C
    {
        A _a;
        public C(A a)
        {
            _a = a;
            _a.intval += 1000;
            _a.strval += "From C;";
        }
    }
}

In above code, why the instance "b" and “c” could set value to instance "a"?

In my guess, the Class B and C have their own variables "a", when we call "B b = new B(a);" or "C c = new C(a);", the value should be changed on their own fields and the variable "a" in Main would be impacted?

But, i'm wrong. Could you please help me understand the result? Thank you very much.

Body:
Your class A is a reference type, so any changes to any instance of an A object will be shared across all other references of that same object.

Think of your variables as addresses to a place like, say, a park. When you create an instance of a reference type like so:

Foo a = new Foo();

then that is like writing the address to the park on a piece of paper. Then when you assign another variable to be equal to the first variable:

Foo b = a;

That is essentially copying the address onto another piece of paper. You now have two pieces of paper that are pointing to the same place (the park).

Then if someone were to use one of the pieces of paper to go to the park and change it somehow (like, say, build a new fountain):

b.Bar = 5;

that change would be reflected across all existing objects. Or in terms of the metaphor, anyone going to the park at that address would see the change:

Console.WriteLine(a.Bar);
// Console Output: 5

So when you are doing what you are doing in your code:

A a = new A();
B b = new B(a);
C c = new C(a);

Because A is a reference type, a, b._a, and c._a are all references to the same object. (They are all different pieces of paper, all with the same address to the same park.)


问:
Calling an action in ArticlesController, from CommentsController - Rails

The situation:

I have something like the following:

```<code>class Game < ActiveRecord::Base
   has_many :turns

   def calculate_score
      #return score of all turns played so far
   end
end

class Turn < ActiveRecord::Base
   belongs_to :game
end
</code>```

... with corresponding controllers. (this isn't exactly what I have, but my question is very general. The question title shows another similar situation)

When I am in /game/:id (the show action), I display all turns, and have AJAX edit-in-place to update any turns. Updating a turn calls the update method of TurnsController.

The question:

How can I, from TurnsController, call an action in the GameController after a turn is updated?

I need an action called "turn_updated" in GameController to check all turns and perform manipulations on the collection game.turns .

Thanks!

PS: Clearly I am new to Rails, so I can't be more specific because I am not exactly sure of how to phrase my question, or of what is possible.

Update:

Thanks for the answers so far.

I have been using a redirect_to, but my problem with that is that update is an AJAX call. It needs to render :text => @turn.value in some conditions, and redirect_to in others. Since it's an AJAX call, redirect_to replaces the div that showed the turn value with the entire contents of the new address.

I am trying things along these lines now:

```<code>#turn update action
def update
   url = url_for(:controller => 'games', :action => 'turn_updated', :id => @turn.game_id)
   render :partial => 'shared/redirect.js.erb', :locals => {:url => url}
end
</code>```

and the partial is:

```<code><script type="text/javascript">window.location.replace(<%= url %>);</script>
</code>```

I am getting closer with this, but it seems somewhat flimsy...
For instance, if I replace the partial's JS with alert("Works!"); it executes the alert, but the redirect doesn't always happen.

答:
In a controller, use a redirect:

```<code>def my_turn_action
  # ...
  redirect_to :controller => :game, :action => :turn_updated and return
end
</code>```

In a view (i.e., if you just want a link to a different controller):

```<code><%= link_to :controller => :game, :action => :turn_updated %>
</code>```

Body:
The situation:

I have something like the following:

class Game < ActiveRecord::Base
   has_many :turns

   def calculate_score
      #return score of all turns played so far
   end
end

class Turn < ActiveRecord::Base
   belongs_to :game
end

... with corresponding controllers. (this isn't exactly what I have, but my question is very general. The question title shows another similar situation)

When I am in /game/:id (the show action), I display all turns, and have AJAX edit-in-place to update any turns. Updating a turn calls the update method of TurnsController.

The question:

How can I, from TurnsController, call an action in the GameController after a turn is updated?

I need an action called "turn_updated" in GameController to check all turns and perform manipulations on the collection game.turns .

Thanks!

PS: Clearly I am new to Rails, so I can't be more specific because I am not exactly sure of how to phrase my question, or of what is possible.

Update:

Thanks for the answers so far.

I have been using a redirect_to, but my problem with that is that update is an AJAX call. It needs to render :text => @turn.value in some conditions, and redirect_to in others. Since it's an AJAX call, redirect_to replaces the div that showed the turn value with the entire contents of the new address.

I am trying things along these lines now:

#turn update action
def update
   url = url_for(:controller => 'games', :action => 'turn_updated', :id => @turn.game_id)
   render :partial => 'shared/redirect.js.erb', :locals => {:url => url}
end

and the partial is:

I am getting closer with this, but it seems somewhat flimsy...
For instance, if I replace the partial's JS with alert("Works!"); it executes the alert, but the redirect doesn't always happen.

Body:
In a controller, use a redirect:

def my_turn_action
  # ...
  redirect_to :controller => :game, :action => :turn_updated and return
end

In a view (i.e., if you just want a link to a different controller):

<%= link_to :controller => :game, :action => :turn_updated %>


问:
Updating views within a single row of a ListView when clicked
I was wondering how to update views/UI (say, making a TextView invisible) within a single row of a ListView when clicking on the row because every other rows' views would be affected as well. A good example would be playing a song in Google Play Music, and the equalizer animation would be displayed accordingly. Here are my snippets:

MainActivity's onCreate():

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); // Renders only a ListView

    ListView songListView = (ListView) findViewById(R.id.list);
    List<Song> songList = new ArrayList<>();
    for (int i = 1; i <= 200; i++) songList.add(new Song("Song" + i, "Artist" + i));
    SongAdapter songAdapter = new SongAdapter(this, songList);
    songListView.setAdapter(songAdapter);
    songListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
            if (position == view.getId()) {
                TextView titleText = (TextView) view.findViewById(R.id.song_title);
                titleText.setVisibility(View.INVISIBLE);
            }
        }
    });
}
</code>```

... and my ArrayAdapter's getView method and ViewHolder class:

```<code>@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;

    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent,
                false);

        holder = new ViewHolder();
        holder.song = (TextView) convertView.findViewById(R.id.song_title);
        holder.artist = (TextView) convertView.findViewById(R.id.song_artist);

        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    convertView.setId(position);

    Song currentSong = getItem(position);

    if (currentSong != null) {
        holder.song.setText(currentSong.getTitle());
        holder.artist.setText(currentSong.getArtist());
    }

    return convertView;
}

private static class ViewHolder {
    TextView song;
    TextView artist;
}
</code>```

答:
Add one more variable in your song model class to make visibility for each row, please try this below code :

```<code>class Song{
    private boolean isShowing =false;

    public boolean isShowing() {
        return isShowing;
    }

    public void setShowing(boolean showing) {
        isShowing = showing;
    }
}
</code>```

SongsAdapter.class

```<code>class SongAdapter extends BaseAdapter {
           private Context mContext;
           private List<Song> mSongList;

           public SongAdapter(Context context, List<Song> songs) {
               mContext = context;
               mSongList = songs;
           }

           @Override
           public int getCount() {
               return mSongList.size();
           }

           @Override
           public Object getItem(int i) {
               return null;
           }

           @Override
           public long getItemId(int i) {
               return 0;
           }

           @Override
           public View getView(final int position, View convertView, ViewGroup parent) {
               ViewHolder holder;

               if (convertView == null) {
                   convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent,
                           false);
                   holder = new ViewHolder(convertView);

                   convertView.setTag(holder);
               } else {
                   holder = (ViewHolder) convertView.getTag();
               }

               final Song songModel = mSongList.get(position);
               holder.song.setText(songModel.getSongTitle());
               holder.artist.setText(songModel.getSongArtist());

               if(songModel.isShowing()){
                   holder.song.setVisibility(View.VISIBLE);
               }else{
                   holder.song.setVisibility(View.GONE);
               }
               convertView.setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View view) {
                       if(songModel.isShowing()){
                           songModel.setShowing(false);
                       }else{
                           songModel.setShowing(true);
                       }

                       notifyDataSetChanged();

                   }
               });
               return convertView;
           }

           public class ViewHolder{
               TextView song;
               TextView artist;

               public ViewHolder(View itemView) {
                   song = (TextView)itemView.findViewById(R.id.song_title);
                   artist = (TextView)itemView.findViewById(R.id.artist);

               }

           }
       }
</code>```

Body:
I was wondering how to update views/UI (say, making a TextView invisible) within a single row of a ListView when clicking on the row because every other rows' views would be affected as well. A good example would be playing a song in Google Play Music, and the equalizer animation would be displayed accordingly. Here are my snippets:

MainActivity's onCreate():

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); // Renders only a ListView

    ListView songListView = (ListView) findViewById(R.id.list);
    List<Song> songList = new ArrayList<>();
    for (int i = 1; i <= 200; i++) songList.add(new Song("Song" + i, "Artist" + i));
    SongAdapter songAdapter = new SongAdapter(this, songList);
    songListView.setAdapter(songAdapter);
    songListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
            if (position == view.getId()) {
                TextView titleText = (TextView) view.findViewById(R.id.song_title);
                titleText.setVisibility(View.INVISIBLE);
            }
        }
    });
}

... and my ArrayAdapter's getView method and ViewHolder class:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;

    if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent,
                false);

        holder = new ViewHolder();
        holder.song = (TextView) convertView.findViewById(R.id.song_title);
        holder.artist = (TextView) convertView.findViewById(R.id.song_artist);

        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    convertView.setId(position);

    Song currentSong = getItem(position);

    if (currentSong != null) {
        holder.song.setText(currentSong.getTitle());
        holder.artist.setText(currentSong.getArtist());
    }

    return convertView;
}

private static class ViewHolder {
    TextView song;
    TextView artist;
}

Body:
Add one more variable in your song model class to make visibility for each row, please try this below code :

class Song{
    private boolean isShowing =false;

    public boolean isShowing() {
        return isShowing;
    }

    public void setShowing(boolean showing) {
        isShowing = showing;
    }
}

SongsAdapter.class

class SongAdapter extends BaseAdapter {
           private Context mContext;
           private List<Song> mSongList;

           public SongAdapter(Context context, List<Song> songs) {
               mContext = context;
               mSongList = songs;
           }

           @Override
           public int getCount() {
               return mSongList.size();
           }

           @Override
           public Object getItem(int i) {
               return null;
           }

           @Override
           public long getItemId(int i) {
               return 0;
           }

           @Override
           public View getView(final int position, View convertView, ViewGroup parent) {
               ViewHolder holder;

               if (convertView == null) {
                   convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent,
                           false);
                   holder = new ViewHolder(convertView);

                   convertView.setTag(holder);
               } else {
                   holder = (ViewHolder) convertView.getTag();
               }

               final Song songModel = mSongList.get(position);
               holder.song.setText(songModel.getSongTitle());
               holder.artist.setText(songModel.getSongArtist());

               if(songModel.isShowing()){
                   holder.song.setVisibility(View.VISIBLE);
               }else{
                   holder.song.setVisibility(View.GONE);
               }
               convertView.setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View view) {
                       if(songModel.isShowing()){
                           songModel.setShowing(false);
                       }else{
                           songModel.setShowing(true);
                       }

                       notifyDataSetChanged();

                   }
               });
               return convertView;
           }

           public class ViewHolder{
               TextView song;
               TextView artist;

               public ViewHolder(View itemView) {
                   song = (TextView)itemView.findViewById(R.id.song_title);
                   artist = (TextView)itemView.findViewById(R.id.artist);

               }

           }
       }


问:
How does this code access the nested array with just one index and not two?
I am studying a book about JavaScript and I don’t understand a tutorial to make a quiz program, It works fine but it uses a nested array and I am having a problem understanding it.

The code in question is this one:

var score = 0
var question = [
  ['How many moon does Earth Have?', 1],
  ['How many moon does Saturn Have?', 31],
  ['How many moon does Venus Have?', 0]
];

function askQuestion(question) {
  var answer = prompt(question[0], '');
  if (answer == question[1]) {
    alert('Corresct!');
    score++;
  } else {
    alert('Sorry, the correct answer is ' + question[1]);
  }
}

for (var i = 0; i < question.length; i++) {
  askQuestion(question[i]);
}```

I don’t understand how it has access to the array in function askQuestion. Why does it only need one index to access it?

答:
The reason it only takes one index is because the first index is used in the function call, at askQuestion(question[i]);

question[1] for instance is the equivalent of ['How many moon does Saturn Have?' , 31] so when it gets to the function, it is only working with a one-dimensional array, not a two-dimensional one.

It is confusing because the parameter given to the function is called question and so is the variable at the top, but they are actually different variables because they are in different scopes -- one only exists in the context of the function, and the other exists outside of it.

Body:
I am studying a book about JavaScript and I don’t understand a tutorial to make a quiz program, It works fine but it uses a nested array and I am having a problem understanding it.

The code in question is this one:

var score = 0
var question = [
  ['How many moon does Earth Have?', 1],
  ['How many moon does Saturn Have?', 31],
  ['How many moon does Venus Have?', 0]
];

function askQuestion(question) {
  var answer = prompt(question[0], '');
  if (answer == question[1]) {
    alert('Corresct!');
    score++;
  } else {
    alert('Sorry, the correct answer is ' + question[1]);
  }
}

for (var i = 0; i < question.length; i++) {
  askQuestion(question[i]);
}

I don’t understand how it has access to the array in function askQuestion. Why does it only need one index to access it?