问:
Populating table with textbox value from previous HTML page
I have some JS that stores the name and value of selected checkboxes on one page and then, on a button click, adds this data to a table on page 2.

This works, but now I am looking to do the same for a textbox containing a number. Specifically, I'm looking to take the value entered by the user and add this to a cell in the table. What would be the best way to approach this? Add to the existing function or create a separate on button click function specifically for the textbox value?

I have added a screenshot of the HTML table on page 2 along with where I would like the textbox value to go (highlighted with a red rectangle).

Here's what I have so far:

HTML for textbox (page 1):

```<code><div class="selecttier">
  <h1>5. Number of Clicks</h1>
  <input id="numberofclickstextbox" name="numberofclicks" type="text" value="0" data-total="0" oninput="calculatetier()" />
</div>
</code>```

JS on page 1:

```<code>$('#sales_order_form_button').click(function() {
        let table_info = [];
        $('input[type=checkbox]').each(
            function(index, value) {
            if($(this).is(':checked')) {
                table_info.push(
                    {
                        name: $(this).attr('name'),
                        value: $(this).attr('value'),
                    }
                );
            }
        });
        let base64str=btoa(JSON.stringify(table_info));

        window.location = "page2.html?table_data=" + base64str;
        });
</code>```

JS on page 2:

```<code>// Helper function
        function getUrlParameter(name) {
            name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
            var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
            var results = regex.exec(location.href);
            return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, '    '));
        };

        // actual code
        let table_data = getUrlParameter('table_data');
        let data_from_page_1 = JSON.parse(atob(table_data));

        for(let i = 0; i < data_from_page_1.length; i++){
            let row = $("<tr></tr>");
            let recordName = $("<td></td>").text(data_from_page_1[i].name);
            let recordValue = $("<td></td>").text(data_from_page_1[i].value);
            row.append(recordName, recordValue);
            $('#output_table').append(row);
        }

        // code to sum CPC column
        var sum1 = 0;

        $("#output_table tr > td:nth-child(2)").each(
        (_,el) => sum1 += Number($(el).text()) || 0
        );

        $("#sum1").text(sum1);

        //datetime stamp
        var dt = new Date();
        document.getElementById("datetime").innerHTML = dt.toLocaleString();
</code>```

Output HTML table (page 2):

```<code><table id="output_table">
        <tr>
            <th>Name</th>
            <th>Value</th>
            <th>Number of Clicks</th>
        </tr>
        <tfoot>
            <tr>
                <th id="total" colspan="1">Total CPC:</th>
                <td id="sum1"></td>
            </tr>
    </tfoot>
    </table>
</code>```

答:
I highly recommend localStorage and sessionStorage to be used, as per this and this

Page 1 code full source

```<code>        $('#next_page_button').click(function(){
        let table_info = [];
        // Do for checkboxes
        $('.campaignstrategy input[type=checkbox]').each(
            function(index, value){
            if($(this).is(':checked')){
                table_info.push(
                    {
                        name: $(this).attr('name'),
                        value: $(this).attr('value'),
                        type: 'checkbox'
                    }
                );
            }
        });
        $('.campaignstrategy input[type=text]').each(
            function(index, value){
                table_info.push(
                {
                    name: $(this).attr('name'),
                    value: $(this).attr('value'),
                    type: 'text'
                }
            );
        });
        let base64str=btoa(JSON.stringify(table_info));
        window.location = "page2.html?table_data=" + base64str;
        });
</code>```

Page 2 Code full source

```<code>
        // Helper function
        function getUrlParameter(name) {
            name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
            var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
            var results = regex.exec(location.href);
            return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, '    '));
        };

        // actual code
        let table_data = getUrlParameter('table_data');
        let data_from_page_1 = JSON.parse(atob(table_data));

        // clear table
        $('#output_table').html("");

        // generator checboxes
        for(let i=0;i<data_from_page_1.length;i++){
            if(data_from_page_1[i].type == "checkbox"){
                let row = $("<tr></tr>");
                let recordName = $("<td></td>").text(data_from_page_1[i].name);
                let recordValue = $("<td></td>").text(data_from_page_1[i].value);
                let recordCount = $("<td></td>").text("");
                row.append(recordName, recordValue, recordCount); // not used but needed
                $('#output_table').append(row);
            }
        }

        // generate textboxes
        for(let i=0;i<data_from_page_1.length;i++){
            if(data_from_page_1[i].type == "text"){
                let row = $("<tr></tr>");
                let recordName = $("<td></td>").text("");
                let recordValue = $("<td></td>").text("");
                let recordCount = $("<td></td>").text(data_from_page_1[i].value);
                row.append(recordName, recordValue, recordCount);
                $('#output_table').append(row);
            }
        }
</code>```

Body:
I have some JS that stores the name and value of selected checkboxes on one page and then, on a button click, adds this data to a table on page 2.

This works, but now I am looking to do the same for a textbox containing a number. Specifically, I'm looking to take the value entered by the user and add this to a cell in the table. What would be the best way to approach this? Add to the existing function or create a separate on button click function specifically for the textbox value?

I have added a screenshot of the HTML table on page 2 along with where I would like the textbox value to go (highlighted with a red rectangle).

Here's what I have so far:

HTML for textbox (page 1):

5. Number of Clicks

  <input id="numberofclickstextbox" name="numberofclicks" type="text" value="0" data-total="0" oninput="calculatetier()" />

JS on page 1:

$('#sales_order_form_button').click(function() {
        let table_info = [];
        $('input[type=checkbox]').each(
            function(index, value) {
            if($(this).is(':checked')) {
                table_info.push(
                    {
                        name: $(this).attr('name'),
                        value: $(this).attr('value'),
                    }
                );
            }
        });
        let base64str=btoa(JSON.stringify(table_info));

        window.location = "page2.html?table_data=" + base64str;
        });

JS on page 2:

// Helper function
        function getUrlParameter(name) {
            name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
            var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
            var results = regex.exec(location.href);
            return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, '    '));
        };

        // actual code
        let table_data = getUrlParameter('table_data');
        let data_from_page_1 = JSON.parse(atob(table_data));

        for(let i = 0; i < data_from_page_1.length; i++){
            let row = $("

");
            let recordName = $("	").text(data_from_page_1[i].name);
            let recordValue = $("	").text(data_from_page_1[i].value);
            row.append(recordName, recordValue);
            $('#output_table').append(row);
        }

        // code to sum CPC column
        var sum1 = 0;

        $("#output_table tr > td:nth-child(2)").each(
        (_,el) => sum1 += Number($(el).text()) || 0
        );

        $("#sum1").text(sum1);

        //datetime stamp
        var dt = new Date();
        document.getElementById("datetime").innerHTML = dt.toLocaleString();

Output HTML table (page 2):

            Name
            Value
            Number of Clicks

                Total CPC:

Body:
I highly recommend localStorage and sessionStorage to be used, as per this and this

Page 1 code full source

        $('#next_page_button').click(function(){
        let table_info = [];
        // Do for checkboxes
        $('.campaignstrategy input[type=checkbox]').each(
            function(index, value){
            if($(this).is(':checked')){
                table_info.push(
                    {
                        name: $(this).attr('name'),
                        value: $(this).attr('value'),
                        type: 'checkbox'
                    }
                );
            }
        });
        $('.campaignstrategy input[type=text]').each(
            function(index, value){
                table_info.push(
                {
                    name: $(this).attr('name'),
                    value: $(this).attr('value'),
                    type: 'text'
                }
            );
        });
        let base64str=btoa(JSON.stringify(table_info));
        window.location = "page2.html?table_data=" + base64str;
        });

Page 2 Code full source

        // Helper function
        function getUrlParameter(name) {
            name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
            var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
            var results = regex.exec(location.href);
            return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, '    '));
        };

        // actual code
        let table_data = getUrlParameter('table_data');
        let data_from_page_1 = JSON.parse(atob(table_data));

        // clear table
        $('#output_table').html("");

        // generator checboxes
        for(let i=0;i<data_from_page_1.length;i++){
            if(data_from_page_1[i].type == "checkbox"){
                let row = $("<tr></tr>");
                let recordName = $("<td></td>").text(data_from_page_1[i].name);
                let recordValue = $("<td></td>").text(data_from_page_1[i].value);
                let recordCount = $("<td></td>").text("");
                row.append(recordName, recordValue, recordCount); // not used but needed
                $('#output_table').append(row);
            }
        }

        // generate textboxes
        for(let i=0;i<data_from_page_1.length;i++){
            if(data_from_page_1[i].type == "text"){
                let row = $("<tr></tr>");
                let recordName = $("<td></td>").text("");
                let recordValue = $("<td></td>").text("");
                let recordCount = $("<td></td>").text(data_from_page_1[i].value);
                row.append(recordName, recordValue, recordCount);
                $('#output_table').append(row);
            }
        }


来源: stackexchange

问:
FilesSystemWatcher For each item in List, look at that file
Goal:

The main goal is to get all path names from MySQL, and use File System Watch to watch them paths for rename, deleted and created.

I have this full code here:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using MySql.Data.MySqlClient;

namespace ConsoleApp1

{
    class Program
    {

        static void Main(string[] args)
        {

            Run();
        }

