问:
Moving subforms in standard PDF
I am trying to move subforms in a standard pdf file (not a dynamic XML). I have an old copy of LiveCycle (ES2) and have produced the following code

```<code>xfa.host.setFocus(clearArrows);

var gridX = xfa.layout.x(gridPICK);
var gridY = xfa.layout.y(gridPICK);
var gridW = xfa.layout.w(gridPICK);
var gridH = xfa.layout.h(gridPICK);

var markerDim = 0;

var mouseX = event.target.mouseX;
var newX = (mouseX + "points").toString();
var mouseY = xfa.layout.h(Page3) - event.target.mouseY;
var newY = (mouseY + "points").toString();

for (var i = 0; i < 10; i++){
    var indicatorObject = xfa.resolveNode("Indicator[" + i.toString() +     "]");
    var indicatorX = xfa.layout.x(indicatorObject);
    if (indicatorX < gridX) {
        var pointIndicator = indicatorObject;
        pointIndicator.presence = "visible";
        xfa.host.setFocus(pointIndicator.Description);
        xfa.host.openList("Indicator[" + i.toString() + "].Description");

        i = 10;
    }

}

if (mouseX <= gridX + markerDim)
{
    pointIndicator.x = (gridX + markerDim + "points").toString();
}
else if (mouseX >= gridX + gridW - markerDim)
{
    pointIndicator.x = (gridX + gridW - markerDim + "points").toString();
}
else
{
    pointIndicator.x = newX;
}

if (mouseY >= gridY + gridH - markerDim)
{
    pointIndicator.y = (gridY + gridH - markerDim + "points").toString();
}
else if (mouseY <= gridY + markerDim)
{
    pointIndicator.y = (gridY + markerDim + "points").toString();
}
else
{
    pointIndicator.y = newY;
}
</code>```

This works fine if I extend the features and use it on a PC or mac however if I try to use it on an ipad it does not work. Essentially this code is placed on the click event of a large button in a grid square.

Any help would be greatly appreciated.

答:
I'm afraid I don't think you'll be able to get this to work.

The iPad version of Adobe Reader does not support XFA forms designed in LiveCycle Designer.

Title: Moving subforms in standard PDF

Body:
I am trying to move subforms in a standard pdf file (not a dynamic XML). I have an old copy of LiveCycle (ES2) and have produced the following code

xfa.host.setFocus(clearArrows);

var gridX = xfa.layout.x(gridPICK);
var gridY = xfa.layout.y(gridPICK);
var gridW = xfa.layout.w(gridPICK);
var gridH = xfa.layout.h(gridPICK);

var markerDim = 0;

var mouseX = event.target.mouseX;
var newX = (mouseX + "points").toString();
var mouseY = xfa.layout.h(Page3) - event.target.mouseY;
var newY = (mouseY + "points").toString();

for (var i = 0; i < 10; i++){
    var indicatorObject = xfa.resolveNode("Indicator[" + i.toString() +     "]");
    var indicatorX = xfa.layout.x(indicatorObject);
    if (indicatorX < gridX) {
        var pointIndicator = indicatorObject;
        pointIndicator.presence = "visible";
        xfa.host.setFocus(pointIndicator.Description);
        xfa.host.openList("Indicator[" + i.toString() + "].Description");

        i = 10;
    }

}

if (mouseX <= gridX + markerDim)
{
    pointIndicator.x = (gridX + markerDim + "points").toString();
}
else if (mouseX >= gridX + gridW - markerDim)
{
    pointIndicator.x = (gridX + gridW - markerDim + "points").toString();
}
else
{
    pointIndicator.x = newX;
}

if (mouseY >= gridY + gridH - markerDim)
{
    pointIndicator.y = (gridY + gridH - markerDim + "points").toString();
}
else if (mouseY <= gridY + markerDim)
{
    pointIndicator.y = (gridY + markerDim + "points").toString();
}
else
{
    pointIndicator.y = newY;
}

This works fine if I extend the features and use it on a PC or mac however if I try to use it on an ipad it does not work. Essentially this code is placed on the click event of a large button in a grid square.

Any help would be greatly appreciated.


来源: stackexchange

问:
How to apply border in nav-pills when using nav-stacked?
How can I apply the border on the left side (or right as the case may be) when I use nav-stacked in nav-pills?

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

States

States tab

Subscriptions

Subscriptions tab

Comments

Comments tab

          States

          Subscriptions

          Comments

```

答:
You can implement it like that and tweak it around according to your needs. Hope, it helps. If you want it to apply on all instead of just the active one you need to modify .nav-pills> .active to .nav-pills> *

.nav-pills>li {
  border-left:2px solid #444444;
}

.nav-pills>.active {
  border-right: 2px solid #444444;
  border-top: 2px solid #444444;
  border-bottom: 2px solid #444444;
  border-left:none;
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="row">
  <div class="col-md-9">
    <div class="tab-content">
      <div id="states" class="tab-pane fade in active">
        <h3>States</h3>
        <p>States tab</p>
      </div>
      <div id="subs" class="tab-pane fade">
        <h3>Subscriptions</h3>
        <p>Subscriptions tab</p>
      </div>
      <div id="comments" class="tab-pane fade">
        <h3>Comments</h3>
        <p>Comments tab</p>
      </div>
    </div>
  </div>

  <div class="col-md-3">
    <ul class="nav nav-pills nav-stacked" id="myTabs">
      <li class="active">

          States

      </li>
      <li>

          Subscriptions

      </li>
      <li>

          Comments

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

Updated- Added other borders to make it look like nav-tabs.

ContentLicense: CC BY-SA 3.0

Body:
You can implement it like that and tweak it around according to your needs. Hope, it helps. If you want it to apply on all instead of just the active one you need to modify .nav-pills> .active to .nav-pills> *

.nav-pills>li {
  border-left:2px solid #444444;
}

.nav-pills>.active {
  border-right: 2px solid #444444;
  border-top: 2px solid #444444;
  border-bottom: 2px solid #444444;
  border-left:none;
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="row">
  <div class="col-md-9">
    <div class="tab-content">
      <div id="states" class="tab-pane fade in active">
        <h3>States</h3>
        <p>States tab</p>
      </div>
      <div id="subs" class="tab-pane fade">
        <h3>Subscriptions</h3>
        <p>Subscriptions tab</p>
      </div>
      <div id="comments" class="tab-pane fade">
        <h3>Comments</h3>
        <p>Comments tab</p>
      </div>
    </div>
  </div>

  <div class="col-md-3">
    <ul class="nav nav-pills nav-stacked" id="myTabs">
      <li class="active">
        <a href="#states" data-toggle="tab">
          States
        </a>
      </li>
      <li>
        <a href="#subs" data-toggle="tab">
          Subscriptions
        </a>
      </li>
      <li>
        <a href="#comments" data-toggle="tab">
          Comments
        </a>
      </li>
    </ul>
  </div>
</div>

Updated- Added other borders to make it look like nav-tabs.


问:
App Icons not included in build from Xcode
I can't see iOS AppIcon when installing the build from the latest Xcode Beta. What could be the possible error?

I have included the required icon sizes including 1024x1024.

答: In my case one of the Pods contained .xcasset. Removing it solved the problem.</p>

ContentLicense: CC BY-SA 4.0


问:
How to make the data only available for one time on firebase
I want to make a report that can only apply by one user for one day only, so the user can't post double record on the same date.
Here is the code

// I use ionic and firebase

this is the code for the html

```<code><ion-header>

  <ion-navbar>
    <ion-title>laporanharian</ion-title>
  </ion-navbar>

</ion-header>

<ion-content padding>
    <ion-list>
          <ion-datetime displayFormat="MMM DD YY" [(ngModel)]="myDate" #mydate></ion-datetime>

          <ion-item>
            <ion-label floating>Porsi Karbohidrat</ion-label>
            <ion-input type="number" #porsiKarbohidrat></ion-input>
          </ion-item>

          <ion-item>
            <ion-label floating>Porsi Protein Hewani</ion-label>
            <ion-input type="number" #porsiProteinHewani></ion-input>
          </ion-item>

          <ion-item>
            <ion-label floating>Porsi Protein Nabati</ion-label>
            <ion-input type="number" #porsiProteinNabati></ion-input>
          </ion-item>

          <ion-item>
              <ion-label floating>Porsi Lemak</ion-label>
              <ion-input type="number" #porsiLemak></ion-input>
            </ion-item>

    </ion-list>
    <button ion-button full (click)="submitLaporan()">Submit</button>

</ion-content>
</code>```

and this is the code for ts

```<code>import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams,AlertController } from 'ionic-angular';
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFireDatabase} from 'angularfire2/database';

/**
 * Generated class for the LaporanharianPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */

@Component({
  selector: 'page-laporanharian',
  templateUrl: 'laporanharian.html',
})
export class LaporanharianPage {

  myDate: String = new Date().toISOString();
  id : string;

  constructor(private alertctrl :AlertController ,private db : AngularFireDatabase,public fire :AngularFireAuth,public navCtrl: NavController, public navParams: NavParams) {
  }

  @ViewChild('mydate') mydate;
  @ViewChild('porsiKarbohidrat') porsiKarbohidrat;
  @ViewChild('porsiProteinHewani') porsiProteinHewani;
  @ViewChild('porsiProteinNabati') porsiProteinNabati;
  @ViewChild('porsiLemak') porsiLemak;

  ionViewDidLoad() {
    console.log('ionViewDidLoad LaporanharianPage');
  }
  alert(message : string)
  {
    this.alertctrl.create({
      title: 'info !',
      subTitle: message,
      buttons: ['OK']
    }).present();
  }

  submitLaporan()
  {

    this.id = this.fire.auth.currentUser.uid;
    this.db.list('/laporan/'+this.id).push({
      mydate : this.mydate.value,
      porsiKarbohidrat : this.porsiKarbohidrat.value,
      porsiProteinHewani : this.porsiProteinHewani.value,
      porsiProteinNabati : this.porsiProteinNabati.value,
      porsiLemak : this.porsiLemak.value,
    })

    this.alert("Sukses")
    }

}
</code>```

I just use the standar code to push the data to firebase.
With this code I can upload report double on the same day.

答:
You can check Firebase for existing reports which are newer than one day (in milliseconds). If there is a rapport, permit inserting a new one.

Method to filter reports from Firebase:

```<code>const yesterday = Date.now() - (24 * 60 * 60 * 1000);

