问:
Angular 4 Event Emitter not Emitting
So I have an event emitter working just fine. In my child, I call a function:

```<code>(click)="EnterEditMode()
</code>```

which fires:

```<code>EnterEditMode(){
    this.enterEdit.emit(null);
  }
</code>```

In my parent, I then:

```<code>  enterEdit(){
    console.log("got some text");
  }
</code>```

This works flawlessly. But now I want to add a second output right next to it. So in the child, I call:

```<code>SaveChanges();
</code>```

Which triggers a function:

```<code>SaveChanges() {
    this.saveChanges.emit(null);
    console.log("save");
  }
</code>```

When I call this, the console log is triggered but the emit is not triggered. My parent has a function that is thus never called.

```<code>saveChanges() {
    console.log("saving changes");
    this.editing ? this.editing = false : this.editing = true;
  }
</code>```

I really can't see what I'm doing wrong and have tried to trouble shoot but I'm getting no errors, just the console log that the "SaveChanges()" has been called. Am I missing something about emitters?

Edit to show my event emitters

In my child component I:

```<code>@Output() enterEdit = new EventEmitter<any>();
@Output() saveChanges = new EventEmitter<any>();
</code>```

Again, enterEdit works but saveChanges does not...

答:
So this was due to a fundamental misunderstanding of how Output Emitters work in Angular.

Wrong assumption
Simply triggering an emitter would force my controller to react.

Solution
In my html file, I have to add the listener to an element and then pass the event from the html to the controller. This triggers the controller to do what ever the function is supposed to do.

In my .html file I need to add (saveChanges)='saveChanges($event)' to my custom component. This works.

Title: Angular 4 Event Emitter not Emitting

Body:
So I have an event emitter working just fine. In my child, I call a function:

(click)="EnterEditMode()

which fires:

EnterEditMode(){
    this.enterEdit.emit(null);
  }

In my parent, I then:

  enterEdit(){
    console.log("got some text");
  }

This works flawlessly. But now I want to add a second output right next to it. So in the child, I call:

SaveChanges();

Which triggers a function:

SaveChanges() {
    this.saveChanges.emit(null);
    console.log("save");
  }

When I call this, the console log is triggered but the emit is not triggered. My parent has a function that is thus never called.

saveChanges() {
    console.log("saving changes");
    this.editing ? this.editing = false : this.editing = true;
  }

I really can't see what I'm doing wrong and have tried to trouble shoot but I'm getting no errors, just the console log that the "SaveChanges()" has been called. Am I missing something about emitters?

Edit to show my event emitters

In my child component I:

@Output() enterEdit = new EventEmitter<any>();
@Output() saveChanges = new EventEmitter<any>();

Again, enterEdit works but saveChanges does not...


来源: stackexchange

问:
How can i force sql server to execute subquery first and filter the 'where' statement
i have a query like this:

```<code>select * from (
    select * from TableX
    where col1 % 2 = 0
) subquery
where col1 % 4 = 0
</code>```

The actual subquery is more complicated. when i execute the subquery alone it returns maybe 200rows quickly, but when i execute the whole query, it takes too long to wait.

I know sql server takes some optimization here and merge the where statement into the subquery, and produce the new execution plan which is not that efficient. Althought i can dive into the execution plan and analyze why, like index missing, statistics stale.

But i surely know that, my subquery which serves as a BaseTable will only return a small portion of data, so i want all further filtering or joining will only take place in these small portion of data.

My question is, can i force sql server to execute the subquery first, without caring about the outer where statement? (btw, TempTable is my last option, CTE is not working)

答:
Have you tried:

select * from (
  select * from TableX as inner
  where inner.col1 % 2 = 0
) as subquery
where subquery.col1 % 4 = 0

I believe it has to execute the subquery first here because you're explicitly having the where condition on the aliased result of the subquery.

ContentLicense: CC BY-SA 3.0

Body:
i have a query like this:

select * from (
    select * from TableX
    where col1 % 2 = 0
) subquery
where col1 % 4 = 0

The actual subquery is more complicated. when i execute the subquery alone it returns maybe 200rows quickly, but when i execute the whole query, it takes too long to wait.

I know sql server takes some optimization here and merge the where statement into the subquery, and produce the new execution plan which is not that efficient. Althought i can dive into the execution plan and analyze why, like index missing, statistics stale.

But i surely know that, my subquery which serves as a BaseTable will only return a small portion of data, so i want all further filtering or joining will only take place in these small portion of data.

My question is, can i force sql server to execute the subquery first, without caring about the outer where statement? (btw, TempTable is my last option, CTE is not working)


问:
Django: redirect to view with parameters
I am using Django authentication. Whenever a user logs in, I want to redirect him to /profile/user_id, being user_id a number. I can get the value of user_id by request.user.profile.id. In settings.py I have LOGIN_REDIRECT_URL = 'app_1:index'

app_1/urls.py:

```<code>url(r'^profile/$', views.index, name='index'),
# ex: /profile/5/
url(r'^profile/(?P<user_id>[0-9]+)/$', views.profile, name='profile'),
</code>```