        public static void Run()
        {

            MySqlConnection mcon = new MySqlConnection("credentials");
            MySqlDataReader myreader = null;
            MySqlCommand cmd = new MySqlCommand("select * from files", mcon);
            mcon.Open();

            myreader = cmd.ExecuteReader();

            List<String> list = new List<String>();
            while (myreader.Read())
            {
                list.Add(myreader[1].ToString());

                foreach (string i in list)
                {
                    Console.WriteLine(i);
                    FileSystemWatcher watcher = new FileSystemWatcher();
                    watcher.Path = Path.GetDirectoryName($@"{i}");
                    watcher.Filter = Path.GetFileName($@"{i}");
                    watcher.EnableRaisingEvents = true;
                    watcher.IncludeSubdirectories = true;

                    watcher.Created += directoryChange;
                    watcher.Deleted += directoryChange;
                    watcher.Renamed += onRename;

                    Console.Read();
                }
            }
            mcon.Close();

        }

        private static void directoryChange(object source, System.IO.FileSystemEventArgs e)
        {
            Console.WriteLine($"{e.ChangeType} - {e.FullPath} - {System.Environment.NewLine}");
        }

        private static void onRename(object source, RenamedEventArgs e)
        {
            Console.WriteLine($"{e.OldFullPath} renamed to {e.FullPath}");
        }

    }
}
</code>```

And this is a table in MySQL:

```<code>ID                   Path
1   G:/Folder/EdGzi/Test purposes Python/file.txt
2   G:/Folder/EdGzi/Test purposes Python/test2.txt
</code>```

Problem:

When I run this application. It watches only 1 file(only the top record only from MySQL data). Whereas, it should have been watching all the files returned from MySQL table.

That's why I have created the foreach code.

Question:

How can I do this?

答:
Get rid of Console.Read from the loop, place it after the loop. That will Console.WriteLine(i); each record from MySQL table.

Like so:

```<code>public static void Run()
{
    MySqlConnection mcon = new MySqlConnection("server=WINX-PC04;user id=root;password=GS201706;database=technical");
    MySqlDataReader myreader = null;
    MySqlCommand cmd = new MySqlCommand("select * from files", mcon);
    mcon.Open();

    myreader = cmd.ExecuteReader();

    List<String> list = new List<String>();
    while (myreader.Read())
    {
        list.Add(myreader[1].ToString());
    }
    mcon.Close();

    foreach (string i in list)
    {
        Console.WriteLine(i);
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = Path.GetDirectoryName($@"{i}");
        watcher.Filter = Path.GetFileName($@"{i}");
        watcher.EnableRaisingEvents = true;
        watcher.IncludeSubdirectories = true;

        watcher.Created += directoryChange;
        watcher.Deleted += directoryChange;
        watcher.Renamed += onRename;
    }
    Console.Read(); // Likethis
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Goal:

The main goal is to get all path names from MySQL, and use File System Watch to watch them paths for rename, deleted and created.

I have this full code here:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using MySql.Data.MySqlClient;

namespace ConsoleApp1

{
    class Program
    {

        static void Main(string[] args)
        {

            Run();
        }

        public static void Run()
        {

            MySqlConnection mcon = new MySqlConnection("credentials");
            MySqlDataReader myreader = null;
            MySqlCommand cmd = new MySqlCommand("select * from files", mcon);
            mcon.Open();

            myreader = cmd.ExecuteReader();

            List<String> list = new List<String>();
            while (myreader.Read())
            {
                list.Add(myreader[1].ToString());

                foreach (string i in list)
                {
                    Console.WriteLine(i);
                    FileSystemWatcher watcher = new FileSystemWatcher();
                    watcher.Path = Path.GetDirectoryName($@"{i}");
                    watcher.Filter = Path.GetFileName($@"{i}");
                    watcher.EnableRaisingEvents = true;
                    watcher.IncludeSubdirectories = true;

                    watcher.Created += directoryChange;
                    watcher.Deleted += directoryChange;
                    watcher.Renamed += onRename;

                    Console.Read();
                }
            }
            mcon.Close();

        }

        private static void directoryChange(object source, System.IO.FileSystemEventArgs e)
        {
            Console.WriteLine($"{e.ChangeType} - {e.FullPath} - {System.Environment.NewLine}");
        }

        private static void onRename(object source, RenamedEventArgs e)
        {
            Console.WriteLine($"{e.OldFullPath} renamed to {e.FullPath}");
        }

    }
}

And this is a table in MySQL:

ID                   Path
1   G:/Folder/EdGzi/Test purposes Python/file.txt
2   G:/Folder/EdGzi/Test purposes Python/test2.txt

Problem:

When I run this application. It watches only 1 file(only the top record only from MySQL data). Whereas, it should have been watching all the files returned from MySQL table.

That's why I have created the foreach code.

Question:

How can I do this?

Body:
Get rid of Console.Read from the loop, place it after the loop. That will Console.WriteLine(i); each record from MySQL table.

Like so:

public static void Run()
{
    MySqlConnection mcon = new MySqlConnection("server=WINX-PC04;user id=root;password=GS201706;database=technical");
    MySqlDataReader myreader = null;
    MySqlCommand cmd = new MySqlCommand("select * from files", mcon);
    mcon.Open();

    myreader = cmd.ExecuteReader();

    List<String> list = new List<String>();
    while (myreader.Read())
    {
        list.Add(myreader[1].ToString());
    }
    mcon.Close();

    foreach (string i in list)
    {
        Console.WriteLine(i);
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = Path.GetDirectoryName($@"{i}");
        watcher.Filter = Path.GetFileName($@"{i}");
        watcher.EnableRaisingEvents = true;
        watcher.IncludeSubdirectories = true;

        watcher.Created += directoryChange;
        watcher.Deleted += directoryChange;
        watcher.Renamed += onRename;
    }
    Console.Read(); // Likethis
}


问:
Email notification when disk drive reaches a certain percentage? (Laravel)
I'd love to be able to monitor my disk drives automatically with email notifications. I'm using Laravel (and therefore it should be possible to schedule a task to check) this but I'm unsure how to go about checking the available disk size through Laravel/PHP code. Any ideas?

I did find this article (but it's not strictly what I want as it uses shell directly to send emails and I want a laravel scheduled task to send the emails whenever it finds the disk drive at a specified percentage): https://www.cyberciti.biz/tips/shell-script-to-watch-the-disk-space.html

答:
You can use disk_free_space() and  disk_total_space()</p>

```<code><?php
   define('MAX_LIMIT', 90);

   $diskRoot = "/"; // for unix/linux in case of windows use "C:" / "D:"

   $perSpace = (disk_free_space($diskRoot) / disk_total_space($diskRoot)) * 100;
   if(MAX_LIMIT < $perSpace) {
       //send email from here
   }
?>

</code>```

Body:
You can use disk_free_space() and  disk_total_space()

<?php
   define('MAX_LIMIT', 90);

   $diskRoot = "/"; // for unix/linux in case of windows use "C:" / "D:"

   $perSpace = (disk_free_space($diskRoot) / disk_total_space($diskRoot)) * 100;
   if(MAX_LIMIT < $perSpace) {
       //send email from here
   }
?>


问:
how to manage terraform state file in azure for preventing deletion and replacement
How to manage terraform state file in azure for preventing deletion and replacement,
just like arm templates.
I am deploying VMs with terraform and terraform plan and apply is replacing
my vms each time.</p>

答:
You could store Terraform state in Azure Storage from this tutorial, Azure Storage blobs are automatically locked before any operation that writes state.

If so, you will configure the state back end. The Terraform state back end is configured when you run the terraform init command. The following data is needed to configure the state back end:

storage_account_name: The name of the Azure Storage account.

container_name: The name of the blob container.

key: The name of the state store file to be created.

access_key: The storage access key.

Here is an example.

```<code>terraform {
  backend "azurerm" {
    resource_group_name   = "tstate"
    storage_account_name  = "tstate09762"
    container_name        = "tstate"
    key                   = "terraform.tfstate"
  }
}

resource "azurerm_resource_group" "state-demo-secure" {
  name     = "state-demo"
  location = "eastus"
}
</code>```

Body:
You could store Terraform state in Azure Storage from this tutorial, Azure Storage blobs are automatically locked before any operation that writes state.

If so, you will configure the state back end. The Terraform state back end is configured when you run the terraform init command. The following data is needed to configure the state back end:

storage_account_name: The name of the Azure Storage account.

container_name: The name of the blob container.

key: The name of the state store file to be created.

access_key: The storage access key.

Here is an example.

terraform {
  backend "azurerm" {
    resource_group_name   = "tstate"
    storage_account_name  = "tstate09762"
    container_name        = "tstate"
    key                   = "terraform.tfstate"
  }
}

resource "azurerm_resource_group" "state-demo-secure" {
  name     = "state-demo"
  location = "eastus"
}


问:
not able to access Django project through Docker Compose
I have created a simple Docker file for DJango project and when I issue docker run, I am able to access through browser.

docker run -p 8000:8000 s3bucket-ms:1

Here is the Docker File:

```<code>FROM python:3.6.7-alpine
ENV PYTHONUNBUFFERED 1
COPY ./requirements.txt /requirements.txt
RUN pip install --upgrade pip
RUN apk update \
    && apk add postgresql-dev gcc python3-dev musl-dev
RUN pip install -r requirements.txt
RUN mkdir /app
WORKDIR /app
ADD ./s3bucket /app/
EXPOSE 8000
CMD ["python", "./manage.py", "runserver", "0.0.0.0:8000"]
</code>```

However, when I am using Docker Compose , i can't access the project through the browser.

Here is the docker-compose.yml

```<code>version: '3'

services:
  web:
    build: .
    command: python ./manage.py runserver 8000
    ports:
      - "8000:8000"
</code>```

With Docker Compose , I also commented CMD within Docker File.
Output from Docker Compose UP

```<code>web_1  | Run 'python manage.py migrate' to apply them.
web_1  | February 17, 2020 - 14:29:22
web_1  | Django version 3.0.3, using settings 's3bucket.settings'
web_1  | Starting development server at http://127.0.0.1:8000/
web_1  | Quit the server with CONTROL-C.
</code>```

Am I missing something? Any help is appreciated.
Thanks,

答:
Add EXPOSE 8000 on your Dockerfile

Update1:

With docker run

```<code>docker run \
    -v /path/to/s3bucket:/app \ # absolute path
    -p 8000:8000 \
    s3bucket-ms:1
</code>```

With docker-compose

```<code>version: '3'

services:
  web:
    build: .
    command: python ./manage.py runserver 8000
    volumes:
      - /path/to/s3bucket:/app # absolute path
    ports:
      - "8000:8000"
</code>```

More infos on https://docs.docker.com/storage/volumes/

Body:
I have created a simple Docker file for DJango project and when I issue docker run, I am able to access through browser.

docker run -p 8000:8000 s3bucket-ms:1

Here is the Docker File:

FROM python:3.6.7-alpine
ENV PYTHONUNBUFFERED 1
COPY ./requirements.txt /requirements.txt
RUN pip install --upgrade pip
RUN apk update \
    && apk add postgresql-dev gcc python3-dev musl-dev
RUN pip install -r requirements.txt
RUN mkdir /app
WORKDIR /app
ADD ./s3bucket /app/
EXPOSE 8000
CMD ["python", "./manage.py", "runserver", "0.0.0.0:8000"]

However, when I am using Docker Compose , i can't access the project through the browser.

Here is the docker-compose.yml

version: '3'

services:
  web:
    build: .
    command: python ./manage.py runserver 8000
    ports:
      - "8000:8000"

With Docker Compose , I also commented CMD within Docker File.
Output from Docker Compose UP

web_1  | Run 'python manage.py migrate' to apply them.
web_1  | February 17, 2020 - 14:29:22
web_1  | Django version 3.0.3, using settings 's3bucket.settings'
web_1  | Starting development server at http://127.0.0.1:8000/
web_1  | Quit the server with CONTROL-C.

Am I missing something? Any help is appreciated.
Thanks,

Body:
Add EXPOSE 8000 on your Dockerfile

Update1:

With docker run

docker run \
    -v /path/to/s3bucket:/app \ # absolute path
    -p 8000:8000 \
    s3bucket-ms:1

With docker-compose

version: '3'

services:
  web:
    build: .
    command: python ./manage.py runserver 8000
    volumes:
      - /path/to/s3bucket:/app # absolute path
    ports:
      - "8000:8000"

More infos on https://docs.docker.com/storage/volumes/


问:
How many branches can be created in github/gitlab?
Are there any limitations to create branches in GitHub/GitLab?

I am currenly working on a project, so that I am curious about creation of branches.
   How many branches can be created ?

答:
By default there is no limit to the size of pack files, although git gets a bit sluggish if they are too large to fit nicely in memory. Git also has branches. Each branch is simply a text file that stores the 40-byte sha1 of the commit. Therefore, each branch takes up 40 bytes (but really, 4.0KB on disk).

For more info, you can read this link: Limit on number of git branches


问:
Install dll into the gac + .net 4.0
I want to add some .net 4.0 dlls to the gac, I know that the new gac is C:\Windows\Microsoft.NET\assembly

I cannot use the gacutil because visual studio in not installed on the deployment machine, and i cannot simply drag/drop the dll to the folder as i usually do in the previous versions.

How can I install the dlls to the GAC.

答:
Using Microsoft Installer Package. You can get download of installer from
http://www.microsoft.com.

I am not confirmed but ideally Gacutil must be part of framework and you can find it out in .net framework folder

ContentLicense: CC BY-SA 3.0

Title: Install dll into the gac + .net 4.0


问:
How to make an alert dialog fill 90% of screen size?
I can create and display a custom alert dialog just fine but even so I have android:layout_width/height="fill_parent" in the dialog xml it is only as big as the contents.

What I want is dialog that fills the entire screen except maybe a padding of 20 pixel.
Then the image that is part of the dialog would automatically stretch to the full dialog size with fill_parent.

答:
Just give the AlertDialog this theme</p>

```<code><style name="DialogTheme" parent="Theme.MaterialComponents.Light.Dialog.MinWidth">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="android:windowMinWidthMajor">90%</item>
    <item name="android:windowMinWidthMinor">90%</item>
</style>
</code>```

Body:
Just give the AlertDialog this theme

<style name="DialogTheme" parent="Theme.MaterialComponents.Light.Dialog.MinWidth">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="android:windowMinWidthMajor">90%</item>
    <item name="android:windowMinWidthMinor">90%</item>
</style>


问:
Android StrictMode Policy: A resource was acquired at attached stack trace but never released Error
I am using Image Compression method from this link it working fine if i compress single image but as soon as i give this method multiple images to compress in STRICT MODE app get crashed at ExifInterface exif = new ExifInterface(filePath); with logcat all i can understand something is not close which might cause leaks. I tried lots of things but none work it crashed everytime i give this method multiple images.

Image Compression Method

```<code> public static String compressImage(Uri imageUri, boolean multiple, Context context) {

        String   filePath = imageUri.getPath();

        Log.d(TAG,"File Path "+filePath);
        Bitmap scaledBitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();

//      by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If
//      you try the use the bitmap here, you will get null.
        options.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeFile(filePath, options);
        Log.d(TAG,"Bitmap value "+bmp);

        int actualHeight = options.outHeight;
        int actualWidth = options.outWidth;
        Log.d(TAG,"Actual Height and Width "+actualHeight+" "+actualWidth);

//      max Height and width values of the compressed image is taken as 816x612

        float maxHeight = 816.0f;
        float maxWidth = 612.0f;
        float imgRatio = actualWidth / actualHeight;
        float maxRatio = maxWidth / maxHeight;

//      width and height values are set maintaining the aspect ratio of the image

        if (actualHeight > maxHeight || actualWidth > maxWidth) {
            if (imgRatio < maxRatio) {               imgRatio = maxHeight / actualHeight;
                actualWidth = (int) (imgRatio * actualWidth);
                actualHeight = (int) maxHeight;
            } else if (imgRatio > maxRatio) {
                imgRatio = maxWidth / actualWidth;
                actualHeight = (int) (imgRatio * actualHeight);
                actualWidth = (int) maxWidth;
            } else {
                actualHeight = (int) maxHeight;
                actualWidth = (int) maxWidth;

            }
        }

//      setting inSampleSize value allows to load a scaled down version of the original image

        options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);

//      inJustDecodeBounds set to false to load the actual bitmap
        options.inJustDecodeBounds = false;

//      this options allow android to claim the bitmap memory if it runs low on memory
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inTempStorage = new byte[16 * 1024];

        try {
//          load the bitmap from its path
            bmp = BitmapFactory.decodeFile(filePath, options);
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();

        }
        try {
            scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight,Bitmap.Config.ARGB_8888);
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();
        }

        float ratioX = actualWidth / (float) options.outWidth;
        float ratioY = actualHeight / (float) options.outHeight;
        float middleX = actualWidth / 2.0f;
        float middleY = actualHeight / 2.0f;

        Matrix scaleMatrix = new Matrix();
        scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

        Canvas canvas = new Canvas(scaledBitmap);
        canvas.setMatrix(scaleMatrix);
        canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));

//      check the rotation of the image and display it properly

        try {
            ExifInterface exif = new ExifInterface(filePath);

            int orientation = exif.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION, 0);
            Log.d("EXIF", "Exif: " + orientation);
            Matrix matrix = new Matrix();
            if (orientation == 6) {
                matrix.postRotate(90);
                Log.d("EXIF", "Exif: " + orientation);
            } else if (orientation == 3) {
                matrix.postRotate(180);
                Log.d("EXIF", "Exif: " + orientation);
            } else if (orientation == 8) {
                matrix.postRotate(270);
                Log.d("EXIF", "Exif: " + orientation);
            }
            scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
                    scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix,
                    true);

            String filename = getFilename();
            FileOutputStream out = new FileOutputStream(filename);
//          write the compressed bitmap at the destination specified by filename.
            scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);

            return filename;

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
</code>```

Calling image compression method

```<code>for (int i = 0; i <size ; i++) {
                        String compressImage = App_Functions.compressImage(Uri.parse(attachmentPath.get(i).getImagePath()),true,this);
                        imageArray.add(compressImage);

                    }
</code>```

Error Log

```<code>02-17 17:55:28.124 21641-21649/com.Example.test E/StrictMode: A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
    java.lang.Throwable: Explicit termination method 'close' not called
        at dalvik.system.CloseGuard.open(CloseGuard.java:180)
        at java.io.FileInputStream.<init>(FileInputStream.java:78)
        at java.io.FileInputStream.<init>(FileInputStream.java:103)
        at android.media.ExifInterface.loadAttributes(ExifInterface.java:1338)
        at android.media.ExifInterface.<init>(ExifInterface.java:1057)
        at com.Example.App_Functions.compressImage(App_Functions.java:685)
        at com.Example.Navigation_Drawer.onBottomSheetClicked(Navigation_Drawer.java:851)
        at com.Example.mainScreenFragments.BottomSheet.onClick(BottomSheet.java:410)
        at android.view.View.performClick(View.java:5204)
        at android.view.View$PerformClick.run(View.java:21153)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
02-17 17:55:28.124 21641-21649/com.Example.test W/System.err: StrictMode VmPolicy violation with POLICY_DEATH; shutting down.
02-17 17:55:28.124 21641-21649/com.Example.test I/Process: Sending signal. PID: 21641 SIG: 9
</code>```

答:
When it comes to ExifInterface, always use one from a library, for a few reasons:

Devices older than Android 7.0 may have a security flaw in the framework copy of ExifInterface

The API changed over the years, and the library will give you a consistent API and functionality regardless of Android version

The framework team does not always test their code with StrictMode enabled, and device manufacturers make similar mistakes

Body:
I am using Image Compression method from this link it working fine if i compress single image but as soon as i give this method multiple images to compress in STRICT MODE app get crashed at ExifInterface exif = new ExifInterface(filePath); with logcat all i can understand something is not close which might cause leaks. I tried lots of things but none work it crashed everytime i give this method multiple images.

Image Compression Method

 public static String compressImage(Uri imageUri, boolean multiple, Context context) {

        String   filePath = imageUri.getPath();

        Log.d(TAG,"File Path "+filePath);
        Bitmap scaledBitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();

//      by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If
//      you try the use the bitmap here, you will get null.
        options.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeFile(filePath, options);
        Log.d(TAG,"Bitmap value "+bmp);

        int actualHeight = options.outHeight;
        int actualWidth = options.outWidth;
        Log.d(TAG,"Actual Height and Width "+actualHeight+" "+actualWidth);

//      max Height and width values of the compressed image is taken as 816x612

        float maxHeight = 816.0f;
        float maxWidth = 612.0f;
        float imgRatio = actualWidth / actualHeight;
        float maxRatio = maxWidth / maxHeight;

//      width and height values are set maintaining the aspect ratio of the image

        if (actualHeight > maxHeight || actualWidth > maxWidth) {
            if (imgRatio < maxRatio) {               imgRatio = maxHeight / actualHeight;
                actualWidth = (int) (imgRatio * actualWidth);
                actualHeight = (int) maxHeight;
            } else if (imgRatio > maxRatio) {
                imgRatio = maxWidth / actualWidth;
                actualHeight = (int) (imgRatio * actualHeight);
                actualWidth = (int) maxWidth;
            } else {
                actualHeight = (int) maxHeight;
                actualWidth = (int) maxWidth;

            }
        }

//      setting inSampleSize value allows to load a scaled down version of the original image

        options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);

//      inJustDecodeBounds set to false to load the actual bitmap
        options.inJustDecodeBounds = false;

//      this options allow android to claim the bitmap memory if it runs low on memory
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inTempStorage = new byte[16 * 1024];

        try {
//          load the bitmap from its path
            bmp = BitmapFactory.decodeFile(filePath, options);
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();

        }
        try {
            scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight,Bitmap.Config.ARGB_8888);
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();
        }

        float ratioX = actualWidth / (float) options.outWidth;
        float ratioY = actualHeight / (float) options.outHeight;
        float middleX = actualWidth / 2.0f;
        float middleY = actualHeight / 2.0f;

        Matrix scaleMatrix = new Matrix();
        scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

        Canvas canvas = new Canvas(scaledBitmap);
        canvas.setMatrix(scaleMatrix);
        canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));

