问:
Form submission in angular 2
I have successfully implemented Http post request with my rest micro service .

When i make post request using the login form ,if the username password matches with database entry , it gives me back the username password in my console.

And if the username password does not exist, it returns me null.

But i want to redirect to my homepage only after successful login i.e if username and password is correct.

How to check if my console returns me null then i should not redirect ?

Below shown is my code

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HeaderComponent } from "./header.component";
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';

import { GetService } from './home/get.service';
import { PostService } from './login/post.service';

import { routing } from "./app.routing";
import { RouterModule, Routes} from '@angular/router';

import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

@NgModule({

  declarations: [AppComponent,HeaderComponent,LoginComponent,HomeComponent],

  imports: [RouterModule,BrowserModule, HttpModule , routing ],

  providers: [GetService,PostService],

  bootstrap: [AppComponent]

})

export class AppModule { }
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'

})
export class AppComponent {
  title = '';
}
</code>```

app.component.html

```<code><div style="text-align:justify-all;">
  <h1>
    {{title}}
  </h1>

 <div class="container">
<router-outlet></router-outlet>
</div>
</code>```

app.routing.ts

```<code>import { Routes, RouterModule } from "@angular/router";
import { LoginComponent } from "./login/login.component";
import { HomeComponent } from "./home/home.component";

const APP_ROUTES: Routes = [
{ path: '' , redirectTo: '/homepage', pathMatch: 'full' },
{ path: 'homepage', component: LoginComponent },
{ path: 'homepage/home', component: HomeComponent }
];

export const routing = RouterModule.forRoot(APP_ROUTES);
</code>```

header.component.ts

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
})
export class HeaderComponent {}
</code>```

header.component.html

```<code><div class="row">
<div class="col-xs-12"><ul class="nav nav-pills">
<li routerLinkActive="active"><a [routerLink]="['/homepage/home']">
<strong>Home</strong></a></li>
<li><a [routerLink]="['/homepage']"><strong>Logout</strong></a></li>
</ul></div>
</div>
</code>```

Here is my login component where i have implemented the post request

login.component.ts

```<code>import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { PostService } from './post.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
})

export class LoginComponent {
  data:any;

  constructor(private router:Router ,private MyService: PostService){ }

 checkByCredential(username: string, password: string)
 {
   this.MyService.checkByCredential(username, password).subscribe(users => console.log(users));

    this.router.navigate(['homepage/home']);
  }
}
</code>```

As shown above in the login.component.ts file i need to check if my console returns me null then i should not redirect else i should redirect to /homepage/home

login.component.html

```<code><div class="container formWidth" style="text-align:center;">
  <h1> eSpace Login</h1><hr>
<br/>
     <h2>Login</h2>
    <form role="form">
      <div ng-control-group="credentials">
        <label for="username">Username</label>
        <input
          type="text"
          #username
          id="username"
          ng-control="username"
          required>
<br/>
        <label for="password">Password</label>
        <input
          type="password"
          #password
          id="password"
          ng-control="password"
          required>
      </div>
      <button type="button" (click)="checkByCredential(username.value,password.value)">Login</button>
    </form>
</div>
</code>```

post.service.ts

```<code>import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class PostService {
constructor(private http:Http) { }

 checkByCredential(username: string, password: string) {
 const user = { username: username, password: password };
 return this.http
    .post('http://localhost:8080/checkByCredential', user)
    .map(result => result.json());
  } }
</code>```

Here is my home component in which i implemented get request

home.component.ts

```<code>import { Component } from '@angular/core';
import { GetService } from './get.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})

export class HomeComponent{
 title :string;
  data:any;

  constructor(private MyService: GetService){
  this.title="Angular Service";

  this.MyService.GetUsers()
 .subscribe(users => {this.data=users });
 }
}
</code>```

home.component.html

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'

})
export class AppComponent {
  title = '';
}
</code>```0

get.service.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'

})
export class AppComponent {
  title = '';
}
</code>```1

Here are the screen shots of my output

when i submit my form with the username and password which is not in my database,even then its redirecting me to homepage and returns null in my console

And when the credentials match my database ,even then it redirects to homepage and returns the credentials

can anybody please suggest me how to verify and redirect ?

答:
In your login.component.ts, you have your router.navigate outside of the subscribe.

An observable is asynchronous, so router.navigate will be trigger indepedently of chechByCredential.

If you want trigger the navigation when you have the API's answer, you could put your code into the subscribe:

```<code>import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { PostService } from './post.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
})

export class LoginComponent {
  data:any;

  constructor(private router:Router ,private MyService: PostService){ }

 checkByCredential(username: string, password: string)
 {
   this.MyService.checkByCredential(username, password)
      .subscribe(users => {
           if(users)
              this.router.navigate(['homepage/home']);
           else
              console.log(users) //or do somethings else
      });
  }
}
</code>```

Title: Form submission in angular 2

Body:
I have successfully implemented Http post request with my rest micro service .

When i make post request using the login form ,if the username password matches with database entry , it gives me back the username password in my console.

And if the username password does not exist, it returns me null.

But i want to redirect to my homepage only after successful login i.e if username and password is correct.

How to check if my console returns me null then i should not redirect ?

Below shown is my code

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HeaderComponent } from "./header.component";
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';

import { GetService } from './home/get.service';
import { PostService } from './login/post.service';

import { routing } from "./app.routing";
import { RouterModule, Routes} from '@angular/router';

import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

@NgModule({

  declarations: [AppComponent,HeaderComponent,LoginComponent,HomeComponent],

  imports: [RouterModule,BrowserModule, HttpModule , routing ],

  providers: [GetService,PostService],

  bootstrap: [AppComponent]

})

export class AppModule { }

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'

})
export class AppComponent {
  title = '';
}

app.component.html

    {{title}}

<router-outlet></router-outlet>

app.routing.ts

import { Routes, RouterModule } from "@angular/router";
import { LoginComponent } from "./login/login.component";
import { HomeComponent } from "./home/home.component";

const APP_ROUTES: Routes = [
{ path: '' , redirectTo: '/homepage', pathMatch: 'full' },
{ path: 'homepage', component: LoginComponent },
{ path: 'homepage/home', component: HomeComponent }
];

export const routing = RouterModule.forRoot(APP_ROUTES);

header.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
})
export class HeaderComponent {}

header.component.html

Home

Logout

Here is my login component where i have implemented the post request

login.component.ts

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { PostService } from './post.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
})

export class LoginComponent {
  data:any;

  constructor(private router:Router ,private MyService: PostService){ }

 checkByCredential(username: string, password: string)
 {
   this.MyService.checkByCredential(username, password).subscribe(users => console.log(users));

    this.router.navigate(['homepage/home']);
  }
}

As shown above in the login.component.ts file i need to check if my console returns me null then i should not redirect else i should redirect to /homepage/home

login.component.html

 eSpace Login

Login

    <form role="form">

        Username
        <input
          type="text"
          #username
          id="username"
          ng-control="username"
          required>

        Password
        <input
          type="password"
          #password
          id="password"
          ng-control="password"
          required>

      <button type="button" (click)="checkByCredential(username.value,password.value)">Login</button>
    </form>

post.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class PostService {
constructor(private http:Http) { }

 checkByCredential(username: string, password: string) {
 const user = { username: username, password: password };
 return this.http
    .post('http://localhost:8080/checkByCredential', user)
    .map(result => result.json());
  } }

Here is my home component in which i implemented get request

home.component.ts

import { Component } from '@angular/core';
import { GetService } from './get.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})

export class HomeComponent{
 title :string;
  data:any;

  constructor(private MyService: GetService){
  this.title="Angular Service";

  this.MyService.GetUsers()
 .subscribe(users => {this.data=users });
 }
}

home.component.html

<app-header></app-header>

  Welcome to eSpace Home

Angular GET service

Username	  Password

             {{ item.username }}	  {{ item.password }}

get.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class GetService {
constructor(private http:Http) { }

GetUsers(){
  return this.http.get('http://localhost:8080/checkUsers')
    .map(result => result.json());
           }
 }

Here are the screen shots of my output

when i submit my form with the username and password which is not in my database,even then its redirecting me to homepage and returns null in my console

And when the credentials match my database ,even then it redirects to homepage and returns the credentials

can anybody please suggest me how to verify and redirect ?

Body:
In your login.component.ts, you have your router.navigate outside of the subscribe.

An observable is asynchronous, so router.navigate will be trigger indepedently of chechByCredential.

If you want trigger the navigation when you have the API's answer, you could put your code into the subscribe:

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { PostService } from './post.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
})

export class LoginComponent {
  data:any;

  constructor(private router:Router ,private MyService: PostService){ }

 checkByCredential(username: string, password: string)
 {
   this.MyService.checkByCredential(username, password)
      .subscribe(users => {
           if(users)
              this.router.navigate(['homepage/home']);
           else
              console.log(users) //or do somethings else
      });
  }
}


来源: stackexchange

问:
R: merge two lists of lists of dataframes
I have two lists of lists of dataframes like this:

```<code>L1 <- list(Q1=list(A=data.frame(X1=1:3),C=data.frame(X1=1:3)),
        Q2=list(B=data.frame(X1=1:3),C=data.frame(X1=1:3)))
L2 <- list(Q1=list(B=data.frame(X1=4:6),C=data.frame(X1=4:6)),
        Q2=list(A=data.frame(X1=4:6),C=data.frame(X1=4:6)))
</code>```

The names on the first level "Q1" and "Q2" are identical in both lists.

I want to merge both lists so that dataframes with same names (e.g. "$Q1$C") will be combined like with rbind, and new ones will be added to the list. The desired output should look like this:

```<code>> L3
$Q1
$Q1$A
  X1
1  1
2  2
3  3

$Q1$B
  X1
1  4
2  5
3  6

$Q1$C
  X1
1  1
2  2
3  3
4  4
5  5
6  6

$Q2
$Q2$A
  X1
1  4
2  5
3  6

$Q2$B
  X1
1  1
2  2
3  3

$Q2$C
  X1
1  1
2  2
3  3
4  4
5  5
6  6
</code>```

I tried some combinations using Map() and lapply() but I could not fix it, yet. E.g.:

```<code>L3 <- Map('rbind',lapply(L1,'['),lapply(L2,'['))
</code>```

Any help is appreciated!

答:
Here is a solution using base R:

```<code>x <- c(L1, L2)
lapply(split(x, names(x)), function(i){
    xsub <- do.call(c, unname(i))
    lapply(split(xsub, names(xsub)), function(j) do.call(rbind, unname(j)))
})
</code>```

