问:
Cohort by Month and Location in SQL (SSMS)
I am trying to get a monthly cohort analysis from our database by month from 01/01/2015 to 01/01/2016. It needs to display it by month, by location. Here is what I have so far:

```<code>Select playsite_id, count([member_guid]) members,sum(TotalVisits) visitdiff
FROM
(SELECT playsite_id, member_guid,
         sum(case when [date_id] < 20150401
                     then 1
                     else null
                     end) as PreviousVisits,
       sum(case when [date_id] between 20150401 and 20150501
                     then 1
                     else null
                     end) as CohortVisits,
    sum(case when [date_id] between 20150401 and 20160401
                     then 1
                     else null
                     end) as TotalVisits  w
   FROM [Guest_Visit_Fact]
   where visit_type in ('WALK-IN NEW','WALK-IN REPEAT')
   group by playsite_id, [member_guid]) as innertable
where PreviousVisits is null and CohortVisits > 0
group by playsite_id
</code>```

This code is for just the month of April. We are wondering if there is a way to do it so we don't have to rewrite the code 12 times, one for each month. Maybe we're overthinking it, we've hit a wall. Here's what that code returns.
So it shows, between April 2015 and April 2016, how many first time visitors came, and how many of those returned.
Any help would be appreciated. We're close, yet far.

答:
Try this query

```<code>DECLARE @MonthStart INT, @YearStart INT ,@YearEnd INT
SET @MonthStart=4
SET @YearStart=2015
SET @YearEnd=2016
WHILE @MonthStart <= 12 -- condition of months
BEGIN
Select playsite_id, count([member_guid]) members,sum(TotalVisits) visitdiff
FROM
(SELECT playsite_id, member_guid,
         sum(case when MONTH([date_id]) <@MonthStart  AND YEAR([date_id])=@YearStart
                     then 1
                     else null
                     end) as PreviousVisits,
       sum(case when MONTH([date_id]) between @MonthStart and @MonthStart+1 and YEAR([date_id])= @YearStart
                     then 1
                     else null
                     end) as CohortVisits,
    sum(case when YEAR([date_id]) between @YearStart and @YearEnd AND MONTH([date_id]) = @MonthStart
                     then 1
                     else null
                     end) as TotalVisits  W
   FROM [Guest_Visit_Fact]
   where visit_type in ('WALK-IN NEW','WALK-IN REPEAT')
   group by playsite_id, [member_guid]) as innertable
where PreviousVisits is null and CohortVisits > 0
group by playsite_id
SET @MonthStart=@MonthStart+1
END
GO
</code>```

I hope you work

Body:
I am trying to get a monthly cohort analysis from our database by month from 01/01/2015 to 01/01/2016. It needs to display it by month, by location. Here is what I have so far:

Select playsite_id, count([member_guid]) members,sum(TotalVisits) visitdiff
FROM
(SELECT playsite_id, member_guid,
         sum(case when [date_id] < 20150401
                     then 1
                     else null
                     end) as PreviousVisits,
       sum(case when [date_id] between 20150401 and 20150501
                     then 1
                     else null
                     end) as CohortVisits,
    sum(case when [date_id] between 20150401 and 20160401
                     then 1
                     else null
                     end) as TotalVisits  w
   FROM [Guest_Visit_Fact]
   where visit_type in ('WALK-IN NEW','WALK-IN REPEAT')
   group by playsite_id, [member_guid]) as innertable
where PreviousVisits is null and CohortVisits > 0
group by playsite_id

This code is for just the month of April. We are wondering if there is a way to do it so we don't have to rewrite the code 12 times, one for each month. Maybe we're overthinking it, we've hit a wall. Here's what that code returns.
So it shows, between April 2015 and April 2016, how many first time visitors came, and how many of those returned.
Any help would be appreciated. We're close, yet far.

Body:
Try this query

DECLARE @MonthStart INT, @YearStart INT ,@YearEnd INT
SET @MonthStart=4
SET @YearStart=2015
SET @YearEnd=2016
WHILE @MonthStart <= 12 -- condition of months
BEGIN
Select playsite_id, count([member_guid]) members,sum(TotalVisits) visitdiff
FROM
(SELECT playsite_id, member_guid,
         sum(case when MONTH([date_id]) <@MonthStart  AND YEAR([date_id])=@YearStart
                     then 1
                     else null
                     end) as PreviousVisits,
       sum(case when MONTH([date_id]) between @MonthStart and @MonthStart+1 and YEAR([date_id])= @YearStart
                     then 1
                     else null
                     end) as CohortVisits,
    sum(case when YEAR([date_id]) between @YearStart and @YearEnd AND MONTH([date_id]) = @MonthStart
                     then 1
                     else null
                     end) as TotalVisits  W
   FROM [Guest_Visit_Fact]
   where visit_type in ('WALK-IN NEW','WALK-IN REPEAT')
   group by playsite_id, [member_guid]) as innertable
where PreviousVisits is null and CohortVisits > 0
group by playsite_id
SET @MonthStart=@MonthStart+1
END
GO

I hope you work


来源: stackexchange

问:
Angular HttpClient error handling
I am struggling a bit with how to execute code after an error happened in HttpClient. I would like to know how to set the flag that would turn off a loading spinner when the http called failed.
I am using RxJs 5.5.2 and Angular 5

```<code>  private fetch(): Observable<LegalTerm[]> {

    this.isLoading = true;
    return this._http
                .get<LegalTerm[]>(AppSettings.LegalTermUrl, { withCredentials: true })
                .do(() => this.isLoading = false)
                .catch<any, LegalTerm>(this._trace.handleError)
                .do(() => this.isLoading = false)
  }
</code>```

So in the happy path isLoading = false works but not sure how to do that after catch. It is not working the way the code is now. I am also using a custom error handler as per Angular docs

```<code>public handleError<T>(operation = 'operation', error: any, result?: T) {
   // do logging etc
   return Observable.of(result as T); // return empty result
}
</code>```

答:
You could use the finally operator to change the flag to false on complete/error events.

This could be done as follows:

```<code>import { BehaviorSubject }from 'rxjs/BehaviorSubject';
import 'rxjs/add/operator/finally';

@Component()
export class FooComponent {
  private loadingSub$ = new BehaviorSubeject<boolean>(false);
  loading$ = this.loadingSub$.asObservable();

  constructor(private fooService: FooService){
  }

  fetch(){
     this.loadingSub$.next(true);
     this.fooService.getData()
     // notice that getData() returns a stream that isnt infinite
     .finally(()=>this.loadingSub$.next(false))
     .subscribe(fooData => console.log(fooData)); // error handling not considered
   }
}

@Injectable()
export class FooService {
   constructor(private http: HttpClient){}

   getData(): Observable<any>{
      // error handling not considered
      return this.http.get('foourl');
   }
}
</code>```

More info about the operator can be found here

ContentLicense: CC BY-SA 3.0

Title: Angular HttpClient error handling

Body:
I am struggling a bit with how to execute code after an error happened in HttpClient. I would like to know how to set the flag that would turn off a loading spinner when the http called failed.
I am using RxJs 5.5.2 and Angular 5

  private fetch(): Observable<LegalTerm[]> {

    this.isLoading = true;
    return this._http
                .get<LegalTerm[]>(AppSettings.LegalTermUrl, { withCredentials: true })
                .do(() => this.isLoading = false)
                .catch<any, LegalTerm>(this._trace.handleError)
                .do(() => this.isLoading = false)
  }

So in the happy path isLoading = false works but not sure how to do that after catch. It is not working the way the code is now. I am also using a custom error handler as per Angular docs

public handleError<T>(operation = 'operation', error: any, result?: T) {
   // do logging etc
   return Observable.of(result as T); // return empty result
}

Body:
You could use the finally operator to change the flag to false on complete/error events.

This could be done as follows:

import { BehaviorSubject }from 'rxjs/BehaviorSubject';
import 'rxjs/add/operator/finally';

@Component()
export class FooComponent {
  private loadingSub$ = new BehaviorSubeject<boolean>(false);
  loading$ = this.loadingSub$.asObservable();

  constructor(private fooService: FooService){
  }

  fetch(){
     this.loadingSub$.next(true);
     this.fooService.getData()
     // notice that getData() returns a stream that isnt infinite
     .finally(()=>this.loadingSub$.next(false))
     .subscribe(fooData => console.log(fooData)); // error handling not considered
   }
}

@Injectable()
export class FooService {
   constructor(private http: HttpClient){}

   getData(): Observable<any>{
      // error handling not considered
      return this.http.get('foourl');
   }
}

More info about the operator can be found here


问:
MYSQL Foreign Key Set
Abstract: Table A has a row which contains a list of Integers that reference IDs in Table B.

Why not just create a column in table B that references Table A? Because the items in Table B are reusable, and apply to many rows in table A.

Specific example: An educational software, which consists of lessons and line items. Each lesson incorporates many line items, and each line item is used in many lessons.

This many-to-many linking is a common task and I have probably been doing it wrong forever. The easiest way I have done it in the past is to have Table A contain a varchar with a delimited list, interpret that list in code and then run another query to get the needed information from table B.

Is there more elegant way? Some way of combining the functionality of SET data type with Foreign Keys index?

答:
What you need is accomplished with a relationship table.

A is one to one with B

A or B should contain the id of the other.

A is one to many with B

B should contain the id of A.

A is many to many with B

Create a relationship table AB that holds ids for both A and B.

These are standard patterns.

Title: MYSQL Foreign Key Set


问:
Laravel installer v1.4.1 not compatible with PHP 7.1 packages?
I can't install 'laravel 5.5' on fresh 'Pop!_OS' (based on Ubuntu 17.10 by system76) linux instalation.

Can't find how to 'remove symfony/console v4.0.1'.
So can anyone help me solve this annoyance?

I followed https://www.youtube.com/watch?v=b38mUODC1l4 this tutorial and everything went perfect till composer global require "laravel/installer" command.

After entering this command the result in terminal is:

```<code>    Changed current directory to /home/chakra/.config/composer
Using version ^1.4 for laravel/installer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Conclusion: don't install laravel/installer v1.4.1
    - Conclusion: remove symfony/console v4.0.1
    - Installation request for laravel/installer ^1.4 -> satisfiable by laravel/installer[v1.4.0, v1.4.1].
    - Conclusion: don't install symfony/console v4.0.1
    - laravel/installer v1.4.0 requires symfony/console ~2.3|~3.0 -> satisfiable by symfony/console[v2.3.0, ..., v3.4.1].
    - Can only install one of: symfony/console[v3.0.0, v4.0.1].
    ...
    - Can only install one of: symfony/console[v2.8.9, v4.0.1].
    - Installation request for symfony/console (locked at v4.0.1) -> satisfiable by symfony/console[v4.0.1].

Installation failed, reverting ./composer.json to its original content.
➜  Sites
</code>```

composer.json  /home/chakra/.config/composer (everything is default haven't changed anything like in video tutorial)

After sudo nano composer.json:

```<code>{
    "require": {
        "cpriego/valet-linux": "^2.0"
        }
}
</code>```

Composer, npm, nginx version:

```<code>➜  ~ which composer
/usr/local/bin/composer
➜  ~ composer --version
Composer version 1.5.5 2017-12-01 14:42:57
➜  ~ npm --version
5.5.1
➜  ~ nginx -v
nginx version: nginx/1.12.1 (Ubuntu)
➜  ~
</code>```

答:
So with the help of Nico Haase I've figured it out.

And the solution for the problem is:

composer global remove cpriego/valet-linux (this will also remove troublesome symfony/console v4.0.1) after removing this install laravel:

composer global require "laravel/installer" (it installed all required packages without any errors) after this reinstall 'Valet Linux'

composer global require cpriego/valet-linux

Now everything works as it should. I can create laravel application by laravel new application and also valet works as it should. :)

