问:
PHP jQuery ajax submit button not working
I would like to create a dynamic form with add and remove field using jquery and ajax. but unfortunately,my insert button supposedly go to insert.php wont work.When I click insert button,nothing is happened. When the insert button clicked,it will be redirect to insert.php store data inside the database.Here is my coding

repeater.js

```<code>
    jQuery.fn.extend({
        createRepeater: function (options = {}) {
            var hasOption = function (optionKey) {
                return options.hasOwnProperty(optionKey);
            };

            var option = function (optionKey) {
                return options[optionKey];
            };

            var generateId = function (string) {
                return string
                    .replace(/\[/g, '_')
                    .replace(/\]/g, '')
                    .toLowerCase();
            };

            var addItem = function (items, key, fresh = true) {
                var itemContent = items;
                var group = itemContent.data("group");
                var item = itemContent;
                var input = item.find('input,select');

                input.each(function (index, el) {
                    var attrName = $(el).data('name');
                    var skipName = $(el).data('skip-name');
                    if (skipName != true) {
                        $(el).attr("name", group + "[" + key + "]" + "[" + attrName + "]");
                    } else {
                        if (attrName != 'undefined') {
                            $(el).attr("name", attrName);
                        }
                    }
                    if (fresh == true) {
                        $(el).attr('value', '');
                    }

                    $(el).attr('id', generateId($(el).attr('name')));
                    $(el).parent().find('label').attr('for', generateId($(el).attr('name')));
                })

                var itemClone = items;

                /* Handling remove btn */
                var removeButton = itemClone.find('.remove-btn');

                if (key == 0) {
                    removeButton.attr('disabled', true);
                } else {
                    removeButton.attr('disabled', false);
                }

                removeButton.attr('onclick', '$(this).parents(\'.items\').remove()');

                var newItem = $("<div class='items'>" + itemClone.html() + "<div/>");
                newItem.attr('data-index', key)

                newItem.appendTo(repeater);
            };

            /* find elements */
            var repeater = this;
            var items = repeater.find(".items");
            var key = 0;
            var addButton = repeater.find('.repeater-add-btn');

            items.each(function (index, item) {
                items.remove();
                if (hasOption('showFirstItemToDefault') && option('showFirstItemToDefault') == true) {
                    addItem($(item), key);
                    key++;
                } else {
                    if (items.length > 1) {
                        addItem($(item), key);
                        key++;
                    }
                }
            });

            /* handle click and add items */
            addButton.on("click", function () {
                addItem($(items[0]), key);
                key++;
            });
        }
    });

</code>```

index.php

```<code><?php
//session_start();
$servername = "localhost";
$username = "root";
$password = "bptm2012";
$dbname = "icompex";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
$sql = "select panel_id,panel_kp,panel_nm from mem_panel";
$result = mysqli_query($conn, $sql);
?>
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Add Remove Panel Group and Category</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"
            integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ"
            crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="repeater.js" type="text/javascript"></script>

</head>
<body>
<div class="container">
    <br/>
    <h3 align="center">Kemaskini Ahli dan Kumpulan Panel Penilai</h3>
    <br/>
    <div style="width:100%; max-width: 600px; margin:0 auto;">
        <div class="panel panel-default">
            <div class="panel-heading">Menu Kumpulan dan Ahli Panel</div>
            <div class="panel-body">
                <span id="success_result"></span>
                <div id="div1"><h2></h2></div>

                <form method="post" id="repeater_form">
                    <div class="form-group">
                        <label>Pilih Group</label><br>
                        <select class="form-control" name="cat">

                            <option value="" disabled selected>Sila Pilih Kategori</option>
                            <option value="A">A - Rekabentuk Alam Bina & Rekabentuk Dalaman</option>
                            <option value="B">B - Pembinaan dan Bahan</option>
                            <option value="C">C - Mesin, Peralatan dan Proses Pergilangan</option>
                            <option value="D">D - ICT & Multimedia</option>
                            <option value="E">E - Elektrik, Elektronik dan Telekomunikasi</option>
                            <option value="F">F - Pengangkutan, Automatif & Penerbangan</option>
                            <option value="G">G - Pertanian, Alam Sekitar dan Tenaga Boleh Diperbaharui</option>
                            <option value="H">H - Pengajaran dan Pembelajaran</option>
                            <option value="I">I - Perkhidmatan dan Pemasaran Produk</option>
                        </select>
                        <label>Sila Pilih Kumpulan Panel</label><br>
                        <select name="group" class="form-control">
                            <option value="" disabled selected>Sila Pilih Kumpulan Panel</option>
                            <option value="1">Panel 1</option>
                            <option value="2">Panel 2</option>
                            <option value="3">Panel 3</option>
                            <option value="4">Panel 4</option>
                            <option value="5">Panel 5</option>
                            <option value="6">Panel 6</option>
                            <option value="7">Panel 7</option>
                            <option value="8">Panel 8</option>
                            <option value="9">Panel 9</option>
                            <option value="10">Panel 10</option>
                            <option value="11">Panel 11</option>
                            <option value="12">Panel 12</option>
                            <option value="13">Panel 13</option>
                            <option value="14">Panel 14</option>
                            <option value="15">Panel 15</option>
                        </select>
                    </div>
                    <div id="repeater">
                        <div class="repeater-heading" align="right">
                            <button type="button" class="btn btn-primary repeater-add-btn">Tambah Ahli</button>
                        </div>
                        <div class="clearfix"></div>
                        <div class="items" data-group="programming_languages">
                            <div class="item-content">
                                <div class="form-group">
                                    <div class="row">
                                        <div class="col-md-9">
                                            <label>Pilih Nama Ahli Panel</label>
                                            <select class="form-control" data-skip-name="true" data-name="skill[]"
                                                    required>
                                                <?php
                                                echo "<option>Sila Pilih Ahli Panel</option>";
                                                if (mysqli_num_rows($result) > 0) {
                                                    // output data of each row
                                                    while ($row = mysqli_fetch_assoc($result)) {
                                                        echo '<option value="' . $row['panel_id'] . '">' . $row['panel_nm'] . '</option>';
                                                    }
                                                } else {
                                                    echo "<option>Maaf Belum ada pendaftaran ahli panel dibuat</option>";
                                                }

                                                mysqli_close($conn);
                                                ?>
                                            </select>
                                        </div>
                                        <div class="col-md-3" style="margin-top:24px;" align="center">
                                            <button id="remove-btn" class="btn btn-danger"
                                                    onclick="$(this).parents('.items').remove()">Remove
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="clearfix"></div>
                    <div class="form-group" align="center">
                        <br/><br/>
                        <input type="submit" name="insert" class="btn btn-success" value="insert"/>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function () {

        $("#repeater").createRepeater();

        $('#repeater_form').on('submit', function (event) {
            event.preventDefault();
            $.ajax({
                url: "insert.php",
                method: "POST",
                data: $(this).serialize(),
                success: function (data) {
                    $('#repeater_form')[0].reset();
                    $("#repeater").createRepeater();
                    $('#success_result').html(data);
                    /*setInterval(function(){
                        location.reload();
                    }, 3000);*/
                }
            });
        });

    });

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

insert.php

```<code><?php

connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

if (isset($_POST["name"])) {
    $skill = implode(", ", $_POST["skill"]);

    $data = array(
        ':panel_cat' => $_POST["cat"],
        ':panel_group' => $_POST["group"],
        ':panel_mem' => $skill
    );

    $query = "
 INSERT INTO panel_penilai
 (panel_cat, panel_group,panel_mem)
 VALUES (:panel_cat, :panel_group, :panel_mem)
 ";

    $statement = $connect->prepare($query);
    if ($statement->execute($data)) {
        echo '
  <div class="alert alert-success">
   Data Successfully Inserted
  </div>
  ';
    }
}