split(x, names(x)) will put Q1s together and Q2s together;

xsub <- do.call(c, unname(i)) will combine Q1s or Q2s into a list data.frames;

split(xsub, names(xsub)) will group data.frames by their names (A, B, C);

The output is:

```<code># $Q1
# $Q1$A
# X1
# 1  1
# 2  2
# 3  3
#
# $Q1$B
# X1
# 1  4
# 2  5
# 3  6
#
# $Q1$C
# X1
# 1  1
# 2  2
# 3  3
# 4  4
# 5  5
# 6  6
#
#
# $Q2
# $Q2$A
# X1
# 1  4
# 2  5
# 3  6
#
# $Q2$B
# X1
# 1  1
# 2  2
# 3  3
#
# $Q2$C
# X1
# 1  1
# 2  2
# 3  3
# 4  4
# 5  5
# 6  6
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two lists of lists of dataframes like this:

L1 <- list(Q1=list(A=data.frame(X1=1:3),C=data.frame(X1=1:3)),
        Q2=list(B=data.frame(X1=1:3),C=data.frame(X1=1:3)))
L2 <- list(Q1=list(B=data.frame(X1=4:6),C=data.frame(X1=4:6)),
        Q2=list(A=data.frame(X1=4:6),C=data.frame(X1=4:6)))

The names on the first level "Q1" and "Q2" are identical in both lists.

I want to merge both lists so that dataframes with same names (e.g. "$Q1$C") will be combined like with rbind, and new ones will be added to the list. The desired output should look like this:

> L3
$Q1
$Q1$A
  X1
1  1
2  2
3  3

$Q1$B
  X1
1  4
2  5
3  6

$Q1$C
  X1
1  1
2  2
3  3
4  4
5  5
6  6

$Q2
$Q2$A
  X1
1  4
2  5
3  6

$Q2$B
  X1
1  1
2  2
3  3

$Q2$C
  X1
1  1
2  2
3  3
4  4
5  5
6  6

I tried some combinations using Map() and lapply() but I could not fix it, yet. E.g.:

L3 <- Map('rbind',lapply(L1,'['),lapply(L2,'['))

Any help is appreciated!

Body:
Here is a solution using base R:

x <- c(L1, L2)
lapply(split(x, names(x)), function(i){
    xsub <- do.call(c, unname(i))
    lapply(split(xsub, names(xsub)), function(j) do.call(rbind, unname(j)))
})

split(x, names(x)) will put Q1s together and Q2s together;

xsub <- do.call(c, unname(i)) will combine Q1s or Q2s into a list data.frames;

split(xsub, names(xsub)) will group data.frames by their names (A, B, C);

The output is:

# $Q1
# $Q1$A
# X1
# 1  1
# 2  2
# 3  3
#
# $Q1$B
# X1
# 1  4
# 2  5
# 3  6
#
# $Q1$C
# X1
# 1  1
# 2  2
# 3  3
# 4  4
# 5  5
# 6  6
#
#
# $Q2
# $Q2$A
# X1
# 1  4
# 2  5
# 3  6
#
# $Q2$B
# X1
# 1  1
# 2  2
# 3  3
#
# $Q2$C
# X1
# 1  1
# 2  2
# 3  3
# 4  4
# 5  5
# 6  6


问:
Draw several pcolormesh at different positions
I would like to draw a pcolormesh (here called qm2) with its left bottom pixel in a given position according to another pcolormesh (here called qm1).

I tried following:

```<code>import matplotlib.pyplot as plt
import numpy as np

if __name__ == '__main__':

    s_det = 4
    s_array = 14

    x_shift = 5
    y_shift = 5

    array = np.zeros([s_array, s_array])
    det = np.random.randint(0, 2, [s_det, s_det])

    qm1 = plt.pcolormesh(array, alpha=.0)
    qm2 = plt.pcolormesh(det, cmap='Oranges', edgecolor='black')
    qm2.set_offset_position('data')
    qm2.set_offsets = ([x_shift, y_shift])

    ax = plt.axes()
    ax.set_aspect('equal')
    plt.show()
</code>```

But qm2 remains un-shifted.

I expected something like this:

答:
You have a typo in your code, the correct syntax on line 17 is

```<code>qm2.set_offsets([x_shift, y_shift])
</code>```

however, although it does shift the position of qm2, it does not do so in data coordinates, and I don't really know why. You could play around with the values of x_shift and y_shift until you get to the desired position, but that's not very elegant.

One solution that I could offer is to explicitly specify the coordinates X,Y of your pcolormesh. The documentation for pcolormesh is not very explicit, but I believe it uses the same convention as pcolor.

```<code>s_det = 4
s_array = 14

x_shift = 5
y_shift = 5

array = np.zeros([s_array, s_array])
det = np.random.randint(0, 2, [s_det, s_det])

qm2_x = x_shift + np.arange(s_det+1)
qm2_y = y_shift + np.arange(s_det+1)

qm1 = plt.pcolormesh(array, alpha=.0)
qm2 = plt.pcolormesh(qm2_x, qm2_y, det, cmap='Oranges', edgecolor='black')