app_1/views.py (things I've also tried are commented):

```<code>def index(request):
    userid = request.user.profile.id
    #return render(request, 'app_1/index.html', context)
    #return profile(request, request.user.profile.id)
    #return render(request, 'app_1/user_prof.html', {'user': request.user.profile.id})
    #return redirect(profile, user_id= request.user.profile.id)
    return redirect('profile', user_id=userid)

def profile(request, user_id):
    user = get_object_or_404(Profile, pk=user_id)
    return render(request, 'app_1/user_prof.html', {'user': user})
</code>```

I must be missing something because this should be easy but I'm stuck on it. Thanks in advance.

EDIT: The error I'm getting is Reverse for 'profile' not found. 'profile' is not a valid view function or pattern name.: http://dpaste.com/270YRJ9

答:
Try using this instead

```<code>from django.urls import reverse

return redirect(reverse('profile', kwargs={"user_id": userid}))
</code>```

Or this:

```<code>return redirect('app_1:profile', user_id=userid)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using Django authentication. Whenever a user logs in, I want to redirect him to /profile/user_id, being user_id a number. I can get the value of user_id by request.user.profile.id. In settings.py I have LOGIN_REDIRECT_URL = 'app_1:index'

app_1/urls.py:

url(r'^profile/$', views.index, name='index'),
# ex: /profile/5/
url(r'^profile/(?P<user_id>[0-9]+)/$', views.profile, name='profile'),

app_1/views.py (things I've also tried are commented):

def index(request):
    userid = request.user.profile.id
    #return render(request, 'app_1/index.html', context)
    #return profile(request, request.user.profile.id)
    #return render(request, 'app_1/user_prof.html', {'user': request.user.profile.id})
    #return redirect(profile, user_id= request.user.profile.id)
    return redirect('profile', user_id=userid)

def profile(request, user_id):
    user = get_object_or_404(Profile, pk=user_id)
    return render(request, 'app_1/user_prof.html', {'user': user})

I must be missing something because this should be easy but I'm stuck on it. Thanks in advance.

EDIT: The error I'm getting is Reverse for 'profile' not found. 'profile' is not a valid view function or pattern name.: http://dpaste.com/270YRJ9

Body:
Try using this instead

from django.urls import reverse

return redirect(reverse('profile', kwargs={"user_id": userid}))

Or this:

return redirect('app_1:profile', user_id=userid)


问:
How to put data from my database into select in angular
I want to allow the user to be able to choose their email that has been entered beforehand but when I used ng-options and I have tried ngFor but it still doesn't seem to work, did I do it wrong or something?

transfer.component.html

```<code><form (ngSubmit)="transFunds()" >
  <div class="container">
    <div class="row">
        <div class="col-sm-6 col-sm-offset-3">
          <select [ngModel]="selectedName" (ngModelChange)="updateSelectedValue($event)">
              <option *ngFor ="let recipient of recipients" value="{{recipient.emailTo}}">{{recipient.emailTo}}</option>
        </select>
        </div>
    </div>
    <div class="row">
        <div class="row">
          <p><input type="number"  placeholder="Amount Transfering" [(ngModel)]="amount"></p>
        </div>
      </div>
     <div class="row">
      <div class="col-sm-6 col-sm-offset-3">
        <p><button class="btn btn-primary" type="submit">Send</button> </p>
      </div>
    </div>
   </div>
  </form>
</code>```

transfer.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { Http } from '@angular/http';
import { PostsService } from '../posts.service';

@Component({
  selector: 'app-transfer',
  templateUrl: './transfer.component.html',
  styleUrls: ['./transfer.component.css']
})
export class TransferComponent implements OnInit {

  constructor(private fb: FormBuilder, private http: Http, private router: Router, private auth: AuthService,private postsService: PostsService) { }
  transfer = {};
  recipients: any;
  transferForm: FormGroup;
  public userEmail: string;

  ngOnInit() {
    this.transferForm = this.fb.group({
      emailTo: '',
      amount: ''
    });
    this.auth.currentEmail.subscribe(email => this.userEmail = email);

    this.postsService.getAllRecipient().subscribe(recipient => {
      this.recipients = recipient;
    });
  }

}
</code>```

答:
You are mixing up angularjs and angular syntax, it should be,</p>

```<code> <select class="form-control" name="someDrpDown" [(ngModel)]="selectedName">
        <option *ngFor="let recpient of recipients" [ngValue]="recipient">
          {{recpient.email}}
        </option>
  </select>
</code>```

Body:
I want to allow the user to be able to choose their email that has been entered beforehand but when I used ng-options and I have tried ngFor but it still doesn't seem to work, did I do it wrong or something?

transfer.component.html

<form (ngSubmit)="transFunds()" >

          <select [ngModel]="selectedName" (ngModelChange)="updateSelectedValue($event)">
              <option *ngFor ="let recipient of recipients" value="{{recipient.emailTo}}">{{recipient.emailTo}}</option>
        </select>

<input type="number"  placeholder="Amount Transfering" [(ngModel)]="amount">

<button class="btn btn-primary" type="submit">Send</button>

  </form>

transfer.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { Http } from '@angular/http';
import { PostsService } from '../posts.service';

@Component({
  selector: 'app-transfer',
  templateUrl: './transfer.component.html',
  styleUrls: ['./transfer.component.css']
})
export class TransferComponent implements OnInit {

  constructor(private fb: FormBuilder, private http: Http, private router: Router, private auth: AuthService,private postsService: PostsService) { }
  transfer = {};
  recipients: any;
  transferForm: FormGroup;
  public userEmail: string;

  ngOnInit() {
    this.transferForm = this.fb.group({
      emailTo: '',
      amount: ''
    });
    this.auth.currentEmail.subscribe(email => this.userEmail = email);

    this.postsService.getAllRecipient().subscribe(recipient => {
      this.recipients = recipient;
    });
  }

}

Body:
You are mixing up angularjs and angular syntax, it should be,

 <select class="form-control" name="someDrpDown" [(ngModel)]="selectedName">
        <option *ngFor="let recpient of recipients" [ngValue]="recipient">
          {{recpient.email}}
        </option>
  </select>


问:
How to check if elements in list 'a' meet conditions in list 'b'?
I have a list of numbers:

```<code>a = [3, 6, 20, 24, 36, 92, 130]
</code>```

And a list of conditions:

```<code>b = ["2", "5", "20", "range(50,100)", ">120"]
</code>```

I want to check if a number in 'a' meets one of the conditions in 'b' and if yes, put these numbers in list 'c'

In above case:

```<code>c = [20, 92, 130]
</code>```

I created this code what seems to do what I want:

```<code>c = []
for x in a:
    for y in b:
        if "range" in y:
            rangelist = list(eval(y))
            if x in rangelist:
                c.append(x)
        elif ">" in y or "<" in y:
            if eval(str(x) + y):
                c.append(x)
        else:
            if x == eval(y):
                c.append(x)
</code>```

However my list 'a' can be very big.

Is there not an easier and faster way to obtain what I want?

答:
Based on previous answers, I think there could be 2 more ways.

```<code>#1
numbers = [3, 6, 20, 24, 36, 92, 130]
conditions = [
    lambda n: n == 2,
    lambda n: n == 5,
    lambda n: n == 20,
    lambda n: n in range(50, 100),
    lambda n: n > 120,
]
result = [num for num in numbers for condition in conditions if condition(num)]

#2
condition = lambda n: n in {2, 5, 20} or 50 <= n <= 100 or n > 120
result = list(filter(condition, numbers))
</code>```

For a really big list, you should go with example #2 because it is more memory efficient and time complexity is linear instead of quadratic-like in #1

Body:
I have a list of numbers:

a = [3, 6, 20, 24, 36, 92, 130]

And a list of conditions:

b = ["2", "5", "20", "range(50,100)", ">120"]

I want to check if a number in 'a' meets one of the conditions in 'b' and if yes, put these numbers in list 'c'

In above case:

c = [20, 92, 130]

I created this code what seems to do what I want:

c = []
for x in a:
    for y in b:
        if "range" in y:
            rangelist = list(eval(y))
            if x in rangelist:
                c.append(x)
        elif ">" in y or "<" in y:
            if eval(str(x) + y):
                c.append(x)
        else:
            if x == eval(y):
                c.append(x)

However my list 'a' can be very big.

Is there not an easier and faster way to obtain what I want?

Body:
Based on previous answers, I think there could be 2 more ways.

#1
numbers = [3, 6, 20, 24, 36, 92, 130]
conditions = [
    lambda n: n == 2,
    lambda n: n == 5,
    lambda n: n == 20,
    lambda n: n in range(50, 100),
    lambda n: n > 120,
]
result = [num for num in numbers for condition in conditions if condition(num)]

#2
condition = lambda n: n in {2, 5, 20} or 50 <= n <= 100 or n > 120
result = list(filter(condition, numbers))

For a really big list, you should go with example #2 because it is more memory efficient and time complexity is linear instead of quadratic-like in #1


问:
FatalErrorException in routes.php line 22: Class 'Painting' not found
I got this error when I was trying to learn Laravel migrations from a video tutorial. The tutor created a file named Painting.php in the app/models folder. The content of Painting.php is:

```<code><?php

    class Painting extends Eloquent{

    }
?>
</code>```

and then in the routes.php:

```<code>Route::get('/', function () {
     $painting = new Painting; //**this thing generates error**
     $painting->title='Do no wrong';
     $painting->save();

    return view('welcome');
});
</code>```

Now , question is where I am supposed to place Painting.php file since there is no models folder in Laravel 5.1?

答:
The following changes made will make your code work
-----------------------------------------------------------------------------

Painting.php

```<code><?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Painting extends Model
{

}
</code>```

/routes/web.php

```<code><?php

use App\Painting;

Route::get('/', function () {

  $painting = new Painting;
  $painting->title = 'Its Your Wish';
  $painting->artist = 'Working Fine';
  $painting->year = 2017;
  $painting->save();

  return view('welcome');
});
</code>```

Body:
I got this error when I was trying to learn Laravel migrations from a video tutorial. The tutor created a file named Painting.php in the app/models folder. The content of Painting.php is:

<?php

    class Painting extends Eloquent{

    }
?>

and then in the routes.php:

Route::get('/', function () {
     $painting = new Painting; //**this thing generates error**
     $painting->title='Do no wrong';
     $painting->save();

    return view('welcome');
});

Now , question is where I am supposed to place Painting.php file since there is no models folder in Laravel 5.1?

Body:
The following changes made will make your code work
-----------------------------------------------------------------------------

Painting.php

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Painting extends Model
{

}

/routes/web.php

<?php

use App\Painting;

Route::get('/', function () {

  $painting = new Painting;
  $painting->title = 'Its Your Wish';
  $painting->artist = 'Working Fine';
  $painting->year = 2017;
  $painting->save();

  return view('welcome');
});


问:
MVVM-Light pass data to new ViewModel
Just fiddling around with some WP8.1 development + MVVM-Light toolkit and am having trouble trying to figure out how to achieve something..

Basically:

I have a View (let's call it View1) which has a control (LongListSelector in this case) that is databound to a Collection of items (let's call them DataItem) (which is populated by a Service from a ViewModel)

And I want it so:

When the user taps on a particular item in this control, it passes the item tapped (or a property of this item) to a new View (called View2), which will either create a new ViewModel for View2 or re-use an existing one (depending on the Key of the instances in SimpleIoC, determined by some property in the DataItem tapped).

This new ViewModel then uses the passed property of the DataItem tapped in its' constructor to fetch data from a different Service

So how can I achieve this? I am thinking of Creating/Registering the new ViewModel on the SelectionChanged event of the control, passing it in the Service and Property like so:

```<code>    private void LongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        DataItem item = e.AddedItems[0] as DataItem;

        SimpleIoc.Default.Register(() => new ViewModel2(new Model2Service(), item.Name));

        NavigationService.Navigate(new Uri("/View2.xaml", UriKind.Relative));
    }
</code>```

Which works fine for the first DataItem tapped, but not when a second is tapped.
Note: I couldn't register ViewModel2 in ViewModelLocator as I couldn't get DataItem properties passed to the constructor for ViewModel2, which is why I'm trying to Register it elsewhere.

Not sure if this is abiding by MVVM architecture, I suppose not as this answer states that I shouldn't be handling this in my View.

So to recap, I want a user to be able to tap on an item in a LongListSelector which will then navigate the user to a new View which is bound to a new (or existing) ViewModel according to a property of the selected item. How can I achieve this?

Any help would be greatly appreciated.

答:
If you are using UWP with Template Studio 10 and MVVM Light and want to either:

Access the parameter that is passed in the NavigationServicesEx.Navigate method

Call a method in your ViewModel when a page is navigated to.

This blog by Marco Minerva is the only guidance I could find that is up to up to date with UWP, Templates Studio 10 and MVVM Light 5.0 (thanks again Marco!)

tl;dr It works by hooking in to the Frame_Navigating event that it missing from the vanilla NavigationServiceEx class.

Create the INavigable interface described in the blog:

```<code>public interface INavigable
{
    Task OnNavigatedToAsync(object parameter, NavigationMode mode);
    void OnNavigatingFrom(NavigatingCancelEventArgs e);
    void OnNavigatedFrom();
}
</code>```

Add a handler for the Frame.Navigating event in the NavigationServicesEx class (with some additional plumbing, see blog) then realise the INavigable interface in your ViewModels.

You will then be able to access the parameter that you passed in your Navigate call:

```<code>NavigationServiceEx.Navigate(typeof(DestinationPage).FullName, yourParameter);
</code>```

In the OnNavigatedToAsync method that you implement in your ViewModel:

```<code>public Task OnNavigatedToAsync(object parameter, NavigationMode mode)
{
    if (parameter != null)
    {
        YourThing thing = parameter as YourThing;
        this.UseYourThing(thing);
    }
    return Task.CompletedTask;
}
</code>```

Title: MVVM-Light pass data to new ViewModel

Body:
Just fiddling around with some WP8.1 development + MVVM-Light toolkit and am having trouble trying to figure out how to achieve something..

Basically:

I have a View (let's call it View1) which has a control (LongListSelector in this case) that is databound to a Collection of items (let's call them DataItem) (which is populated by a Service from a ViewModel)

And I want it so:

When the user taps on a particular item in this control, it passes the item tapped (or a property of this item) to a new View (called View2), which will either create a new ViewModel for View2 or re-use an existing one (depending on the Key of the instances in SimpleIoC, determined by some property in the DataItem tapped).

This new ViewModel then uses the passed property of the DataItem tapped in its' constructor to fetch data from a different Service

So how can I achieve this? I am thinking of Creating/Registering the new ViewModel on the SelectionChanged event of the control, passing it in the Service and Property like so:

    private void LongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        DataItem item = e.AddedItems[0] as DataItem;

        SimpleIoc.Default.Register(() => new ViewModel2(new Model2Service(), item.Name));

        NavigationService.Navigate(new Uri("/View2.xaml", UriKind.Relative));
    }

Which works fine for the first DataItem tapped, but not when a second is tapped.
Note: I couldn't register ViewModel2 in ViewModelLocator as I couldn't get DataItem properties passed to the constructor for ViewModel2, which is why I'm trying to Register it elsewhere.

Not sure if this is abiding by MVVM architecture, I suppose not as this answer states that I shouldn't be handling this in my View.

So to recap, I want a user to be able to tap on an item in a LongListSelector which will then navigate the user to a new View which is bound to a new (or existing) ViewModel according to a property of the selected item. How can I achieve this?

Any help would be greatly appreciated.

Body:
If you are using UWP with Template Studio 10 and MVVM Light and want to either:

Access the parameter that is passed in the NavigationServicesEx.Navigate method

Call a method in your ViewModel when a page is navigated to.

This blog by Marco Minerva is the only guidance I could find that is up to up to date with UWP, Templates Studio 10 and MVVM Light 5.0 (thanks again Marco!)

tl;dr It works by hooking in to the Frame_Navigating event that it missing from the vanilla NavigationServiceEx class.

Create the INavigable interface described in the blog:

public interface INavigable
{
    Task OnNavigatedToAsync(object parameter, NavigationMode mode);
    void OnNavigatingFrom(NavigatingCancelEventArgs e);
    void OnNavigatedFrom();
}

Add a handler for the Frame.Navigating event in the NavigationServicesEx class (with some additional plumbing, see blog) then realise the INavigable interface in your ViewModels.

You will then be able to access the parameter that you passed in your Navigate call:

NavigationServiceEx.Navigate(typeof(DestinationPage).FullName, yourParameter);

In the OnNavigatedToAsync method that you implement in your ViewModel:

public Task OnNavigatedToAsync(object parameter, NavigationMode mode)
{
    if (parameter != null)
    {
        YourThing thing = parameter as YourThing;
        this.UseYourThing(thing);
    }
    return Task.CompletedTask;
}


问:
Multiple SQL Queries with Google Script and JDBC connectors in a single Sheet
I'm using an App Script with JDBC connector to create a connection with my MySQL stats database.
I would like to be able to run multiple Queries in a single script to pull out specific info from my database into a single sheet
All my Queries' results have the same structure (all are group by date) YEAR,MONTH,DAY,VALUE and I was wondering if it was possible to have the YEAR,MONTH, DATE Columns fixed and all the other results populating following columns in my results.

Something like
Col A: YEAR, Col B: MONTH, Col C: DAY, Col D: Result from Query 1, Col E: Result from Query 2....

Here is what I started with