db
  .list<Report>('/laporan/' + this.id)
  .valueChanges()
  .map(reports => reports.filter(report => report.mydate > yesterday))
  .subscribe(reports => {
    if (reports.length === 0) {
      // insert report in Firebase
    }

    console.log(reports);
});
</code>```

Note: mydate = milliseconds elapsed since 1 January 1970 00:00:00 UTC.

Body:
I want to make a report that can only apply by one user for one day only, so the user can't post double record on the same date.
Here is the code

// I use ionic and firebase

this is the code for the html

<ion-header>

  <ion-navbar>
    <ion-title>laporanharian</ion-title>
  </ion-navbar>

</ion-header>

<ion-content padding>
    <ion-list>
          <ion-datetime displayFormat="MMM DD YY" [(ngModel)]="myDate" #mydate></ion-datetime>

          <ion-item>
            <ion-label floating>Porsi Karbohidrat</ion-label>
            <ion-input type="number" #porsiKarbohidrat></ion-input>
          </ion-item>

          <ion-item>
            <ion-label floating>Porsi Protein Hewani</ion-label>
            <ion-input type="number" #porsiProteinHewani></ion-input>
          </ion-item>

          <ion-item>
            <ion-label floating>Porsi Protein Nabati</ion-label>
            <ion-input type="number" #porsiProteinNabati></ion-input>
          </ion-item>

          <ion-item>
              <ion-label floating>Porsi Lemak</ion-label>
              <ion-input type="number" #porsiLemak></ion-input>
            </ion-item>

    </ion-list>
    <button ion-button full (click)="submitLaporan()">Submit</button>

</ion-content>

and this is the code for ts

import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams,AlertController } from 'ionic-angular';
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFireDatabase} from 'angularfire2/database';

/**
 * Generated class for the LaporanharianPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */

@Component({
  selector: 'page-laporanharian',
  templateUrl: 'laporanharian.html',
})
export class LaporanharianPage {

  myDate: String = new Date().toISOString();
  id : string;

  constructor(private alertctrl :AlertController ,private db : AngularFireDatabase,public fire :AngularFireAuth,public navCtrl: NavController, public navParams: NavParams) {
  }

  @ViewChild('mydate') mydate;
  @ViewChild('porsiKarbohidrat') porsiKarbohidrat;
  @ViewChild('porsiProteinHewani') porsiProteinHewani;
  @ViewChild('porsiProteinNabati') porsiProteinNabati;
  @ViewChild('porsiLemak') porsiLemak;

  ionViewDidLoad() {
    console.log('ionViewDidLoad LaporanharianPage');
  }
  alert(message : string)
  {
    this.alertctrl.create({
      title: 'info !',
      subTitle: message,
      buttons: ['OK']
    }).present();
  }

  submitLaporan()
  {

    this.id = this.fire.auth.currentUser.uid;
    this.db.list('/laporan/'+this.id).push({
      mydate : this.mydate.value,
      porsiKarbohidrat : this.porsiKarbohidrat.value,
      porsiProteinHewani : this.porsiProteinHewani.value,
      porsiProteinNabati : this.porsiProteinNabati.value,
      porsiLemak : this.porsiLemak.value,
    })

    this.alert("Sukses")
    }

}

I just use the standar code to push the data to firebase.
With this code I can upload report double on the same day.

Body:
You can check Firebase for existing reports which are newer than one day (in milliseconds). If there is a rapport, permit inserting a new one.

Method to filter reports from Firebase:

const yesterday = Date.now() - (24 * 60 * 60 * 1000);

db
  .list<Report>('/laporan/' + this.id)
  .valueChanges()
  .map(reports => reports.filter(report => report.mydate > yesterday))
  .subscribe(reports => {
    if (reports.length === 0) {
      // insert report in Firebase
    }

    console.log(reports);
});

Note: mydate = milliseconds elapsed since 1 January 1970 00:00:00 UTC.


问:
SLES 12 syntax error: '=~' unexpected operator/operand
i have developed a bigger script for SLES11 and everything is running fine.
But with SLES12 there are some syntax errors when starting the script.

ERROR: syntax error: '=~' unexpected operator/operand

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

while [[ ! $BIGTAB =~ ^-?[0-9* ]+$ ]] || [[ ! $BIGTAB -ge 1 ]]; do
echo "  Enter number of tables to display:"
read BIGTAB
...
</code>```

=~ seems to be not supported any more!?
Could you give me help, how to replace the syntax for SLES12 (and still also running under SLES11).

Thank you!

答:
You're using legacy ksh (built on mksh) on SLES 12:

# echo $KSH_VERSION
@(#)LEGACY KSH R54 2016/11/11
# [[ a =~ a ]]
ksh: syntax error: '=~' unexpected operator/operand
#
```
<p>So you need to install the <em>real</em> ksh/ksh93 (not sure what's the pkg name on SLES though).</p>
<pre class="lang-none prettyprint-override"><code># echo $KSH_VERSION
Version AJM 93u+ 2012-08-01
# [[ a =~ a ]]
#
</code>```

UPDATE:

Just checked SUSE's web site, there's ksh (and no mksh) in SLES 11 but only mksh in SLES 12.

UPDATE #2:

According to the SLES 12 SP1 release notes, you need to install the legacy module to get back ksh.

1.4.1.3 Support for Korn Shell (ksh) Extended Until End of March 2022

Support for the legacy package ksh in SLE was originally slated to end in 2017. However, many customers still depend on ksh.

Support for ksh has been extended until the end of March 2022.

Beyond that time, you can use the mksh implementation of Korn Shell (package mksh). However, as mksh is based on pdksh, there are certain functional differences. For example, its handling of pipelines is similar to Bash.

8.2.5 KSH 93v Replaced with KSH 93u Report

In the Legacy Module for SUSE Linux Enterprise 12, we shipped KSH 93v. However, the 93v branch was not fully stable yet.

With SLE 12 SP1, we release KSH 93u, which is more stable version 93v. In order to provide a regular update path from 93v to 93u, a higher version number (93vu) has been used for this update.

Body:
i have developed a bigger script for SLES11 and everything is running fine.
But with SLES12 there are some syntax errors when starting the script.

ERROR: syntax error: '=~' unexpected operator/operand

#!/bin/ksh

while [[ ! $BIGTAB =~ ^-?[0-9* ]+$ ]] || [[ ! $BIGTAB -ge 1 ]]; do
echo "  Enter number of tables to display:"
read BIGTAB
...

=~ seems to be not supported any more!?
Could you give me help, how to replace the syntax for SLES12 (and still also running under SLES11).

Thank you!

Body:
You're using legacy ksh (built on mksh) on SLES 12:

# echo $KSH_VERSION
@(#)LEGACY KSH R54 2016/11/11
# [[ a =~ a ]]
ksh: syntax error: '=~' unexpected operator/operand
#

So you need to install the real ksh/ksh93 (not sure what's the pkg name on SLES though).

# echo $KSH_VERSION
Version AJM 93u+ 2012-08-01
# [[ a =~ a ]]
#

UPDATE:

Just checked SUSE's web site, there's ksh (and no mksh) in SLES 11 but only mksh in SLES 12.

UPDATE #2:

According to the SLES 12 SP1 release notes, you need to install the legacy module to get back ksh.

1.4.1.3 Support for Korn Shell (ksh) Extended Until End of March 2022

Support for the legacy package ksh in SLE was originally slated to end in 2017. However, many customers still depend on ksh.

Support for ksh has been extended until the end of March 2022.

Beyond that time, you can use the mksh implementation of Korn Shell (package mksh). However, as mksh is based on pdksh, there are certain functional differences. For example, its handling of pipelines is similar to Bash.

8.2.5 KSH 93v Replaced with KSH 93u Report

In the Legacy Module for SUSE Linux Enterprise 12, we shipped KSH 93v. However, the 93v branch was not fully stable yet.

With SLE 12 SP1, we release KSH 93u, which is more stable version 93v. In order to provide a regular update path from 93v to 93u, a higher version number (93vu) has been used for this update.


问:
SNS multiple subscribers
We have an SNS queue with multiple subscribers (2 * SQS, 1 * email, etc.). However, we only get the notification for the last subscriber.
I.e. when each of them is registered alone we get to notification. So as far as I understand each of them alone is configured all right.

I didn't find any relevant AWS documentation about it (limit of subscribers, policies, etc.)

Would love to hear any hint about it. Thanks in advance.

Solution: the issue was the order in which the SQS permission-subscription was created in. The correct order is detailed here. If you do step 3 before 2 it won't work.

答:
```<code>{
  "Version": "2012-10-17",
  "Id": "arn:aws:sqs:us-east-1:<account-number>:<sqs-name>/SQSDefaultPolicy",
  "Statement": [
         {
        "Sid": "<sid>",
        "Effect": "Allow",
        "Principal": "*",
        "Action": "SQS:SendMessage",
        "Resource": "arn:aws:sqs:us-east-1:<account-number>:<name>",
        "Condition": {
                "ArnEquals": {
                      "aws:SourceArn": "arn:aws:sns:us-west-2:<account-number>:*"
                     }
                }
          }
     ]
}
</code>```

<p>Here * is the key. It allows other sns to write to the same queue. </p>

Title: SNS multiple subscribers

Body:
{
  "Version": "2012-10-17",
  "Id": "arn:aws:sqs:us-east-1:<account-number>:<sqs-name>/SQSDefaultPolicy",
  "Statement": [
         {
        "Sid": "<sid>",
        "Effect": "Allow",
        "Principal": "*",
        "Action": "SQS:SendMessage",
        "Resource": "arn:aws:sqs:us-east-1:<account-number>:<name>",
        "Condition": {
                "ArnEquals": {
                      "aws:SourceArn": "arn:aws:sns:us-west-2:<account-number>:*"
                     }
                }
          }
     ]
}

Here * is the key. It allows other sns to write to the same queue.


问:
Making an element of a 2d array a constant
Suppose I have a 2d array as

```<code>arr[10][15];
</code>```

Now, I want just one element of the array to be constant. I want the arr[9][8] to be fixed to 101:

```<code>arr[9][8] = 101;
</code>```

I tried this:

```<code>const arr[9][8] = 101;
</code>```

But the compiler gave errors.
How can I make it constant?

答: You can make the whole array constant, but you cannot make just part of it constant.  If part of the array is mutable, then the whole array has to be mutable.

Body:
Suppose I have a 2d array as

arr[10][15];

Now, I want just one element of the array to be constant. I want the arr[9][8] to be fixed to 101:

arr[9][8] = 101;

I tried this:

const arr[9][8] = 101;

But the compiler gave errors.
How can I make it constant?


问:
How to find difference between dates per each id in python?
I have a pandas dataframe with a format like this:

```<code>student_id     subject_id   subject_date
100             2000        2010-01-01
100             2001        2010-03-05
100             2002        2012-05-25
101             2000        2009-01-10
101             2001        2016-08-16
102             2000        2008-05-05
102             2003        2008-05-20
102             2004        2009-01-03
102             2005        2010-02-13
</code>```

The dataframe is already ordered by student_id and subject_date.
The goal is to get the difference between subject_date for each student_id. For each student_id, it is guaranteed that there will be a minimum of 2 distinct subject_id. The resulting dataframe will look something like this:

```<code>student_id     subject_id   subject_date  diff_in_dates
100             2000        2010-01-01    NA
100             2001        2010-03-05    30
100             2002        2012-05-25    60
101             2000        2009-01-10    NA
101             2001        2016-08-16    3000
102             2000        2008-05-05    NA
102             2003        2008-05-20    15
102             2004        2009-01-03    180
102             2005        2010-02-13    370
</code>```

diff_in_dates values are just an approximation here and not the actual difference.

Body:
I have a pandas dataframe with a format like this:

student_id     subject_id   subject_date
100             2000        2010-01-01
100             2001        2010-03-05
100             2002        2012-05-25
101             2000        2009-01-10
101             2001        2016-08-16
102             2000        2008-05-05
102             2003        2008-05-20
102             2004        2009-01-03
102             2005        2010-02-13

The dataframe is already ordered by student_id and subject_date.
The goal is to get the difference between subject_date for each student_id. For each student_id, it is guaranteed that there will be a minimum of 2 distinct subject_id. The resulting dataframe will look something like this:

student_id     subject_id   subject_date  diff_in_dates
100             2000        2010-01-01    NA
100             2001        2010-03-05    30
100             2002        2012-05-25    60
101             2000        2009-01-10    NA
101             2001        2016-08-16    3000
102             2000        2008-05-05    NA
102             2003        2008-05-20    15
102             2004        2009-01-03    180
102             2005        2010-02-13    370

diff_in_dates values are just an approximation here and not the actual difference.

Body:
IIUC:

In [362]: df['diff_in_dates '] = df.groupby('student_id')['subject_date'].diff().dt.days

In [363]: df
Out[363]:
   student_id  subject_id subject_date  diff_in_dates
0         100        2000   2010-01-01             NaN
1         100        2001   2010-03-05            63.0
2         100        2002   2012-05-25           812.0
3         101        2000   2009-01-10             NaN
4         101        2001   2016-08-16          2775.0
5         102        2000   2008-05-05             NaN
6         102        2003   2008-05-20            15.0
7         102        2004   2009-01-03           228.0
8         102        2005   2010-02-13           406.0


问:
Suppress warning CS1998: This async method lacks 'await'
I've got an interface with some functions that return Task. Some of the classes that implement the interface do not have anything to await, while others might just throw - so the warnings are spurious and annoying.

Is it possible to suppress these warnings? E.g.:

public async Task<object> test()
{
    throw new NotImplementedException();
}
```

yields:

warning CS1998: This async method lacks 'await' operators and will run
synchronously. Consider using the 'await' operator to await
non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work
on a background thread.

答:
Here is some alternatives depending on your method signature.</p>

```<code>    public async Task Test1()
    {
        await Task.CompletedTask;
    }

    public async Task<object> Test2()
    {
        return await Task.FromResult<object>(null);
    }

    public async Task<object> Test3()
    {
        return await Task.FromException<object>(new NotImplementedException());
    }
</code>```

Body:
I've got an interface with some functions that return Task. Some of the classes that implement the interface do not have anything to await, while others might just throw - so the warnings are spurious and annoying.

Is it possible to suppress these warnings? E.g.:

public async Task<object> test()
{
    throw new NotImplementedException();
}

yields:

warning CS1998: This async method lacks 'await' operators and will run
synchronously. Consider using the 'await' operator to await
non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work
on a background thread.

Body:
Here is some alternatives depending on your method signature.

    public async Task Test1()
    {
        await Task.CompletedTask;
    }

    public async Task<object> Test2()
    {
        return await Task.FromResult<object>(null);
    }

    public async Task<object> Test3()
    {
        return await Task.FromException<object>(new NotImplementedException());
    }


答:
this is simple in practice! Check out dif():

```<code>df1['diff_in_date'] = df1.groupby('student_id')['subject_date'].diff()

   student_id  subject_id subject_date diff_in_date
0         100        2000   2010-01-01          NaT
1         100        2001   2010-03-05      63 days
2         100        2002   2012-05-25     812 days
3         101        2000   2009-01-10          NaT
4         101        2001   2016-08-16    2775 days
5         102        2000   2008-05-05          NaT
6         102        2003   2008-05-20      15 days
7         102        2004   2009-01-03     228 days
8         102        2005   2010-02-13     406 days
</code>```

dif() is just doing a difference from the current record and the previous record along the column. It's great that your data was already sorted correctly!

for future use dif() could also take in a parameter to add multiple row differences into the result. so see the an example output below:

```<code>df1['diff_in_date'] = df1.groupby('student_id')['subject_date'].diff(2)

# output
   student_id  subject_id subject_date diff_in_date
0         100        2000   2010-01-01          NaT
1         100        2001   2010-03-05          NaT
2         100        2002   2012-05-25     875 days
3         101        2000   2009-01-10          NaT
4         101        2001   2016-08-16          NaT
5         102        2000   2008-05-05          NaT
6         102        2003   2008-05-20          NaT
7         102        2004   2009-01-03     243 days
8         102        2005   2010-02-13     634 days
</code>```

Title: How to find difference between dates per each id in python?

Body:
this is simple in practice! Check out dif():

df1['diff_in_date'] = df1.groupby('student_id')['subject_date'].diff()

   student_id  subject_id subject_date diff_in_date
0         100        2000   2010-01-01          NaT
1         100        2001   2010-03-05      63 days
2         100        2002   2012-05-25     812 days
3         101        2000   2009-01-10          NaT
4         101        2001   2016-08-16    2775 days
5         102        2000   2008-05-05          NaT
6         102        2003   2008-05-20      15 days
7         102        2004   2009-01-03     228 days
8         102        2005   2010-02-13     406 days

dif() is just doing a difference from the current record and the previous record along the column. It's great that your data was already sorted correctly!

for future use dif() could also take in a parameter to add multiple row differences into the result. so see the an example output below:

df1['diff_in_date'] = df1.groupby('student_id')['subject_date'].diff(2)

# output
   student_id  subject_id subject_date diff_in_date
0         100        2000   2010-01-01          NaT
1         100        2001   2010-03-05          NaT
2         100        2002   2012-05-25     875 days
3         101        2000   2009-01-10          NaT
4         101        2001   2016-08-16          NaT
5         102        2000   2008-05-05          NaT
6         102        2003   2008-05-20          NaT
7         102        2004   2009-01-03     243 days
8         102        2005   2010-02-13     634 days


问:
pyspark how can I combine column values if columns have a same value
I have an idea to combine dataframe values (a list) in different rows with the same key.
The combination must have a same value or more in different rows, so I can not just use df.groupBy('id') to get the result.

Following is the example:

```<code>+---------+--------------------+
|id       |num_list            |
+---------+--------------------+
|apple    |[11, 12]            |
|apple    |[11, 13 ,14]        |
|apple    |[10, 22, 25]        |
|banana   |[15, 26]            |
|banana   |[15, 29]            |
|banana   |[15, 27]            |
+---------+--------------------+
</code>```

we can find id=apple have two record and two lists like: [11, 12],[11, 13, 14], so they would be combined to a new record id=apple,num_list=[11, 12, 13, 14]

But id=apple,num_list=[10, 22, 25] will not be combined.

and this is the answer i want:

```<code>+---------+--------------------+
|id       |num_list            |
+---------+--------------------+
|apple    |[11, 12, 13, 14]    |
|apple    |[10, 22, 25]        |
|banana   |[15, 26, 27, 29]    |
+---------+--------------------+
</code>```

Edit:

There are some rules that I have to explain.

Just as @Usernamenotfound commented,

Assuming apple have three values [11, 12, 14], [9, 13 ,14], and [12,13,27], the answer will be [9, 11, 12, 13 ,14, 27] not [9, 11, 12, 13 ,14] and[12,13,27].

There are some new example:

```<code>+--------------------+------------+
|                  id|num_list    |
+--------------------+------------+
|apple               |         [0]|
|apple               |         [0]|
|apple               |         [1]|
|apple               |         [1]|
|apple               |         [2]|
|apple               |         [3]|
|apple               |         [4]|
|apple               |         [5]|
|apple               |         [6]|
|apple               |         [6]|
|apple               |         [7]|
|apple               |      [7, 8]|
|apple               |         [9]|
|apple               |         [9]|
|apple               |         [9]|
|apple               |     [9, 10]|
|apple               | [9, 17, 18]|
|apple               |        [10]|
|apple               |        [10]|
|apple               |        [10]|
+--------------------+------------+
</code>```

and if i tried the code from @mayank would get wrong answer.

```<code>+--------------------------------+---------------------------------------------------------------------------------------+
|                              id|num_list                                                                               |
+--------------------------------+---------------------------------------------------------------------------------------+
|apple                           |[0]                                                                                |
|apple                           |[0]                                                                                |
|apple                           |[1]                                                                                |
|apple                           |[2]                                                                                |
|apple                           |[3]                                                                                |
|apple                           |[4]                                                                                |
|apple                           |[5]                                                                                |
|apple                           |[6]                                                                                |
|apple                           |[8, 7]                                                                                |
|apple                           |[9, 10, 11, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 29, 30, 36, 37, 38]|
|apple                           |[12]                                                                                |
|apple                           |[14]                                                                                |
|apple                           |[24]                                                                                |
|apple                           |[31]                                                                                |
|apple                           |[32]                                                                                |
|apple                           |[33, 34]                                                                               |
|apple                           |[35]                                                                                |
|apple                           |[39]                                                                                |
+--------------------------------+---------------------------------------------------------------------------------------+
</code>```

Any help would be greatly appreciated.

答:
Maybe not the most efficient solution, but it solves your problem.</p>

```<code>import pyspark.sql.functions as F
from pyspark.sql.types import *

def get_combinations(lis):
   final = []

   for li in lis:
       if [y for y in final if [z for z in li if z in y]]:
           found = [y for y in final if [z for z in li if z in y]][0]
           to_add = list(set(found + li))
           final[final.index(found)] = to_add
       else:
           final.append(li)
   return final

apply_udf = F.udf(lambda x:get_combinations(x),ArrayType(ArrayType(IntegerType())))

df = df.groupby('id').agg(F.collect_list('num_list').alias('num_list'))\
        .select(['id', F.explode(apply_udf('num_list')).alias('num_list')])
</code>```

Body:
I have an idea to combine dataframe values (a list) in different rows with the same key.
The combination must have a same value or more in different rows, so I can not just use df.groupBy('id') to get the result.

Following is the example:

+---------+--------------------+
|id       |num_list            |
+---------+--------------------+
|apple    |[11, 12]            |
|apple    |[11, 13 ,14]        |
|apple    |[10, 22, 25]        |
|banana   |[15, 26]            |
|banana   |[15, 29]            |
|banana   |[15, 27]            |
+---------+--------------------+

we can find id=apple have two record and two lists like: [11, 12],[11, 13, 14], so they would be combined to a new record id=apple,num_list=[11, 12, 13, 14]

But id=apple,num_list=[10, 22, 25] will not be combined.

and this is the answer i want:

+---------+--------------------+
|id       |num_list            |
+---------+--------------------+
|apple    |[11, 12, 13, 14]    |
|apple    |[10, 22, 25]        |
|banana   |[15, 26, 27, 29]    |
+---------+--------------------+

Edit:

There are some rules that I have to explain.

Just as @Usernamenotfound commented,

Assuming apple have three values [11, 12, 14], [9, 13 ,14], and [12,13,27], the answer will be [9, 11, 12, 13 ,14, 27] not [9, 11, 12, 13 ,14] and[12,13,27].

There are some new example:

+--------------------+------------+
|                  id|num_list    |
+--------------------+------------+
|apple               |         [0]|
|apple               |         [0]|
|apple               |         [1]|
|apple               |         [1]|
|apple               |         [2]|
|apple               |         [3]|
|apple               |         [4]|
|apple               |         [5]|
|apple               |         [6]|
|apple               |         [6]|
|apple               |         [7]|
|apple               |      [7, 8]|
|apple               |         [9]|
|apple               |         [9]|
|apple               |         [9]|
|apple               |     [9, 10]|
|apple               | [9, 17, 18]|
|apple               |        [10]|
|apple               |        [10]|
|apple               |        [10]|
+--------------------+------------+

and if i tried the code from @mayank would get wrong answer.

+--------------------------------+---------------------------------------------------------------------------------------+
|                              id|num_list                                                                               |
+--------------------------------+---------------------------------------------------------------------------------------+
|apple                           |[0]                                                                                |
|apple                           |[0]                                                                                |
|apple                           |[1]                                                                                |
|apple                           |[2]                                                                                |
|apple                           |[3]                                                                                |
|apple                           |[4]                                                                                |
|apple                           |[5]                                                                                |
|apple                           |[6]                                                                                |
|apple                           |[8, 7]                                                                                |
|apple                           |[9, 10, 11, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 28, 29, 30, 36, 37, 38]|
|apple                           |[12]                                                                                |
|apple                           |[14]                                                                                |
|apple                           |[24]                                                                                |
|apple                           |[31]                                                                                |
|apple                           |[32]                                                                                |
|apple                           |[33, 34]                                                                               |
|apple                           |[35]                                                                                |
|apple                           |[39]                                                                                |
+--------------------------------+---------------------------------------------------------------------------------------+

Any help would be greatly appreciated.

Body:
Maybe not the most efficient solution, but it solves your problem.

import pyspark.sql.functions as F
from pyspark.sql.types import *

def get_combinations(lis):
   final = []

   for li in lis:
       if [y for y in final if [z for z in li if z in y]]:
           found = [y for y in final if [z for z in li if z in y]][0]
           to_add = list(set(found + li))
           final[final.index(found)] = to_add
       else:
           final.append(li)
   return final

apply_udf = F.udf(lambda x:get_combinations(x),ArrayType(ArrayType(IntegerType())))

df = df.groupby('id').agg(F.collect_list('num_list').alias('num_list'))\
        .select(['id', F.explode(apply_udf('num_list')).alias('num_list')])


问:
ASP.NET Core DI: Resolve same instance if scoped service is registered both as service type and implementation type
Say I have a service that I want to resolve with a scoped lifetime. But sometime I try to resolve it as the interface type and sometimes at the implementation type.

The first thing I tried to do was this:

```<code>ServiceCollection services;
services.AddScoped<MyClass>();
services.AddScoped<IMyInterface, MyClass>();
</code>```

The problem with the above sample is that a different instance is used if I resolve IMyInterface, and than resolve MyClass. Basically it's possible that 2 scoped instances are alife at the same time.

I work around this issue in the following way. But it's very error-prone because you can easily forget to do this at one place, and it's really hard to notice.

```<code>serviceCollection.AddScoped<MyClass>();
serviceCollection.AddScoped<IMyInterface, MyClass>(sp => sp.GetRequiredService<MyClass>());
</code>```

Is there any way to accomplish what I want in a way that is less error prone. Preferrably, but not necessarily, in a single registration?

I.e. as an xUnit test:

```<code>public class Tests
{
    [Fact]
    public void ReturnsSameInstanceForImplementationAndServiceType()
    {
        var serviceCollection = new ServiceCollection();

        // TODO: Change these lines so they're less error prone.
        serviceCollection.AddScoped<MyClass>();
        serviceCollection.AddScoped<IMyInterface, MyClass>(sp => sp.GetRequiredService<MyClass>());

        var services = serviceCollection.BuildServiceProvider();
        var myInt = services.GetRequiredService<IMyInterface>();
        var myCls = services.GetRequiredService<MyClass>();

        Assert.Equal(myCls, myInt);
    }

    class MyClass : IMyInterface { }
    interface IMyInterface { }
}
</code>```

答:
One option would be to create your own extension method that wraps up the two lines you've shown in your question. For example:

```<code>public static class ServiceCollectionExtensions
{
    public static void AddScopedInterfaceAndClass<TInterface, TClass>(this IServiceCollection serviceCollection)
        where TInterface : class
        where TClass : class, TInterface
    {
        serviceCollection.AddScoped<TClass>();
        serviceCollection.AddScoped<TInterface, TClass>(sp => sp.GetRequiredService<TClass>());
    }
}
</code>```

You could call this like so:

```<code>serviceCollection.AddScopedInterfaceAndClass<IMyInterface, MyClass>();
</code>```

I appreciate that AddScopedInterfaceAndClass isn't the perfect name - it's just an example to demonstrate the idea. Also, there is still the downside that you'd have to remember to use this extension rather then AddScoped.

Note: You could simplify the second AddScoped in the extension method by removing the second generic (TClass) as this is inferred by the compiler.

Body:
Say I have a service that I want to resolve with a scoped lifetime. But sometime I try to resolve it as the interface type and sometimes at the implementation type.

The first thing I tried to do was this:

ServiceCollection services;
services.AddScoped<MyClass>();
services.AddScoped<IMyInterface, MyClass>();

The problem with the above sample is that a different instance is used if I resolve IMyInterface, and than resolve MyClass. Basically it's possible that 2 scoped instances are alife at the same time.

I work around this issue in the following way. But it's very error-prone because you can easily forget to do this at one place, and it's really hard to notice.

serviceCollection.AddScoped<MyClass>();
serviceCollection.AddScoped<IMyInterface, MyClass>(sp => sp.GetRequiredService<MyClass>());

Is there any way to accomplish what I want in a way that is less error prone. Preferrably, but not necessarily, in a single registration?

I.e. as an xUnit test:

public class Tests
{
    [Fact]
    public void ReturnsSameInstanceForImplementationAndServiceType()
    {
        var serviceCollection = new ServiceCollection();

        // TODO: Change these lines so they're less error prone.
        serviceCollection.AddScoped<MyClass>();
        serviceCollection.AddScoped<IMyInterface, MyClass>(sp => sp.GetRequiredService<MyClass>());

        var services = serviceCollection.BuildServiceProvider();
        var myInt = services.GetRequiredService<IMyInterface>();
        var myCls = services.GetRequiredService<MyClass>();

        Assert.Equal(myCls, myInt);
    }

    class MyClass : IMyInterface { }
    interface IMyInterface { }
}

Body:
One option would be to create your own extension method that wraps up the two lines you've shown in your question. For example:

public static class ServiceCollectionExtensions
{
    public static void AddScopedInterfaceAndClass<TInterface, TClass>(this IServiceCollection serviceCollection)
        where TInterface : class
        where TClass : class, TInterface
    {
        serviceCollection.AddScoped<TClass>();
        serviceCollection.AddScoped<TInterface, TClass>(sp => sp.GetRequiredService<TClass>());
    }
}

You could call this like so:

serviceCollection.AddScopedInterfaceAndClass<IMyInterface, MyClass>();

I appreciate that AddScopedInterfaceAndClass isn't the perfect name - it's just an example to demonstrate the idea. Also, there is still the downside that you'd have to remember to use this extension rather then AddScoped.

Note: You could simplify the second AddScoped in the extension method by removing the second generic (TClass) as this is inferred by the compiler.


问:
ExtJS 4 smartphone size
I had very simple appication written for old (24x80) terminals
working in production company. My client ask me to transfer it
as a web application and I use ExtJS 4 to do it. It looks like
this:

and its working on pc stations without any problem.

But next question of my client is to modify this application to
work also on tablets and smartphones. And only problem we see
is proportion, on smartphone this screens are to small. What is
the best way to do it? How can I resize fields and fonts and buttons depending on screen size?

答:
What you need is a Responsive Application.
The problem is that the responsiveConfig was introduced in ExtJS 5.

So if you cannot move to extjs 5.0 or above take a look at this answer.

Another aproach is to use multiple instances for the view. Create three different view instances, one for desktop, one for tablet and one for mobile, keep the same Controller, Model, Store etc and when you initialize your application display the correct view according to the screen size.

Title: ExtJS 4 smartphone size


问:
Validate a form dynamically inserted to the DOM
I am working on a project where I need to validate a form dynamically inserted to the DOM. Was wondering how to properly accomplish this?

I tried the following unsuccessfully:

```<code>  $(document).on('formValidation', '#myform', {
                fields: {
                    "first_name": {
                        validators: {
</code>```

Current Validation format:

```<code>$('#myForm')
        .formValidation({
            fields: {
                "first_name": {
                    validators: {
                        notEmpty: {
                            message: 'Please enter a first name.'
                        }
                    }
                },
</code>```

答:
One solution is to use MutationObserver to listen in on nodes dynamically added to the DOM.

When a form with the id myForm is added to the body you will know and can then execute your form validation logic.

For example

// dynamically add the form for testing
setTimeout(function(){
  var elem = document.createElement('form');
  elem.id="myForm";
  elem.innerHTML="Hello I am a dynamically added form";
  document.body.appendChild(elem);
}, 2000);

// select the target node
var target = document.body;

// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    mutation.addedNodes.forEach(function(node){
      if(node.id === "myForm"){
        console.log("myForm was just added");
        // do validation logic here
      }
    })
  });
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };

// pass in the target node, as well as the observer options
observer.observe(target, config);```

Body:
I am working on a project where I need to validate a form dynamically inserted to the DOM. Was wondering how to properly accomplish this?

I tried the following unsuccessfully:

  $(document).on('formValidation', '#myform', {
                fields: {
                    "first_name": {
                        validators: {

Current Validation format:

$('#myForm')
        .formValidation({
            fields: {
                "first_name": {
                    validators: {
                        notEmpty: {
                            message: 'Please enter a first name.'
                        }
                    }
                },


问:
XPath axis, get all following nodes until
I have the following example of HTML:

```<code><!-- lots of html -->
<h2>Foo bar</h2>
<p>lorem</p>
<p>ipsum</p>
<p>etc</p>

<h2>Bar baz</h2>
<p>dum dum dum</p>
<p>poopfiddles</p>
<!-- lots more html ... -->
</code>```

I'm looking to extract all paragraphs following the 'Foo bar' header, until I reach the 'Bar baz' header (the text for the 'Bar baz' header is unknown, so unfortunately I can't use the answer provided by bougyman). Now I can of course using something like //h2[text()='Foo bar']/following::p but that of course will grab all paragraphs following this header. So I have the option to traverse the nodeset and push paragraphs into an Array until the text matches that of the next following header, but let's be honest, that's never as cool as being able to do it in XPath.

Is there a way to do this that I'm missing?

答:
how about matching on the second one? If you only want the top section, match the second and grab everything above it
.

doc.xpath("//h2[text()='Bar baz']/preceding-sibling::p").map { |m| m.text }
=> ["lorem", "ipsum", "etc"]

or if you don't know the second one, go another level with:
doc.xpath("//h2[text()='Foo bar']/following-sibling::h2/preceding-sibling::p").map { |it| it.text }
=> ["lorem", "ipsum", "etc"]

ContentLicense: CC BY-SA 2.5

Body:
I have the following example of HTML:

Foo bar

lorem

ipsum

etc

Bar baz

dum dum dum

poopfiddles

I'm looking to extract all paragraphs following the 'Foo bar' header, until I reach the 'Bar baz' header (the text for the 'Bar baz' header is unknown, so unfortunately I can't use the answer provided by bougyman). Now I can of course using something like //h2[text()='Foo bar']/following::p but that of course will grab all paragraphs following this header. So I have the option to traverse the nodeset and push paragraphs into an Array until the text matches that of the next following header, but let's be honest, that's never as cool as being able to do it in XPath.

Is there a way to do this that I'm missing?


问:
Embedding a link in react render method
I am fairly new to React JS. I am inside the React render method. I want to embed a link inside of an if statement {menu.Title == "Club Finder" ?  "Club Finder"  : menu.Title}  but it is not rendering the html. Instead the html is being displayed in the navigation menu.  I can not figure out why this is. Any insight on this would be great.  My code is below:</p>

```<code>render() {
    if (!this.props.data.Items) {
      return (
        <div className="alert alert-danger">Menu is empty</div>
      );
    }
    const menuItems = this.props.data.Items.map((menu, index) => (
      <Hammer
        onTap={this.handleMenuTap}
        onClick={this.handleMenuClick}
        onClick={this.handleMenuEnter}
        key={`menu-item-${menu.Title}`}
      >
        <li
          id={`menu-item-${index}`}
        >
          {menu.Title == "Club Finder" ? "<a href='#'>Club Finder</a>"  : menu.Title} <span className="fa fa-chevron-down" />
        </li>
      </Hammer>
    ));
    return (
      <nav className="mega-main-menu">
        <div className="mega-main-menu__logo-container">
          <a className="mega-main-menu__logo" href="/">
            {
              this.props.data.Image ?
                (
                  <img
                    src={this.props.data.Image.Src}
                    alt={this.props.data.Image.Alt}
                    width="264"
                    height="50"
                  />
                ) : ''
            }
          </a>
        </div>
        <div className="mega-main-menu__nav-search-container">
          <Search show={this.state.showSearch} />
          <div className="mega-main-menu__items-container" onMouseLeave={this.handleMenuLeave}>
            <ul className="mega-main-menu__items list--nostyle" style={{ width: 'auto' }}>
              {menuItems}
              {
                this.state.megaMenuContent !== null ? (<MegaMenuOverlay content={this.state.megaMenuContent} />) : ''
              }
            </ul>
          </div>
          <button
            className="mega-main-menu__toggle-mobile btn btn-default"
            onClick={this.showMobileMenu}
          >
            <i className="fa fa-bars text-primary" />
          </button>
          <div className="mega-main-menu__actions">
            <a
              href="/login"
              className="btn bg-primary mega-main-menu__actions-login"
              ref={(button) => { this.usmsButton = button; }}
            >
              MY USMS
            </a>
            <i
              className="fa fa-search text-primary mega-main-menu__actions-search"
              onClick={this.toggleSearch}
            />
          </div>
        </div>
        <MobileMenu
          content={this.props.data.Items}
          handleCloseMenu={this.hideMobileMenu}
          showMobileMenu={this.state.showMobileMenu}
        />
      </nav>
    );
  }
</code>```

答:
Do you mean you get rendered RAW HTML output?

Try:

```<code>{
  menu.Title == "Club Finder" ? <a href='#'>Club Finder</a> : menu.Title
}
<span className="fa fa-chevron-down" />
</code>```

Title: Embedding a link in react render method

Body:
I am fairly new to React JS. I am inside the React render method. I want to embed a link inside of an if statement {menu.Title == "Club Finder" ?  "Club Finder"  : menu.Title}  but it is not rendering the html. Instead the html is being displayed in the navigation menu.  I can not figure out why this is. Any insight on this would be great.  My code is below:

render() {
    if (!this.props.data.Items) {
      return (

Menu is empty

      );
    }
    const menuItems = this.props.data.Items.map((menu, index) => (
      <Hammer
        onTap={this.handleMenuTap}
        onClick={this.handleMenuClick}
        onClick={this.handleMenuEnter}
        key={`menu-item-${menu.Title}`}
      >
        <li
          id={`menu-item-${index}`}
        >
          {menu.Title == "Club Finder" ? "Club Finder"  : menu.Title}

      </Hammer>
    ));
    return (

            {
              this.props.data.Image ?
                (

                ) : ''
            }

          <Search show={this.state.showSearch} />

              {menuItems}
              {
                this.state.megaMenuContent !== null ? (<MegaMenuOverlay content={this.state.megaMenuContent} />) : ''
              }

          <button
            className="mega-main-menu__toggle-mobile btn btn-default"
            onClick={this.showMobileMenu}
          >

          </button>

             { this.usmsButton = button; }}
            >
              MY USMS

        <MobileMenu
          content={this.props.data.Items}
          handleCloseMenu={this.hideMobileMenu}
          showMobileMenu={this.state.showMobileMenu}
        />

    );
  }

Body:
Do you mean you get rendered RAW HTML output?

Try:

{
  menu.Title == "Club Finder" ? <a href='#'>Club Finder</a> : menu.Title
}
<span className="fa fa-chevron-down" />


问:
How to do superscripts and subscripts in Jupyter Notebook?
I want to to use numbers to indicate references in footnotes, so I was wondering inside of Jupyter Notebook how can I use superscripts and subscripts?</p>

答:
You can use HTML ' superscript '

http://wikimarkup.wikia.com/wiki/How_to_superscript_text

You can also use Latex $foo^{superscript}$, but the font used to render the text will change and you might not like how it looks.


问:
Onclick event: divs appear one at a time
Is it possible to make based on this actual one div at a time, that is to say both of the two events onclick can't open , but if one is open and the other one is clicked the first automatically close. By the way the context which this code is used doesn't allow the use of Jquery. Thanks for your help

SOCIETES: 400

Part SBF 120 : 120

Part Filiales +100M€: 280

fermer

CONTACTS: 25 400

Part CAC 40 : 15 700

Part Filiales +100M€: 9 700

% contacts IT: 21%

fermer

EMAILS NOMINATIFS: 400

OPT OUT: 3%

LIGNES DIRECTES: 35%

```

答:
```<code>function show(id) {
var v = parseInt(id);
var list = document.getElementsByClassName("benefits");
//var num = list.length;

if(document.getElementById('b'+id).style.display=='none')       {
    document.getElementById('b'+id).style.display='block';
}

for (i = v+1; i <= list.length ; i++) {
if(document.getElementById('b'+i).style.display=='block')       {
    document.getElementById('b'+i).style.display='none';
}
}
for (i = v-1; i >=0 ; i--) {
if(document.getElementById('b'+i).style.display=='block')       {
    document.getElementById('b'+i).style.display='none';
}
}

return false;
}
</code>```


问:
Spring Boot not updating static html (with Kotlin/Intellij)
I built a pretty simple static content web server using Spring Boot, Kotlin and Intellij. I run my program and it properly serves my html on localhost:8080. However, if I update that html while the server is running then force reload the page in the browser my changes are never shown. I've read a bunch of things that could be the problem. Something about thymeleaf cache. Spring Boot Devtools. Intellij auto builds or something. Nothing seems to work. Maybe an extra set of eyes on my code could pick up something I'm missing.

Here's my build.gradle

```<code>buildscript {
    ext.kotlin_version = "1.2.0"
    ext.httpcomponents_version = "4.5.4"
    ext.springframework_version = "1.5.9.RELEASE"

    repositories {
        mavenCentral()
    }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.springframework.boot:spring-boot-gradle-plugin:$springframework_version"
    }
}

group "com.atomicslurry"
version "1.0"

apply plugin: "java"
apply plugin: "kotlin"
apply plugin: "spring-boot"

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
    compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
    compile "org.apache.httpcomponents:httpclient:$httpcomponents_version"
    compile "org.apache.httpcomponents:fluent-hc:$httpcomponents_version"
    compile "com.fasterxml.jackson.module:jackson-module-kotlin:2.9.2"
    compile "org.springframework.boot:spring-boot-starter-thymeleaf:$springframework_version"
    compile "org.springframework.boot:spring-boot-devtools:$springframework_version"
    testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
</code>```

Here's my kotlin app main

```<code>package com.atomicslurry.sentinel

import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication

@SpringBootApplication
open class App

fun main(args: Array<String>) {
    SpringApplication.run(App::class.java, *args)
}
</code>```

Finally, my static html is in src/main/resources/static

Any ideas?

答:
The general workflow that is working for me:

Edit HTML

Press Build Project (Ctr+F9) in IntelliJ, then wait until changes completed

Go to Browser and refresh

Body:
I built a pretty simple static content web server using Spring Boot, Kotlin and Intellij. I run my program and it properly serves my html on localhost:8080. However, if I update that html while the server is running then force reload the page in the browser my changes are never shown. I've read a bunch of things that could be the problem. Something about thymeleaf cache. Spring Boot Devtools. Intellij auto builds or something. Nothing seems to work. Maybe an extra set of eyes on my code could pick up something I'm missing.

Here's my build.gradle

buildscript {
    ext.kotlin_version = "1.2.0"
    ext.httpcomponents_version = "4.5.4"
    ext.springframework_version = "1.5.9.RELEASE"

    repositories {
        mavenCentral()
    }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.springframework.boot:spring-boot-gradle-plugin:$springframework_version"
    }
}

group "com.atomicslurry"
version "1.0"

apply plugin: "java"
apply plugin: "kotlin"
apply plugin: "spring-boot"

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
    compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
    compile "org.apache.httpcomponents:httpclient:$httpcomponents_version"
    compile "org.apache.httpcomponents:fluent-hc:$httpcomponents_version"
    compile "com.fasterxml.jackson.module:jackson-module-kotlin:2.9.2"
    compile "org.springframework.boot:spring-boot-starter-thymeleaf:$springframework_version"
    compile "org.springframework.boot:spring-boot-devtools:$springframework_version"
    testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

Here's my kotlin app main

package com.atomicslurry.sentinel

import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication

@SpringBootApplication
open class App

fun main(args: Array<String>) {
    SpringApplication.run(App::class.java, *args)
}

Finally, my static html is in src/main/resources/static

Any ideas?


问:
Looper or while in a thread?
I'm trying to understand the Looper...

This time i'm getting a little bit confused, because I've only used (until now) the while(true) condition to maintain the thread in an infinite loop.

I just want to know if it is better to use the Looper or the while(true) condition.

I've searched a possible answer to my question in internet and I was quite disappointed in finding codes that use Looper and while(true) together.

Probably I didn't get the point of using the Looper but, you know, we are here to learn... isn't it?

答:
I just want to know if it is better to use the Looper or the while(true) condition.

I'd say, as a general rule, unless you need some very specific low-level control, use the API that are provided by the framework, whichever the framework is.

They usually take care of many aspects that would otherwise have you implement them yourself, such as messaging, task deletion, and so on...

I guess that with the while (true) loop you are trying to achieve some regular task repetition.

In this particular case, yes, use a Handler with its own Looper, so the UI Thread is not blocked, and post your Runnable instances regularly with postDelay(Runnable, long).

@DeeV 's answer already gives you a good understanding about the mentioned components, but you sure will find out everything you need in Android documentation.

Title: Looper or while in a thread?


问:
Android Camera2 API preview sometimes distorted
I am building a custom camera with the Camera2 API.
So far the camera works very well except for the preview which is distorted sometimes. Let's say I open the camera 7 times in a row. All of the attempts are succesful and the 8th time the camera preview is distorted. It looks like it uses the width as the height and vice versa.

I have based my code on the Google sample implementation of the camera2 which can be found here.
the interesting thing is that even the Google sample implementation has this distorted preview sometimes. I have tried to modify the AutoFitTextureView but nothing was successful. I am currently using the AutoFitTextureView.java Google provides again.

A similar post to this one can be found here.
However the proposed fixes didn't solve the problem.

I can reproduce the problem by changing the following in the setUpCameraOutputs method:

```<code>mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
</code>```

to:

```<code>mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
</code>```

Another weird thing is that whenever the distorted preview occurs and you just press the home button so the app goes in onPause() and open up the app again so onResume() gets called, the preview is perfect every time.

Has anyone here experienced this problem and found a fix for it?

Thanks in advance

答: The Google Camera2Basic sample was finally fixed. The original code had a tiny < vs > mistake. It had been wrong for 2 years.

Body:
I am building a custom camera with the Camera2 API.
So far the camera works very well except for the preview which is distorted sometimes. Let's say I open the camera 7 times in a row. All of the attempts are succesful and the 8th time the camera preview is distorted. It looks like it uses the width as the height and vice versa.

I have based my code on the Google sample implementation of the camera2 which can be found here.
the interesting thing is that even the Google sample implementation has this distorted preview sometimes. I have tried to modify the AutoFitTextureView but nothing was successful. I am currently using the AutoFitTextureView.java Google provides again.

A similar post to this one can be found here.
However the proposed fixes didn't solve the problem.

I can reproduce the problem by changing the following in the setUpCameraOutputs method:

mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());

to:

mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());

Another weird thing is that whenever the distorted preview occurs and you just press the home button so the app goes in onPause() and open up the app again so onResume() gets called, the preview is perfect every time.

Has anyone here experienced this problem and found a fix for it?

Thanks in advance


问:
Checking if a variable is initialized
Seems like this would be a duplicate, but maybe it is just so obvious it hasn't been asked...

Is this the proper way of checking if a variable (not pointer) is initialized in a C++ class?

```<code>class MyClass
{
    void SomeMethod();

    char mCharacter;
    double mDecimal;
};

void MyClass::SomeMethod()
{
    if ( mCharacter )
    {
        // do something with mCharacter.
    }

    if ( ! mDecimal )
    {
        // define mDecimal.
    }
}
</code>```

答:
With C++17 you can use std::optional to check if a variable is initialized:

```<code>#include <optional>
#include <iostream>  // needed only for std::cout

int main() {
    std::optional<int> variable;

    if (!variable) {
        std::cout << "variable is NOT initialized\n";
    }

    variable = 3;

    if (variable) {
        std::cout << "variable IS initialized and is set to " << *variable << '\n';
    }

    return 0;
}
</code>```

This will produce the output:

```<code>variable is NOT initialized
variable IS initialized and is set to 3
</code>```

To use std::optional in the code snipped you provided, you'll have to include the <optional> standard library header and add std::optional<...> to the respective variable declarations:

```<code>#include <optional>

class MyClass
{
    void SomeMethod();

    std::optional<char> mCharacter;
    std::optional<double> mDecimal;
};

void MyClass::SomeMethod()
{
    if ( mCharacter )
    {
        std::cout << *mCharacter;  // do something with mCharacter.
    }

    if ( ! mDecimal )
    {
        mDecimal = 3.14159;  // define mDecimal.
    }
}
</code>```

Title: Checking if a variable is initialized

Body:
Seems like this would be a duplicate, but maybe it is just so obvious it hasn't been asked...

Is this the proper way of checking if a variable (not pointer) is initialized in a C++ class?

class MyClass
{
    void SomeMethod();

    char mCharacter;
    double mDecimal;
};

void MyClass::SomeMethod()
{
    if ( mCharacter )
    {
        // do something with mCharacter.
    }

    if ( ! mDecimal )
    {
        // define mDecimal.
    }
}

Body:
With C++17 you can use std::optional to check if a variable is initialized:

#include <optional>
#include <iostream>  // needed only for std::cout

int main() {
    std::optional<int> variable;

    if (!variable) {
        std::cout << "variable is NOT initialized\n";
    }

    variable = 3;

    if (variable) {
        std::cout << "variable IS initialized and is set to " << *variable << '\n';
    }

    return 0;
}

This will produce the output:

variable is NOT initialized
variable IS initialized and is set to 3

To use std::optional in the code snipped you provided, you'll have to include the <optional> standard library header and add std::optional<...> to the respective variable declarations:

#include <optional>

class MyClass
{
    void SomeMethod();

    std::optional<char> mCharacter;
    std::optional<double> mDecimal;
};

void MyClass::SomeMethod()
{
    if ( mCharacter )
    {
        std::cout << *mCharacter;  // do something with mCharacter.
    }

    if ( ! mDecimal )
    {
        mDecimal = 3.14159;  // define mDecimal.
    }
}


问:
Ionic 3: Check if sub-array exists in NavParams.get
So, my app gets a response and navCtrl.push's it as an array into another page
let's say the constructor on the ts of that page looks like this

constructor(public navCtrl: NavController, public navParams: NavParams) {
    this.id = navParams.get('infoList')[0].id;
    this.name = navParams.get('infoList')[0].full_name;
    this.email = navParams.get('infoList')[0].email;
    this.epmname = navParams.get('infoList')[0].managers[0].full_name;
    this.epmemail = navParams.get('infoList')[0].managers[0].email;
    this.epm2name = navParams.get('infoList')[0].managers[1].full_name;
    this.epm2email = navParams.get('infoList')[0].managers[1].email;
    this.epm3name = navParams.get('infoList')[0].managers[2].full_name;
    this.epm3email = navParams.get('infoList')[0].managers[2].email;
  }```
</div>
</div>
</p>

<p>Now, the response may not always have a managers sub array or may only have 1 or 2 sub-elements and not 3, How can I perform a check for this? Thanks</p>

<p>UPDATE: this is how a part of my results.html page looks like:</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-html lang-html prettyprint-override"><code><ion-item-divider color="light">
      Manager Info (Second EPM - if exists):
    </ion-item-divider>
    <ion-item color="none">
      Name: {{epm2name}}
    </ion-item>
    <ion-item color="none">
      Country Code: {{epm2countrycode}}
    </ion-item>
    <ion-item color="none">
      Phone number: {{epm2phone}}
    </ion-item>
    <ion-item color="none">
      Email: {{epm2email}}
    </ion-item></code>```

答:
This is really a horrible way to do that. I highly suggest you use a more object-oriented pattern here. If you follow that then you can easily check the null and etc.

Note: I have extracted below example from one of my project.So please adjust it according to your app. If you have any questions feel free to ask it.

Send

my-send-page.ts

```<code>goToEditBudget(data: Budget) {
    let dtoBudget = new DtoBudget();
    dtoBudget.budget = data;
    dtoBudget.action = 'edit'
    this.navCtrl.push('AddBudgetPage', { data: dtoBudget });
  }
</code>```

Retrieved

add-budget-page.ts

```<code>constructor(private navCtrl: NavController, private navParams: NavParams) {
    let data: DtoBudget = this.navParams.get('data');
    if (data != null) {
      this.data = data.budget;
      this.action = data.action;
    }
  }
</code>```

DtoBudget.ts

```<code>import { Transaction } from './../Transaction';
import { Budget } from './../Budget';

export class DtoBudget {
    budget: Budget;
    action: string;
    transactions: Transaction[]
}
</code>```

Body:
So, my app gets a response and navCtrl.push's it as an array into another page
let's say the constructor on the ts of that page looks like this

constructor(public navCtrl: NavController, public navParams: NavParams) {
    this.id = navParams.get('infoList')[0].id;
    this.name = navParams.get('infoList')[0].full_name;
    this.email = navParams.get('infoList')[0].email;
    this.epmname = navParams.get('infoList')[0].managers[0].full_name;
    this.epmemail = navParams.get('infoList')[0].managers[0].email;
    this.epm2name = navParams.get('infoList')[0].managers[1].full_name;
    this.epm2email = navParams.get('infoList')[0].managers[1].email;
    this.epm3name = navParams.get('infoList')[0].managers[2].full_name;
    this.epm3email = navParams.get('infoList')[0].managers[2].email;
  }

Now, the response may not always have a managers sub array or may only have 1 or 2 sub-elements and not 3, How can I perform a check for this? Thanks

UPDATE: this is how a part of my results.html page looks like:

<ion-item-divider color="light">
      Manager Info (Second EPM - if exists):
    </ion-item-divider>
    <ion-item color="none">
      Name: {{epm2name}}
    </ion-item>
    <ion-item color="none">
      Country Code: {{epm2countrycode}}
    </ion-item>
    <ion-item color="none">
      Phone number: {{epm2phone}}
    </ion-item>
    <ion-item color="none">
      Email: {{epm2email}}
    </ion-item>

Body:
This is really a horrible way to do that. I highly suggest you use a more object-oriented pattern here. If you follow that then you can easily check the null and etc.

Note: I have extracted below example from one of my project.So please adjust it according to your app. If you have any questions feel free to ask it.

Send

my-send-page.ts

goToEditBudget(data: Budget) {
    let dtoBudget = new DtoBudget();
    dtoBudget.budget = data;
    dtoBudget.action = 'edit'
    this.navCtrl.push('AddBudgetPage', { data: dtoBudget });
  }

Retrieved

add-budget-page.ts

constructor(private navCtrl: NavController, private navParams: NavParams) {
    let data: DtoBudget = this.navParams.get('data');
    if (data != null) {
      this.data = data.budget;
      this.action = data.action;
    }
  }

DtoBudget.ts

import { Transaction } from './../Transaction';
import { Budget } from './../Budget';

export class DtoBudget {
    budget: Budget;
    action: string;
    transactions: Transaction[]
}


问:
How can I optimize the conversion of a Data Frame to Map[String,List[String]] in scala/spark?
I have a DataFrame with a lot of Signals and I want to convert it into a Map[String, List[String]]

I have running Code, but I have the problem that it takes very long to execute it. For only a bunch of hundred signals it needs about 13 minutes.

This is the inputDataFrame I got in the beginning (example):

```<code>+----------+-----+
|SignalName|Value|
+----------+-----+
|        S1|   V1|
|        S2|   V1|
|        S1|   V2|
|        S2|   V2|
|        S3|   V1|
|        S1|   V3|
|        S1|   V1|
+----------+-----+
</code>```

Then I want to filter the duplicates

```<code>var reducedDF = inputDataFrame.select("SignalName","Value").dropDuplicates()
</code>```

The ouput for reduedDF.show :

```<code>+----------+-----+
|SignalName|Value|
+----------+-----+
|        S1|   V1|
|        S1|   V2|
|        S1|   V3|
|        S2|   V1|
|        S2|   V2|
|        S3|   V1|
+----------+-----+
</code>```

The next step is to get an RDD of SignalNames without an duplicate. And I used zipWithIndex(), because later I want to read every value of the RDD.
I can do this with the following code:

```<code>var RDDOfSignalNames = reducedDF.select("SignalName").rdd.map(r => r(0).asInstanceOf[String])
RDDOfSignalNames = RDDOfSignalNames.distinct()
val RDDwithIndex = RDDOfSignalNames.zipWithIndex()
val indexKey = RDDwithIndex.map { case (k, v) => (v, k) }
</code>```

And now the last step is to get for every SignalName every possible Value as a List of Type List[String] and add it to an Map:

```<code>var dataTmp: DataFrame = null
var signalname = Seq[String]("")
var map = scala.collection.mutable.Map[String, List[String]]()

for (i <- 0 to (RDDOfSignalNames.count()).toInt - 1) {

  signalname = indexKey.lookup(i)

  dataTmp = reducedDF.filter(data.col("Signalname").contains(signalname(0)))

  map += (signalname(0) -> dataTmp.rdd.map(r => r(0).asInstanceOf[String]).collect().toList)
  println(i+"/"+(RDDOfSignalNames.count().toInt - 1).toString())

}
</code>```

In the End the Map looks like this:

```<code>scala.collection.mutable.Map[String,List[String]] = Map(S1 -> List(V1, V2, V3), S3 -> List(V1), S2 -> List(V1, V2))
</code>```

The Problem is the line map += ... for 106 Signals it takes about 13 minutes! Is there more efficient way to do this?

答:
First of all, use of var is not recommended in scala. You should always try to use immutable variables. So changing the following line

```<code>var reducedDF = inputDataFrame.select("SignalName","Value").dropDuplicates()
</code>```

to

```<code>val reducedDF = inputDataFrame.select("SignalName","Value").distinct()
</code>```

is preferred.

And,

You don't need to go through such complexities to get your desired output. You can get your desired output doing the following

```<code>import org.apache.spark.sql.functions.collect_list
reducedDF
      .groupBy("SignalName")
      .agg(collect_list($"Value").as("Value"))
      .rdd
      .map(row => (row(0).toString -> row(1).asInstanceOf[scala.collection.mutable.WrappedArray[String]].toList))
      .collectAsMap()
</code>```

where,

reducedDF.groupBy("SignalName").agg(collect_list($"Value").as("Value")) gives you dataframe as

```<code>+----------+------------+
|SignalName|Value       |
+----------+------------+
|S3        |[V1]        |
|S2        |[V2, V1]    |
|S1        |[V1, V2, V3]|
+----------+------------+
</code>```

the rest of the code .rdd.map(row => (row(0).toString -> row(1).asInstanceOf[scala.collection.mutable.WrappedArray[String]].toList)).collectAsMap() is just converting the dataframe to your desired output Map.

final map output is

```<code>Map(S1 -> List(V1, V2, V3), S3 -> List(V1), S2 -> List(V2, V1))
</code>```

Body:
I have a DataFrame with a lot of Signals and I want to convert it into a Map[String, List[String]]

I have running Code, but I have the problem that it takes very long to execute it. For only a bunch of hundred signals it needs about 13 minutes.

This is the inputDataFrame I got in the beginning (example):

+----------+-----+
|SignalName|Value|
+----------+-----+
|        S1|   V1|
|        S2|   V1|
|        S1|   V2|
|        S2|   V2|
|        S3|   V1|
|        S1|   V3|
|        S1|   V1|
+----------+-----+

Then I want to filter the duplicates

var reducedDF = inputDataFrame.select("SignalName","Value").dropDuplicates()

The ouput for reduedDF.show :

+----------+-----+
|SignalName|Value|
+----------+-----+
|        S1|   V1|
|        S1|   V2|
|        S1|   V3|
|        S2|   V1|
|        S2|   V2|
|        S3|   V1|
+----------+-----+

The next step is to get an RDD of SignalNames without an duplicate. And I used zipWithIndex(), because later I want to read every value of the RDD.
I can do this with the following code:

var RDDOfSignalNames = reducedDF.select("SignalName").rdd.map(r => r(0).asInstanceOf[String])
RDDOfSignalNames = RDDOfSignalNames.distinct()
val RDDwithIndex = RDDOfSignalNames.zipWithIndex()
val indexKey = RDDwithIndex.map { case (k, v) => (v, k) }

And now the last step is to get for every SignalName every possible Value as a List of Type List[String] and add it to an Map:

var dataTmp: DataFrame = null
var signalname = Seq[String]("")
var map = scala.collection.mutable.Map[String, List[String]]()

for (i <- 0 to (RDDOfSignalNames.count()).toInt - 1) {

  signalname = indexKey.lookup(i)

  dataTmp = reducedDF.filter(data.col("Signalname").contains(signalname(0)))

  map += (signalname(0) -> dataTmp.rdd.map(r => r(0).asInstanceOf[String]).collect().toList)
  println(i+"/"+(RDDOfSignalNames.count().toInt - 1).toString())

}

In the End the Map looks like this:

scala.collection.mutable.Map[String,List[String]] = Map(S1 -> List(V1, V2, V3), S3 -> List(V1), S2 -> List(V1, V2))

The Problem is the line map += ... for 106 Signals it takes about 13 minutes! Is there more efficient way to do this?

Body:
First of all, use of var is not recommended in scala. You should always try to use immutable variables. So changing the following line

var reducedDF = inputDataFrame.select("SignalName","Value").dropDuplicates()

to

val reducedDF = inputDataFrame.select("SignalName","Value").distinct()

is preferred.

And,

You don't need to go through such complexities to get your desired output. You can get your desired output doing the following

import org.apache.spark.sql.functions.collect_list
reducedDF
      .groupBy("SignalName")
      .agg(collect_list($"Value").as("Value"))
      .rdd
      .map(row => (row(0).toString -> row(1).asInstanceOf[scala.collection.mutable.WrappedArray[String]].toList))
      .collectAsMap()

where,

reducedDF.groupBy("SignalName").agg(collect_list($"Value").as("Value")) gives you dataframe as

+----------+------------+
|SignalName|Value       |
+----------+------------+
|S3        |[V1]        |
|S2        |[V2, V1]    |
|S1        |[V1, V2, V3]|
+----------+------------+

the rest of the code .rdd.map(row => (row(0).toString -> row(1).asInstanceOf[scala.collection.mutable.WrappedArray[String]].toList)).collectAsMap() is just converting the dataframe to your desired output Map.

final map output is

Map(S1 -> List(V1, V2, V3), S3 -> List(V1), S2 -> List(V2, V1))


问:
C++ Composition Constructor
So I've got a program with classes Car, Route and Taxi. I'm using composition in order to obtain the data from the classes Car and Route. Each class needs to be able to enter data on it's own and the data entered to be checked. I'm having difficulties with how to make the constructor of the Taxi class the way that he uses and checks the data with the get/set methods of the classes Car and Route.
How to access the parameters in the setRouteTaxidata method?

Any suggestions?

```<code>class RouteTaxi {
    private:
        int id;
    public:
        Car car;
        Route route;
        RouteTaxi();
        ~RouteTaxi();
        void setRouteTaxidata(string cbrand, string cmodel, int cyears, int cseatingCapacity, double cloadCapacity, double cfuelConsumption,string rnodes, double rrouteLength, int rtoursPerDay, int i);

};

RouteTaxi::RouteTaxi(){
    setRouteTaxidata(??)   ??????
}

void RouteTaxi::setRouteTaxidata(string cbrand, string cmodel, int cyears, int cseatingCapacity, double cloadCapacity, double cfuelConsumption, string rnodes, double rrouteLength, int rtoursPerDay, int i){
    car.setBrand(cbrand);

}
</code>```

答:
Your constructor RouteTaxi() is a default constructor. It must create a valid object without any of those, so you would have to have acceptable default values.

There's no good way to make a default route, unless you have a "nowhere" route with a "nocar" car, so you can instead require those arguments in the constructor, as in this example:

```<code>#include<string>
using std::string;

class Car {
public:
    Car(string cbrand, string cmodel, int cyears, int cseatingCapacity, double cloadCapacity, double cfuelConsumption){}
};

class Route {
public:
    Route(string rnodes, double rrouteLength, int rtoursPerDay){}
};

class RouteTaxi
{
private:
    int id;
public:
    Car car;
    Route route;
    RouteTaxi(string cbrand, string cmodel, int cyears, int
        cseatingCapacity, double cloadCapacity, double cfuelConsumption,
        string rnodes, double rrouteLength, int rtoursPerDay, int i)
        : car(cbrand, cmodel, cyears, cseatingCapacity, cloadCapacity, cfuelConsumption),
          route(rnodes, rrouteLength, rtoursPerDay),
          id(i)
    {}
    static RouteTaxi generate_from_console_input();
};

// this is a factory function (class static member of RouteTaxi)
RouteTaxi RouteTaxi::generate_from_console_input() {
    // input from console
    string cbrand, cmodel, rnodes;
    int cyears, cseatingCapacity, rtoursPerDay, i;
    double cloadCapacity, cfuelConsuption, rrouteLength;

    // return the object
    // this is an error, using uninitialized data, simply because I am not actually getting the data from the console. You will do that, so it will not be a problem.
    return RouteTaxi(cbrand, cmodel, cyears, cseatingCapacity, cloadCapacity, cfuelConsuption, rnodes, rrouteLength, rtoursPerDay, i);
}
</code>```

Note the colon and initializer list which the constructor uses to initialize other objects before it executes its own constructor body. http://en.cppreference.com/w/cpp/language/initializer_list

The factory generator is another way to create objects. You need all the info before you call the actual constructor, so ... write a function which gets it, before you actually call the constructor.

This is a well known design pattern. See https://en.wikipedia.org/wiki/Creational_pattern. Although those go into a lot more detail. You are not dealing with a lot of different types of RouteTaxi and subclasses.

Title: C++ Composition Constructor

Body:
So I've got a program with classes Car, Route and Taxi. I'm using composition in order to obtain the data from the classes Car and Route. Each class needs to be able to enter data on it's own and the data entered to be checked. I'm having difficulties with how to make the constructor of the Taxi class the way that he uses and checks the data with the get/set methods of the classes Car and Route.
How to access the parameters in the setRouteTaxidata method?

Any suggestions?

class RouteTaxi {
    private:
        int id;
    public:
        Car car;
        Route route;
        RouteTaxi();
        ~RouteTaxi();
        void setRouteTaxidata(string cbrand, string cmodel, int cyears, int cseatingCapacity, double cloadCapacity, double cfuelConsumption,string rnodes, double rrouteLength, int rtoursPerDay, int i);

};

RouteTaxi::RouteTaxi(){
    setRouteTaxidata(??)   ??????
}

void RouteTaxi::setRouteTaxidata(string cbrand, string cmodel, int cyears, int cseatingCapacity, double cloadCapacity, double cfuelConsumption, string rnodes, double rrouteLength, int rtoursPerDay, int i){
    car.setBrand(cbrand);

}

Body:
Your constructor RouteTaxi() is a default constructor. It must create a valid object without any of those, so you would have to have acceptable default values.

There's no good way to make a default route, unless you have a "nowhere" route with a "nocar" car, so you can instead require those arguments in the constructor, as in this example:

#include<string>
using std::string;

class Car {
public:
    Car(string cbrand, string cmodel, int cyears, int cseatingCapacity, double cloadCapacity, double cfuelConsumption){}
};

class Route {
public:
    Route(string rnodes, double rrouteLength, int rtoursPerDay){}
};

class RouteTaxi
{
private:
    int id;
public:
    Car car;
    Route route;
    RouteTaxi(string cbrand, string cmodel, int cyears, int
        cseatingCapacity, double cloadCapacity, double cfuelConsumption,
        string rnodes, double rrouteLength, int rtoursPerDay, int i)
        : car(cbrand, cmodel, cyears, cseatingCapacity, cloadCapacity, cfuelConsumption),
          route(rnodes, rrouteLength, rtoursPerDay),
          id(i)
    {}
    static RouteTaxi generate_from_console_input();
};

// this is a factory function (class static member of RouteTaxi)
RouteTaxi RouteTaxi::generate_from_console_input() {
    // input from console
    string cbrand, cmodel, rnodes;
    int cyears, cseatingCapacity, rtoursPerDay, i;
    double cloadCapacity, cfuelConsuption, rrouteLength;

    // return the object
    // this is an error, using uninitialized data, simply because I am not actually getting the data from the console. You will do that, so it will not be a problem.
    return RouteTaxi(cbrand, cmodel, cyears, cseatingCapacity, cloadCapacity, cfuelConsuption, rnodes, rrouteLength, rtoursPerDay, i);
}

Note the colon and initializer list which the constructor uses to initialize other objects before it executes its own constructor body. http://en.cppreference.com/w/cpp/language/initializer_list

The factory generator is another way to create objects. You need all the info before you call the actual constructor, so ... write a function which gets it, before you actually call the constructor.

This is a well known design pattern. See https://en.wikipedia.org/wiki/Creational_pattern. Although those go into a lot more detail. You are not dealing with a lot of different types of RouteTaxi and subclasses.


问:
Any good 2d engines with a GUI system?
I'm trying to develop a simple app ( it will resemble something like a powerpoint presentation) that will require some simple GUI controls: button, textbox, slider and listbox.

And i would want to be able to skin the controls.
So i'm looking for an easy to learn 2d engine that will aid me in doing what i want.

Any recommendation for such engine?

It can be in python or .net (xna) preferable or if not c/c++ will be ok i guess.

L.E.: I'm looking for a graphic rendering engine that has specified gui controls available.
For example Irrlicht.

答: Qt is a very nice cross-platform C++ library, it has three GPL, LPGP and commercial licenses also. </p>

OwnerDisplayName: daniels

Title: Any good 2d engines with a GUI system?

LastEditorDisplayName: daniels

OwnerDisplayName: michal


问:
Fast duplicates filtering in T-SQL procedure
I need to store some records in a table. It's crucial the records must be unique. All duplicates must be silently ignored.

I wrote a procedure which accepts a user-defined table type, I send a record collection to it, and I try to have NEW, UNIQUE records stored.

How do I determine unique? I calculate SHA1 from a couple of columns. In my table, I have a Hash column. It has UNIQUE index constraint.

Here comes the tricky part. Instead of using IF EXIST(SEELCT ..) I use TRY / CATCH blocks, I let the INSERT silently fail on duplicate hash.

So I use cursor to fetch my rows, then I calculate the hash for each row, then I try to insert this row. If it fails, the next row is processed.

It works. It's quite fast. However I'm very disappointed with my identity column.

If I try to enter 3 identical records and 1 new one I get following id-s: 1, 4. I would expect 1 and 2, not 1 and 4. So identity is incremented on each failed insert. I need to avoid it.

I tried to wrap the INSERT into TRANSACTION and ROLLBACK in the CATCH block. It does nothing. It works, just the id-s are wrong.

Is there a way to use UNIQUE constraint to filter the duplicates efficiently or the only way is using IF EXISTS method?

Is using UNIQUE constraint really faster than IF EXISTS?

UPDATE:
The typical scenario would look like 1000 duplicates and 2 new rows. There will be some concurrent calls to this procedure. I just don't want it to slow the server considerably when I'll have like a couple of millions of rows in my table.

答:
you can use SET IDENTITY INSERT and control that identity field till the end of insert:

```<code>SET IDENTITY INSERT ON
CURSOR --increasing also counter for identity column and setting it during loop
SET IDENTITY INSERT OFF
</code>```

By the way, are you sure you cannot avoid cursors?
You could use EXCEPT to get only the values that are not already existing and inserting them in only one statement, that would be definitely faster; just to give an idea:

```<code>INSERT INTO DestTable
SELECT * FROM (SELECT * FROM SourceTable
               EXCEPT
               SELECT * FROM DestTable)
</code>```

Body:
you can use SET IDENTITY INSERT and control that identity field till the end of insert:

SET IDENTITY INSERT ON
CURSOR --increasing also counter for identity column and setting it during loop
SET IDENTITY INSERT OFF

By the way, are you sure you cannot avoid cursors?
You could use EXCEPT to get only the values that are not already existing and inserting them in only one statement, that would be definitely faster; just to give an idea:

INSERT INTO DestTable
SELECT * FROM (SELECT * FROM SourceTable
               EXCEPT
               SELECT * FROM DestTable)


问:
Random Forest classifier class_weight
I have an unbalanced dataset of 200000 descriptions being class 0, and something like 10000 being class 1. However, in my training dataset I have equal number of 'positive' and 'negative' samples, about 8000 each. So now I am confused about how I should properly use the "class_weight" option of the classifier. It seems that it works only if the number of the 'positive' and 'negative' samples in the training data is the same as in the whole dataset. In this case it would be 8000 'positive' and 160000 of 'negative' ones, which is not really feasible. And reducing the number of the 'positive' samples doesn't seem to be a good idea either. Or am I wrong?</p>

答:
The class_weightoption does nothing more than increasing the weight of making an error with the under-represented class. In other words, misclassifying the rare class is punished harsher.

The classifier is likely to perform better on your test set (where both classes are represented equally, so both are equally important), but that is something you can easily verify yourself.

A side-effect is that predict_proba returns probabilities which are far away from the actual probabilities. (If you want to understand why, plot the simple average chance and the distribution of predicted scores without and with different class_weight=. How do the predicted scores shift?). Depending on your final use-case (classification, ranking, probability estimation) you should consider the choices in your model.

Title: Random Forest classifier class_weight


问:
key is undefined react
when I play this code in my localhost it tell me that "key is not defined"

```<code>import React from 'react';
import PropTypes from 'prop-types'

class LineTable extends React.Component{

supprimerLine = key => {
    const newLines = {...this.state.newLines};
    newLines[key] = null;
    this.setState({newLines})
};
render(){
return(
    <tr>
        <td>{this.props.details.colone1}</td>
        <td>{this.props.details.colone2}</td>
        <td>{this.props.details.colone3}</td>
        <td><button onClick={() => this.props.supprimerLine(key)}>
                                    supprimer</button></td>
    </tr>)};
static propTypes = {
    supprimerLine: PropTypes.func.isRequired};}
export default LineTable
</code>```

I think it is because I did not import the keys but I don't know how I can import it

答:
You have two point for correction.

supprimerLine is defined within the same class LineTable.

So,this.props.supprimerLine(key) is not right way to call it.It going  to throws an error.

The right way is this.supprimerLine(key) and

in the constructor add
this.supprimerLine = this.supprimerLine.bind(this);

You have not defined key in current context or anywhere in the class.You need to defined it first.

Title: key is undefined react

Body:
when I play this code in my localhost it tell me that "key is not defined"

import React from 'react';
import PropTypes from 'prop-types'

class LineTable extends React.Component{

supprimerLine = key => {
    const newLines = {...this.state.newLines};
    newLines[key] = null;
    this.setState({newLines})
};
render(){
return(

        {this.props.details.colone1}
        {this.props.details.colone2}
        {this.props.details.colone3}
        <button onClick={() => this.props.supprimerLine(key)}>
                                    supprimer</button>

)};
static propTypes = {
    supprimerLine: PropTypes.func.isRequired};}
export default LineTable

I think it is because I did not import the keys but I don't know how I can import it