//      check the rotation of the image and display it properly

        try {
            ExifInterface exif = new ExifInterface(filePath);

            int orientation = exif.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION, 0);
            Log.d("EXIF", "Exif: " + orientation);
            Matrix matrix = new Matrix();
            if (orientation == 6) {
                matrix.postRotate(90);
                Log.d("EXIF", "Exif: " + orientation);
            } else if (orientation == 3) {
                matrix.postRotate(180);
                Log.d("EXIF", "Exif: " + orientation);
            } else if (orientation == 8) {
                matrix.postRotate(270);
                Log.d("EXIF", "Exif: " + orientation);
            }
            scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
                    scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix,
                    true);

            String filename = getFilename();
            FileOutputStream out = new FileOutputStream(filename);
//          write the compressed bitmap at the destination specified by filename.
            scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);

            return filename;

        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

Calling image compression method

for (int i = 0; i <size ; i++) {
                        String compressImage = App_Functions.compressImage(Uri.parse(attachmentPath.get(i).getImagePath()),true,this);
                        imageArray.add(compressImage);

                    }

Error Log

02-17 17:55:28.124 21641-21649/com.Example.test E/StrictMode: A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
    java.lang.Throwable: Explicit termination method 'close' not called
        at dalvik.system.CloseGuard.open(CloseGuard.java:180)
        at java.io.FileInputStream.<init>(FileInputStream.java:78)
        at java.io.FileInputStream.<init>(FileInputStream.java:103)
        at android.media.ExifInterface.loadAttributes(ExifInterface.java:1338)
        at android.media.ExifInterface.<init>(ExifInterface.java:1057)
        at com.Example.App_Functions.compressImage(App_Functions.java:685)
        at com.Example.Navigation_Drawer.onBottomSheetClicked(Navigation_Drawer.java:851)
        at com.Example.mainScreenFragments.BottomSheet.onClick(BottomSheet.java:410)
        at android.view.View.performClick(View.java:5204)
        at android.view.View$PerformClick.run(View.java:21153)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