//?>
</code>```

答:
Remove event.preventDefault(); .
preventDefault() method is used to stop submitting the form. Removing it will allow the form to submit the data to insert.php

Body:
I would like to create a dynamic form with add and remove field using jquery and ajax. but unfortunately,my insert button supposedly go to insert.php wont work.When I click insert button,nothing is happened. When the insert button clicked,it will be redirect to insert.php store data inside the database.Here is my coding

repeater.js

    jQuery.fn.extend({
        createRepeater: function (options = {}) {
            var hasOption = function (optionKey) {
                return options.hasOwnProperty(optionKey);
            };

            var option = function (optionKey) {
                return options[optionKey];
            };

            var generateId = function (string) {
                return string
                    .replace(/\[/g, '_')
                    .replace(/\]/g, '')
                    .toLowerCase();
            };

            var addItem = function (items, key, fresh = true) {
                var itemContent = items;
                var group = itemContent.data("group");
                var item = itemContent;
                var input = item.find('input,select');

                input.each(function (index, el) {
                    var attrName = $(el).data('name');
                    var skipName = $(el).data('skip-name');
                    if (skipName != true) {
                        $(el).attr("name", group + "[" + key + "]" + "[" + attrName + "]");
                    } else {
                        if (attrName != 'undefined') {
                            $(el).attr("name", attrName);
                        }
                    }
                    if (fresh == true) {
                        $(el).attr('value', '');
                    }

                    $(el).attr('id', generateId($(el).attr('name')));
                    $(el).parent().find('label').attr('for', generateId($(el).attr('name')));
                })

                var itemClone = items;

                /* Handling remove btn */
                var removeButton = itemClone.find('.remove-btn');

                if (key == 0) {
                    removeButton.attr('disabled', true);
                } else {
                    removeButton.attr('disabled', false);
                }

                removeButton.attr('onclick', '$(this).parents(\'.items\').remove()');

                var newItem = $("
" + itemClone.html() + "
");
                newItem.attr('data-index', key)

                newItem.appendTo(repeater);
            };

            /* find elements */
            var repeater = this;
            var items = repeater.find(".items");
            var key = 0;
            var addButton = repeater.find('.repeater-add-btn');

            items.each(function (index, item) {
                items.remove();
                if (hasOption('showFirstItemToDefault') && option('showFirstItemToDefault') == true) {
                    addItem($(item), key);
                    key++;
                } else {
                    if (items.length > 1) {
                        addItem($(item), key);
                        key++;
                    }
                }
            });

            /* handle click and add items */
            addButton.on("click", function () {
                addItem($(items[0]), key);
                key++;
            });
        }
    });

index.php

<?php
//session_start();
$servername = "localhost";
$username = "root";
$password = "bptm2012";
$dbname = "icompex";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
$sql = "select panel_id,panel_kp,panel_nm from mem_panel";
$result = mysqli_query($conn, $sql);
?>
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Add Remove Panel Group and Category</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>

Kemaskini Ahli dan Kumpulan Panel Penilai

Menu Kumpulan dan Ahli Panel

                <form method="post" id="repeater_form">

                        Pilih Group

                        <select class="form-control" name="cat">

                            <option value="" disabled selected>Sila Pilih Kategori</option>
                            <option value="A">A - Rekabentuk Alam Bina & Rekabentuk Dalaman</option>
                            <option value="B">B - Pembinaan dan Bahan</option>
                            <option value="C">C - Mesin, Peralatan dan Proses Pergilangan</option>
                            <option value="D">D - ICT & Multimedia</option>
                            <option value="E">E - Elektrik, Elektronik dan Telekomunikasi</option>
                            <option value="F">F - Pengangkutan, Automatif & Penerbangan</option>
                            <option value="G">G - Pertanian, Alam Sekitar dan Tenaga Boleh Diperbaharui</option>
                            <option value="H">H - Pengajaran dan Pembelajaran</option>
                            <option value="I">I - Perkhidmatan dan Pemasaran Produk</option>
                        </select>
                        Sila Pilih Kumpulan Panel

                        <select name="group" class="form-control">
                            <option value="" disabled selected>Sila Pilih Kumpulan Panel</option>
                            <option value="1">Panel 1</option>
                            <option value="2">Panel 2</option>
                            <option value="3">Panel 3</option>
                            <option value="4">Panel 4</option>
                            <option value="5">Panel 5</option>
                            <option value="6">Panel 6</option>
                            <option value="7">Panel 7</option>
                            <option value="8">Panel 8</option>
                            <option value="9">Panel 9</option>
                            <option value="10">Panel 10</option>
                            <option value="11">Panel 11</option>
                            <option value="12">Panel 12</option>
                            <option value="13">Panel 13</option>
                            <option value="14">Panel 14</option>
                            <option value="15">Panel 15</option>
                        </select>

                            <button type="button" class="btn btn-primary repeater-add-btn">Tambah Ahli</button>

                                            Pilih Nama Ahli Panel
                                            <select class="form-control" data-skip-name="true" data-name="skill[]"
                                                    required>
                                                <?php
                                                echo "<option>Sila Pilih Ahli Panel</option>";
                                                if (mysqli_num_rows($result) > 0) {
                                                    // output data of each row
                                                    while ($row = mysqli_fetch_assoc($result)) {
                                                        echo '<option value="' . $row['panel_id'] . '">' . $row['panel_nm'] . '</option>';
                                                    }
                                                } else {
                                                    echo "<option>Maaf Belum ada pendaftaran ahli panel dibuat</option>";
                                                }

                                                mysqli_close($conn);
                                                ?>
                                            </select>

                                            <button id="remove-btn" class="btn btn-danger"
                                                    onclick="$(this).parents('.items').remove()">Remove
                                            </button>

                        <input type="submit" name="insert" class="btn btn-success" value="insert"/>

                </form>

insert.php

<?php

connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

if (isset($_POST["name"])) {
    $skill = implode(", ", $_POST["skill"]);

    $data = array(
        ':panel_cat' => $_POST["cat"],
        ':panel_group' => $_POST["group"],
        ':panel_mem' => $skill
    );

    $query = "
 INSERT INTO panel_penilai
 (panel_cat, panel_group,panel_mem)
 VALUES (:panel_cat, :panel_group, :panel_mem)
 ";

    $statement = $connect->prepare($query);
    if ($statement->execute($data)) {
        echo '

   Data Successfully Inserted

  ';
    }
}

//?>


来源: stackexchange

问:
Is there a Python function to repeat string patterns to get faster multiple columns in different dataframes
I'm new in Python, I need to get many variables in multiple dataframes:

I wrote this code but I need a long time to configure it for many excersises.

This is the code:

```<code>import pandas as pd

df = pd.concat([df1[df1.columns[0]], df2[df1.columns[0]], df1[df1.columns[1]],
                df2[df1.columns[1]], df1[df1.columns[2]], df2[df1.columns[2]],
                df1[df1.columns[3]], df2[df1.columns[3]], df1[df1.columns[4]],
                df2[df1.columns[4]], df1[df1.columns[5]], df2[df1.columns[5]],
                df1[df1.columns[6]], df2[df1.columns[6]]], axis=1)
</code>```

The number of dataframes and columns can be much bigger. Thanks.

答:
It looks like what you're trying to do is: for all of the columns in one dataframe, combine the columns from that dataframe with those from another with the same columns, into a single dataframe with two of every column in the same original order.

In your case:

```<code>df1 = DataFrame([['a','b','c'], ['d','e','f']])
df2 = DataFrame([['g','h','i'], ['j','k','l']])

df = concat([s for ss in [(df1[c], df2[c]) for c in df1.columns] for s in ss], axis=1)

print(df)
</code>```

Result:

```<code>   0  0  1  1  2  2
0  a  g  b  h  c  i
1  d  j  e  k  f  l
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new in Python, I need to get many variables in multiple dataframes:

I wrote this code but I need a long time to configure it for many excersises.

This is the code:

import pandas as pd

df = pd.concat([df1[df1.columns[0]], df2[df1.columns[0]], df1[df1.columns[1]],
                df2[df1.columns[1]], df1[df1.columns[2]], df2[df1.columns[2]],
                df1[df1.columns[3]], df2[df1.columns[3]], df1[df1.columns[4]],
                df2[df1.columns[4]], df1[df1.columns[5]], df2[df1.columns[5]],
                df1[df1.columns[6]], df2[df1.columns[6]]], axis=1)

The number of dataframes and columns can be much bigger. Thanks.

Body:
It looks like what you're trying to do is: for all of the columns in one dataframe, combine the columns from that dataframe with those from another with the same columns, into a single dataframe with two of every column in the same original order.

In your case:

df1 = DataFrame([['a','b','c'], ['d','e','f']])
df2 = DataFrame([['g','h','i'], ['j','k','l']])

df = concat([s for ss in [(df1[c], df2[c]) for c in df1.columns] for s in ss], axis=1)

print(df)

Result:

   0  0  1  1  2  2
0  a  g  b  h  c  i
1  d  j  e  k  f  l


问:
Run WPF Application and in that call other wpf application
i have two WPF Application say WPFApplication1 and WPFApplication2 , WPFApplication1 has reference of WPFApplication2 , now i am calling one class of WPFApplication2 in WPFApplication1 using reference, and from WPFApplication2 class creating App class instance of WPFApplication2 , so i am facing issue like below
Error

Please help me out with this, THanks in Advance

答:
Look at Process.Start and ProcessStartInfo
Here is an example for Console application. But there are not different how to start other application.

By ProcessStartInfo you can specify many things like Are you has to wait it? Or run without waiting. Is you want to redirect output? And so one.

using System.Diagnostics;

```<code>class Program
{
    static void Main()
    {
        LaunchCommandLineApp();
    }

    /// <summary>
    /// Launch the application with some options set.
    /// </summary>
    static void LaunchCommandLineApp()
    {
        // For the example
        const string ex1 = "C:\\";
        const string ex2 = "C:\\Dir";

        // Use ProcessStartInfo class
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.CreateNoWindow = false;
        startInfo.UseShellExecute = false;
        startInfo.FileName = "dcm2jpg.exe";
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.Arguments = "-f j -o \"" + ex1 + "\" -z 1.0 -s y " + ex2;

        try
        {
            // Start the process with the info we specified.
            // Call WaitForExit and then the using statement will close.
            using (Process exeProcess = Process.Start(startInfo))
            {
                exeProcess.WaitForExit();
            }
        }
        catch
        {
             // Log error.
        }
    }
}
</code>```

Body:
Look at Process.Start and ProcessStartInfo
Here is an example for Console application. But there are not different how to start other application.

By ProcessStartInfo you can specify many things like Are you has to wait it? Or run without waiting. Is you want to redirect output? And so one.

using System.Diagnostics;

class Program
{
    static void Main()
    {
        LaunchCommandLineApp();
    }

    /// <summary>
    /// Launch the application with some options set.
    /// </summary>
    static void LaunchCommandLineApp()
    {
        // For the example
        const string ex1 = "C:\\";
        const string ex2 = "C:\\Dir";

        // Use ProcessStartInfo class
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.CreateNoWindow = false;
        startInfo.UseShellExecute = false;
        startInfo.FileName = "dcm2jpg.exe";
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.Arguments = "-f j -o \"" + ex1 + "\" -z 1.0 -s y " + ex2;

        try
        {
            // Start the process with the info we specified.
            // Call WaitForExit and then the using statement will close.
            using (Process exeProcess = Process.Start(startInfo))
            {
                exeProcess.WaitForExit();
            }
        }
        catch
        {
             // Log error.
        }
    }
}


问:
replace multiple values in a column and keep other values unchanged in pandas dataframe
I have an example dataframe like below:

```<code>df = pd.DataFrame({'name': ['red', 'orange', 'blue'],
                   'value': [22,44,66]})

    name    value
0   red     22
1   orange  44
2   blue    66
</code>```

I need to replace red with 1 and blue with 2, leaving orange as it is, in the column name.

I use map function like below:

```<code>df.name.map({'red': 0, 'blue': 1})
</code>```

I got result like:

```<code>    name    value
0   0.0     22
1   NaN     44
2   1.0     66
</code>```

In the column, orange becomes NaN

What is the best way to replace the values?

I do not want to use df.name.str.replace(..) many times to replace many values. In my real data, there are 10 values to replace in a column.
Thanks.

答:
Fix your code with fillna