Body:
I can't install 'laravel 5.5' on fresh 'Pop!_OS' (based on Ubuntu 17.10 by system76) linux instalation.

Can't find how to 'remove symfony/console v4.0.1'.
So can anyone help me solve this annoyance?

I followed https://www.youtube.com/watch?v=b38mUODC1l4 this tutorial and everything went perfect till composer global require "laravel/installer" command.

After entering this command the result in terminal is:

    Changed current directory to /home/chakra/.config/composer
Using version ^1.4 for laravel/installer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Conclusion: don't install laravel/installer v1.4.1
    - Conclusion: remove symfony/console v4.0.1
    - Installation request for laravel/installer ^1.4 -> satisfiable by laravel/installer[v1.4.0, v1.4.1].
    - Conclusion: don't install symfony/console v4.0.1
    - laravel/installer v1.4.0 requires symfony/console ~2.3|~3.0 -> satisfiable by symfony/console[v2.3.0, ..., v3.4.1].
    - Can only install one of: symfony/console[v3.0.0, v4.0.1].
    ...
    - Can only install one of: symfony/console[v2.8.9, v4.0.1].
    - Installation request for symfony/console (locked at v4.0.1) -> satisfiable by symfony/console[v4.0.1].

Installation failed, reverting ./composer.json to its original content.
➜  Sites