```<code>function loadData() {
var sheet = SpreadsheetApp.getActiveSheet();
var instanceUrl = 'jdbc:mysql://' + address;
var dbUrl = instanceUrl + '/' + db;
var conn = Jdbc.getConnection(dbUrl, user, userPwd);

var stmt = conn.createStatement();
stmt.setMaxRows(10);
var results = stmt.executeQuery('Select YEAR(dateCreated) as yearAdded,MONTH(dateCreated) as monthAdded, DAY(dateCreated) as dayAdded,sum(amount)/100 from stripeTransactions GROUP BY yearAdded ,monthAdded,dayAdded;');
var numCols = results.getMetaData().getColumnCount();
while (results.next()) {
  var rowArray = new Array();
   for (var col = 0; col < numCols; col++) {
    rowArray.push(results.getString(col+1));
  }
  sheet.appendRow(rowArray);
}

results.close();
stmt.close();
var stmt2 = conn.createStatement();
stmt2.setMaxRows(10);
var results2= stmt2.executeQuery('Select YEAR(dateAdded) as yearAdded,MONTH(dateAdded) as monthAdded, DAY(dateAdded) as dayAdded,sum(amount) from itunestransactions GROUP BY yearAdded ,monthAdded,dayAdded;');
var numCols2 = results2.getMetaData().getColumnCount();
 while (results2.next()) {
  var rowArray2 = new Array();
   for (var cal = numCols; cal < numCols2; cal++) {
    rowArray2.push(results2.getString(cal+1));
  }
 sheet.appendRow(rowArray2);
}

results2.close();
stmt2.close();
}
</code>```

Thanks
(this script only append rows for every results, I guess could have a single sheet per results for each query then merge every sheet in one but I'd rather do it in a single sheet from the beginning)

答:
You'll need to know more advanced MySQL to pull this off but you can nest sub-queries into your main query.

Moreover, if you want your queries to be more efficient you can wrap your queries into a MySQL stored procedure and then call that procedure from Apps Script via JDBC.

Here are links to some tutorials to get you started:

MySQL Subquery

MySQL Stored Procedures

Body:
I'm using an App Script with JDBC connector to create a connection with my MySQL stats database.
I would like to be able to run multiple Queries in a single script to pull out specific info from my database into a single sheet
All my Queries' results have the same structure (all are group by date) YEAR,MONTH,DAY,VALUE and I was wondering if it was possible to have the YEAR,MONTH, DATE Columns fixed and all the other results populating following columns in my results.

Something like
Col A: YEAR, Col B: MONTH, Col C: DAY, Col D: Result from Query 1, Col E: Result from Query 2....

Here is what I started with

function loadData() {
var sheet = SpreadsheetApp.getActiveSheet();
var instanceUrl = 'jdbc:mysql://' + address;
var dbUrl = instanceUrl + '/' + db;
var conn = Jdbc.getConnection(dbUrl, user, userPwd);

var stmt = conn.createStatement();
stmt.setMaxRows(10);
var results = stmt.executeQuery('Select YEAR(dateCreated) as yearAdded,MONTH(dateCreated) as monthAdded, DAY(dateCreated) as dayAdded,sum(amount)/100 from stripeTransactions GROUP BY yearAdded ,monthAdded,dayAdded;');
var numCols = results.getMetaData().getColumnCount();
while (results.next()) {
  var rowArray = new Array();
   for (var col = 0; col < numCols; col++) {
    rowArray.push(results.getString(col+1));
  }
  sheet.appendRow(rowArray);
}

results.close();
stmt.close();
var stmt2 = conn.createStatement();
stmt2.setMaxRows(10);
var results2= stmt2.executeQuery('Select YEAR(dateAdded) as yearAdded,MONTH(dateAdded) as monthAdded, DAY(dateAdded) as dayAdded,sum(amount) from itunestransactions GROUP BY yearAdded ,monthAdded,dayAdded;');
var numCols2 = results2.getMetaData().getColumnCount();
 while (results2.next()) {
  var rowArray2 = new Array();
   for (var cal = numCols; cal < numCols2; cal++) {
    rowArray2.push(results2.getString(cal+1));
  }
 sheet.appendRow(rowArray2);
}

results2.close();
stmt2.close();
}

Thanks
(this script only append rows for every results, I guess could have a single sheet per results for each query then merge every sheet in one but I'd rather do it in a single sheet from the beginning)


问:
macos iterm2 tmux remap ctrl-b to right option/alt-a
I thought this was a no brainer. I am using tmux with iterm2 (latest version) on maxOs on a MacBook.

Using ctrl-b as prefix is a terrible key combination for a MacBook, since the MacBook has only one control key, which is placed on the left hand side. So pressing these two buttons at the same time is almost painful for me. But tmux is awesome, so it lets you remap the prefix.

So, quite naively, I entered this line into my ~/.tmux.conf in order to set the prefix to option/alt-a:

```<code>set-option -g prefix M-a
</code>```

However, that line didn't change a thing.

Entering tmux show-options -g still outputs

```<code>prefix C-b
</code>```

Has anyone ever solved this?

BTW: I know I could use iterm2's tmux integration. But I don't want that. I want a plain text mode solution.

答:
Yeah, so I found a solution:

```<code>  1 # change ctrl-a to alt-a
  2 unbind C-b
  3 set-option -g prefix M-a
  4 bind C-a send-prefix
</code>```

And then in iterm2 -> profiles -> [your profile] > Keys

for Right Option/Alt Key

click Esc+

I'm sorry. I found this solution, after having posted the question.

Body:
I thought this was a no brainer. I am using tmux with iterm2 (latest version) on maxOs on a MacBook.

Using ctrl-b as prefix is a terrible key combination for a MacBook, since the MacBook has only one control key, which is placed on the left hand side. So pressing these two buttons at the same time is almost painful for me. But tmux is awesome, so it lets you remap the prefix.

So, quite naively, I entered this line into my ~/.tmux.conf in order to set the prefix to option/alt-a:

set-option -g prefix M-a

However, that line didn't change a thing.

Entering tmux show-options -g still outputs

prefix C-b

Has anyone ever solved this?

BTW: I know I could use iterm2's tmux integration. But I don't want that. I want a plain text mode solution.

Body:
Yeah, so I found a solution:

  1 # change ctrl-a to alt-a
  2 unbind C-b
  3 set-option -g prefix M-a
  4 bind C-a send-prefix

And then in iterm2 -> profiles -> [your profile] > Keys

for Right Option/Alt Key

click Esc+

I'm sorry. I found this solution, after having posted the question.


问:
Need advice on how to make the turtle move with W,A,S,D. (Coding Noob)
This is my second coding "project", but first using turtle. So I am trying to make the turtle move with w,a,s, and d. But it isn't working with my code and ideas?

```<code>from turtle import *
setup(1000,1000)
Screen()
title("Turtle Keys")
move = Turtle()
showturtle()

def w():
    move.forward(45)

def s():
    move.back(45)

def a():
    move.left(45)

def d():
    move.right(45)

onkey(w, "Up")
onkey(s, "Back")
onkey(a, "Left")
onkey(d, "Right")

listen()
mainloop()
</code>```

`

答:
You've made a mistake with one of the 'Key' symbols.  "Back" should be "Down". The following works for me:</p>

```<code>from turtle import *
setup(1000,1000)
Screen()
title("Turtle Keys")
move = Turtle()
showturtle()

def w():
    move.forward(45)

def s():
    move.back(45)

def a():
    move.left(45)

def d():
    move.right(45)

onkey(w, "Up")
onkey(s, "Down") # "Back"
#         ^^^^
onkey(a, "Left")
onkey(d, "Right")

listen()
mainloop()
</code>```

Body:
This is my second coding "project", but first using turtle. So I am trying to make the turtle move with w,a,s, and d. But it isn't working with my code and ideas?

from turtle import *
setup(1000,1000)
Screen()
title("Turtle Keys")
move = Turtle()
showturtle()

def w():
    move.forward(45)

def s():
    move.back(45)

def a():
    move.left(45)

def d():
    move.right(45)

onkey(w, "Up")
onkey(s, "Back")
onkey(a, "Left")
onkey(d, "Right")

listen()
mainloop()

`

Body:
You've made a mistake with one of the 'Key' symbols.  "Back" should be "Down". The following works for me:

from turtle import *
setup(1000,1000)
Screen()
title("Turtle Keys")
move = Turtle()
showturtle()

def w():
    move.forward(45)

def s():
    move.back(45)

def a():
    move.left(45)

def d():
    move.right(45)

onkey(w, "Up")
onkey(s, "Down") # "Back"
#         ^^^^
onkey(a, "Left")
onkey(d, "Right")

listen()
mainloop()


问:
take a particular key from list and store to another list using stream
I have a Class with these fields

```<code>class ListA {
    Long id
    double lat
    doubel lon
    Timestamp timestamp
}
</code>```

I need to make a new list which will only have lat, lon

```<code>class LatLng {
    double lat
    double lon
}
</code>```

how can I do this using streams in Java?

I am able to do this using native for loop. But I want to learn to do it using stream.

```<code>List<ListA> listAs = this.dao.findAll();

List<LatLng> latLngs = new ArrayList();
for (ListA listA : listAs) {
    LatLng latLng = new LatLng(listA.getLat(), listA.getLon());
    latLngs.add(latlng)
}
</code>```

I just want to pluck lat and lon from ListA and store it to LatLng.

答:
You can do this in this case by filtering on size == 3 because that is an identifier for these two. You can of course also filter on any other characteristic.

```<code>final List<String> newItems = items.stream()
                                   .filter(s -> s.length() == 3)
                                   .collect(Collectors.toList());
</code>```

UPDATE: better solution...

```<code>final List<String> newItems = items.stream()
            .filter(s -> "lat".equals(s) || "lon".equals(s))
            .collect(Collectors.toList());
</code>```

Body:
I have a Class with these fields

class ListA {
    Long id
    double lat
    doubel lon
    Timestamp timestamp
}

I need to make a new list which will only have lat, lon

class LatLng {
    double lat
    double lon
}

how can I do this using streams in Java?

I am able to do this using native for loop. But I want to learn to do it using stream.

List<ListA> listAs = this.dao.findAll();

List<LatLng> latLngs = new ArrayList();
for (ListA listA : listAs) {
    LatLng latLng = new LatLng(listA.getLat(), listA.getLon());
    latLngs.add(latlng)
}

I just want to pluck lat and lon from ListA and store it to LatLng.

Body:
You can do this in this case by filtering on size == 3 because that is an identifier for these two. You can of course also filter on any other characteristic.

final List<String> newItems = items.stream()
                                   .filter(s -> s.length() == 3)
                                   .collect(Collectors.toList());

UPDATE: better solution...

final List<String> newItems = items.stream()
            .filter(s -> "lat".equals(s) || "lon".equals(s))
            .collect(Collectors.toList());


问:
Play partially downloaded video in swift 3
I need to play specific part of a video (eg. form 10 sec to 20 sec).
so I use Alamofire with custom header range to download just this part of the video:

```<code>Alamofire.download(videoUrl,
                           method: .get,
                           headers: ["Range":String(format: "bytes=%d-%d", startByte, endByte)],
                           to: destination).response { (response) in

                                completionHandler(response.destinationURL)
        }
</code>```

so far so good, I can see the downloaded file.

But when I'm trying to play it, avplayer will fail to do that, I'm using

videoAsset.loadValuesAsynchronously(forKeys: [ObserverContexts.urlAssetDurationKey, ObserverContexts.urlAssetPlayableKey])

to load that specific keys async but the duration state can not be loaded:

```<code>let durationStatus = self.videoAsset.statusOfValue(forKey: ObserverContexts.urlAssetDurationKey, error: &durationError)
                guard durationStatus == .loaded else {
                    Logger.log.error("durationStatus not loaded: \(self.videoId)")
                    self.delegate?.onLoadError(error: . durationStatusNotLoaded)
                    return
                }
</code>```

so this error gets triggered and I can't play the video.

I'm not master in video files, but I think the video file has an header and partially downloading will ruin this header and player can not play it.

so any suggestion or idea (even the simplest) would be appreciated.

tnx in advance.

EDIT: There is definitely something wrong with video header, if I start download 10 second from start of the video, the video get played for 10 sec, BUT the end video time or duration is wrong, how can I fix this?

答:
I don't think IOS or Swift provides this feature of downloading an image from the mid of it and then play it. You can download the video file contents as they are in the form of bits and then can save them with any extension to any file name.
But a video file contains a lots of data in addition to just these bytes that you have downloaded such as header, type, duration, etc. If your downloaded file doesn't contain that data your video will be unplayable.

In this case I think(99% sure) you will have to use native code not just Swift to decode the video from a specific time to your desired time.

A lots of free libraries are available, give them a try. One such kind of library is ffmpeg. Check this as well.

All the best.

Body:
I need to play specific part of a video (eg. form 10 sec to 20 sec).
so I use Alamofire with custom header range to download just this part of the video:

Alamofire.download(videoUrl,
                           method: .get,
                           headers: ["Range":String(format: "bytes=%d-%d", startByte, endByte)],
                           to: destination).response { (response) in

                                completionHandler(response.destinationURL)
        }

so far so good, I can see the downloaded file.

But when I'm trying to play it, avplayer will fail to do that, I'm using

videoAsset.loadValuesAsynchronously(forKeys: [ObserverContexts.urlAssetDurationKey, ObserverContexts.urlAssetPlayableKey])

to load that specific keys async but the duration state can not be loaded:

let durationStatus = self.videoAsset.statusOfValue(forKey: ObserverContexts.urlAssetDurationKey, error: &durationError)
                guard durationStatus == .loaded else {
                    Logger.log.error("durationStatus not loaded: \(self.videoId)")
                    self.delegate?.onLoadError(error: . durationStatusNotLoaded)
                    return
                }

so this error gets triggered and I can't play the video.

I'm not master in video files, but I think the video file has an header and partially downloading will ruin this header and player can not play it.

so any suggestion or idea (even the simplest) would be appreciated.

tnx in advance.

EDIT: There is definitely something wrong with video header, if I start download 10 second from start of the video, the video get played for 10 sec, BUT the end video time or duration is wrong, how can I fix this?


问:
Error message "gradlew: command not found"
I am working on a Java project with Gradle Wrapper (gradlew). I use Ubuntu Linux as my OS. When I run "gradle" it runs, and gives me information. But when I run "gradlew", it outputs as:

No command 'gradlew' found, did you mean:

Command 'gradle' from package 'gradle' (universe)

gradlew: command not found"

I did my research, I have the JDK, and I did sudo apt-get install gradle. How can I fix it?

The error is:

```<code>gradlew clean jpackage
</code>```

Output:

```<code>bash: gradlew: command not found...
</code>```

答:
I use IntelliJ IDEA and in Windows in the terminal I type:

gradlew.bat run

It is working for me.

Body:
I am working on a Java project with Gradle Wrapper (gradlew). I use Ubuntu Linux as my OS. When I run "gradle" it runs, and gives me information. But when I run "gradlew", it outputs as:

No command 'gradlew' found, did you mean:

Command 'gradle' from package 'gradle' (universe)

gradlew: command not found"

I did my research, I have the JDK, and I did sudo apt-get install gradle. How can I fix it?

The error is:

gradlew clean jpackage

Output:

bash: gradlew: command not found...


问:
MySQL Workbench 6.3 (Mac) hangs on simple queries
I am using MySQL Workbench 6.3.7 build 1199 CE (64 bits) on a Mac with OS X Yosemite 10.10.5.  I am connecting to an Amazon RDS MySQL instance.

When I enter a simple query such as

```<code>select * from `devices`;
</code>```

and click the lightning-bolt-with-cursor icon, the query starts, indicated by the spinner activating next to the "SQL File 4" tab in the following screenshot.  However, the query doesn't complete and it just hangs.  The white-hand-in-red-stop-sign icon is disabled.

I can only force quit MySQL Workbench from this point on.  If I try to do a regular quit, nothing happens.

How can I consistently run a simple query on my database?  Sometimes it works (maybe 10% of the time), but it mostly just hangs.

答:
At last I have downloaded MySQL Workbench 6.3.10 and install MySQL Workbench 6.3.10 and solved my problem. I have downloaded  MySQL Workbench 6.3.10 from bellow link https://dev.mysql.com/downloads/workbench/

It is working for me.. I think this will work for you..

Body:
I am using MySQL Workbench 6.3.7 build 1199 CE (64 bits) on a Mac with OS X Yosemite 10.10.5.  I am connecting to an Amazon RDS MySQL instance.

When I enter a simple query such as

select * from `devices`;

and click the lightning-bolt-with-cursor icon, the query starts, indicated by the spinner activating next to the "SQL File 4" tab in the following screenshot.  However, the query doesn't complete and it just hangs.  The white-hand-in-red-stop-sign icon is disabled.

I can only force quit MySQL Workbench from this point on.  If I try to do a regular quit, nothing happens.

How can I consistently run a simple query on my database?  Sometimes it works (maybe 10% of the time), but it mostly just hangs.


问:
Simulator iPhone Retina has wrong screen resolution
I'm trying to write a Universal Application.  The display should be slightly different for different screen resolutions.  But when I code like this:

```<code>- (void)viewDidLoad {
    SCREEN_WIDTH=[[UIScreen mainScreen] applicationFrame].size.width;
    SCREEN_HEIGHT=[[UIScreen mainScreen] applicationFrame].size.height;
    NSLog(@"w:%f h:%f",SCREEN_WIDTH,SCREEN_HEIGHT);
...
}
</code>```

I get output: w:320.000000 h:480.000000 even when the simulator is set to

Hardware->Device->iPhone (Retina)

Furthermore, images with this resolution display as full-screen images in the simulator.

I understand I should be getting w:640.000000 h:960.000000.

Is it like this for anyone else? And any ideas why/how to fix?
See the related thread: here

答:
UIScreen will always report the resolution of a Retina Display device as that of a non-Retina Display device. This allows old code to run transparently on such screens. However, UIScreen exposes a scale property which, when combined with the bounds of the screen, can be used to determine the physical pixel resolution of a device:

```<code>CGSize PhysicalPixelSizeOfScreen(UIScreen *s) {
    CGSize result = s.bounds.size;

    if ([s respondsToSelector: @selector(scale)]) {
        CGFloat scale = s.scale;
        result = CGSizeMake(result.width * scale, result.height * scale);
    }

    return result;
}
</code>```

The resulting value on an iPhone 4 would be { 640.0, 960.0 }.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to write a Universal Application.  The display should be slightly different for different screen resolutions.  But when I code like this:

- (void)viewDidLoad {
    SCREEN_WIDTH=[[UIScreen mainScreen] applicationFrame].size.width;
    SCREEN_HEIGHT=[[UIScreen mainScreen] applicationFrame].size.height;
    NSLog(@"w:%f h:%f",SCREEN_WIDTH,SCREEN_HEIGHT);
...
}

I get output: w:320.000000 h:480.000000 even when the simulator is set to

Hardware->Device->iPhone (Retina)

Furthermore, images with this resolution display as full-screen images in the simulator.

I understand I should be getting w:640.000000 h:960.000000.

Is it like this for anyone else? And any ideas why/how to fix?
See the related thread: here

Body:
UIScreen will always report the resolution of a Retina Display device as that of a non-Retina Display device. This allows old code to run transparently on such screens. However, UIScreen exposes a scale property which, when combined with the bounds of the screen, can be used to determine the physical pixel resolution of a device:

CGSize PhysicalPixelSizeOfScreen(UIScreen *s) {
    CGSize result = s.bounds.size;

    if ([s respondsToSelector: @selector(scale)]) {
        CGFloat scale = s.scale;
        result = CGSizeMake(result.width * scale, result.height * scale);
    }

    return result;
}

The resulting value on an iPhone 4 would be { 640.0, 960.0 }.


问:
delete item in sqlite database with cursor
I have a cursor that filled my database and i would like to delete the elements from this table.

her is the removal code fro my database:

```<code>public void deleteItem(int id){
    SQLiteDatabase database = this.getWritableDatabase();
    database.delete(ContractParaGastos.GASTO, ContractParaGastos.Columnas.MONTO + " = ?", new String[]{String.valueOf(id)});
    database.close();
}
</code>```

And here is the removal code in recyclerviewAdapter:

```<code> viewHolder.button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           databaseHelper.deleteItem(i);
        }
    });
}
</code>```

I add this line in my adapter:

```<code> databaseHelper = new DatabaseHelper(context, ContractParaGastos.GASTO, null, 4);
</code>```

But when i click on the delete button nothing happens. the line is still present in my recyclerview.

Help me please!

答:
from the little code you provided I would check that the variable i in:
    databaseHelper.deleteItem(i);
represents really an existing id of the record I need to delete. </p>

Body:
I have a cursor that filled my database and i would like to delete the elements from this table.

her is the removal code fro my database:

public void deleteItem(int id){
    SQLiteDatabase database = this.getWritableDatabase();
    database.delete(ContractParaGastos.GASTO, ContractParaGastos.Columnas.MONTO + " = ?", new String[]{String.valueOf(id)});
    database.close();
}

And here is the removal code in recyclerviewAdapter:

 viewHolder.button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           databaseHelper.deleteItem(i);
        }
    });
}