02-17 17:55:28.124 21641-21649/com.Example.test W/System.err: StrictMode VmPolicy violation with POLICY_DEATH; shutting down.
02-17 17:55:28.124 21641-21649/com.Example.test I/Process: Sending signal. PID: 21641 SIG: 9


问:
Observing class parameters in Android using databinding and Kotlin
I have a model

```<code>data class RegisterPostDataWithPwdCheck(
    var phone_number: String?,
    var name: String?,
    var password: String?,
    var secondPassword: String?)
</code>```

And a ViewModel

```<code>class SignUpViewModel(application: Application) : BaseViewModel(application){
        val registerPostData = MutableLiveData<RegisterPostDataWithPwdCheck>...
        fun checkPassword(){}...}
</code>```

I also have a View that has this code inside

```<code>viewModel.registerPostData.observe(viewLifecycleOwner, Observer {
    viewModel.checkPassword()
    })
</code>```

In the XML there are two fields of interest

```<code><EditText
android:id="@+id/edittext_sign_up_password"
android:text="@={view_model.registerPostData.password}" />
<EditText
android:id="@+id/edittext_sign_up_second_pw"
android:text="@={view_model.registerPostData.secondPassword}" />
</code>```

What I understood so far is that the .observe will be called only when the entire RegisterPostDataWithPwdCheck object changes and I don't want that. I want it to be triggered when any of the parameters changes so I can call the fun checkPassword(){} in order to see if the two fields match. Is this possible?

答:
Using @mahdi-shahbazi comment I've managed to work this out in Kotlin. My Model is now:

```<code>data class RegisterPostDataWithPwdCheck(
@SerializedName(value = "phone_number")
private var phoneNumber: String?,
private var name: String?,
private var password: String?,
private var secondPassword: String?
) : BaseObservable() {

@Bindable
fun getPhoneNumber(): String? {
    return phoneNumber
}

fun setPhoneNumber(value: String) {
    if (value != phoneNumber) {
        phoneNumber = value
        notifyPropertyChanged(BR.phoneNumber)
    }
}

@Bindable
fun getName(): String? {
    return name
}

fun setName(value: String?) {
    if (value != name) {
        name = value
        notifyPropertyChanged(BR.name)
    }
}

@Bindable
fun getPassword(): String? {
    return password
}

fun setPassword(value: String?) {
    if (value != password) {
        password = value
        notifyPropertyChanged(BR.password)
    }
}

@Bindable
fun getSecondPassword(): String? {
    return secondPassword
}

fun setSecondPassword(value: String?) {
    if (value != secondPassword) {
        secondPassword = value
        notifyPropertyChanged(BR.secondPassword)
    }
}
}
</code>```

And creating custom LiveData class:

```<code>class PropertyAwareMutableLiveData<T : BaseObservable> : MutableLiveData<T>()
{

private val callback = object : Observable.OnPropertyChangedCallback() {
    override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
        value = value
    }
}

override fun setValue(value: T?) {
    super.setValue(value)
    value?.addOnPropertyChangedCallback(callback)
}
}
</code>```

What I still don't know if there is a way to automate this @Binding process which is terribly slow and boring and also forces some changes (turning parameters to private).

Body:
I have a model

data class RegisterPostDataWithPwdCheck(
    var phone_number: String?,
    var name: String?,
    var password: String?,
    var secondPassword: String?)

And a ViewModel

class SignUpViewModel(application: Application) : BaseViewModel(application){
        val registerPostData = MutableLiveData<RegisterPostDataWithPwdCheck>...
        fun checkPassword(){}...}

I also have a View that has this code inside

viewModel.registerPostData.observe(viewLifecycleOwner, Observer {
    viewModel.checkPassword()
    })