ax = plt.axes()
ax.set_aspect('equal')
plt.show()
</code>```

Body:
I would like to draw a pcolormesh (here called qm2) with its left bottom pixel in a given position according to another pcolormesh (here called qm1).

I tried following:

import matplotlib.pyplot as plt
import numpy as np

if __name__ == '__main__':

    s_det = 4
    s_array = 14

    x_shift = 5
    y_shift = 5

    array = np.zeros([s_array, s_array])
    det = np.random.randint(0, 2, [s_det, s_det])

    qm1 = plt.pcolormesh(array, alpha=.0)
    qm2 = plt.pcolormesh(det, cmap='Oranges', edgecolor='black')
    qm2.set_offset_position('data')
    qm2.set_offsets = ([x_shift, y_shift])

    ax = plt.axes()
    ax.set_aspect('equal')
    plt.show()

But qm2 remains un-shifted.

I expected something like this:

Body:
You have a typo in your code, the correct syntax on line 17 is

qm2.set_offsets([x_shift, y_shift])

however, although it does shift the position of qm2, it does not do so in data coordinates, and I don't really know why. You could play around with the values of x_shift and y_shift until you get to the desired position, but that's not very elegant.

One solution that I could offer is to explicitly specify the coordinates X,Y of your pcolormesh. The documentation for pcolormesh is not very explicit, but I believe it uses the same convention as pcolor.

s_det = 4
s_array = 14

x_shift = 5
y_shift = 5

array = np.zeros([s_array, s_array])
det = np.random.randint(0, 2, [s_det, s_det])

qm2_x = x_shift + np.arange(s_det+1)
qm2_y = y_shift + np.arange(s_det+1)

qm1 = plt.pcolormesh(array, alpha=.0)
qm2 = plt.pcolormesh(qm2_x, qm2_y, det, cmap='Oranges', edgecolor='black')

ax = plt.axes()
ax.set_aspect('equal')
plt.show()


问:
JSONPatch WCF REST API getting invalid payload error
I am trying to use JSONPatch(KevinDockx version) in my WCF REST API(ASP.NET v4.5). My operation contract is as below:-

```<code>[OperationContract]
[WebInvoke(UriTemplate = "/{raceId}/participants", Method = "PATCH")]
void UpdateRace(string id, JsonPatchDocument<ParticipantContract[]> participantsContract);
</code>```

And implementation as follows :-

```<code>public void UpdateRace(string id, JsonPatchDocument<ParticipantContract[]> participantsContract)
{
    //Someoperation
}
</code>```

My data is like the below format where I want to perform add, update delete, move and swap operations on the participants array.

```<code>{
    "raceId" : 1
    "participants": [
        {
            "id": "abc",
            "car": "Mercedes",
            "model": "F1 W08 EQ Power",
            "teamname": "Mercedes-AMG Petronas Motorsport",
            "driver": {
                "id": "111",
                "firstname": "Lewis",
                "lastname": "Hamilton",
                "age": "29"
            },
            "codriver": {
                "id": "222",
                "firstname": "Valtteri",
                "lastname": "Bottas",
                "age": "32"
            }
        },
        {
            "id": "def",
            "car": "Ferrari",
            "model": "SF70H",
            "teamname": "Scuderia Ferrari",
            "borrower": {
                "id": "333",
                "firstname": "Sebastian",
                "lastname": "Vettel",
                "age": "30"
            },
            "coborrower": {
                "id": "444",
                "firstname": "Kimi",
                "lastname": "Räikkönen",
                "age": "37"
            }
        }
    ]
}
</code>```

On JSON deserialization I am getting below error:-

```<code>{
    "summary": "Bad Request",
    "details": "Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'ParticipantContract' because the type requires a JSON object (e.g. {\"name\":\"value\"}) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON object (e.g. {\"name\":\"value\"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.\r\nPath '', line 1, position 1."
}
</code>```

Can you help me with what I am missing in this? Is there something additional that needs to be done?

答:
As I can see your JSON object is not valid

```<code>    {
        "raceId" : 1  // you missed comma here
        "participants": [
         {
</code>```

Just checking for any other mistake in your JSON object and passing a valid JSON will fix the error.

Body:
I am trying to use JSONPatch(KevinDockx version) in my WCF REST API(ASP.NET v4.5). My operation contract is as below:-

[OperationContract]
[WebInvoke(UriTemplate = "/{raceId}/participants", Method = "PATCH")]
void UpdateRace(string id, JsonPatchDocument<ParticipantContract[]> participantsContract);

And implementation as follows :-

public void UpdateRace(string id, JsonPatchDocument<ParticipantContract[]> participantsContract)
{
    //Someoperation
}

My data is like the below format where I want to perform add, update delete, move and swap operations on the participants array.

{
    "raceId" : 1
    "participants": [
        {
            "id": "abc",
            "car": "Mercedes",
            "model": "F1 W08 EQ Power",
            "teamname": "Mercedes-AMG Petronas Motorsport",
            "driver": {
                "id": "111",
                "firstname": "Lewis",
                "lastname": "Hamilton",
                "age": "29"
            },
            "codriver": {
                "id": "222",
                "firstname": "Valtteri",
                "lastname": "Bottas",
                "age": "32"
            }
        },
        {
            "id": "def",
            "car": "Ferrari",
            "model": "SF70H",
            "teamname": "Scuderia Ferrari",
            "borrower": {
                "id": "333",
                "firstname": "Sebastian",
                "lastname": "Vettel",
                "age": "30"
            },
            "coborrower": {
                "id": "444",
                "firstname": "Kimi",
                "lastname": "Räikkönen",
                "age": "37"
            }
        }
    ]
}

On JSON deserialization I am getting below error:-

{
    "summary": "Bad Request",
    "details": "Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'ParticipantContract' because the type requires a JSON object (e.g. {\"name\":\"value\"}) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON object (e.g. {\"name\":\"value\"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.\r\nPath '', line 1, position 1."
}

Can you help me with what I am missing in this? Is there something additional that needs to be done?

Body:
As I can see your JSON object is not valid

    {
        "raceId" : 1  // you missed comma here
        "participants": [
         {

Just checking for any other mistake in your JSON object and passing a valid JSON will fix the error.


问:
tokenltk word_tokenize() tokenizes the same word two different ways in different functions
I have a name of a tennis player that apparently is not parsed correctly by pandas. It is "radwa?ska". I have two functions where I tokenize using the word_tokenize() function.
It tokenizes the sentence in two different ways
 in the two different functions. How do I get the second one to go the first way

['radwa?ska']

['radwa','?','ska']

Here's the code in both the functions.

first function:

word_tokenize(keyword) the keyword is 'martina hingis, nadia petrova, agnieszka radwa?ska'

and in the second function is:

word_tokenize(content[j]) where content[j] is 'agnieszka radwa?ska'
.

答:
For both sentence in your original post, they should return the same output:

```<code>>>> from nltk import word_tokenize
>>> text1 = 'martina hingis, nadia petrova, agnieszka radwa?ska'
>>> text2 = 'agnieszka radwa?ska'

>>> word_tokenize(text1)
['martina', 'hingis', ',', 'nadia', 'petrova', ',', 'agnieszka', 'radwa', '?', 'ska']

>>> word_tokenize(text2)
['agnieszka', 'radwa', '?', 'ska']
</code>```

It's because the TreebankWordTokenizer object behind word_tokenize always always puts a space before and after a question mark at https://github.com/nltk/nltk/blob/develop/nltk/tokenize/treebank.py#L80

One can hack some ways to disable that regex but it will cause problems somewhere else down the road.

But I urge you to take a closer look at how you're reading/collecting your data, the fact that radwa?ska appears hint at some encoding problems exists upstream before tokenization. The correct reading of the file/stream would have got you radwańska.

See also

Unicode (UTF-8) reading and writing to files in Python

Python Requests and Unicode

Body:
For both sentence in your original post, they should return the same output:

>>> from nltk import word_tokenize
>>> text1 = 'martina hingis, nadia petrova, agnieszka radwa?ska'
>>> text2 = 'agnieszka radwa?ska'

>>> word_tokenize(text1)
['martina', 'hingis', ',', 'nadia', 'petrova', ',', 'agnieszka', 'radwa', '?', 'ska']

>>> word_tokenize(text2)
['agnieszka', 'radwa', '?', 'ska']

It's because the TreebankWordTokenizer object behind word_tokenize always always puts a space before and after a question mark at https://github.com/nltk/nltk/blob/develop/nltk/tokenize/treebank.py#L80

One can hack some ways to disable that regex but it will cause problems somewhere else down the road.

But I urge you to take a closer look at how you're reading/collecting your data, the fact that radwa?ska appears hint at some encoding problems exists upstream before tokenization. The correct reading of the file/stream would have got you radwańska.

See also

Unicode (UTF-8) reading and writing to files in Python

Python Requests and Unicode


问:
FileDialouge Filter type not accepting .tiproj
I am trying to filter the file type in the openfiledialouge but it is not accepting .tiproj it saying invalid file type.</p>

```<code> Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

                  dlg.DefaultExt = ".tiproj";
                  dlg.Filter = "*.tiproj";
</code>```

答:
Below format worked for me.</p>

```<code> Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
 dlg.Filter = "tiproj files (*.tiproj)|*.tiproj";
</code>```

Body:
I am trying to filter the file type in the openfiledialouge but it is not accepting .tiproj it saying invalid file type.

 Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

                  dlg.DefaultExt = ".tiproj";
                  dlg.Filter = "*.tiproj";

Body:
Below format worked for me.

 Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
 dlg.Filter = "tiproj files (*.tiproj)|*.tiproj";


问:
Compare key and values of one nested dictionary in other nested dictionary
I am trying to recursively compare below two python dictionaries:

```<code>expectededr = {'uid': 'e579b8cb-7d9f-4c0b-97de-a03bb52a1ec3', 'attempted': {'smpp': {'registeredDelivery': 0}, 'status': 'success', 'OATON': 1, 'OANPI': 1, 'DATON': 1, 'DANPI': 1, 'OA': '12149921220', 'DA': '1514525404'}, 'customerID': 'customer01', 'productID': 'product'}

edr = {'Category': 'NO', 'Type': 'mt', 'uid': 'e579b8cb-7d9f-4c0b-97de-a03bb52a1ec3', 'protocolID': 'smpp', 'direction': 'attempted', 'attempted': {'status': 'success', 'OANPI': 1, 'DATON': 1, 't2': 1512549691602, 'DANPI': 1, 'OA': '12149921220', 'DA': '1514525404', 'smpp': {'fragmented': False, 'sequenceID': 1, 'registeredDelivery': 0, 'messageID': '4e7b48ad-b39e-4e91-a7bb-2de463e4a6ee', 'srcPort': 39417, 'messageType': 4, 'Status': 0, 'ESMClass': 0, 'dstPort': 0, 'size': 0}, 'OATON': 1, 'PID': 0, 't1': 1512549691602}, 'customerID': 'customer01', 'productID': 'product'}
</code>```

I am trying to compare the in a way that find and compare the key and value of first dictionary in second and if matching then print PASS else print FAIL.

```<code>for key in expectededr:
   if expectededr[key] == edr[key]:
       print("PASS")
   else:
       print("FAIL")
</code>```

Output:

```<code>FAIL
PASS
PASS
PASS
</code>```

Above code is not able to compare all the keys and values as these are nested dictionaries.

As you can see below, if i print key and values above i see that its not going in sub dictionary and missing their keys:

```<code>for key in expectededr:
    if expectededr[key] == edr[key]:
        print(expectededr[key])
        print(edr[key])
</code>```

Output:

```<code>customer01
customer01
e579b8cb-7d9f-4c0b-97de-a03bb52a1ec3
e579b8cb-7d9f-4c0b-97de-a03bb52a1ec3
product
product
</code>```

Could someone help to update this code so that I can do the comparision in these nested dictionaries ?

答:
Simple way :</p>

```<code>for i in edr.keys():
    if i in expectededr.keys():
        print 'true : key'+i
    else:
        print 'fail : key'+ i
</code>```

Body:
I am trying to recursively compare below two python dictionaries:

expectededr = {'uid': 'e579b8cb-7d9f-4c0b-97de-a03bb52a1ec3', 'attempted': {'smpp': {'registeredDelivery': 0}, 'status': 'success', 'OATON': 1, 'OANPI': 1, 'DATON': 1, 'DANPI': 1, 'OA': '12149921220', 'DA': '1514525404'}, 'customerID': 'customer01', 'productID': 'product'}

edr = {'Category': 'NO', 'Type': 'mt', 'uid': 'e579b8cb-7d9f-4c0b-97de-a03bb52a1ec3', 'protocolID': 'smpp', 'direction': 'attempted', 'attempted': {'status': 'success', 'OANPI': 1, 'DATON': 1, 't2': 1512549691602, 'DANPI': 1, 'OA': '12149921220', 'DA': '1514525404', 'smpp': {'fragmented': False, 'sequenceID': 1, 'registeredDelivery': 0, 'messageID': '4e7b48ad-b39e-4e91-a7bb-2de463e4a6ee', 'srcPort': 39417, 'messageType': 4, 'Status': 0, 'ESMClass': 0, 'dstPort': 0, 'size': 0}, 'OATON': 1, 'PID': 0, 't1': 1512549691602}, 'customerID': 'customer01', 'productID': 'product'}

I am trying to compare the in a way that find and compare the key and value of first dictionary in second and if matching then print PASS else print FAIL.

for key in expectededr:
   if expectededr[key] == edr[key]:
       print("PASS")
   else:
       print("FAIL")

Output:

FAIL
PASS
PASS
PASS

Above code is not able to compare all the keys and values as these are nested dictionaries.

As you can see below, if i print key and values above i see that its not going in sub dictionary and missing their keys:

for key in expectededr:
    if expectededr[key] == edr[key]:
        print(expectededr[key])
        print(edr[key])

Output:

customer01
customer01
e579b8cb-7d9f-4c0b-97de-a03bb52a1ec3
e579b8cb-7d9f-4c0b-97de-a03bb52a1ec3
product
product

Could someone help to update this code so that I can do the comparision in these nested dictionaries ?

Body:
Simple way :

for i in edr.keys():
    if i in expectededr.keys():
        print 'true : key'+i
    else:
        print 'fail : key'+ i


问:
send sms from SMSPortalFragment not working
I have been trying to send test messages from using send_sms api. My SMSPortalFragment.java code show no error. Also there is no other error shown in Logcat.

The code builds and installs in the Galaxy S8.

The app runs fun.

Going to fragment_smsportal.xml is working fine.

I can type in my name and message.

On button click it asks for my PERMISSION in runtime.

NO MESSAGE IS SENT EVEN AFTER I ALLOW PERMISSION.

java code:

```<code>private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;

Button sendButon;
EditText fullName;
EditText textMessage;
String phoneNo = "***********";
String name;
String message;
String sendMessage;

public SMSPortalFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View smsportal = inflater.inflate(R.layout.fragment_smsportal, container, false);

    fullName = (EditText) smsportal.findViewById(R.id.fullName);
    textMessage = (EditText) smsportal.findViewById(R.id.textMessage);
    sendButon = (Button) smsportal.findViewById(R.id.sendButon);

    sendButon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            sendSMSMessage();
        }
    });

    return smsportal;
}