composer.json  /home/chakra/.config/composer (everything is default haven't changed anything like in video tutorial)

After sudo nano composer.json:

{
    "require": {
        "cpriego/valet-linux": "^2.0"
        }
}

Composer, npm, nginx version:

➜  ~ which composer
/usr/local/bin/composer
➜  ~ composer --version
Composer version 1.5.5 2017-12-01 14:42:57
➜  ~ npm --version
5.5.1
➜  ~ nginx -v
nginx version: nginx/1.12.1 (Ubuntu)
➜  ~


问:
How to make only part of Ember route model a promise?
I have a simple template.hbs like this:

```<code>// template.hbs

<p>{{model.x}}</p>
<p>{{model.y}}</p>
</code>```

The following route.js works as expected:

```<code>// route.js

import Route from '@ember/routing/route';

export default Route.extend({

    model() {

        return {
            x: 'foo',
            y: 'bar'
        };

    }
});

// output, immediately:
// foo
// bar
</code>```

The following also works, now using a promise for the whole model:

```<code>// route.js

import Route from '@ember/routing/route';
import RSVP from 'rsvp';

export default Route.extend({

    model() {

        return new RSVP.Promise((resolve) => {
            setTimeout(() => {
                resolve({
                    x: 'foo',
                    y: 'bar'
                });
            }, 1000);
        });

    }
});

// output, after 1s:
// foo
// bar
</code>```

The following, where I want to make only model.x a promise - does NOT work.

```<code>// route.js

import Route from '@ember/routing/route';
import RSVP from 'rsvp';

export default Route.extend({

    model() {

        return {
            x: new RSVP.Promise((resolve) => {
                setTimeout(() => {
                    resolve('foo');
                }, 1000);
            }),
            y: 'bar'
        };

    }
});

// output, IMMEDIATELY:
// [object Object]
// bar
</code>```

It renders output immediately, but after it enters the callback in setTimeout it doesn't change the rendered value for model.x.

I am aware of RSVP.hash(), but that will reject if any of the promises rejects. Is it possible to have independent promises for different parts of route model or only all-or-nothing?

Oddly enough, if the promise in question is returned by ember-data, e.g. x: this.get('store').findRecord('user'), it works as it should work (changing template.hbs with
{{model.x.name}}
 for instance).

答:
In the last case,

model.x is Promise object, if you do {{log model.x}} in hbs, you can see it in console. You can try access the value using {{model.x._result}}. but this is not right way to do it.

In your case, you can try implementing setupController hook of the route,

```<code>setupController(controller,model)
  {
    this._super(...arguments);
    let xPromise = new RSVP.Promise((resolve) => {
                setTimeout(() => {
                    resolve('foo');
                }, 1000);
            });
    xPromise.then((result) =>{
      this.set('model.x',result);
    });

  }
</code>```

Body:
I have a simple template.hbs like this:

// template.hbs

{{model.x}}

{{model.y}}

The following route.js works as expected:

// route.js

import Route from '@ember/routing/route';

export default Route.extend({

    model() {

        return {
            x: 'foo',
            y: 'bar'
        };

    }
});

// output, immediately:
// foo
// bar

The following also works, now using a promise for the whole model:

// route.js

import Route from '@ember/routing/route';
import RSVP from 'rsvp';

export default Route.extend({

    model() {

        return new RSVP.Promise((resolve) => {
            setTimeout(() => {
                resolve({
                    x: 'foo',
                    y: 'bar'
                });
            }, 1000);
        });

    }
});

// output, after 1s:
// foo
// bar

The following, where I want to make only model.x a promise - does NOT work.

// route.js

import Route from '@ember/routing/route';
import RSVP from 'rsvp';

export default Route.extend({

    model() {

        return {
            x: new RSVP.Promise((resolve) => {
                setTimeout(() => {
                    resolve('foo');
                }, 1000);
            }),
            y: 'bar'
        };

    }
});

// output, IMMEDIATELY:
// [object Object]
// bar

It renders output immediately, but after it enters the callback in setTimeout it doesn't change the rendered value for model.x.

I am aware of RSVP.hash(), but that will reject if any of the promises rejects. Is it possible to have independent promises for different parts of route model or only all-or-nothing?

Oddly enough, if the promise in question is returned by ember-data, e.g. x: this.get('store').findRecord('user'), it works as it should work (changing template.hbs with
{{model.x.name}}
 for instance).

Body:
In the last case,

model.x is Promise object, if you do {{log model.x}} in hbs, you can see it in console. You can try access the value using {{model.x._result}}. but this is not right way to do it.

In your case, you can try implementing setupController hook of the route,

setupController(controller,model)
  {
    this._super(...arguments);
    let xPromise = new RSVP.Promise((resolve) => {
                setTimeout(() => {
                    resolve('foo');
                }, 1000);
            });
    xPromise.then((result) =>{
      this.set('model.x',result);
    });

  }


问:
Alfresco SDK Custom REST API without WebScripts
It's possible to expose custom REST services in Alfresco SDK AMP without Alfresco WebScripts but using other methods like Jersey (JAX-RS) or Spring REST Controllers since it has Spring framework support ?

答:
Never done it, but I think that you can.

Given that Alfresco is a Spring application, you can create your beans using a framework integrated with Spring and inject the Alfresco services as dependencies.

With these dependencies, you can access the Alfresco repository.

I do not know how easy it would be to reuse the authentication that is free for webscripts.


问:
Can't access data from user Defaults in the lifecycle of the app
In my app I have saved data in userDefaults and when I try to update the data with the same key it does get updated but only if I close the app and relaunch the simulator. Else if I want to access it right away(it other view Controller) it doesn't give me the the updated object but it gives me the last data that I saved with that key.
I update the data in one view controller in override func viewWillDisappear(_ animated : ) and try to access it in the parent view controller.

Here is how I do that:

```<code>override func viewWillDisappear(_ animated : Bool) {
    super.viewWillDisappear(animated)
    if self.isMovingFromParentViewController {
        if saveButtonPressed != true {
            // here I don't need to execute code the back button is pressed
        } else {
            if let selection = selectedMinutes {
                UserDefaults.standard.set(selection, forKey: "selectedRow")
                print(UserDefaults.standard.object(forKey: "selectedRow")!) // this line prints the actual updated data but I still cannot get it in the parent view controller
            }
        }
    }
}
</code>```

答:
You should call synchronize UserDefaults after set data</p>

```<code>UserDefaults.standard.set(selection, forKey: "selectedRow")
UserDefaults.standard.synchronize();
</code>```

Body:
In my app I have saved data in userDefaults and when I try to update the data with the same key it does get updated but only if I close the app and relaunch the simulator. Else if I want to access it right away(it other view Controller) it doesn't give me the the updated object but it gives me the last data that I saved with that key.
I update the data in one view controller in override func viewWillDisappear(_ animated : ) and try to access it in the parent view controller.

Here is how I do that:

override func viewWillDisappear(_ animated : Bool) {
    super.viewWillDisappear(animated)
    if self.isMovingFromParentViewController {
        if saveButtonPressed != true {
            // here I don't need to execute code the back button is pressed
        } else {
            if let selection = selectedMinutes {
                UserDefaults.standard.set(selection, forKey: "selectedRow")
                print(UserDefaults.standard.object(forKey: "selectedRow")!) // this line prints the actual updated data but I still cannot get it in the parent view controller
            }
        }
    }
}

Body:
You should call synchronize UserDefaults after set data

UserDefaults.standard.set(selection, forKey: "selectedRow")
UserDefaults.standard.synchronize();


问:
How to dynamically remove a input form created in html using javascript
I'm currently stuck and I don't know what to do. The solution may be simple but since I'm new to the JavaScript environment I am kind of lost.

I created a check option that when pressed, it generates a input form to be filled with a "Add new" button to generate another input form.

In my code, when the button "Add new" is pressed, it already creates a dynamic input form with a "Delete" button BUT, I can't seem to make this "delete" ban work when pressed.

All help is welcome. I am using html with JavaScript. Ultimately I'll be saving these form values in a sql database using pup as my middle man.

PS: I am working on WordPress as the web development since the page is already created in it and Yes, I know that I should be using JavaScript and CSS apart from the main html page.

Here's the code I have so far:

```<code>    <!DOCTYPE html>
<html>
<style type="text/css">
  label{
    float:left;
    width: 10em;
    text-align: right;
    margin-right: 10px;
  }
</style>

<script type="text\javascript">
  function checkform(form) {
    // get all the inputs within the submitted form
    var inputs = form.getElementsByTagName('input');
    for (var i = 0; i < inputs.length; i++) {
        // only validate the inputs that have the required attribute
        if(inputs[i].hasAttribute("required")){
            if(inputs[i].value == ""){
                // found an empty field that is required
                alert("Please fill all required fields");
                return false;
            }
        }
    }
    return true;
}
</script>

<script type="text/javascript">

//This function adds another form input when button "Add" is pressed
  var counter = 1;
var limit = 5;
function addInput(divName){
     if (counter == limit)  {
          alert("You have reached the limit of adding " + counter + " Co-PI or Co-Investigators");
     }
     else {
          var divName = divName;
          var newDivName = (divName + counter);
          var newdiv = document.createElement('div');
          newdiv.id = "dynamicInput" + counter;
          newdiv.innerHTML = (counter + 1) + ". Co-PI or Co-Investigator Information: <br>" +
          "<label>First Name  : </label><input type='text' name='fname[]' maxlength='35' required><br> " +
           "<label>Last Name  : </label><input type='text' name='lname[]' maxlength='35'><br> " +
           "<label>Degree  : </label><input type='text' name='degree[]' maxlength='10'><br> " +
           "<label>Current Position  : </label><input type='text' name='cPos[]' maxlength='30'><br> " +
           "<label>Institution  : </label><input type='text' name='inst[]' maxlength='40'><br> " +
           "<label>School  : </label><input type='text' name='school[]' maxlength='40'><br> " +
           "<label>Department  : </label><input type='text' name='depart[]' maxlength='40'><br> " +
           "<label>Program  : </label><input type='text' name='program[]' maxlength='40'><br> " +
           "<label>Email  : </label><input type='text' name='email[]' maxlength='255'><br> " +
           "<label>Phone (xxx-xxx-xxxx)  : </label><input type='text' name='phone[]' maxlength='10'> <br><br>"  +
           "<input type='button' value='Delete Previous Form' onClick='removeForm(divName, newDivName);'>  ";

          document.getElementById(divName).appendChild(newdiv);
          counter++;
     }
}

//Delete div form when delete button is pressed
function removeForm(parentDiv, childDiv){
    if(childDiv == parentDiv)
    {
        alert("Cannot delete anymore form entries!");
    }

    else if (document.getElementById(childDiv))
    {
        var child = document.getElementById(childDiv);
        var parent = document.getElementById(parentDiv)
        parent.removeChild(child);
        counter--;
    }

    else
    {
        alert("Form has been removed or does not exist.");
        return false;
    }
}
</script>

<script type="text/javascript">
function aff_div(ladiv) {
  document.getElementById(ladiv).style.display = "inline";
}

function cach_div(ladiv) {
  document.getElementById(ladiv).style.display = "none";
}

function affich_conj() {
  if (document.forms.CoPI_CoInv_Info.yesNoChkbox[0].checked == true) {
    aff_div("dynamicInput");
    aff_divBtn("btn_New_CoPI_Inv");
  }

  if (document.forms.CoPI_CoInv_Info.yesNoChkbox[1].checked == true) {
    cach_div("dynamicInput");
    cach_divBtn("btn_New_CoPI_Inv");
  }
}

function aff_divBtn(BtnDiv) {
  document.getElementById(BtnDiv).style.display = "inline";
}

function cach_divBtn(BtnDiv) {
  document.getElementById(BtnDiv).style.display = "none";
}

</script>

<form id="CoPI_CoInv_Info" onsubmit="return checkform(this)">

<label1>Do you want to add a Co-PI or Co-Investigator? </label1>
  <input type="radio" name="yesNoChkbox" value="yes" onclick="affich_conj();"> yes
  <input type="radio" name="yesNoChkbox" value="no" checked="checked" onclick="affich_conj();"> no
<br><br>

  <div id="dynamicInput">
                 1. Co-PI or Co-Investigator Information: <br>
       <label>First Name  : </label><input type="text" name="fname[]" maxlength="35" required><br>
       <label>Last Name  : </label><input type="text" name="lname[]" maxlength="35"><br>
       <label>Degree  : </label><input type="text" name="degree[]" maxlength="10"><br>
       <label>Current Position  : </label><input type="text" name="cPos[]" maxlength="30"><br>
       <label>Institution  : </label><input type="text" name="inst[]" maxlength="40"><br>
       <label>School  : </label><input type="text" name="school[]" maxlength="40"><br>
       <label>Department  : </label><input type="text" name="depart[]" maxlength="40"><br>
       <label>Program  : </label><input type="text" name="program[]" maxlength="40"><br>
       <label>Email  : </label><input type="text" name="email[]" maxlength="255"><br>
       <label>Phone (xxx-xxx-xxxx)  : </label><input type="text" name="phone[]" maxlength="10"> <br><br>

     </div>
<divBtn id="btn_New_CoPI_Inv">
<input type="button" value="Add New Co-PI or Co-Investigator..." onClick="addInput('dynamicInput');">

</divBtn>
</form>

<script type="text/javascript">
  cach_div("dynamicInput");
  cach_divBtn("btn_New_CoPI_Inv");
</script>
</html>
</code>```

答:
You need to quote and escape the variables within the string ~ look at the inline event handler.

```<code>  var divName = divName;
  var newDivName = (divName + counter);
  var newdiv = document.createElement('div');
  newdiv.id = "dynamicInput" + counter;
  newdiv.innerHTML = (counter + 1) + ". Co-PI or Co-Investigator Information: <br>" +
  "<label>First Name  : </label><input type='text' name='fname[]' maxlength='35' required><br> " +
   "<label>Last Name  : </label><input type='text' name='lname[]' maxlength='35'><br> " +
   "<label>Degree  : </label><input type='text' name='degree[]' maxlength='10'><br> " +
   "<label>Current Position  : </label><input type='text' name='cPos[]' maxlength='30'><br> " +
   "<label>Institution  : </label><input type='text' name='inst[]' maxlength='40'><br> " +
   "<label>School  : </label><input type='text' name='school[]' maxlength='40'><br> " +
   "<label>Department  : </label><input type='text' name='depart[]' maxlength='40'><br> " +
   "<label>Program  : </label><input type='text' name='program[]' maxlength='40'><br> " +
   "<label>Email  : </label><input type='text' name='email[]' maxlength='255'><br> " +
   "<label>Phone (xxx-xxx-xxxx)  : </label><input type='text' name='phone[]' maxlength='10'> <br><br>"  +
   "<input type='button' value='Delete Previous Form' onClick='removeForm(\""+divName+"\", \""+newDivName+"\");'>  ";
</code>```

The removeForm function could be simplified if you were to use the parentNode selector as it appears the button is a direct child of the div you create so potentially you could do:

```<code>function removeForm(e){
    e.target.parentNode.parentNode.removeChild( e.target.parentNode );
}
</code>```

and call it in the HTML using

```<code>    <input type='button' value='Delete Previous Form' onClick='removeForm(event);'>
</code>```

Body:
I'm currently stuck and I don't know what to do. The solution may be simple but since I'm new to the JavaScript environment I am kind of lost.

I created a check option that when pressed, it generates a input form to be filled with a "Add new" button to generate another input form.

In my code, when the button "Add new" is pressed, it already creates a dynamic input form with a "Delete" button BUT, I can't seem to make this "delete" ban work when pressed.

All help is welcome. I am using html with JavaScript. Ultimately I'll be saving these form values in a sql database using pup as my middle man.

PS: I am working on WordPress as the web development since the page is already created in it and Yes, I know that I should be using JavaScript and CSS apart from the main html page.

Here's the code I have so far:

    <!DOCTYPE html>

<form id="CoPI_CoInv_Info" onsubmit="return checkform(this)">

<label1>Do you want to add a Co-PI or Co-Investigator? </label1>
  <input type="radio" name="yesNoChkbox" value="yes" onclick="affich_conj();"> yes
  <input type="radio" name="yesNoChkbox" value="no" checked="checked" onclick="affich_conj();"> no

                 1. Co-PI or Co-Investigator Information:

       First Name  : <input type="text" name="fname[]" maxlength="35" required>

       Last Name  : <input type="text" name="lname[]" maxlength="35">

       Degree  : <input type="text" name="degree[]" maxlength="10">

       Current Position  : <input type="text" name="cPos[]" maxlength="30">

       Institution  : <input type="text" name="inst[]" maxlength="40">

       School  : <input type="text" name="school[]" maxlength="40">

       Department  : <input type="text" name="depart[]" maxlength="40">

       Program  : <input type="text" name="program[]" maxlength="40">

       Email  : <input type="text" name="email[]" maxlength="255">

       Phone (xxx-xxx-xxxx)  : <input type="text" name="phone[]" maxlength="10">

<divBtn id="btn_New_CoPI_Inv">
<input type="button" value="Add New Co-PI or Co-Investigator..." onClick="addInput('dynamicInput');">

</divBtn>
</form>

Body:
You need to quote and escape the variables within the string ~ look at the inline event handler.

  var divName = divName;
  var newDivName = (divName + counter);
  var newdiv = document.createElement('div');
  newdiv.id = "dynamicInput" + counter;
  newdiv.innerHTML = (counter + 1) + ". Co-PI or Co-Investigator Information: <br>" +
  "<label>First Name  : </label><input type='text' name='fname[]' maxlength='35' required><br> " +
   "<label>Last Name  : </label><input type='text' name='lname[]' maxlength='35'><br> " +
   "<label>Degree  : </label><input type='text' name='degree[]' maxlength='10'><br> " +
   "<label>Current Position  : </label><input type='text' name='cPos[]' maxlength='30'><br> " +
   "<label>Institution  : </label><input type='text' name='inst[]' maxlength='40'><br> " +
   "<label>School  : </label><input type='text' name='school[]' maxlength='40'><br> " +
   "<label>Department  : </label><input type='text' name='depart[]' maxlength='40'><br> " +
   "<label>Program  : </label><input type='text' name='program[]' maxlength='40'><br> " +
   "<label>Email  : </label><input type='text' name='email[]' maxlength='255'><br> " +
   "<label>Phone (xxx-xxx-xxxx)  : </label><input type='text' name='phone[]' maxlength='10'> <br><br>"  +
   "<input type='button' value='Delete Previous Form' onClick='removeForm(\""+divName+"\", \""+newDivName+"\");'>  ";

The removeForm function could be simplified if you were to use the parentNode selector as it appears the button is a direct child of the div you create so potentially you could do:

function removeForm(e){
    e.target.parentNode.parentNode.removeChild( e.target.parentNode );
}

and call it in the HTML using

    <input type='button' value='Delete Previous Form' onClick='removeForm(event);'>


问:
Initializing array inside struct
I'm trying to initialize an array inside a struct, Like this.

I want the array to have the size of row*col.

Here is part of the code:

```<code>struct tbl{
    int col;
    int row;
    char** elem [col*row];
};

int main(int argc, char** argv){

    int i, row, col;
    col = row = 0;
    bool loop = true;
    char c;
    col = col/row;

    table tab;
    tab.row = row;
    tab.col = col;

    return 0;
}
</code>```

答:
Please not that

You cannot preset the values of row col in your code.

To acheive this you need dynamic allocation like this,

```<code>struct matrix {
    int row_count;
    int col_count;
    int **values;
};

void free_matrix(struct matrix *const M);
int initialize_matrix(struct matrix *const M, int row_count, int col_count);

int initialize_matrix(struct matrix *const M, int row_count, int col_count)
{
    M->values = malloc(sizeof *M->values * row_count);
    if (M->values == NULL)
        return -1;
    M->row_count = 0;
    for (int row = 0; row < row_count; ++row) {
        M->values[row] = malloc(sizeof **M->values * col_count);
        // In case of failure to allocate
        // free all rows.
        if (M->values[row] == NULL) {
            free_matrix(M);
        } else {
            M->row_count += 1;
        }
    }
    M->col_count = col_count;
}

void free_matrix(struct matrix *const M)
{
    if (M == NULL)
        return;
    for (int row = 0; row < M->row_count; ++row) {
        free(M->values[row]);
    }
    free(M->values);
}

int main(void)
{
    struct matrix M;
    initialize_matrix(&M);
    // Use the matrix here
    free_matrix(&M);
}
</code>```

You should be extremely careful with the use of malloc() and free(), you must use it correctly or unexpected things will happen to your program.

Title: Initializing array inside struct

Body:
I'm trying to initialize an array inside a struct, Like this.

I want the array to have the size of row*col.

Here is part of the code:

struct tbl{
    int col;
    int row;
    char** elem [col*row];
};

int main(int argc, char** argv){

    int i, row, col;
    col = row = 0;
    bool loop = true;
    char c;
    col = col/row;

    table tab;
    tab.row = row;
    tab.col = col;

    return 0;
}

Body:
Please not that

You cannot preset the values of row col in your code.

To acheive this you need dynamic allocation like this,

struct matrix {
    int row_count;
    int col_count;
    int **values;
};

void free_matrix(struct matrix *const M);
int initialize_matrix(struct matrix *const M, int row_count, int col_count);

int initialize_matrix(struct matrix *const M, int row_count, int col_count)
{
    M->values = malloc(sizeof *M->values * row_count);
    if (M->values == NULL)
        return -1;
    M->row_count = 0;
    for (int row = 0; row < row_count; ++row) {
        M->values[row] = malloc(sizeof **M->values * col_count);
        // In case of failure to allocate
        // free all rows.
        if (M->values[row] == NULL) {
            free_matrix(M);
        } else {
            M->row_count += 1;
        }
    }
    M->col_count = col_count;
}

void free_matrix(struct matrix *const M)
{
    if (M == NULL)
        return;
    for (int row = 0; row < M->row_count; ++row) {
        free(M->values[row]);
    }
    free(M->values);
}

int main(void)
{
    struct matrix M;
    initialize_matrix(&M);
    // Use the matrix here
    free_matrix(&M);
}

You should be extremely careful with the use of malloc() and free(), you must use it correctly or unexpected things will happen to your program.


问:
Convert String to Double - JAVA
```<code>private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:

        //9

        txtTot.setText(jComboBox1.getSelectedItem().toString());
        tot= Double.parseDouble(txtTot.getText());
        CMB= (Double)jComboBox1.getSelectedItem();
        Total2=tot+CMB;
        txtTot.setText(Double.toString(Total2));

    }
</code>```

From the ComboBox I'm setting the jtextfield and the second line I'm taking the string from the textfield and trying to convert it into a double.

Error below:

```<code>Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
    at test.Test.jComboBox1ActionPerformed(Test.java:392)
    at test.Test.access$600(Test.java:18)
    at test.Test$7.actionPerformed(Test.java:134)
    at javax.swing.JComboBox.fireActionEvent(JComboBox.java:1258)
    at javax.swing.JComboBox.setSelectedItem(JComboBox.java:586)
    at javax.swing.JComboBox.setSelectedIndex(JComboBox.java:622)
</code>```

答: Try to print the txtTot.getText () to the console and check whether it is in proper decimal format. Incorrect format could be the cause of error.</p>

Title: Convert String to Double - JAVA

Body:
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:

        //9

        txtTot.setText(jComboBox1.getSelectedItem().toString());
        tot= Double.parseDouble(txtTot.getText());
        CMB= (Double)jComboBox1.getSelectedItem();
        Total2=tot+CMB;
        txtTot.setText(Double.toString(Total2));

    }