```<code>df.name = df.name.map({'red': 0, 'blue': 1}).fillna(df.name)
0         0
1    orange
2         1
Name: name, dtype: object
</code>```

Body:
I have an example dataframe like below:

df = pd.DataFrame({'name': ['red', 'orange', 'blue'],
                   'value': [22,44,66]})

    name    value
0   red     22
1   orange  44
2   blue    66

I need to replace red with 1 and blue with 2, leaving orange as it is, in the column name.

I use map function like below:

df.name.map({'red': 0, 'blue': 1})

I got result like:

    name    value
0   0.0     22
1   NaN     44
2   1.0     66

In the column, orange becomes NaN

What is the best way to replace the values?

I do not want to use df.name.str.replace(..) many times to replace many values. In my real data, there are 10 values to replace in a column.
Thanks.

Body:
Fix your code with fillna

df.name = df.name.map({'red': 0, 'blue': 1}).fillna(df.name)
0         0
1    orange
2         1
Name: name, dtype: object


问:
Problem restoring stdout after using pipe
Using the advise found here: Restoring stdout after using dup
I tried to restore the stdin and stdout. However, when using printf to check if stdout was restored I could not read an output.
The code is as follows. After restoring stdout as 1, I tried printing "done".

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

void main(int argv, char *argc) {
    int stdin_copy = dup(STDIN_FILENO);
    int stdout_copy = dup(STDOUT_FILENO);
    int testpipe[2];
    pipe(testpipe);
    int PID = fork();
    if (PID == 0) {
        dup2(testpipe[0], 0);
        close(testpipe[1]);
        execl("./multby", "multby", "3", NULL);// Just multiplies argument 3 with the number in testpipe.
    } else {
        dup2(testpipe[1], 1);
        close(testpipe[0]);
        printf("5");
        fclose(stdout);
        close(testpipe[1]);
        char initialval[100];
        read(testpipe[0], initialval, 100);
        fprintf(stderr, "initial value: %s\n", initialval);
        wait(NULL);
        dup2(stdin_copy, 0);
        dup2(stdout_copy, 1);
        printf("done");//was not displayed when I run code.
    }
}
</code>```

However, I did not see a "done" when I ran the code. (There should be a done after 15).
This is my output:
initial value:
exec successful
a: 3
b: 5
multby successful
15

What did I do wrong when restoring stdout?

答:
You're calling fclose(stdout); which closes the stdout FILE object as well as STDOUT_FILELO -- the stdout file descriptor (they're two different things, linked together).  So when you later call dup2(stdout_copy, 1);, that restores the file descriptor, but the FILE object remains closed, so you can't use it to output anything.  There's no way to reopen the FILE object to refer to a file descriptor1, so your best bet is just to remove the fclose line.  The dup2 will close the file descriptor you're replacing (so you don't really need a separate close) and you should be able to see the output

1You could possibly use freopen with /dev/fd on some systems, but /dev/fd is non-portable

Body:
Using the advise found here: Restoring stdout after using dup
I tried to restore the stdin and stdout. However, when using printf to check if stdout was restored I could not read an output.
The code is as follows. After restoring stdout as 1, I tried printing "done".

#include <stdio.h>
#include <unistd.h>

void main(int argv, char *argc) {
    int stdin_copy = dup(STDIN_FILENO);
    int stdout_copy = dup(STDOUT_FILENO);
    int testpipe[2];
    pipe(testpipe);
    int PID = fork();
    if (PID == 0) {
        dup2(testpipe[0], 0);
        close(testpipe[1]);
        execl("./multby", "multby", "3", NULL);// Just multiplies argument 3 with the number in testpipe.
    } else {
        dup2(testpipe[1], 1);
        close(testpipe[0]);
        printf("5");
        fclose(stdout);
        close(testpipe[1]);
        char initialval[100];
        read(testpipe[0], initialval, 100);
        fprintf(stderr, "initial value: %s\n", initialval);
        wait(NULL);
        dup2(stdin_copy, 0);
        dup2(stdout_copy, 1);
        printf("done");//was not displayed when I run code.
    }
}

However, I did not see a "done" when I ran the code. (There should be a done after 15).
This is my output:
initial value:
exec successful
a: 3
b: 5
multby successful
15

What did I do wrong when restoring stdout?


问:
Get images from PHP server to Android
I am prototyping an android application and need to get images from a web server to Android ListView. I understand the android side of things (although am yet to implement and test) via this thread Lazy load of images in ListView

I need help with the PHP/server side of it. The particular images that need to be populated in a list view will be decided dynamically (those images that have a given tag). I am new to web applications but have managed to set up a web server which can run PHP scripts.

1) Android decides which tags to retrieve. Makes an HTTP connection and calls a PHP script with the given tag as a parameter.

2) The PHP script looks up the MySQL database for the tag, decides the ids of images to upload, which are stored in a folder.

3) [Here is where I am unclear how to implement] The PHP sends these images followed by meta-data associated with each image. The number of records to send will not be fixed beforehand and will be decided by the number of records returned by MySQL (only maximum will be fixed).

I would greatly appreciate any sample scripts, and pointers to where I could find more information to better understand the inner working. Also, if there are better frameworks to do what I want to, I am happy to learn about that (I am not married to PHP/MySQL).

答:
If i were you i would do a php webservice nosoap http://android-developers.blogspot.com/2009/05/painless-threading.html

for dowload images. Api's i would use ksoap2 dowload

the rest is reading a lot but actually it's easy :D

ContentLicense: CC BY-SA 3.0

Title: Get images from PHP server to Android


问:
In Unity how to save 3D model(prefab) to a PNG image with transparent background?
In Unity how to save 3D model(prefab) to a PNG image with transparent background?

If not possible in unity, how about using maya?

答:
There's no easy way but by searching I could come with this. Hope it what's you need.

AssetPreview.GetAssetPreview to get a Texture2D of your model.

Then use Texture2D.EncoreToPNG to encore it to a PNG.


问:
how to extract specifc numbers from a text string?
How could I extract different number values within text strings?

The goal is to extract the numbers after specific text strings for example: the number 290 below is between "NBF " and " +".

For cell A1: USD 1009  SUBJECT TO: NBF 290 + GFS 60 + IPS 18 + CCT 15 + BLF 75/20’DV

Result Desired would be:

CELL B1 1009

CELL C1 290 (number after NBF and before " +")

CELL D1 60 (number after GFS)

CELL E1 18 (number after IPS)

CELL F1 15 (number after CCT)

CELL G1 75 (number after BLF)

Usually I would use text to columns, but there are different lengths to the cells containing all info, so it doesnt always cuts the information properly.

答:
Use this:

```<code>=MID($A$1,(FIND("USD",$A$1)+LEN("USD"))+1,(FIND(" ",$A$1,(FIND("USD",$A$1)+LEN("USD"))+1)-(FIND("USD",$A$1)+LEN("USD"))))
</code>```

With the clarification that the last one will need to be:

```<code>=MID($A$1,(FIND("BLF",$A$1)+LEN("BLF"))+1,(FIND("/",$A$1,(FIND("BLF",$A$1)+LEN("BLF"))+1)-(FIND("BLF",$A$1)+LEN("BLF")+1)))
</code>```

Body:
Use this:

=MID($A$1,(FIND("USD",$A$1)+LEN("USD"))+1,(FIND(" ",$A$1,(FIND("USD",$A$1)+LEN("USD"))+1)-(FIND("USD",$A$1)+LEN("USD"))))

With the clarification that the last one will need to be:

=MID($A$1,(FIND("BLF",$A$1)+LEN("BLF"))+1,(FIND("/",$A$1,(FIND("BLF",$A$1)+LEN("BLF"))+1)-(FIND("BLF",$A$1)+LEN("BLF")+1)))


问:
How to mock "fluent" DataSourceHealthIndicator?
I am using Spring Boot 2.2.4.RELEASE.

I have this piece of code in my controller, where i am using the "free" DataSourceHealthIndicator to check if the DB is DOWN:

```<code>@Autowired
private DataSourceHealthIndicator d;

//some code

if("DOWN".equals(d.getHealth(false).getStatus().getCode())) {
 // do something
} else {
 // proceed
}
</code>```

Now, in my slice test, i would like to mock it(the DataSourceHealthIndicator), but i have a null pointer, as obviously getHealth() is not returning a Health object, getStatus() is not returning a Status object...

```<code>@WebMvcTest
//some code
@MockBean
private DataSourceHealthIndicator d;
//some code

given(this.d.getHealth(anyBoolean()).getStatus().getCode()).willReturn("UP");
</code>```

How can i go about mocking it?

I tried this:

```<code>given(this.d.getHealth(anyBoolean())).willReturn(Health.up().build());
given(this.d.getHealth(anyBoolean()).getStatus()).willReturn(Status.UP);
given(this.d.getHealth(anyBoolean()).getStatus().getCode()).willReturn("UP");
</code>```

But it is failing on the 2nd given statement:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
 Status
  cannot be returned by getHealth()
 getHealth() should return Health

答:
I shifted the DataSourceHealthIndicator code to a class of its own.

This has allowed me to easily slice test the Controller layer and at the same time it has allowed me to easily test the other class, with just the MockitoExtension.class.

SRP & KISS principle in action.

Body:
I am using Spring Boot 2.2.4.RELEASE.

I have this piece of code in my controller, where i am using the "free" DataSourceHealthIndicator to check if the DB is DOWN:

@Autowired
private DataSourceHealthIndicator d;

//some code

if("DOWN".equals(d.getHealth(false).getStatus().getCode())) {
 // do something
} else {
 // proceed
}

Now, in my slice test, i would like to mock it(the DataSourceHealthIndicator), but i have a null pointer, as obviously getHealth() is not returning a Health object, getStatus() is not returning a Status object...

@WebMvcTest
//some code
@MockBean
private DataSourceHealthIndicator d;
//some code

given(this.d.getHealth(anyBoolean()).getStatus().getCode()).willReturn("UP");

How can i go about mocking it?

I tried this:

given(this.d.getHealth(anyBoolean())).willReturn(Health.up().build());
given(this.d.getHealth(anyBoolean()).getStatus()).willReturn(Status.UP);
given(this.d.getHealth(anyBoolean()).getStatus().getCode()).willReturn("UP");

But it is failing on the 2nd given statement:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
 Status
  cannot be returned by getHealth()
 getHealth() should return Health


问:
Remove Element in ArrayList in loop
I need help. I tried to remove an element from an ArrayList.
I have two lists. One list from a file, the second list from the database.

I need to find the same elements to later remove them from the original list, and thus have a list with differences.

```<code>List<BinInternacionalMarcaDEL> listDiff = new ArrayList<BinInternacionalMarcaDEL>();