private void sendSMSMessage() {
    name = fullName.getText().toString();
    message = textMessage.getText().toString();
    sendMessage = name + " " + message;

    if (ContextCompat.checkSelfPermission(getActivity(),
            Manifest.permission.SEND_SMS)
            != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                Manifest.permission.SEND_SMS)) {
        } else {
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.SEND_SMS},
                    MY_PERMISSIONS_REQUEST_SEND_SMS);
        }
    }
}
@Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_SEND_SMS: {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                SmsManager smsManager = SmsManager.getDefault();
                smsManager.sendTextMessage(phoneNo, null, sendMessage, null, null);
                Toast.makeText(getActivity(),"SMS sent.", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getActivity(),"SMS failed, please try again.", Toast.LENGTH_LONG).show();
            }
        }
    }

}
</code>```

Can anyone tell me what I am doing wrong?

PS: I removed my phone number from this code for security concern.

答:
Do not write your send logic in onRequestPermissionsResult()
and

Try this...

Manifest permission

```<code><uses-permission-sdk-23 android:name="android.permission.SEND_SMS"/>
</code>```

and here is the snippet

```<code>   try {
            Bundle msgDataBundle = intent.getExtras();
            String mobileNumber = msgDataBundle.getString("MobileNumber");
            SmsManager smsManager = SmsManager.getDefault();
            //  smsManager.sendTextMessage(mobileNumber,null,"sam",null,null);
            smsManager.sendTextMessage(mobileNumber, null, "Test Sample Message Text", null, null);
            Toast.makeText(context, "SMS Sent!", Toast.LENGTH_LONG).show();
            Log.d("---", "Sent");

        } catch (Exception e) {
            Toast.makeText(context, "SMS faild, please try again.", Toast.LENGTH_LONG).show();
            Log.d("---", "Fail");
            e.printStackTrace();
        }
</code>```

Body:
I have been trying to send test messages from using send_sms api. My SMSPortalFragment.java code show no error. Also there is no other error shown in Logcat.

The code builds and installs in the Galaxy S8.

The app runs fun.

Going to fragment_smsportal.xml is working fine.

I can type in my name and message.

On button click it asks for my PERMISSION in runtime.

NO MESSAGE IS SENT EVEN AFTER I ALLOW PERMISSION.

java code:

private static final int MY_PERMISSIONS_REQUEST_SEND_SMS =0 ;

Button sendButon;
EditText fullName;
EditText textMessage;
String phoneNo = "***********";
String name;
String message;
String sendMessage;

public SMSPortalFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View smsportal = inflater.inflate(R.layout.fragment_smsportal, container, false);

    fullName = (EditText) smsportal.findViewById(R.id.fullName);
    textMessage = (EditText) smsportal.findViewById(R.id.textMessage);
    sendButon = (Button) smsportal.findViewById(R.id.sendButon);

    sendButon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            sendSMSMessage();
        }
    });

    return smsportal;
}

private void sendSMSMessage() {
    name = fullName.getText().toString();
    message = textMessage.getText().toString();
    sendMessage = name + " " + message;

    if (ContextCompat.checkSelfPermission(getActivity(),
            Manifest.permission.SEND_SMS)
            != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                Manifest.permission.SEND_SMS)) {
        } else {
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.SEND_SMS},
                    MY_PERMISSIONS_REQUEST_SEND_SMS);
        }
    }
}
@Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_SEND_SMS: {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                SmsManager smsManager = SmsManager.getDefault();
                smsManager.sendTextMessage(phoneNo, null, sendMessage, null, null);
                Toast.makeText(getActivity(),"SMS sent.", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getActivity(),"SMS failed, please try again.", Toast.LENGTH_LONG).show();
            }
        }
    }

}

Can anyone tell me what I am doing wrong?

PS: I removed my phone number from this code for security concern.

Body:
Do not write your send logic in onRequestPermissionsResult()
and

Try this...

Manifest permission

<uses-permission-sdk-23 android:name="android.permission.SEND_SMS"/>

and here is the snippet

   try {
            Bundle msgDataBundle = intent.getExtras();
            String mobileNumber = msgDataBundle.getString("MobileNumber");
            SmsManager smsManager = SmsManager.getDefault();
            //  smsManager.sendTextMessage(mobileNumber,null,"sam",null,null);
            smsManager.sendTextMessage(mobileNumber, null, "Test Sample Message Text", null, null);
            Toast.makeText(context, "SMS Sent!", Toast.LENGTH_LONG).show();
            Log.d("---", "Sent");

        } catch (Exception e) {
            Toast.makeText(context, "SMS faild, please try again.", Toast.LENGTH_LONG).show();
            Log.d("---", "Fail");
            e.printStackTrace();
        }


问:
Pulse icon or element color for one minute with javascript/angularjs
I would create a pulse color effect with a max duration of one minute. To have this effect with css I can do something like this:

@-webkit-keyframes pulse {
  0% { background-color: #ed8c55; }
  50% { background-color: #FFF; }
  100% { background-color: #ed8c55; }
}

@-moz-keyframes pulse {
  0% { background-color: #ed8c55; }
  50% { background-color: #FFF; }
  100% { background-color: #ed8c55; }
}

@-o-keyframes pulse {
  0% { background-color: #ed8c55; }
  50% { background-color: #FFF; }
  100% { background-color: #ed8c55; }
}

@keyframes pulse {
  0% { background-color: #ed8c55; }
  50% { background-color: #FFF; }
  100% { background-color: #ed8c55; }
}

.element {
  width: 50px;
  height: 50px;
  background: #ed8c55;
  -webkit-animation: pulse 3s infinite; /* Safari 4+ */
  -moz-animation:    pulse 3s infinite; /* Fx 5+ */
  -o-animation:      pulse 3s infinite; /* Opera 12+ */
  animation:         pulse 3s infinite; /* IE 10+, Fx 29+ */
}
```

<pre class="lang-html prettyprint-override"><code><div class="element"></div>
</code>```

But in this one I can't control the time. Particularly, I would make this effect in an icon inside a button

```<code><md-button aria-label="Info" id="info" title="info" ng-click="openInfo()" class="md-icon-button">
  <i class="zmdi zmdi-help red-color"></i>
</md-button>
</code>```

That  element should pulse for max one minute in red color. Is this possible do it with angularjs or simply javascript?

答:
But in this one I can't control the time

You can by using animation-iteration-count. As your animation takes 3 seconds you can give it a value of 20:

```<code>.element {
  width: 50px;
  height: 50px;
   background: #ed8c55;
  -webkit-animation: pulse 3s 20; /* Safari 4+ */
  -moz-animation:    pulse 3s 20; /* Fx 5+ */
  -o-animation:      pulse 3s 20; /* Opera 12+ */
  animation:         pulse 3s 20; /* IE 10+, Fx 29+ */
}
</code>```

Body:
I would create a pulse color effect with a max duration of one minute. To have this effect with css I can do something like this:

@-webkit-keyframes pulse {
  0% { background-color: #ed8c55; }
  50% { background-color: #FFF; }
  100% { background-color: #ed8c55; }
}

@-moz-keyframes pulse {
  0% { background-color: #ed8c55; }
  50% { background-color: #FFF; }
  100% { background-color: #ed8c55; }
}

@-o-keyframes pulse {
  0% { background-color: #ed8c55; }
  50% { background-color: #FFF; }
  100% { background-color: #ed8c55; }
}

@keyframes pulse {
  0% { background-color: #ed8c55; }
  50% { background-color: #FFF; }
  100% { background-color: #ed8c55; }
}

.element {
  width: 50px;
  height: 50px;
  background: #ed8c55;
  -webkit-animation: pulse 3s infinite; /* Safari 4+ */
  -moz-animation:    pulse 3s infinite; /* Fx 5+ */
  -o-animation:      pulse 3s infinite; /* Opera 12+ */
  animation:         pulse 3s infinite; /* IE 10+, Fx 29+ */
}

But in this one I can't control the time. Particularly, I would make this effect in an icon inside a button

<md-button aria-label="Info" id="info" title="info" ng-click="openInfo()" class="md-icon-button">

</md-button>

That  element should pulse for max one minute in red color. Is this possible do it with angularjs or simply javascript?

Body:
But in this one I can't control the time

You can by using animation-iteration-count. As your animation takes 3 seconds you can give it a value of 20:

.element {
  width: 50px;
  height: 50px;
   background: #ed8c55;
  -webkit-animation: pulse 3s 20; /* Safari 4+ */
  -moz-animation:    pulse 3s 20; /* Fx 5+ */
  -o-animation:      pulse 3s 20; /* Opera 12+ */
  animation:         pulse 3s 20; /* IE 10+, Fx 29+ */
}


问:
JSON schema validation by value
I am trying to validate the value of one field in my JSON with the respect to the other field. It will be clear in the example.

I have a field "interface", that is an "enum": ["01", "02"]
Then I have a field "template", that is an "enum": ["01", "02", "03", "04", "05"].

Now what I want to achieve is:

IF "interface" is "01", THEN "template" can be: ["01", "02", "03", "04"].

IF "interface" is "02", THEN "template" can be: ["01", "02", "03", "04", "05"].

Is that possible to do with JSON schema v4?

答:
Yes, you can use "oneOf" with 2 definitions.

The first has interface with value 01 (use an enum with only one value) and template with all the possible values (for when interface is 01), again, using enums.

And the 2nd definition for the interface with value 02 and the template with the possible values for when interface is 02.

See these on how to use oneOf:

https://spacetelescope.github.io/understanding-json-schema/reference/combining.html#oneof

http://queirozf.com/entries/json-schema-examples

Title: JSON schema validation by value


问:
C# .NET: how to pause and resume a program execution on a keypress?
it's a .NET non GUI application. It is specified as a console application, but the console is not really used. what the application does is  GUI testing of other applications</p>

答:
Ok It Should look like this..

```<code>//Assuming the thread name given is 'newthread'
//First Start a thread

newthread.Start();

//use Console Key Class to read a key from keyboard
ConsoleKeyInfo cki = new ConsoleKeyInfo();
cki = Console.ReadKey(true);

//I am using letter 'p' to pause
if (cki.Key == ConsoleKey.P)
{
  newthread.Suspend();
  Console.WriteLine("Process Is Paused,Press 'Enter' to Continue...");
}

//Thread Resumption can only occur through another thread
//If the thread control has passed on to the main function
//resume it from there