I add this line in my adapter:

 databaseHelper = new DatabaseHelper(context, ContractParaGastos.GASTO, null, 4);

But when i click on the delete button nothing happens. the line is still present in my recyclerview.

Help me please!


答:
i do like this in my code , make use of *ngfor available in angular js 2

```<code><select [(ngModel)]="selectedName"="selectedName"
    (ngModelChange)="updateSelectedValue($event)">
        <option *ngFor ="let recipient of recipients"
           value="{{recipient.email}}">{{recipient.email}}</option>
</select>
</code>```

I think value="{{recipient.email}}" is need to be replace by Id of receipient so it will be like value="{{recipient.Id}}"

Title: How to put data from my database into select in angular

Body:
I want to allow the user to be able to choose their email that has been entered beforehand but when I used ng-options and I have tried ngFor but it still doesn't seem to work, did I do it wrong or something?

transfer.component.html

<form (ngSubmit)="transFunds()" >

          <select [ngModel]="selectedName" (ngModelChange)="updateSelectedValue($event)">
              <option *ngFor ="let recipient of recipients" value="{{recipient.emailTo}}">{{recipient.emailTo}}</option>
        </select>

<input type="number"  placeholder="Amount Transfering" [(ngModel)]="amount">

<button class="btn btn-primary" type="submit">Send</button>

  </form>

transfer.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { Http } from '@angular/http';
import { PostsService } from '../posts.service';

@Component({
  selector: 'app-transfer',
  templateUrl: './transfer.component.html',
  styleUrls: ['./transfer.component.css']
})
export class TransferComponent implements OnInit {

  constructor(private fb: FormBuilder, private http: Http, private router: Router, private auth: AuthService,private postsService: PostsService) { }
  transfer = {};
  recipients: any;
  transferForm: FormGroup;
  public userEmail: string;