ListOriginal= binInternacionalRepositoryDEL.findAllByBin();

public  List<BinInternacionalMarcaDEL> Differences(List<BinInternacionalMarcaDEL> listA,
                                                   List<BinInternacionalMarcaDEL> listB) {
    try {
        for(BinInternacionalMarcaDEL elementA: listaA){
            for(BinInternacionalMarcaDEL elementB: listaB) {
                if(elementA.getNumRangoini().compareTo(elementB.getNumRangoini()) == 0 ){
                    listDiff.add(elementA);
                }
            }
        }
        ListOriginal.removeAll(listDiff);
    } catch (Exception e) {
        LOGGER.error(e.toString());
    }
</code>```

but this doesn't work.

答:
just you can do one thing

```<code> listA.retainAll(listB);
</code>```

here now listA contains only similar elements in both ListA and ListB.

Example:

```<code>List<String> listA =  new ArrayList<>(Arrays.asList("12","13","15","2","5")) ;
List<String> listB =  new ArrayList<> (Arrays.asList("2","12","48","49","55"));
listA .retainAll(listB );
System.out.println(listA ); //[12, 2]
</code>```

Title: Remove Element in ArrayList in loop

Body:
I need help. I tried to remove an element from an ArrayList.
I have two lists. One list from a file, the second list from the database.

I need to find the same elements to later remove them from the original list, and thus have a list with differences.

List<BinInternacionalMarcaDEL> listDiff = new ArrayList<BinInternacionalMarcaDEL>();

ListOriginal= binInternacionalRepositoryDEL.findAllByBin();

public  List<BinInternacionalMarcaDEL> Differences(List<BinInternacionalMarcaDEL> listA,
                                                   List<BinInternacionalMarcaDEL> listB) {
    try {
        for(BinInternacionalMarcaDEL elementA: listaA){
            for(BinInternacionalMarcaDEL elementB: listaB) {
                if(elementA.getNumRangoini().compareTo(elementB.getNumRangoini()) == 0 ){
                    listDiff.add(elementA);
                }
            }
        }
        ListOriginal.removeAll(listDiff);
    } catch (Exception e) {
        LOGGER.error(e.toString());
    }

but this doesn't work.

Body:
just you can do one thing

 listA.retainAll(listB);

here now listA contains only similar elements in both ListA and ListB.

Example:

List<String> listA =  new ArrayList<>(Arrays.asList("12","13","15","2","5")) ;
List<String> listB =  new ArrayList<> (Arrays.asList("2","12","48","49","55"));
listA .retainAll(listB );
System.out.println(listA ); //[12, 2]


问:
Compare line by line within a linux file
I have a file (test1.txt) like this:

```<code>100 100
200 200
300 HR
400 IT
500 500
600 600
</code>```

And I want to desired output like this:

```<code>100 100 0
200 200 0
300 HR  1
400 IT  1
500 500 0
600 600 0
</code>```

I already try to run this command:

```<code>#!/bin/bash

awk1=`awk '{print $1}' test1.txt`
awk2=`awk '{print $2}' test1.txt`

if [ "$awk1" = "$awk2" ]; then
        echo "0"
else
        echo "1"
fi
</code>```

but the result is not as I expected.

答:
Could you please try following.

```<code>awk '{$(NF+1)=$1==$2?0:1} 1' Input_file
</code>```

OR to have output TAB delimited try:

```<code>awk 'BEGIN{OFS="\t"} {$(NF+1)=$1==$2?0:1} 1' Input_file
</code>```

Explanation: Adding detailed explanation for above code.

```<code>awk '                   ##Starting awk program from here.
{
  $(NF+1)=$1==$2?0:1    ##Creating a new NF+1 field which will be newer last field and its value will be decided as per condition:
}                       ##If $1 and $2 are equal then set 0 or set 1 its value.
1                       ##1 will print the complete line value here(including new last field value).
' Input_file            ##Mentioning Input_file name here.
</code>```

Body:
I have a file (test1.txt) like this:

100 100
200 200
300 HR
400 IT
500 500
600 600

And I want to desired output like this:

100 100 0
200 200 0
300 HR  1
400 IT  1
500 500 0
600 600 0

I already try to run this command:

#!/bin/bash

awk1=`awk '{print $1}' test1.txt`
awk2=`awk '{print $2}' test1.txt`

if [ "$awk1" = "$awk2" ]; then
        echo "0"
else
        echo "1"
fi

but the result is not as I expected.

Body:
Could you please try following.

awk '{$(NF+1)=$1==$2?0:1} 1' Input_file

OR to have output TAB delimited try:

awk 'BEGIN{OFS="\t"} {$(NF+1)=$1==$2?0:1} 1' Input_file

Explanation: Adding detailed explanation for above code.

awk '                   ##Starting awk program from here.
{
  $(NF+1)=$1==$2?0:1    ##Creating a new NF+1 field which will be newer last field and its value will be decided as per condition:
}                       ##If $1 and $2 are equal then set 0 or set 1 its value.
1                       ##1 will print the complete line value here(including new last field value).
' Input_file            ##Mentioning Input_file name here.


问:
Regular Expression validator for date format DD/MMM/YYYY
```<code><asp:TextBox ID="txtDob" runat="server" MaxLength="100" CssClass="textbox2" size="10"  />
<ajax:TextBoxWatermarkExtender ID="txtWEDOB" WatermarkText="DD/MON/YYYY" TargetControlID="txtDob" runat="server" />
<asp:RegularExpressionValidator ID="rfv" runat="server" ControlToValidate="txtDob" SetFocusOnError="true"
ValidationExpression="^(3[0-1]|2[0-9]|1[0-9]|0[1-9])[\s{1}|\/|-](Jan|JAN|Feb|FEB|Mar|MAR|Apr|APR|May|MAY|Jun|JUN|Jul|JUL|Aug|AUG|Sep|SEP|Oct|OCT|Nov|NOV|Dec|DEC)[\s{1}|\/|-]\d{4}$"
Display="None" ValidationGroup="search" ErrorMessage="Please enter correct date">
</asp:RegularExpressionValidator>
</code>```

I am using this regular expression validator for date. It is not giving error for like 12-FEB-2010 or 12 Feb 2010. I strictly want 12/FEB/2010 format. This Regular expressii\on is not working for date like 29/FEB/2010. what changes need to be made.

答:
I assume you've cut-and-paste this regex from somewhere else?

This part ([\s{1}|\/|-]) is where your problem is.  This allows space (\s) and hyphen (-), as well as the / character.

It should instead be \/.  So your current regex

```<code>"^(3[0-1]|2[0-9]|1[0-9]|0[1-9])[\s{1}|\/|-](Jan|JAN|Feb|FEB|Mar|MAR|Apr|APR|May|MAY|Jun|JUN|Jul|JUL|Aug|AUG|Sep|SEP|Oct|OCT|Nov|NOV|Dec|DEC)[\s{1}|\/|-]\d{4}$
</code>```

becomes

```<code>"^(3[0-1]|2[0-9]|1[0-9]|0[1-9])\/(Jan|JAN|Feb|FEB|Mar|MAR|Apr|APR|May|MAY|Jun|JUN|Jul|JUL|Aug|AUG|Sep|SEP|Oct|OCT|Nov|NOV|Dec|DEC)\/\d{4}$
</code>```

edit: there was a typo (a missing () in the 'new' regex in this answer which I've fixed.

Be aware that this does not resolve any problems regarding the number of days in different months (e.g. 30 Feb).  However I do not find that it matches "311apr}2011" as Hans has posited in the comments - any further comment?

This correctly addresses your question.  I do agree with the comments below that regex are a terrible tool for date validation, but I'm providing an answer rather than trying to give you general advice.

Body:
<asp:TextBox ID="txtDob" runat="server" MaxLength="100" CssClass="textbox2" size="10"  />
<ajax:TextBoxWatermarkExtender ID="txtWEDOB" WatermarkText="DD/MON/YYYY" TargetControlID="txtDob" runat="server" />
<asp:RegularExpressionValidator ID="rfv" runat="server" ControlToValidate="txtDob" SetFocusOnError="true"
ValidationExpression="^(3[0-1]|2[0-9]|1[0-9]|0[1-9])[\s{1}|\/|-](Jan|JAN|Feb|FEB|Mar|MAR|Apr|APR|May|MAY|Jun|JUN|Jul|JUL|Aug|AUG|Sep|SEP|Oct|OCT|Nov|NOV|Dec|DEC)[\s{1}|\/|-]\d{4}$"
Display="None" ValidationGroup="search" ErrorMessage="Please enter correct date">
</asp:RegularExpressionValidator>

I am using this regular expression validator for date. It is not giving error for like 12-FEB-2010 or 12 Feb 2010. I strictly want 12/FEB/2010 format. This Regular expressii\on is not working for date like 29/FEB/2010. what changes need to be made.

Body:
I assume you've cut-and-paste this regex from somewhere else?

This part ([\s{1}|\/|-]) is where your problem is.  This allows space (\s) and hyphen (-), as well as the / character.

It should instead be \/.  So your current regex

"^(3[0-1]|2[0-9]|1[0-9]|0[1-9])[\s{1}|\/|-](Jan|JAN|Feb|FEB|Mar|MAR|Apr|APR|May|MAY|Jun|JUN|Jul|JUL|Aug|AUG|Sep|SEP|Oct|OCT|Nov|NOV|Dec|DEC)[\s{1}|\/|-]\d{4}$

becomes

"^(3[0-1]|2[0-9]|1[0-9]|0[1-9])\/(Jan|JAN|Feb|FEB|Mar|MAR|Apr|APR|May|MAY|Jun|JUN|Jul|JUL|Aug|AUG|Sep|SEP|Oct|OCT|Nov|NOV|Dec|DEC)\/\d{4}$

edit: there was a typo (a missing () in the 'new' regex in this answer which I've fixed.

Be aware that this does not resolve any problems regarding the number of days in different months (e.g. 30 Feb).  However I do not find that it matches "311apr}2011" as Hans has posited in the comments - any further comment?

This correctly addresses your question.  I do agree with the comments below that regex are a terrible tool for date validation, but I'm providing an answer rather than trying to give you general advice.


问:
Why does Stream.reduce take BinaryOperator<T> rather than BiFunction<T, T, T>?
For my specific case I want to use functional composition in a reduction; for example:

```<code>BiFunction<ImmutableSet<Integer>, ImmutableSet<Integer>, Sets.SetView<Integer>> f = Sets::intersection;
Function<Sets.SetView<Integer>, ImmutableSet<Integer>> g = Sets.SetView::immutableCopy;
BiFunction<ImmutableSet<Integer>, ImmutableSet<Integer>, ImmutableSet<Integer>> biFunction = f.andThen(g);
ImmutableSet<Integer> intersection = Stream.of(ImmutableSet.of(1, 2, 3), ImmutableSet.of(1, 2), ImmutableSet.of(4))
    .reduce(biFunction)
    .orElse(ImmutableSet.of());
</code>```

This has a compilation error:

argument mismatch BiFunction cannot be converted to BinaryOperator
```

<p>Instead, I need to do:</p>

```ImmutableSet<Integer> intersection = Stream.of(ImmutableSet.of(1, 2, 3), ImmutableSet.of(1, 2), ImmutableSet.of(4))
    .reduce((a, b) -> Sets.intersection(a, b).immutableCopy())
    .orElse(ImmutableSet.of());
```

However, this loses the point-free style that composition provides.

Why is the Stream API is designed like this? A BinaryOperator is a BiFunction, so wouldn't it make more sense to declare the reduce method's parameter with the supertype?

答:
This is a lot simpler and relatable with the existing overload

```<code>Optional<T> reduce(BinaryOperator<T> accumulator)
</code>```

used in the question and can be used as in:

```<code>ImmutableSet<Integer> intersection = Stream.of(ImmutableSet.of(1, 2, 3), ImmutableSet.of(1, 2), ImmutableSet.of(4))
        .reduce(biFunction::apply)
        .orElse(ImmutableSet.of());
</code>```

Body:
For my specific case I want to use functional composition in a reduction; for example:

BiFunction<ImmutableSet<Integer>, ImmutableSet<Integer>, Sets.SetView<Integer>> f = Sets::intersection;
Function<Sets.SetView<Integer>, ImmutableSet<Integer>> g = Sets.SetView::immutableCopy;
BiFunction<ImmutableSet<Integer>, ImmutableSet<Integer>, ImmutableSet<Integer>> biFunction = f.andThen(g);
ImmutableSet<Integer> intersection = Stream.of(ImmutableSet.of(1, 2, 3), ImmutableSet.of(1, 2), ImmutableSet.of(4))
    .reduce(biFunction)
    .orElse(ImmutableSet.of());

This has a compilation error:

argument mismatch BiFunction cannot be converted to BinaryOperator

Instead, I need to do:

ImmutableSet<Integer> intersection = Stream.of(ImmutableSet.of(1, 2, 3), ImmutableSet.of(1, 2), ImmutableSet.of(4))
    .reduce((a, b) -> Sets.intersection(a, b).immutableCopy())
    .orElse(ImmutableSet.of());

However, this loses the point-free style that composition provides.

Why is the Stream API is designed like this? A BinaryOperator is a BiFunction, so wouldn't it make more sense to declare the reduce method's parameter with the supertype?

Body:
This is a lot simpler and relatable with the existing overload

Optional<T> reduce(BinaryOperator<T> accumulator)

used in the question and can be used as in:

ImmutableSet<Integer> intersection = Stream.of(ImmutableSet.of(1, 2, 3), ImmutableSet.of(1, 2), ImmutableSet.of(4))
        .reduce(biFunction::apply)
        .orElse(ImmutableSet.of());


问:
program to handle Heterogeneous Lists in Scala;
I have to find out the maximum/minimum from this list:

```<code> val data= List(List(1,2), List(3,4,91,9,10),11,211,456,345)
</code>```

From some stack over flow example ,i can see below solution:

```<code>val flatdata=data.collect{case i:Int => List(i); case l @ a :: b => l}.flatten
</code>```

[
But this is giving error]

Can some one please help.
want the solution using pure scala and not spark

答:
There's nothing wrong with your code, it evaluates fine. Not sure what error you're getting.

scala>  val data= List(List(1,2), List(3,4,91,9,10),11,211,456,345)
data: List[Any] = List(List(1, 2), List(3, 4, 91, 9, 10), 11, 211, 456, 345)

scala> data.collect{case i:Int => List(i); case l @ a :: b => l}
res0: List[List[Any]] = List(List(1, 2), List(3, 4, 91, 9, 10), List(11), List(211), List(456), List(345))

scala> data.collect{case i:Int => List(i); case l @ a :: b => l}.flatten
res1: List[Any] = List(1, 2, 3, 4, 91, 9, 10, 11, 211, 456, 345)
```

Body:
I have to find out the maximum/minimum from this list:

 val data= List(List(1,2), List(3,4,91,9,10),11,211,456,345)

From some stack over flow example ,i can see below solution:

val flatdata=data.collect{case i:Int => List(i); case l @ a :: b => l}.flatten

[
But this is giving error]

Can some one please help.
want the solution using pure scala and not spark


问:
How to select value from Oracle table having field name as default keyword
We have Oracle table having default keyword(i.e in as field name) field name.Now i am querying table but unable to extract specific field data.

```<code>select a.filename,a.in from table a
</code>```

Following error appears "invalid field name.

答:
You can use default (oracle reserved) keywords as the name of the columns but yes it is not advisable to use it.

Anyway, If you want to use oracle reserved keywords then you must have to enclose them in the double-quotes.

Note that oracle is case insensitive in terms of its object names until and unless it is wrapped in the double-quotes. it means if you enclose any object name in double-quotes then you must have to use them anywhere in the entire DB as case sensitive manner.

So if your table definition is:

```<code>CREATE TABLE YOUR_TABLE ("IN" NUMBER);
</code>```

Then you need to use "IN" wherever you want to refer the column but if your table definition is:

```<code>CREATE TABLE YOUR_TABLE ("in" NUMBER);
</code>```

Then you need to use "in" wherever you want to refer the column. -- case sensitive names.

I hope it will clear all your doubts.

Cheers!!

Body:
We have Oracle table having default keyword(i.e in as field name) field name.Now i am querying table but unable to extract specific field data.

select a.filename,a.in from table a

Following error appears "invalid field name.

Body:
You can use default (oracle reserved) keywords as the name of the columns but yes it is not advisable to use it.

Anyway, If you want to use oracle reserved keywords then you must have to enclose them in the double-quotes.

Note that oracle is case insensitive in terms of its object names until and unless it is wrapped in the double-quotes. it means if you enclose any object name in double-quotes then you must have to use them anywhere in the entire DB as case sensitive manner.

So if your table definition is:

CREATE TABLE YOUR_TABLE ("IN" NUMBER);

Then you need to use "IN" wherever you want to refer the column but if your table definition is:

CREATE TABLE YOUR_TABLE ("in" NUMBER);

Then you need to use "in" wherever you want to refer the column. -- case sensitive names.

I hope it will clear all your doubts.

Cheers!!


问:
Find the Diameter of an unweighted undirected graph
The diameter as in, the largest minimum distance between any two points in the graph.

To solve this, would we just do BFS from any node, and then choose a node among the farthest nodes from the original node. Do BFS on this new node, and then the largest distance here is the diameter of the graph.

Another post talks about weighted directed graphs. This is strictly for unweighted. Although the same algorithm might work here, I am asking if we can do it more efficiently w/ the algo I proposed here.

答:
diameter does exactly this.

```<code>G = nx.lollipop_graph(5, 5)
nx.diameter(G)
</code>```

Output: 6

Body:
diameter does exactly this.

G = nx.lollipop_graph(5, 5)
nx.diameter(G)

Output: 6


问:
Assistance in Pivoting Table Dynamic Rows to Dynamic Column
I have a table of data that needs the columns to be the EventId (the number of these can change, and so need to be dynamic) with the rows being Employee and the summary data of each EventId/Employee being the Sum(CallFee).

I was thinking a Pivot would work well for this however unsure how to do this with the dynamic number of Events. Any suggestions would be most appreciated.

The following is the source SQL

```<code>SELECT Group, Employee, EventId, CallFee
FROM A
GROUP BY Group, Employee
ORDER BY Employee
</code>```

This is the desired output:

This is the source table:

答:
Please use sample data preferably in text format instead of images for any code.

A PIVOT can help you to group rows and convert it into columns. But the result you are expecting I wonder whether you can get this thru PIVOT.

And if you are not sure about how PIVOT works, you can google for it before posting question to wide community forum. You can have a look at the PIVOT in SQL Server here.

Anyway, I think below sample should work for you.

```<code>SELECT
[Group],
[Employee],
ISNULL([21837], 0) AS [21837],
ISNULL([21838], 0) AS [21838],
ISNULL([21839], 0) AS [21839],
ISNULL([21840], 0) AS [21840],
ISNULL([21841], 0) AS [21841],
ISNULL([21837], 0) + ISNULL([21838], 0) + ISNULL([21839], 0) + ISNULL([21840], 0) + ISNULL([21841], 0) AS Total
FROM
(
    SELECT *
    FROM TableA
) AS T
PIVOT
(
    SUM(CallFee)
    FOR EventId IN ([21837], [21838], [21839], [21840], [21841])
) AS P
ORDER BY [Group];
</code>```

If the number of columns are not known, have a look at this thread. You can easily specify dynamic columns using stuff and many other ways.

Body:
I have a table of data that needs the columns to be the EventId (the number of these can change, and so need to be dynamic) with the rows being Employee and the summary data of each EventId/Employee being the Sum(CallFee).

I was thinking a Pivot would work well for this however unsure how to do this with the dynamic number of Events. Any suggestions would be most appreciated.

The following is the source SQL

SELECT Group, Employee, EventId, CallFee
FROM A
GROUP BY Group, Employee
ORDER BY Employee

This is the desired output:

This is the source table:

Body:
Please use sample data preferably in text format instead of images for any code.

A PIVOT can help you to group rows and convert it into columns. But the result you are expecting I wonder whether you can get this thru PIVOT.

And if you are not sure about how PIVOT works, you can google for it before posting question to wide community forum. You can have a look at the PIVOT in SQL Server here.

Anyway, I think below sample should work for you.

SELECT
[Group],
[Employee],
ISNULL([21837], 0) AS [21837],
ISNULL([21838], 0) AS [21838],
ISNULL([21839], 0) AS [21839],
ISNULL([21840], 0) AS [21840],
ISNULL([21841], 0) AS [21841],
ISNULL([21837], 0) + ISNULL([21838], 0) + ISNULL([21839], 0) + ISNULL([21840], 0) + ISNULL([21841], 0) AS Total
FROM
(
    SELECT *
    FROM TableA
) AS T
PIVOT
(
    SUM(CallFee)
    FOR EventId IN ([21837], [21838], [21839], [21840], [21841])
) AS P
ORDER BY [Group];

If the number of columns are not known, have a look at this thread. You can easily specify dynamic columns using stuff and many other ways.


问:
PHP jQuery ajax submit button not working
I would like to create a dynamic form with add and remove field using jquery and ajax. but unfortunately,my insert button supposedly go to insert.php wont work.When I click insert button,nothing is happened. When the insert button clicked,it will be redirect to insert.php store data inside the database.Here is my coding

repeater.js

```<code>
    jQuery.fn.extend({
        createRepeater: function (options = {}) {
            var hasOption = function (optionKey) {
                return options.hasOwnProperty(optionKey);
            };

            var option = function (optionKey) {
                return options[optionKey];
            };

            var generateId = function (string) {
                return string
                    .replace(/\[/g, '_')
                    .replace(/\]/g, '')
                    .toLowerCase();
            };

            var addItem = function (items, key, fresh = true) {
                var itemContent = items;
                var group = itemContent.data("group");
                var item = itemContent;
                var input = item.find('input,select');

                input.each(function (index, el) {
                    var attrName = $(el).data('name');
                    var skipName = $(el).data('skip-name');
                    if (skipName != true) {
                        $(el).attr("name", group + "[" + key + "]" + "[" + attrName + "]");
                    } else {
                        if (attrName != 'undefined') {
                            $(el).attr("name", attrName);
                        }
                    }
                    if (fresh == true) {
                        $(el).attr('value', '');
                    }

                    $(el).attr('id', generateId($(el).attr('name')));
                    $(el).parent().find('label').attr('for', generateId($(el).attr('name')));
                })

                var itemClone = items;

                /* Handling remove btn */
                var removeButton = itemClone.find('.remove-btn');

                if (key == 0) {
                    removeButton.attr('disabled', true);
                } else {
                    removeButton.attr('disabled', false);
                }

                removeButton.attr('onclick', '$(this).parents(\'.items\').remove()');

                var newItem = $("<div class='items'>" + itemClone.html() + "<div/>");
                newItem.attr('data-index', key)

                newItem.appendTo(repeater);
            };

            /* find elements */
            var repeater = this;
            var items = repeater.find(".items");
            var key = 0;
            var addButton = repeater.find('.repeater-add-btn');

            items.each(function (index, item) {
                items.remove();
                if (hasOption('showFirstItemToDefault') && option('showFirstItemToDefault') == true) {
                    addItem($(item), key);
                    key++;
                } else {
                    if (items.length > 1) {
                        addItem($(item), key);
                        key++;
                    }
                }
            });

            /* handle click and add items */
            addButton.on("click", function () {
                addItem($(items[0]), key);
                key++;
            });
        }
    });

</code>```

index.php

```<code><?php
//session_start();
$servername = "localhost";
$username = "root";
$password = "bptm2012";
$dbname = "icompex";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
$sql = "select panel_id,panel_kp,panel_nm from mem_panel";
$result = mysqli_query($conn, $sql);
?>
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Add Remove Panel Group and Category</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"
            integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ"
            crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="repeater.js" type="text/javascript"></script>

</head>
<body>
<div class="container">
    <br/>
    <h3 align="center">Kemaskini Ahli dan Kumpulan Panel Penilai</h3>
    <br/>
    <div style="width:100%; max-width: 600px; margin:0 auto;">
        <div class="panel panel-default">
            <div class="panel-heading">Menu Kumpulan dan Ahli Panel</div>
            <div class="panel-body">
                <span id="success_result"></span>
                <div id="div1"><h2></h2></div>

                <form method="post" id="repeater_form">
                    <div class="form-group">
                        <label>Pilih Group</label><br>
                        <select class="form-control" name="cat">

                            <option value="" disabled selected>Sila Pilih Kategori</option>
                            <option value="A">A - Rekabentuk Alam Bina & Rekabentuk Dalaman</option>
                            <option value="B">B - Pembinaan dan Bahan</option>
                            <option value="C">C - Mesin, Peralatan dan Proses Pergilangan</option>
                            <option value="D">D - ICT & Multimedia</option>
                            <option value="E">E - Elektrik, Elektronik dan Telekomunikasi</option>
                            <option value="F">F - Pengangkutan, Automatif & Penerbangan</option>
                            <option value="G">G - Pertanian, Alam Sekitar dan Tenaga Boleh Diperbaharui</option>
                            <option value="H">H - Pengajaran dan Pembelajaran</option>
                            <option value="I">I - Perkhidmatan dan Pemasaran Produk</option>
                        </select>
                        <label>Sila Pilih Kumpulan Panel</label><br>
                        <select name="group" class="form-control">
                            <option value="" disabled selected>Sila Pilih Kumpulan Panel</option>
                            <option value="1">Panel 1</option>
                            <option value="2">Panel 2</option>
                            <option value="3">Panel 3</option>
                            <option value="4">Panel 4</option>
                            <option value="5">Panel 5</option>
                            <option value="6">Panel 6</option>
                            <option value="7">Panel 7</option>
                            <option value="8">Panel 8</option>
                            <option value="9">Panel 9</option>
                            <option value="10">Panel 10</option>
                            <option value="11">Panel 11</option>
                            <option value="12">Panel 12</option>
                            <option value="13">Panel 13</option>
                            <option value="14">Panel 14</option>
                            <option value="15">Panel 15</option>
                        </select>
                    </div>
                    <div id="repeater">
                        <div class="repeater-heading" align="right">
                            <button type="button" class="btn btn-primary repeater-add-btn">Tambah Ahli</button>
                        </div>
                        <div class="clearfix"></div>
                        <div class="items" data-group="programming_languages">
                            <div class="item-content">
                                <div class="form-group">
                                    <div class="row">
                                        <div class="col-md-9">
                                            <label>Pilih Nama Ahli Panel</label>
                                            <select class="form-control" data-skip-name="true" data-name="skill[]"
                                                    required>
                                                <?php
                                                echo "<option>Sila Pilih Ahli Panel</option>";
                                                if (mysqli_num_rows($result) > 0) {
                                                    // output data of each row
                                                    while ($row = mysqli_fetch_assoc($result)) {
                                                        echo '<option value="' . $row['panel_id'] . '">' . $row['panel_nm'] . '</option>';
                                                    }
                                                } else {
                                                    echo "<option>Maaf Belum ada pendaftaran ahli panel dibuat</option>";
                                                }

                                                mysqli_close($conn);
                                                ?>
                                            </select>
                                        </div>
                                        <div class="col-md-3" style="margin-top:24px;" align="center">
                                            <button id="remove-btn" class="btn btn-danger"
                                                    onclick="$(this).parents('.items').remove()">Remove
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="clearfix"></div>
                    <div class="form-group" align="center">
                        <br/><br/>
                        <input type="submit" name="insert" class="btn btn-success" value="insert"/>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function () {

        $("#repeater").createRepeater();

        $('#repeater_form').on('submit', function (event) {
            event.preventDefault();
            $.ajax({
                url: "insert.php",
                method: "POST",
                data: $(this).serialize(),
                success: function (data) {
                    $('#repeater_form')[0].reset();
                    $("#repeater").createRepeater();
                    $('#success_result').html(data);
                    /*setInterval(function(){
                        location.reload();
                    }, 3000);*/
                }
            });
        });

    });

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

