问:
Mdb datatable does not rendering data in Vue.js
I'm trying to implement a datatable with mdbootstrap in vue.js.
I would like to update table data on events and when initialized but it does not work.

Template;

```<code> <div class="col-md-12">
        <mdb-datatable
                :data="data"
                striped
                bordered
        />

    </div>
</code>```

Script;

```<code>    import { mdbDatatable } from 'mdbvue';
export default {

    name: 'userManagement',
    components: {
        mdbDatatable
    },
    data() {
        return {
            className:"",
            classList: [],

            data: {
                columns: [
                    {
                        label: 'Name',
                        field: 'className',
                        sort: 'asc'
                    }, {
                        label: 'ID',
                        field: 'id',
                        sort: 'asc'
                    }
                ],
                rows: [
                    {
                        className: 'Tiger Nixon',
                        id:1
                    },
                    {
                        className: 'Garrett Winters',
                        id:2
                    }
                ]
            }
        }
    },
    methods: {

        getClassList(){
            var _this = this;
            this.$axios.get('my_url/admin/classes').then(function (response) {
                if (response.status === 200) {

                    _this.data.rows = [];
                    response.data.forEach(function (obj) {
                        let item = {
                            className: obj.className,
                            id: obj.id
                        };
                        _this.data.rows.push(item);
                    });
                }
            }).catch(function (err) {
                alert("" + err);
            });
        }
    },
    mounted(){
        this.getClassList();
    },
</code>```

It always shows default values, I check the data rows from console the value seems to be updated but no change on the datatable.

Any help would be appreciated.

答:
We've found the solution for Your issue.
The new code is available here: https://mdbootstrap.com/docs/vue/tables/datatables/#external-api

Also to make sure the data is reactive it's necessary to add the following code to the Datatable component in our package:

```<code>watch: {
    data(newVal) {
      this.columns = newVal.columns;
    },
    (...)
}
</code>```

It will be fixed in the next MDB Vue release.

Body:
I'm trying to implement a datatable with mdbootstrap in vue.js.
I would like to update table data on events and when initialized but it does not work.

Template;

        <mdb-datatable
                :data="data"
                striped
                bordered
        />

Script;

    import { mdbDatatable } from 'mdbvue';