From the ComboBox I'm setting the jtextfield and the second line I'm taking the string from the textfield and trying to convert it into a double.

Error below:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
    at test.Test.jComboBox1ActionPerformed(Test.java:392)
    at test.Test.access$600(Test.java:18)
    at test.Test$7.actionPerformed(Test.java:134)
    at javax.swing.JComboBox.fireActionEvent(JComboBox.java:1258)
    at javax.swing.JComboBox.setSelectedItem(JComboBox.java:586)
    at javax.swing.JComboBox.setSelectedIndex(JComboBox.java:622)


问:
How to remove the coulmn name in Json in c#
For example this is my JSON:

```<code>[
   {
      "id":1,
      "name":"Core"
   },
   {
      "id":2,
      "name":"Moderate"
   },
   {
      "id":3,
      "name":"Remote"
   }
]
</code>```

How can I remove id and name?

My desired output:

```<code>[
  {
    "1":"Core"
  },
  {
    "2":"Moderate"
  },
  {
    "3":"Remote"
  }
]
</code>```

答:
You could deserialize your json string to an object (MyType) and override the ToString() method</p>

```<code>public void YourMethod(){
   string json = ...; // your json string
   List<MyType> myType = JsonConvert.DeserializeObject<List<MyType>>(json);
   var output = string.Join(", ", myType);
}

public class MyType
{
    public int Id
    {
        get;
        set;
    }

    public string Name{
        get;
        set;
    }

    public override string ToString()
    {
        return string.Format("{0}:{1}", Id.ToString(), Name);
    }
}
</code>```

Body:
For example this is my JSON:

[
   {
      "id":1,
      "name":"Core"
   },
   {
      "id":2,
      "name":"Moderate"
   },
   {
      "id":3,
      "name":"Remote"
   }
]

How can I remove id and name?

My desired output:

[
  {
    "1":"Core"
  },
  {
    "2":"Moderate"
  },
  {
    "3":"Remote"
  }
]

Body:
You could deserialize your json string to an object (MyType) and override the ToString() method

public void YourMethod(){
   string json = ...; // your json string
   List<MyType> myType = JsonConvert.DeserializeObject<List<MyType>>(json);
   var output = string.Join(", ", myType);
}

public class MyType
{
    public int Id
    {
        get;
        set;
    }

    public string Name{
        get;
        set;
    }

    public override string ToString()
    {
        return string.Format("{0}:{1}", Id.ToString(), Name);
    }
}


问:
Remove underline in nested element whose parent element is underlined?

Click Me?
```
</div>
</div>
</p>

<p>I'm trying to nest an element in an element that has an underline property but remove that property for the nested element. It's not working, the <code>?</code> remains underlined in this scenario and adding <code>!important</code> does not help.</p>

<p>Edit: The actual elements are in an abbreviation:</p>

```

  Actions?

```

So I can't have sup be outside of th as it is invalid in tr.

答:
The child elements style won't change the parent element's.

You could do something like this:

```<code><p>
    <span class="underline">Click Me</span>
    <span>?</span>
</p>
</code>```

Body:
Click Me?

I'm trying to nest an element in an element that has an underline property but remove that property for the nested element. It's not working, the ? remains underlined in this scenario and adding !important does not help.

Edit: The actual elements are in an abbreviation:

  Actions?

So I can't have sup be outside of th as it is invalid in tr.

Body:
The child elements style won't change the parent element's.

You could do something like this:

<p>
    <span class="underline">Click Me</span>
    <span>?</span>
</p>


问:
How to plot a line between two points in a scatter3 plot in MATLAB?
I am using the following code for producing a scatter3 plot:

```<code>X = [1,2,3,1,2,3,1,2,3,1,2,3,1,2,3];
Y = [0,0,0,20,20,20,40,40,40,60,60,60,80,80,80,];
Z1 = [10,-48.7863,-73.3457, -68.3091, -142.0666,...
      12, -35.7863, -23.347, -29.3091,-141.0660,...
      13,3.2137,-10.3457,-33.3091,-128.0666]
Z2 = [2,8.2137,-2.3457, 46.6909, 12.9334,...
      10,11.2137, 19.6543,35.6909, 45.9334,...
       -1,16.2137,37.6543,50.6909,34.9334]

figure;scatter3(X,Y,Z1,'filled'); hold on;
scatter3(X,Y,Z2,'filled')
</code>```

Which results in the following image:

What I would like to have is a vertical line between each blue and red dot.

An exemplary output could look like this:

I tried using the line function, however I am not sure how to build up the vector.

I tried:

```<code>line(X,Y,Z1) % will only connect the blue dots
line(X,Y,Z2) % will only connect the red dots

