问:
How to merge two models in keras tensoflow to make one model
I have two pre-trained models one is for age classification and the other is for Gender Classification. I wanted to make age-gender classifier network so i wanted to merge the two networks and pridict both age and gender from same network .

what i tried was

```<code>from keras.models import load_model

model_age = load_model(model_age_path)
model_gender = load_model(model_gender_path)
</code>```

how can i merge the two models and train network that do both

答:
It depends on what "merge" means to you.

If you want to output both age and gender from a single input, then you need multiple "heads":

from keras import Input
from keras.models import load_model

model_age = load_model('age.hdf5')
model_gender = load_model('gender.hdf5')

x = Input(shape=[299, 299, 3])
y_age = model_age(x)
y_gen = model_gender(x)

model = Model(inputs=x, outputs=[y_age, y_gen])

data, target = load_data()
p_age, p_gender = model.predict(data)

print(p_age)
# [[ 0.57398415,  0.42601582],
#  [ 0.5397228 ,  0.46027723],
#  [ 0.6648131 ,  0.33518684],
#  [ 0.5917415 ,  0.4082585 ]]

print(p_gender)
# [[ 0.13119246],
#  [ 0.        ],
#  [ 0.1875571 ],
#  [ 0.        ]]
```

<p>But now considers this: both tasks (regress age, classify gender) have -- to some extent -- some degree of similarity, right? If your data is composed by images, for example, both need to detect lines, patches and simple geometric forms to make their decision. In other words, a lot of conv layers' weights could be reused by both networks, making the whole process more efficient.
You can achieve this training a new model that do both things at the same time:</p>

<pre class="lang-py prettyprint-override"><code>from keras.applications import VGG19

base_model = VGG19(weights='imagenet')  # or any model, really.
y = base_model.output
y_age = Dense(1, activation='relu')(y)

y = base_model.output
y = Dense(128, activation='relu')(y)
y = Dense(128, activation='relu')(y)
y_gender = Dense(2, activation='softmax')(y)

model = Model(inputs=base_model.inputs, outputs=[y_age, y_gender])
</code>```

Body:
I have two pre-trained models one is for age classification and the other is for Gender Classification. I wanted to make age-gender classifier network so i wanted to merge the two networks and pridict both age and gender from same network .

what i tried was

from keras.models import load_model

model_age = load_model(model_age_path)
model_gender = load_model(model_gender_path)

how can i merge the two models and train network that do both

Body:
It depends on what "merge" means to you.

If you want to output both age and gender from a single input, then you need multiple "heads":

from keras import Input
from keras.models import load_model

model_age = load_model('age.hdf5')
model_gender = load_model('gender.hdf5')

x = Input(shape=[299, 299, 3])
y_age = model_age(x)
y_gen = model_gender(x)

model = Model(inputs=x, outputs=[y_age, y_gen])

data, target = load_data()
p_age, p_gender = model.predict(data)

print(p_age)
# [[ 0.57398415,  0.42601582],
#  [ 0.5397228 ,  0.46027723],
#  [ 0.6648131 ,  0.33518684],
#  [ 0.5917415 ,  0.4082585 ]]

print(p_gender)
# [[ 0.13119246],
#  [ 0.        ],
#  [ 0.1875571 ],
#  [ 0.        ]]

But now considers this: both tasks (regress age, classify gender) have -- to some extent -- some degree of similarity, right? If your data is composed by images, for example, both need to detect lines, patches and simple geometric forms to make their decision. In other words, a lot of conv layers' weights could be reused by both networks, making the whole process more efficient.
You can achieve this training a new model that do both things at the same time:

from keras.applications import VGG19

base_model = VGG19(weights='imagenet')  # or any model, really.
y = base_model.output
y_age = Dense(1, activation='relu')(y)

y = base_model.output
y = Dense(128, activation='relu')(y)
y = Dense(128, activation='relu')(y)
y_gender = Dense(2, activation='softmax')(y)

model = Model(inputs=base_model.inputs, outputs=[y_age, y_gender])


来源: stackexchange

问:
Error on commit - How to increase Docker default container size when using Docker Toolbox and Windows 7
I'm running Docker on Windows 7, so Docker runs within a Virtual Box.

I've got an issue where I've got an Oracle image which has then had a database restored to it, pushing the image size up to 7.5 gigs. I want to do a docker commit on this, but I'm getting an out of space error when I do the commit.

I've seen a lot of posts on changing the default container size, but I'm not sure if this is possible with aufs, or how to change to a different file system type when running on Windows 7/VirtualBox.

Does anyone know how to increase the default container size in this environment ?

```<code>Error response from daemon: Error processing tar file(exit status 1): write /u01/app/oracle/oradata/XE/support.dbf: no space left on device
</code>```

Docker info:

```<code>    Containers: 1
 Running: 1
 Paused: 0
 Stopped: 0
Images: 72
Server Version: 17.10.0-ce
Storage Driver: aufs
 Root Dir: /mnt/sda1/var/lib/docker/aufs
 Backing Filesystem: extfs
 Dirs: 127
 Dirperm1 Supported: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
 Volume: local
 Network: bridge host macvlan null overlay
 Log: awslogs fluentd gcplogs gelf journald json-file logentries splunk syslog
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Init Binary: docker-init
containerd version: 06b9cb35161009dcb7123345749fef02f7cea8e0
runc version: 0351df1c5a66838d0c392b4ac4cf9450de844e2d
init version: 949e6fa
Security Options:
 seccomp
  Profile: default
Kernel Version: 4.4.93-boot2docker
Operating System: Boot2Docker 17.10.0-ce (TCL 7.2); HEAD : 34fe485 - Wed Oct 18 17:16:34 UTC 2017
OSType: linux
Architecture: x86_64
CPUs: 2
Total Memory: 7.79GiB
Name: default
ID: 2NWU:57WJ:4QAP:EBMY:MMF2:JFWA:IBWU:THGO:A4VD:SGVW:YQBP:MP2N
Docker Root Dir: /mnt/sda1/var/lib/docker
Debug Mode (client): false
Debug Mode (server): true
 File Descriptors: 24
 Goroutines: 35
 System Time: 2017-12-06T09:33:14.736388742Z
 EventsListeners: 2
Registry: https://index.docker.io/v1/
Labels:
 provider=virtualbox
Experimental: false
Insecure Registries:
 127.0.0.0/8
</code>```

答:
The default size for a docker machine is 20GB, you can double-check by running docker-machine inspect default. This size can be configured when creating the machine from the cli. You can recreate the default machine and set the size as follows:

```<code>docker-machine rm default
docker-machine create -d virtualbox --virtualbox-disk-size "400000" default
</code>```

You can also edit the file C:\Program Files\Docker Toolbox\start.sh to set default values for size and ram for created machines.

ContentLicense: CC BY-SA 3.0

Body:
I'm running Docker on Windows 7, so Docker runs within a Virtual Box.

I've got an issue where I've got an Oracle image which has then had a database restored to it, pushing the image size up to 7.5 gigs. I want to do a docker commit on this, but I'm getting an out of space error when I do the commit.

I've seen a lot of posts on changing the default container size, but I'm not sure if this is possible with aufs, or how to change to a different file system type when running on Windows 7/VirtualBox.

Does anyone know how to increase the default container size in this environment ?

Error response from daemon: Error processing tar file(exit status 1): write /u01/app/oracle/oradata/XE/support.dbf: no space left on device

Docker info:

    Containers: 1
 Running: 1
 Paused: 0
 Stopped: 0
Images: 72
Server Version: 17.10.0-ce
Storage Driver: aufs
 Root Dir: /mnt/sda1/var/lib/docker/aufs
 Backing Filesystem: extfs
 Dirs: 127
 Dirperm1 Supported: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
 Volume: local
 Network: bridge host macvlan null overlay
 Log: awslogs fluentd gcplogs gelf journald json-file logentries splunk syslog
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Init Binary: docker-init
containerd version: 06b9cb35161009dcb7123345749fef02f7cea8e0
runc version: 0351df1c5a66838d0c392b4ac4cf9450de844e2d
init version: 949e6fa
Security Options:
 seccomp
  Profile: default
Kernel Version: 4.4.93-boot2docker
Operating System: Boot2Docker 17.10.0-ce (TCL 7.2); HEAD : 34fe485 - Wed Oct 18 17:16:34 UTC 2017
OSType: linux
Architecture: x86_64
CPUs: 2
Total Memory: 7.79GiB
Name: default
ID: 2NWU:57WJ:4QAP:EBMY:MMF2:JFWA:IBWU:THGO:A4VD:SGVW:YQBP:MP2N
Docker Root Dir: /mnt/sda1/var/lib/docker
Debug Mode (client): false
Debug Mode (server): true
 File Descriptors: 24
 Goroutines: 35
 System Time: 2017-12-06T09:33:14.736388742Z
 EventsListeners: 2
Registry: https://index.docker.io/v1/
Labels:
 provider=virtualbox
Experimental: false
Insecure Registries:
 127.0.0.0/8

Body:
The default size for a docker machine is 20GB, you can double-check by running docker-machine inspect default. This size can be configured when creating the machine from the cli. You can recreate the default machine and set the size as follows:

docker-machine rm default
docker-machine create -d virtualbox --virtualbox-disk-size "400000" default

You can also edit the file C:\Program Files\Docker Toolbox\start.sh to set default values for size and ram for created machines.


问:
How to set up email alerts for Azure SQL Server database for new sign ups
My web app uses ASP.NET MVC and out of box account model for registration. Azure SQL Server table where new sign-ups are stored is AspNetUsers.

How can I setup email alerts when a new user signs up on my web site?

Thanks.

答: You can make a Logic App to poll the table on the database periodically and add an action item to send an email as explained here or make a RESTful call.</p>


问:
Highchart - hide name in legend if no data
This is a little specific situation, I need to compare ITEMS and show the result in a chart. User enters two or three or four article ID and gets data in chart.
Problem is when user enters only two or three articles ID, then in chart legend, I still get a name for line without data.

```<code>$scope.chartConfig1 = getChartConfigWithYaxisPlotLines('Production');
            $scope.chartConfig1.series.push({
                id: 1,
                name: "Item " + firstId,
                data: $scope.data[0],
                tooltip: {
                    valueDecimals: 2
                }
            }, {
                id: 2,
                name: "Item  " + firstId,
                color: "#1ea775",
                data: $scope.data[1],
                tooltip: {
                    valueDecimals: 2
                }
            }, {
                id: 3,
                name: "Item  " + firstId,
                data: $scope.data[2],
                tooltip: {
                    valueDecimals: 2
                }
            }, {
                id: 4,
                name: "Item " + firstId,
                data: $scope.data[3],
                tooltip: {
                    valueDecimals: 2
                }
            },{
                id: 5,
                name: "Item " + secondId,
                data: $scope.data[4],
                tooltip: {
                    valueDecimals: 2
                }
            }, {
                id: 6,
                name: "Item " + secondId,
                data: $scope.data[5],
                tooltip: {
                    valueDecimals: 2
                }
            }, {
                id: 7,
                name: "Item " + secondId,
                data: $scope.data[6],
                tooltip: {
                    valueDecimals: 2
                }
            }, {
                id: 8,
                name: "Item " + secondId,
                data: $scope.data[7],
                tooltip: {
                    valueDecimals: 2
                }
            },{
                id: 9,
                name: "Item " + thirdId,
                data: $scope.data[8],
                tooltip: {
                    valueDecimals: 2
                }
            }, {
                id: 10,
                name: "Item " + thirdId,
                data: $scope.data[9],
                tooltip: {
                    valueDecimals: 2
                }
            }, {
                id: 11,
                name: "Item " + thirdId,
                data: $scope.data[10],
                tooltip: {
                    valueDecimals: 2
                }
            }, {
                id: 12,
                name: "Item " + thirdId,
                data: $scope.data[11],
                tooltip: {
                    valueDecimals: 2
                }
            }
            );
</code>```