export default {

    name: 'userManagement',
    components: {
        mdbDatatable
    },
    data() {
        return {
            className:"",
            classList: [],

            data: {
                columns: [
                    {
                        label: 'Name',
                        field: 'className',
                        sort: 'asc'
                    }, {
                        label: 'ID',
                        field: 'id',
                        sort: 'asc'
                    }
                ],
                rows: [
                    {
                        className: 'Tiger Nixon',
                        id:1
                    },
                    {
                        className: 'Garrett Winters',
                        id:2
                    }
                ]
            }
        }
    },
    methods: {

        getClassList(){
            var _this = this;
            this.$axios.get('my_url/admin/classes').then(function (response) {
                if (response.status === 200) {

                    _this.data.rows = [];
                    response.data.forEach(function (obj) {
                        let item = {
                            className: obj.className,
                            id: obj.id
                        };
                        _this.data.rows.push(item);
                    });
                }
            }).catch(function (err) {
                alert("" + err);
            });
        }
    },
    mounted(){
        this.getClassList();
    },

It always shows default values, I check the data rows from console the value seems to be updated but no change on the datatable.

Any help would be appreciated.

Body:
We've found the solution for Your issue.
The new code is available here: https://mdbootstrap.com/docs/vue/tables/datatables/#external-api

Also to make sure the data is reactive it's necessary to add the following code to the Datatable component in our package:

watch: {
    data(newVal) {
      this.columns = newVal.columns;
    },
    (...)
}

It will be fixed in the next MDB Vue release.


来源: stackexchange

问:
LabelSelector for Secrets List in k8s
I want to get Secret object from k8s cluster using go-client API

I have function that looks like that

```<code>func GetSecret( version string) (retVal interface{}, err error){
    clientset := GetClientOutOfCluster()
    labelSelector := metav1.LabelSelector{MatchLabels: map[string]string{"version":version}}

    listOptions := metav1.ListOptions{
        LabelSelector: labelSelector.String(),
        Limit:         100,
    }
    secretList, err := clientset.CoreV1().Secrets("namespace").List( listOptions )
    retVal = secretList.Items[0]
    return retVal, err
}
</code>```

GetClientOutOfCluster is basically retrieves configuration from cluster or from local ~/.kube/config

I used metav1.LabelSelector just like i do when i generate new Deployment object.So i thought i was cool. But ListOptions.LabelSelector is a string.
When i run my function it fails.

```<code>unable to parse requirement: invalid label key "&LabelSelector{MatchLabels:map[string]string{version:": name part must consist of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character (e.g. 'MyName',  or 'my.name',  or '123-abc', regex used for validation is '([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]')
</code>```

I cannot find example of usage of this function anywhere. Documentation assumes that you know what is LabelSelector.

What is format of LabelSelector for ListOptions?

Thanks

答:
You can use the k8s provided function to do the toString operation</p>

```<code>import "k8s.io/apimachinery/pkg/labels"
...

func GetSecret(version string) (retVal interface{}, err error){
  clientset := GetClientOutOfCluster()
  labelSelector := metav1.LabelSelector{MatchLabels: map[string]string{"version":version}}

  listOptions := metav1.ListOptions{
    LabelSelector: labels.Set(labelSelector.MatchLabels).String(),
    Limit:         100,
  }
  secretList, err := clientset.CoreV1().Secrets("namespace").List(listOptions)
  retVal = secretList.Items[0]
  return retVal, err
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: LabelSelector for Secrets List in k8s

Body:
I want to get Secret object from k8s cluster using go-client API

I have function that looks like that

func GetSecret( version string) (retVal interface{}, err error){
    clientset := GetClientOutOfCluster()
    labelSelector := metav1.LabelSelector{MatchLabels: map[string]string{"version":version}}

    listOptions := metav1.ListOptions{
        LabelSelector: labelSelector.String(),
        Limit:         100,
    }
    secretList, err := clientset.CoreV1().Secrets("namespace").List( listOptions )
    retVal = secretList.Items[0]
    return retVal, err
}

GetClientOutOfCluster is basically retrieves configuration from cluster or from local ~/.kube/config

I used metav1.LabelSelector just like i do when i generate new Deployment object.So i thought i was cool. But ListOptions.LabelSelector is a string.
When i run my function it fails.

unable to parse requirement: invalid label key "&LabelSelector{MatchLabels:map[string]string{version:": name part must consist of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character (e.g. 'MyName',  or 'my.name',  or '123-abc', regex used for validation is '([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]')

I cannot find example of usage of this function anywhere. Documentation assumes that you know what is LabelSelector.

What is format of LabelSelector for ListOptions?

Thanks

Body:
You can use the k8s provided function to do the toString operation

import "k8s.io/apimachinery/pkg/labels"
...

func GetSecret(version string) (retVal interface{}, err error){
  clientset := GetClientOutOfCluster()
  labelSelector := metav1.LabelSelector{MatchLabels: map[string]string{"version":version}}

  listOptions := metav1.ListOptions{
    LabelSelector: labels.Set(labelSelector.MatchLabels).String(),
    Limit:         100,
  }
  secretList, err := clientset.CoreV1().Secrets("namespace").List(listOptions)
  retVal = secretList.Items[0]
  return retVal, err
}


问:
Python: extracting datetime to year, month, and day result in float
My data has a datetime index like this 2016-11-05 23:40:00.

I want to extract the datetime elements into three new columns of the year, month, and day. I use the following

```<code>import datetime as dt
df['year'] = df.index.year
df['month'] = df.index.month
df['day'] = df.index.day
</code>```

But the results are in float

```<code>year    month   day
2016.0  11.0    5.0
</code>```

I want

```<code>year    month   day
2016    11      5
</code>```

Any help is appreciated.

答:
convert it on int</p>

```<code>import datetime as dt
df['year'] = int(df.index.year)
df['month'] = int(df.index.month)
df['day'] = int(df.index.day)
</code>```

Body:
My data has a datetime index like this 2016-11-05 23:40:00.

I want to extract the datetime elements into three new columns of the year, month, and day. I use the following

import datetime as dt
df['year'] = df.index.year
df['month'] = df.index.month
df['day'] = df.index.day

But the results are in float

year    month   day
2016.0  11.0    5.0

I want

year    month   day
2016    11      5

Any help is appreciated.

Body:
convert it on int

import datetime as dt
df['year'] = int(df.index.year)
df['month'] = int(df.index.month)
df['day'] = int(df.index.day)


问:
AWS Glue: Failed to start job run due to missing metadata
In order to run a job using boto3, the documentation states only JobName is required. However, my code:

```<code>    def start_job_run(self, name):
        print("The name of the job to be run via client is: {}".format(name))
        self.response_de_start_job = self.client.start_job_run(
            JobName=name
        )
        print(self.response_de_start_job)
</code>```

and the client is:

```<code>    self.client = boto3.client(
            'glue',
            region_name='ap-south-1',
            aws_access_key_id=os.getenv('AWS_ACCESS_KEY_ID'),
            aws_secret_access_key=os.getenv('AWS_SECRET_ACCESS_KEY'),
        )
</code>```

when executed via Python3, gives out an error:

```<code>botocore.errorfactory.EntityNotFoundException: An error occurred (EntityNotFoundException) when calling the StartJobRun operation: Failed to start job run due to missing metadata
</code>```

but when I do the same operation on the same job from UI and from the cli(aws glue start-job-run --job-name march15_9), it works all alright.

答:
I too faced the same error, the problem is passing ARN of glue job as JobName. Resolved by passing only Name of the glue job.</p>

```<code>response = client.start_job_run(
    JobName='Glue Job Name not ARN'
)
</code>```

Body:
In order to run a job using boto3, the documentation states only JobName is required. However, my code:

    def start_job_run(self, name):
        print("The name of the job to be run via client is: {}".format(name))
        self.response_de_start_job = self.client.start_job_run(
            JobName=name
        )
        print(self.response_de_start_job)

and the client is:

    self.client = boto3.client(
            'glue',
            region_name='ap-south-1',
            aws_access_key_id=os.getenv('AWS_ACCESS_KEY_ID'),
            aws_secret_access_key=os.getenv('AWS_SECRET_ACCESS_KEY'),
        )

when executed via Python3, gives out an error:

botocore.errorfactory.EntityNotFoundException: An error occurred (EntityNotFoundException) when calling the StartJobRun operation: Failed to start job run due to missing metadata

but when I do the same operation on the same job from UI and from the cli(aws glue start-job-run --job-name march15_9), it works all alright.

Body:
I too faced the same error, the problem is passing ARN of glue job as JobName. Resolved by passing only Name of the glue job.

response = client.start_job_run(
    JobName='Glue Job Name not ARN'
)


问:
How to order tr based on td value in Jquery
I'm setting up a table with data which always orders the rows based on the highest value in a td.

I've tried using this function which does sort the rows but then appends new rows into my table so I get replicated rows.

I have my table set up like this and I need to check the TOT column which need to order by highest score.

$(document).ready(function() {
  sortTable($('#table'), 'asc');
});

function sortTable(table, order) {
  var asc = order === 'asc',
    tbody = table.find('tbody');

  tbody.find('tr').sort(function(a, b) {
    if (asc) {
      return $('td:first', a).text().localeCompare($('td:first', b).text());
    } else {
      return $('td:first', b).text().localeCompare($('td:first', a).text());
    }
  }).appendTo(tbody);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <table id="table">
    <tr>
      <th></th>
      <th>POS</th>
      <th>TEAM</th>
      <th>DRIVER</th>
      <th>TOT</th>
    </tr>
    <tbody>
      <tr>
        <td></td>
        <td>1ST</td>
        <td>PROSPORT PERFORMANCE (85)</td>
        <td>ROBERT RENAUER</td>
        <td>85</td>
      </tr>
      <tr>
        <td></td>
        <td>1ST</td>
        <td>PROSPORT PERFORMANCE (85)</td>
        <td>ROBERT RENAUER</td>
        <td>100</td>
      </tr>
      <tr>
        <td></td>
        <td>1ST</td>
        <td>PROSPORT PERFORMANCE (85)</td>
        <td>ROBERT RENAUER</td>
        <td>34</td>
      </tr>
    </tbody>
  </table>
</div></code>```

答:
To sort by your 'TOT' you have to sort by td:last instead of td:first.

After this you have to append it to table instead of tbody.

$(document).ready(function() {
  sortTable($('#table'), 'asc');
});

function sortTable(table, order) {
  var asc = order === 'asc',
    tbody = table.find('tbody');

  tbody.find('tr').sort(function(a, b) {
    if (asc) {
      return $('td:last', a).text().localeCompare($('td:last', b).text());
    } else {
      return $('td:last', b).text().localeCompare($('td:last', a).text());
    }
  }).appendTo(table);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <table id="table">
    <tr>
      <th></th>
      <th>POS</th>
      <th>TEAM</th>
      <th>DRIVER</th>
      <th>TOT</th>
    </tr>
    <tbody>
      <tr>
        <td></td>
        <td>1ST</td>
        <td>PROSPORT PERFORMANCE (85)</td>
        <td>ROBERT RENAUER</td>
        <td>85</td>
      </tr>
      <tr>
        <td></td>
        <td>1ST</td>
        <td>PROSPORT PERFORMANCE (85)</td>
        <td>ROBERT RENAUER</td>
        <td>100</td>
      </tr>
      <tr>
        <td></td>
        <td>1ST</td>
        <td>PROSPORT PERFORMANCE (85)</td>
        <td>ROBERT RENAUER</td>
        <td>34</td>
      </tr>
    </tbody>
  </table>
</div></code>```

Body:
I'm setting up a table with data which always orders the rows based on the highest value in a td.

I've tried using this function which does sort the rows but then appends new rows into my table so I get replicated rows.

I have my table set up like this and I need to check the TOT column which need to order by highest score.

$(document).ready(function() {
  sortTable($('#table'), 'asc');
});

function sortTable(table, order) {
  var asc = order === 'asc',
    tbody = table.find('tbody');

  tbody.find('tr').sort(function(a, b) {
    if (asc) {
      return $('td:first', a).text().localeCompare($('td:first', b).text());
    } else {
      return $('td:first', b).text().localeCompare($('td:first', a).text());
    }
  }).appendTo(tbody);
}

      POS
      TEAM
      DRIVER
      TOT

        1ST
        PROSPORT PERFORMANCE (85)
        ROBERT RENAUER
        85

        1ST
        PROSPORT PERFORMANCE (85)
        ROBERT RENAUER
        100

        1ST
        PROSPORT PERFORMANCE (85)
        ROBERT RENAUER
        34

Body:
To sort by your 'TOT' you have to sort by td:last instead of td:first.

After this you have to append it to table instead of tbody.

$(document).ready(function() {
  sortTable($('#table'), 'asc');
});

function sortTable(table, order) {
  var asc = order === 'asc',
    tbody = table.find('tbody');

  tbody.find('tr').sort(function(a, b) {
    if (asc) {
      return $('td:last', a).text().localeCompare($('td:last', b).text());
    } else {
      return $('td:last', b).text().localeCompare($('td:last', a).text());
    }
  }).appendTo(table);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <table id="table">
    <tr>
      <th></th>
      <th>POS</th>
      <th>TEAM</th>
      <th>DRIVER</th>
      <th>TOT</th>
    </tr>
    <tbody>
      <tr>
        <td></td>
        <td>1ST</td>
        <td>PROSPORT PERFORMANCE (85)</td>
        <td>ROBERT RENAUER</td>
        <td>85</td>
      </tr>
      <tr>
        <td></td>
        <td>1ST</td>
        <td>PROSPORT PERFORMANCE (85)</td>
        <td>ROBERT RENAUER</td>
        <td>100</td>
      </tr>
      <tr>
        <td></td>
        <td>1ST</td>
        <td>PROSPORT PERFORMANCE (85)</td>
        <td>ROBERT RENAUER</td>
        <td>34</td>
      </tr>
    </tbody>
  </table>
</div>


问:
ARcore - Can't Rotate Model without using TransformableNode
I'm creating a AR application, but one of my models is in the wrong orientation.

I need it to rotate but no allowing the user to rotate it by touch.
Once loaded it has to remain in the same orientation.

I tried the code below and TransformableNode.

```<code>AnchorNode anchorNode = new AnchorNode(anchor);
           if (imageName.equals("fox")){
               anchorNode.setLocalRotation(Quaternion.axisAngle(new
   Vector3(0f, 0, 1f), 180f));
           }else
               anchorNode.setLocalRotation(Quaternion.axisAngle(new
   Vector3(1f, 0, 0f), -10f));
           anchorNode.setRenderable(modelRenderable);
           arFragment.getArSceneView().getScene().onAddChild(anchorNode);
</code>```

答:
Try the following code code:</p>

```<code>// Imaginary anchor – example 1
float[] position = { 0, 0, -0.5 };
float[] rotation = { 0, 0, 0, 1 };
Anchor anchor = session.createAnchor(new Pose(position, rotation));

// Imaginary anchor – example 2
Anchor anchor = hitResult.createAnchor();

///////////////////////////////////////////////

AnchorNode anchorNode = new AnchorNode(anchor);
anchorNode.setParent(arFragment.getArSceneView().getScene());

// 180 Degrees CCW
Quaternion rotation180 = Quaternion.axisAngle(new Vector3(0.0f, 0.0f, 1.0f), 180);
//  10 Degrees CW
Quaternion rotation010 = Quaternion.axisAngle(new Vector3(1.0f, 0.0f, 0.0f), -10);

TransformableNode node = new TransformableNode(arFragment.getTransformationSystem());
node.setParent(anchorNode);
node.select();

if (imageName.equals("fox")) {
    node.setLocalRotation(rotation180);
    Node foxxy = new Node();
    foxxy.setParent(node);
    foxxy.setRenderable(modelRenderable);
} else {
    node.setLocalRotation(rotation010);
    Node notFox = new Node();
    notFox.setParent(node);
    notFox.setRenderable(modelRenderable);
}

arFragment.getArSceneView().getScene().onAddChild(node);
</code>```

Body:
I'm creating a AR application, but one of my models is in the wrong orientation.

I need it to rotate but no allowing the user to rotate it by touch.
Once loaded it has to remain in the same orientation.

I tried the code below and TransformableNode.

AnchorNode anchorNode = new AnchorNode(anchor);
           if (imageName.equals("fox")){
               anchorNode.setLocalRotation(Quaternion.axisAngle(new
   Vector3(0f, 0, 1f), 180f));
           }else
               anchorNode.setLocalRotation(Quaternion.axisAngle(new
   Vector3(1f, 0, 0f), -10f));
           anchorNode.setRenderable(modelRenderable);
           arFragment.getArSceneView().getScene().onAddChild(anchorNode);

Body:
Try the following code code:

// Imaginary anchor – example 1
float[] position = { 0, 0, -0.5 };
float[] rotation = { 0, 0, 0, 1 };
Anchor anchor = session.createAnchor(new Pose(position, rotation));

// Imaginary anchor – example 2
Anchor anchor = hitResult.createAnchor();

///////////////////////////////////////////////

AnchorNode anchorNode = new AnchorNode(anchor);
anchorNode.setParent(arFragment.getArSceneView().getScene());

// 180 Degrees CCW
Quaternion rotation180 = Quaternion.axisAngle(new Vector3(0.0f, 0.0f, 1.0f), 180);
//  10 Degrees CW
Quaternion rotation010 = Quaternion.axisAngle(new Vector3(1.0f, 0.0f, 0.0f), -10);

TransformableNode node = new TransformableNode(arFragment.getTransformationSystem());
node.setParent(anchorNode);
node.select();

if (imageName.equals("fox")) {
    node.setLocalRotation(rotation180);
    Node foxxy = new Node();
    foxxy.setParent(node);
    foxxy.setRenderable(modelRenderable);
} else {
    node.setLocalRotation(rotation010);
    Node notFox = new Node();
    notFox.setParent(node);
    notFox.setRenderable(modelRenderable);
}

arFragment.getArSceneView().getScene().onAddChild(node);


问:
Numpy engineering notation
Is there a way to limit the representation of floating point numbers so that they correspond only to the prefixes used in physical units.

An example will make it clearer:

```<code>0.01   ->   currently       1e-02
       ->   what I'd like   10e-03

0.0001   ->   currently       1e-04
         ->   what I'd like   100e-06
</code>```

The motivation behind it is that I'm doing some time measurements and having the representations as representations of 1000 is much more user friendly. I know that 10e-03 -> 10mili or 100e-06 -> 100u

Update

For numpy 1.7< there is a formatter attribute in the set_printoptions(). The solution for which I'm heading for is writing an inline function which would do the formating.
Once set, it the formatting should be available globally.

Reference about the formatter

答:
If helps, a 'solution' can be:

Use ticker.EngFormatter() from matplotlib library together with numpy's set_printoptions. As pointed out by @TheMeaningfulEngineer's update link, it's formatter attribute requires a dict of keys each with a callable value (a function basically). The possible keys are basically the types to apply the format to. Those can be found in numpy's  documentation.

Matplolib ticker don't use exponent but SI units (n, μ, k, k, M, etc)

Example:

```<code>import numpy as np
from matplotlib import ticker
formatter = ticker.EngFormatter()
np.set_printoptions(formatter={'float': formatter})
np.array([0.0000001, 0.000001, 10, 1000., 10000, 1000000])
</code>```

which results in:

```<code>array([100 n, 1 μ, 10, 1 k, 10 k, 1 M])
</code>```

For more on how to redefine SI units, I recommend this blog.

Update:

For those interested, matplolib's EngFormatter can accept argument such as units=' Hz', so that after the prefix values are printed with the unit. Like so:

```<code>array([100 n Hz, 1 μ Hz, 10  Hz, 1 k Hz, 10 k Hz, 1 M Hz])
</code>```

Also, same idea can be applied to pandas by overwriting corresponding formatter.

```<code>pd.options.display.float_format = formatter
</code>```

ContentLicense: CC BY-SA 3.0

Title: Numpy engineering notation

Body:
Is there a way to limit the representation of floating point numbers so that they correspond only to the prefixes used in physical units.

An example will make it clearer:

0.01   ->   currently       1e-02
       ->   what I'd like   10e-03

0.0001   ->   currently       1e-04
         ->   what I'd like   100e-06

The motivation behind it is that I'm doing some time measurements and having the representations as representations of 1000 is much more user friendly. I know that 10e-03 -> 10mili or 100e-06 -> 100u

Update

For numpy 1.7< there is a formatter attribute in the set_printoptions(). The solution for which I'm heading for is writing an inline function which would do the formating.
Once set, it the formatting should be available globally.

Reference about the formatter

Body:
If helps, a 'solution' can be:

Use ticker.EngFormatter() from matplotlib library together with numpy's set_printoptions. As pointed out by @TheMeaningfulEngineer's update link, it's formatter attribute requires a dict of keys each with a callable value (a function basically). The possible keys are basically the types to apply the format to. Those can be found in numpy's  documentation.

Matplolib ticker don't use exponent but SI units (n, μ, k, k, M, etc)

Example:

import numpy as np
from matplotlib import ticker
formatter = ticker.EngFormatter()
np.set_printoptions(formatter={'float': formatter})
np.array([0.0000001, 0.000001, 10, 1000., 10000, 1000000])

which results in:

array([100 n, 1 μ, 10, 1 k, 10 k, 1 M])

For more on how to redefine SI units, I recommend this blog.

Update:

For those interested, matplolib's EngFormatter can accept argument such as units=' Hz', so that after the prefix values are printed with the unit. Like so:

array([100 n Hz, 1 μ Hz, 10  Hz, 1 k Hz, 10 k Hz, 1 M Hz])

Also, same idea can be applied to pandas by overwriting corresponding formatter.

pd.options.display.float_format = formatter


问:
Fixed pod count per node
I need fixed pod count on each node and count should stay fixed in any case. Pod count will be different on each node. Should I create separate deployments for each node or somehow use taints?</p>

答:
Once you are done with defining taints on required node. Only pods that have tolerations for them will be deployed on that particular node. Now, its fairly easy to control the number of pods that you want to run for that deployment.

deployment can be scaled up and down using

```<code>kubectl scale deployment <my_deployment> --replicas=<number of desired pods>
</code>```

So, effectively you will be controlling number of pods on particular node.

Note: As I already commented, this design will be introducing single point of failure in your system for example, no pod of type A will be running if its node type is down.

Title: Fixed pod count per node

Body:
Once you are done with defining taints on required node. Only pods that have tolerations for them will be deployed on that particular node. Now, its fairly easy to control the number of pods that you want to run for that deployment.

deployment can be scaled up and down using

kubectl scale deployment <my_deployment> --replicas=<number of desired pods>

So, effectively you will be controlling number of pods on particular node.

Note: As I already commented, this design will be introducing single point of failure in your system for example, no pod of type A will be running if its node type is down.


问:
What EL 2.2 implementation is available in Maven Central?
I'm trying to find Java EL 2.2 implementation available in Maven Central.</p>

答:
One Possible one:

```<code><dependency>
  <groupId>org.glassfish.web</groupId>
  <artifactId>el-impl</artifactId>
  <version>2.2</version>
</dependency>
</code>```

Can be found in the java.net m2 repository: http://download.java.net/maven/2/

Body:
One Possible one:

<dependency>
  <groupId>org.glassfish.web</groupId>
  <artifactId>el-impl</artifactId>
  <version>2.2</version>
</dependency>

Can be found in the java.net m2 repository: http://download.java.net/maven/2/


问:
clear intervals and timeouts on nuxt.js build
On my website I have a few intervals and timeouts set, for things such as a carousel. Now I do clear them on the components destroyed() lifecycle hook. But I am still getting this build warning.

This is an example of one of my components

```<code><script>
  data() {
    return {
      carouselInterval: null
    }
  },
  created() {
    this.startInterval();
  },
  methods: {
    startInterval() {
      this.carouselInterval = setInterval(() => {
         ...
      }, 5000);
    }
  },
  destroyed() {
    clearInterval(this.carouselInterval);
  }
</script>
</code>```

I also have a timeOut like so

```<code><script>
  data() {
    return {
      testTimeout: null
    }
  },
  created() {
    this.startTimeout();
  },
  methods: {
    startTimeout() {
      this.testTimeout = setTimeout(() => {
         ...
      }, 5000);
    }
  },
  destroyed() {
    clearTimeout(this.testTimeout);
  }
</script>
</code>```

Now I would assume this would clear these timing functions but, I am still getting this warning.

Is there something I am doing wrong? Is there another way to clear all timing functions on build?

EDIT

I am 100% sure I have cleaned up all timing functions on the destroyed() lifecycle hook

答:
The destroyed() lifecycle hook does not get called whilst using SSR. You can read more about this here SSR component lifecycle hooks

This means you can not use it to clear timeouts on the server.

You can solve this issue by moving your interval functions to either be called in the mounted() or beforeMount() lifecycle hooks since they are only called on the client side.

In your example you can change your code to be

```<code><script>
  data() {
    return {
      carouselInterval: null
    }
  },
  mounted() {
     this.startInterval();
  },
  methods: {
    startInterval() {
      this.carouselInterval = setInterval(() => {
         ...
      }, 5000);
    }
  }
</script>
</code>```

This will prevent the nuxt.js build from timing out.

Body:
On my website I have a few intervals and timeouts set, for things such as a carousel. Now I do clear them on the components destroyed() lifecycle hook. But I am still getting this build warning.

This is an example of one of my components

I also have a timeOut like so

Now I would assume this would clear these timing functions but, I am still getting this warning.

Is there something I am doing wrong? Is there another way to clear all timing functions on build?

EDIT

I am 100% sure I have cleaned up all timing functions on the destroyed() lifecycle hook

Body:
The destroyed() lifecycle hook does not get called whilst using SSR. You can read more about this here SSR component lifecycle hooks

This means you can not use it to clear timeouts on the server.

You can solve this issue by moving your interval functions to either be called in the mounted() or beforeMount() lifecycle hooks since they are only called on the client side.

In your example you can change your code to be

<script>
  data() {
    return {
      carouselInterval: null
    }
  },
  mounted() {
     this.startInterval();
  },
  methods: {
    startInterval() {
      this.carouselInterval = setInterval(() => {
         ...
      }, 5000);
    }
  }
</script>

This will prevent the nuxt.js build from timing out.


问:
Why every SYCL device by default comes in separate context?
When I use a cpu_selector and a gpu_selector, these two devices fall into 2 different context by default? Why is that the default when having devices within same context helps with performant memory access of buffers (no overhead of copying over the data to a different context)?</p>

答:
The SYCL context can only encapsulate the devices from a single platform, and cannot be created using devices from two or more different platforms.

The devices which can be attached to the same context is platform dependant, not user-defined. You can construct a context for many devices from the same platform if the same platform reports them, but if they are on different platforms then you won't be able to.

If you want to understand the details you can read this section of the SYCL specification https://www.khronos.org/registry/SYCL/specs/sycl-1.2.1.pdf#page=54


答:
Just use astype:

```<code>import datetime as dt
df['year'] = df.index.year.astype(int)
df['month'] = df.index.month.astype(int)
df['day'] = df.index.day.astype(int)
</code>```

If there are Nan's then use errors parameter:

```<code>df['year'] = df.index.year.astype(int, errors='ignore')
</code>```

This will return nans for the columns with null index

Title: Python: extracting datetime to year, month, and day result in float

Body:
Just use astype:

import datetime as dt
df['year'] = df.index.year.astype(int)
df['month'] = df.index.month.astype(int)
df['day'] = df.index.day.astype(int)

If there are Nan's then use errors parameter:

df['year'] = df.index.year.astype(int, errors='ignore')

This will return nans for the columns with null index


问:
C++ binary search for a class
I have a class and I want to implement binary_search (from  library) to it:

```<code>#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

class T_value{
public:

    T_value(const int _timestamp, const string _value) :
        timestamp(_timestamp),
        value(_value)
    {}
    int get_time() {return timestamp;}

private:
    int timestamp;
    string value;
};

int main()
{

    T_value one(1, "one"),
    two(3, "two"),
    three(43, "three"),
    four(-1, "four");
    vector<T_value> v{one,two,three, four};

    cout << binary_search(begin(v), end(v), 3);
}
</code>```

Is that possible? Should I overload '==' and '<' operators (tried, didn't succeed) or something else?

Thank you in advance!

答:
Since you send an int as the 3rd argument to binary_search,
just an operator< will not be enough, because you need to
support both int<T_value and T_value<int

The suggestion is to create a comparator class with the members:

```<code>bool operator()(const T_value& lhs, int rhs) const
bool operator()(int lhs, const T_value& rhs) const
</code>```

and send an instance as a fourth parameter.

Furthermore, the vector should be sorted before binary_search is
invoked. You could do this with std::sort, but now you need to
support a 3rd type of comparison, a 3rd member of the comparator
class could do that, like:

```<code>bool operator()(const T_value& lhs, const T_value& rhs) const
</code>```

The end result might look something like this

Title: C++ binary search for a class

Body:
I have a class and I want to implement binary_search (from  library) to it:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

class T_value{
public:

    T_value(const int _timestamp, const string _value) :
        timestamp(_timestamp),
        value(_value)
    {}
    int get_time() {return timestamp;}

private:
    int timestamp;
    string value;
};

int main()
{

    T_value one(1, "one"),
    two(3, "two"),
    three(43, "three"),
    four(-1, "four");
    vector<T_value> v{one,two,three, four};

    cout << binary_search(begin(v), end(v), 3);
}

Is that possible? Should I overload '==' and '<' operators (tried, didn't succeed) or something else?

Thank you in advance!

Body:
Since you send an int as the 3rd argument to binary_search,
just an operator< will not be enough, because you need to
support both int<T_value and T_value<int

The suggestion is to create a comparator class with the members:

bool operator()(const T_value& lhs, int rhs) const
bool operator()(int lhs, const T_value& rhs) const

and send an instance as a fourth parameter.

Furthermore, the vector should be sorted before binary_search is
invoked. You could do this with std::sort, but now you need to
support a 3rd type of comparison, a 3rd member of the comparator
class could do that, like:

bool operator()(const T_value& lhs, const T_value& rhs) const

The end result might look something like this


答:
Or if you have a lot of columns, easiest may well be after all the code for constructing data-frame:</p>

```<code>df = df.astype(int)
</code>```

Body:
My data has a datetime index like this 2016-11-05 23:40:00.

I want to extract the datetime elements into three new columns of the year, month, and day. I use the following

import datetime as dt
df['year'] = df.index.year
df['month'] = df.index.month
df['day'] = df.index.day

But the results are in float

year    month   day
2016.0  11.0    5.0

I want

year    month   day
2016    11      5

Any help is appreciated.

Body:
Or if you have a lot of columns, easiest may well be after all the code for constructing data-frame:

df = df.astype(int)


问:
GL_Invalid_Operation in OpenGL applications
I am currently wiring an OpenGL application and am getting GL_INVALID_OPERATION. The whole GL is scattered among several files and its hard to create an example out of it, but I have created an OpenGL trace using apitrace. This is one chunk that created the error:

glMatrixMode(mode = GL_PROJECTION)
glLoadIdentity()
glViewport(x = 0, y = 0, width = 1190, height = 746)
glOrtho(left = 0, right = 1190, bottom = 0, top = 746, zNear = 0, zFar = 128)
glBegin(mode = GL_QUADS)
glColor4f(red = 0.5, green = 0.5, blue = 0.5, alpha = 1)
glVertex3f(x = 1190, y = 746, z = 0)
glColor4f(red = 0.5, green = 0.5, blue = 0.5, alpha = 1)
glVertex3f(x = 0, y = 746, z = 0)
glColor4f(red = 0.5, green = 0.5, blue = 0.5, alpha = 1)
glVertex3f(x = 0, y = 100, z = 0)
glColor4f(red = 0.5, green = 0.5, blue = 0.5, alpha = 1)
glVertex3f(x = 1190, y = 100, z = 0)
glEnd()
glGetError() = GL_INVALID_OPERATION
```

Has someone any idea on this?

答:
GL_QUADS is deprecated since version 3 and removed since version 3.1.

https://www.khronos.org/opengl/wiki/Primitive#Quads

Body:
I am currently wiring an OpenGL application and am getting GL_INVALID_OPERATION. The whole GL is scattered among several files and its hard to create an example out of it, but I have created an OpenGL trace using apitrace. This is one chunk that created the error:

glMatrixMode(mode = GL_PROJECTION)
glLoadIdentity()
glViewport(x = 0, y = 0, width = 1190, height = 746)
glOrtho(left = 0, right = 1190, bottom = 0, top = 746, zNear = 0, zFar = 128)
glBegin(mode = GL_QUADS)
glColor4f(red = 0.5, green = 0.5, blue = 0.5, alpha = 1)
glVertex3f(x = 1190, y = 746, z = 0)
glColor4f(red = 0.5, green = 0.5, blue = 0.5, alpha = 1)
glVertex3f(x = 0, y = 746, z = 0)
glColor4f(red = 0.5, green = 0.5, blue = 0.5, alpha = 1)
glVertex3f(x = 0, y = 100, z = 0)
glColor4f(red = 0.5, green = 0.5, blue = 0.5, alpha = 1)
glVertex3f(x = 1190, y = 100, z = 0)
glEnd()
glGetError() = GL_INVALID_OPERATION

Has someone any idea on this?


问:
How to write data from queue to MongoDB
I have a running zookeeper + kafka and I am successfully sending tweets to the kafka producer. The tweets are taken from a queue:

```<code>queue = new LinkedBlockingQueue<>(10000);
public void run() {
        client.connect();
        try (Producer<Long, String> producer = getProducer()) {
            while (true) {
                Tweet tweet = gson.fromJson(queue.take(), Tweet.class);
                System.out.printf("Fetched tweet id %d\n", tweet.getId());
                long key = tweet.getId();
                String msg = tweet.toString();
                ProducerRecord<Long, String> record = new ProducerRecord<>(KafkaConfiguration.TOPIC, key, msg);
                producer.send(record, callback);

            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            client.stop();
        }
</code>```

My question is how to write the already received object (the class Tweet) to MongoDB? I have the configuration setup like this on my localhost:

```<code>//MongoDB config
    int port_no = 27017;
    String host_name = "localhost", db_name = "bigdata", db_coll_name = "twitter";

    // Mongodb connection string.
    String client_url = "mongodb://" + host_name + ":" + port_no + "/" + db_name;
    MongoClientURI uri = new MongoClientURI(client_url);

    // Connecting to the mongodb server using the given client uri.
    MongoClient mongo_client = new MongoClient(uri);

    // Fetching the database from the mongodb.
    MongoDatabase db = mongo_client.getDatabase(db_name);

    // Fetching the collection from the mongodb.
    MongoCollection<Document> coll = db.getCollection(db_coll_name);
</code>```

Is there some way to deserialize it with JSON? Any suggestions would be greatly appreciated. Thanks in advance.

答:
I would suggest to use Kafka Connect MongoDB Sink Connector in order to push data from Kafka to MongoDB

Configuration example for JSON with schema:

```<code>key.converter=org.apache.kafka.connect.json.JsonConverter
key.converter.schemas.enable=true

value.converter=org.apache.kafka.connect.json.JsonConverter
value.converter.schemas.enable=true
</code>```

If you are using Confluent Hub, you can find instructions on how to install the connector here.

Title: How to write data from queue to MongoDB

Body:
I have a running zookeeper + kafka and I am successfully sending tweets to the kafka producer. The tweets are taken from a queue:

queue = new LinkedBlockingQueue<>(10000);
public void run() {
        client.connect();
        try (Producer<Long, String> producer = getProducer()) {
            while (true) {
                Tweet tweet = gson.fromJson(queue.take(), Tweet.class);
                System.out.printf("Fetched tweet id %d\n", tweet.getId());
                long key = tweet.getId();
                String msg = tweet.toString();
                ProducerRecord<Long, String> record = new ProducerRecord<>(KafkaConfiguration.TOPIC, key, msg);
                producer.send(record, callback);

            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            client.stop();
        }

My question is how to write the already received object (the class Tweet) to MongoDB? I have the configuration setup like this on my localhost:

//MongoDB config
    int port_no = 27017;
    String host_name = "localhost", db_name = "bigdata", db_coll_name = "twitter";

    // Mongodb connection string.
    String client_url = "mongodb://" + host_name + ":" + port_no + "/" + db_name;
    MongoClientURI uri = new MongoClientURI(client_url);

    // Connecting to the mongodb server using the given client uri.
    MongoClient mongo_client = new MongoClient(uri);

    // Fetching the database from the mongodb.
    MongoDatabase db = mongo_client.getDatabase(db_name);

    // Fetching the collection from the mongodb.
    MongoCollection<Document> coll = db.getCollection(db_coll_name);

Is there some way to deserialize it with JSON? Any suggestions would be greatly appreciated. Thanks in advance.

Body:
I would suggest to use Kafka Connect MongoDB Sink Connector in order to push data from Kafka to MongoDB

Configuration example for JSON with schema:

key.converter=org.apache.kafka.connect.json.JsonConverter
key.converter.schemas.enable=true

value.converter=org.apache.kafka.connect.json.JsonConverter
value.converter.schemas.enable=true

If you are using Confluent Hub, you can find instructions on how to install the connector here.


问:
U-SQl declaring @variables as null
I have a master table which I am ingesting data to from a couple of source tables which I am not joining.

One of the tables doesn't have one of the columns so I want to insert Nulls into this column with an 'insert into' statement. To do this, I am trying to create a @missing_column variable.

DECLARE @missing_column string IS NULL;  // This does not work.
```

How would you recommend doing this? I know I can write the words "NULL" as a string and insert it as that. But that would not work for a column if it decimals.

答:
U-SQL uses the C# type system, so you need to define types and assign values using the C# syntax.  This means you will need to use a nullable type and assign the correctly typed null values:

Because string is a nullable type already, you can simply use:

```<code>DECLARE @missing_column string = (string)null;
</code>```

Though if you were trying to use a non-nullable type such as int, you would need to specify the nullable version in your variable and table column:

```<code>DECLARE @missing_column int? = (int?)null;
</code>```

The official documentation on U-SQL DECLARE statements can be found here.

Having re-read your question, for your specific example you should just be able to ignore the missing column in your INSERT statement.  This will assign the values from the source table where assigned and leave the additional, unspecified target column null.  To to this, you will obviously need to have a nullable type in the table column per what I have written above:

Master table definition:

```<code>CREATE TABLE dbo.MasterTarget
(
  Col1 Int,
  Col2 string,    // string is already nullable
  Col3 DateTime?, // DateTime is not, so need to specify DateTime? that accepts null values
  INDEX clx_Col1 CLUSTERED(Col1 ASC)
)
DISTRIBUTED BY HASH(Col1);
</code>```

All column data load:

```<code>@src1 =
    EXTRACT Col1 Int,
            Col2 string,
            Col3 DateTime
    FROM "/SourceFile1.csv"
    USING Extractors.Csv();

INSERT INTO dbo.MasterTarget
(
  Col1,
  Col2,
  Col3
)
SELECT Col1,
       Col2,
       Col3
FROM @src1;
</code>```

Missing column data load:

```<code>@src2 =
    EXTRACT Col1 Int,
            Col2 string
    FROM "/SourceFile2.csv"
    USING Extractors.Csv();

INSERT INTO dbo.MasterTarget
(
  Col1,
  Col2
)
SELECT Col1,
       Col2
FROM @src2;
</code>```

Title: U-SQl declaring @variables as null

Body:
I have a master table which I am ingesting data to from a couple of source tables which I am not joining.

One of the tables doesn't have one of the columns so I want to insert Nulls into this column with an 'insert into' statement. To do this, I am trying to create a @missing_column variable.

DECLARE @missing_column string IS NULL;  // This does not work.

How would you recommend doing this? I know I can write the words "NULL" as a string and insert it as that. But that would not work for a column if it decimals.

Body:
U-SQL uses the C# type system, so you need to define types and assign values using the C# syntax.  This means you will need to use a nullable type and assign the correctly typed null values:

Because string is a nullable type already, you can simply use:

DECLARE @missing_column string = (string)null;

Though if you were trying to use a non-nullable type such as int, you would need to specify the nullable version in your variable and table column:

DECLARE @missing_column int? = (int?)null;

The official documentation on U-SQL DECLARE statements can be found here.

Having re-read your question, for your specific example you should just be able to ignore the missing column in your INSERT statement.  This will assign the values from the source table where assigned and leave the additional, unspecified target column null.  To to this, you will obviously need to have a nullable type in the table column per what I have written above:

Master table definition:

CREATE TABLE dbo.MasterTarget
(
  Col1 Int,
  Col2 string,    // string is already nullable
  Col3 DateTime?, // DateTime is not, so need to specify DateTime? that accepts null values
  INDEX clx_Col1 CLUSTERED(Col1 ASC)
)
DISTRIBUTED BY HASH(Col1);

All column data load:

@src1 =
    EXTRACT Col1 Int,
            Col2 string,
            Col3 DateTime
    FROM "/SourceFile1.csv"
    USING Extractors.Csv();

INSERT INTO dbo.MasterTarget
(
  Col1,
  Col2,
  Col3
)
SELECT Col1,
       Col2,
       Col3
FROM @src1;

Missing column data load:

@src2 =
    EXTRACT Col1 Int,
            Col2 string
    FROM "/SourceFile2.csv"
    USING Extractors.Csv();

INSERT INTO dbo.MasterTarget
(
  Col1,
  Col2
)
SELECT Col1,
       Col2
FROM @src2;


问:
Semantic UI React dropdown does not set the value onChange: React+ Typescript
I am implementing a semantic-ui-react dropdown and I am unable to set the value of this dropdown on change event.

Help would be appreciated

```<code>//options object
const options =  [
  {name: "val1" , label: "val1"},
  {name: "val2" , label: "val2"},
  {name: "val3" , label: "val3"}
]

this.state= {location: ''} //state object

//onchange event
dropdownChange = (event: React.SyntheticEvent<HTMLElement>, data:any) => {
    this.setState({[data.name]:data.value})
}

//select component
<Select options={options}
  name="location"
  value={this.state.location}
  onChange={this.dropdownChange}
/>
</code>```

答:
EDIT: You need to add a value key to the array of data.

Look at how they generate data in their example :

```<code>const countryOptions = _.map(faker.definitions.address.country, country => ({
  key: country,
  text: country,
  value: country
}));

</code>```

OLD ANSWER:
There is no such propertie as data.name in the onChange handler (it prints undefined in this codesandbox)

I guess you should populate location key in the state :

```<code>dropdownChange = (event: React.SyntheticEvent<HTMLElement>, data:any) => {
    this.setState({location: data.value})
}
</code>```

Body:
I am implementing a semantic-ui-react dropdown and I am unable to set the value of this dropdown on change event.

Help would be appreciated

//options object
const options =  [
  {name: "val1" , label: "val1"},
  {name: "val2" , label: "val2"},
  {name: "val3" , label: "val3"}
]

this.state= {location: ''} //state object

//onchange event
dropdownChange = (event: React.SyntheticEvent<HTMLElement>, data:any) => {
    this.setState({[data.name]:data.value})
}

//select component
<Select options={options}
  name="location"
  value={this.state.location}
  onChange={this.dropdownChange}
/>

Body:
EDIT: You need to add a value key to the array of data.

Look at how they generate data in their example :

const countryOptions = _.map(faker.definitions.address.country, country => ({
  key: country,
  text: country,
  value: country
}));

OLD ANSWER:
There is no such propertie as data.name in the onChange handler (it prints undefined in this codesandbox)

I guess you should populate location key in the state :

dropdownChange = (event: React.SyntheticEvent<HTMLElement>, data:any) => {
    this.setState({location: data.value})
}


问:
Consolidate array of numbers without exceeding a predefined maximum value per element
I'm trying to combine numbers in an array by adding them so that the max value can only by 30.

For example, this is my array:

```<code>array(10,30,10,10,15);
</code>```

After combining the numbers in the array to items with a max value 30, the result should be:

```<code>array(30,30,15);
</code>```

How to achieve this?

答:
I'm trying to combine numbers in an array by adding them so that the
  max value can only by 30

So, when you combine numbers, you can achieve the lowest possible set of values in your array and also make sure that max value remains 30 by:

First, sort them.

Second, keeping adding elements to sum till you are about to get a sum > 30.

Third, once an element can no longer be added to a sum, add the current sum in your array and make the current element as the new sum.

Code:

```<code><?php

$arr = array(10,30,10,10,15);
sort($arr);

$res = [];
$curr_sum = 0;

foreach($arr as $each_value){
    if($curr_sum + $each_value <= 30) $curr_sum += $each_value;
    else{
        $res[] = $curr_sum;
        $curr_sum = $each_value;
    }
}

$res[] = $curr_sum;

print_r($res);
</code>```

Demo: https://3v4l.org/BYhuE

Update: If order of the numbers matters, seeing your current output, you could just use rsort() to show them in descending order.

```<code>rsort($res);
</code>```

Body:
I'm trying to combine numbers in an array by adding them so that the max value can only by 30.

For example, this is my array:

array(10,30,10,10,15);

After combining the numbers in the array to items with a max value 30, the result should be:

array(30,30,15);

How to achieve this?

Body:
I'm trying to combine numbers in an array by adding them so that the
  max value can only by 30

So, when you combine numbers, you can achieve the lowest possible set of values in your array and also make sure that max value remains 30 by:

First, sort them.

Second, keeping adding elements to sum till you are about to get a sum > 30.

Third, once an element can no longer be added to a sum, add the current sum in your array and make the current element as the new sum.

Code:

<?php

$arr = array(10,30,10,10,15);
sort($arr);

$res = [];
$curr_sum = 0;

foreach($arr as $each_value){
    if($curr_sum + $each_value <= 30) $curr_sum += $each_value;
    else{
        $res[] = $curr_sum;
        $curr_sum = $each_value;
    }
}

$res[] = $curr_sum;

print_r($res);

Demo: https://3v4l.org/BYhuE

Update: If order of the numbers matters, seeing your current output, you could just use rsort() to show them in descending order.

rsort($res);


问:
android restore application's default preferences
I'm developing an android app which has some settings. It is still a draft, but I encountered a problem which I just don't succeed to solve: I created a sample settings activity (using the PreferenceFragment as suggested by the android developer's guide), and I added a "restore default settings" button. However, this button only partially works - it restores only the edit text preference, but not the rest. My intent is that when I press the button all of the preferences should be restored to the values that appear in the preferences.xml file.

here's the code:

Main Activity

```<code>public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    }

    public void applyCoF(View view) {
    }

    public void changeSettings(View view) {
        Intent settingsIntent = new Intent(this, SettingsActivity.class);
        startActivity(settingsIntent);
    }
}
</code>```

Settings Activity

```<code>public class SettingsActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();

    }

    public static class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);
            getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);

            Preference button = findPreference(getString(R.string.restoreDefaultSettingsButton));
            button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    //code for what you want it to do
                    DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            switch (which) {
                                case DialogInterface.BUTTON_POSITIVE:
                                    //Yes button clicked
                                    restoreDefaultSettings();
                                    break;

                                case DialogInterface.BUTTON_NEGATIVE:
                                    //No button clicked
                                    break;
                            }
                        }
                    };

                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    builder.setTitle(R.string.restoreDefaultSettingsDialogTitle);
                    builder.setMessage(R.string.restoreDefaultSettingsDialogText).
                            setPositiveButton("Yes", dialogClickListener).
                            setNegativeButton("No", dialogClickListener).
                            show();
                    return true;
                }
            });
        }

        private void restoreDefaultSettings() {
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
            SharedPreferences.Editor editor = preferences.edit();
            editor.clear();
            editor.apply();
            PreferenceManager.setDefaultValues(getActivity(), R.xml.preferences, true);
        }

        @Override
        public void onResume() {
            super.onResume();
            for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); ++i) {
                Preference preference = getPreferenceScreen().getPreference(i);
                if (preference instanceof PreferenceGroup) {
                    PreferenceGroup preferenceGroup = (PreferenceGroup) preference;
                    for (int j = 0; j < preferenceGroup.getPreferenceCount(); ++j) {
                        Preference singlePref = preferenceGroup.getPreference(j);
                        updatePreference(singlePref, singlePref.getKey());
                    }
                } else {
                    updatePreference(preference, preference.getKey());
                }
            }
        }

        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            updatePreference(findPreference(key), key);
        }

        private void updatePreference(Preference preference, String key) {
            if (preference == null || preference instanceof CheckBoxPreference) {
                return;
            }
            if (preference instanceof ListPreference) {
                ListPreference listPreference = (ListPreference) preference;
                listPreference.setSummary(listPreference.getEntry());
                return;
            }

            SharedPreferences sharedPrefs = getPreferenceManager().getSharedPreferences();
            preference.setSummary(sharedPrefs.getString(key, "Default"));
        }
    }
}
</code>```

preferences.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <CheckBoxPreference
        android:defaultValue="true"
        android:key="check_box_preference_1"
        android:title="Check box preference"/>
    <EditTextPreference
        android:defaultValue="DEFAULT EDIT TEXT"
        android:key="edit_text_preference_1"
        android:selectAllOnFocus="true"
        android:singleLine="true"
        android:title="Edit text preference"/>
    <ListPreference
        android:defaultValue="DEFAULT LIST"
        android:entries="@array/list_preference_entry_values"
        android:entryValues="@array/list_preference_entries"
        android:key="list_preference_1"
        android:title="List preference"/>

    <Preference android:title="Restore default values"
                android:summary=""
                android:key="@string/restoreDefaultSettingsButton"/>
</PreferenceScreen>
</code>```