line(X,Y,Z1:Z2) % will give an error that the vectors must be the same length
</code>```

答:
You must vertically concatenate your Z1 and Z2 data so that each column defines a line to plot. You will also have to replicate X and Y in the same way:

```<code>line([X; X], [Y; Y], [Z1; Z2], 'Color', 'r');
</code>```

And the result (added to your scatter plot):

Body:
I am using the following code for producing a scatter3 plot:

X = [1,2,3,1,2,3,1,2,3,1,2,3,1,2,3];
Y = [0,0,0,20,20,20,40,40,40,60,60,60,80,80,80,];
Z1 = [10,-48.7863,-73.3457, -68.3091, -142.0666,...
      12, -35.7863, -23.347, -29.3091,-141.0660,...
      13,3.2137,-10.3457,-33.3091,-128.0666]
Z2 = [2,8.2137,-2.3457, 46.6909, 12.9334,...
      10,11.2137, 19.6543,35.6909, 45.9334,...
       -1,16.2137,37.6543,50.6909,34.9334]

figure;scatter3(X,Y,Z1,'filled'); hold on;
scatter3(X,Y,Z2,'filled')

Which results in the following image:

What I would like to have is a vertical line between each blue and red dot.

An exemplary output could look like this:

I tried using the line function, however I am not sure how to build up the vector.

I tried:

line(X,Y,Z1) % will only connect the blue dots
line(X,Y,Z2) % will only connect the red dots

line(X,Y,Z1:Z2) % will give an error that the vectors must be the same length

Body:
You must vertically concatenate your Z1 and Z2 data so that each column defines a line to plot. You will also have to replicate X and Y in the same way:

line([X; X], [Y; Y], [Z1; Z2], 'Color', 'r');

And the result (added to your scatter plot):


问:
Symfony 3.3 custom config file
I've very new to Symfony. Before I've used mostly Laravel.

Lets assume I have an API Key which I want to use here and there thru the project.
It doesn't feel right to store it as a class constant because I can't find any class to keep it in. And it seems pretty dumb to have it in various places thru the app as a string.

Normally using Laravel I would have used a config file specifically for this task.

However in symfony I can't seem to do the same(either that or my google-fu skills are pretty bad). If they are, a simple link to some documentation will do just fine.

So my question is: Where can I store various constants used thru the app?

答:
I'm sorry, but I'm afraid your Google-fu skills let you down this time.

Symfony.com has an excellent article about Configuration: Configuration -
Symfony Best Practices

The common way to save configuration parameters is by using parameters.yml. It supports environment variables as of Symfony 3.2.

The best practice for Symfony 2.x and 3.x:

Define the infrastructure-related configuration options in the
  app/config/parameters.yml file.

The best practice for Symfony 4:

Define the infrastructure-related configuration options as environment
  variables. During development, use the .env file at the root of your
  project to set these.

Title: Symfony 3.3 custom config file


问:
Select2 with a checkbox list for a multiple select
I need to implement a select similar to this http://www.erichynds.com/examples/jquery-ui-multiselect-widget/demos/

I want to use select2 for this, but I haven't been able to find anything from the creator of the select2 that would support this style of dropdown with checkboxes in it. Does anyone know a way to do this?

答:
Another workaround is to "prepend" checkbox icons using CSS. I use bootstrap theme - your select2-container may be different.</p>

```<code>.select2-container--bootstrap .select2-results__option[aria-selected=true]:before { content:'\e067 '; padding:0 8px 0 0px; font-family:'Glyphicons Halflings' }
.select2-container--bootstrap .select2-results__option:before { content:'\e157 '; padding:0 8px 0 0px; font-family:'Glyphicons Halflings' }
</code>```

Body:
Another workaround is to "prepend" checkbox icons using CSS. I use bootstrap theme - your select2-container may be different.

.select2-container--bootstrap .select2-results__option[aria-selected=true]:before { content:'\e067 '; padding:0 8px 0 0px; font-family:'Glyphicons Halflings' }
.select2-container--bootstrap .select2-results__option:before { content:'\e157 '; padding:0 8px 0 0px; font-family:'Glyphicons Halflings' }


问:
Spring Data JPA save list entity return list in same the order?
Does the method in Spring-Data-JPA's CrudRepository

```<code> <S extends T> Iterable<S> saveAll(Iterable<S> entities)
</code>```

return list in the same order ?

答:
In that version an actual List is the return type:

```<code>@Transactional
public <S extends T> List<S> save(Iterable<S> entities) {

    List<S> result = new ArrayList<S>();

    if (entities == null) {
        return result;
    }

    for (S entity : entities) {
        result.add(save(entity));
    }

    return result;
}
</code>```

so if you pass a List to the method, you will get the result in the exact same order as the ArrayList is the implementation.

ContentLicense: CC BY-SA 4.0

Body:
Does the method in Spring-Data-JPA's CrudRepository

 <S extends T> Iterable<S> saveAll(Iterable<S> entities)

return list in the same order ?

Body:
In that version an actual List is the return type:

@Transactional
public <S extends T> List<S> save(Iterable<S> entities) {

    List<S> result = new ArrayList<S>();

    if (entities == null) {
        return result;
    }

    for (S entity : entities) {
        result.add(save(entity));
    }

    return result;
}

so if you pass a List to the method, you will get the result in the exact same order as the ArrayList is the implementation.


问:
Setting custom URLs with PHP
So, I need to set custom URLs so that

http://example.com/dynamic/

goes to:

http://example.com/dynamic.php

I know this is a pretty simple operation but after some googling, I can't find the answer. What is the simplest method for handling something like this?

答:
you have to do it using url rewriting.
that depends on the web server that you are using .
for example, you can use .htaccess if your webserver is Apache.
Apache URL Rewriting.</p>

ContentLicense: CC BY-SA 2.5

Title: Setting custom URLs with PHP


问:
Use ENTER or RETURN as TAB in form and panels
My form as multiple controls like Textboxes and Panels, and Textboxes in Panels, which cause problem. I try to make keys ENTER and RETURN do the same as TAB, so select next control, but for an unknown reason if I i go from any control to a panel, it doesn't enter the first control in the panel, it skips to the next control which isn't a panel.

My form key preview is already True and my tab index are okay :
First textbox is 10, first panel 11, first textbox of panel 12. For now it skips to 20, next textbox not in a panel.

Code based on this question : Tab Key Functionality Using Enter Key in VB.Net

Here is my code

```<code>Private Sub Values_KeyDown(ByVal sender As Control,
  ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    If e.KeyCode = Keys.Return Or e.KeyCode = Keys.Enter Then
        If TypeOf Me.GetNextControl(Me.ActiveControl, True) Is Panel Then
            Me.SelectNextControl(CType(Me.ActiveControl, Panel).Controls.Item(0), True, True, False, True)
        Else
            Me.SelectNextControl(Me.ActiveControl, True, True, False, True)
        End If
        e.Handled = True
    End If
End Sub
</code>```

Thanks!

答:
I don't really understand the code snippet, it looks like the last attempt before giving up.  Nor how it got to run at all, KeyPreview is not good enough to intercept KeyDown for the navigation keys like the Enter key.  The nested argument for SelectNextControl() should not certainly not be False, you do want to consider controls that are nested inside a panel as the next tab target, presumably what made the code jump off the rails.

I'll post a more universal solution that does not depend on KeyPreview and still properly deals with controls that need the Enter key to function correctly.  Simply copy/paste it into the form, it does not use events:

```<code>Protected Overrides Function ProcessCmdKey(ByRef msg As Message, keyData As Keys) As Boolean
    Dim dotab = False
    Dim ctl = Me.ActiveControl
    If ctl IsNot Nothing And keyData = Keys.Enter Then
        dotab = True
        If TypeOf ctl Is TextBoxBase Then
            If DirectCast(ctl, TextBoxBase).Multiline Then dotab = False
        End If
    End If
    If dotab Then
        If Me.SelectNextControl(ctl, True, True, True, True) Then Return True
    End If
    Return MyBase.ProcessCmdKey(msg, keyData)
End Function
</code>```

Body:
My form as multiple controls like Textboxes and Panels, and Textboxes in Panels, which cause problem. I try to make keys ENTER and RETURN do the same as TAB, so select next control, but for an unknown reason if I i go from any control to a panel, it doesn't enter the first control in the panel, it skips to the next control which isn't a panel.

My form key preview is already True and my tab index are okay :
First textbox is 10, first panel 11, first textbox of panel 12. For now it skips to 20, next textbox not in a panel.

Code based on this question : Tab Key Functionality Using Enter Key in VB.Net

Here is my code

Private Sub Values_KeyDown(ByVal sender As Control,
  ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
    If e.KeyCode = Keys.Return Or e.KeyCode = Keys.Enter Then
        If TypeOf Me.GetNextControl(Me.ActiveControl, True) Is Panel Then
            Me.SelectNextControl(CType(Me.ActiveControl, Panel).Controls.Item(0), True, True, False, True)
        Else
            Me.SelectNextControl(Me.ActiveControl, True, True, False, True)
        End If
        e.Handled = True
    End If
End Sub

Thanks!

Body:
I don't really understand the code snippet, it looks like the last attempt before giving up.  Nor how it got to run at all, KeyPreview is not good enough to intercept KeyDown for the navigation keys like the Enter key.  The nested argument for SelectNextControl() should not certainly not be False, you do want to consider controls that are nested inside a panel as the next tab target, presumably what made the code jump off the rails.

I'll post a more universal solution that does not depend on KeyPreview and still properly deals with controls that need the Enter key to function correctly.  Simply copy/paste it into the form, it does not use events:

Protected Overrides Function ProcessCmdKey(ByRef msg As Message, keyData As Keys) As Boolean
    Dim dotab = False
    Dim ctl = Me.ActiveControl
    If ctl IsNot Nothing And keyData = Keys.Enter Then
        dotab = True
        If TypeOf ctl Is TextBoxBase Then
            If DirectCast(ctl, TextBoxBase).Multiline Then dotab = False
        End If
    End If
    If dotab Then
        If Me.SelectNextControl(ctl, True, True, True, True) Then Return True
    End If
    Return MyBase.ProcessCmdKey(msg, keyData)
End Function


问:
Cannot trigger addListenerForSingleValueEvent
I have a piece of code below. I don't know why the onDataChange cannot be triggered. As a result, the object singleChildSummary is null.</p>

```<code>>ChildSummary singleChildSummary;
>DatabaseReference childSummaryRef = getChildDatabaseReference().child(id);
>     childSummaryRef.addListenerForSingleValueEvent(new ValueEventListener() {
>                 @Override
>                 public void onDataChange(DataSnapshot dataSnapshot) {
>                     singleChildSummary = dataSnapshot.getValue(ChildSummary.class);
 >                 }
>
>                 @Override
>                 public void onCancelled(DatabaseError error) {
>                     // Failed to read value
>     //                Log.w(TAG, "Failed to read value.", error.toException());
>                 }
>             });
</code>```

答: If getValue() returns null "if there is no data at this location", according to the API documentation.</p>

Body:
I have a piece of code below. I don't know why the onDataChange cannot be triggered. As a result, the object singleChildSummary is null.

>ChildSummary singleChildSummary;
>DatabaseReference childSummaryRef = getChildDatabaseReference().child(id);
>     childSummaryRef.addListenerForSingleValueEvent(new ValueEventListener() {
>                 @Override
>                 public void onDataChange(DataSnapshot dataSnapshot) {
>                     singleChildSummary = dataSnapshot.getValue(ChildSummary.class);
 >                 }
>
>                 @Override
>                 public void onCancelled(DatabaseError error) {
>                     // Failed to read value
>     //                Log.w(TAG, "Failed to read value.", error.toException());
>                 }
>             });


问:
Add implicit promotion to complex class, last step
I would like to allow implicit conversion when summing complex numbers.
For example:

```<code> complex<double> a;
 complex<long double> b;
 int i;

 auto sum = a + b; // (1)
 auto SUM = a + i; // (2)
</code>```

I have the code that enable conversion (1) thanks to answer implicit type promotion in summing two complex<>
In order to enable also the (2) conversion I used enable_if_t

```<code>  template <typename T, typename U>
  auto operator +(const ::std::complex<T> &a,     std::enable_if_t<std::is_arithmetic<U>::value, U>  &b)
  {
   typedef decltype(::std::declval<T>() + ::std::declval<U>()) comcomp_t;
   typedef ::std::complex<comcomp_t> result_t;
   return ::std::operator +(result_t{a}, result_t{b});
  }
</code>```

However, I got a compilation error saying "couldn't deduce template paramter 'U'. I guess my comprehension of SFINAE is very shallow. Any help would be highly appreciated. Thanks

答:
I am not sure that you need SFINAE here. A minimal working C++14 code is:

```<code>#include <ccomplex>
#include <type_traits>

template <typename T, typename U>
using add_t = decltype(std::declval<T>() + std::declval<U>());

template <typename T, typename U>
constexpr std::complex<add_t<T, U>> operator+(const std::complex<T>& a,
                                              const std::complex<U>& b) noexcept
{
  using returnType = decltype(a + b);
  return returnType(a.real() + b.real(), a.imag() + b.imag());
}

template <typename T, typename U>
constexpr std::complex<add_t<T, U>> operator+(const std::complex<T>& a,
                                              const U& b) noexcept
{
  using returnType = decltype(a + b);
  return returnType(a.real() + b, a.imag());
}

template <typename T, typename U>
constexpr auto operator+(const T& a, const std::complex<U>& b) noexcept
{
  return b + a;  // assume commutativity of + operator
}

using namespace std;

int main()
{

  constexpr complex<double> a;
  constexpr complex<long double> b;
  constexpr int i = 1;

  constexpr auto s1 = a + b;  // (1)
  constexpr auto s2 = a + i;  // (2)
  constexpr auto s3 = i + a;  // (3)
  constexpr auto s4 = a + 2;  // (4)
  constexpr auto s5 = 2 + a;  // (5)
}
</code>```

Note: it also works with constexpr expressions.

Body:
I would like to allow implicit conversion when summing complex numbers.
For example:

 complex<double> a;
 complex<long double> b;
 int i;

 auto sum = a + b; // (1)
 auto SUM = a + i; // (2)

I have the code that enable conversion (1) thanks to answer implicit type promotion in summing two complex<>
In order to enable also the (2) conversion I used enable_if_t

  template <typename T, typename U>
  auto operator +(const ::std::complex<T> &a,     std::enable_if_t<std::is_arithmetic::value, U>  &b)
  {
   typedef decltype(::std::declval<T>() + ::std::declval()) comcomp_t;
   typedef ::std::complex<comcomp_t> result_t;
   return ::std::operator +(result_t{a}, result_t{b});
  }

However, I got a compilation error saying "couldn't deduce template paramter 'U'. I guess my comprehension of SFINAE is very shallow. Any help would be highly appreciated. Thanks

Body:
I am not sure that you need SFINAE here. A minimal working C++14 code is:

#include <ccomplex>
#include <type_traits>

template <typename T, typename U>
using add_t = decltype(std::declval<T>() + std::declval<U>());

template <typename T, typename U>
constexpr std::complex<add_t<T, U>> operator+(const std::complex<T>& a,
                                              const std::complex<U>& b) noexcept
{
  using returnType = decltype(a + b);
  return returnType(a.real() + b.real(), a.imag() + b.imag());
}

template <typename T, typename U>
constexpr std::complex<add_t<T, U>> operator+(const std::complex<T>& a,
                                              const U& b) noexcept
{
  using returnType = decltype(a + b);
  return returnType(a.real() + b, a.imag());
}

template <typename T, typename U>
constexpr auto operator+(const T& a, const std::complex<U>& b) noexcept
{
  return b + a;  // assume commutativity of + operator
}

using namespace std;

int main()
{

  constexpr complex<double> a;
  constexpr complex<long double> b;
  constexpr int i = 1;

  constexpr auto s1 = a + b;  // (1)
  constexpr auto s2 = a + i;  // (2)
  constexpr auto s3 = i + a;  // (3)
  constexpr auto s4 = a + 2;  // (4)
  constexpr auto s5 = 2 + a;  // (5)
}

Note: it also works with constexpr expressions.


问:
open jspanel in minimized mode
i am working on to add jspanel plugin  in my project, is there any way to open jspanel in minimized mode, i found some question related to, but could not find any right answer, here is sample code  </p>

```<code> <!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jspanel3/3.10.0/jquery.jspanel.css">
        <script src="https://code.jquery.com/jquery-3.2.1.js"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jspanel3/3.10.0/jquery.jspanel-compiled.js"></script>
    </head>
    <body>
    <script type="text/javascript">
    function clickToOpen() {
     $.jsPanel({
    position: "left",
    size:     {width: 120, height: 270},
    overflow: {vertical: 'scroll'},
    theme:    "light",
    });
    }
    </script>
       <input type="button" value="click to open" onclick="clickToOpen()"></input>
    </body>
</html>
</code>```

答:
Take a look at option.setStatus of jsPanel v3.x

$.jsPanel({
    setstatus: "minimize"
});```

Title: open jspanel in minimized mode

Body:
i am working on to add jspanel plugin  in my project, is there any way to open jspanel in minimized mode, i found some question related to, but could not find any right answer, here is sample code

 <!DOCTYPE html>

        <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jspanel3/3.10.0/jquery.jspanel.css">

       <input type="button" value="click to open" onclick="clickToOpen()"></input>


问:
Git Diff with Beyond Compare
I have succeeded in getting git to start Beyond Compare 3 as a diff tool however, when I do a diff, the file I am comparing against is not being loaded.  Only the latest version of the file is loaded and nothing else, so there is nothing in the right pane of Beyond Compare.

I am running git 1.6.3.1 with Cygwin with Beyond Compare 3.  I have set up beyond compare as they suggest in the support part of their website with a script like such:

```<code>#!/bin/sh
# diff is called by git with 7 parameters:
# path old-file old-hex old-mode new-file new-hex new-mode
"path_to_bc3_executable" "$2" "$5" | cat
</code>```

Has anyone else encountered this problem and know a solution to this?

Edit:

I have followed the suggestions by VonC but I am still having exactly the same problem as before. I am kinda new to Git so perhaps I am not using the diff correctly.

For example, I am trying to see the diff on a file with a command like such:

    git diff main.css

Beyond Compare will then open and only display my current main.css in the left pane, there is nothing in the right pane.  I would like the see my current main.css in the left pane compared to the HEAD, basically what I have last committed.

My git-diff-wrapper.sh looks like this:

```<code>#!/bin/sh
# diff is called by git with 7 parameters:
# path old-file old-hex old-mode new-file new-hex new-mode
"c:/Program Files/Beyond Compare 3/BCompare.exe" "$2" "$5" | cat
</code>```

My git config looks like this for Diff:

```<code>[diff]
external = c:/cygwin/bin/git-diff-wrapper.sh
</code>```

答:
For git version 2.15.1.windows.2 with BC2.exe.

The config below finally works on my machine.

[difftool "bc2"]
cmd = \"c:/program files/beyond compare 2/bc2.exe\" ${LOCAL} ${REMOTE}

Title: Git Diff with Beyond Compare

Body:
I have succeeded in getting git to start Beyond Compare 3 as a diff tool however, when I do a diff, the file I am comparing against is not being loaded.  Only the latest version of the file is loaded and nothing else, so there is nothing in the right pane of Beyond Compare.

I am running git 1.6.3.1 with Cygwin with Beyond Compare 3.  I have set up beyond compare as they suggest in the support part of their website with a script like such:

#!/bin/sh
# diff is called by git with 7 parameters:
# path old-file old-hex old-mode new-file new-hex new-mode
"path_to_bc3_executable" "$2" "$5" | cat

Has anyone else encountered this problem and know a solution to this?

Edit:

I have followed the suggestions by VonC but I am still having exactly the same problem as before. I am kinda new to Git so perhaps I am not using the diff correctly.

For example, I am trying to see the diff on a file with a command like such:

    git diff main.css

Beyond Compare will then open and only display my current main.css in the left pane, there is nothing in the right pane.  I would like the see my current main.css in the left pane compared to the HEAD, basically what I have last committed.

My git-diff-wrapper.sh looks like this:

#!/bin/sh
# diff is called by git with 7 parameters:
# path old-file old-hex old-mode new-file new-hex new-mode
"c:/Program Files/Beyond Compare 3/BCompare.exe" "$2" "$5" | cat

My git config looks like this for Diff:

[diff]
external = c:/cygwin/bin/git-diff-wrapper.sh


问:
How to update TextView using listView every second
I have a simple android application. Inside that app, there is an editText which inputs an item to a listView on button click. Then when a button with onClick ''start'' is clicked, it displays a textView which shows the listview items as a whole.

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

private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
private ListView lvItems;
TextView displayText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_math);

    lvItems = (ListView) findViewById(R.id.lvItems);
    items = new ArrayList<String>();
    itemsAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, items);
    lvItems.setAdapter(itemsAdapter);
    displayText = (TextView)findViewById(R.id.displayText);
    //displayText is textView that displays list values.
}