In legend, I show Item and article ID (passed in function when submitting input ID for compare), and if we compare only two article, in legend we get Item 1, Item 2, Item undefined, Item undefined. If enter all four input everything is fine

Is there any way in highchart to hide name in legend if data is null or undefined? Thnx

答:
You can use the load event to examine series in a loop and hide the ones without any data:

```<code>var chart = Highcharts.chart('container', {

  chart: {
    events: {
      load: function() {
        this.series.forEach(function(s) {
          s.update({
            showInLegend: s.points.length
          });
        });
      }
    }
  },

  series: [{
    data: [1, 2]
  }, {
    data: [3, 4, 2]
  }, {
    data: [] // no data
  }]
});
</code>```

Live demo: http://jsfiddle.net/kkulig/355u0kaw/

API references:

https://api.highcharts.com/highcharts/plotOptions.series.showInLegend

https://api.highcharts.com/highcharts/chart.events.render

Body:
This is a little specific situation, I need to compare ITEMS and show the result in a chart. User enters two or three or four article ID and gets data in chart.
Problem is when user enters only two or three articles ID, then in chart legend, I still get a name for line without data.

$scope.chartConfig1 = getChartConfigWithYaxisPlotLines('Production');
            $scope.chartConfig1.series.push({
                id: 1,
                name: "Item " + firstId,
                data: $scope.data[0],
                tooltip: {
                    valueDecimals: 2
                }
            }, {
                id: 2,
                name: "Item  " + firstId,
                color: "#1ea775",
                data: $scope.data[1],
                tooltip: {
                    valueDecimals: 2
                }
            }, {
                id: 3,
                name: "Item  " + firstId,
                data: $scope.data[2],
                tooltip: {
                    valueDecimals: 2
                }
            }, {
                id: 4,
                name: "Item " + firstId,
                data: $scope.data[3],
                tooltip: {
                    valueDecimals: 2
                }
            },{
                id: 5,
                name: "Item " + secondId,
                data: $scope.data[4],
                tooltip: {
                    valueDecimals: 2
                }
            }, {
                id: 6,
                name: "Item " + secondId,
                data: $scope.data[5],
                tooltip: {
                    valueDecimals: 2
                }
            }, {
                id: 7,
                name: "Item " + secondId,
                data: $scope.data[6],
                tooltip: {
                    valueDecimals: 2
                }
            }, {
                id: 8,
                name: "Item " + secondId,
                data: $scope.data[7],
                tooltip: {
                    valueDecimals: 2
                }
            },{
                id: 9,
                name: "Item " + thirdId,
                data: $scope.data[8],
                tooltip: {
                    valueDecimals: 2
                }
            }, {
                id: 10,
                name: "Item " + thirdId,
                data: $scope.data[9],
                tooltip: {
                    valueDecimals: 2
                }
            }, {
                id: 11,
                name: "Item " + thirdId,
                data: $scope.data[10],
                tooltip: {
                    valueDecimals: 2
                }
            }, {
                id: 12,
                name: "Item " + thirdId,
                data: $scope.data[11],
                tooltip: {
                    valueDecimals: 2
                }
            }
            );

In legend, I show Item and article ID (passed in function when submitting input ID for compare), and if we compare only two article, in legend we get Item 1, Item 2, Item undefined, Item undefined. If enter all four input everything is fine

Is there any way in highchart to hide name in legend if data is null or undefined? Thnx

Body:
You can use the load event to examine series in a loop and hide the ones without any data:

var chart = Highcharts.chart('container', {

  chart: {
    events: {
      load: function() {
        this.series.forEach(function(s) {
          s.update({
            showInLegend: s.points.length
          });
        });
      }
    }
  },

  series: [{
    data: [1, 2]
  }, {
    data: [3, 4, 2]
  }, {
    data: [] // no data
  }]
});

Live demo: http://jsfiddle.net/kkulig/355u0kaw/

API references:

https://api.highcharts.com/highcharts/plotOptions.series.showInLegend

https://api.highcharts.com/highcharts/chart.events.render


问:
Java 8 Stream: Defining collectors based on other collectors
I'm new to using Java 8 Stream APIs but I'm looking to use it for the following problem.  Say I have a POJO called InputRecord containing name, fieldA, and fieldB properties that can represent each row record of the following:

```<code>name | fieldA | fieldB
----------------------
A    | 100    | 1.1
A    | 150    | 2.0
B    | 200    | 1.5
A    | 120    | 1.3
</code>```

InputRecord would look like:

```<code>public class InputRecord {
    private String name;
    private Integer fieldA;
    private BigDecimal fieldB;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getFieldA() {
        return fieldA;
    }

    public void setFieldA(Integer fieldA) {
        this.fieldA = fieldA;
    }

    public BigDecimal getFieldB() {
        return fieldB;
    }

    public void setFieldB(BigDecimal fieldB) {
        this.fieldB = fieldB;
    }
}
</code>```

Those four records above need to be combined into two records grouped by name, where:

Property fieldA is summed

Property fieldB is summed

The combined records includes a fieldC property which is the result of multiplying the accumulating sums of both fieldA and fieldB.

Therefore the results for above would be:

```<code>name | sumOfFieldA | sumOfFieldB | fieldC (sumOfFieldA*sumOfFieldB)
-------------------------------------------------------------------
A    | 370         | 4.4         | 1628
B    | 200         | 1.5         | 300
</code>```

A different POJO called OutputRecord would represent each row record of the combined records:

```<code>public class OutputRecord {
    private String name;
    private Integer sumOfFieldA;
    private BigDecimal sumOfFieldB;
    private BigDecimal fieldC;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getSumOfFieldA() {
        return sumOfFieldA;
    }

    public void setSumOfFieldA(Integer sumOfFieldA) {
        this.sumOfFieldA = sumOfFieldA;
    }

    public BigDecimal getSumOfFieldB() {
        return sumOfFieldB;
    }

    public void setSumOfFieldB(BigDecimal sumOfFieldB) {
        this.sumOfFieldB = sumOfFieldB;
    }

    public BigDecimal getFieldC() {
        return fieldC;
    }

    public void setFieldC(BigDecimal fieldC) {
        this.fieldC = fieldC;
    }
}
</code>```

What are some good approaches/solutions for transforming a list of InputRecords into a list of OutputRecords?

I was seeing if the following link would help but I got stuck trying to put collectors for fieldA and fieldB together in order to form a new collector for fieldC:
Java 8 Stream: groupingBy with multiple Collectors

```<code>Collector<InputRecord, ?, Integer> fieldACollector = Collectors.summingInt(InputRecord::getFieldA);
Collector<InputRecord, ?, BigDecimal> fieldBCollector = Collectors.reducing(BigDecimal.ZERO, InputRecord::getFieldB, BigDecimal::add);

List<Collector<InputRecord, ?, ?>> collectors = Arrays.asList(fieldACollector, fieldBCollector); // need a fieldCCollector object in the list
</code>```

The collectors object would then be used to create a complexCollector object (as per the accepted answer by Tagir Valeev in the above link).

答:
You can use Stream.reduce(..) to transform two records into a single one. It creates a bunch of temporary objects that needs to be garbage collected by the JVM.</p>

```<code>Collection<InputRecord> input = Arrays.asList(
        new InputRecord("A", 100, new BigDecimal(1.1)),
        new InputRecord("A", 150, new BigDecimal(2.0)),
        new InputRecord("B", 200, new BigDecimal(1.5)),
        new InputRecord("A", 120, new BigDecimal(1.3)));

Collection<OutputRecord> output = input.stream()
        // group records for particular Name into a List
        .collect(Collectors.groupingBy(InputRecord::getName))
        .values().stream()
        // Reduce every List to a single records, performing summing
        .map(records -> records.stream()
                .reduce((a, b) ->
                        new InputRecord(a.getName(),
                                a.getFieldA() + b.getFieldA(),
                                a.getFieldB().add(b.getFieldB()))))
        .filter(Optional::isPresent)
        .map(Optional::get)
        // Finally transform the InputRecord to OutputRecord
        .map(record -> new OutputRecord(record.getName(),
                record.getFieldA(),
                record.getFieldB(),
                record.getFieldB().multiply(new BigDecimal(record.getFieldA()))))
        .collect(Collectors.toList());
</code>```

Body:
I'm new to using Java 8 Stream APIs but I'm looking to use it for the following problem.  Say I have a POJO called InputRecord containing name, fieldA, and fieldB properties that can represent each row record of the following:

name | fieldA | fieldB
----------------------
A    | 100    | 1.1
A    | 150    | 2.0
B    | 200    | 1.5
A    | 120    | 1.3

InputRecord would look like:

public class InputRecord {
    private String name;
    private Integer fieldA;
    private BigDecimal fieldB;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getFieldA() {
        return fieldA;
    }

    public void setFieldA(Integer fieldA) {
        this.fieldA = fieldA;
    }

    public BigDecimal getFieldB() {
        return fieldB;
    }

    public void setFieldB(BigDecimal fieldB) {
        this.fieldB = fieldB;
    }
}

Those four records above need to be combined into two records grouped by name, where:

Property fieldA is summed

Property fieldB is summed

The combined records includes a fieldC property which is the result of multiplying the accumulating sums of both fieldA and fieldB.

Therefore the results for above would be:

name | sumOfFieldA | sumOfFieldB | fieldC (sumOfFieldA*sumOfFieldB)
-------------------------------------------------------------------
A    | 370         | 4.4         | 1628
B    | 200         | 1.5         | 300

A different POJO called OutputRecord would represent each row record of the combined records:

public class OutputRecord {
    private String name;
    private Integer sumOfFieldA;
    private BigDecimal sumOfFieldB;
    private BigDecimal fieldC;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getSumOfFieldA() {
        return sumOfFieldA;
    }

    public void setSumOfFieldA(Integer sumOfFieldA) {
        this.sumOfFieldA = sumOfFieldA;
    }

    public BigDecimal getSumOfFieldB() {
        return sumOfFieldB;
    }

    public void setSumOfFieldB(BigDecimal sumOfFieldB) {
        this.sumOfFieldB = sumOfFieldB;
    }

    public BigDecimal getFieldC() {
        return fieldC;
    }

    public void setFieldC(BigDecimal fieldC) {
        this.fieldC = fieldC;
    }
}

What are some good approaches/solutions for transforming a list of InputRecords into a list of OutputRecords?

I was seeing if the following link would help but I got stuck trying to put collectors for fieldA and fieldB together in order to form a new collector for fieldC:
Java 8 Stream: groupingBy with multiple Collectors

Collector<InputRecord, ?, Integer> fieldACollector = Collectors.summingInt(InputRecord::getFieldA);
Collector<InputRecord, ?, BigDecimal> fieldBCollector = Collectors.reducing(BigDecimal.ZERO, InputRecord::getFieldB, BigDecimal::add);

List<Collector<InputRecord, ?, ?>> collectors = Arrays.asList(fieldACollector, fieldBCollector); // need a fieldCCollector object in the list

The collectors object would then be used to create a complexCollector object (as per the accepted answer by Tagir Valeev in the above link).

Body:
You can use Stream.reduce(..) to transform two records into a single one. It creates a bunch of temporary objects that needs to be garbage collected by the JVM.