答:
I had a similar problem - my EditTextPreferences changes, but when I clicked them it showed old value. When I closed preferences screen and go back everything was fine.

I resolved this problem, and verified that other preferences works the same but you see it in different way. F.E. CheckBoxPreference restored to default is restored when you reaopen preferences screen. But it doesn't work after clicking "restore defaults" because it doesn't refresh preference screen in your code.

I simply modified it to:

```<code> private void restoreDefaultSettings() {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
    SharedPreferences.Editor editor = preferences.edit();
    editor.clear();
    editor.apply();
    PreferenceManager.setDefaultValues(getActivity(), R.xml.pref, true);
    getPreferenceScreen().removeAll();
    onCreatePreferences(null,null); //or onCreate(null) in your code
}
</code>```

I don't know that it's the best solution, but it works

Body:
I'm developing an android app which has some settings. It is still a draft, but I encountered a problem which I just don't succeed to solve: I created a sample settings activity (using the PreferenceFragment as suggested by the android developer's guide), and I added a "restore default settings" button. However, this button only partially works - it restores only the edit text preference, but not the rest. My intent is that when I press the button all of the preferences should be restored to the values that appear in the preferences.xml file.

here's the code:

Main Activity

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    }

    public void applyCoF(View view) {
    }

    public void changeSettings(View view) {
        Intent settingsIntent = new Intent(this, SettingsActivity.class);
        startActivity(settingsIntent);
    }
}