  ngOnInit() {
    this.transferForm = this.fb.group({
      emailTo: '',
      amount: ''
    });
    this.auth.currentEmail.subscribe(email => this.userEmail = email);

    this.postsService.getAllRecipient().subscribe(recipient => {
      this.recipients = recipient;
    });
  }

}

Body:
i do like this in my code , make use of *ngfor available in angular js 2

<select [(ngModel)]="selectedName"="selectedName"
    (ngModelChange)="updateSelectedValue($event)">
        <option *ngFor ="let recipient of recipients"
           value="{{recipient.email}}">{{recipient.email}}</option>
</select>

I think value="{{recipient.email}}" is need to be replace by Id of receipient so it will be like value="{{recipient.Id}}"


问:
Angular4 FullName field validator doesn't work as expected
I'm trying to make a custom validator for a fullname input field for a register form in Angular 4, but it doesn't behave accordingly: It shows the "Only letters and spaces allowed" message even though it only contains letters and spaces.

Here's my validator code:

```<code>import {AbstractControl, ValidationErrors} from '@angular/forms';

export class FullNameValidator {

  static eachWordShouldBeginWithCapital(control: AbstractControl) : ValidationErrors | null {
    let fullname = control.value as string;
    for(let word of fullname.split(' '))
      if (word[0] == undefined || word[0] == word[0].toLowerCase())
        return {eachWordShouldBeginWithCapital: true};
    return null;

  }

  static onlyAlphabeticalCharactersAndSpaceAllowed(control: AbstractControl) : ValidationErrors | null {
    let regex = '/^[a-zA-Z\\s]*$/';
    if (!(control.value as string).match(regex))
      return {onlyAlphabeticalCharactersAndSpaceAllowed: true};
    return null;
  }
}
</code>```

Here's my template:

```<code>          <div class="form-group">
            <label class="control-label" for="signupName">Your name</label>
            <input id="signupName" formControlName="fullname" type="text" class="form-control">
          </div>
          <div class="alert alert-danger" *ngIf="fullname.touched && fullname.invalid">
            <div *ngIf="fullname.errors.eachWordShouldBeginWithCapital">Each word should begin with capital letter</div>
            <div *ngIf="fullname.errors.onlyAlphabeticalCharactersAndSpaceAllowed">Only letters and spaces allowed</div>
          </div>
</code>```

And here's my component's code:

```<code>import {Component, OnInit} from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';
import {FullNameValidator} from '../../common/validators/fullname-validator';
import {EmailValidators} from '../../common/validators/email-validators';
import {AuthService} from '../../services/data-services/auth.service';

@Component({
  selector: 'register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {

  constructor(private authService: AuthService) {
  }

  form = new FormGroup({
    'fullname': new FormControl('', [
      FullNameValidator.eachWordShouldBeginWithCapital,
      FullNameValidator.onlyAlphabeticalCharactersAndSpaceAllowed
    ]),
    'email': new FormControl('', [
      EmailValidators.shouldHaveEmailFormat
    ]),
    'password': new FormControl('', [
      Validators.minLength(6)
    ]),
    'passwordAgain': new FormControl(),
    'dateOfBirth': new FormControl(),
    'gender': new FormControl()
  });

  ngOnInit() {
  }

  get fullname() {
    return this.form.get('fullname');
  }
}
</code>```

答:
Your regular expression doesn't allow spaces. Its because you misspell \s with \\s.
use this one  ^[a-zA-Z\s]*$  and it should work.

Body:
I'm trying to make a custom validator for a fullname input field for a register form in Angular 4, but it doesn't behave accordingly: It shows the "Only letters and spaces allowed" message even though it only contains letters and spaces.

Here's my validator code:

import {AbstractControl, ValidationErrors} from '@angular/forms';

export class FullNameValidator {

  static eachWordShouldBeginWithCapital(control: AbstractControl) : ValidationErrors | null {
    let fullname = control.value as string;
    for(let word of fullname.split(' '))
      if (word[0] == undefined || word[0] == word[0].toLowerCase())
        return {eachWordShouldBeginWithCapital: true};
    return null;

  }

  static onlyAlphabeticalCharactersAndSpaceAllowed(control: AbstractControl) : ValidationErrors | null {
    let regex = '/^[a-zA-Z\\s]*$/';
    if (!(control.value as string).match(regex))
      return {onlyAlphabeticalCharactersAndSpaceAllowed: true};
    return null;
  }
}

Here's my template:

            Your name
            <input id="signupName" formControlName="fullname" type="text" class="form-control">

Each word should begin with capital letter

Only letters and spaces allowed

And here's my component's code:

import {Component, OnInit} from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';
import {FullNameValidator} from '../../common/validators/fullname-validator';
import {EmailValidators} from '../../common/validators/email-validators';
import {AuthService} from '../../services/data-services/auth.service';

@Component({
  selector: 'register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {

  constructor(private authService: AuthService) {
  }

  form = new FormGroup({
    'fullname': new FormControl('', [
      FullNameValidator.eachWordShouldBeginWithCapital,
      FullNameValidator.onlyAlphabeticalCharactersAndSpaceAllowed
    ]),
    'email': new FormControl('', [
      EmailValidators.shouldHaveEmailFormat
    ]),
    'password': new FormControl('', [
      Validators.minLength(6)
    ]),
    'passwordAgain': new FormControl(),
    'dateOfBirth': new FormControl(),
    'gender': new FormControl()
  });

  ngOnInit() {
  }

  get fullname() {
    return this.form.get('fullname');
  }
}


问:
Should I create different projects for iOS(Game Center) and Android(Google Play Games)?
I have an Android Game made with Unity that is succeeding and now I want to launch it for iOS.

Should I have two Unity projects, one for Android and another for iOS, or can I do it with an only project?

I use Google Play Games and I want to use Game Center for iOS, and I don't know if it all could work in a single project.

答:
Should I have two Unity projects, one for Android and another for iOS,
  or can I do it with an only project?

No. You only need one project. Multiple projects will be very hard to maintain and that's unnecessary.

Use Unity's directives such as UNITY_IOS and UNITY_ANDROID to make Unity include your Game Center code for iOS and Google Play Games code for Android during compile-time.  See Platform dependent compilation for other directives.

You can also do this during runtime by checking Application.platform with RuntimePlatform.Android and RuntimePlatform.IPhonePlayer.


问:
sessions not working when trying to do admin login
Creating an admin and normal user login, but getting error when running code. Admin log in and directed to index.php and when guest logs in directed too display.php but when log in nothing happpens. Anyoneable to help?
Here is my code for authen_login.php:</p>

```<code> <?php
session_start();
 require('config2.php');

if (isset($_POST['user_id']) and isset($_POST['user_pass'])){

// Assigning POST values to variables.
$username = $_POST['user_id'];
$password = $_POST['user_pass'];

// CHECK FOR THE RECORD FROM TABLE
$query = "SELECT * FROM `user_login` WHERE username='$username' and Password='$password'";

$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
$_SESSION['user_type'] = $count['user_type'];

 if($_SESSION['type'] == 'admin'){ //check if user or password is correct from query

  header("Location: index.php"); //if normal user redirect to app.php

 }
 elseif ($_SESSION['type']) == 'guest'){

 header("Location: display.php"); //if admin user redirect to admin.php

  }
}

 ?>
</code>```

答:
you have missed a bracket</p>

```<code>elseif (($_SESSION['type']) == 'guest') // add '(' before $_SESSION['type']
</code>```

Body:
Creating an admin and normal user login, but getting error when running code. Admin log in and directed to index.php and when guest logs in directed too display.php but when log in nothing happpens. Anyoneable to help?
Here is my code for authen_login.php:

 <?php
session_start();
 require('config2.php');

if (isset($_POST['user_id']) and isset($_POST['user_pass'])){

// Assigning POST values to variables.
$username = $_POST['user_id'];
$password = $_POST['user_pass'];

// CHECK FOR THE RECORD FROM TABLE
$query = "SELECT * FROM `user_login` WHERE username='$username' and Password='$password'";

$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
$_SESSION['user_type'] = $count['user_type'];

 if($_SESSION['type'] == 'admin'){ //check if user or password is correct from query

  header("Location: index.php"); //if normal user redirect to app.php

 }
 elseif ($_SESSION['type']) == 'guest'){

 header("Location: display.php"); //if admin user redirect to admin.php

  }
}

 ?>

Body:
you have missed a bracket

elseif (($_SESSION['type']) == 'guest') // add '(' before $_SESSION['type']


问:
How do I get Apache Ignite persistence to work?
I have the following configuration for my embedded Ignite (v2.3) service (it will be a cluster eventually, but embedded is easier for development):

```<code>    val config = new IgniteConfiguration

    val dsConfig = new DataStorageConfiguration
    dsConfig.setStoragePath("ignitedb/storage")
    dsConfig.setWalPath("ignitedb/wal")
    dsConfig.setWalArchivePath("ignitedb/wal/archive")
    dsConfig.getDefaultDataRegionConfiguration.setPersistenceEnabled(true)
    config.setDataStorageConfiguration(dsConfig)

    Ignition.setClientMode(false)
    config.setConsistentId(java.net.InetAddress.getLocalHost.getHostName)

    val ignite = Ignition.start(config)
    ignite.active(true)
</code>```

Various files are created in those directories:

```<code>ignitedb/
├── storage
│   └── imac_home
│       ├── cache-changes
│       │   ├── 1113bbb3-6183-4f97-8783-ca61c4afffb0
│       │   │   ├── cache_data.dat
│       │   │   └── index.bin
│       │   └── 605e79c8-63aa-49d5-86b2-68468e648375
│       │       ├── cache_data.dat
│       │       └── index.bin
│       ├── cache-ignite-sys-cache
│       ├── cache-pings
│       │   ├── 86d44085-3eca-4dfa-92fb-c2e7fd0f4f4b
│       │   │   ├── cache_data.dat
│       │   │   ├── index.bin
│       │   │   └── part-714.bin
│       │   └── f69da997-fae5-45a5-9abc-44639bb46e8e
│       │       ├── cache_data.dat
│       │       ├── index.bin
│       │       ├── part-142.bin
│       │       ├── part-152.bin
│       │       ├── <many more>
│       ├── cache-products
│       │   ├── 1113bbb3-6183-4f97-8783-ca61c4afffb0
│       │   │   ├── cache_data.dat
│       │   │   ├── index.bin
│       │   │   ├── part-49.bin
│       │   │   ├── part-50.bin
│       │   │   ├── <many more>
│       │   └── 605e79c8-63aa-49d5-86b2-68468e648375
│       │       ├── cache_data.dat
│       │       ├── index.bin
│       │       └── part-49.bin
│       ├── cacheGroup-default-ds-group
│       │   ├── ignite-sys-atomic-cache@default-ds-groupcache_data.dat
│       │   ├── index.bin
│       │   ├── part-264.bin
│       │   └── part-791.bin
│       ├── cp
│       │   ├── 1512524465868-cecd4b2e-5c0f-4b25-8ede-92336ba2aac3-END.bin
│       │   ├── 1512524465868-cecd4b2e-5c0f-4b25-8ede-92336ba2aac3-START.bin
│       │   ├── 1512524645873-70f73379-5e49-4779-849c-e1dda08e2f84-END.bin
│       │   ├── 1512524645873-70f73379-5e49-4779-849c-e1dda08e2f84-START.bin
│       │   ├── <many more>
│       └── lock
└── wal
    ├── archive
    │   └── imac_home
    └── imac_home
        ├── 0000000000000000.wal
        ├── 0000000000000001.wal
        ├── <many more>
</code>```