Collection<InputRecord> input = Arrays.asList(
        new InputRecord("A", 100, new BigDecimal(1.1)),
        new InputRecord("A", 150, new BigDecimal(2.0)),
        new InputRecord("B", 200, new BigDecimal(1.5)),
        new InputRecord("A", 120, new BigDecimal(1.3)));

Collection<OutputRecord> output = input.stream()
        // group records for particular Name into a List
        .collect(Collectors.groupingBy(InputRecord::getName))
        .values().stream()
        // Reduce every List to a single records, performing summing
        .map(records -> records.stream()
                .reduce((a, b) ->
                        new InputRecord(a.getName(),
                                a.getFieldA() + b.getFieldA(),
                                a.getFieldB().add(b.getFieldB()))))
        .filter(Optional::isPresent)
        .map(Optional::get)
        // Finally transform the InputRecord to OutputRecord
        .map(record -> new OutputRecord(record.getName(),
                record.getFieldA(),
                record.getFieldB(),
                record.getFieldB().multiply(new BigDecimal(record.getFieldA()))))
        .collect(Collectors.toList());


问:
Moving items from one listbox to another listbox through jquery
enter image description hereI am trying to move items from one list to another on checkbox check but actually 1st list are select options and checked property is not coming in jquery , can anybody help how to achieve this ?