Settings Activity

public class SettingsActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();

    }

    public static class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);
            getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);

            Preference button = findPreference(getString(R.string.restoreDefaultSettingsButton));
            button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    //code for what you want it to do
                    DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            switch (which) {
                                case DialogInterface.BUTTON_POSITIVE:
                                    //Yes button clicked
                                    restoreDefaultSettings();
                                    break;

                                case DialogInterface.BUTTON_NEGATIVE:
                                    //No button clicked
                                    break;
                            }
                        }
                    };

                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    builder.setTitle(R.string.restoreDefaultSettingsDialogTitle);
                    builder.setMessage(R.string.restoreDefaultSettingsDialogText).
                            setPositiveButton("Yes", dialogClickListener).
                            setNegativeButton("No", dialogClickListener).
                            show();
                    return true;
                }
            });
        }

        private void restoreDefaultSettings() {
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
            SharedPreferences.Editor editor = preferences.edit();
            editor.clear();
            editor.apply();
            PreferenceManager.setDefaultValues(getActivity(), R.xml.preferences, true);
        }

        @Override
        public void onResume() {
            super.onResume();
            for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); ++i) {
                Preference preference = getPreferenceScreen().getPreference(i);
                if (preference instanceof PreferenceGroup) {
                    PreferenceGroup preferenceGroup = (PreferenceGroup) preference;
                    for (int j = 0; j < preferenceGroup.getPreferenceCount(); ++j) {
                        Preference singlePref = preferenceGroup.getPreference(j);
                        updatePreference(singlePref, singlePref.getKey());
                    }
                } else {
                    updatePreference(preference, preference.getKey());
                }
            }
        }

        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            updatePreference(findPreference(key), key);
        }

        private void updatePreference(Preference preference, String key) {
            if (preference == null || preference instanceof CheckBoxPreference) {
                return;
            }
            if (preference instanceof ListPreference) {
                ListPreference listPreference = (ListPreference) preference;
                listPreference.setSummary(listPreference.getEntry());
                return;
            }

            SharedPreferences sharedPrefs = getPreferenceManager().getSharedPreferences();
            preference.setSummary(sharedPrefs.getString(key, "Default"));
        }
    }
}

preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <CheckBoxPreference
        android:defaultValue="true"
        android:key="check_box_preference_1"
        android:title="Check box preference"/>
    <EditTextPreference
        android:defaultValue="DEFAULT EDIT TEXT"
        android:key="edit_text_preference_1"
        android:selectAllOnFocus="true"
        android:singleLine="true"
        android:title="Edit text preference"/>
    <ListPreference
        android:defaultValue="DEFAULT LIST"
        android:entries="@array/list_preference_entry_values"
        android:entryValues="@array/list_preference_entries"
        android:key="list_preference_1"
        android:title="List preference"/>

    <Preference android:title="Restore default values"
                android:summary=""
                android:key="@string/restoreDefaultSettingsButton"/>
</PreferenceScreen>

Body:
I had a similar problem - my EditTextPreferences changes, but when I clicked them it showed old value. When I closed preferences screen and go back everything was fine.

I resolved this problem, and verified that other preferences works the same but you see it in different way. F.E. CheckBoxPreference restored to default is restored when you reaopen preferences screen. But it doesn't work after clicking "restore defaults" because it doesn't refresh preference screen in your code.

I simply modified it to:

 private void restoreDefaultSettings() {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
    SharedPreferences.Editor editor = preferences.edit();
    editor.clear();
    editor.apply();
    PreferenceManager.setDefaultValues(getActivity(), R.xml.pref, true);
    getPreferenceScreen().removeAll();
    onCreatePreferences(null,null); //or onCreate(null) in your code
}