public void AddItem(View v) {
    //Where items are added to the list
    EditText etNewItem = (EditText) findViewById(R.id.etNewItem);
    String itemText = etNewItem.getText().toString();
    items.add(itemText);
    etNewItem.setText("");
}
public void start(View v) {
    //Where it displays text
    RelativeLayout lc = (RelativeLayout)findViewById(R.id.contentContainer);
    lc.setVisibility(View.GONE);
    RelativeLayout tc = (RelativeLayout)findViewById(R.id.tvContainer);
    tc.setVisibility(View.VISIBLE);

    for (int i = 0; i < items.size(); i++) {
        displayText.setText(displayText.getText().toString() + "\n" + items.get(i));
    }

}
}
</code>```

Is there any way that I can display the listView items in displayText one by one every second.

答:
Here is updated code, as per your requirement::

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

    int listSize=0;
    private ArrayList<String> items;
    private ArrayAdapter<String> itemsAdapter;
    private ListView lvItems;
    TextView displayText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_math);

       lvItems = (ListView) findViewById(R.id.lvItems);
       items = new ArrayList<String>();
       itemsAdapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_list_item_1, items);
       lvItems.setAdapter(itemsAdapter);
       displayText = (TextView)findViewById(R.id.displayText);
      //displayText is textView that displays list values.
 }

 public void AddItem(View v) {
    //Where items are added to the list
    EditText etNewItem = (EditText) findViewById(R.id.etNewItem);
    String itemText = etNewItem.getText().toString();
    items.add(itemText);
    etNewItem.setText("");
 }
 public void start(View v) {
     //Where it displays text
     RelativeLayout lc = (RelativeLayout)findViewById(R.id.contentContainer);
     lc.setVisibility(View.GONE);
     RelativeLayout tc = (RelativeLayout)findViewById(R.id.tvContainer);
     tc.setVisibility(View.VISIBLE);

     final Timer timer = new Timer();
    timer.schedule(new TimerTask() {

        @Override
        public void run() {

            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if(count>items.size())
                        timer.cancel();
                    else {
                        displayText.setText(displayText.getText().toString() + "\n" + items.get(count));
                    }
                }
            });

        }
    }, 0, 1000);

     }

 }
 }
</code>```

I think it will work as per your expectation, if something to change please tell me I will do.

thanks and happy coding.

Body:
I have a simple android application. Inside that app, there is an editText which inputs an item to a listView on button click. Then when a button with onClick ''start'' is clicked, it displays a textView which shows the listview items as a whole.

public class Math extends AppCompatActivity {

private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
private ListView lvItems;
TextView displayText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_math);

    lvItems = (ListView) findViewById(R.id.lvItems);
    items = new ArrayList<String>();
    itemsAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, items);
    lvItems.setAdapter(itemsAdapter);
    displayText = (TextView)findViewById(R.id.displayText);
    //displayText is textView that displays list values.
}

public void AddItem(View v) {
    //Where items are added to the list
    EditText etNewItem = (EditText) findViewById(R.id.etNewItem);
    String itemText = etNewItem.getText().toString();
    items.add(itemText);
    etNewItem.setText("");
}
public void start(View v) {
    //Where it displays text
    RelativeLayout lc = (RelativeLayout)findViewById(R.id.contentContainer);
    lc.setVisibility(View.GONE);
    RelativeLayout tc = (RelativeLayout)findViewById(R.id.tvContainer);
    tc.setVisibility(View.VISIBLE);

    for (int i = 0; i < items.size(); i++) {
        displayText.setText(displayText.getText().toString() + "\n" + items.get(i));
    }

}
}

Is there any way that I can display the listView items in displayText one by one every second.

Body:
Here is updated code, as per your requirement::

  public class Math extends AppCompatActivity {

    int listSize=0;
    private ArrayList<String> items;
    private ArrayAdapter<String> itemsAdapter;
    private ListView lvItems;
    TextView displayText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_math);

       lvItems = (ListView) findViewById(R.id.lvItems);
       items = new ArrayList<String>();
       itemsAdapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_list_item_1, items);
       lvItems.setAdapter(itemsAdapter);
       displayText = (TextView)findViewById(R.id.displayText);
      //displayText is textView that displays list values.
 }

 public void AddItem(View v) {
    //Where items are added to the list
    EditText etNewItem = (EditText) findViewById(R.id.etNewItem);
    String itemText = etNewItem.getText().toString();
    items.add(itemText);
    etNewItem.setText("");
 }
 public void start(View v) {
     //Where it displays text
     RelativeLayout lc = (RelativeLayout)findViewById(R.id.contentContainer);
     lc.setVisibility(View.GONE);
     RelativeLayout tc = (RelativeLayout)findViewById(R.id.tvContainer);
     tc.setVisibility(View.VISIBLE);

     final Timer timer = new Timer();
    timer.schedule(new TimerTask() {

        @Override
        public void run() {

            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if(count>items.size())
                        timer.cancel();
                    else {
                        displayText.setText(displayText.getText().toString() + "\n" + items.get(count));
                    }
                }
            });

        }
    }, 0, 1000);

     }

 }
 }

I think it will work as per your expectation, if something to change please tell me I will do.

thanks and happy coding.


问:
Laravel eloquent update column value by adding new value
I am using updateOrCreate() method to update points of current user:

```<code>   $point->updateOrCreate(
        ['user_id' => auth()->id()],
        ['score' => request('totalScore')]
    );
</code>```

If request('totalScore') is  50, and current value of column score is 10, I want to update it to 60. But as you can see, the above-mentioned approach directly replaces 10 with 50.

Google search returned results containing query builder's increment() method. But I didn't have to use the query builder in my entire application. Why should I use it now? Would it be possible to update the value using the Eloquent methods?

答:
"Since Eloquent models are query builders, you should review all of the methods available on the query builder. You may use any of these methods in your Eloquent queries."