insert.php

```<code><?php

connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

if (isset($_POST["name"])) {
    $skill = implode(", ", $_POST["skill"]);

    $data = array(
        ':panel_cat' => $_POST["cat"],
        ':panel_group' => $_POST["group"],
        ':panel_mem' => $skill
    );

    $query = "
 INSERT INTO panel_penilai
 (panel_cat, panel_group,panel_mem)
 VALUES (:panel_cat, :panel_group, :panel_mem)
 ";

    $statement = $connect->prepare($query);
    if ($statement->execute($data)) {
        echo '
  <div class="alert alert-success">
   Data Successfully Inserted
  </div>
  ';
    }
}

//?>
</code>```

答:
You just change the submit button type to button

```<code><input type="submit" name="insert" class="btn btn-success" value="insert" />
change to
<input type="button" id="submit" name="insert" class="btn btn-success" value="insert" />
</code>```

And event must be click not submit

```<code>$('#repeater_form').on('submit', function(event){}
change to
$('#submit').on('click', function(event){}
</code>```

so page will not redirect, data  post throw ajax.

Body:
I would like to create a dynamic form with add and remove field using jquery and ajax. but unfortunately,my insert button supposedly go to insert.php wont work.When I click insert button,nothing is happened. When the insert button clicked,it will be redirect to insert.php store data inside the database.Here is my coding