I don't know that it's the best solution, but it works


问:
Way to determine checkbox checked in react (useState)
This is my first time to develop a react application. I tried to implement checkboxes in each row of a table and check which of the rows are selected.

I used useState hook to make checked and onChange events, but seems the values are not refreshing when I check then uncheck the checkbox.

I would like to ask how to add a logic to remove the unticked values on the hooks.

T1
Checkbox A- Checked
Checkbox B- Checked
CheckedMap- A,B

T2
Checkbox B- Unchecked
CheckedMap- A,B // Unticked Checkbox B is also stored in CheckedMap

Thank you for your help.

```<code>export default function({ infinite }) {
  const [checkedMap, setCheckedMap] = useState(new Map());
}

const handleCheckedChange = transaction_seq => {
    let modifiedMap = checkedMap;
    modifiedMap.set(transaction_seq, !checkedMap.get(transaction_seq));
    setCheckedMap(modifiedMap);
  };

const columns = [
    {
      Header: "Transaction(s)",
      className: "left",
      columns: [
        {
          id: "checkbox",
          accessor: "checkbox",
          Cell: ({ row }) => {
            return (
              <input
                type="checkbox"
                className="checkbox"
                checked={checkedMap.get(row.original.transaction_seq)}
                onChange={() =>
                  handleCheckedChange(row.original.transaction_seq)
                }
</code>```

答:
You can check the check status in map and then decide whether to set the value or delete it</p>

```<code>const handleCheckedChange = transaction_seq => {
    let modifiedMap = checkedMap;
    if(checkedMap.get(transaction_seq)) {
        modifiedMap.delete(transaction_seq)
    } else {
        modifiedMap.set(transaction_seq, true);
    }
    setCheckedMap(modifiedMap);
  };
</code>```

Body:
This is my first time to develop a react application. I tried to implement checkboxes in each row of a table and check which of the rows are selected.

I used useState hook to make checked and onChange events, but seems the values are not refreshing when I check then uncheck the checkbox.

I would like to ask how to add a logic to remove the unticked values on the hooks.

T1
Checkbox A- Checked
Checkbox B- Checked
CheckedMap- A,B

T2
Checkbox B- Unchecked
CheckedMap- A,B // Unticked Checkbox B is also stored in CheckedMap

Thank you for your help.

export default function({ infinite }) {
  const [checkedMap, setCheckedMap] = useState(new Map());
}

const handleCheckedChange = transaction_seq => {
    let modifiedMap = checkedMap;
    modifiedMap.set(transaction_seq, !checkedMap.get(transaction_seq));
    setCheckedMap(modifiedMap);
  };