Laravel 5.5 Docs - Eloquent - Retrieving Models

You can use Eloquent to use any of the Query Builder methods or any Eloquent specific methods.

Body:
I am using updateOrCreate() method to update points of current user:

   $point->updateOrCreate(
        ['user_id' => auth()->id()],
        ['score' => request('totalScore')]
    );

If request('totalScore') is  50, and current value of column score is 10, I want to update it to 60. But as you can see, the above-mentioned approach directly replaces 10 with 50.

Google search returned results containing query builder's increment() method. But I didn't have to use the query builder in my entire application. Why should I use it now? Would it be possible to update the value using the Eloquent methods?


问:
Saving iteratively to a new DataFrame in Pyspark
I'm performing computations based on 3 different PySpark DataFrames.

This script works in the sense that it performs the computation as it should, however, I struggle with working properly with the results of said computation.

import sys
import numpy as np
from pyspark import SparkConf, SparkContext, SQLContext
sc = SparkContext("local")
sqlContext = SQLContext(sc)

# Dummy Data
df = sqlContext.createDataFrame([[0,1,0,0,0],[1,1,0,0,1],[0,0,1,0,1],[1,0,1,1,0],[1,1,0,0,0]], ['p1', 'p2', 'p3', 'p4', 'p5'])
df.show()
+---+---+---+---+---+
| p1| p2| p3| p4| p5|
+---+---+---+---+---+
|  0|  1|  0|  0|  0|
|  1|  1|  0|  0|  1|
|  0|  0|  1|  0|  1|
|  1|  0|  1|  1|  0|
|  1|  1|  0|  0|  0|
+---+---+---+---+---+

# Values
values = sqlContext.createDataFrame([(0,1,'p1'),(None,1,'p2'),(0,0,'p3'),(None,0, 'p4'),(1,None,'p5')], ('f1', 'f2','index'))
values.show()
+----+----+-----+
|  f1|  f2|index|
+----+----+-----+
|   0|   1|   p1|
|null|   1|   p2|
|   0|   0|   p3|
|null|   0|   p4|
|   1|null|   p5|
+----+----+-----+

# Weights
weights = sqlContext.createDataFrame([(4,3,'p1'),(None,1,'p2'),(2,2,'p3'),(None, 3, 'p4'),(3,None,'p5')], ('f1', 'f2','index'))
weights.show()
+----+----+-----+
|  f1|  f2|index|
+----+----+-----+
|   4|   3|   p1|
|null|   1|   p2|
|   2|   2|   p3|
|null|   3|   p4|
|   3|null|   p5|
+----+----+-----+

# Function: it sums the vector W for the values of Row equal to the value of V and then divide by the length of V.
# If there a no similarities between Row and V outputs 0
def W_sum(row,v,w):
    if len(w[row==v])>0:
        return float(np.sum(w[row==v])/len(w))
    else:
        return 0.0
```

<p>For each of the columns and for each row in Data, the above function is applied.</p>

<pre class="lang-python prettyprint-override"><code># We iterate over the columns of Values (except the last one called index)
for val in values.columns[:-1]:
    # we filter the data to work only with the columns that are defined for the selected Value
    defined_col = [i[0] for i in values.where(F.col(val) >= 0).select(values.index).collect()]
    # we select only the useful columns
    df_select= df.select(defined_col)
    # we retrieve the reference value and weights
    V = np.array(values.where(values.index.isin(defined_col)).select(val).collect()).flatten()
    W = np.array(weights.where(weights.index.isin(defined_col)).select(val).collect()).flatten()
    W_sum_udf = F.udf(lambda row: W_sum(row, V, W), FloatType())
    df_select.withColumn(val, W_sum_udf(F.array(*(F.col(x) for x in df_select.columns))))
</code>```

This gives :

+---+---+---+---+---+---+
| p1| p2| p3| p4| p5| f1|
+---+---+---+---+---+---+
|  0|  1|  0|  0|  0|2.0|
|  1|  1|  0|  0|  1|1.0|
|  0|  0|  1|  0|  1|2.0|
|  1|  0|  1|  1|  0|0.0|
|  1|  1|  0|  0|  0|0.0|
+---+---+---+---+---+---+
```

<p>It added the column to the sliced DataFrame as I asked it to. The problem is that I would rather collect the data into a new one that I could access at the end to consult the results.<br>
It it possible to grow (somewhat efficiently) a DataFrame in PySpark as I would with pandas?</p>

<p><strong>Edit to make my goal clearer:</strong><br>
Ideally I would get a DataFrame with the just the computed columns, like this:</p>

<pre class="lang-python prettyprint-override"><code>    +---+---+
    | f1| f2|
    +---+---+
    |2.0|1.0|
    |1.0|2.0|
    |2.0|0.0|
    |0.0|0.0|
    |0.0|2.0|
    +---+---+
</code>```

答:
There are some issues with your question...

First, your for loop will produce an error, since df_select in the last line is nowhere defined; there is also no assignment at the end (what does it produce?).

Assuming that df_select is actually your subsubsample dataframe, defined some lines before, and that your last line is something like

new_df = subsubsample.withColumn(val, W_sum_udf(F.array(*(F.col(x) for x in subsubsample.columns))))
```

<p>then your problem starts getting more clear. Since</p>

<pre class="lang-python prettyprint-override"><code>values.columns[:-1]
#  ['f1', 'f2']
</code>```

the result of the whole loop would be just

+---+---+---+---+---+
| p1| p2| p3| p4| f2|
+---+---+---+---+---+
|  0|  1|  0|  0|1.0|
|  1|  1|  0|  0|2.0|
|  0|  0|  1|  0|0.0|
|  1|  0|  1|  1|0.0|
|  1|  1|  0|  0|2.0|
+---+---+---+---+---+
```

<p>i.e. with only the column <code>f2</code> included (natural, since the results with <code>f1</code> are simply overwritten).</p>

<p>Now, as I said, <em>assuming</em> that the situation is like this, and that your problem is actually how to have both columns <code>f1</code> & <code>f2</code> together rather in different dataframes, you can just forget <code>subsubsample</code> and append columns to your initial <code>df</code>, possibly dropping afterwards the unwanted ones:</p>

<pre class="lang-python prettyprint-override"><code>init_cols = df.columns
init_cols
#  ['p1', 'p2', 'p3', 'p4', 'p5']

new_df = df

for val in values.columns[:-1]:
    # we filter the data to work only with the columns that are defined for the selected Value
    defined_col = [i[0] for i in values.where(F.col(val) >= 0).select(values.index).collect()]
    # we retrieve the reference value and weights
    V = np.array(values.where(values.index.isin(defined_col)).select(val).collect()).flatten()
    W = np.array(weights.where(weights.index.isin(defined_col)).select(val).collect()).flatten()
    W_sum_udf = F.udf(lambda row: W_sum(row, V, W), FloatType())
    new_df = new_df.withColumn(val, W_sum_udf(F.array(*(F.col(x) for x in defined_col)))) # change here

# drop initial columns:
for i in init_cols:
  new_df = new_df.drop(i)
</code>```

The resulting new_df will be:

+---+---+
| f1| f2|
+---+---+
|2.0|1.0|
|1.0|2.0|
|2.0|0.0|
|0.0|0.0|
|0.0|2.0|
+---+---+
```

<p>UPDATE (after comment): To force the division in your <code>W_sum</code> function to be a float, use:</p>

<pre class="lang-python prettyprint-override"><code>from __future__ import division
</code>```

new_df now will be:

+---------+----+
|       f1|  f2|
+---------+----+
|      2.0| 1.5|
|1.6666666|2.25|
|2.3333333|0.75|
|      0.0|0.75|
|0.6666667|2.25|
+---------+----+
```

with f2 exactly as it should be according to your comment.

Body:
I'm performing computations based on 3 different PySpark DataFrames.

This script works in the sense that it performs the computation as it should, however, I struggle with working properly with the results of said computation.

import sys
import numpy as np
from pyspark import SparkConf, SparkContext, SQLContext
sc = SparkContext("local")
sqlContext = SQLContext(sc)

# Dummy Data
df = sqlContext.createDataFrame([[0,1,0,0,0],[1,1,0,0,1],[0,0,1,0,1],[1,0,1,1,0],[1,1,0,0,0]], ['p1', 'p2', 'p3', 'p4', 'p5'])
df.show()
+---+---+---+---+---+
| p1| p2| p3| p4| p5|
+---+---+---+---+---+
|  0|  1|  0|  0|  0|
|  1|  1|  0|  0|  1|
|  0|  0|  1|  0|  1|
|  1|  0|  1|  1|  0|
|  1|  1|  0|  0|  0|
+---+---+---+---+---+

# Values
values = sqlContext.createDataFrame([(0,1,'p1'),(None,1,'p2'),(0,0,'p3'),(None,0, 'p4'),(1,None,'p5')], ('f1', 'f2','index'))
values.show()
+----+----+-----+
|  f1|  f2|index|
+----+----+-----+
|   0|   1|   p1|
|null|   1|   p2|
|   0|   0|   p3|
|null|   0|   p4|
|   1|null|   p5|
+----+----+-----+

# Weights
weights = sqlContext.createDataFrame([(4,3,'p1'),(None,1,'p2'),(2,2,'p3'),(None, 3, 'p4'),(3,None,'p5')], ('f1', 'f2','index'))
weights.show()
+----+----+-----+
|  f1|  f2|index|
+----+----+-----+
|   4|   3|   p1|
|null|   1|   p2|
|   2|   2|   p3|
|null|   3|   p4|
|   3|null|   p5|
+----+----+-----+

# Function: it sums the vector W for the values of Row equal to the value of V and then divide by the length of V.
# If there a no similarities between Row and V outputs 0
def W_sum(row,v,w):
    if len(w[row==v])>0:
        return float(np.sum(w[row==v])/len(w))
    else:
        return 0.0

For each of the columns and for each row in Data, the above function is applied.

# We iterate over the columns of Values (except the last one called index)
for val in values.columns[:-1]:
    # we filter the data to work only with the columns that are defined for the selected Value
    defined_col = [i[0] for i in values.where(F.col(val) >= 0).select(values.index).collect()]
    # we select only the useful columns
    df_select= df.select(defined_col)
    # we retrieve the reference value and weights
    V = np.array(values.where(values.index.isin(defined_col)).select(val).collect()).flatten()
    W = np.array(weights.where(weights.index.isin(defined_col)).select(val).collect()).flatten()
    W_sum_udf = F.udf(lambda row: W_sum(row, V, W), FloatType())
    df_select.withColumn(val, W_sum_udf(F.array(*(F.col(x) for x in df_select.columns))))

This gives :

+---+---+---+---+---+---+
| p1| p2| p3| p4| p5| f1|
+---+---+---+---+---+---+
|  0|  1|  0|  0|  0|2.0|
|  1|  1|  0|  0|  1|1.0|
|  0|  0|  1|  0|  1|2.0|
|  1|  0|  1|  1|  0|0.0|
|  1|  1|  0|  0|  0|0.0|
+---+---+---+---+---+---+

It added the column to the sliced DataFrame as I asked it to. The problem is that I would rather collect the data into a new one that I could access at the end to consult the results.

It it possible to grow (somewhat efficiently) a DataFrame in PySpark as I would with pandas?

Edit to make my goal clearer:

Ideally I would get a DataFrame with the just the computed columns, like this:

    +---+---+
    | f1| f2|
    +---+---+
    |2.0|1.0|
    |1.0|2.0|
    |2.0|0.0|
    |0.0|0.0|
    |0.0|2.0|
    +---+---+

Body:
There are some issues with your question...

First, your for loop will produce an error, since df_select in the last line is nowhere defined; there is also no assignment at the end (what does it produce?).

Assuming that df_select is actually your subsubsample dataframe, defined some lines before, and that your last line is something like

new_df = subsubsample.withColumn(val, W_sum_udf(F.array(*(F.col(x) for x in subsubsample.columns))))

then your problem starts getting more clear. Since

values.columns[:-1]
#  ['f1', 'f2']

the result of the whole loop would be just

+---+---+---+---+---+
| p1| p2| p3| p4| f2|
+---+---+---+---+---+
|  0|  1|  0|  0|1.0|
|  1|  1|  0|  0|2.0|
|  0|  0|  1|  0|0.0|
|  1|  0|  1|  1|0.0|
|  1|  1|  0|  0|2.0|
+---+---+---+---+---+

i.e. with only the column f2 included (natural, since the results with f1 are simply overwritten).

Now, as I said, assuming that the situation is like this, and that your problem is actually how to have both columns f1 & f2 together rather in different dataframes, you can just forget subsubsample and append columns to your initial df, possibly dropping afterwards the unwanted ones:

init_cols = df.columns
init_cols
#  ['p1', 'p2', 'p3', 'p4', 'p5']

new_df = df

for val in values.columns[:-1]:
    # we filter the data to work only with the columns that are defined for the selected Value
    defined_col = [i[0] for i in values.where(F.col(val) >= 0).select(values.index).collect()]
    # we retrieve the reference value and weights
    V = np.array(values.where(values.index.isin(defined_col)).select(val).collect()).flatten()
    W = np.array(weights.where(weights.index.isin(defined_col)).select(val).collect()).flatten()
    W_sum_udf = F.udf(lambda row: W_sum(row, V, W), FloatType())
    new_df = new_df.withColumn(val, W_sum_udf(F.array(*(F.col(x) for x in defined_col)))) # change here

# drop initial columns:
for i in init_cols:
  new_df = new_df.drop(i)

The resulting new_df will be:

+---+---+
| f1| f2|
+---+---+
|2.0|1.0|
|1.0|2.0|
|2.0|0.0|
|0.0|0.0|
|0.0|2.0|
+---+---+

UPDATE (after comment): To force the division in your W_sum function to be a float, use:

from __future__ import division

new_df now will be:

+---------+----+
|       f1|  f2|
+---------+----+
|      2.0| 1.5|
|1.6666666|2.25|
|2.3333333|0.75|
|      0.0|0.75|
|0.6666667|2.25|
+---------+----+

with f2 exactly as it should be according to your comment.


问:
How to print a reverse linked list without using recursion in Java?
I try printing a reverse linked list without recursion and reversing the linked list. How can I do that?

Questions: How to print a reverse linked list without using recursion and not reversing the list?

Requirements: No extra space, cannot reverse a linked list, cannot use recursion.

Here is the definition of the linked list Node

```<code>class Node {
  int value;
  Node next;

  public Node(int val) {
    this.value = val;
  }
}
</code>```

Here is my recursion version of printReverseLinkedList:

```<code>public void printReverseList(Node head) {
    Node temp = head;
    if (temp.next != null) {
        printReverseList(temp.next);
    }
    System.out.print(temp.value);
}
</code>```

Performace does not matter, because I just want to do in this way.

答:
```<code>void ReversePrint(Node head) {
    // This is a "method-only" submission.
    // You only need to complete this method.
    Stack<Node> stk=new Stack<>();

    Node temp=head;
    while(temp!=null){
        stk.push(temp);
        temp=temp.next;
    }
    while(!stk.isEmpty()){
        System.out.println(stk.pop().data);
    }
}
</code>```

Body:
I try printing a reverse linked list without recursion and reversing the linked list. How can I do that?

Questions: How to print a reverse linked list without using recursion and not reversing the list?

Requirements: No extra space, cannot reverse a linked list, cannot use recursion.

Here is the definition of the linked list Node

class Node {
  int value;
  Node next;

  public Node(int val) {
    this.value = val;
  }
}

Here is my recursion version of printReverseLinkedList:

public void printReverseList(Node head) {
    Node temp = head;
    if (temp.next != null) {
        printReverseList(temp.next);
    }
    System.out.print(temp.value);
}

Performace does not matter, because I just want to do in this way.


问:
jQuery background image fading on a submit button input
I've been using the basic gist of this tutorial to create links with background images that fade to different background images (using a sprite) on hover. This is basically done by putting an empty span inside the link which is hidden until hover, and then it fades in to view.

How can I do the same using a submit button input? I can't just put a span in because obviously you can't insert HTML inside an input tag since it is self-closing. So any other options?

One thing I was thinking was surrounding the input with a div of the same width/height and giving the div the hover background image, and on hover, fade the span out to opacity of something like 0.01 so that it would still be clickable but be transparent. Are there any better options or is this the way to go?

答:
I ended up using this technique.

Basically, instead of adding a span INSIDE the element, you add a div AROUND the element and fade in the button on hover.


问:
Why is Data Null?
I came across an error today, and I am not sure why it occurred. At the second for loop, the access to data will be undefined instead of the data that was inserted as a parameter into the function. Somehow the data gets the value of null, instead of the Object that was passed to this function. Does anyone know why? The error I get is "data is not defined".

```<code>     createDataObject: function (data) {
        let dataObj = data.source[0];
        let backedData = data.backedData;
        for (let i in dataObj) {
            let d = dataObj[i];
            d.data = { source: d.data };
        }
        for (let i = 0; i < data.backedData.length; i++) {
            let bd = data.backedData[i];      //<- this is where the error occurrs
            let data = bd.data[0];
        }
}
</code>```

Here is some code outside of the object, if you want to try, that I was using, this will work on your console or in node. Seems like I have come across a Javascript compiler bug. I am not sure.

```<code>createDataObject({source: [[{data: 1}]],  backedData: [1,2,3, 4]});
</code>```

The code above will work if I do the following

```<code>    createDataObject: function (data) {
        let dataObj = data.source[0];
        let backedData = data.backedData;   //create the backedData variable here
        for (let i in dataObj) {
            let d = dataObj[i];
            d.data = { source: d.data };
        }
        for (let i = 0; i < backedData.length; i++) {
            let bd = backedData[i]; // no Error
            let data = bd.data[0];
            //.....
        }
    }
</code>```

答:
in the second for loop you create another data object.  Data is not created on the first line in the for loop.
Try using</p>

```<code>   for (let i = 0; i < data.backedData.length; i++) {
        let bd = data.backedData[i];
        let d= bd.data[0];   // Convert data to d or another variable name
        //.....
    }
</code>```

Title: Why is Data Null?

Body:
I came across an error today, and I am not sure why it occurred. At the second for loop, the access to data will be undefined instead of the data that was inserted as a parameter into the function. Somehow the data gets the value of null, instead of the Object that was passed to this function. Does anyone know why? The error I get is "data is not defined".

     createDataObject: function (data) {
        let dataObj = data.source[0];
        let backedData = data.backedData;
        for (let i in dataObj) {
            let d = dataObj[i];
            d.data = { source: d.data };
        }
        for (let i = 0; i < data.backedData.length; i++) {
            let bd = data.backedData[i];      //<- this is where the error occurrs
            let data = bd.data[0];
        }
}

Here is some code outside of the object, if you want to try, that I was using, this will work on your console or in node. Seems like I have come across a Javascript compiler bug. I am not sure.

createDataObject({source: [[{data: 1}]],  backedData: [1,2,3, 4]});

The code above will work if I do the following

    createDataObject: function (data) {
        let dataObj = data.source[0];
        let backedData = data.backedData;   //create the backedData variable here
        for (let i in dataObj) {
            let d = dataObj[i];
            d.data = { source: d.data };
        }
        for (let i = 0; i < backedData.length; i++) {
            let bd = backedData[i]; // no Error
            let data = bd.data[0];
            //.....
        }
    }

Body:
in the second for loop you create another data object.  Data is not created on the first line in the for loop.
Try using

   for (let i = 0; i < data.backedData.length; i++) {
        let bd = data.backedData[i];
        let d= bd.data[0];   // Convert data to d or another variable name
        //.....
    }


问:
Programmatically setting LinearLayout divider size
I have tried multiple solutions to this but none seem to work! I am currently using the following Drawable as a divider (this is the horizontal example but the same approach works for vertical too, switching height for width).

```<code>LinearLayout linearLayout; // set with findViewById
linearLayout.setDividerDrawable(getResources().getDrawable(R.drawable.divider));
linearLayout.setShowDividers(SHOW_DIVIDER_MIDDLE);
</code>```

Where divider looks like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <size
        android:width="10dp"
        android:height="0dp" />
</shape>
</code>```

However I'd like to be able to set the divider size programatically as I don't know what the size should be until runtime. I've tried creating a ShapeDrawable like this:

```<code>int desiredWidth = 10;
LinearLayout linearLayout; // set with findViewById
ShapeDrawable shapeDrawable = new ShapeDrawable(new RectShape());
shapeDrawable.getPaint().setColor(Color.TRANSPARENT);
shapeDrawable.setIntrinsicWidth(desiredWidth);
linearLayout.setDividerDrawable(shapeDrawable);
linearLayout.setShowDividers(SHOW_DIVIDER_MIDDLE);
</code>```

But the divider doesn't appear, and the items are just stuck together. I'm pretty sure it's not a pixel density issue as whatever number I put in I get the same effect - it's as though the drawable doesn't actually take the size I set it to.

答:
your drawable height is 0. try the following:

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android">
    <size
        android:width="10dp"
        android:height="10dp" />
     <!--android:height depends on the height you want for the horizontal line--->
</shape>
</code>```

or add:

```<code>drawable.setIntrinsicHeight(height);
</code>```

Body:
I have tried multiple solutions to this but none seem to work! I am currently using the following Drawable as a divider (this is the horizontal example but the same approach works for vertical too, switching height for width).

LinearLayout linearLayout; // set with findViewById
linearLayout.setDividerDrawable(getResources().getDrawable(R.drawable.divider));
linearLayout.setShowDividers(SHOW_DIVIDER_MIDDLE);

Where divider looks like this:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <size
        android:width="10dp"
        android:height="0dp" />
</shape>

However I'd like to be able to set the divider size programatically as I don't know what the size should be until runtime. I've tried creating a ShapeDrawable like this:

int desiredWidth = 10;
LinearLayout linearLayout; // set with findViewById
ShapeDrawable shapeDrawable = new ShapeDrawable(new RectShape());
shapeDrawable.getPaint().setColor(Color.TRANSPARENT);
shapeDrawable.setIntrinsicWidth(desiredWidth);
linearLayout.setDividerDrawable(shapeDrawable);
linearLayout.setShowDividers(SHOW_DIVIDER_MIDDLE);

But the divider doesn't appear, and the items are just stuck together. I'm pretty sure it's not a pixel density issue as whatever number I put in I get the same effect - it's as though the drawable doesn't actually take the size I set it to.

Body:
your drawable height is 0. try the following:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <size
        android:width="10dp"
        android:height="10dp" />
     <!--android:height depends on the height you want for the horizontal line--->
</shape>

or add:

drawable.setIntrinsicHeight(height);