repeater.js

    jQuery.fn.extend({
        createRepeater: function (options = {}) {
            var hasOption = function (optionKey) {
                return options.hasOwnProperty(optionKey);
            };

            var option = function (optionKey) {
                return options[optionKey];
            };

            var generateId = function (string) {
                return string
                    .replace(/\[/g, '_')
                    .replace(/\]/g, '')
                    .toLowerCase();
            };

            var addItem = function (items, key, fresh = true) {
                var itemContent = items;
                var group = itemContent.data("group");
                var item = itemContent;
                var input = item.find('input,select');

                input.each(function (index, el) {
                    var attrName = $(el).data('name');
                    var skipName = $(el).data('skip-name');
                    if (skipName != true) {
                        $(el).attr("name", group + "[" + key + "]" + "[" + attrName + "]");
                    } else {
                        if (attrName != 'undefined') {
                            $(el).attr("name", attrName);
                        }
                    }
                    if (fresh == true) {
                        $(el).attr('value', '');
                    }

                    $(el).attr('id', generateId($(el).attr('name')));
                    $(el).parent().find('label').attr('for', generateId($(el).attr('name')));
                })

                var itemClone = items;

                /* Handling remove btn */
                var removeButton = itemClone.find('.remove-btn');

                if (key == 0) {
                    removeButton.attr('disabled', true);
                } else {
                    removeButton.attr('disabled', false);
                }

                removeButton.attr('onclick', '$(this).parents(\'.items\').remove()');

                var newItem = $("
" + itemClone.html() + "
");
                newItem.attr('data-index', key)

                newItem.appendTo(repeater);
            };

            /* find elements */
            var repeater = this;
            var items = repeater.find(".items");
            var key = 0;
            var addButton = repeater.find('.repeater-add-btn');

            items.each(function (index, item) {
                items.remove();
                if (hasOption('showFirstItemToDefault') && option('showFirstItemToDefault') == true) {
                    addItem($(item), key);
                    key++;
                } else {
                    if (items.length > 1) {
                        addItem($(item), key);
                        key++;
                    }
                }
            });

            /* handle click and add items */
            addButton.on("click", function () {
                addItem($(items[0]), key);
                key++;
            });
        }
    });

index.php

<?php
//session_start();
$servername = "localhost";
$username = "root";
$password = "bptm2012";
$dbname = "icompex";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
$sql = "select panel_id,panel_kp,panel_nm from mem_panel";
$result = mysqli_query($conn, $sql);
?>
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Add Remove Panel Group and Category</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>

Kemaskini Ahli dan Kumpulan Panel Penilai

Menu Kumpulan dan Ahli Panel

                <form method="post" id="repeater_form">

                        Pilih Group

                        <select class="form-control" name="cat">

                            <option value="" disabled selected>Sila Pilih Kategori</option>
                            <option value="A">A - Rekabentuk Alam Bina & Rekabentuk Dalaman</option>
                            <option value="B">B - Pembinaan dan Bahan</option>
                            <option value="C">C - Mesin, Peralatan dan Proses Pergilangan</option>
                            <option value="D">D - ICT & Multimedia</option>
                            <option value="E">E - Elektrik, Elektronik dan Telekomunikasi</option>
                            <option value="F">F - Pengangkutan, Automatif & Penerbangan</option>
                            <option value="G">G - Pertanian, Alam Sekitar dan Tenaga Boleh Diperbaharui</option>
                            <option value="H">H - Pengajaran dan Pembelajaran</option>
                            <option value="I">I - Perkhidmatan dan Pemasaran Produk</option>
                        </select>
                        Sila Pilih Kumpulan Panel

                        <select name="group" class="form-control">
                            <option value="" disabled selected>Sila Pilih Kumpulan Panel</option>
                            <option value="1">Panel 1</option>
                            <option value="2">Panel 2</option>
                            <option value="3">Panel 3</option>
                            <option value="4">Panel 4</option>
                            <option value="5">Panel 5</option>
                            <option value="6">Panel 6</option>
                            <option value="7">Panel 7</option>
                            <option value="8">Panel 8</option>
                            <option value="9">Panel 9</option>
                            <option value="10">Panel 10</option>
                            <option value="11">Panel 11</option>
                            <option value="12">Panel 12</option>
                            <option value="13">Panel 13</option>
                            <option value="14">Panel 14</option>
                            <option value="15">Panel 15</option>
                        </select>

                            <button type="button" class="btn btn-primary repeater-add-btn">Tambah Ahli</button>

                                            Pilih Nama Ahli Panel
                                            <select class="form-control" data-skip-name="true" data-name="skill[]"
                                                    required>
                                                <?php
                                                echo "<option>Sila Pilih Ahli Panel</option>";
                                                if (mysqli_num_rows($result) > 0) {
                                                    // output data of each row
                                                    while ($row = mysqli_fetch_assoc($result)) {
                                                        echo '<option value="' . $row['panel_id'] . '">' . $row['panel_nm'] . '</option>';
                                                    }
                                                } else {
                                                    echo "<option>Maaf Belum ada pendaftaran ahli panel dibuat</option>";
                                                }

                                                mysqli_close($conn);
                                                ?>
                                            </select>

                                            <button id="remove-btn" class="btn btn-danger"
                                                    onclick="$(this).parents('.items').remove()">Remove
                                            </button>

                        <input type="submit" name="insert" class="btn btn-success" value="insert"/>

                </form>

insert.php

<?php

connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

if (isset($_POST["name"])) {
    $skill = implode(", ", $_POST["skill"]);

    $data = array(
        ':panel_cat' => $_POST["cat"],
        ':panel_group' => $_POST["group"],
        ':panel_mem' => $skill
    );

    $query = "
 INSERT INTO panel_penilai
 (panel_cat, panel_group,panel_mem)
 VALUES (:panel_cat, :panel_group, :panel_mem)
 ";

    $statement = $connect->prepare($query);
    if ($statement->execute($data)) {
        echo '

   Data Successfully Inserted

  ';
    }
}

//?>

Body:
You just change the submit button type to button

<input type="submit" name="insert" class="btn btn-success" value="insert" />
change to
<input type="button" id="submit" name="insert" class="btn btn-success" value="insert" />

And event must be click not submit

$('#repeater_form').on('submit', function(event){}
change to
$('#submit').on('click', function(event){}

so page will not redirect, data  post throw ajax.


问:
Interpreting the Kolmogorov-Smirnov test results to test if our data follows a Gamma distribution
Getting the result from the KS test:

from scipy import stats
stats.kstest(myarray, 'gamma', (a, b))

we conclude that myarray does not follow a gamma distribution in case p<0.01 (when rejecting the null hypothesis)?

In addition, when we calculate the a and b of the gamma distribution (used for comparing our data) from our data, we cannot use the KS test results?

答:
Yes - that's what the p value indicates - the probability of observing a KS statistic as extreme as this if my_array follows the gamma distribution is less than 1 percent.

I wouldn't say that it is meaningless, in the sense that deriving parameters and then doing a KS test on the same data is not the same as a tautology like 1 =1, but it is of not much value practically. It is best to use a different array for testing, and in case an array is not available - then you can do a parameter estimation on, say, 50 percent of the data and the KS test on the other 50 percent.

Also, this question is better suited for the stats.stackexchange.com forum


问:
AzureDevOps+Terraform - create agent job and job tasks
We have an existing AzureDevOps CI/CD. For every project, we have to manually set it up and add the job agent tasks one by one for each project.

Now, we decided to use IaC to auto deploy it using Terraform (as we have been using it for other projects as well). But there isn't much of documentation available there yet aside from this. It does have information on how to provision the project itself, but not the pipelines and other stuffs there, kind of limited at the moment, or I may have just not been able to find the complete documentation of the resources available.

We are keen to use Terraform for automating the creation of our CI/CD infrastructure, I just can't create agent jobs and tasks.

答:
we ended up creating our own forked off of this last year, and added things that were missing, like service connections and things like that.

However, for the pipelines and such Azure DevOps is expecting you to use azure-pipelines.yml for the actual pipeline definition.

To have a build defined by Terraform and Azure something like this would work:

```<code>resource "azuredevops_build_definition" "build_definition" {
  project_id = azuredevops_project.project.id
  name       = "My Awesome Build Pipeline"
  path       = "\\"

  repository {
    repo_type   = "TfsGit"
    repo_name   = azuredevops_azure_git_repository.repository.name
    branch_name = azuredevops_azure_git_repository.repository.default_branch
    yml_path    = "path to your azure-pipelines.yaml file in the repo"
  }
}
</code>```

So within the repo you are running the terraform from just have azure-pipeline.yaml describing the pipeline you wish to execute.

Damian Brady has a good blog on this from October 2 years ago:
https://damianbrady.com.au/2018/10/10/what-yaml-do-i-need-for-azure-pipelines/

There is also a lot of documentation around the supported Azure DevOps YAML Schema:
https://learn.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=azure-devops&tabs=schema

Once comfortable with the basics you can start to look towards using templates if there are seemingly common patterns you find:
https://learn.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=azure-devops&tabs=schema#template-references

Hope this helps!

Body:
we ended up creating our own forked off of this last year, and added things that were missing, like service connections and things like that.

However, for the pipelines and such Azure DevOps is expecting you to use azure-pipelines.yml for the actual pipeline definition.

To have a build defined by Terraform and Azure something like this would work:

resource "azuredevops_build_definition" "build_definition" {
  project_id = azuredevops_project.project.id
  name       = "My Awesome Build Pipeline"
  path       = "\\"

  repository {
    repo_type   = "TfsGit"
    repo_name   = azuredevops_azure_git_repository.repository.name
    branch_name = azuredevops_azure_git_repository.repository.default_branch
    yml_path    = "path to your azure-pipelines.yaml file in the repo"
  }
}

So within the repo you are running the terraform from just have azure-pipeline.yaml describing the pipeline you wish to execute.

Damian Brady has a good blog on this from October 2 years ago:
https://damianbrady.com.au/2018/10/10/what-yaml-do-i-need-for-azure-pipelines/

There is also a lot of documentation around the supported Azure DevOps YAML Schema:
https://learn.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=azure-devops&tabs=schema

Once comfortable with the basics you can start to look towards using templates if there are seemingly common patterns you find:
https://learn.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=azure-devops&tabs=schema#template-references

Hope this helps!


问:
I have a list Contacts that appears twice on a page and I only want to add a button to the list in the second occurrence of the list/app
I have a custom list called contacts that appears on a WIKI Page twice (next to each other). On the first instance (the left) will be a list of contacts that have a hyperlink to a RACI page.  On the second instance (the right), I have a list of maybe two contacts that are the result of a view that will display a list of support contacts.

The script that I have developed will find the contacts list and append a button to send an email to the applicable contact.  This same script will add the button to the first instance as well.  I only want my script to affect the second instance.

My script is:

```<code>var subjectType="";
var bodyText="";
$(document).ready(function() {

    // Get the subject type
    var this_js_script = $('script[src*=AddContactButtons]');
    subjectType = this_js_script.attr('data-Subject');
    if (typeof subjectType == 'undefined' || subjectType == null || subjectType == ''){
      subjectType = "Site";
    }
    //console.log('subjectType='+subjectType);
    buttonLabel = this_js_script.attr('data-Button');
    if (typeof buttonLabel == 'undefined' || buttonLabel == null || buttonLabel == ''){
      buttonLabel = "Help";
    }
    //console.log('buttonLabel='+buttonLabel);
    bodyText = this_js_script.attr('data-BodyText');
    if (typeof bodyText == 'undefined' || bodyText == null || bodyText == ''){
      bodyText = "";
    }
    //console.log('bodyText='+bodyText);
    buttoncolor = this_js_script.attr('data-ButtonColor');
    if (typeof buttoncolor == 'undefined' || buttoncolor == null || buttoncolor == ''){
      buttoncolor = "#004d99";
    }
    //console.log('buttoncolor='+buttoncolor);
    buttontextcolor = this_js_script.attr('data-ButtonTextColor');
    if (typeof buttontextcolor == 'undefined' || buttontextcolor == null || buttontextcolor == ''){
      buttontextcolor = "white";
    }
    //console.log('buttontextcolor='+buttontextcolor);
    addContactButtons(subjectType,bodyText,buttoncolor,buttontextcolor);
});
function addContactButtons(subjectType,bodyText,buttoncolor,buttontextcolor){
    var listTitle="Contacts";
    //console.log('addcontactButtons:subjectType='+subjectType);
    //console.log('addcontactButtons:bodyText='+bodyText);
    //console.log('addcontactButtons:buttoncolor='+buttoncolor);
    $("table.ms-listviewtable[summary='"+listTitle+"']>tbody>tr").each(function(){
        $(this).append("<input type='button' value='"+buttonLabel+"' style='background-color:"+buttoncolor+"; color:"+buttontextcolor+"' class='btnSub' onclick='javascript:openMail(this);'>");
    });
}
function openMail(btn){
    var emailString = "mailto:";
    var emailID = $(btn).prev("td").text()
    var URL = _spPageContextInfo.webServerRelativeUrl;
    //console.log('openMail:subjectType='+subjectType);
    //console.log('openMail:bodyText='+bodyText);
    //console.log('openMail:URL='+URL);

    emailString += emailID ;
    if (subjectType == 'Site'){
        emailString += "?Subject=SharePoint Site Support - Site=";
        //emailString += _spPageContextInfo.webServerRelativeUrl;
    } else {
        emailString += "?Subject="+subjectType;
    }
    if (bodyText != ''){
        emailString += "&Body="+bodyText;
    }
    var finalEmailString = emailString.replace(/Site=/,"Site="+URL);
    //console.log(finalEmailString);
    location.href=finalEmailString;
}
</code>```

What can I do to limit the scope of the script to only the second instance of the App Part?

答:
Try:

```<code>$("tbody>tr","table.ms-listviewtable[summary='MyList']:eq(1)").each(function () {
                $(this).append("<input type='button' value='value' class='btnSub' onclick='javascript:openMail(this);'/>");
            });
</code>```

Body:
I have a custom list called contacts that appears on a WIKI Page twice (next to each other). On the first instance (the left) will be a list of contacts that have a hyperlink to a RACI page.  On the second instance (the right), I have a list of maybe two contacts that are the result of a view that will display a list of support contacts.

The script that I have developed will find the contacts list and append a button to send an email to the applicable contact.  This same script will add the button to the first instance as well.  I only want my script to affect the second instance.

My script is:

var subjectType="";
var bodyText="";
$(document).ready(function() {

    // Get the subject type
    var this_js_script = $('script[src*=AddContactButtons]');
    subjectType = this_js_script.attr('data-Subject');
    if (typeof subjectType == 'undefined' || subjectType == null || subjectType == ''){
      subjectType = "Site";
    }
    //console.log('subjectType='+subjectType);
    buttonLabel = this_js_script.attr('data-Button');
    if (typeof buttonLabel == 'undefined' || buttonLabel == null || buttonLabel == ''){
      buttonLabel = "Help";
    }
    //console.log('buttonLabel='+buttonLabel);
    bodyText = this_js_script.attr('data-BodyText');
    if (typeof bodyText == 'undefined' || bodyText == null || bodyText == ''){
      bodyText = "";
    }
    //console.log('bodyText='+bodyText);
    buttoncolor = this_js_script.attr('data-ButtonColor');
    if (typeof buttoncolor == 'undefined' || buttoncolor == null || buttoncolor == ''){
      buttoncolor = "#004d99";
    }
    //console.log('buttoncolor='+buttoncolor);
    buttontextcolor = this_js_script.attr('data-ButtonTextColor');
    if (typeof buttontextcolor == 'undefined' || buttontextcolor == null || buttontextcolor == ''){
      buttontextcolor = "white";
    }
    //console.log('buttontextcolor='+buttontextcolor);
    addContactButtons(subjectType,bodyText,buttoncolor,buttontextcolor);
});
function addContactButtons(subjectType,bodyText,buttoncolor,buttontextcolor){
    var listTitle="Contacts";
    //console.log('addcontactButtons:subjectType='+subjectType);
    //console.log('addcontactButtons:bodyText='+bodyText);
    //console.log('addcontactButtons:buttoncolor='+buttoncolor);
    $("table.ms-listviewtable[summary='"+listTitle+"']>tbody>tr").each(function(){
        $(this).append("<input type='button' value='"+buttonLabel+"' style='background-color:"+buttoncolor+"; color:"+buttontextcolor+"' class='btnSub' onclick='javascript:openMail(this);'>");
    });
}
function openMail(btn){
    var emailString = "mailto:";
    var emailID = $(btn).prev("td").text()
    var URL = _spPageContextInfo.webServerRelativeUrl;
    //console.log('openMail:subjectType='+subjectType);
    //console.log('openMail:bodyText='+bodyText);
    //console.log('openMail:URL='+URL);

    emailString += emailID ;
    if (subjectType == 'Site'){
        emailString += "?Subject=SharePoint Site Support - Site=";
        //emailString += _spPageContextInfo.webServerRelativeUrl;
    } else {
        emailString += "?Subject="+subjectType;
    }
    if (bodyText != ''){
        emailString += "&Body="+bodyText;
    }
    var finalEmailString = emailString.replace(/Site=/,"Site="+URL);
    //console.log(finalEmailString);
    location.href=finalEmailString;
}

What can I do to limit the scope of the script to only the second instance of the App Part?

Body:
Try:

$("tbody>tr","table.ms-listviewtable[summary='MyList']:eq(1)").each(function () {
                $(this).append("<input type='button' value='value' class='btnSub' onclick='javascript:openMail(this);'/>");
            });


问:
How to check if a program is run in Bash on Ubuntu on Windows and not just plain Ubuntu?
Pretty straightforward, the usual places to figure out the OS you're on seem to be identical to plain Ubuntu on Ubuntu for Windows. For example uname -a is identical to a native GNU/Linux install and /etc/os-version is identical to a Ubuntu Trusty Tahr install.

The only thing I can think of is to check if /mnt/c/Windows exists, but I'm not sure if that's a foolproof idea.

答:
I needed to test for macOS in addition to Windows Subsystem for Linux 2.

This is the simplest thing working for us.

if [[ $OSTYPE == darwin* ]]; then
  # macOS
elif [[ "$(</proc/sys/kernel/osrelease)" == *microsoft* ]]; then
  # WSL2
else
  # Other *nix distro.
fi
```

NOTE: The if order matters. On macOS you get this error when looking at proc/version.

 /proc/version: No such file or directory

hat-tip @Niklas Holm and @Marc Cornellà in the top answer's comments for aiming me toward the correct WSL check.

Body:
I needed to test for macOS in addition to Windows Subsystem for Linux 2.

This is the simplest thing working for us.

if [[ $OSTYPE == darwin* ]]; then
  # macOS
elif [[ "$(</proc/sys/kernel/osrelease)" == *microsoft* ]]; then
  # WSL2
else
  # Other *nix distro.
fi

NOTE: The if order matters. On macOS you get this error when looking at proc/version.

 /proc/version: No such file or directory

hat-tip @Niklas Holm and @Marc Cornellà in the top answer's comments for aiming me toward the correct WSL check.


问:
How to increase heap memory of elasticsearch in Centos 7?
When we run elasticsearch in server then we face Broken pipe issue in elasticsearch.

"org.apache.catalina.connector.ClientAbortException: java.io.IOException: Broken pipe"

答:
We just increase the heap memory of the elasticsearch as given step.

First check current heap memory of elasticsearch.

ps aux | grep elasticsearch

"-Xms1g -Xmx1g"

Increase the size of heap Memory

vi /etc/sysconfig/elasticsearch

**Heap size defaults to 256m min, 1g max

Set ES_HEAP_SIZE to 50% of available RAM, but no more than 31g**

ES_HEAP_SIZE=3g

Check new heap memory

ps aux | grep elasticsearch

"-Xms3g -Xmx3g"