In the XML there are two fields of interest

<EditText
android:id="@+id/edittext_sign_up_password"
android:text="@={view_model.registerPostData.password}" />
<EditText
android:id="@+id/edittext_sign_up_second_pw"
android:text="@={view_model.registerPostData.secondPassword}" />

What I understood so far is that the .observe will be called only when the entire RegisterPostDataWithPwdCheck object changes and I don't want that. I want it to be triggered when any of the parameters changes so I can call the fun checkPassword(){} in order to see if the two fields match. Is this possible?

Body:
Using @mahdi-shahbazi comment I've managed to work this out in Kotlin. My Model is now:

data class RegisterPostDataWithPwdCheck(
@SerializedName(value = "phone_number")
private var phoneNumber: String?,
private var name: String?,
private var password: String?,
private var secondPassword: String?
) : BaseObservable() {

@Bindable
fun getPhoneNumber(): String? {
    return phoneNumber
}

fun setPhoneNumber(value: String) {
    if (value != phoneNumber) {
        phoneNumber = value
        notifyPropertyChanged(BR.phoneNumber)
    }
}

@Bindable
fun getName(): String? {
    return name
}

fun setName(value: String?) {
    if (value != name) {
        name = value
        notifyPropertyChanged(BR.name)
    }
}

@Bindable
fun getPassword(): String? {
    return password
}

fun setPassword(value: String?) {
    if (value != password) {
        password = value
        notifyPropertyChanged(BR.password)
    }
}

@Bindable
fun getSecondPassword(): String? {
    return secondPassword
}

fun setSecondPassword(value: String?) {
    if (value != secondPassword) {
        secondPassword = value
        notifyPropertyChanged(BR.secondPassword)
    }
}
}

And creating custom LiveData class:

class PropertyAwareMutableLiveData<T : BaseObservable> : MutableLiveData<T>()
{

private val callback = object : Observable.OnPropertyChangedCallback() {
    override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
        value = value
    }
}

override fun setValue(value: T?) {
    super.setValue(value)
    value?.addOnPropertyChangedCallback(callback)
}
}

What I still don't know if there is a way to automate this @Binding process which is terribly slow and boring and also forces some changes (turning parameters to private).


问:
How to add array to the paramter with SimpleIoc in the MVVM Light?
I using MVVM light library in my project.
I trying to add an array to the constructor of the ViewModel.

For example... if the code below is

```<code>public MainViewModel(ToolWindowViewModel[] toolItems)
{
    // to do
}
</code>```

I would like to know a way that injects the array to the constructor of the MainViewModel with SimpleIoC class.

Is there a formulaic way to add an array with SimpleIoc class?

If it is, could someone tell me how to do?
If it is not, what is the best way in this scenario?

Thanks for reading.

答:
You could register a Func<MainViewModel> in the ViewModelLocator where you initialize the array:

```<code>public class ViewModelLocator
{
    public ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
        SimpleIoc.Default.Register(new System.Func<MainViewModel>(() => new MainViewModel(new ToolWindowViewModel[0])));
    }

    public MainViewModel Main
    {
        get
        {
            return ServiceLocator.Current.GetInstance<MainViewModel>();
        }
    }
}
</code>```

Body:
I using MVVM light library in my project.
I trying to add an array to the constructor of the ViewModel.

For example... if the code below is

public MainViewModel(ToolWindowViewModel[] toolItems)
{
    // to do
}

I would like to know a way that injects the array to the constructor of the MainViewModel with SimpleIoC class.

Is there a formulaic way to add an array with SimpleIoc class?

If it is, could someone tell me how to do?
If it is not, what is the best way in this scenario?

Thanks for reading.

Body:
You could register a Func<MainViewModel> in the ViewModelLocator where you initialize the array:

public class ViewModelLocator
{
    public ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
        SimpleIoc.Default.Register(new System.Func<MainViewModel>(() => new MainViewModel(new ToolWindowViewModel[0])));
    }

    public MainViewModel Main
    {
        get
        {
            return ServiceLocator.Current.GetInstance<MainViewModel>();
        }
    }
}


问:
Unable to create the first GCP project via API
I'm trying to create a Dialogflow Agent via API, It require a GCP project that also have to be created via API.

Actually both works well when the end user has already been once in the GCP console and accept the new terms and services.

The problem is that I would like to create the agent without the end user to have to perform any action on Google Cloud Platform.

Before it was possible, but it seems Google added a new terms of services for APIs on the GCP console that pop up the first time the user log in.

My question is, do you think there's any possibility to accepte those terms of services via Oauth or any other possibility?

Seems like Dialogflow still does it well.. so it should be possible :p

TY.

答: As stated by @John Hanley the user must login to accept the TOS so that the user-entity is bound to the Terms. Here you may find all the information regarding Google APIs Terms of Service.</p>


问:
Find column name in Pandas that contains a specific value in the row from another column
I have 200 plus columns by 10000 plus rows. I am trying to find the name of the column that contains a specific value in the row. In the example below, the specific value is in the value column. How I identified the value in the 'Value' column is not important.

Example: The Value_Col is the value I am trying to return.

```<code>Date   Time  A     B     C     D     E     F     Value   Value_Col
Jan1   1245  3.0   3.2   4.6   5.7   2.1   8.0   5.7     D
Jan2   1045  4.5   8.4   3.9   2.2   9.4   8.3   3.9     C
Jan3   1350  1.4   3.3   4.5   8.9   1.4   0.4   1.4     A
</code>```

I want to search only columns A through F and find the column name for the first instance (leftmost) the value exists. In the example, my value of interest appears twice in the row beginning with the Date of Jan3. I want to basically index the column names the value appears and select the first one. I understand this would be index 0 (or [0]) based on the list that is returned for the value search.

The example above is only a small subset of data. I currently have a list of all column names I want the value search to occur in. The value of interest can occur through many of the columns in the same row.

答:
I want to search only columns A through F and find the column name for the first instance (leftmost) the value exists

You can use idxmax on axis=1 after comparing Value column with the slice of the datframe (using .loc[])

```<code>df['Value_Col'] = df.loc[:,'A':'F'].isin(df['Value']).idxmax(1)
print(df)
</code>```

```<code>   Date  Time    A    B    C    D    E    F  Value Value_Col
0  Jan1  1245  3.0  3.2  4.6  5.7  2.1  8.0    5.7         D
1  Jan2  1045  4.5  8.4  3.9  2.2  9.4  8.3    3.9         C
2  Jan3  1350  1.4  3.3  4.5  8.9  1.4  0.4    1.4         A
</code>```