// Resuming Thread if paused
if (newthread.ThreadState>0)
{
  ConsoleKeyInfo ckm = new ConsoleKeyInfo();
  ckm = Console.ReadKey(true);
  if (ckm.Key == ConsoleKey.Enter)
   {
     Console.WriteLine("Resuming Process...");
     newthread.Resume();
   }
}
</code>```

Note:This should work fine for now, but in reality you should synchronise your threads. When you will run the program then it will say that the pause and resume functions are obsolete. It will tell you to synchronise the threads.

ContentLicense: CC BY-SA 2.5

Body:
Ok It Should look like this..

//Assuming the thread name given is 'newthread'
//First Start a thread

newthread.Start();

//use Console Key Class to read a key from keyboard
ConsoleKeyInfo cki = new ConsoleKeyInfo();
cki = Console.ReadKey(true);

//I am using letter 'p' to pause
if (cki.Key == ConsoleKey.P)
{
  newthread.Suspend();
  Console.WriteLine("Process Is Paused,Press 'Enter' to Continue...");
}

//Thread Resumption can only occur through another thread
//If the thread control has passed on to the main function
//resume it from there

// Resuming Thread if paused
if (newthread.ThreadState>0)
{
  ConsoleKeyInfo ckm = new ConsoleKeyInfo();
  ckm = Console.ReadKey(true);
  if (ckm.Key == ConsoleKey.Enter)
   {
     Console.WriteLine("Resuming Process...");
     newthread.Resume();
   }
}

Note:This should work fine for now, but in reality you should synchronise your threads. When you will run the program then it will say that the pause and resume functions are obsolete. It will tell you to synchronise the threads.


问:
stratified sampling with fixed proportions of observation types in R
I have a sample where 50% of the observations are White and 50% African-American.

I would like to obtain a random subsample where such proportion is modified to 80% White and 20% African-American.

I have tried the command stratified but I could not find an option allowing me to allocate shares to the stratifying criterion.

Thank you in advance for your help!

答:
If your original dataset had 100 rows (50 white and 50 African-American) then 80% would be 40 samples, and 20% would be 10 samples. Knowing these values, you can try: stratified(mydf, "group", size = c("White" = 40, "African-American" = 10)).

Example:

```<code>mydf <- data.frame(group = rep(c("White", "African-American"), each = 50), value = 1:100)
mydf
library(splitstackshape)
set.seed(1)
x <- stratified(mydf, "group", size = c("White" = 40, "African-American" = 10))
summary(x)
 #              group        value
 # African-American:10   Min.   : 1.00
 # White           :40   1st Qu.:15.25
 #                       Median :31.00
 #                       Mean   :34.88
 #                       3rd Qu.:47.50
 #                       Max.   :93.00
</code>```

Body:
If your original dataset had 100 rows (50 white and 50 African-American) then 80% would be 40 samples, and 20% would be 10 samples. Knowing these values, you can try: stratified(mydf, "group", size = c("White" = 40, "African-American" = 10)).

Example:

mydf <- data.frame(group = rep(c("White", "African-American"), each = 50), value = 1:100)
mydf
library(splitstackshape)
set.seed(1)
x <- stratified(mydf, "group", size = c("White" = 40, "African-American" = 10))
summary(x)
 #              group        value
 # African-American:10   Min.   : 1.00
 # White           :40   1st Qu.:15.25
 #                       Median :31.00
 #                       Mean   :34.88
 #                       3rd Qu.:47.50
 #                       Max.   :93.00


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

This is the code for profile.php:

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

session_start();

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

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

This is the code for the Login:

```<code>      session_start();

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

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

        $Email_Ses = $_SESSION['Email_Ses'];

        $Name_Ses =   $_SESSION['Name_Ses'];

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

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

But i get this error

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

the error is on this line:

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

答:
If you were to use prepared statements you could avoid nasty surprises due to sql injection.

```<code><?php

    /* profile.php*/
    session_start();

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

    $sql = "select `email`, `first_name`, `last_name` from `users` where `email`=?";
    $stmt=$conn->prepare( $sql );

    if( $stmt && isset( $_SESSION['Email_Ses'] ) ){

        $stmt->bind_param('s', $_SESSION['Email_Ses'] );
        $result=$stmt->execute();

        if( $result ){
            $stmt->store_result();
            $stmt->bind_result( $email, $firstname, $lastname );
            $stmt->fetch();
            $stmt->free_result();
            $stmt->close();

            echo "email: $email, Name: $firstname $lastname";
        } else {
            echo "No results"
        }
    }
?>
</code>```

The login script is - or should be a little different. Generally the accepted way of storing a user's password is to do so in a hashed format within the database - but this depends upon the version of PHP that you have - I think 5.6+ has password_hash and password_verify natively - before that there is a 3rd party script to achieve the same thing. I'd strongly suggest that the user's password is hashed!

```<code><?php
    /* login.php */
    session_start();

    if( isset( $_POST['email'],$_POST['name'],$_POST['password'] ) ){

        $email=$_POST['email'];
        $name=$_POST['name'];
        $password=$_POST['password'];

        $sql='select `password` from `users` where `email`=?';
        $stmt=$conn->prepare( $sql );
        if( $stmt ){
            $stmt->bind_param('s',$email);
            $stmt->execute();
            $stmt->store_result();
            $stmt->bind_result( $dbpwd );
            $stmt->fetch();
            $stmt->free_result();
            $stmt->close();

            /*
                here is where, if the password was hashed, you would use `password_verify`
                but in this case it is not.
            */

            if( $dbpwd==$password ){
                /* ok */

                $_SESSION['Email_Ses'] = $email;
                $_SESSION['Name_Ses'] = $name;

            } else {
                /* bogus */
            }
        }
    }
?>
</code>```

For the record - this is not tested but should help get started using prepared statements. For more info regarding the password functions mentioned above try password_hash and password_verify

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

This is the code for profile.php:

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

session_start();

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

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

This is the code for the Login:

      session_start();

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

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

        $Email_Ses = $_SESSION['Email_Ses'];

        $Name_Ses =   $_SESSION['Name_Ses'];

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

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

But i get this error

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

the error is on this line:

if (mysqli_num_rows($result) > 0) {

Body:
If you were to use prepared statements you could avoid nasty surprises due to sql injection.

<?php

    /* profile.php*/
    session_start();

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

    $sql = "select `email`, `first_name`, `last_name` from `users` where `email`=?";
    $stmt=$conn->prepare( $sql );

    if( $stmt && isset( $_SESSION['Email_Ses'] ) ){

        $stmt->bind_param('s', $_SESSION['Email_Ses'] );
        $result=$stmt->execute();

        if( $result ){
            $stmt->store_result();
            $stmt->bind_result( $email, $firstname, $lastname );
            $stmt->fetch();
            $stmt->free_result();
            $stmt->close();

            echo "email: $email, Name: $firstname $lastname";
        } else {
            echo "No results"
        }
    }
?>

The login script is - or should be a little different. Generally the accepted way of storing a user's password is to do so in a hashed format within the database - but this depends upon the version of PHP that you have - I think 5.6+ has password_hash and password_verify natively - before that there is a 3rd party script to achieve the same thing. I'd strongly suggest that the user's password is hashed!

<?php
    /* login.php */
    session_start();

    if( isset( $_POST['email'],$_POST['name'],$_POST['password'] ) ){

        $email=$_POST['email'];
        $name=$_POST['name'];
        $password=$_POST['password'];

        $sql='select `password` from `users` where `email`=?';
        $stmt=$conn->prepare( $sql );
        if( $stmt ){
            $stmt->bind_param('s',$email);
            $stmt->execute();
            $stmt->store_result();
            $stmt->bind_result( $dbpwd );
            $stmt->fetch();
            $stmt->free_result();
            $stmt->close();

            /*
                here is where, if the password was hashed, you would use `password_verify`
                but in this case it is not.
            */

            if( $dbpwd==$password ){
                /* ok */

                $_SESSION['Email_Ses'] = $email;
                $_SESSION['Name_Ses'] = $name;

            } else {
                /* bogus */
            }
        }
    }
?>

For the record - this is not tested but should help get started using prepared statements. For more info regarding the password functions mentioned above try password_hash and password_verify


问:
table keeps resizing not overflow
I'm trying to make my table overflow on the x axis instead of resizing once it gets past 900px browser width.

Here is my code:

```<code><div className='jobTableTop'>
<table className='jobsTable'>
  <tbody>
    <tr className='jobsTableHeader'>
      <td style={{"color": "lightgray"}}>BY</td>
      <td style={{"color": "lightgray"}}>JOB TITLE</td>
      <td style={{"color": "lightgray"}}>OPTION</td>
      <td style={{"color": "lightgray"}}>LOCATION</td>
      <td style={{"color": "lightgray"}}>WAGE</td>
      <td style={{"padding-top": "0px"}}></td>
    </tr>
    {this.props.dataToShow.map(function (item, index) {
      return (
        (index >= minItem && index <= maxItem) ?
          <tr key={item.id}>
            <td>{item.company}</td>
            <td>{item.title}</td>
            <td>{item.option}</td>
            <td>{item.location}</td>
            <td>{item.wage}</td>
            <td style={{"padding-top": "0px"}}>
              <a href={'/job-detail/' + item.id}>
                <Button className={classes.button} style={{"font-size": "20px"}} raised color="accent">
                  Apply
                </Button>
              </a>
            </td>
          </tr>
          :
          ''
        )})}
      </tbody>
    </table>
   </div>
</code>```

that is the jsx/html code

here is the css:

```<code>@media screen and (max-width: 900px){
    .jobsTable{
        overflow: hidden;
    }
}
.jobsTable tr {
border-bottom: 1px solid lightgray;
display: flex;
}
.jobsTable tr td {
    width: 16.6%;
    height: 40px;
    padding-top: 20px;
    font-size: 20px;
    vertical-align: middle;
    color: black;
}
</code>```

so when it goes under 900px i want it so that theres a scroll bar instead of the table going smaller no matter what i seem to do nothing makes it do this. Im trying to make it mobile compatible without making a separate version of the site.

edit changed:

all i changed was this.

```<code>.jobTableTop {
    width: 100%;
    overflow-x: scroll;
    overflow-y: hidden;
}
</code>```

i have to make the webpage around 750px instead of 900px. how would i achieve said goal.

答:
you must use @media media query and write your css like this:

```<code>@media screen and (max-width: 900px){
  .jobsTable{
    width: 100%;
    overflow-y: hidden;
    overflow-x: auto;
  }
}
</code>```

Title: table keeps resizing not overflow

Body:
I'm trying to make my table overflow on the x axis instead of resizing once it gets past 900px browser width.

Here is my code:

      BY
      JOB TITLE
      OPTION
      LOCATION
      WAGE

    {this.props.dataToShow.map(function (item, index) {
      return (
        (index >= minItem && index <= maxItem) ?

            {item.company}
            {item.title}
            {item.option}
            {item.location}
            {item.wage}

                <Button className={classes.button} style={{"font-size": "20px"}} raised color="accent">
                  Apply
                </Button>

          :
          ''
        )})}

that is the jsx/html code

here is the css:

@media screen and (max-width: 900px){
    .jobsTable{
        overflow: hidden;
    }
}
.jobsTable tr {
border-bottom: 1px solid lightgray;
display: flex;
}
.jobsTable tr td {
    width: 16.6%;
    height: 40px;
    padding-top: 20px;
    font-size: 20px;
    vertical-align: middle;
    color: black;
}

so when it goes under 900px i want it so that theres a scroll bar instead of the table going smaller no matter what i seem to do nothing makes it do this. Im trying to make it mobile compatible without making a separate version of the site.

edit changed:

all i changed was this.

.jobTableTop {
    width: 100%;
    overflow-x: scroll;
    overflow-y: hidden;
}

i have to make the webpage around 750px instead of 900px. how would i achieve said goal.

Body:
you must use @media media query and write your css like this:

@media screen and (max-width: 900px){
  .jobsTable{
    width: 100%;
    overflow-y: hidden;
    overflow-x: auto;
  }
}


问:
Hashtable underlying place holder?
I am trying to understand the HashTable data structure. I understand that in HashTable we first use HashFunction to coverts a key to hash Code and then using modulo operator to convert Hash code to  integer index and which is used to get the location in HashTable where data is placed.

At a high level, the flow is like this?

Key -> Hash Function -> Hash code -> Modulo operator -> integer index -> Store in HashTable

Since the key is stored based on the index as emitted by the modulo operator, my doubt is, what is the underlying data structure which is used to hold the actual data? Is it an array, for array can be accessed using Index.

Can anyone help me understand this?

答:
Though it completely depends on implementation, I would agree that underlying data structure would be array with linked list, since array is convinient to access elements at low cost, while linked list is necessary to handle hash collisions.

Here is example of details how it is implemented in java openjdk Hashtable

Initially it creates array with initial capacity:

```<code>table = new Entry<?,?>[initialCapacity];
</code>```

It checks for capacity threshold everytime when new element is added. When threshold limit is reached it performs rehashing and creates a new array which is double size of old array

```<code>    int newCapacity = (oldCapacity << 1) + 1;
    if (newCapacity - MAX_ARRAY_SIZE > 0) {
        if (oldCapacity == MAX_ARRAY_SIZE)
            // Keep running with MAX_ARRAY_SIZE buckets
            return;
        newCapacity = MAX_ARRAY_SIZE;
    }
    Entry<?,?>[] newMap = new Entry<?,?>[newCapacity];

    modCount++;
    threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
    table = newMap;
</code>```

Hashtable Entry forms a linked list. It is used in case of hash collisions, since index for 2 different values would become same and required value is checked through linked list.

```<code>private static class Entry<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Entry<K,V> next;
</code>```

You may want to check other more simple implementations of Hashtables for better understanding.

Title: Hashtable underlying place holder?

Body:
Though it completely depends on implementation, I would agree that underlying data structure would be array with linked list, since array is convinient to access elements at low cost, while linked list is necessary to handle hash collisions.

Here is example of details how it is implemented in java openjdk Hashtable

Initially it creates array with initial capacity:

table = new Entry<?,?>[initialCapacity];

It checks for capacity threshold everytime when new element is added. When threshold limit is reached it performs rehashing and creates a new array which is double size of old array

    int newCapacity = (oldCapacity << 1) + 1;
    if (newCapacity - MAX_ARRAY_SIZE > 0) {
        if (oldCapacity == MAX_ARRAY_SIZE)
            // Keep running with MAX_ARRAY_SIZE buckets
            return;
        newCapacity = MAX_ARRAY_SIZE;
    }
    Entry<?,?>[] newMap = new Entry<?,?>[newCapacity];

    modCount++;
    threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
    table = newMap;

Hashtable Entry forms a linked list. It is used in case of hash collisions, since index for 2 different values would become same and required value is checked through linked list.

private static class Entry<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Entry<K,V> next;

You may want to check other more simple implementations of Hashtables for better understanding.


问:
split character data into numbers and letters
I have a vector of character data.  Most of the elements in the vector consist of one or more letters followed by one or more numbers.   I wish to split each element in the vector into the character portion and the number portion.  I found a similar question on Stackoverflow.com here:

split a character from a number with multiple digits

However, the answer given above does not seem to work completely in my case or I am doing something wrong.  An example vector is below:

```<code>my.data <- c("aaa", "b11", "b21", "b101", "b111", "ccc1", "ddd1", "ccc20", "ddd13")

# I can obtain the number portion using:
gsub("[^[:digit:]]", "", my.data)

# However, I cannot obtaining the character portion using:
gsub("[:digit:]", "", my.data)
</code>```

How can I obtain the character portion?  I am using R version 2.14.1 on a Windows 7 64-bit machine.

答:
Since none of the previous answers use tidyr::separate here it goes:

library(tidyr)

df <- data.frame(mycol = c("APPLE348744", "BANANA77845", "OATS2647892", "EGG98586456"))

df %>%
  separate(mycol,
           into = c("text", "num"),
           sep = "(?<=[A-Za-z])(?=[0-9])"
           )
```

Body:
I have a vector of character data.  Most of the elements in the vector consist of one or more letters followed by one or more numbers.   I wish to split each element in the vector into the character portion and the number portion.  I found a similar question on Stackoverflow.com here:

split a character from a number with multiple digits

However, the answer given above does not seem to work completely in my case or I am doing something wrong.  An example vector is below:

my.data <- c("aaa", "b11", "b21", "b101", "b111", "ccc1", "ddd1", "ccc20", "ddd13")

# I can obtain the number portion using:
gsub("[^[:digit:]]", "", my.data)

# However, I cannot obtaining the character portion using:
gsub("[:digit:]", "", my.data)

How can I obtain the character portion?  I am using R version 2.14.1 on a Windows 7 64-bit machine.


问:
Spring Boot multi module project with Gradle doesn't build
I'm working on a Spring Boot app with multiple modules and we're using Gradle to build it. Unfortunately I can't get the Gradle configuration right.

The project structure is this:

```<code>parent
  |
  + build.gradle
  |
  + settings.gradle
  |
  + core
  |   |
  |   + build.gradle
  |
  + apis
  |   |
  |   + build.gradle
  |
  + services
  |   |
  |   + build.gradle
  |
  + data
  |   |
  |   + build.gradle
</code>```

When I try to build the project, I get compilation errors like error: cannot find symbol saying, that the classes from data used in services aren't imported. And I assume this is true between all the modules.

My parent build.gradle looks like this:

```<code>buildscript {
    ext {
        springBootVersion = '2.0.0.BUILD-SNAPSHOT'
    }
    repositories {
        mavenCentral()
        maven { url "https://repo.spring.io/snapshot" }
        maven { url "https://repo.spring.io/milestone" }
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'eclipse'
apply plugin: 'idea'

allprojects {
    apply plugin: 'java'
    apply plugin: 'org.springframework.boot'
    apply plugin: 'io.spring.dependency-management'

    group = 'com.example'
    version = '0.0.1-SNAPSHOT'
    sourceCompatibility = 1.8
    targetCompatibility = 1.8

    repositories {
        mavenCentral()
        maven { url "https://repo.spring.io/snapshot" }
        maven { url "https://repo.spring.io/milestone" }
    }

    dependencies {
        testCompile('org.springframework.boot:spring-boot-starter-test')
    }
}

dependencies {
    compile project(':data')
    compile project(':services')
    compile project(':apis')
    compile project(':core')
}

jar {
    baseName = 'my-jar'
    version = '0.0.1-SNAPSHOT'
}
</code>```

settings.gradle:

```<code>rootProject.name = 'my-app'
include ':apis'
include ':core'
include ':data'
include ':services'
</code>```

one of children (core) has this in it's build.gradle:

```<code>dependencies {
    compile('org.springframework.boot:spring-boot-starter-actuator')
    compile('org.springframework.boot:spring-boot-starter-quartz')
    compile('org.springframework.boot:spring-boot-starter-tomcat')
    runtime('com.h2database:h2')

    compile project(':data')
    compile project(':services')
    compile project(':apis')
}
</code>```

services build.gradle looks like this:

```<code>dependencies {
    compile('org.springframework.boot:spring-boot-starter-quartz')
    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    runtime('com.h2database:h2')

    compile project(':data')
}
</code>```

The other ones also declare only dependencies.

The dependency structure looks like this:

```<code>core - apis, services, data

apis - services, data

services - data

data -
</code>```

Example of the compilation errors:

```<code>/my-app/services/src/main/java/com/example/my-app/business/IssuedTokenService.java:3: error: package com.examples.data.dao does not exist import com.examples.data.dao.IssuedToken;

/my-app/services/src/main/java/com/example/my-app/business/IssuedTokenService.java:4: error: package com.examples.data.repository does not exist import com.examples.data.repository.IssuedTokenRepository;

/my-app/services/src/main/java/com/example/my-app/business/IssuedTokenService.java:12: error: cannot find symbol
    private IssuedTokenRepository issuedTokenRepository;

    symbol:   class IssuedTokenRepository
   location: class IssuedTokenService

/my-app/services/src/main/java/com/example/my-app/business/IssuedTokenService.java:15: error: cannot find symbol
   public void saveToken(IssuedToken issuedToken) {
                                  ^
   symbol:   class IssuedToken
   location: class IssuedTokenService
</code>```

答:
In your utility (data) projects put:

```<code>bootJar {
    enabled = false
}

jar {
    enabled = true
}
</code>```

If kotlin dsl

```<code>tasks.getByName<BootJar>("bootJar") {
    enabled = false
}

tasks.getByName<Jar>("jar") {
    enabled = true
}
</code>```

Body:
I'm working on a Spring Boot app with multiple modules and we're using Gradle to build it. Unfortunately I can't get the Gradle configuration right.

The project structure is this:

parent
  |
  + build.gradle
  |
  + settings.gradle
  |
  + core
  |   |
  |   + build.gradle
  |
  + apis
  |   |
  |   + build.gradle
  |
  + services
  |   |
  |   + build.gradle
  |
  + data
  |   |
  |   + build.gradle

When I try to build the project, I get compilation errors like error: cannot find symbol saying, that the classes from data used in services aren't imported. And I assume this is true between all the modules.

My parent build.gradle looks like this:

buildscript {
    ext {
        springBootVersion = '2.0.0.BUILD-SNAPSHOT'
    }
    repositories {
        mavenCentral()
        maven { url "https://repo.spring.io/snapshot" }
        maven { url "https://repo.spring.io/milestone" }
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'eclipse'
apply plugin: 'idea'

allprojects {
    apply plugin: 'java'
    apply plugin: 'org.springframework.boot'
    apply plugin: 'io.spring.dependency-management'

    group = 'com.example'
    version = '0.0.1-SNAPSHOT'
    sourceCompatibility = 1.8
    targetCompatibility = 1.8

    repositories {
        mavenCentral()
        maven { url "https://repo.spring.io/snapshot" }
        maven { url "https://repo.spring.io/milestone" }
    }

    dependencies {
        testCompile('org.springframework.boot:spring-boot-starter-test')
    }
}

dependencies {
    compile project(':data')
    compile project(':services')
    compile project(':apis')
    compile project(':core')
}

jar {
    baseName = 'my-jar'
    version = '0.0.1-SNAPSHOT'
}

settings.gradle:

rootProject.name = 'my-app'
include ':apis'
include ':core'
include ':data'
include ':services'

one of children (core) has this in it's build.gradle:

dependencies {
    compile('org.springframework.boot:spring-boot-starter-actuator')
    compile('org.springframework.boot:spring-boot-starter-quartz')
    compile('org.springframework.boot:spring-boot-starter-tomcat')
    runtime('com.h2database:h2')

    compile project(':data')
    compile project(':services')
    compile project(':apis')
}

services build.gradle looks like this:

dependencies {
    compile('org.springframework.boot:spring-boot-starter-quartz')
    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    runtime('com.h2database:h2')

    compile project(':data')
}

The other ones also declare only dependencies.

The dependency structure looks like this:

core - apis, services, data

apis - services, data

services - data

data -

Example of the compilation errors:

/my-app/services/src/main/java/com/example/my-app/business/IssuedTokenService.java:3: error: package com.examples.data.dao does not exist import com.examples.data.dao.IssuedToken;

/my-app/services/src/main/java/com/example/my-app/business/IssuedTokenService.java:4: error: package com.examples.data.repository does not exist import com.examples.data.repository.IssuedTokenRepository;

/my-app/services/src/main/java/com/example/my-app/business/IssuedTokenService.java:12: error: cannot find symbol
    private IssuedTokenRepository issuedTokenRepository;

    symbol:   class IssuedTokenRepository
   location: class IssuedTokenService

/my-app/services/src/main/java/com/example/my-app/business/IssuedTokenService.java:15: error: cannot find symbol
   public void saveToken(IssuedToken issuedToken) {
                                  ^
   symbol:   class IssuedToken
   location: class IssuedTokenService

Body:
In your utility (data) projects put:

bootJar {
    enabled = false
}

jar {
    enabled = true
}

If kotlin dsl

tasks.getByName<BootJar>("bootJar") {
    enabled = false
}

tasks.getByName<Jar>("jar") {
    enabled = true
}

ContentLicense: CC BY-SA 4.0


问:
Algorithm finding path in an undirected tree
Suppose I am given a undirected tree and I need to find a path(the only path) between two nodes.

What is the best algorithm to do it.I probably could use a Dijkstra's algorithm but there a probably something better for trees.

C++ example would be helpful but not necessary

Thank you

答:
Assuming each node has a pointer to its parent, then simply back-track up the tree towards the root from each start node.  Eventually, the two paths must intersect.  Testing for intersection could be as simple as maintaining a std::map of node addresses.

UPDATE

As you've updated your question to specify undirected trees, then the above isn't valid.  A simple approach is simply to perform a depth-first traversal starting at Node #1, eventually you'll hit Node #2.  This is O(n) in the size of the tree.  I'm not sure there's going to be a faster approach than that, assuming a completely general tree.


问:
NodeJs unzip stream
I need unzip some two level zip:

```<code>file1.zip
  - file1.1.zip
    - data.txt
  - file1.2.zip
  - file1.3.zip
</code>```

I need just data.txt in file1.1.zip inside file1.zip and I need ignore (entry.autodrain();) other entries.

This is info about zip:

```<code>apshenichnikov@IAS-WS-UX02:/tmp$ file /var/logs-storage/wcm/119/2017-11-01-119-TcVXBh5RPEHTm86y7sOvJc7TjyQcAc6bqZVawcniIPwyJpWlYqCBJ2XNqBj1ikVF.zip
/var/logs-storage/wcm/119/2017-11-01-119-TcVXBh5RPEHTm86y7sOvJc7TjyQcAc6bqZVawcniIPwyJpWlYqCBJ2XNqBj1ikVF.zip: Zip archive data, at least v4.5 to extract

apshenichnikov@IAS-WS-UX02:/tmp$ unzip -t /var/logs-storage/wcm/119/2017-11-01-119-TcVXBh5RPEHTm86y7sOvJc7TjyQcAc6bqZVawcniIPwyJpWlYqCBJ2XNqBj1ikVF.zip
Archive:  /var/logs-storage/wcm/119/2017-11-01-119-TcVXBh5RPEHTm86y7sOvJc7TjyQcAc6bqZVawcniIPwyJpWlYqCBJ2XNqBj1ikVF.zip
    testing: datamining_119_20171101_clickevent.zip   OK
    testing: datamining_119_20171101_impressionvisibility.zip   OK
    testing: datamining_119_20171101_conversion.zip   OK
No errors detected in compressed data of /var/logs-storage/wcm/119/2017-11-01-119-TcVXBh5RPEHTm86y7sOvJc7TjyQcAc6bqZVawcniIPwyJpWlYqCBJ2XNqBj1ikVF.zip.
</code>```

This is the code:

```<code>fs.createReadStream(source)
    .pipe(unzipper.Parse())
    .on('entry', (entry) =>
    {
        if (found || stop)
        {
            entry.autodrain();
            return;
        }

        var filePath = entry.path;
        var type = entry.type; // 'Directory' or 'File'
        //var size = entry.size; // might be undefined in some archives

        log.info(getMessage(ID, util.format("Entry: %s", filePath)));

        var outPath = path.join(target, filePath);

        if (
            filePath.match(
                new RegExp(
                    util.format(
                        "datamining_\d+_\d+_%s.*\.zip",
                        type
                    )
                )
            )
        ) {
            var outStream = fs.createWriteStream(outPath);
            entry.pipe(outStream);
            found = true;

            procLogStream.write(util.format(
                "%s Found: %s\r\n",
                utils.getCurrentDate(),
                filePath
            ));

            outStream.on('finish', () =>
            {
                if (!stop)
                {
                    cb();
                    //tmpdir.removeCallback();
                    console.log('out stream finish');
                }

                stop = true;
            }).on('error', (err) =>
            {
                if (!stop)
                {
                    cb(err);
                    //tmpdir.removeCallback();
                    console.log('out stream error');
                }

                stop = true;
            });
        } else {
            entry.autodrain();
        }
    })
    .on('error', (err) =>
    {
        console.log('zip stream error');
        console.log(err);
        if (!found && !stop) {
            cb(err);
            //tmpdir.removeCallback();
        }

        stop = true;
    })
    .on('finish', () =>
    {
        console.log('zip stream finish');
        if (!found && !stop) {
            cb();
            //tmpdir.removeCallback();
        }

        stop = true;
    });
</code>```

And these are the errors:

```<code>info: [utils/worker.js] 5a27a822cb569b2db8bc493d: Entry: datamining_119_20171101_clickevent.zip
zip stream error
Error: invalid signature: 0x83268e0
    at /home/apshenichnikov/NetBeansProjects/lps/node_modules/unzip/lib/parse.js:59:13
    at runCallback (timers.js:666:20)
    at tryOnImmediate (timers.js:639:5)
    at processImmediate [as _immediateCallback] (timers.js:611:5)
error: [utils/worker.js] 5a27a822cb569b2db8bc493d Error: invalid signature: 0x83268e0
error: [utils/worker.js] 5a27a822cb569b2db8bc493d: errored
zip stream error
{ Error: unexpected end of file
    at Zlib._handle.onerror (zlib.js:370:17) errno: -5, code: 'Z_BUF_ERROR' }
</code>```

I search much for library which will actually work, I tried tree...

I feel that there is no option in NodeJs to handle zip files...

Can you disprove my belief?

答:
You need to unzip the archive recursively. For that purpose a node module called "runzip" is already available. Github link: https://github.com/dherman/runzip

or, you can write a recursive function on our own, adding a check on filename

Title: NodeJs unzip stream

Body:
I need unzip some two level zip:

file1.zip
  - file1.1.zip
    - data.txt
  - file1.2.zip
  - file1.3.zip

I need just data.txt in file1.1.zip inside file1.zip and I need ignore (entry.autodrain();) other entries.

This is info about zip:

apshenichnikov@IAS-WS-UX02:/tmp$ file /var/logs-storage/wcm/119/2017-11-01-119-TcVXBh5RPEHTm86y7sOvJc7TjyQcAc6bqZVawcniIPwyJpWlYqCBJ2XNqBj1ikVF.zip
/var/logs-storage/wcm/119/2017-11-01-119-TcVXBh5RPEHTm86y7sOvJc7TjyQcAc6bqZVawcniIPwyJpWlYqCBJ2XNqBj1ikVF.zip: Zip archive data, at least v4.5 to extract

apshenichnikov@IAS-WS-UX02:/tmp$ unzip -t /var/logs-storage/wcm/119/2017-11-01-119-TcVXBh5RPEHTm86y7sOvJc7TjyQcAc6bqZVawcniIPwyJpWlYqCBJ2XNqBj1ikVF.zip
Archive:  /var/logs-storage/wcm/119/2017-11-01-119-TcVXBh5RPEHTm86y7sOvJc7TjyQcAc6bqZVawcniIPwyJpWlYqCBJ2XNqBj1ikVF.zip
    testing: datamining_119_20171101_clickevent.zip   OK
    testing: datamining_119_20171101_impressionvisibility.zip   OK
    testing: datamining_119_20171101_conversion.zip   OK
No errors detected in compressed data of /var/logs-storage/wcm/119/2017-11-01-119-TcVXBh5RPEHTm86y7sOvJc7TjyQcAc6bqZVawcniIPwyJpWlYqCBJ2XNqBj1ikVF.zip.

This is the code:

fs.createReadStream(source)
    .pipe(unzipper.Parse())
    .on('entry', (entry) =>
    {
        if (found || stop)
        {
            entry.autodrain();
            return;
        }

        var filePath = entry.path;
        var type = entry.type; // 'Directory' or 'File'
        //var size = entry.size; // might be undefined in some archives

        log.info(getMessage(ID, util.format("Entry: %s", filePath)));

        var outPath = path.join(target, filePath);

        if (
            filePath.match(
                new RegExp(
                    util.format(
                        "datamining_\d+_\d+_%s.*\.zip",
                        type
                    )
                )
            )
        ) {
            var outStream = fs.createWriteStream(outPath);
            entry.pipe(outStream);
            found = true;

            procLogStream.write(util.format(
                "%s Found: %s\r\n",
                utils.getCurrentDate(),
                filePath
            ));

            outStream.on('finish', () =>
            {
                if (!stop)
                {
                    cb();
                    //tmpdir.removeCallback();
                    console.log('out stream finish');
                }

                stop = true;
            }).on('error', (err) =>
            {
                if (!stop)
                {
                    cb(err);
                    //tmpdir.removeCallback();
                    console.log('out stream error');
                }

                stop = true;
            });
        } else {
            entry.autodrain();
        }
    })
    .on('error', (err) =>
    {
        console.log('zip stream error');
        console.log(err);
        if (!found && !stop) {
            cb(err);
            //tmpdir.removeCallback();
        }

        stop = true;
    })
    .on('finish', () =>
    {
        console.log('zip stream finish');
        if (!found && !stop) {
            cb();
            //tmpdir.removeCallback();
        }

        stop = true;
    });

And these are the errors:

info: [utils/worker.js] 5a27a822cb569b2db8bc493d: Entry: datamining_119_20171101_clickevent.zip
zip stream error
Error: invalid signature: 0x83268e0
    at /home/apshenichnikov/NetBeansProjects/lps/node_modules/unzip/lib/parse.js:59:13
    at runCallback (timers.js:666:20)
    at tryOnImmediate (timers.js:639:5)
    at processImmediate [as _immediateCallback] (timers.js:611:5)
error: [utils/worker.js] 5a27a822cb569b2db8bc493d Error: invalid signature: 0x83268e0
error: [utils/worker.js] 5a27a822cb569b2db8bc493d: errored
zip stream error
{ Error: unexpected end of file
    at Zlib._handle.onerror (zlib.js:370:17) errno: -5, code: 'Z_BUF_ERROR' }

I search much for library which will actually work, I tried tree...

I feel that there is no option in NodeJs to handle zip files...

Can you disprove my belief?


问:
How to check whether some variable returns something in predicate
Lets assume I have facts as follows:

```<code>airport(nyc,'newyork').
</code>```

I want want to display a message if the user inputs an airport that doesn't exist.

My Attempt:

```<code>isAirport(Air)  :-
      airport(Air,T),
     (var(T) -> true
      ;
       write('Airport not found'),
       fail
      ).
</code>```

However, this doesn't seem to work.

答:
First let's see what happens if you query a conjunction (the , operator) first:

```<code>?- airport(nyc, _), write('found!').
found!
true.

?- airport(abc, _), write('found!').
false.
</code>```

This means, isAirport(abc) directly fails after trying airport(abc,_) without the rest of your predicate being evaluated. In many cases, you can therefore get by without an explicit if-then-else construct and just write something of the form

```<code>predicate(X) :-
  first_condition(X),
  second_condition(X).
</code>```

and it will only succeed if both conditions are fulfilled for X.

In case you really want to create some user interface, this is a bit more tricky, because I/O is inherently non-logical, in particular when there is backtracking involved. We usually call a program which behaves like we would expect from a logical formula pure and when it contains non-logical constructs like I/O or the cut operator ! are called impure.

Unfortunately, the if-then-else construct (-> and ;) and negation (\+) are implemented via cut and therefore impure as well. Luckily, most of the time people want a conditional, a pure disjunction is sufficient:

```<code>case(1,a).
case(2,b).
</code>```

We have an automatic branching from the execution mechanism of Prolog:

```<code>?- case(X,Y).
X = 1,
Y = a ;
X = 2,
Y = b.
</code>```

But sometimes we really want to do something that needs the impure constructs, like user input. Then the easiest way to keep the nice logical properties of our program is to separate the task into pure and impure ones:

```<code>main :-
    uinput(Data),
    pure_predicate(Data, Result),
    write(Result).
</code>```

After we have done all the impure parts, Data is unified with the user data we wanted. Let's have a look at the implementation of uinput/1:

```<code>uinput(data(Airport,D-M-Y)) :-
    format('~nAirport? '),
    read(Airport),
    ( ground(Airport), airport(Airport, _) )
    ->
        (
            format('~nDay? '),
            read(D),
            format('~nMonth? '),
            read(M),
            format('~nYear? '),
            read(Y),
            ( ground(D-M-Y), isDate(D-M-Y) )
        ->
        true
        ;
        throw(failure('unknown date'))
        )
    ;
    throw(failure('unknown airport'))
    .
</code>```

We successively read terms from the input and throw an exception if we can't handle it. For the if-then-else construct to work, we need to take special care. If we compare the two queries:

```<code>?- between(1,3,X), write(X).
1
X = 1 ;
2
X = 2 ;
3
X = 3.
</code>```

and

```<code>?- between(1,3,X) -> write(X); false.
1
X = 1.
</code>```

you can see that the if-then-else is losing solutions. This means we need to make sure that our condition is deterministic. Asking for a user input term to be ground is already a good idea, because without variables, there is only one solution term. Still, a call to one of the data-predicates airport/1 and isDate/1 might generate the same term multiple times or not terminate at all. In this particular case, we just need to make sure that each airport has a unique shortcut name, we can also generate dates without repetition:

```<code>airport(nyc, 'New York City').
airport(wdc, 'Washington DC').

isDate(X-Y-Z) :-
    between(1,31,X),
    between(1,12,Y),
    between(1970,2100,Z).
</code>```

Another trick in the implementation of uinput is that we just succeed with true when we have validated everything. The only effect of is now that Data is instantiated with whatever the user entered.

If we give a dummy implementation of the actual implementation, we can already try the implementation oursevles:

```<code>pure_predicate(_Data, Result) :-
    % here goes the actual stuff
    Result='we have found something awesome'.
</code>```

On the prompt we can use the pure predicate without trouble:

```<code>?- pure_predicate(someinputdata,Y).
Y = 'we have computed something awesome'.
</code>```

On the other hand, we can also use the full predicate as follows:

```<code>?- main(_).

Airport? wdc.

Day? |: 1.

Month? |: 2.

Year? |: 2000.
we have found something awesome
true.
</code>```

Since we are using read, we have to input prolog terms and terminate with a dot ., but everything worked as expected.

In case the user input fails, we get:

```<code>?- main(_).

Airport? bla(X).

ERROR: Unhandled exception: failure('unknown airport')
</code>```

Please note that we only went through this trouble to actually fail early and give a user message in that case. For the actual computation, this is completely unneccessary.

Body:
Lets assume I have facts as follows:

airport(nyc,'newyork').

I want want to display a message if the user inputs an airport that doesn't exist.

My Attempt:

isAirport(Air)  :-
      airport(Air,T),
     (var(T) -> true
      ;
       write('Airport not found'),
       fail
      ).

However, this doesn't seem to work.

Body:
First let's see what happens if you query a conjunction (the , operator) first:

?- airport(nyc, _), write('found!').
found!
true.

?- airport(abc, _), write('found!').
false.

This means, isAirport(abc) directly fails after trying airport(abc,_) without the rest of your predicate being evaluated. In many cases, you can therefore get by without an explicit if-then-else construct and just write something of the form

predicate(X) :-
  first_condition(X),
  second_condition(X).

and it will only succeed if both conditions are fulfilled for X.

In case you really want to create some user interface, this is a bit more tricky, because I/O is inherently non-logical, in particular when there is backtracking involved. We usually call a program which behaves like we would expect from a logical formula pure and when it contains non-logical constructs like I/O or the cut operator ! are called impure.

Unfortunately, the if-then-else construct (-> and ;) and negation (\+) are implemented via cut and therefore impure as well. Luckily, most of the time people want a conditional, a pure disjunction is sufficient:

case(1,a).
case(2,b).

We have an automatic branching from the execution mechanism of Prolog:

?- case(X,Y).
X = 1,
Y = a ;
X = 2,
Y = b.

But sometimes we really want to do something that needs the impure constructs, like user input. Then the easiest way to keep the nice logical properties of our program is to separate the task into pure and impure ones:

main :-
    uinput(Data),
    pure_predicate(Data, Result),
    write(Result).

After we have done all the impure parts, Data is unified with the user data we wanted. Let's have a look at the implementation of uinput/1:

uinput(data(Airport,D-M-Y)) :-
    format('~nAirport? '),
    read(Airport),
    ( ground(Airport), airport(Airport, _) )
    ->
        (
            format('~nDay? '),
            read(D),
            format('~nMonth? '),
            read(M),
            format('~nYear? '),
            read(Y),
            ( ground(D-M-Y), isDate(D-M-Y) )
        ->
        true
        ;
        throw(failure('unknown date'))
        )
    ;
    throw(failure('unknown airport'))
    .

We successively read terms from the input and throw an exception if we can't handle it. For the if-then-else construct to work, we need to take special care. If we compare the two queries:

?- between(1,3,X), write(X).
1
X = 1 ;
2
X = 2 ;
3
X = 3.

and

?- between(1,3,X) -> write(X); false.
1
X = 1.

you can see that the if-then-else is losing solutions. This means we need to make sure that our condition is deterministic. Asking for a user input term to be ground is already a good idea, because without variables, there is only one solution term. Still, a call to one of the data-predicates airport/1 and isDate/1 might generate the same term multiple times or not terminate at all. In this particular case, we just need to make sure that each airport has a unique shortcut name, we can also generate dates without repetition:

airport(nyc, 'New York City').
airport(wdc, 'Washington DC').

isDate(X-Y-Z) :-
    between(1,31,X),
    between(1,12,Y),
    between(1970,2100,Z).

Another trick in the implementation of uinput is that we just succeed with true when we have validated everything. The only effect of is now that Data is instantiated with whatever the user entered.

If we give a dummy implementation of the actual implementation, we can already try the implementation oursevles:

pure_predicate(_Data, Result) :-
    % here goes the actual stuff
    Result='we have found something awesome'.

On the prompt we can use the pure predicate without trouble:

?- pure_predicate(someinputdata,Y).
Y = 'we have computed something awesome'.

On the other hand, we can also use the full predicate as follows:

?- main(_).

Airport? wdc.

Day? |: 1.

Month? |: 2.

Year? |: 2000.
we have found something awesome
true.

Since we are using read, we have to input prolog terms and terminate with a dot ., but everything worked as expected.

In case the user input fails, we get:

?- main(_).

Airport? bla(X).

ERROR: Unhandled exception: failure('unknown airport')

Please note that we only went through this trouble to actually fail early and give a user message in that case. For the actual computation, this is completely unneccessary.