$(document).ready(function() {
  //Once a field selected / deslected, update UI List
  $('#GridFields').bind('change', function(option, checked, select) {
    var selectedval = $('#GridFields option:selected').last().val();
    if ($('.sort-selected li[field-id="+selectedval+"').length > 0) {
      $('.sort-selected').remove(selectedval);
    } else {
      $('.sort-selected').append('
' + $(this).find(':selected').last().text() + '
');
      $('.sort-selected').animate({
        scrollTop: $(".sort-selected")[0].scrollHeight
      }, 1000);
    }
    enableSort();
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code><div class="form-group">
<select class="form-control input-sm multiselect" id="GridFields" multiple="multiple" name="GridFields" style="display: none;">
<option disabled="disabled" value="Remedy_Short_ID">Request ID</option>
<option value="Actuals_Per_Day">Actuals Per Day</option>
</select>
<div class="btn-group open" style="width: 100%;"><button type="button" class="multiselect dropdown-toggle btn btn-default" data-toggle="dropdown" title="Request ID, Summary, Request Category, Product Name, Comp Progress Level" style="width: 100%; overflow: hidden; text-overflow: ellipsis;" aria-expanded="true">
<ul class="multiselect-container dropdown-menu" style="-ms-overflow-x: hidden; -ms-overflow-y: auto; max-height: 300px;"><li class="multiselect-item filter"><div class="input-group input-group-sm">

--First Five Elements

<li class="disabled active"><label class="checkbox"><input type="checkbox" value="Comp_Progress_Level"> Comp Progress Level</label></li>

--Remaining Elements
<li><label class="checkbox"><input type="checkbox" value="Actuals_Per_Day"> Actuals Per Day</label></li>

</ul>
</div></code>```

    @Html.Label("Layout Columns", "Layout Columns", new { @class = "form-label" })  @Html.ListBox("GridFields", CommonEntities.getGridFieldsMultiList(), new { @class = "form-control input-sm multiselect"})

Display Order (Drag n Drop an Item)

Request ID

Summary

Request Category

Product Name

Comp Progress Level

```

答:
Based on your description, following should work :

$(document).ready(function() {
  //Once a field selected / deslected, update UI List
  $('#GridFieldsWrap input[type=checkbox]').bind('change', function() {

    $('#GridFieldsWrap input[type=checkbox]').each(function() {
      if ($(this).is(":checked")) {

        if ( $(".sort-selected li[field-id=" + $(this).val() + "]").length==0) {
          $('.sort-selected').append('
' + $(this).parent().text() + '
');
        }
      } else {
        $(".sort-selected li[field-id=" + $(this).val() + "]").remove()
      }
    })

    $('.sort-selected').animate({
      scrollTop: $(".sort-selected")[0].scrollHeight
    }, 1000);
  })
  //enableSort();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3">
  <div class="form-group" id="GridFieldsWrap">
    <ul id="GridFields">
      <li class="disabled active"><label class="checkbox"  ><input type="checkbox" value="Request_ID" checked> Request ID</label></li>
      <li class="disabled active"><label class="checkbox" ><input type="checkbox" checked value="Summary"> Summary</label></li>
      <li class="disabled active"><label class="checkbox"><input type="checkbox" checked value="Request_Category"> Request Category</label></li>
      <li><label class="checkbox"><input type="checkbox" value="Product_Name"> Product Name</label></li>
      <li><label class="checkbox"><input type="checkbox" value="Comp_Progress_Level"> Comp Progress Level</label></li>
    </ul>
  </div>
</div>
<div class="col-md-3">
  <div class="panel panel-custom1">
    <ul class="list-group sort-selected" style="height:100px;overflow-y:auto">
      <li class="list-group-item disabled" field-id="Request_ID">Request ID</li>
      <li class="list-group-item disabled" field-id="Summary">Summary</li>
      <li class="list-group-item disabled" field-id="Request_Category">Request Category</li>
    </ul>
  </div>
</div></code>```

Body:
enter image description hereI am trying to move items from one list to another on checkbox check but actually 1st list are select options and checked property is not coming in jquery , can anybody help how to achieve this ?

$(document).ready(function() {
  //Once a field selected / deslected, update UI List
  $('#GridFields').bind('change', function(option, checked, select) {
    var selectedval = $('#GridFields option:selected').last().val();
    if ($('.sort-selected li[field-id="+selectedval+"').length > 0) {
      $('.sort-selected').remove(selectedval);
    } else {
      $('.sort-selected').append('
' + $(this).find(':selected').last().text() + '
');
      $('.sort-selected').animate({
        scrollTop: $(".sort-selected")[0].scrollHeight
      }, 1000);
    }
    enableSort();
  });

<select class="form-control input-sm multiselect" id="GridFields" multiple="multiple" name="GridFields" style="display: none;">
<option disabled="disabled" value="Remedy_Short_ID">Request ID</option>
<option value="Actuals_Per_Day">Actuals Per Day</option>
</select>

<button type="button" class="multiselect dropdown-toggle btn btn-default" data-toggle="dropdown" title="Request ID, Summary, Request Category, Product Name, Comp Progress Level" style="width: 100%; overflow: hidden; text-overflow: ellipsis;" aria-expanded="true">

--First Five Elements

<input type="checkbox" value="Comp_Progress_Level"> Comp Progress Level

--Remaining Elements

<input type="checkbox" value="Actuals_Per_Day"> Actuals Per Day

    @Html.Label("Layout Columns", "Layout Columns", new { @class = "form-label" })  @Html.ListBox("GridFields", CommonEntities.getGridFieldsMultiList(), new { @class = "form-control input-sm multiselect"})

Display Order (Drag n Drop an Item)

Request ID

Summary

Request Category

Product Name

Comp Progress Level

Body:
Based on your description, following should work :

$(document).ready(function() {
  //Once a field selected / deslected, update UI List
  $('#GridFieldsWrap input[type=checkbox]').bind('change', function() {

    $('#GridFieldsWrap input[type=checkbox]').each(function() {
      if ($(this).is(":checked")) {

        if ( $(".sort-selected li[field-id=" + $(this).val() + "]").length==0) {
          $('.sort-selected').append('<li class="list-group-item" field-id="' + $(this).val() + '">' + $(this).parent().text() + '</li>');
        }
      } else {
        $(".sort-selected li[field-id=" + $(this).val() + "]").remove()
      }
    })

    $('.sort-selected').animate({
      scrollTop: $(".sort-selected")[0].scrollHeight
    }, 1000);
  })
  //enableSort();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-3">
  <div class="form-group" id="GridFieldsWrap">
    <ul id="GridFields">
      <li class="disabled active"><a tabindex="-1"><label class="checkbox"  ><input type="checkbox" value="Request_ID" checked> Request ID</label></a></li>
      <li class="disabled active"><a tabindex="-1"><label class="checkbox" ><input type="checkbox" checked value="Summary"> Summary</label></a></li>
      <li class="disabled active"><a tabindex="-1"><label class="checkbox"><input type="checkbox" checked value="Request_Category"> Request Category</label></a></li>
      <li><a tabindex="0"><label class="checkbox"><input type="checkbox" value="Product_Name"> Product Name</label></a></li>
      <li><a tabindex="0"><label class="checkbox"><input type="checkbox" value="Comp_Progress_Level"> Comp Progress Level</label></a></li>
    </ul>
  </div>
</div>
<div class="col-md-3">
  <div class="panel panel-custom1">
    <ul class="list-group sort-selected" style="height:100px;overflow-y:auto">
      <li class="list-group-item disabled" field-id="Request_ID">Request ID</li>
      <li class="list-group-item disabled" field-id="Summary">Summary</li>
      <li class="list-group-item disabled" field-id="Request_Category">Request Category</li>
    </ul>
  </div>
</div>


问:
Couldn't find 'rspec' generator
I'm trying to install RSpec as a gem after having it installed as a plugin.  I've gone ahead and followed the directions found here http://github.com/dchelimsky/rspec-rails/wikis for the section titled rspec and rspec-rails gems.  When I run ruby script/generate rspec, I get the error Couldn't find 'rspec' generator.  Do only the plugins work?  If so, why do they even offer the gems for rspec and rspec-rails?  I'm running a frozen copy of Rails 2.1.2, and the version of rpsec and rspec-rails I'm using is the newest for today (Nov 7, 2008) 1.1.11.

EDIT Nov 12, 2008
I have both the rspec and rspec-rails gems installed. I've unpacked the gems into the vender/gems folder. Both are version 1.1.11.

答:
If you are using bundler version 1.0.8 you should $ gem update bundler to a newer version 1.0.9.

I had the same symptons and updating bundler helped me out.
Now $ rails g is using gems defined in the Gemfile. Also I grouped my gems like this:

```<code>source 'http://rubygems.org'

gem 'rails', '3.0.3'
gem 'sqlite3-ruby', :require => 'sqlite3'

group :test, :development do
  gem 'capybara', '0.4.1.1'
  gem 'database_cleaner'
  gem 'cucumber-rails'
  gem 'rspec-rails', '~> 2.4'
  gem 'launchy'
end
</code>```

(Note that test gems are also in the :development group.)

Have a nice day :)

Lukas

ContentLicense: CC BY-SA 2.5

Title: Couldn't find 'rspec' generator

LastEditorDisplayName: mikeweber

Body:
If you are using bundler version 1.0.8 you should $ gem update bundler to a newer version 1.0.9.

I had the same symptons and updating bundler helped me out.
Now $ rails g is using gems defined in the Gemfile. Also I grouped my gems like this:

source 'http://rubygems.org'

gem 'rails', '3.0.3'
gem 'sqlite3-ruby', :require => 'sqlite3'

group :test, :development do
  gem 'capybara', '0.4.1.1'
  gem 'database_cleaner'
  gem 'cucumber-rails'
  gem 'rspec-rails', '~> 2.4'
  gem 'launchy'
end

(Note that test gems are also in the :development group.)

Have a nice day :)

Lukas


问:
Jquery table edit row cancel button is not working properly
I am trying to edit table row but not working properly.
If i click the edit button then remove the textbox value then clicked the edit button showing alert to fill the text box otherwise ucer will click the cancel button previuse value i want to show but cancel button is not working properly.anybody resolve this issue. see JSFiddle for code:http://jsfiddle.net/9KEGd/191/

Js:

```<code> $(function () {

$(".edit").click(function (e) {
    e.preventDefault();
    e.stopImmediatePropagation();
    var btn = $(this);
    var td = btn.closest("tr").find(".editable");

    var currentValue = td.text();

    //Save current text in td data attribute
    $(td).data("current-value", currentValue);

    if(btn.text() === "edit")
    {
        td.html("<input type='text' value="+currentValue+" />");
        btn.html("save");
    }
    else
    {
     if(td.find("input").val()==""){

    alert("please fill the text box")
    }else{
         td.html(td.find("input").val());
        btn.html("edit");
        }
    }

});

 $(".cancel").click(function (e) {
    e.preventDefault();
    e.stopImmediatePropagation();
    var td = $(this).closest("tr").find(".editable");

    //Read data attribute to get saved text
    var currentValue = $(td).data("current-value");
    if(currentValue != "")
    {
        td.html(currentValue);
        $(this).parent().find(".edit").html("edit");

        //Set attribute to empty string
        $(td).data("current-value", "");
    }else{

    }
});
});
</code>```

html:

```<code>  <table id="tabledata">
  <thead>
    <th>RecID</th>
    <th>Col1</th>
    <th>opt</th>
</thead>
<tr>
<td><a><div class="nestedtable">Tableshowing no need edit</div></a><span class="editable">RecID1</span></td>
    <td>Val1.1</td>
    <td>
    <ul>
    <li> <a class="edit">edit</a></li>
     <li> <a class="cancel">cancel</a></li>
    </ul>

    </td>
</tr>
<tr>
<td><a><div class="nestedtable">Tableshowings no need edit</div></a><span class="editable">RecID2</span></td>
    <td>Val2.1</td>
    <td>    <ul>
    <li> <a class="edit">edit</a></li>
     <li> <a class="cancel">cancel</a></li>
    </ul></td>
</tr>
<tr>
    <td><a><div class="nestedtable">Tableshowing no need edit</div></a><span class="editable">RecID3</span></td>
    <td>Val3.1</td>
    <td>    <ul>
    <li> <a class="edit">edit</a></li>
     <li> <a class="cancel">cancel</a></li>
    </ul></td>
</tr>
</table>
</code>```

答:
I got your question. You need to store the current value on click of edit but you were storing it on click of both edit and save. Here is an updated working fiddle. http://jsfiddle.net/9KEGd/193/

Working code same as fiddle:

```<code>$(function () {

$(".edit").click(function (e) {
    e.preventDefault();
    e.stopImmediatePropagation();
    var btn = $(this);
    var td = btn.closest("tr").find(".editable");

    //Save current text in td data attribute

    if(btn.text() === "edit")
    {
    //store the current value only on click of EDIT and not on save
      var currentValue = td.text();
      $(td).data("current-value", currentValue);
        td.html("<input type='text' value="+currentValue+" />");
        btn.html("save");
    }
    else
    {
     if(td.find("input").val()==""){

    alert("please fill the text box")
    }else{
         td.html(td.find("input").val());
        btn.html("edit");
        }
    }

});

 $(".cancel").click(function (e) {
    e.preventDefault();
    e.stopImmediatePropagation();
    var td = $(this).closest("tr").find(".editable");

    //Read data attribute to get saved text
    var currentValue = $(td).data("current-value");
    if(currentValue != "")
    {
        td.html(currentValue);

        //Set attribute to empty string
        $(td).data("current-value", "");
    }else{

    }
    $(this).parents('tr').find(".edit").html("edit");
});
</code>```

});

Also I have fixed changing the html to EDIT on click of cancel.

Body:
I am trying to edit table row but not working properly.
If i click the edit button then remove the textbox value then clicked the edit button showing alert to fill the text box otherwise ucer will click the cancel button previuse value i want to show but cancel button is not working properly.anybody resolve this issue. see JSFiddle for code:http://jsfiddle.net/9KEGd/191/

Js:

 $(function () {

$(".edit").click(function (e) {
    e.preventDefault();
    e.stopImmediatePropagation();
    var btn = $(this);
    var td = btn.closest("tr").find(".editable");

    var currentValue = td.text();

    //Save current text in td data attribute
    $(td).data("current-value", currentValue);

    if(btn.text() === "edit")
    {
        td.html("<input type='text' value="+currentValue+" />");
        btn.html("save");
    }
    else
    {
     if(td.find("input").val()==""){

    alert("please fill the text box")
    }else{
         td.html(td.find("input").val());
        btn.html("edit");
        }
    }

});

 $(".cancel").click(function (e) {
    e.preventDefault();
    e.stopImmediatePropagation();
    var td = $(this).closest("tr").find(".editable");

    //Read data attribute to get saved text
    var currentValue = $(td).data("current-value");
    if(currentValue != "")
    {
        td.html(currentValue);
        $(this).parent().find(".edit").html("edit");

        //Set attribute to empty string
        $(td).data("current-value", "");
    }else{

    }
});
});

html:

    RecID
    Col1
    opt

Tableshowing no need edit
RecID1
    Val1.1

 edit

 cancel

Tableshowings no need edit
RecID2
    Val2.1

 edit

 cancel

Tableshowing no need edit
RecID3
    Val3.1

 edit

 cancel

Body:
I got your question. You need to store the current value on click of edit but you were storing it on click of both edit and save. Here is an updated working fiddle. http://jsfiddle.net/9KEGd/193/

Working code same as fiddle:

$(function () {

$(".edit").click(function (e) {
    e.preventDefault();
    e.stopImmediatePropagation();
    var btn = $(this);
    var td = btn.closest("tr").find(".editable");

    //Save current text in td data attribute

    if(btn.text() === "edit")
    {
    //store the current value only on click of EDIT and not on save
      var currentValue = td.text();
      $(td).data("current-value", currentValue);
        td.html("<input type='text' value="+currentValue+" />");
        btn.html("save");
    }
    else
    {
     if(td.find("input").val()==""){

    alert("please fill the text box")
    }else{
         td.html(td.find("input").val());
        btn.html("edit");
        }
    }

});

 $(".cancel").click(function (e) {
    e.preventDefault();
    e.stopImmediatePropagation();
    var td = $(this).closest("tr").find(".editable");

    //Read data attribute to get saved text
    var currentValue = $(td).data("current-value");
    if(currentValue != "")
    {
        td.html(currentValue);

        //Set attribute to empty string
        $(td).data("current-value", "");
    }else{

    }
    $(this).parents('tr').find(".edit").html("edit");
});

});

Also I have fixed changing the html to EDIT on click of cancel.


问:
how to minimise a long && statement - Java
I would like to check if all of the items in array squareData[] is 5.

I could just do this:

if(squareData[0] == 5 && squareData[1] == 5 && ...){...}

But it seems rather inefficient.

Is there a way to minimise this into a for loop of some kind?

Note that the size of squareData[] is 9 items

Thanks!

答:
```<code>private boolean haveAllItemsCorrectValue(int[] array) {
    for (int value : array) {
        if (value != 5) {
            return false;
        }
    }

    return true;
}
</code>```

And then

```<code>if(haveAllItemsCorrectValue(squareData){...}
</code>```

Body:
private boolean haveAllItemsCorrectValue(int[] array) {
    for (int value : array) {
        if (value != 5) {
            return false;
        }
    }

    return true;
}

And then

if(haveAllItemsCorrectValue(squareData){...}


问:
How to create an ajax login for modx & bootstrap modal
I'm almost there, creating an ajax login for a bootstrap modal but have run into a little problem.

Consider this:

Here is the modal, stock bootstrap & stock login form:

```<code><div class="modal fade" id="LoginModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body">

<div id="loginMessage"></div>
        <div class="loginForm">
    <div class="loginMessage">[[+errors]]</div>
    <div class="loginLogin">
        <form id="loginform" class="loginLoginForm" action="[[~[[*id]]]]" method="post">
                 <legend class="loginLegend">[[+actionMsg]]</legend>
                <label class="loginUsernameLabel">[[%login.username]]
                    <input class="loginUsername" type="text" name="username" />
                </label>
                <label class="loginPasswordLabel">[[%login.password]]
                    <input class="loginPassword" type="password" name="password" />
                </label>
                <input class="returnUrl" type="hidden" name="returnUrl" value="[[+request_uri]]" />
                [[+login.recaptcha_html]]
                <input class="loginLoginValue" type="hidden" name="service" value="login" />
                <span class="loginLoginButton"><button type="button" id="loginSubmit" name="submit">login</button></span>
         </form>
    </div>
</div>
<a href="[[~15]]">Forgot your Password?</a>
</div>

    </div>
  </div>
</div>
</code>```

Now the jquery:

```<code><script>

    // ajax login
    $(function() {

        $("button#loginSubmit").click(function(){

            console.log("running processor");

            $.ajax({
                type: "POST",
                url: "[[~17]]",
                dataType  : "json",
                cache : false,
                data: $('form#loginform').serialize(),
                success: function(data){

                    if(data.status == 'success'){

                        console.log("login success");

                        $("#loginMessage").html('success' + data.msg)
                        $("#LoginModal").modal('hide');
                        window.location.replace('[[~14]]');

                    }else if(data.status == 'error'){

                        console.log("login error");

                        $("#loginMessage").html('err' + data.msg)

                    }

                },

                error: function(data){
                    //alert("failure");
                }

            });

        });

    });

</script>
</code>```

Now the processor:

```<code><?php

$status = 'success';
$msg = 'login was successful';

$output = $modx->runSnippet('Login',array(
   'errTpl' => 'ajaxLoginErrorTpl',
   'loginResourceId' => '14',
   'logoutResourceId' => '15',
));

$loginerror = $modx->getPlaceholder('errors');

if(isset($loginerror)){

    $status = 'error';
    $msg = $loginerror;

}

$response_array = array(
    'status' => $status,
    'msg' => $msg,
    );

header('Content-type: application/json');

$output = json_encode($response_array);

return $output;
</code>```

This works fine for a failed login, the errors get caught and displayed in the loginMessage div.

The problem starts when a user has a ~successful~ log in. A user has to click twice to "appear" logged in.

I saw only "appear" logged in because on the first click the modal does not disappear & the user is not redirected BUT the user does get logged in. Login is trying to redirect, the response array is not returned and the jquery does not complete. On the second click the user does get redirected, I don't know why.

I can ~sort of~ fix this by altering the login.php package ~ adding a return to the redirectAfterLogin function before it can redirect, but we all know that is dirty pool.

So;

Is there a way to tell login to not redirect on a successful login?

if not,

Any thoughts on how to fix this?

答:
Столкнулся с подобной проблемой.
Создал posthook, если какие-то проблемы с авторизацией, то posthook не вызывается, а возвращается ошибка.
Поэтому решение можно сделать так:

Обработчик AJAX(php):

```<code>```
if($_POST['ajax']=='loginajax' && isset($_POST['service']) && $_POST['service']=='login' && isset($_POST['password']) && isset($_POST['username'])){

    $arrayRes = array(
        'status' => 'ok', // never used. It's for me, to remember what it returns on success :)
        'msg' => '',
    );

    $modx->runSnippet('Login', array(
        'tplType' => 'modChunk',
        'loginResourceId' => 6,
        'postHooks' => 'authHookAjax'   // this is solution!!!
    ));

    $loginerror = $modx->getPlaceholder('errors');
    // if it has errors in auth
    if(!empty($loginerror)){
        $arrayRes['status'] = 'error';
        $arrayRes['msg'] = $loginerror;
        die(json_encode($arrayRes));
    }

    die(json_encode($arrayRes)); // never do it
}
```
</code>```

Snippet (Hook) - authHookAjax:

```
    $formFields = $hook->getValues();

    // checking ajax :)
    if(isset($formFields['ajax']) && $formFields['ajax']=='loginajax'){
        die(json_encode(array('status' => 'ok', 'msg' => '')));
    }

    return true;
```

Теперь в Javascript:

```
    $.ajax({
       .....
    .done(function(data){

          if(data.status=='error'){ err.html(data.msg); return ;} // error
          if(data.status=='ok'){
               window.location.reload();
               return ;
          }

       }).....
    ```

Body:
I'm almost there, creating an ajax login for a bootstrap modal but have run into a little problem.

Consider this:

Here is the modal, stock bootstrap & stock login form:

[[+errors]]

        <form id="loginform" class="loginLoginForm" action="[[~[[*id]]]]" method="post">
                 <legend class="loginLegend">[[+actionMsg]]</legend>
                [[%login.username]]
                    <input class="loginUsername" type="text" name="username" />

                [[%login.password]]
                    <input class="loginPassword" type="password" name="password" />

                <input class="returnUrl" type="hidden" name="returnUrl" value="[[+request_uri]]" />
                [[+login.recaptcha_html]]
                <input class="loginLoginValue" type="hidden" name="service" value="login" />
                <button type="button" id="loginSubmit" name="submit">login</button>
         </form>

Forgot your Password?

Now the jquery:

Now the processor:

<?php

$status = 'success';
$msg = 'login was successful';

$output = $modx->runSnippet('Login',array(
   'errTpl' => 'ajaxLoginErrorTpl',
   'loginResourceId' => '14',
   'logoutResourceId' => '15',
));

$loginerror = $modx->getPlaceholder('errors');

if(isset($loginerror)){

    $status = 'error';
    $msg = $loginerror;

}

$response_array = array(
    'status' => $status,
    'msg' => $msg,
    );

header('Content-type: application/json');

$output = json_encode($response_array);

return $output;

This works fine for a failed login, the errors get caught and displayed in the loginMessage div.

The problem starts when a user has a ~successful~ log in. A user has to click twice to "appear" logged in.

I saw only "appear" logged in because on the first click the modal does not disappear & the user is not redirected BUT the user does get logged in. Login is trying to redirect, the response array is not returned and the jquery does not complete. On the second click the user does get redirected, I don't know why.

I can ~sort of~ fix this by altering the login.php package ~ adding a return to the redirectAfterLogin function before it can redirect, but we all know that is dirty pool.

So;

Is there a way to tell login to not redirect on a successful login?

if not,

Any thoughts on how to fix this?

Body:
Столкнулся с подобной проблемой.
Создал posthook, если какие-то проблемы с авторизацией, то posthook не вызывается, а возвращается ошибка.
Поэтому решение можно сделать так:

Обработчик AJAX(php):

<pre>
if($_POST['ajax']=='loginajax' && isset($_POST['service']) && $_POST['service']=='login' && isset($_POST['password']) && isset($_POST['username'])){

    $arrayRes = array(
        'status' => 'ok', // never used. It's for me, to remember what it returns on success :)
        'msg' => '',
    );

    $modx->runSnippet('Login', array(
        'tplType' => 'modChunk',
        'loginResourceId' => 6,
        'postHooks' => 'authHookAjax'   // this is solution!!!
    ));

    $loginerror = $modx->getPlaceholder('errors');
    // if it has errors in auth
    if(!empty($loginerror)){
        $arrayRes['status'] = 'error';
        $arrayRes['msg'] = $loginerror;
        die(json_encode($arrayRes));
    }

    die(json_encode($arrayRes)); // never do it
}
</pre>

Snippet (Hook) - authHookAjax:

    $formFields = $hook->getValues();

    // checking ajax :)
    if(isset($formFields['ajax']) && $formFields['ajax']=='loginajax'){
        die(json_encode(array('status' => 'ok', 'msg' => '')));
    }

    return true;

Теперь в Javascript:

    $.ajax({
       .....
    .done(function(data){

          if(data.status=='error'){ err.html(data.msg); return ;} // error
          if(data.status=='ok'){
               window.location.reload();
               return ;
          }

       }).....


问:
Extracting, and then use in a comparison, the object type within a vector appropriately. c++
I have a vector of pointers to vehicles which contains vehicles like cars, lorries, motorcycles. These vehicles have positions associated with them and these positions are tracked and drawn using drawPoint() in QT. I would like to know how to implement an alternative way of checking the object type of each element, i.e, without using typeid.

```<code>for (unsigned int jV = 0; jV < fRoadDisp->getCurrentLane(iLane)->getNVehiclesinLane(); jV++)
   {
       //QPainter painter(this); //already done outside loop
       QPen pointpenv(Qt::red);
       pointpenv.setWidth(5);
       QPen pointpenC(Qt::blue); // For a Car
       pointpenC.setWidth(5);
       QPen pointpenL(Qt::green); // For a Lorry
       pointpenL.setWidth(5);
       QPen pointpenM(Qt::yellow); // For a Motorcycle
       pointpenM.setWidth(5);

       double position = fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)->getPosition();

       if(typeid(fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)) == typeid(Car*)){painter.setPen(pointpenC);}
       else if(typeid(fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)) == typeid(Lorry*)){painter.setPen(pointpenL);}
       else if(typeid(fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)) == typeid(Motorcycle*)){painter.setPen(pointpenM);}

       painter.drawPoint(((iLane * (width()/fRoadDisp->getNLanes())) + width()/(2 *   fRoadDisp->getNLanes())), position * height()/300);
   }
</code>```

The above loops over all the vehicles in a vector of pointers to vehicles and just makes available different coloured pens for different vehicles, and, depending on which type of vehicle is being drawn, I would like the appropriate pen to be activated.

Currently, any points just appear white. A possible solution (I have been told) is to use static public variables, but I am not sure how to implement this in place of typeid.

Any help would be appreciated.

答:
I would add the colour to the vehicle class

```<code>class Vehicle : public QObject
{
    public:
       Vehicle(QColor colour);
       QColor Colour() const;

    private:
        QColor m_vehicleColour;
};
</code>```

This makes more sense than storing the actual QPen, which is not a property of a vehicle.

I would like to know how to implement an alternative way of checking the object type of each element, i.e, without using typeid.

If your vehicles are QObjects, it should be noted that you can use QMetaObject to retrieve a vehicle's type

Assuming we've derived Car from Vehicle

```<code>Vehicle* pCar = new Car(Qt::red);
if(pCar->metaObject() == "Car")
{
    // This instance of vehicle is a car
}
</code>```

Of-course, it's better not to have if(type) then...

So, the renderer can now create a QPen with the right color

```<code>QPen pen(vehicle->Colour());
</code>```

Body:
I have a vector of pointers to vehicles which contains vehicles like cars, lorries, motorcycles. These vehicles have positions associated with them and these positions are tracked and drawn using drawPoint() in QT. I would like to know how to implement an alternative way of checking the object type of each element, i.e, without using typeid.

for (unsigned int jV = 0; jV < fRoadDisp->getCurrentLane(iLane)->getNVehiclesinLane(); jV++)
   {
       //QPainter painter(this); //already done outside loop
       QPen pointpenv(Qt::red);
       pointpenv.setWidth(5);
       QPen pointpenC(Qt::blue); // For a Car
       pointpenC.setWidth(5);
       QPen pointpenL(Qt::green); // For a Lorry
       pointpenL.setWidth(5);
       QPen pointpenM(Qt::yellow); // For a Motorcycle
       pointpenM.setWidth(5);

       double position = fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)->getPosition();

       if(typeid(fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)) == typeid(Car*)){painter.setPen(pointpenC);}
       else if(typeid(fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)) == typeid(Lorry*)){painter.setPen(pointpenL);}
       else if(typeid(fRoadDisp->getCurrentLane(iLane)->getCurrentVehicle(jV)) == typeid(Motorcycle*)){painter.setPen(pointpenM);}

       painter.drawPoint(((iLane * (width()/fRoadDisp->getNLanes())) + width()/(2 *   fRoadDisp->getNLanes())), position * height()/300);
   }

The above loops over all the vehicles in a vector of pointers to vehicles and just makes available different coloured pens for different vehicles, and, depending on which type of vehicle is being drawn, I would like the appropriate pen to be activated.

Currently, any points just appear white. A possible solution (I have been told) is to use static public variables, but I am not sure how to implement this in place of typeid.

Any help would be appreciated.

Body:
I would add the colour to the vehicle class

class Vehicle : public QObject
{
    public:
       Vehicle(QColor colour);
       QColor Colour() const;

    private:
        QColor m_vehicleColour;
};

This makes more sense than storing the actual QPen, which is not a property of a vehicle.

I would like to know how to implement an alternative way of checking the object type of each element, i.e, without using typeid.

If your vehicles are QObjects, it should be noted that you can use QMetaObject to retrieve a vehicle's type

Assuming we've derived Car from Vehicle

Vehicle* pCar = new Car(Qt::red);
if(pCar->metaObject() == "Car")
{
    // This instance of vehicle is a car
}

Of-course, it's better not to have if(type) then...

So, the renderer can now create a QPen with the right color

QPen pen(vehicle->Colour());


问:
Check if two PHP datetime objects are set to the same date ( ignoring time )
I just want to compare 2 datetime objects to see if they are set to the same date, but I don't care about the time component of the the object.  At the moment I am using the date_format command to extract strings like 'Y-m-d' to compare but this seems awkward.

```<code>$firstDate = date_format($firstDateTimeObj, 'Y-m-d');
$secondDate = date_format($secondDateTimeObj, 'Y-m-d');

if !($firstDate == $secondDate) {

// some code
}
</code>```

I'm new to programming and PHP so any pointers appreciated.

答:
Quick and dirty, reusable with as many dates as you like, may still need some adjusting:

update: less dirty.

```<code>if(sameDate($firstDateTimeObj, $secondDateTimeObj, $ThirdDateTimeObj))
{
   // your code

}

function sameDate (DateTime ...$dates) {

   foreach($dates as $date)
   {
      $test[] = $date->format('Ymd');
   }

   $result = array_unique($test);

   if(count($result) == 1)
   {
      return true;
   {

   return false;

}
</code>```

Body:
I just want to compare 2 datetime objects to see if they are set to the same date, but I don't care about the time component of the the object.  At the moment I am using the date_format command to extract strings like 'Y-m-d' to compare but this seems awkward.

$firstDate = date_format($firstDateTimeObj, 'Y-m-d');
$secondDate = date_format($secondDateTimeObj, 'Y-m-d');

if !($firstDate == $secondDate) {

// some code
}

I'm new to programming and PHP so any pointers appreciated.

Body:
Quick and dirty, reusable with as many dates as you like, may still need some adjusting:

update: less dirty.

if(sameDate($firstDateTimeObj, $secondDateTimeObj, $ThirdDateTimeObj))
{
   // your code

}

function sameDate (DateTime ...$dates) {

   foreach($dates as $date)
   {
      $test[] = $date->format('Ymd');
   }

   $result = array_unique($test);

   if(count($result) == 1)
   {
      return true;
   {

   return false;

}


问:
check previous and current element of array
Imagine: I have a an array: ["1", "2", "X", ".", "4", "3", "Z", "-", "12"];

I consider which function should I use to:

find first NaN element in array (let say index = 2) and check if the next (index = 3) is also NaN and if yes (delete from array element with index = 2).

So the result of the transformed array should be: ["1", "2",".", "4", "3", "-", "12"];

I do not want your code, just suggestion/help how to start it.

Thank you for your responses and help.

答:
You can do it recursively:

var arr = ["1", "2", "X", ".", "4", "3", "Z", "-", "12"];
var i = 0;
function removeFirstNan (arr) {
  for (var i = 0; i < arr.length; i++) {
    if (isNaN(arr[i]) && isNaN(arr[i + 1])) {
      var newArr = [ ...arr.slice(0, i), ...arr.slice(i + 1, arr.length) ];
      return removeFirstNan(newArr);
    }
  }
  return arr;
}

arr = removeFirstNan(arr);
console.log(arr);```
</div>
</div>
</p>

<p>A more readable way with <em>array.prototype.findIndex</em> :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = ["1", "2", "X", ".", "4", "3", "Z", "-", "12"];
function removeFirstNan (arg) {
    var firstNanIndex = arg.findIndex((e, i) => (isNaN(e) && isNaN(arg[i + 1])));
    if (firstNanIndex !== -1) {
        var newArr = [ ...arg.slice(0, firstNanIndex), ...arg.slice(firstNanIndex + 1, arg.length) ];
        return removeFirstNan(newArr);
    }
    return arg;
}
arr = removeFirstNan(arr);
console.log(arr);</code>```

Body:
You can do it recursively:

var arr = ["1", "2", "X", ".", "4", "3", "Z", "-", "12"];
var i = 0;
function removeFirstNan (arr) {
  for (var i = 0; i < arr.length; i++) {
    if (isNaN(arr[i]) && isNaN(arr[i + 1])) {
      var newArr = [ ...arr.slice(0, i), ...arr.slice(i + 1, arr.length) ];
      return removeFirstNan(newArr);
    }
  }
  return arr;
}

arr = removeFirstNan(arr);
console.log(arr);

A more readable way with array.prototype.findIndex :

var arr = ["1", "2", "X", ".", "4", "3", "Z", "-", "12"];
function removeFirstNan (arg) {
    var firstNanIndex = arg.findIndex((e, i) => (isNaN(e) && isNaN(arg[i + 1])));
    if (firstNanIndex !== -1) {
        var newArr = [ ...arg.slice(0, firstNanIndex), ...arg.slice(firstNanIndex + 1, arg.length) ];
        return removeFirstNan(newArr);
    }
    return arg;
}
arr = removeFirstNan(arr);
console.log(arr);


问:
iOS app (Hang) Freeze in iPhone 7 but Work in Simulator

I have developed an iOS app on Swift 3. It is a car tracking app. Car shown on map with animation from server data location set (API parse).
I have use  Timer for animation time distance. New problem has encountered that after some time animation car in map the app become hang (freeze) for iPhone 7 and for iPhone 4s I got “Lost connection to x iPhone” at debug mode. But work good in Simulator.

I search a lot for solving that. Some one said Thread issue, memory issue … But nothing can help me. Code skeleton given bellow.

```<code>@IBAction func submitRecordedAction(_ sender: UIButton){
       recordation()
 }

func recordation(){
 let parameters = [ ---- ] as [String : Any]

            loc.getRecordedLocations(para: parameters, success: { (status, msg) in

                            let poiSearchQue = DispatchQueue(label: "com.poiSearchQue", qos: .utility)

                            poiSearchQue.async {

                                self.parsePOI()

                            }

                    DispatchQueue.main.asyncAfter(deadline: .now() + 5.0, execute: {

                          self.recordedDataShow()

                    })

            }, failure: { (msg) in

            })

}

func self.recordedDataShow(){
     //Calling timer from here according to location array
 }
</code>```

答:
Check permissions on the info.plist, if you are using microphone, camera, or photo library on your app, you have to add these permissions on info.plist in order for your app to work perfectly.

here are few examples:

if you are using camera on you app: key NSCameraUsageDescription
or if you are using photo library: NSPhotoLibraryUsageDescription

Body:
I have developed an iOS app on Swift 3. It is a car tracking app. Car shown on map with animation from server data location set (API parse).
I have use  Timer for animation time distance. New problem has encountered that after some time animation car in map the app become hang (freeze) for iPhone 7 and for iPhone 4s I got “Lost connection to x iPhone” at debug mode. But work good in Simulator.

I search a lot for solving that. Some one said Thread issue, memory issue … But nothing can help me. Code skeleton given bellow.

@IBAction func submitRecordedAction(_ sender: UIButton){
       recordation()
 }

func recordation(){
 let parameters = [ ---- ] as [String : Any]

            loc.getRecordedLocations(para: parameters, success: { (status, msg) in

                            let poiSearchQue = DispatchQueue(label: "com.poiSearchQue", qos: .utility)

                            poiSearchQue.async {

                                self.parsePOI()

                            }

                    DispatchQueue.main.asyncAfter(deadline: .now() + 5.0, execute: {

                          self.recordedDataShow()

                    })

            }, failure: { (msg) in

            })

}

func self.recordedDataShow(){
     //Calling timer from here according to location array
 }


问:
Querying and displaying from a database using Sessions
I am trying to query from a phpmyadmin database, comparing an email with a session that was collected during the login.I want to echo it out on a profile page

This is the code for profile.php:

```<code> $conn = mysqli_connect($servername, $username, $password, $dbname);

session_start();

$sql = "SELECT Email, First_Name, Last_Name FROM Users WHERE Email='$Email_Ses'";

 if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
    echo "email: " . $row["Email"]. " - Name: " . $row["First_Name"]. " " .
 $row["Last_Name"]. "<br>";
 }
} else {
echo "0 results";
}
</code>```

This is the code for the Login:

```<code>      session_start();

      if(isset($_POST['email']))

    {
        $_SESSION['Email_Ses'] = $_POST ['email'];
       $_SESSION['Name_Ses'] = $_POST ['name'];
        $password =$_POST ['password'];

        $Email_Ses = $_SESSION['Email_Ses'];

        $Name_Ses =   $_SESSION['Name_Ses'];

        $query = "SELECT * FROM Users WHERE Email='$Email_Ses' AND Password='$password' LIMIT 1";
</code>```

I want to echo out the logged in users's details on a profile page

But i get this error

```<code>Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null
given in /home/ubuntu/workspace/profile.php on line 20
</code>```

the error is on this line:

```<code>if (mysqli_num_rows($result) > 0) {
</code>```

答:
your $result variable does't exist.</p>

```<code>$sql = mysqli_query("SELECT Email, First_Name, Last_Name FROM Users WHERE Email= ='$Email_Ses'");
$result = mysqli_num_rows($conn,$sql);
if ($result > 0)
{
    while($row = mysqli_fetch_assoc($result))
    {
        echo "email: " . $row["Email"]. " - Name: " . $row["First_Name"]. " " .
        $row["Last_Name"]. "<br>";
    }
}
else
{
    echo "0 results";
}
</code>```

Body:
I am trying to query from a phpmyadmin database, comparing an email with a session that was collected during the login.I want to echo it out on a profile page

This is the code for profile.php:

 $conn = mysqli_connect($servername, $username, $password, $dbname);

session_start();

$sql = "SELECT Email, First_Name, Last_Name FROM Users WHERE Email='$Email_Ses'";

 if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
    echo "email: " . $row["Email"]. " - Name: " . $row["First_Name"]. " " .
 $row["Last_Name"]. "
";
 }
} else {
echo "0 results";
}

This is the code for the Login:

      session_start();

      if(isset($_POST['email']))

    {
        $_SESSION['Email_Ses'] = $_POST ['email'];
       $_SESSION['Name_Ses'] = $_POST ['name'];
        $password =$_POST ['password'];

        $Email_Ses = $_SESSION['Email_Ses'];

        $Name_Ses =   $_SESSION['Name_Ses'];

        $query = "SELECT * FROM Users WHERE Email='$Email_Ses' AND Password='$password' LIMIT 1";

I want to echo out the logged in users's details on a profile page

But i get this error

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null
given in /home/ubuntu/workspace/profile.php on line 20

the error is on this line:

if (mysqli_num_rows($result) > 0) {

Body:
your $result variable does't exist.

$sql = mysqli_query("SELECT Email, First_Name, Last_Name FROM Users WHERE Email= ='$Email_Ses'");
$result = mysqli_num_rows($conn,$sql);
if ($result > 0)
{
    while($row = mysqli_fetch_assoc($result))
    {
        echo "email: " . $row["Email"]. " - Name: " . $row["First_Name"]. " " .
        $row["Last_Name"]. "<br>";
    }
}
else
{
    echo "0 results";
}


问:
Can not decode json string in command line
I have a json that is an array of objects.

The following code works just fine:

```<code>use JSON qw( decode_json );
# the contents of json are from the file jsonfile.json
my $data='[{...}]'; # omitted for clarity
@decoded = @{decode_json($data)};
print Dumper \@decoded;
</code>```

But when I try to run it from the command line as an one-liner it breaks

None of the following work:

```<code>cat jsonfile.json | perl -MData::Dumper -MJSON=decode_json -ne'my $data=q{$_}; print decode_json($data)'

cat jsonfile.json | perl -MData::Dumper -MJSON=decode_json -ne"print decode_json('$_')"
</code>```

I think the issue is the quoting. I had the same issue in the script until I replaced qw with ’ otherwise it would complaint e.g. if an @ was in the fields or it was confused with the double quotes of the json fields.

What am I doing wrong here?

Another example:

This breaks:

```<code>$ echo [{"a":"b"}] |perl -MData::Dumper -MJSON=decode_json -ne'print decode_json($_)'
unexpected end of string while parsing JSON string, at character offset 3 (before ":b}]\n") at -e line 1.
</code>```

But this works:

```<code>$ echo '[{"a":"b"}]'| perl -MData::Dumper -MJSON=decode_json -ne'print decode_json($_)'
ARRAY(0x7fd8d400b2b8)
</code>```

答:
Bash has a number of different quoting modes:

within single quotes '...' nothing is expanded. There are no escapes available. So within such quotes you can use $variables without them being expanded as Bash variables. This is desirable for Perl one-liners. But you cannot use single quotes within that string. As a consequence, Perl one-liners should prefer quoting operators such as q(...) within the Perl code.

within double quotes "..." variables are expanded, and special characters can be escaped. This is not desirable for Perl one-liners.

Bash has these quoting modes but not strings. You can switch between quoting modes within one word, so the command line parameter foo"bar"baz'qux' is equal to foobarbazqux.

When we look at your JSON snippets:

echo [{"a":"b"}] is equal to echo '[{a:b}]', because the " quotes are  stripped. That is not valid JSON.

echo '[{"a":"b"}]' works as expected, because the double quotes are protected by the single quotes.

Within your Perl oneliners:

-ne"print decode_json('$_')" is a double quoted string. The Bash variable $_ expands to the last argument of the previous command. So we are actually passing something like the argument "-neprint decode_json('RANDOM GARBAGE')".

-ne'my $data=q{$_}; print decode_json($data)' is escaped correctly, as far as Bash is concerned.

Both your initial Perl one-liners use single quotes around the $_ variable: '$_' and q{$_}. Perl does not interpolate variables into single quoted strings, so you were using the literal string $_, not the value of the $_ variable. In these cases no quotes were necessary. If you had to use quotes, double quoted strings like qq{$_} would have been preferable.

Putting all of this together, a command like this should work:

```<code>$ perl -MJSON=decode_json -ne'print decode_json($_)' jsonfile.json
</code>```

But note that this reads the file line by line due to the -n flag, i.e. expects one JSON document per line.

Body:
I have a json that is an array of objects.

The following code works just fine:

use JSON qw( decode_json );
# the contents of json are from the file jsonfile.json
my $data='[{...}]'; # omitted for clarity
@decoded = @{decode_json($data)};
print Dumper \@decoded;

But when I try to run it from the command line as an one-liner it breaks

None of the following work:

cat jsonfile.json | perl -MData::Dumper -MJSON=decode_json -ne'my $data=q{$_}; print decode_json($data)'

cat jsonfile.json | perl -MData::Dumper -MJSON=decode_json -ne"print decode_json('$_')"

I think the issue is the quoting. I had the same issue in the script until I replaced qw with ’ otherwise it would complaint e.g. if an @ was in the fields or it was confused with the double quotes of the json fields.

What am I doing wrong here?

Another example:

This breaks:

$ echo [{"a":"b"}] |perl -MData::Dumper -MJSON=decode_json -ne'print decode_json($_)'
unexpected end of string while parsing JSON string, at character offset 3 (before ":b}]\n") at -e line 1.

But this works:

$ echo '[{"a":"b"}]'| perl -MData::Dumper -MJSON=decode_json -ne'print decode_json($_)'
ARRAY(0x7fd8d400b2b8)

Body:
Bash has a number of different quoting modes:

within single quotes '...' nothing is expanded. There are no escapes available. So within such quotes you can use $variables without them being expanded as Bash variables. This is desirable for Perl one-liners. But you cannot use single quotes within that string. As a consequence, Perl one-liners should prefer quoting operators such as q(...) within the Perl code.

within double quotes "..." variables are expanded, and special characters can be escaped. This is not desirable for Perl one-liners.

Bash has these quoting modes but not strings. You can switch between quoting modes within one word, so the command line parameter foo"bar"baz'qux' is equal to foobarbazqux.

When we look at your JSON snippets:

echo [{"a":"b"}] is equal to echo '[{a:b}]', because the " quotes are  stripped. That is not valid JSON.

echo '[{"a":"b"}]' works as expected, because the double quotes are protected by the single quotes.

Within your Perl oneliners:

-ne"print decode_json('$_')" is a double quoted string. The Bash variable $_ expands to the last argument of the previous command. So we are actually passing something like the argument "-neprint decode_json('RANDOM GARBAGE')".

-ne'my $data=q{$_}; print decode_json($data)' is escaped correctly, as far as Bash is concerned.

Both your initial Perl one-liners use single quotes around the $_ variable: '$_' and q{$_}. Perl does not interpolate variables into single quoted strings, so you were using the literal string $_, not the value of the $_ variable. In these cases no quotes were necessary. If you had to use quotes, double quoted strings like qq{$_} would have been preferable.

Putting all of this together, a command like this should work:

$ perl -MJSON=decode_json -ne'print decode_json($_)' jsonfile.json

But note that this reads the file line by line due to the -n flag, i.e. expects one JSON document per line.


问:
Solr with normalized document structure
I have a Solr document like this, where all the fields are mapped as a single document.

```<code><doc>
    <int name="Id">7</int>
    <str name="Name">PersonName</str>
    <str name="Address">Address Line 1, Address Line 2, City</str>
    <str name="Country">India</str>
    <str name="ImageURL">0000028415.jpeg</str>
    <arr name="Category">
      <str>Student</str>
      <str>Group A</str>
    </arr>
</doc>
</code>```

We would like to normalize it and have separate doc type for Person, Country and Category.

```<code><doc>
    <int name="PId">7</int>
    <str name="Name">PersonName</str>
    <str name="Address">Address Line 1, Address Line 2, City</str>
    <str name="CountryId">91</str>
    <str name="ImageURL">0000028415.jpeg</str>
    <arr name="CategoryId">
      <str>2</str>
      <str>5</str>
    </arr>
</doc>

    <doc>
        <int name="CId">91</int>
        <str name="CountryName">India</str>
    </doc>

<doc>
        <int name="CatId">2</int>
        <str name="CategoryName">Student</str>
    </doc>
</code>```

Note that I am just simplifying the example, actual document that I work with is too much complex than this, and we have millions of documents in the index.

I would like to understand, how to join and do filter query with this kind of document structure. And how does it impact performance compared to previous case, where all details are stored in single doc structure.

Update

Sample query with current structure, hope this helps with some idea on how it is done currently:

Here is the sample query for search with certain facets applied -

```<code>/select?indent=on&wt=json&facet.field={!ex%3DCategory}Category&facet.field=Manufacturer&facet.field=Vendor&facet.field=f_Hardrive&facet.field=f_Operating%2BSystem&facet.field=f_Memory&facet.field=f_CPU%2BType&facet.field=f_Screensize&facet.field=pa_OS&bf=&start=0&fq={!tag%3DCategory}Category:Notebooks&fq=Price:[0+TO+9999999999999]&rows=6&version=2.2&bq=&facet.query=AverageRating:[4+TO+5]&facet.query=AverageRating:[3+TO+5]&facet.query=AverageRating:[2+TO+5]&facet.query=AverageRating:[1+TO+5]&q=(laptop)&defType=edismax&spellcheck.q=(laptop)&qf=Name^7++ShortDescription^6++FullDescription^4+CategoryCopy^2+ManufacturerCopy^2+Sku^3+ChildSku^3+nGramContent+Attributes+ProductAttributes+Tag+ManufacturerPartNumber+CustomProperties&spellcheck=true&stats=true&facet.mincount=1&facet=true&spellcheck.collate=true&stats.field=Price
</code>```

This filter query with facets:

```<code>select?indent=on&wt=json&facet.field=f_Hardrive&facet.field=f_Operating%2BSystem&facet.field=f_Memory&facet.field=f_CPU%2BType&facet.field={!ex%3Df_Screensize}f_Screensize&facet.field=pa_HDD&facet.field=pa_OS&facet.field={!ex%3Dpa_OS}pa_OS&facet.field=pa_OS&facet.field=pa_Processor&facet.field=pa_RAM&facet.field=pa_Software&facet.field=Vendor&facet.field={!ex%3DManufacturer}Manufacturer&facet.field=Category&start=0&fq=StockAvailability:(true)&fq={!tag%3Df_Screensize}f_Screensize:15.0%2527%2527\!!4!!&fq={!tag%3Dpa_OS}pa_OS:Apple\!!0!!&fq={!tag%3DPrice}Price:[594+TO+1800]&sort=CDO_1+asc&rows=6&version=2.2&facet.query=AverageRating:[4+TO+5]&facet.query=AverageRating:[3+TO+5]&facet.query=AverageRating:[2+TO+5]&facet.query=AverageRating:[1+TO+5]&q=CategoryID:(1+OR+2+OR+3+OR+4)&defType=edismax&spellcheck=true&stats=true&facet.mincount=1&facet=true&spellcheck.collate=true&stats.field=Price
</code>```

答:
The only thing that comes to my mind is using an XSLTResponseWriter to modify the query response with an XSLT file that transforms that response in a more adequate one.

Check: https://wiki.apache.org/solr/XsltResponseWriter

Check: https://lucene.apache.org/solr/guide/6_6/response-writers.html

Don't know if thats what you wanted.

EDIT: I will add more info about this.

So XSLT allows you transform an XML file into another (or anothers). You can swap the place of your tags, create new ones, combine them, take info from other XMLs and use it in the file you want to transform, etc.
You can find more info about this here: https://www.w3schools.com/xml/xsl_intro.asp

Solr allows you to apply an XSLT tranformation in query time, to your query result. You just have to create your .xsl file and place it in mySolrCollection/conf/xslt/ dicrectory (create xslt/ if it doesn't exist). For example: mySolrCollection/conf/xslt/transformation.xsl

This file (transformation.xsl) will contain all transformations you want to apply to the query response. Im not going to go into how to write this transformations, it's not that hard to learn so you can just check the web  for examples and for tutorials ;)

The last thing to do is to tell Solr that you want to apply a transformation to the response of the query, and you must do that by changing the query syntax. You must add the &wt=xslt&tr=transformation.xsl parts to your query to tell Solr that you want to apply a transformation to the response and that that transformation is defined in transformation.xsl

An example of a query should be:

http://<your_host>:<your_port>/solr/"your_collection"/select?q=*:*&wt=xslt&tr=tranformation.xsl&rows=100&...

If your query is correct, you will have your response transformed as you specified in your .xsl file.

Hope this in enough.

Title: Solr with normalized document structure

Body:
I have a Solr document like this, where all the fields are mapped as a single document.

<doc>
    <int name="Id">7</int>
    <str name="Name">PersonName</str>
    <str name="Address">Address Line 1, Address Line 2, City</str>
    <str name="Country">India</str>
    <str name="ImageURL">0000028415.jpeg</str>
    <arr name="Category">
      <str>Student</str>
      <str>Group A</str>
    </arr>
</doc>

We would like to normalize it and have separate doc type for Person, Country and Category.

<doc>
    <int name="PId">7</int>
    <str name="Name">PersonName</str>
    <str name="Address">Address Line 1, Address Line 2, City</str>
    <str name="CountryId">91</str>
    <str name="ImageURL">0000028415.jpeg</str>
    <arr name="CategoryId">
      <str>2</str>
      <str>5</str>
    </arr>
</doc>

    <doc>
        <int name="CId">91</int>
        <str name="CountryName">India</str>
    </doc>

<doc>
        <int name="CatId">2</int>
        <str name="CategoryName">Student</str>
    </doc>

Note that I am just simplifying the example, actual document that I work with is too much complex than this, and we have millions of documents in the index.

I would like to understand, how to join and do filter query with this kind of document structure. And how does it impact performance compared to previous case, where all details are stored in single doc structure.

Update

Sample query with current structure, hope this helps with some idea on how it is done currently:

Here is the sample query for search with certain facets applied -

/select?indent=on&wt=json&facet.field={!ex%3DCategory}Category&facet.field=Manufacturer&facet.field=Vendor&facet.field=f_Hardrive&facet.field=f_Operating%2BSystem&facet.field=f_Memory&facet.field=f_CPU%2BType&facet.field=f_Screensize&facet.field=pa_OS&bf=&start=0&fq={!tag%3DCategory}Category:Notebooks&fq=Price:[0+TO+9999999999999]&rows=6&version=2.2&bq=&facet.query=AverageRating:[4+TO+5]&facet.query=AverageRating:[3+TO+5]&facet.query=AverageRating:[2+TO+5]&facet.query=AverageRating:[1+TO+5]&q=(laptop)&defType=edismax&spellcheck.q=(laptop)&qf=Name^7++ShortDescription^6++FullDescription^4+CategoryCopy^2+ManufacturerCopy^2+Sku^3+ChildSku^3+nGramContent+Attributes+ProductAttributes+Tag+ManufacturerPartNumber+CustomProperties&spellcheck=true&stats=true&facet.mincount=1&facet=true&spellcheck.collate=true&stats.field=Price

This filter query with facets:

select?indent=on&wt=json&facet.field=f_Hardrive&facet.field=f_Operating%2BSystem&facet.field=f_Memory&facet.field=f_CPU%2BType&facet.field={!ex%3Df_Screensize}f_Screensize&facet.field=pa_HDD&facet.field=pa_OS&facet.field={!ex%3Dpa_OS}pa_OS&facet.field=pa_OS&facet.field=pa_Processor&facet.field=pa_RAM&facet.field=pa_Software&facet.field=Vendor&facet.field={!ex%3DManufacturer}Manufacturer&facet.field=Category&start=0&fq=StockAvailability:(true)&fq={!tag%3Df_Screensize}f_Screensize:15.0%2527%2527\!!4!!&fq={!tag%3Dpa_OS}pa_OS:Apple\!!0!!&fq={!tag%3DPrice}Price:[594+TO+1800]&sort=CDO_1+asc&rows=6&version=2.2&facet.query=AverageRating:[4+TO+5]&facet.query=AverageRating:[3+TO+5]&facet.query=AverageRating:[2+TO+5]&facet.query=AverageRating:[1+TO+5]&q=CategoryID:(1+OR+2+OR+3+OR+4)&defType=edismax&spellcheck=true&stats=true&facet.mincount=1&facet=true&spellcheck.collate=true&stats.field=Price


问:
How to write a command line C# program that posts to Twitter
I'd like to write a console program in C# that posts a Tweet to Twitter.  I've never used the Twitter APIs before and don't know anything about how their authentication works.  I found an API library called Twitterizer, but it seems geared towards web applications and wants the user to logon with a web browser.  All the API docs on Twitter's website seems geared around this scenario as well.

Is it possible to access the Twitter APIs using a console app with no web browser access?  I'm perfectly fine hard coding in the name and password for the Twitter user I want to post under as well.  Thanks!

Mike

答:
I couldn't find any decent information on the web on how to do this, so I decided to write my own blog post with all the details..  Enjoy!

http://blog.kitchenpc.com/2011/01/22/rise-of-the-twitterbot/


问:
flask-bcrypt Invalid Salt; encoding issue?
I know a similar question has been asked here, but no answer seems to address my problem. I am using Python3, Flask, and flask-bcrypt.

My login function was working fine earlier and I don't believe I changed anything so I'm not sure what happened. The way I understand it is, at signup, we are meant to encode the received password to UTF-8, then decode the hashed password before we pass it to the database as follows:

```<code>password = form.password.data.encode('utf-8')
hashed_password = bcrypt.generate_password_hash(password).decode('utf-8')
</code>```

Then, at login, we are supposed to encode the candidate password and compare that to the hashed password in the database as follows:

```<code>password = form.password.data.encode('utf-8')
if bcrypt.check_password_hash(user.password, password):
</code>```

But i get the error Invalid Salt from this. And I have tried several other variants with no success.

Any help would be greatly appreciated. Here are the views. I can provide any other code necessary.

```<code>@app.route('/<role>/signup/', methods=['GET', 'POST'])
def signUp(role):
    form = RegisterForm()

    if form.validate_on_submit():
        password = form.password.data.encode('utf-8')
        hashed_password = bcrypt.generate_password_hash(password).decode('utf-8')
        new_user = User(role=role, password=hashed_password, visits=1)
        form.populate_obj(new_user)

        db.session.add(new_user)
        db.session.commit()

        login_user(new_user)

        return redirect(url_for('createContactInfo', user_id=current_user.id))

    return render_template('signup.html', form=form, role=role)

@app.route('/login/', methods=['GET', 'POST'])
def logIn():
    form = LoginForm()

    if form.validate_on_submit():
        password = form.password.data.encode('utf-8')
        user = User.query.filter_by(email=form.email.data).first()
        if user:
            if bcrypt.check_password_hash(user.password, password):
                login_user(user, remember=form.remember.data)
                User.query.filter_by(id=current_user.id).update({'visits': User.visits + 1})
                db.session.commit()

                if current_user.role == 'admin':
                    return redirect(url_for('adminMainPage', user_id=current_user.id))
                elif current_user.role == 'guest':
                    return redirect(url_for('guestMainPage', user_id=current_user.id))
                else:
                    return "wrong role!"

            flash('Invalid login')
            return render_template('login.html', form=form)

        flash('Invalid login')
        return render_template('login.html', form=form)

    return render_template('login.html', form=form)
</code>```

答:
So I figured it out and the answer really had nothing to do with the question.

The issue was, in signup, I instantiated the object new_user with password=hashed_password, but then I called form.populate_obj(new_user), which according to the wtforms docs is a destructive operation, and as a result overrode new_user.password = form.password.data, which was not hashed.

So I stored the unhashed password in my DB and, at login, I was comparing the hashed candidate password with the unhashed stored password. Hence, Invalid Salt. As discussed in other related matters, the Invalid Salt error is a huge catchall that doesn't really point to the underlying problem.

To fix, I called form.populate_obj(new_user) first, then added the attributes separately as follows:

```<code>    new_user = User()

    form.populate_obj(new_user)

    new_user.role = role
    new_user.password = hashed_password
    new_user.visits = 1
</code>```

Body:
I know a similar question has been asked here, but no answer seems to address my problem. I am using Python3, Flask, and flask-bcrypt.

My login function was working fine earlier and I don't believe I changed anything so I'm not sure what happened. The way I understand it is, at signup, we are meant to encode the received password to UTF-8, then decode the hashed password before we pass it to the database as follows:

password = form.password.data.encode('utf-8')
hashed_password = bcrypt.generate_password_hash(password).decode('utf-8')

Then, at login, we are supposed to encode the candidate password and compare that to the hashed password in the database as follows:

password = form.password.data.encode('utf-8')
if bcrypt.check_password_hash(user.password, password):

But i get the error Invalid Salt from this. And I have tried several other variants with no success.

Any help would be greatly appreciated. Here are the views. I can provide any other code necessary.

@app.route('/<role>/signup/', methods=['GET', 'POST'])
def signUp(role):
    form = RegisterForm()

    if form.validate_on_submit():
        password = form.password.data.encode('utf-8')
        hashed_password = bcrypt.generate_password_hash(password).decode('utf-8')
        new_user = User(role=role, password=hashed_password, visits=1)
        form.populate_obj(new_user)

        db.session.add(new_user)
        db.session.commit()

        login_user(new_user)

        return redirect(url_for('createContactInfo', user_id=current_user.id))

    return render_template('signup.html', form=form, role=role)

@app.route('/login/', methods=['GET', 'POST'])
def logIn():
    form = LoginForm()

    if form.validate_on_submit():
        password = form.password.data.encode('utf-8')
        user = User.query.filter_by(email=form.email.data).first()
        if user:
            if bcrypt.check_password_hash(user.password, password):
                login_user(user, remember=form.remember.data)
                User.query.filter_by(id=current_user.id).update({'visits': User.visits + 1})
                db.session.commit()

                if current_user.role == 'admin':
                    return redirect(url_for('adminMainPage', user_id=current_user.id))
                elif current_user.role == 'guest':
                    return redirect(url_for('guestMainPage', user_id=current_user.id))
                else:
                    return "wrong role!"

            flash('Invalid login')
            return render_template('login.html', form=form)

        flash('Invalid login')
        return render_template('login.html', form=form)

    return render_template('login.html', form=form)

Body:
So I figured it out and the answer really had nothing to do with the question.

The issue was, in signup, I instantiated the object new_user with password=hashed_password, but then I called form.populate_obj(new_user), which according to the wtforms docs is a destructive operation, and as a result overrode new_user.password = form.password.data, which was not hashed.

So I stored the unhashed password in my DB and, at login, I was comparing the hashed candidate password with the unhashed stored password. Hence, Invalid Salt. As discussed in other related matters, the Invalid Salt error is a huge catchall that doesn't really point to the underlying problem.

To fix, I called form.populate_obj(new_user) first, then added the attributes separately as follows:

    new_user = User()

    form.populate_obj(new_user)

    new_user.role = role
    new_user.password = hashed_password
    new_user.visits = 1


答:
Try using enumerate:

```<code>list3 = []
for i,j in enumerate(list1):
    list3.append(list2[i:i+len(j)])
</code>```

Title: In python. Use the format of one list to another list

Body:
list1 = [['WA', 'WA'], ['DC'], ['HI'], ['NJ', 'NJ', 'NJ', 'NJ', 'NJ'], ['TX', 'TX', 'TX'], ['LA', 'LA'], ['NC'], ['NY'], ['IL', 'IL'], ['GA'], ['MA'], ['AZ']]

list2 = [0.875, 10.875, 0, 0, 0, 0, 0.0, 0.0, 10.0, 0, 0, 0, 0.625, -0.25, 0, 10.0, 0.5, 0, 0, 10.0, 9.25]

I want the list3 be like this:

list 3 = [[0.875, 10.875], [0], [0], [0, 0, 0.0, 0.0, 10.0], [0, 0, 0], [0.625, -0.25], [0], [10.0], [0.5, 0], [0], [10.0], [9.25]]

I had already get the index of the list1 like that:

index_list = [[0, 1], [2], [3], [4, 5, 6, 7, 8], [9, 10, 11], [12, 13], [14], [15], [16, 17], [18], [19], [20]]

Body:
Try using enumerate:

list3 = []
for i,j in enumerate(list1):
    list3.append(list2[i:i+len(j)])


问:
Running out of RAM on large AQL query | Trying to split a collection into two
In my efforts to solve my issue here, I'm using ArangoDb's AQL language to split a collection into two. As creating graphs can only be done on "normalized" collections. But my query is eating up all of my RAM (16gb).

```<code>FOR comment IN collection_name
    COLLECT author = comment.author
    , subreddit = comment.subreddit
    WITH COUNT INTO counter
    RETURN {author, counter, subreddit}
</code>```

Is there a way I could dump the results directly to disk without pulling it into RAM? Or a way I could split it directly without using a query?

答:
the problem here is, that the COLLECT statement works in memory. Since your collection has 40 million documents and you want to work with all of them, and they give 72.424.492 uniq items to collect this won't work out.

To create the subset collection you desire you create,

one can use the OPTIONS { ignoreErrors: true } to create this subset.

Since your author-field may contain strings that are not allowed in the _key field (which we need to identify and skip duplicates with the ignoreErrors-option) you can use MD5() to create a _key uniq to each author. A resulting query creating one author entry per uniq author could look like that:

```<code>db._query(`
  FOR item IN RawSubReddits
    INSERT {
      _key: MD5(item.author),
      author: item.author
      } INTO authors
        OPTIONS { ignoreErrors: true }`);
</code>```

once you have these, you could update a count from an edge collection:

```<code> db._query(`
   FOR onesubred IN RawSubReddits
     INSERT {
       _from: CONCAT('authors/', MD5(onesubred.author)),
       _to: CONCAT('RawSubReddits/', onesubred._key)
     } INTO  authorsToSubreddits")
</code>```

This post on github can provide more information.

Body:
In my efforts to solve my issue here, I'm using ArangoDb's AQL language to split a collection into two. As creating graphs can only be done on "normalized" collections. But my query is eating up all of my RAM (16gb).

FOR comment IN collection_name
    COLLECT author = comment.author
    , subreddit = comment.subreddit
    WITH COUNT INTO counter
    RETURN {author, counter, subreddit}

Is there a way I could dump the results directly to disk without pulling it into RAM? Or a way I could split it directly without using a query?

Body:
the problem here is, that the COLLECT statement works in memory. Since your collection has 40 million documents and you want to work with all of them, and they give 72.424.492 uniq items to collect this won't work out.

To create the subset collection you desire you create,

one can use the OPTIONS { ignoreErrors: true } to create this subset.

Since your author-field may contain strings that are not allowed in the _key field (which we need to identify and skip duplicates with the ignoreErrors-option) you can use MD5() to create a _key uniq to each author. A resulting query creating one author entry per uniq author could look like that:

db._query(`
  FOR item IN RawSubReddits
    INSERT {
      _key: MD5(item.author),
      author: item.author
      } INTO authors
        OPTIONS { ignoreErrors: true }`);

once you have these, you could update a count from an edge collection:

 db._query(`
   FOR onesubred IN RawSubReddits
     INSERT {
       _from: CONCAT('authors/', MD5(onesubred.author)),
       _to: CONCAT('RawSubReddits/', onesubred._key)
     } INTO  authorsToSubreddits")

This post on github can provide more information.