If there are chances that none of the column may contain the df['Value] value , you can use:

```<code>m = df.loc[:,'A':'F']
df['Value_Col'] = m.isin(df['Value']).dot(m.columns).str[0]
</code>```

Body:
I have 200 plus columns by 10000 plus rows. I am trying to find the name of the column that contains a specific value in the row. In the example below, the specific value is in the value column. How I identified the value in the 'Value' column is not important.

Example: The Value_Col is the value I am trying to return.

Date   Time  A     B     C     D     E     F     Value   Value_Col
Jan1   1245  3.0   3.2   4.6   5.7   2.1   8.0   5.7     D
Jan2   1045  4.5   8.4   3.9   2.2   9.4   8.3   3.9     C
Jan3   1350  1.4   3.3   4.5   8.9   1.4   0.4   1.4     A

I want to search only columns A through F and find the column name for the first instance (leftmost) the value exists. In the example, my value of interest appears twice in the row beginning with the Date of Jan3. I want to basically index the column names the value appears and select the first one. I understand this would be index 0 (or [0]) based on the list that is returned for the value search.

The example above is only a small subset of data. I currently have a list of all column names I want the value search to occur in. The value of interest can occur through many of the columns in the same row.

Body:
I want to search only columns A through F and find the column name for the first instance (leftmost) the value exists

You can use idxmax on axis=1 after comparing Value column with the slice of the datframe (using .loc[])

df['Value_Col'] = df.loc[:,'A':'F'].isin(df['Value']).idxmax(1)
print(df)

   Date  Time    A    B    C    D    E    F  Value Value_Col
0  Jan1  1245  3.0  3.2  4.6  5.7  2.1  8.0    5.7         D
1  Jan2  1045  4.5  8.4  3.9  2.2  9.4  8.3    3.9         C
2  Jan3  1350  1.4  3.3  4.5  8.9  1.4  0.4    1.4         A

If there are chances that none of the column may contain the df['Value] value , you can use:

m = df.loc[:,'A':'F']
df['Value_Col'] = m.isin(df['Value']).dot(m.columns).str[0]


问:
$ bundle update - error - Can't find the PostgreSQL client library (libpq) *** extconf.rb failed ***
I'm trying to run
$bundle update, but it errors after going through several gems with the following:

```<code>Installing pg (0.11.0) with native extensions /Library/Ruby/Site/1.8/rubygems/installer.rb:483:in `build_extensions': ERROR: Failed to build gem native extension. (Gem::Installer::ExtensionBuildError)

/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby extconf.rb
checking for pg_config... yes
Using config values from /opt/local/lib/postgresql83/bin/pg_config
checking for libpq-fe.h... yes
checking for libpq/libpq-fs.h... yes
checking for PQconnectdb() in -lpq... no
checking for PQconnectdb() in -llibpq... no
checking for PQconnectdb() in -lms/libpq... no
Can't find the PostgreSQL client library (libpq)
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby
    --with-pg
    --without-pg
    --with-pg-dir
    --without-pg-dir
    --with-pg-include
    --without-pg-include=${pg-dir}/include
    --with-pg-lib
    --without-pg-lib=${pg-dir}/lib
    --with-pg-config
    --without-pg-config
    --with-pg_config
    --without-pg_config
    --with-pqlib
    --without-pqlib
    --with-libpqlib
    --without-libpqlib
    --with-ms/libpqlib
    --without-ms/libpqlib

Gem files will remain installed in /Library/Ruby/Gems/1.8/gems/pg-0.11.0 for inspection.
Results logged to /Library/Ruby/Gems/1.8/gems/pg-0.11.0/ext/gem_make.out
    from /Library/Ruby/Site/1.8/rubygems/installer.rb:446:in `each'
    from /Library/Ruby/Site/1.8/rubygems/installer.rb:446:in `build_extensions'
    from /Library/Ruby/Site/1.8/rubygems/installer.rb:198:in `install'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/source.rb:100:in `install'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/installer.rb:55:in `run'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/spec_set.rb:12:in `each'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/spec_set.rb:12:in `each'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/installer.rb:44:in `run'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/installer.rb:8:in `install'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/cli.rb:252:in `update'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor/task.rb:22:in `send'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor/task.rb:22:in `run'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor/invocation.rb:118:in `invoke_task'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor.rb:246:in `dispatch'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor/base.rb:389:in `start'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/bin/bundle:13
    from /usr/bin/bundle:19:in `load'
    from /usr/bin/bundle:19
</code>```

Have you seen this or have any ideas on what's breaking here? thanks

答:
Worked by running: </p>

```<code>sudo bundle install
</code>```

Body:
I'm trying to run
$bundle update, but it errors after going through several gems with the following:

Installing pg (0.11.0) with native extensions /Library/Ruby/Site/1.8/rubygems/installer.rb:483:in `build_extensions': ERROR: Failed to build gem native extension. (Gem::Installer::ExtensionBuildError)

/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby extconf.rb
checking for pg_config... yes
Using config values from /opt/local/lib/postgresql83/bin/pg_config
checking for libpq-fe.h... yes
checking for libpq/libpq-fs.h... yes
checking for PQconnectdb() in -lpq... no
checking for PQconnectdb() in -llibpq... no
checking for PQconnectdb() in -lms/libpq... no
Can't find the PostgreSQL client library (libpq)
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby
    --with-pg
    --without-pg
    --with-pg-dir
    --without-pg-dir
    --with-pg-include
    --without-pg-include=${pg-dir}/include
    --with-pg-lib
    --without-pg-lib=${pg-dir}/lib
    --with-pg-config
    --without-pg-config
    --with-pg_config
    --without-pg_config
    --with-pqlib
    --without-pqlib
    --with-libpqlib
    --without-libpqlib
    --with-ms/libpqlib
    --without-ms/libpqlib

Gem files will remain installed in /Library/Ruby/Gems/1.8/gems/pg-0.11.0 for inspection.
Results logged to /Library/Ruby/Gems/1.8/gems/pg-0.11.0/ext/gem_make.out
    from /Library/Ruby/Site/1.8/rubygems/installer.rb:446:in `each'
    from /Library/Ruby/Site/1.8/rubygems/installer.rb:446:in `build_extensions'
    from /Library/Ruby/Site/1.8/rubygems/installer.rb:198:in `install'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/source.rb:100:in `install'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/installer.rb:55:in `run'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/spec_set.rb:12:in `each'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/spec_set.rb:12:in `each'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/installer.rb:44:in `run'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/installer.rb:8:in `install'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/cli.rb:252:in `update'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor/task.rb:22:in `send'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor/task.rb:22:in `run'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor/invocation.rb:118:in `invoke_task'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor.rb:246:in `dispatch'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor/base.rb:389:in `start'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/bin/bundle:13
    from /usr/bin/bundle:19:in `load'
    from /usr/bin/bundle:19

Have you seen this or have any ideas on what's breaking here? thanks

Body:
Worked by running:

sudo bundle install


问:
How to export and destructure an object?
I have reducer keys

```<code>const foo = {
    ADD: 1,
    REDO: 2,
    UNDO: 3,
}
</code>```

And I want to export it but when importing, I should be able to do

```<code>import MyComponent, { ADD, REDO } from '../bar'
</code>```

The only problem is that I already another thing to export

Here is what my code looks like

```<code>export default Component
export { Bar, ...foo} // can't do this, gives me syntax error
</code>```

答:
export { Bar, ...foo} // can't do this, gives me syntax error

Yes, that is a syntax error. Exports need names so you must do something like the following:

```<code>export Bar;
export foo;
</code>```

But this requires you to import foo:

```<code>import { foo } from '../bar'
</code>```

If you want to import ADD, REDO etc they must be their own named objects:

```<code>export const ADD = 1;
export const REDO = 2;
export const UNDO = 3;
</code>```

Body:
I have reducer keys

const foo = {
    ADD: 1,
    REDO: 2,
    UNDO: 3,
}

And I want to export it but when importing, I should be able to do

import MyComponent, { ADD, REDO } from '../bar'

The only problem is that I already another thing to export

Here is what my code looks like

export default Component
export { Bar, ...foo} // can't do this, gives me syntax error

Body:
export { Bar, ...foo} // can't do this, gives me syntax error

Yes, that is a syntax error. Exports need names so you must do something like the following:

export Bar;
export foo;

But this requires you to import foo:

import { foo } from '../bar'

If you want to import ADD, REDO etc they must be their own named objects:

export const ADD = 1;
export const REDO = 2;
export const UNDO = 3;


问:
Add/remove form inputs dynamically
I have a form with one initial empty input field that I want to clone using a Add button and to remove with a Remove one.

As it's not recommended to use index for the keys with dynamic forms, I tried to use uniqid module. But each time the state is updating, keys are renewed and I don't have unique data to identify each input of the form. I can add some items, but can't remove.

input fields have no unique values, no id, how can I do ?

```<code>const Form = () => {
  const update = e => {};
  const items = [{ content: "", color: "" }];

  return (
    <Fragment>
      {items.map((item, idx) => (
        <input
          htmlFor={`item_${idx}`}
          value={item.content}
          onChange={update("item", idx)}
        />
      ))}
      <button onClick={e => dispatch(add(idx))}>Add</button>
      <button onClick={e => dispatch(remove(idx))}>Remove</button>
    </Fragment>
  );
</code>```

答:
You may simply extend your existing items to have unique id property - at its very simplest, you may assign the value of maximum used id increased by 1 to that property - I guess, it'll do the trick for most of practical use cases:

```<code>const [inputs, setInputs] = useState([{id:0,value:''}]),
      onRowAdd = () => {
          const maxId = Math.max(...inputs.map(({id}) => id))
          setInputs([...inputs, {id:maxId+1, value:''}])
      }
</code>```

With that, you'll have unique id to anchor to as you delete rows:

```<code>onRowRemove = idToDelete => setInputs(inputs.filter(({id}) => id != idToDelete))
</code>```

Following is the demo of this concept:

const { useState } = React,
      { render } = ReactDOM

const Form = () => {
  const [inputs, setInputs] = useState([{id:0,value:''}]),
        onInput = (id,value) => {
          const inputsCopy = [...inputs],
                itemToModify = inputsCopy.find(item => item.id == id)
          itemToModify.value = value
          setInputs(inputsCopy)
        },
        onRowAdd = () => {
          const maxId = Math.max(...inputs.map(({id}) => id))
          setInputs([...inputs, {id:maxId+1, value:''}])
        },
        onRowRemove = idToDelete => setInputs(inputs.filter(({id}) => id != idToDelete)),
        onFormSubmit = e => (e.preventDefault(), console.log(inputs))
  return (
    <form onSubmit={onFormSubmit} >
      {
        inputs.map(({id,value}) => (

            <input
              onKeyUp={({target:{value}}) => onInput(id,value)}
            />
            <input type="button" onClick={onRowAdd} value="Add" />
            <input type="button" onClick={() => onRowRemove(id)} value="Remove" />

        ))
      }
      <input type="submit" value="Log Form Data" />
    </form>
  )
}

render (
  <Form />,
  document.getElementById('root')
)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div></code>```

Title: Add/remove form inputs dynamically

Body:
I have a form with one initial empty input field that I want to clone using a Add button and to remove with a Remove one.

As it's not recommended to use index for the keys with dynamic forms, I tried to use uniqid module. But each time the state is updating, keys are renewed and I don't have unique data to identify each input of the form. I can add some items, but can't remove.

input fields have no unique values, no id, how can I do ?

const Form = () => {
  const update = e => {};
  const items = [{ content: "", color: "" }];

  return (
    <Fragment>
      {items.map((item, idx) => (
        <input
          htmlFor={`item_${idx}`}
          value={item.content}
          onChange={update("item", idx)}
        />
      ))}
      <button onClick={e => dispatch(add(idx))}>Add</button>
      <button onClick={e => dispatch(remove(idx))}>Remove</button>
    </Fragment>
  );

Body:
You may simply extend your existing items to have unique id property - at its very simplest, you may assign the value of maximum used id increased by 1 to that property - I guess, it'll do the trick for most of practical use cases:

const [inputs, setInputs] = useState([{id:0,value:''}]),
      onRowAdd = () => {
          const maxId = Math.max(...inputs.map(({id}) => id))
          setInputs([...inputs, {id:maxId+1, value:''}])
      }

With that, you'll have unique id to anchor to as you delete rows:

onRowRemove = idToDelete => setInputs(inputs.filter(({id}) => id != idToDelete))

Following is the demo of this concept:

const { useState } = React,
      { render } = ReactDOM

const Form = () => {
  const [inputs, setInputs] = useState([{id:0,value:''}]),
        onInput = (id,value) => {
          const inputsCopy = [...inputs],
                itemToModify = inputsCopy.find(item => item.id == id)
          itemToModify.value = value
          setInputs(inputsCopy)
        },
        onRowAdd = () => {
          const maxId = Math.max(...inputs.map(({id}) => id))
          setInputs([...inputs, {id:maxId+1, value:''}])
        },
        onRowRemove = idToDelete => setInputs(inputs.filter(({id}) => id != idToDelete)),
        onFormSubmit = e => (e.preventDefault(), console.log(inputs))
  return (
    <form onSubmit={onFormSubmit} >
      {
        inputs.map(({id,value}) => (
          <div key={id}>
            <input
              onKeyUp={({target:{value}}) => onInput(id,value)}
            />
            <input type="button" onClick={onRowAdd} value="Add" />
            <input type="button" onClick={() => onRowRemove(id)} value="Remove" />
          </div>
        ))
      }
      <input type="submit" value="Log Form Data" />
    </form>
  )
}

render (
  <Form />,
  document.getElementById('root')
)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div>


问:
Unable to import maven project in IntelliJ14
I'm trying to import the Maven projects from IntelliJ button (the one with the arrows in circle), but I get the following message "Unable to import maven project. See logs for details", as shown in the following picture

If I go into the log, I see:

```<code>2015-06-01 11:16:46,932 [  89176]  ERROR -      #org.jetbrains.idea.maven - org/apache/maven/execution/MavenExecutionRequestPopulationException
java.lang.NoClassDefFoundError: org/apache/maven/execution/MavenExecutionRequestPopulationException
    at org.jetbrains.idea.maven.server.Maven32ServerImpl.applyProfiles(Maven32ServerImpl.java:81)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:322)
    at sun.rmi.transport.Transport$1.run(Transport.java:177)
    at sun.rmi.transport.Transport$1.run(Transport.java:174)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:173)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:556)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:811)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:670)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: org.apache.maven.execution.MavenExecutionRequestPopulationException
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    ... 16 more
2015-06-01 11:16:46,933 [  89177]  ERROR -      #org.jetbrains.idea.maven - IntelliJ IDEA 14.1.3  Build #IU-141.1010.3
2015-06-01 11:16:46,933 [  89177]  ERROR -      #org.jetbrains.idea.maven - JDK: 1.7.0_71
2015-06-01 11:16:46,933 [  89177]  ERROR -      #org.jetbrains.idea.maven - VM: Java HotSpot(TM) 64-Bit Server VM
2015-06-01 11:16:46,933 [  89177]  ERROR -      #org.jetbrains.idea.maven - Vendor: Oracle Corporation
2015-06-01 11:16:46,933 [  89177]  ERROR -      #org.jetbrains.idea.maven - OS: Linux
2015-06-01 11:16:46,933 [  89177]  ERROR -      #org.jetbrains.idea.maven - Last Action: Maven.Reimport
</code>```

I'm using Maven 3.3.3 and JDK 1.7.0_71 on a 64bit Ubuntu machine.

Strange thing, is that I can use Maven by command line. Any idea?

答: I had IntelliJ IDEA 2018.2 and maven 3.6.3 couldn't work. So I updated IntelliJ IDEA to a version 2019.3 and could use maven 3.6.3.</p>

Body:
I'm trying to import the Maven projects from IntelliJ button (the one with the arrows in circle), but I get the following message "Unable to import maven project. See logs for details", as shown in the following picture

If I go into the log, I see:

2015-06-01 11:16:46,932 [  89176]  ERROR -      #org.jetbrains.idea.maven - org/apache/maven/execution/MavenExecutionRequestPopulationException
java.lang.NoClassDefFoundError: org/apache/maven/execution/MavenExecutionRequestPopulationException
    at org.jetbrains.idea.maven.server.Maven32ServerImpl.applyProfiles(Maven32ServerImpl.java:81)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:322)
    at sun.rmi.transport.Transport$1.run(Transport.java:177)
    at sun.rmi.transport.Transport$1.run(Transport.java:174)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:173)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:556)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:811)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:670)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: org.apache.maven.execution.MavenExecutionRequestPopulationException
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    ... 16 more
2015-06-01 11:16:46,933 [  89177]  ERROR -      #org.jetbrains.idea.maven - IntelliJ IDEA 14.1.3  Build #IU-141.1010.3
2015-06-01 11:16:46,933 [  89177]  ERROR -      #org.jetbrains.idea.maven - JDK: 1.7.0_71
2015-06-01 11:16:46,933 [  89177]  ERROR -      #org.jetbrains.idea.maven - VM: Java HotSpot(TM) 64-Bit Server VM
2015-06-01 11:16:46,933 [  89177]  ERROR -      #org.jetbrains.idea.maven - Vendor: Oracle Corporation
2015-06-01 11:16:46,933 [  89177]  ERROR -      #org.jetbrains.idea.maven - OS: Linux
2015-06-01 11:16:46,933 [  89177]  ERROR -      #org.jetbrains.idea.maven - Last Action: Maven.Reimport

I'm using Maven 3.3.3 and JDK 1.7.0_71 on a 64bit Ubuntu machine.

Strange thing, is that I can use Maven by command line. Any idea?


问:
'pageshow' is not received when pressing "back" button on Safari on *IPad"
I have the following handler:

```<code>        $(window).bind('pageshow', function() { alert("back to page"); });
</code>```

When I navigate away from the page (by pressing on a link) and return back to the page (by pressing the "back" button), the alert() is not called (IPad 2, iOS 5.1).

What am I doing wrong please? Any other event I need to bind to?

PS: interesting that pagehide is received properly when navigating away from the page.

答:
I add the same problem where iOS does not always post the "pageshow" event when going back.

If not, safari resumes executing JS on the page so I though a timer would continue to fire.

So I came with this solution:

```<code>var timer;