However, when I stop and restart my application, all my caches have disappeared. How do I actually persist them to disk? Do I need to do something per-cache as well as enabling persistence globally? (The docs don't mention anything like that.)

I'm getting this exception at startup, which on closer inspection looks like it's coming from the persistence layer:

```<code>09:44:33.034 INFO  o.a.i.i.p.c.p.f.FilePageStoreManager - Resolved page store work directory: /Users/dan/projects/livefeeds/ignitedb/storage/imac_home
09:44:33.034 INFO  o.a.i.i.p.c.p.w.FileWriteAheadLogManager - Resolved write ahead log work directory: /Users/dan/projects/livefeeds/ignitedb/wal/imac_home
09:44:33.034 INFO  o.a.i.i.p.c.p.w.FileWriteAheadLogManager - Resolved write ahead log archive directory: /Users/dan/projects/livefeeds/ignitedb/wal/archive/imac_home
09:44:33.044 INFO  o.a.i.i.p.c.p.w.FileWriteAheadLogManager - Started write-ahead log manager [mode=DEFAULT]
Can't load log handler "org.apache.ignite.logger.java.JavaLoggerFileHandler"
java.lang.ClassNotFoundException: org.apache.ignite.logger.java.JavaLoggerFileHandler
java.lang.ClassNotFoundException: org.apache.ignite.logger.java.JavaLoggerFileHandler
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.util.logging.LogManager$5.run(LogManager.java:965)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.util.logging.LogManager.loadLoggerHandlers(LogManager.java:958)
    at java.util.logging.LogManager.initializeGlobalHandlers(LogManager.java:1578)
    at java.util.logging.LogManager.access$1500(LogManager.java:145)
    at java.util.logging.LogManager$RootLogger.accessCheckedHandlers(LogManager.java:1667)
    at java.util.logging.Logger.getHandlers(Logger.java:1776)
    at org.apache.ignite.logger.java.JavaLogger.findHandler(JavaLogger.java:399)
    at org.apache.ignite.logger.java.JavaLogger.configure(JavaLogger.java:229)
    at org.apache.ignite.logger.java.JavaLogger.<init>(JavaLogger.java:170)
    at org.apache.ignite.logger.java.JavaLogger.<init>(JavaLogger.java:126)
    at org.apache.ignite.IgniteJdbcDriver.<clinit>(IgniteJdbcDriver.java:410)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at java.lang.Class.newInstance(Class.java:442)
    at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:380)
    at java.util.ServiceLoader$LazyIterator.access$700(ServiceLoader.java:323)
    at java.util.ServiceLoader$LazyIterator$2.run(ServiceLoader.java:407)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:409)
    at java.util.ServiceLoader$1.next(ServiceLoader.java:480)
    at java.sql.DriverManager$2.run(DriverManager.java:603)
    at java.sql.DriverManager$2.run(DriverManager.java:583)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.sql.DriverManager.loadInitialDrivers(DriverManager.java:583)
    at java.sql.DriverManager.<clinit>(DriverManager.java:101)
    at org.h2.Driver.load(Driver.java:155)
    at org.h2.Driver.<clinit>(Driver.java:41)
    at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.start(IgniteH2Indexing.java:2027)
    at org.apache.ignite.internal.processors.query.GridQueryProcessor.start(GridQueryProcessor.java:240)
    at org.apache.ignite.internal.IgniteKernal.startProcessor(IgniteKernal.java:1870)
    at org.apache.ignite.internal.IgniteKernal.start(IgniteKernal.java:955)
    at org.apache.ignite.internal.IgnitionEx$IgniteNamedInstance.start0(IgnitionEx.java:1909)
    at org.apache.ignite.internal.IgnitionEx$IgniteNamedInstance.start(IgnitionEx.java:1652)
    at org.apache.ignite.internal.IgnitionEx.start0(IgnitionEx.java:1080)
    at org.apache.ignite.internal.IgnitionEx.start(IgnitionEx.java:600)
    at org.apache.ignite.internal.IgnitionEx.start(IgnitionEx.java:525)
    at org.apache.ignite.Ignition.start(Ignition.java:322)
    at io.livefeeds.api.Main$.startIgnite(Main.scala:78)
    at io.livefeeds.api.Main$.main(Main.scala:25)
    at io.livefeeds.api.Main.main(Main.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at sbt.Run.invokeMain(Run.scala:67)
    at sbt.Run.run0(Run.scala:61)
    at sbt.Run.sbt$Run$$execute$1(Run.scala:51)
    at sbt.Run$$anonfun$run$1.apply$mcV$sp(Run.scala:55)
    at sbt.Run$$anonfun$run$1.apply(Run.scala:55)
    at sbt.Run$$anonfun$run$1.apply(Run.scala:55)
    at sbt.Logger$$anon$4.apply(Logger.scala:84)
    at sbt.TrapExit$App.run(TrapExit.scala:248)
    at java.lang.Thread.run(Thread.java:745)
</code>```

The rest of the log output for persistence is:

```<code>09:44:34.682 INFO  o.a.i.i.p.c.p.f.FilePageStoreManager - Resolved page store work directory: /Users/dan/projects/livefeeds/ignitedb/storage/imac_home
09:44:34.682 INFO  o.a.i.i.p.c.p.w.FileWriteAheadLogManager - Resolved write ahead log work directory: /Users/dan/projects/livefeeds/ignitedb/wal/imac_home
09:44:34.682 INFO  o.a.i.i.p.c.p.w.FileWriteAheadLogManager - Resolved write ahead log archive directory: /Users/dan/projects/livefeeds/ignitedb/wal/archive/imac_home
09:44:34.682 INFO  o.a.i.i.p.c.p.w.FileWriteAheadLogManager - Started write-ahead log manager [mode=DEFAULT]
09:44:34.747 INFO  o.a.i.i.p.c.p.p.PageMemoryImpl - Started page memory [memoryAllocated=6.4 GiB, pages=1634272, tableSize=94.9 MiB, checkpointBuffer=1.6 GiB]
09:44:34.785 INFO  o.a.i.i.p.c.p.GridCacheDatabaseSharedManager - Read checkpoint status [startMarker=/Users/dan/projects/livefeeds/ignitedb/storage/imac_home/cp/1512571436282-f25aee22-0e9e-4737-a0ad-aebc3c5a4bd6-START.bin, endMarker=/Users/dan/projects/livefeeds/ignitedb/storage/imac_home/cp/1512571307494-690bb0bf-e75e-4877-a3e5-ba7b43b190bd-END.bin]
09:44:34.786 INFO  o.a.i.i.p.c.p.GridCacheDatabaseSharedManager - Checking memory state [lastValidPos=FileWALPointer [idx=0, fileOffset=8996738, len=20281, forceFlush=false], lastMarked=FileWALPointer [idx=0, fileOffset=9076734, len=20281, forceFlush=false], lastCheckpointId=f25aee22-0e9e-4737-a0ad-aebc3c5a4bd6]
09:44:34.786 WARN  o.a.i.i.p.c.p.GridCacheDatabaseSharedManager - Ignite node stopped in the middle of checkpoint. Will restore memory state and finish checkpoint on node start.
[09:44:34] Ignite node stopped in the middle of checkpoint. Will restore memory state and finish checkpoint on node start.
09:44:34.846 INFO  o.a.i.i.p.c.p.GridCacheDatabaseSharedManager - Found last checkpoint marker [cpId=f25aee22-0e9e-4737-a0ad-aebc3c5a4bd6, pos=FileWALPointer [idx=0, fileOffset=9076734, len=20281, forceFlush=false]]
09:44:34.853 INFO  o.a.i.i.p.c.p.GridCacheDatabaseSharedManager - Finished applying memory changes [changesApplied=8, time=65ms]
09:44:34.857 INFO  o.a.i.i.p.c.p.GridCacheDatabaseSharedManager - Checkpoint finished [cpId=f25aee22-0e9e-4737-a0ad-aebc3c5a4bd6, pages=6, markPos=FileWALPointer [idx=0, fileOffset=9076734, len=20281, forceFlush=false], pagesWrite=-3ms, fsync=0ms, total=-3ms]
09:44:34.861 INFO  o.a.i.i.p.c.p.w.FileWriteAheadLogManager - Resuming logging to WAL segment [file=/Users/dan/projects/livefeeds/ignitedb/wal/imac_home/0000000000000000.wal, offset=9097015, ver=1]
09:44:35.065 INFO  o.a.i.i.p.cache.GridCacheProcessor - Started cache [name=ignite-sys-cache, memoryPolicyName=sysMemPlc, mode=REPLICATED, atomicity=TRANSACTIONAL]
09:44:35.085 INFO  o.a.i.i.p.cache.GridCacheProcessor - Started cache [name=ignite-sys-atomic-cache@default-ds-group, group=default-ds-group, memoryPolicyName=default, mode=PARTITIONED, atomicity=TRANSACTIONAL]
09:44:35.087 INFO  o.a.i.i.p.c.d.d.p.GridDhtPartitionsExchangeFuture - Successfully activated caches [nodeId=f616a68d-e171-4384-8dc4-45c2e6788afc, client=false, topVer=AffinityTopologyVersion [topVer=1, minorTopVer=1]]
09:44:35.091 INFO  o.a.i.i.p.c.d.d.p.GridDhtPartitionsExchangeFuture - Finished waiting for partition release future [topVer=AffinityTopologyVersion [topVer=1, minorTopVer=1], waitTime=0ms, futInfo=NA]
09:44:35.139 INFO  o.a.i.i.p.c.p.GridCacheDatabaseSharedManager - Read checkpoint status [startMarker=/Users/dan/projects/livefeeds/ignitedb/storage/imac_home/cp/1512571436282-f25aee22-0e9e-4737-a0ad-aebc3c5a4bd6-START.bin, endMarker=/Users/dan/projects/livefeeds/ignitedb/storage/imac_home/cp/1512571436282-f25aee22-0e9e-4737-a0ad-aebc3c5a4bd6-END.bin]
09:44:35.140 INFO  o.a.i.i.p.c.p.GridCacheDatabaseSharedManager - Applying lost cache updates since last checkpoint record [lastMarked=FileWALPointer [idx=0, fileOffset=9076734, len=20281, forceFlush=false], lastCheckpointId=f25aee22-0e9e-4737-a0ad-aebc3c5a4bd6]
09:44:35.187 INFO  o.a.i.i.p.c.p.GridCacheDatabaseSharedManager - Finished applying WAL changes [updatesApplied=0, time=51ms]
09:44:35.189 INFO  o.a.i.i.p.c.p.GridCacheDatabaseSharedManager - Finished indexes rebuilding for cache: [name=ignite-sys-cache, grpName=null
</code>```

答: The problem was that the / in my cache names were causing the persistence layer to create extra directories, because they're not escaped at all. I switched to using @, and it seems fine now.

Body:
I have the following configuration for my embedded Ignite (v2.3) service (it will be a cluster eventually, but embedded is easier for development):

    val config = new IgniteConfiguration

    val dsConfig = new DataStorageConfiguration
    dsConfig.setStoragePath("ignitedb/storage")
    dsConfig.setWalPath("ignitedb/wal")
    dsConfig.setWalArchivePath("ignitedb/wal/archive")
    dsConfig.getDefaultDataRegionConfiguration.setPersistenceEnabled(true)
    config.setDataStorageConfiguration(dsConfig)

    Ignition.setClientMode(false)
    config.setConsistentId(java.net.InetAddress.getLocalHost.getHostName)

    val ignite = Ignition.start(config)
    ignite.active(true)

Various files are created in those directories:

ignitedb/
├── storage
│   └── imac_home
│       ├── cache-changes
│       │   ├── 1113bbb3-6183-4f97-8783-ca61c4afffb0
│       │   │   ├── cache_data.dat
│       │   │   └── index.bin
│       │   └── 605e79c8-63aa-49d5-86b2-68468e648375
│       │       ├── cache_data.dat
│       │       └── index.bin
│       ├── cache-ignite-sys-cache
│       ├── cache-pings
│       │   ├── 86d44085-3eca-4dfa-92fb-c2e7fd0f4f4b
│       │   │   ├── cache_data.dat
│       │   │   ├── index.bin
│       │   │   └── part-714.bin
│       │   └── f69da997-fae5-45a5-9abc-44639bb46e8e
│       │       ├── cache_data.dat
│       │       ├── index.bin
│       │       ├── part-142.bin
│       │       ├── part-152.bin
│       │       ├── <many more>
│       ├── cache-products
│       │   ├── 1113bbb3-6183-4f97-8783-ca61c4afffb0
│       │   │   ├── cache_data.dat
│       │   │   ├── index.bin
│       │   │   ├── part-49.bin
│       │   │   ├── part-50.bin
│       │   │   ├── <many more>
│       │   └── 605e79c8-63aa-49d5-86b2-68468e648375
│       │       ├── cache_data.dat
│       │       ├── index.bin
│       │       └── part-49.bin
│       ├── cacheGroup-default-ds-group
│       │   ├── ignite-sys-atomic-cache@default-ds-groupcache_data.dat
│       │   ├── index.bin
│       │   ├── part-264.bin
│       │   └── part-791.bin
│       ├── cp
│       │   ├── 1512524465868-cecd4b2e-5c0f-4b25-8ede-92336ba2aac3-END.bin
│       │   ├── 1512524465868-cecd4b2e-5c0f-4b25-8ede-92336ba2aac3-START.bin
│       │   ├── 1512524645873-70f73379-5e49-4779-849c-e1dda08e2f84-END.bin
│       │   ├── 1512524645873-70f73379-5e49-4779-849c-e1dda08e2f84-START.bin
│       │   ├── <many more>
│       └── lock
└── wal
    ├── archive
    │   └── imac_home
    └── imac_home
        ├── 0000000000000000.wal
        ├── 0000000000000001.wal
        ├── <many more>

However, when I stop and restart my application, all my caches have disappeared. How do I actually persist them to disk? Do I need to do something per-cache as well as enabling persistence globally? (The docs don't mention anything like that.)

I'm getting this exception at startup, which on closer inspection looks like it's coming from the persistence layer:

09:44:33.034 INFO  o.a.i.i.p.c.p.f.FilePageStoreManager - Resolved page store work directory: /Users/dan/projects/livefeeds/ignitedb/storage/imac_home
09:44:33.034 INFO  o.a.i.i.p.c.p.w.FileWriteAheadLogManager - Resolved write ahead log work directory: /Users/dan/projects/livefeeds/ignitedb/wal/imac_home
09:44:33.034 INFO  o.a.i.i.p.c.p.w.FileWriteAheadLogManager - Resolved write ahead log archive directory: /Users/dan/projects/livefeeds/ignitedb/wal/archive/imac_home
09:44:33.044 INFO  o.a.i.i.p.c.p.w.FileWriteAheadLogManager - Started write-ahead log manager [mode=DEFAULT]
Can't load log handler "org.apache.ignite.logger.java.JavaLoggerFileHandler"
java.lang.ClassNotFoundException: org.apache.ignite.logger.java.JavaLoggerFileHandler
java.lang.ClassNotFoundException: org.apache.ignite.logger.java.JavaLoggerFileHandler
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.util.logging.LogManager$5.run(LogManager.java:965)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.util.logging.LogManager.loadLoggerHandlers(LogManager.java:958)
    at java.util.logging.LogManager.initializeGlobalHandlers(LogManager.java:1578)
    at java.util.logging.LogManager.access$1500(LogManager.java:145)
    at java.util.logging.LogManager$RootLogger.accessCheckedHandlers(LogManager.java:1667)
    at java.util.logging.Logger.getHandlers(Logger.java:1776)
    at org.apache.ignite.logger.java.JavaLogger.findHandler(JavaLogger.java:399)
    at org.apache.ignite.logger.java.JavaLogger.configure(JavaLogger.java:229)
    at org.apache.ignite.logger.java.JavaLogger.<init>(JavaLogger.java:170)
    at org.apache.ignite.logger.java.JavaLogger.<init>(JavaLogger.java:126)
    at org.apache.ignite.IgniteJdbcDriver.<clinit>(IgniteJdbcDriver.java:410)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at java.lang.Class.newInstance(Class.java:442)
    at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:380)
    at java.util.ServiceLoader$LazyIterator.access$700(ServiceLoader.java:323)
    at java.util.ServiceLoader$LazyIterator$2.run(ServiceLoader.java:407)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:409)
    at java.util.ServiceLoader$1.next(ServiceLoader.java:480)
    at java.sql.DriverManager$2.run(DriverManager.java:603)
    at java.sql.DriverManager$2.run(DriverManager.java:583)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.sql.DriverManager.loadInitialDrivers(DriverManager.java:583)
    at java.sql.DriverManager.<clinit>(DriverManager.java:101)
    at org.h2.Driver.load(Driver.java:155)
    at org.h2.Driver.<clinit>(Driver.java:41)
    at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.start(IgniteH2Indexing.java:2027)
    at org.apache.ignite.internal.processors.query.GridQueryProcessor.start(GridQueryProcessor.java:240)
    at org.apache.ignite.internal.IgniteKernal.startProcessor(IgniteKernal.java:1870)
    at org.apache.ignite.internal.IgniteKernal.start(IgniteKernal.java:955)
    at org.apache.ignite.internal.IgnitionEx$IgniteNamedInstance.start0(IgnitionEx.java:1909)
    at org.apache.ignite.internal.IgnitionEx$IgniteNamedInstance.start(IgnitionEx.java:1652)
    at org.apache.ignite.internal.IgnitionEx.start0(IgnitionEx.java:1080)
    at org.apache.ignite.internal.IgnitionEx.start(IgnitionEx.java:600)
    at org.apache.ignite.internal.IgnitionEx.start(IgnitionEx.java:525)
    at org.apache.ignite.Ignition.start(Ignition.java:322)
    at io.livefeeds.api.Main$.startIgnite(Main.scala:78)
    at io.livefeeds.api.Main$.main(Main.scala:25)
    at io.livefeeds.api.Main.main(Main.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at sbt.Run.invokeMain(Run.scala:67)
    at sbt.Run.run0(Run.scala:61)
    at sbt.Run.sbt$Run$$execute$1(Run.scala:51)
    at sbt.Run$$anonfun$run$1.apply$mcV$sp(Run.scala:55)
    at sbt.Run$$anonfun$run$1.apply(Run.scala:55)
    at sbt.Run$$anonfun$run$1.apply(Run.scala:55)
    at sbt.Logger$$anon$4.apply(Logger.scala:84)
    at sbt.TrapExit$App.run(TrapExit.scala:248)
    at java.lang.Thread.run(Thread.java:745)

The rest of the log output for persistence is:

09:44:34.682 INFO  o.a.i.i.p.c.p.f.FilePageStoreManager - Resolved page store work directory: /Users/dan/projects/livefeeds/ignitedb/storage/imac_home
09:44:34.682 INFO  o.a.i.i.p.c.p.w.FileWriteAheadLogManager - Resolved write ahead log work directory: /Users/dan/projects/livefeeds/ignitedb/wal/imac_home
09:44:34.682 INFO  o.a.i.i.p.c.p.w.FileWriteAheadLogManager - Resolved write ahead log archive directory: /Users/dan/projects/livefeeds/ignitedb/wal/archive/imac_home
09:44:34.682 INFO  o.a.i.i.p.c.p.w.FileWriteAheadLogManager - Started write-ahead log manager [mode=DEFAULT]
09:44:34.747 INFO  o.a.i.i.p.c.p.p.PageMemoryImpl - Started page memory [memoryAllocated=6.4 GiB, pages=1634272, tableSize=94.9 MiB, checkpointBuffer=1.6 GiB]
09:44:34.785 INFO  o.a.i.i.p.c.p.GridCacheDatabaseSharedManager - Read checkpoint status [startMarker=/Users/dan/projects/livefeeds/ignitedb/storage/imac_home/cp/1512571436282-f25aee22-0e9e-4737-a0ad-aebc3c5a4bd6-START.bin, endMarker=/Users/dan/projects/livefeeds/ignitedb/storage/imac_home/cp/1512571307494-690bb0bf-e75e-4877-a3e5-ba7b43b190bd-END.bin]
09:44:34.786 INFO  o.a.i.i.p.c.p.GridCacheDatabaseSharedManager - Checking memory state [lastValidPos=FileWALPointer [idx=0, fileOffset=8996738, len=20281, forceFlush=false], lastMarked=FileWALPointer [idx=0, fileOffset=9076734, len=20281, forceFlush=false], lastCheckpointId=f25aee22-0e9e-4737-a0ad-aebc3c5a4bd6]
09:44:34.786 WARN  o.a.i.i.p.c.p.GridCacheDatabaseSharedManager - Ignite node stopped in the middle of checkpoint. Will restore memory state and finish checkpoint on node start.
[09:44:34] Ignite node stopped in the middle of checkpoint. Will restore memory state and finish checkpoint on node start.
09:44:34.846 INFO  o.a.i.i.p.c.p.GridCacheDatabaseSharedManager - Found last checkpoint marker [cpId=f25aee22-0e9e-4737-a0ad-aebc3c5a4bd6, pos=FileWALPointer [idx=0, fileOffset=9076734, len=20281, forceFlush=false]]
09:44:34.853 INFO  o.a.i.i.p.c.p.GridCacheDatabaseSharedManager - Finished applying memory changes [changesApplied=8, time=65ms]
09:44:34.857 INFO  o.a.i.i.p.c.p.GridCacheDatabaseSharedManager - Checkpoint finished [cpId=f25aee22-0e9e-4737-a0ad-aebc3c5a4bd6, pages=6, markPos=FileWALPointer [idx=0, fileOffset=9076734, len=20281, forceFlush=false], pagesWrite=-3ms, fsync=0ms, total=-3ms]
09:44:34.861 INFO  o.a.i.i.p.c.p.w.FileWriteAheadLogManager - Resuming logging to WAL segment [file=/Users/dan/projects/livefeeds/ignitedb/wal/imac_home/0000000000000000.wal, offset=9097015, ver=1]
09:44:35.065 INFO  o.a.i.i.p.cache.GridCacheProcessor - Started cache [name=ignite-sys-cache, memoryPolicyName=sysMemPlc, mode=REPLICATED, atomicity=TRANSACTIONAL]
09:44:35.085 INFO  o.a.i.i.p.cache.GridCacheProcessor - Started cache [name=ignite-sys-atomic-cache@default-ds-group, group=default-ds-group, memoryPolicyName=default, mode=PARTITIONED, atomicity=TRANSACTIONAL]
09:44:35.087 INFO  o.a.i.i.p.c.d.d.p.GridDhtPartitionsExchangeFuture - Successfully activated caches [nodeId=f616a68d-e171-4384-8dc4-45c2e6788afc, client=false, topVer=AffinityTopologyVersion [topVer=1, minorTopVer=1]]
09:44:35.091 INFO  o.a.i.i.p.c.d.d.p.GridDhtPartitionsExchangeFuture - Finished waiting for partition release future [topVer=AffinityTopologyVersion [topVer=1, minorTopVer=1], waitTime=0ms, futInfo=NA]
09:44:35.139 INFO  o.a.i.i.p.c.p.GridCacheDatabaseSharedManager - Read checkpoint status [startMarker=/Users/dan/projects/livefeeds/ignitedb/storage/imac_home/cp/1512571436282-f25aee22-0e9e-4737-a0ad-aebc3c5a4bd6-START.bin, endMarker=/Users/dan/projects/livefeeds/ignitedb/storage/imac_home/cp/1512571436282-f25aee22-0e9e-4737-a0ad-aebc3c5a4bd6-END.bin]
09:44:35.140 INFO  o.a.i.i.p.c.p.GridCacheDatabaseSharedManager - Applying lost cache updates since last checkpoint record [lastMarked=FileWALPointer [idx=0, fileOffset=9076734, len=20281, forceFlush=false], lastCheckpointId=f25aee22-0e9e-4737-a0ad-aebc3c5a4bd6]
09:44:35.187 INFO  o.a.i.i.p.c.p.GridCacheDatabaseSharedManager - Finished applying WAL changes [updatesApplied=0, time=51ms]
09:44:35.189 INFO  o.a.i.i.p.c.p.GridCacheDatabaseSharedManager - Finished indexes rebuilding for cache: [name=ignite-sys-cache, grpName=null


问:
Sql: Add 2 or more text in one vaule
I'm working on making a school management system and i'm stuck with the following problem: I need put the 2 parents' names up in the database so it would be in one column named parent.

I have tried this query, but it just says "0" with this code:

```<code>INSERT INTO Students (Name, Class, Birthday, Gender, Parent, Phone, Mail, Address)
VALUES ('Test', '1.B', '11-11-2001', 'Male', '$parent' + '&' + '$parent2', '12358912', 'test@mail.dk', 'Test 31');
</code>```

答:
This could be how you do it

```<code>INSERT INTO Students (Name, Class, Birthday, Gender, Parent, Phone, Mail, Address)
VALUES ('Test', '1.B', '11-11-2001', 'Male', $parent & $parent2, '12358912', 'test@mail.dk', 'Test 31');
</code>```

(Take off your quotes, as these are string variables now, not string literals)

Although I would add a space character too: as in

```<code>INSERT INTO Students (Name, Class, Birthday, Gender, Parent, Phone, Mail, Address)
VALUES ('Test', '1.B', '11-11-2001', 'Male', $parent &' '& $parent2, '12358912', 'test@mail.dk', 'Test 31');
</code>```

But it depends on your database system (syntax) etc

Title: Sql: Add 2 or more text in one vaule

Body:
I'm working on making a school management system and i'm stuck with the following problem: I need put the 2 parents' names up in the database so it would be in one column named parent.

I have tried this query, but it just says "0" with this code:

INSERT INTO Students (Name, Class, Birthday, Gender, Parent, Phone, Mail, Address)
VALUES ('Test', '1.B', '11-11-2001', 'Male', '$parent' + '&' + '$parent2', '12358912', 'test@mail.dk', 'Test 31');

Body:
This could be how you do it

INSERT INTO Students (Name, Class, Birthday, Gender, Parent, Phone, Mail, Address)
VALUES ('Test', '1.B', '11-11-2001', 'Male', $parent & $parent2, '12358912', 'test@mail.dk', 'Test 31');

(Take off your quotes, as these are string variables now, not string literals)

Although I would add a space character too: as in

INSERT INTO Students (Name, Class, Birthday, Gender, Parent, Phone, Mail, Address)
VALUES ('Test', '1.B', '11-11-2001', 'Male', $parent &' '& $parent2, '12358912', 'test@mail.dk', 'Test 31');

But it depends on your database system (syntax) etc


问:
ImportError: No module named enum on python 2.7
I'm running a code with Python 2.7. And I get "ImportError: No module named enum". I installed enum with "pip install enum" but the error keeps coming. What shall I do??</p>

答:
You want the backport:

```<code>pip install enum34
</code>```

The distribution named enum on PyPI is something else, unfortunately.

Body:
You want the backport:

pip install enum34

The distribution named enum on PyPI is something else, unfortunately.


问:
Availability statut in product-list not showing Prestashop
when I list all products from a category of my web the products show the availability statut. However, if I choose an option to filter results or I click in the next page button to see other products, this label disappears.

I don't know why it's happen? Any idea?

答:
It seems that you don't have this behavior properly coded in the global.js in the
display function </p>


问:
Chocolatey unzips a previously installed program to the wrong directory
I am trying to install Neovim to the "C:/Program Files" directory via Chocolatey on Windows 7. I had previously installed Neovim via Chocolatey to a different directory ("C:/Tools"), but later uninstalled it.

```<code>cd C:/Program Files
choco install Neovim
</code>```

When running these lines in Powershell (with Administrative privileges) Chocolatey successfully installs Neovim, but to the "C:/Tools" directory where it had previously been installed.

It seems Chocolatey is remembering where it had installed Neovim and ignoring the current directory. Is there a way to prevent this from occurring?

答:
The package itself uses the ChocolateyToolsLocation environment variable to determine install location, but does not have a package parameter that lets you configure just for this package.

Look at the package files - https://chocolatey.org/packages/neovim#files. If you want a different directory, you will need to update the environment variable for ChocolateyToolsLocation to C:\Program Files, then run your installation. This will affect all package installs that use Get-ToolsLocation. HTH

Body:
I am trying to install Neovim to the "C:/Program Files" directory via Chocolatey on Windows 7. I had previously installed Neovim via Chocolatey to a different directory ("C:/Tools"), but later uninstalled it.

cd C:/Program Files
choco install Neovim

When running these lines in Powershell (with Administrative privileges) Chocolatey successfully installs Neovim, but to the "C:/Tools" directory where it had previously been installed.

It seems Chocolatey is remembering where it had installed Neovim and ignoring the current directory. Is there a way to prevent this from occurring?


问:
Java How can I break a while loop under a switch statement?
I have a homework to implement a simple testing application, below is my current code:

```<code>import java.util.*;

public class Test{

private static int typing;

public static void main(String argv[]){
    Scanner sc = new Scanner(System.in);
    System.out.println("Testing starts");
    while(sc.hasNextInt()){
        typing = sc.nextInt();
        switch(typing){
            case 0:
              break; //Here I want to break the while loop
            case 1:
              System.out.println("You choosed 1");
              break;
            case 2:
              System.out.println("You choosed 2");
              break;
            default:
              System.out.println("No such choice");
        }
    }
      System.out.println("Test is done");
    }
}
</code>```

What I want to do now is that when 0 is pressed, it means that the user wants to quit the test, then I break the while loop and print Test is done, but it doesn't work like that, I know the reason might be that the "break" breaks the switch, how can I let it break the while loop instead?

答:
How to terminate inner menu ?

Example Code :

```<code>import java.util.Scanner;

public class Example {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in); //used to get input
        int option1, option2 = 0;
        boolean loop_terminate = true; //flag used to terminate inner while loop

        //Main Menu
        while (true) {
            //Main Menu options
            System.out.println("1.Option 1");
            System.out.println("2.Option 2");
            System.out.println("3.Option 3");
            System.out.println("4.Option 4");
            System.out.println("5.Exit main menu");

            System.out.print("Please enter your choice : ");
            option1 = input.nextInt();

            switch (option1) {

                case 1:
                       //do something here
                    break;
                case 2:
                       //do something here
                    break;
                case 3:

                    while (loop_terminate) {
                        //Inner menu options
                        System.out.println("1.Inner Menu option 1");
                        System.out.println("2.Inner Menu option 2");
                        System.out.println("3.Inner Menu option 3");
                        System.out.println("4.Return to Main Menu");

                        System.out.print("Please enter your choice : ");
                        option2 = input.nextInt();
                        switch (option2) {

                            case 1:
                                break;
                            case 2:
                                break;
                            case 3:
                                break;
                            case 4:
                                loop_terminate = false; //this will terminate inner menu
                                break;
                            default:
                                System.out.println("Invalid option");
                                break;
                        }
                    }
                    break; //never forget to add this break statement
                case 4:
                      break;
                case 5:
                    return; //terminate outer menu

                default:
                    System.out.println("Invalid option");
            }
        }

    }
}
</code>```

Body:
I have a homework to implement a simple testing application, below is my current code:

import java.util.*;

public class Test{

private static int typing;

public static void main(String argv[]){
    Scanner sc = new Scanner(System.in);
    System.out.println("Testing starts");
    while(sc.hasNextInt()){
        typing = sc.nextInt();
        switch(typing){
            case 0:
              break; //Here I want to break the while loop
            case 1:
              System.out.println("You choosed 1");
              break;
            case 2:
              System.out.println("You choosed 2");
              break;
            default:
              System.out.println("No such choice");
        }
    }
      System.out.println("Test is done");
    }
}

What I want to do now is that when 0 is pressed, it means that the user wants to quit the test, then I break the while loop and print Test is done, but it doesn't work like that, I know the reason might be that the "break" breaks the switch, how can I let it break the while loop instead?

Body:
How to terminate inner menu ?

Example Code :

import java.util.Scanner;

public class Example {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in); //used to get input
        int option1, option2 = 0;
        boolean loop_terminate = true; //flag used to terminate inner while loop

        //Main Menu
        while (true) {
            //Main Menu options
            System.out.println("1.Option 1");
            System.out.println("2.Option 2");
            System.out.println("3.Option 3");
            System.out.println("4.Option 4");
            System.out.println("5.Exit main menu");

            System.out.print("Please enter your choice : ");
            option1 = input.nextInt();

            switch (option1) {

                case 1:
                       //do something here
                    break;
                case 2:
                       //do something here
                    break;
                case 3:

                    while (loop_terminate) {
                        //Inner menu options
                        System.out.println("1.Inner Menu option 1");
                        System.out.println("2.Inner Menu option 2");
                        System.out.println("3.Inner Menu option 3");
                        System.out.println("4.Return to Main Menu");

                        System.out.print("Please enter your choice : ");
                        option2 = input.nextInt();
                        switch (option2) {

                            case 1:
                                break;
                            case 2:
                                break;
                            case 3:
                                break;
                            case 4:
                                loop_terminate = false; //this will terminate inner menu
                                break;
                            default:
                                System.out.println("Invalid option");
                                break;
                        }
                    }
                    break; //never forget to add this break statement
                case 4:
                      break;
                case 5:
                    return; //terminate outer menu

                default:
                    System.out.println("Invalid option");
            }
        }

    }
}


问:
getting error at " edittext.getText().toString() " inside a custom dialog
I am facing errors at the following places inside the custom dialogs that i hav created. Is is not possible to hav such functions inside a custom dialog??

final EditText x= (EditText)findViewById(R.id.edtLocationName);

String strTextValue = x.getText().toString();  //here

int x1 =geoLat.intValue()xt().toString();  //and here

答:
you should use

dlgobject.x.getText().toString();

u may use dialog interface to access the contents of a dialog.