const columns = [
    {
      Header: "Transaction(s)",
      className: "left",
      columns: [
        {
          id: "checkbox",
          accessor: "checkbox",
          Cell: ({ row }) => {
            return (
              <input
                type="checkbox"
                className="checkbox"
                checked={checkedMap.get(row.original.transaction_seq)}
                onChange={() =>
                  handleCheckedChange(row.original.transaction_seq)
                }

Body:
You can check the check status in map and then decide whether to set the value or delete it

const handleCheckedChange = transaction_seq => {
    let modifiedMap = checkedMap;
    if(checkedMap.get(transaction_seq)) {
        modifiedMap.delete(transaction_seq)
    } else {
        modifiedMap.set(transaction_seq, true);
    }
    setCheckedMap(modifiedMap);
  };


问:
how to overide simplenews for drupal tpl and subscribe without being registered
How do I make a simple block to subscribe myself by providing my email in simlenews, without having to register myself.
i'm using drupal 6</p>

答: You just need to enable the permission subscribe to issues to the anonymous users to allow non registered user to subscribe to your mailing list.</p>


问:
Change Time Unit with Kernprof
I've started looking for bottlenecks in Python using line_profiler. Right now, I am doing that by running

```<code>kernprof -l -v myFile.py
</code>```

However, the unit of time seems to be at 1e-6, which lead to output results such as 132329040. How can I increase the time interval to make the output more readable for larger time deltas?

答:
That is a feature so far only present via Jupyter line magic, as discussed here. It can be accessed via the "-u" flag, followed by the timer unit, in seconds. This is a sample usage:

```<code>def m():
  return [0]*10**8

%lprun -u 1e-3 -f m m()
</code>```

Which displays the output with timer unit in milliseconds:

```<code>Out:
Timer unit: 0.001 s

Total time: 0.363548 s
File:
Function: m at line 1

Line # Hits Time Per Hit % Time Line Contents
==============================================================
1 def m():
2 1 363.5 363.5 100.0 return [0]*10**8
</code>```

As documented in this PR.

Title: Change Time Unit with Kernprof

Body:
I've started looking for bottlenecks in Python using line_profiler. Right now, I am doing that by running

kernprof -l -v myFile.py

However, the unit of time seems to be at 1e-6, which lead to output results such as 132329040. How can I increase the time interval to make the output more readable for larger time deltas?

Body:
That is a feature so far only present via Jupyter line magic, as discussed here. It can be accessed via the "-u" flag, followed by the timer unit, in seconds. This is a sample usage:

def m():
  return [0]*10**8

%lprun -u 1e-3 -f m m()

Which displays the output with timer unit in milliseconds:

Out:
Timer unit: 0.001 s

Total time: 0.363548 s
File:
Function: m at line 1

Line # Hits Time Per Hit % Time Line Contents
==============================================================
1 def m():
2 1 363.5 363.5 100.0 return [0]*10**8

As documented in this PR.


问:
form_for 'file_field' not showing file chosen in edit action
I am using file_field and it is working fine on creation - file is getting saved. But when I'm doing edit of the same record no file chosen is coming.

I have created partial form which I am using in new and edit actions. When I am clicking on edit option of a record all other fields are coming pre-selected but file is not coming.

```<code># edit.html.erb
<h3>Order Detail</h3>
<div id="field">
  <div id="field0">
    <%= render 'form', order_detail: @order_detail %>
  </div>
</div>

# _form.html.erb
<%= form_for @order_detail do |f| %>
  <div class="form-group required">
    <label class="col-md-4 control-label" for="action_id">Delivery Date</label>
    <div class="col-md-5">
      <%=f.text_field :delivery_date, "data-provide" => 'datepicker', class: 'form-control input-md datepicker',id: 'selectDate2',placeholder: "Delivery date(yyyy-mm-dd)" ,required: true%>
    </div>
  </div>
  <div class="form-group required">
    <label class="col-md-4 control-label" for="action_id">Pdf File</label>
    <div class="col-md-5">
      <%=f.file_field :pdf_file, class: 'form-control input-md' ,required: true%>
    </div>
  </div>
  <div class="actions">
    <%= submit_tag "Submit",class:"btn btn-success" ,remote: true%>
  </div>
<%end%>
</code>```

I am expecting file chosen should come but it's not coming as it is stored in database.

答:
You need to show that file through a link parallel to your file field.
File field itself cannot show the stored file in edit mode.</p>

```<code><% if !f.object.new_record? && f.object.photo.present? %>
  <%= image_tag :photo.url(:small) %>
<% else %>
  <%=f.file_field :photo, class: 'form-control input-md' ,required: true%>
<% end %>
</code>```

Body:
I am using file_field and it is working fine on creation - file is getting saved. But when I'm doing edit of the same record no file chosen is coming.

I have created partial form which I am using in new and edit actions. When I am clicking on edit option of a record all other fields are coming pre-selected but file is not coming.

# edit.html.erb

Order Detail

    <%= render 'form', order_detail: @order_detail %>

# _form.html.erb
<%= form_for @order_detail do |f| %>

    Delivery Date

      <%=f.text_field :delivery_date, "data-provide" => 'datepicker', class: 'form-control input-md datepicker',id: 'selectDate2',placeholder: "Delivery date(yyyy-mm-dd)" ,required: true%>

    Pdf File

      <%=f.file_field :pdf_file, class: 'form-control input-md' ,required: true%>

    <%= submit_tag "Submit",class:"btn btn-success" ,remote: true%>

<%end%>

I am expecting file chosen should come but it's not coming as it is stored in database.

Body:
You need to show that file through a link parallel to your file field.
File field itself cannot show the stored file in edit mode.

<% if !f.object.new_record? && f.object.photo.present? %>
  <%= image_tag :photo.url(:small) %>
<% else %>
  <%=f.file_field :photo, class: 'form-control input-md' ,required: true%>
<% end %>


问:
Python: extracting datetime to year, month, and day result in float
My data has a datetime index like this 2016-11-05 23:40:00.

I want to extract the datetime elements into three new columns of the year, month, and day. I use the following

```<code>import datetime as dt
df['year'] = df.index.year
df['month'] = df.index.month
df['day'] = df.index.day
</code>```

But the results are in float

```<code>year    month   day
2016.0  11.0    5.0
</code>```

I want

```<code>year    month   day
2016    11      5
</code>```

Any help is appreciated.

答:
I think reason for floats are missing values, so if use pandas 0.24+ is possible use Nullable Integer Data Type:

```<code>df['year'] = df.index.year.astype('Int64')
df['month'] = df.index.month.astype('Int64')
df['day'] = df.index.day.astype('Int64')
</code>```

Body:
My data has a datetime index like this 2016-11-05 23:40:00.

I want to extract the datetime elements into three new columns of the year, month, and day. I use the following

import datetime as dt
df['year'] = df.index.year
df['month'] = df.index.month
df['day'] = df.index.day

But the results are in float

year    month   day
2016.0  11.0    5.0

I want

year    month   day
2016    11      5

Any help is appreciated.

Body:
I think reason for floats are missing values, so if use pandas 0.24+ is possible use Nullable Integer Data Type:

df['year'] = df.index.year.astype('Int64')
df['month'] = df.index.month.astype('Int64')
df['day'] = df.index.day.astype('Int64')


问:
HTML Table structure not displaying data in right order
I have a table that displays data from JSON. I am able to display the data in the table but it does not render the table very well.

The structure of the table is distorted. It does not display the data in the order in which I want it to display.

```<code><table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
    <thead>
        <tr>
            <th>Name</th>
            <th>Number</th>
            <th>Amount</th>
        </tr>
    </thead>

    <?php
        $url = 'xxxxxxxxxxxxxxxxxxxxxx'; // path to your JSON file
        //$url = 'data.json'; // path to your JSON file
        $data = file_get_contents($url); // put the contents of the file into a variable
        $characters = json_decode($data);
        $i = 0;
    ?>
    <tbody>
        <tr>
        <?php
            foreach ($characters as $character)
            {
                ?>
            <td>
                <?php echo $character->name; ?>
            </td>
            <td>
                <?php echo $character->phoneNumber; ?>
            </td>
            <td>
                <?php echo $character->amount; ?>
            </td>
            <?php }
        ?>
        </tr>
    </tbody>
</table>
</code>```

I expect three columns only. With the data showing in the right order

答:
Try</p>

```<code><table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
    <tr>
        <th>Name</th>
        <th>Number</th>
        <th>Amount</th>
    </tr>
</thead>

<?php
            $url = 'xxxxxxxxxxxxxxxxxxxxxx'; // path to your JSON file
            //$url = 'data.json'; // path to your JSON file
            $data = file_get_contents($url); // put the contents of the file into a variable
            $characters = json_decode($data);
            $i = 0;
            ?>
    <tbody>
        <?php
            foreach ($characters as $character)
            {
             ?>
            <tr>
                <td>
                    <?php echo $character->name; ?>
                </td>
                <td>
                    <?php echo $character->phoneNumber; ?>
                </td>
                <td>
                    <?php echo $character->amount; ?>
                </td>
            </tr>
            <?php }
            ?>
    </tbody>
</table>
</code>```

Body:
I have a table that displays data from JSON. I am able to display the data in the table but it does not render the table very well.

The structure of the table is distorted. It does not display the data in the order in which I want it to display.

            Name
            Number
            Amount

    <?php
        $url = 'xxxxxxxxxxxxxxxxxxxxxx'; // path to your JSON file
        //$url = 'data.json'; // path to your JSON file
        $data = file_get_contents($url); // put the contents of the file into a variable
        $characters = json_decode($data);
        $i = 0;
    ?>

        <?php
            foreach ($characters as $character)
            {
                ?>

                <?php echo $character->name; ?>

                <?php echo $character->phoneNumber; ?>

                <?php echo $character->amount; ?>

            <?php }
        ?>

I expect three columns only. With the data showing in the right order

Body:
Try

<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
    <tr>
        <th>Name</th>
        <th>Number</th>
        <th>Amount</th>
    </tr>
</thead>

<?php
            $url = 'xxxxxxxxxxxxxxxxxxxxxx'; // path to your JSON file
            //$url = 'data.json'; // path to your JSON file
            $data = file_get_contents($url); // put the contents of the file into a variable
            $characters = json_decode($data);
            $i = 0;
            ?>
    <tbody>
        <?php
            foreach ($characters as $character)
            {
             ?>
            <tr>
                <td>
                    <?php echo $character->name; ?>
                </td>
                <td>
                    <?php echo $character->phoneNumber; ?>
                </td>
                <td>
                    <?php echo $character->amount; ?>
                </td>
            </tr>
            <?php }
            ?>
    </tbody>
</table>


问:
Transforming a collection to a map in Elixir
If I've got a collection of the form:

```<code>[{key, value}, {key, value2}, {key2, value3}]
</code>```

how do I transform it to a map of the form

```<code>%{key => [value, value2], key2 => [value3]}
</code>```

?

答:
Reducing with Map.update/4 would be a good fit:

[{:key, :value}, {:key, :value2}, {:key2, :value3}]
|> Enum.reduce(%{}, fn {k, v}, acc ->
  Map.update(acc, k, [v], fn l -> [v | l] end)
end)
#⇒ %{key: [:value2, :value], key2: [:value3]}
```

<p>To preserve an order of lists, map to <code>{k, Enum.reverse(n)}</code> afterwards.</p>

<pre class="lang-rb prettyprint-override"><code>[{:key, :value}, {:key, :value2}, {:key2, :value3}]
|> Enum.reduce(%{}, fn {k, v}, acc ->
  Map.update(acc, k, [v], fn l -> [v | l] end)
end)
|> Enum.map(fn {k, v} -> {k, Enum.reverse(v)} end)
#⇒ %{key: [:value, :value2], key2: [:value3]}
</code>```

Another option would be Enum.group_by/3

[{:key, :value}, {:key, :value2}, {:key2, :value3}]
|> Enum.group_by(&elem(&1, 0))
|> Enum.map(fn {k, v} -> {k, Keyword.values(v)} end)
|> Enum.into(%{})
#⇒ %{key: [:value, :value2], key2: [:value3]}
```

<p>or, with a mapper:</p>

<pre class="lang-rb prettyprint-override"><code>[{:key, :value}, {:key, :value2}, {:key2, :value3}]
|> Enum.group_by(&elem(&1, 0), &elem(&1, 1))
#⇒ %{key: [:value, :value2], key2: [:value3]}
</code>```

Body:
If I've got a collection of the form:

[{key, value}, {key, value2}, {key2, value3}]

how do I transform it to a map of the form

%{key => [value, value2], key2 => [value3]}

?

Body:
Reducing with Map.update/4 would be a good fit:

[{:key, :value}, {:key, :value2}, {:key2, :value3}]
|> Enum.reduce(%{}, fn {k, v}, acc ->
  Map.update(acc, k, [v], fn l -> [v | l] end)
end)
#⇒ %{key: [:value2, :value], key2: [:value3]}

To preserve an order of lists, map to {k, Enum.reverse(n)} afterwards.

[{:key, :value}, {:key, :value2}, {:key2, :value3}]
|> Enum.reduce(%{}, fn {k, v}, acc ->
  Map.update(acc, k, [v], fn l -> [v | l] end)
end)
|> Enum.map(fn {k, v} -> {k, Enum.reverse(v)} end)
#⇒ %{key: [:value, :value2], key2: [:value3]}

Another option would be Enum.group_by/3

[{:key, :value}, {:key, :value2}, {:key2, :value3}]
|> Enum.group_by(&elem(&1, 0))
|> Enum.map(fn {k, v} -> {k, Keyword.values(v)} end)
|> Enum.into(%{})
#⇒ %{key: [:value, :value2], key2: [:value3]}

or, with a mapper:

[{:key, :value}, {:key, :value2}, {:key2, :value3}]
|> Enum.group_by(&elem(&1, 0), &elem(&1, 1))
#⇒ %{key: [:value, :value2], key2: [:value3]}


问:
Webpack not finding SCSS ampersand class
I am migrating some SCSS code over that was written for our team to our rails app with webpacker (which runs webpack) and am running into some problems. It is probably quite easy but I am a bit unfamiliar with SCSS and webpack in general, so it has been causing some headaches.

I have an application.css file that looks like this:

```<code>@import "./base/_fonts.scss";
@import "./base/_typography.scss";
@import "./base/_transition.scss";
@import "./base/_grid.scss";
@import "./base/_space.scss";
@import "./base/_link.scss";
...
</code>```

Inside "_transition.scss" there is:

```<code>// Timing
.timing {
  &-1 {
    transition-timing-function: ease;
  }

  &-2 {
    transition-timing-function: ease-in-out;
  }

  &-3 {
    transition-timing-function: var(--bezier-1);
  }
}
</code>```

And yet when webpack compiles this section in "_link.scss" fails:

```<code>// Links
.link {
  @apply no-underline
        font-medium
        inline-block
        timing-1 duration-1 property-all;
</code>```

With the error:

```<code>ERROR in ./app/javascript/stylesheets/application.css (./node_modules/css-loader/dist/cjs.js??ref--3-1!./node_modules/postcss-loader/src??ref--3-2!./app/javascript/stylesheets/application.css)
Module build failed (from ./node_modules/postcss-loader/src/index.js):
SyntaxError

(3:3) `@apply` cannot be used with `.timing-1` because `.timing-1` either cannot be found, or its actual definition includes a pseudo-selector like :hover, :active, etc. If you're sure that `.timing-1` exists, make sure that any `@import` statements are being properly processed *before* Tailwind CSS sees your CSS, as `@apply` can only be used for classes in the same CSS tree.
I am guessing that the scss isn't compiled right because I am using postcss-loader instead of sass-loader or something, but I am at the edge of my knowledge with this stuff and wouldn't know how to change that even if that were the case.
</code>```

Here is my "postcss.config.js" file:

```<code>const tailwindcss = require('tailwindcss')

module.exports = {
  parser: require('postcss-scss'),

  plugins: [
    require('postcss-import'),
    require('postcss-strip-inline-comments'),
    require('tailwindcss')('./app/javascript/stylesheets/tailwind.js'),
    require('postcss-flexbugs-fixes'),
    require('postcss-nested'),
    require('postcss-preset-env')({
      autoprefixer: {
        flexbox: 'no-2009'
      },
      stage: 3
    }),
    require('autoprefixer')
  ]
}
</code>```

Any help is greatly appreciated!

答: This had to do with my entry css file being named "css" and not "scss", which caused the sass loader to give this strange error.</p>

Body:
I am migrating some SCSS code over that was written for our team to our rails app with webpacker (which runs webpack) and am running into some problems. It is probably quite easy but I am a bit unfamiliar with SCSS and webpack in general, so it has been causing some headaches.

I have an application.css file that looks like this:

@import "./base/_fonts.scss";
@import "./base/_typography.scss";
@import "./base/_transition.scss";
@import "./base/_grid.scss";
@import "./base/_space.scss";
@import "./base/_link.scss";
...

Inside "_transition.scss" there is:

// Timing
.timing {
  &-1 {
    transition-timing-function: ease;
  }

  &-2 {
    transition-timing-function: ease-in-out;
  }

  &-3 {
    transition-timing-function: var(--bezier-1);
  }
}

And yet when webpack compiles this section in "_link.scss" fails:

// Links
.link {
  @apply no-underline
        font-medium
        inline-block
        timing-1 duration-1 property-all;

With the error:

ERROR in ./app/javascript/stylesheets/application.css (./node_modules/css-loader/dist/cjs.js??ref--3-1!./node_modules/postcss-loader/src??ref--3-2!./app/javascript/stylesheets/application.css)
Module build failed (from ./node_modules/postcss-loader/src/index.js):
SyntaxError

(3:3) `@apply` cannot be used with `.timing-1` because `.timing-1` either cannot be found, or its actual definition includes a pseudo-selector like :hover, :active, etc. If you're sure that `.timing-1` exists, make sure that any `@import` statements are being properly processed *before* Tailwind CSS sees your CSS, as `@apply` can only be used for classes in the same CSS tree.
I am guessing that the scss isn't compiled right because I am using postcss-loader instead of sass-loader or something, but I am at the edge of my knowledge with this stuff and wouldn't know how to change that even if that were the case.

Here is my "postcss.config.js" file:

const tailwindcss = require('tailwindcss')

module.exports = {
  parser: require('postcss-scss'),

  plugins: [
    require('postcss-import'),
    require('postcss-strip-inline-comments'),
    require('tailwindcss')('./app/javascript/stylesheets/tailwind.js'),
    require('postcss-flexbugs-fixes'),
    require('postcss-nested'),
    require('postcss-preset-env')({
      autoprefixer: {
        flexbox: 'no-2009'
      },
      stage: 3
    }),
    require('autoprefixer')
  ]
}

Any help is greatly appreciated!


问:
Why are .innerHTML problems not an issue when using JQuery().html()?
I worked out any single instance of document.getElementById("MyID").innerHTML = "A value" in this Javascript World Clock guide causes Wordpress Admin not to load completely and breaks various areas of the Wordpress admin interface.

I solved it by replacing each instance with jQuery("#MyID").html("A value")) which appears to work fine. What is causing .innerHTML to fail miserably but not JQuery().html()?

答:
This is how jQuery does it:</p>

```<code>html: function( value ) {
    if ( value === undefined ) {
        return this[0] && this[0].nodeType === 1 ?
            this[0].innerHTML.replace(rinlinejQuery, "") :
            null;

    // See if we can take a shortcut and just use innerHTML
    } else if ( typeof value === "string" && !rnocache.test( value ) &&
        (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
        !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {

        value = value.replace(rxhtmlTag, "<$1></$2>");

        try {
            for ( var i = 0, l = this.length; i < l; i++ ) {
                // Remove element nodes and prevent memory leaks
                if ( this[i].nodeType === 1 ) {
                    jQuery.cleanData( this[i].getElementsByTagName("*") );
                    this[i].innerHTML = value;
                }
            }

        // If using innerHTML throws an exception, use the fallback method
        } catch(e) {
            this.empty().append( value );
        }

    } else if ( jQuery.isFunction( value ) ) {
        this.each(function(i){
            var self = jQuery( this );

            self.html( value.call(this, i, self.html()) );
        });

    } else {
        this.empty().append( value );
    }

    return this;
},
</code>```

Body:
This is how jQuery does it:

html: function( value ) {
    if ( value === undefined ) {
        return this[0] && this[0].nodeType === 1 ?
            this[0].innerHTML.replace(rinlinejQuery, "") :
            null;

    // See if we can take a shortcut and just use innerHTML
    } else if ( typeof value === "string" && !rnocache.test( value ) &&
        (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
        !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {

        value = value.replace(rxhtmlTag, "<$1></$2>");

        try {
            for ( var i = 0, l = this.length; i < l; i++ ) {
                // Remove element nodes and prevent memory leaks
                if ( this[i].nodeType === 1 ) {
                    jQuery.cleanData( this[i].getElementsByTagName("*") );
                    this[i].innerHTML = value;
                }
            }

        // If using innerHTML throws an exception, use the fallback method
        } catch(e) {
            this.empty().append( value );
        }

    } else if ( jQuery.isFunction( value ) ) {
        this.each(function(i){
            var self = jQuery( this );

            self.html( value.call(this, i, self.html()) );
        });

    } else {
        this.empty().append( value );
    }

    return this;
},


问:
how many words end in certain character in function calling to different file?
So I'm trying to make a small function that takes the name of a file as an argument and returns how many WORDS in the file end in "!", "?" or ".".

So far I've tried the following:

```<code>def count_possible_sentences(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
    count = 0
    for ch in word_list:
        if ch in "!?.":
            count += 1
    return count
</code>```

but this isn't working and is not counting how many individual WORDS end with those specified characters in the separate called file. I thought of splitting every word and looping through each character and if it contains one of the character it adds a +1 to the count but I am unsure of how to do that.

edit: also thought of just using .count? would that work? cheers

edit2:
here are my doctests I'm trying to make them pass:

```<code>def count_possible_sentences(file_name):
    """
    >>> count_possible_sentences("frances_oldham_kelsey.txt")
    45
    >>> count_possible_sentences("ernest_rutherford.txt")
    32
    >>> count_possible_sentences("marie_curie.txt")
    24
    """
</code>```

and here is a link to the .txt that is failing:
https://pastebin.com/raw/1NYPeY29

it's saying expected: 45 got: 52

答:
You can do this one line, if you prefer list comprehension. The w[-1] in '!?.' checks last character of a word.

```<code>def count_possible_sentences(file_name):
    return len([w for w in open(file_name).read().split() if w[-1] in '!?.'])

print(count_possible_sentences('input_file.txt'))
</code>```

Body:
So I'm trying to make a small function that takes the name of a file as an argument and returns how many WORDS in the file end in "!", "?" or ".".

So far I've tried the following:

def count_possible_sentences(file_name):
    with open(file_name) as wordfile:
        text_str = wordfile.read()
        word_list = text_str.split()
    count = 0
    for ch in word_list:
        if ch in "!?.":
            count += 1
    return count

but this isn't working and is not counting how many individual WORDS end with those specified characters in the separate called file. I thought of splitting every word and looping through each character and if it contains one of the character it adds a +1 to the count but I am unsure of how to do that.

edit: also thought of just using .count? would that work? cheers

edit2:
here are my doctests I'm trying to make them pass:

def count_possible_sentences(file_name):
    """
    >>> count_possible_sentences("frances_oldham_kelsey.txt")
    45
    >>> count_possible_sentences("ernest_rutherford.txt")
    32
    >>> count_possible_sentences("marie_curie.txt")
    24
    """

and here is a link to the .txt that is failing:
https://pastebin.com/raw/1NYPeY29

it's saying expected: 45 got: 52

Body:
You can do this one line, if you prefer list comprehension. The w[-1] in '!?.' checks last character of a word.

def count_possible_sentences(file_name):
    return len([w for w in open(file_name).read().split() if w[-1] in '!?.'])

print(count_possible_sentences('input_file.txt'))