function onPageBack() { alert("back to page"); }

window.addEventListener('pageshow', function() {
    if (event.persisted)
        onPageBack();

    // avoid calling onPageBack twice if 'pageshow' event has been fired...
    if (timer)
        clearInterval(timer);
});

// when page is hidden, start timer that will fire when going back to the page...
window.addEventListener('pagehide', function() {
    timer = setInterval(function() {
        clearInterval(timer);
        onPageBack();
    }, 100);
});
</code>```

Body:
I have the following handler:

        $(window).bind('pageshow', function() { alert("back to page"); });

When I navigate away from the page (by pressing on a link) and return back to the page (by pressing the "back" button), the alert() is not called (IPad 2, iOS 5.1).

What am I doing wrong please? Any other event I need to bind to?

PS: interesting that pagehide is received properly when navigating away from the page.

Body:
I add the same problem where iOS does not always post the "pageshow" event when going back.

If not, safari resumes executing JS on the page so I though a timer would continue to fire.

So I came with this solution:

var timer;

function onPageBack() { alert("back to page"); }

window.addEventListener('pageshow', function() {
    if (event.persisted)
        onPageBack();

    // avoid calling onPageBack twice if 'pageshow' event has been fired...
    if (timer)
        clearInterval(timer);
});

// when page is hidden, start timer that will fire when going back to the page...
window.addEventListener('pagehide', function() {
    timer = setInterval(function() {
        clearInterval(timer);
        onPageBack();
    }, 100);
});


问:
Converting text range to single integer
if I had a set of data containing the following:

```<code>0-3
0-3
0-3
2-6
2-6
2-6
2-6
2-6
1-3
</code>```

How would I covert this into a single number, say the upper value, or even better the average of the two numbers either side of the hyphen?

Any help would be much appreciated!

答:
You can use read.table to split on - and use rowMeans to get the mean.

```<code>x <- c("0-3", "2-6", "1-3")

rowMeans(read.table(text=x, sep="-"))
#[1] 1.5 4.0 2.0
</code>```

Title: Converting text range to single integer

Body:
if I had a set of data containing the following:

0-3
0-3
0-3
2-6
2-6
2-6
2-6
2-6
1-3

How would I covert this into a single number, say the upper value, or even better the average of the two numbers either side of the hyphen?

Any help would be much appreciated!

Body:
You can use read.table to split on - and use rowMeans to get the mean.

x <- c("0-3", "2-6", "1-3")

rowMeans(read.table(text=x, sep="-"))
#[1] 1.5 4.0 2.0


问:
Gson serialize null for specific class or field
I want to serialize nulls for a specific field or class.

In GSON, the option serializeNulls() applies to the whole JSON.

Example:

```<code>class MainClass {
    public String id;
    public String name;
    public Test test;
}

class Test {
    public String name;
    public String value;
}

MainClass mainClass = new MainClass();
mainClass.id = "101"
// mainClass has no name.
Test test = new Test();
test.name = "testName";
test.value = null;
mainClass.test = test;
</code>```

Creating JSON using GSON:

```<code>GsonBuilder builder = new GsonBuilder().serializeNulls();
Gson gson = builder.create();
System.out.println(gson.toJson(mainClass));
</code>```

Current ouput:

```<code>{
    "id": "101",
    "name": null,
    "test": {
        "name": "testName",
        "value": null
    }
}
</code>```

Desired output:

```<code>{
    "id": "101",
    "test": {
        "name": "testName",
        "value": null
    }
}
</code>```

How to achieve the desired output?

Preferred solution would have the following properties:

Do NOT serialize nulls by default,

Serialize nulls for fields with a specific annotation.

答:
I have a solution similar to the one of Aleksey but that can be applied to one or more fields in any class (example in Kotlin):

Create a new annotation for fields that should be serialized as null:

```<code>@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FIELD)
annotation class SerializeNull
</code>```

Create a TypeAdapterFactory that checks if a class has fields annotated with this annotation and removes the fields that are null and not annotated with the annotation from the JsonTree when writing the object:

class SerializableAsNullConverter : TypeAdapterFactory {

    override fun <T : Any?> create(gson: Gson, type: TypeToken<T>): TypeAdapter<T>? {
        fun Field.serializedName() = declaredAnnotations
            .filterIsInstance<SerializedName>()
            .firstOrNull()?.value ?: name
        val declaredFields = type.rawType.declaredFields
        val nullableFieldNames = declaredFields
            .filter { it.declaredAnnotations.filterIsInstance<SerializeNull>().isNotEmpty() }
            .map { it.serializedName() }
        val nonNullableFields = declaredFields.map { it.serializedName() } - nullableFieldNames

        return if (nullableFieldNames.isEmpty()) {
            null
        } else object : TypeAdapter<T>() {
            private val delegateAdapter = gson.getDelegateAdapter(this@SerializableAsNullConverter, type)
            private val elementAdapter = gson.getAdapter(JsonElement::class.java)

            override fun write(writer: JsonWriter, value: T?) {
                val jsonObject = delegateAdapter.toJsonTree(value).asJsonObject
                nonNullableFields
                    .filter { jsonObject.get(it) is JsonNull }
                    .forEach { jsonObject.remove(it) }
                val originalSerializeNulls = writer.serializeNulls
                writer.serializeNulls = true
                elementAdapter.write(writer, jsonObject)
                writer.serializeNulls = originalSerializeNulls
            }

            override fun read(reader: JsonReader): T {
                return delegateAdapter.read(reader)
            }
        }
    }
}
```

<p>Register the adapter with your Gson instance:</p>

```val builder = GsonBuilder().registerTypeAdapterFactory(SerializableAsNullConverter())
```

<p>And annotate the fields you would like to be nullable:</p>

```class MyClass(val id: String?, @SerializeNull val name: String?)
```

<p>Serialization result:</p>

```val myClass = MyClass(null, null)
val gson = builder.create()
val json = gson.toJson(myClass)
```

<p>json:</p>

```{
    "name": null
}
```

Body:
I want to serialize nulls for a specific field or class.

In GSON, the option serializeNulls() applies to the whole JSON.

Example:

class MainClass {
    public String id;
    public String name;
    public Test test;
}

class Test {
    public String name;
    public String value;
}

MainClass mainClass = new MainClass();
mainClass.id = "101"
// mainClass has no name.
Test test = new Test();
test.name = "testName";
test.value = null;
mainClass.test = test;

Creating JSON using GSON:

GsonBuilder builder = new GsonBuilder().serializeNulls();
Gson gson = builder.create();
System.out.println(gson.toJson(mainClass));

Current ouput:

{
    "id": "101",
    "name": null,
    "test": {
        "name": "testName",
        "value": null
    }
}

Desired output:

{
    "id": "101",
    "test": {
        "name": "testName",
        "value": null
    }
}

How to achieve the desired output?

Preferred solution would have the following properties:

Do NOT serialize nulls by default,

Serialize nulls for fields with a specific annotation.

Body:
I have a solution similar to the one of Aleksey but that can be applied to one or more fields in any class (example in Kotlin):

Create a new annotation for fields that should be serialized as null:

@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FIELD)
annotation class SerializeNull

Create a TypeAdapterFactory that checks if a class has fields annotated with this annotation and removes the fields that are null and not annotated with the annotation from the JsonTree when writing the object:

class SerializableAsNullConverter : TypeAdapterFactory {

    override fun <T : Any?> create(gson: Gson, type: TypeToken<T>): TypeAdapter<T>? {
        fun Field.serializedName() = declaredAnnotations
            .filterIsInstance<SerializedName>()
            .firstOrNull()?.value ?: name
        val declaredFields = type.rawType.declaredFields
        val nullableFieldNames = declaredFields
            .filter { it.declaredAnnotations.filterIsInstance<SerializeNull>().isNotEmpty() }
            .map { it.serializedName() }
        val nonNullableFields = declaredFields.map { it.serializedName() } - nullableFieldNames

        return if (nullableFieldNames.isEmpty()) {
            null
        } else object : TypeAdapter<T>() {
            private val delegateAdapter = gson.getDelegateAdapter(this@SerializableAsNullConverter, type)
            private val elementAdapter = gson.getAdapter(JsonElement::class.java)

            override fun write(writer: JsonWriter, value: T?) {
                val jsonObject = delegateAdapter.toJsonTree(value).asJsonObject
                nonNullableFields
                    .filter { jsonObject.get(it) is JsonNull }
                    .forEach { jsonObject.remove(it) }
                val originalSerializeNulls = writer.serializeNulls
                writer.serializeNulls = true
                elementAdapter.write(writer, jsonObject)
                writer.serializeNulls = originalSerializeNulls
            }

            override fun read(reader: JsonReader): T {
                return delegateAdapter.read(reader)
            }
        }
    }
}

Register the adapter with your Gson instance:

val builder = GsonBuilder().registerTypeAdapterFactory(SerializableAsNullConverter())

And annotate the fields you would like to be nullable:

class MyClass(val id: String?, @SerializeNull val name: String?)

Serialization result:

val myClass = MyClass(null, null)
val gson = builder.create()
val json = gson.toJson(myClass)

json:

{
    "name": null
}


问:
My UIElements are not showing after I set gradient to UIView
i set my view to have a gradient background with this code

```<code>let gradientLayer = CAGradientLayer()
        gradientLayer.frame = view.bounds
        gradientLayer.colors = [#colorLiteral(red: 0, green: 0.2836692631, blue: 0.456893146, alpha: 1).cgColor, UIColor(red: 0/255, green: 237/255, blue: 255/255, alpha: 1).cgColor]
        view.layer.addSublayer(gradientLayer)
</code>```

But when i do that , all my other elements like UIButton and UILabels will not appear. how can i solve that?

答:
You need to insert it as a sublayer.

Check my UIView's Extension.

```<code>extension UIView {
  func setGradientBackgroundColor(colorOne: UIColor, colorTow: UIColor) {
    let gradientLayer = CAGradientLayer()
    gradientLayer.frame = bounds
    gradientLayer.colors = [colorOne.cgColor, colorTow.cgColor]
    gradientLayer.locations = [0.0, 1.0]
    gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
    gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
    layer.insertSublayer(gradientLayer, at: 0)
  }
}
</code>```

You can use it like this:

```<code>myview.setGradientBackgroundColor(colorOne: firstColor, colorTow: secondColor])
</code>```

Body:
i set my view to have a gradient background with this code

let gradientLayer = CAGradientLayer()
        gradientLayer.frame = view.bounds
        gradientLayer.colors = [#colorLiteral(red: 0, green: 0.2836692631, blue: 0.456893146, alpha: 1).cgColor, UIColor(red: 0/255, green: 237/255, blue: 255/255, alpha: 1).cgColor]
        view.layer.addSublayer(gradientLayer)

But when i do that , all my other elements like UIButton and UILabels will not appear. how can i solve that?

Body:
You need to insert it as a sublayer.

Check my UIView's Extension.

extension UIView {
  func setGradientBackgroundColor(colorOne: UIColor, colorTow: UIColor) {
    let gradientLayer = CAGradientLayer()
    gradientLayer.frame = bounds
    gradientLayer.colors = [colorOne.cgColor, colorTow.cgColor]
    gradientLayer.locations = [0.0, 1.0]
    gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
    gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
    layer.insertSublayer(gradientLayer, at: 0)
  }
}

You can use it like this:

myview.setGradientBackgroundColor(colorOne: firstColor, colorTow: secondColor])


问:
How to debug Laravel API request from ReactJs (Another Project) client?
I have two projects one is developed by reactjs another one is by laravel. I want to get some data from the laravel project therefore, I access a method that is inside the laravel project controller folder via api call. if I hit the method from reactjs project, how to debug laravel project? </p>

答:
the best tool is Laravel Telescope

and Take a look Laravel Debugbar


问:
Stop input from losing focus on Virtual keyboard click
I've created a custom virtual keyboard for a kiosk application. The problem is every time you click on keyboard keys, input field loses its focus.
Any help would be appreciated. </p>

答:
Prevents focusing the element then returns focus to the desired field.</p>

```<code>$('#div').on('mousedown', function(event) {
   event.preventDefault();
   $('#field').focus();
});
</code>```

Body:
Prevents focusing the element then returns focus to the desired field.

$('#div').on('mousedown', function(event) {
   event.preventDefault();
   $('#field').focus();
});