问:
Ionic 2 passing tabs NavParams to tab

I'm starting out on creating my first app using Ionic 2 and through a lot of trial and error have got to a point where no number of Google searching can find anything to help.

I'm trying to pass some NavParams to a tab. The NavParams are available in the parent tabs page:

@Page({
    templateUrl: 'build/pages/tabs/tabs.html'
})
export class TabsPage {
  constructor(params: NavParams) {

      this.params = params;
      console.log(this.params); // returns NavParams {data: Object}

      // this tells the tabs component which Pages should be each tab's root Page
      this.tab1Root = Tab1;
      this.tab2Root = Tab2;
      this.tab3Root = Tab3;
    }
}
```

<p>But I cannot seem to get the NavParams within a tab itself:</p>

<pre class="lang-js prettyprint-override"><code>@Page({
    templateUrl: 'build/pages/tab1/tab1.html'
})
export class Tab1 {
    constructor(nav: NavController, params: NavParams, platform: Platform) {
        this.nav = nav;
        this.params = params;
        this.platform = platform;

        console.log(this.params); // returns NavParams {data: null}
    }
}
</code>```

I'm just not entirely sure how to pass the params from the tabs page to the tab itself or somehow request a param from the tab parent. I assume something like:

this.tab1Root = Tab1(this.params);
```

Any help would be greatly appreciated!

答:
I tried with many methods but none of them were helpful to me. As my application did not involve much of complexities, I implemented it using ionic native storage plugin. In the event that triggers the new tab page, I will store some variable in native storage(snippet is as below).

```<code>this.nativeStorage.setItem('myitem', {property: 'value', anotherProperty: 'anotherValue'})
  .then(
    () => console.log('Stored item!'),
    error => console.error('Error storing item', error)
  );
</code>```

In the constructor or ionviewdidload page of the next tab page I will check for this variable and perform the required actions.Snippet is as below.

```<code>this.nativeStorage.getItem('myitem')
  .then(
    data => console.log(data),
    error => console.error(error)
  );
</code>```

Note: This is suitable only for small application or where there is a requirement of passing limited set of variables. If there are lots of variable, it may take more space in the apps cache which may reduce the app performance.

Title: Ionic 2 passing tabs NavParams to tab

Body:
I'm starting out on creating my first app using Ionic 2 and through a lot of trial and error have got to a point where no number of Google searching can find anything to help.

I'm trying to pass some NavParams to a tab. The NavParams are available in the parent tabs page:

@Page({
    templateUrl: 'build/pages/tabs/tabs.html'
})
export class TabsPage {
  constructor(params: NavParams) {

      this.params = params;
      console.log(this.params); // returns NavParams {data: Object}

      // this tells the tabs component which Pages should be each tab's root Page
      this.tab1Root = Tab1;
      this.tab2Root = Tab2;
      this.tab3Root = Tab3;
    }
}

But I cannot seem to get the NavParams within a tab itself:

@Page({
    templateUrl: 'build/pages/tab1/tab1.html'
})
export class Tab1 {
    constructor(nav: NavController, params: NavParams, platform: Platform) {
        this.nav = nav;
        this.params = params;
        this.platform = platform;

        console.log(this.params); // returns NavParams {data: null}
    }
}

I'm just not entirely sure how to pass the params from the tabs page to the tab itself or somehow request a param from the tab parent. I assume something like:

this.tab1Root = Tab1(this.params);

Any help would be greatly appreciated!

Body:
I tried with many methods but none of them were helpful to me. As my application did not involve much of complexities, I implemented it using ionic native storage plugin. In the event that triggers the new tab page, I will store some variable in native storage(snippet is as below).

this.nativeStorage.setItem('myitem', {property: 'value', anotherProperty: 'anotherValue'})
  .then(
    () => console.log('Stored item!'),
    error => console.error('Error storing item', error)
  );

In the constructor or ionviewdidload page of the next tab page I will check for this variable and perform the required actions.Snippet is as below.

this.nativeStorage.getItem('myitem')
  .then(
    data => console.log(data),
    error => console.error(error)
  );

Note: This is suitable only for small application or where there is a requirement of passing limited set of variables. If there are lots of variable, it may take more space in the apps cache which may reduce the app performance.


来源: stackexchange

问:
Union 3 tables with specific column
I have 3 tables and I want to union all but only two columns are able to show data.

```<code>SELECT Vehicle_ID, Total_Weight, date, bilty_No FROM harvesting
UNION
SELECT Vehicle_ID, Total_Weight, date, Bilty_No FROM Blade_Harvesting
</code>```

I want to add another table like below but its giving error

```<code>SELECT Vehicle_ID, Total_Weight, date, bilty_No FROM harvesting
UNION
SELECT Vehicle_ID, Total_Weight, date, Bilty_No FROM Blade_Harvesting
UNION
SELECT Vehicle_ID, Vehicle_Name FROM Vehicle
</code>```

It's giving this error:

All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists

答:
Each SELECT statement within UNION must have the same number of columns.
The columns must also have similar data types.
The columns in each SELECT statement must also be in the same order

Try this

```<code>SELECT Vehicle_ID,cast(Total_Weight as varchar),date,bilty_No FROM harvesting
UNION
SELECT Vehicle_ID,cast(Total_Weight as varchar),date,Bilty_No FROM Blade_Harvesting
union
select Vehicle_ID,Vehicle_Name,'','' from Vehicle
</code>```

ContentLicense: CC BY-SA 3.0

Title: Union 3 tables with specific column

Body:
I have 3 tables and I want to union all but only two columns are able to show data.

SELECT Vehicle_ID, Total_Weight, date, bilty_No FROM harvesting
UNION
SELECT Vehicle_ID, Total_Weight, date, Bilty_No FROM Blade_Harvesting

I want to add another table like below but its giving error

SELECT Vehicle_ID, Total_Weight, date, bilty_No FROM harvesting
UNION
SELECT Vehicle_ID, Total_Weight, date, Bilty_No FROM Blade_Harvesting
UNION
SELECT Vehicle_ID, Vehicle_Name FROM Vehicle

It's giving this error:

All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists

Body:
Each SELECT statement within UNION must have the same number of columns.
The columns must also have similar data types.
The columns in each SELECT statement must also be in the same order

Try this

SELECT Vehicle_ID,cast(Total_Weight as varchar),date,bilty_No FROM harvesting
UNION
SELECT Vehicle_ID,cast(Total_Weight as varchar),date,Bilty_No FROM Blade_Harvesting
union
select Vehicle_ID,Vehicle_Name,'','' from Vehicle


问:
Angular 2 Interface throwing error of non existing property
I have an Angular 2 interface books.ts

```<code>export interface Books {
artists: Object;
tracks: Object;
}
</code>```

This is the my service file where I am using it with http request searchService.ts

```<code>import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Books } from 'app/pages/search-results/books';
import 'rxjs/add/operator/map'

@Injectable()
export class SearchService {

constructor(private _http:Http) { }

 getBook(keyword): Observable<Books[]>{
  return this._http.get('https://api.spotify.com/v1/search?q=' + keyword + '&type=track,artist')
  .map((response: Response) => <Books[]> response.json());
 }
}
</code>```

And this is my component where I am using interface searchResults.ts

```<code>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { SearchService } from 'app/shared/search/search.service';
import { Books } from 'app/pages/search-results/books';

@Component({
 selector: 'app-search-results',
 templateUrl: './search-results.component.html',
 styleUrls: ['./search-results.component.css'],
 providers: [SearchService]
 })
export class SearchResultsComponent implements OnInit {
keyword: any;
sub: any;
books: Books[];
errMessage: string;
arists: Object;

constructor(private _route: ActivatedRoute, private _router: Router,        private _search: SearchService) { }

ngOnInit() {
 this.sub = this._route
  .queryParams
  .subscribe(params => {
    // Defaults to 0 if no query param provided.
    this.keyword = params['keyword'] || 0;
    this.getBooks(this.keyword);
  });

//
}

getBooks(value) {
this._search.getBook(value)
  .subscribe(
  res => {
    this.books = res;
    console.log(res.artists);
  },
  error => { this.errMessage = <any>error }
  );
 }

}
</code>```

The error comes when I try to console the res.artists. The error says Property 'artists' does not exist on type 'Books[]'. I am new to Angular 2 and doesn't know how to fix that.

The response is looks like

```<code>{artists:{limit: 20, item:[]}, tracks:{limit: 20, item:[]}}
</code>```

答:
The problem is that I am getting Object in response and I am assigning it to an Array which is causing the error. I have simply changes the both types to object and it solved my problem.

From this

```<code>books: Books[];
</code>```

To this

```<code>books: Books;
</code>```

Body:
I have an Angular 2 interface books.ts

export interface Books {
artists: Object;
tracks: Object;
}

This is the my service file where I am using it with http request searchService.ts

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Books } from 'app/pages/search-results/books';
import 'rxjs/add/operator/map'

@Injectable()
export class SearchService {

constructor(private _http:Http) { }

 getBook(keyword): Observable<Books[]>{
  return this._http.get('https://api.spotify.com/v1/search?q=' + keyword + '&type=track,artist')
  .map((response: Response) => <Books[]> response.json());
 }
}

And this is my component where I am using interface searchResults.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { SearchService } from 'app/shared/search/search.service';
import { Books } from 'app/pages/search-results/books';

@Component({
 selector: 'app-search-results',
 templateUrl: './search-results.component.html',
 styleUrls: ['./search-results.component.css'],
 providers: [SearchService]
 })
export class SearchResultsComponent implements OnInit {
keyword: any;
sub: any;
books: Books[];
errMessage: string;
arists: Object;

constructor(private _route: ActivatedRoute, private _router: Router,        private _search: SearchService) { }

ngOnInit() {
 this.sub = this._route
  .queryParams
  .subscribe(params => {
    // Defaults to 0 if no query param provided.
    this.keyword = params['keyword'] || 0;
    this.getBooks(this.keyword);
  });

//
}

getBooks(value) {
this._search.getBook(value)
  .subscribe(
  res => {
    this.books = res;
    console.log(res.artists);
  },
  error => { this.errMessage = <any>error }
  );
 }

}

The error comes when I try to console the res.artists. The error says Property 'artists' does not exist on type 'Books[]'. I am new to Angular 2 and doesn't know how to fix that.

The response is looks like

{artists:{limit: 20, item:[]}, tracks:{limit: 20, item:[]}}

Body:
The problem is that I am getting Object in response and I am assigning it to an Array which is causing the error. I have simply changes the both types to object and it solved my problem.

From this

books: Books[];

To this

books: Books;


问:
how to take a screenshot of the iPhone programmatically?
Is it possible in objective C that we can take the screen shot of screen and stored this image in UIImage.</p>

答:
// 100% Work</p>

```<code>- (UIImage *)screenshot
{
  UIGraphicsBeginImageContextWithOptions(self.main_uiview.bounds.size, NO, 2.0f);
  [self.main_uiview drawViewHierarchyInRect:_main_uiview.bounds afterScreenUpdates:YES];

  UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  return image;
}
</code>```

Body:
// 100% Work

- (UIImage *)screenshot
{
  UIGraphicsBeginImageContextWithOptions(self.main_uiview.bounds.size, NO, 2.0f);
  [self.main_uiview drawViewHierarchyInRect:_main_uiview.bounds afterScreenUpdates:YES];

  UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  return image;
}


问:
How to open the push notifications and read the text in Android/iOS device from Appium?
1.When the device receives push how to automate in Appium so that it will open the push notification and read the text.</p>

答:
You can open notifications pane using following inbuilt AndroidDriver's method.

driver.openNotifications();

If you want to scroll down to a specific Push, use following code -

```<code>WebElement element = driver.findElement(By.name("Element Name"));
HashMap<String, String> arguments = new HashMap<String, String>();
arguments.put("element", element.getId());
(JavascriptExecutor)driver.executeScript("mobile: scrollTo", arguments);
</code>```

Note - driver is of type AndroidDriver. If not, then you should type-cast it.

Go through this library for better understanding of functions - https://github.com/appium/java-client

Body:
You can open notifications pane using following inbuilt AndroidDriver's method.

driver.openNotifications();

If you want to scroll down to a specific Push, use following code -

WebElement element = driver.findElement(By.name("Element Name"));
HashMap<String, String> arguments = new HashMap<String, String>();
arguments.put("element", element.getId());
(JavascriptExecutor)driver.executeScript("mobile: scrollTo", arguments);

Note - driver is of type AndroidDriver. If not, then you should type-cast it.

Go through this library for better understanding of functions - https://github.com/appium/java-client


问:
How to create new DWG from existing DWG Files?
I have a web application created using three.js that can create architectural linings, wood claddings and batten screenings. Our 3d Models are from created using Blender since we can't upload autocad files to threejs.

Can autodesk forge give me the ability to create new DWG from my existing DWG files?

for example, I have around separate 5 dwg files and using a web app, I need to put those 5 into 1 dwg file only.

Thanks!

答:
Yes you can achieve this using the Design Automation API: this is a backend technology that allows you to process AutoCAD jobs in the Cloud. You need some AutoCAD API programming skills to use it.

You can then use the Model Derivatives API to convert the resulting dwg(s) into a viewable format that can easily be loaded into the Forge Viewer.


问:
How to add a space between the subtitle and a comma between some of the words?
How would I add a space between the subtitle and a comma between some of the words? I'm using swift 3.</p>

```<code> override
public  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!

    let selectedItem = matchingItems[indexPath.row].placemark
    cell.textLabel?.text = selectedItem.name
    cell.detailTextLabel?.text = selectedItem.subThoroughfare!  + selectedItem.thoroughfare!
    + selectedItem.locality! + selectedItem.administrativeArea! + selectedItem.postalCode!

    return cell
}
</code>```

答:
The reason you are getting crash is because you are force wrapping the optional property of CLPlacemark, also if you want to join address try something like this. Make array of String? with all optional property that you are currently trying to make address without ! after that flatMap array to ignore the nil and then simply joined the array with separator ,.

```<code>override public tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!

    let selectedItem = matchingItems[indexPath.row].placemark
    cell.textLabel?.text = selectedItem.name
    let addressArray = [selectedItem.subThoroughfare, selectedItem.thoroughfare, selectedItem.locality, selectedItem.administrativeArea, selectedItem.postalCode].flatMap({$0})
    if addressArray.isEmpty {
        cell.detailTextLabel?.text = "N/A" //Set any default value
    }
    else {
        cell.detailTextLabel?.text = addressArray.joined(separator: ", ")
    }
    return cell
}
</code>```

Body:
How would I add a space between the subtitle and a comma between some of the words? I'm using swift 3.

 override
public  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!

    let selectedItem = matchingItems[indexPath.row].placemark
    cell.textLabel?.text = selectedItem.name
    cell.detailTextLabel?.text = selectedItem.subThoroughfare!  + selectedItem.thoroughfare!
    + selectedItem.locality! + selectedItem.administrativeArea! + selectedItem.postalCode!

    return cell
}

Body:
The reason you are getting crash is because you are force wrapping the optional property of CLPlacemark, also if you want to join address try something like this. Make array of String? with all optional property that you are currently trying to make address without ! after that flatMap array to ignore the nil and then simply joined the array with separator ,.

override public tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!

    let selectedItem = matchingItems[indexPath.row].placemark
    cell.textLabel?.text = selectedItem.name
    let addressArray = [selectedItem.subThoroughfare, selectedItem.thoroughfare, selectedItem.locality, selectedItem.administrativeArea, selectedItem.postalCode].flatMap({$0})
    if addressArray.isEmpty {
        cell.detailTextLabel?.text = "N/A" //Set any default value
    }
    else {
        cell.detailTextLabel?.text = addressArray.joined(separator: ", ")
    }
    return cell
}


问:
Odoo 8 - on_record_write() not triggered for 'state' field on stock.picking
So I am using the connector to send a status to Magento depending on the status of a stock.picking record in Odoo.

Here is the (beginning of the) function that I use for that :

```<code> @on_record_write(model_names = 'stock.picking')
def change_status_sale_order_sp(session, model_name,
                             record_id, vals):
    if session.context.get('connector_no_export'):
        return
    record = session.env['stock.picking'].browse(record_id)

    if "IN" in record.name: #the stock pickings might be to receive products from the supplier, but we want the one for the deliveries to customers
        return
    origin = record.origin        #String containing the sale order ID + the warehouse from where the order is shipped
    so_name = origin.split(':')[0]
    warehouse = origin.split(':')[1]
    status = record.state

    _logger.debug("STOCK PICKING --- Delivery order " + str(record_id) + " was modified : " + str(vals))
</code>```

I want that function to be called when there is a change on a stock.picking record, hence the decorator on_record_write.

My problem is : that function is called for every write action (every time a field is modified, either manually or on the server side) on a stock.picking record, EXCEPT when it is the state field. I never get the 'vals' parameter to be {'state': whateverthestatusis}. Why is that, am I missing something ?

答:
on_record_write() will every time call when write method of stock.picking will call.

But state field is fields.function field and it will set based on stock moves so you will not get state field in vals of write.

Body:
So I am using the connector to send a status to Magento depending on the status of a stock.picking record in Odoo.

Here is the (beginning of the) function that I use for that :

 @on_record_write(model_names = 'stock.picking')
def change_status_sale_order_sp(session, model_name,
                             record_id, vals):
    if session.context.get('connector_no_export'):
        return
    record = session.env['stock.picking'].browse(record_id)

    if "IN" in record.name: #the stock pickings might be to receive products from the supplier, but we want the one for the deliveries to customers
        return
    origin = record.origin        #String containing the sale order ID + the warehouse from where the order is shipped
    so_name = origin.split(':')[0]
    warehouse = origin.split(':')[1]
    status = record.state

    _logger.debug("STOCK PICKING --- Delivery order " + str(record_id) + " was modified : " + str(vals))

I want that function to be called when there is a change on a stock.picking record, hence the decorator on_record_write.

My problem is : that function is called for every write action (every time a field is modified, either manually or on the server side) on a stock.picking record, EXCEPT when it is the state field. I never get the 'vals' parameter to be {'state': whateverthestatusis}. Why is that, am I missing something ?


问:
What's short Command for making comment and Uncomment the Code?
Short Command for making comment and vice-versa?</p>

答:
command + /

use these commands for comment and uncomment by selecting code.

ContentLicense: CC BY-SA 2.5


问:
Remove extra = (equals to ) symbol from raw email content (which are not user inputs)
I have a java function which reads a raw email content and parses it to get the text content. The emails I send from outlook contains these extra = symbols.

What is Lorem Ipsum?

Lorem Ipsum is simply dummy text of the printing and typesetting
  industry. = Lorem Ipsum has been the industry's standard dummy text
  ever since the 1500= s, when an unknown printer took a galley of type
  and scrambled it to make a=

Something like this. How can I get the email content without these ?

```<code>private static String getTextFromMessage(MimeMessage message) throws IOException, MessagingException {
        StringWriter writer = new StringWriter();
        IOUtils.copy(message.getInputStream(), writer, "UTF-8");
        String s = writer.toString();
        return s;

}
</code>```

I am not looking for how to remove = from a normal string. I want to remove the extra characters added by outlook and retain the user input string as it is

答:
You can use a simple replace method.</p>

```<code>String x = "What is = Lorem Ipsum is simply dummy text of the printing and typesetting industry. = Lorem Ipsum has been the industry's standard dummy text ever since the 1500= s, when an unknown printer took a galley of type and scrambled it to make a=";

System.out.println(x.replace('=', Character.MIN_VALUE));
</code>```

Body:
I have a java function which reads a raw email content and parses it to get the text content. The emails I send from outlook contains these extra = symbols.

What is Lorem Ipsum?

Lorem Ipsum is simply dummy text of the printing and typesetting
  industry. = Lorem Ipsum has been the industry's standard dummy text
  ever since the 1500= s, when an unknown printer took a galley of type
  and scrambled it to make a=

Something like this. How can I get the email content without these ?

private static String getTextFromMessage(MimeMessage message) throws IOException, MessagingException {
        StringWriter writer = new StringWriter();
        IOUtils.copy(message.getInputStream(), writer, "UTF-8");
        String s = writer.toString();
        return s;

}

I am not looking for how to remove = from a normal string. I want to remove the extra characters added by outlook and retain the user input string as it is

Body:
You can use a simple replace method.

String x = "What is = Lorem Ipsum is simply dummy text of the printing and typesetting industry. = Lorem Ipsum has been the industry's standard dummy text ever since the 1500= s, when an unknown printer took a galley of type and scrambled it to make a=";

System.out.println(x.replace('=', Character.MIN_VALUE));


问:
progressbar and thread in xamarin android
I am using thread and progressbar in xamarin android. I am using the following code for progress. But the progressbar is still showing after the thread has completed.
Could anyone help me to resolve this:

```<code>ProgressBar probar=view.FindViewById<ProgressBar>(Resource.Id.progressBar1);
probar.Visibility = ViewStates.Invisible;
Button btnref = view.FindViewById<Button>(Resource.Id.btnrefresh);
    btnref.Click += delegate {
        probar.Visibility = ViewStates.Visible;
        System.Threading.ThreadStart th = new System.Threading.ThreadStart(imagesetting);
        Thread myThread = new Thread(th);
        myThread.Start();
        probar.Visibility = ViewStates.Invisible;
    };

   private void imagesetting() {
        string uri = "example.com/xxx.svc" + Vid + "";
    -----
    }
</code>```

Thanks in Advance,
Manthiram C

答:
1) Make method that hides/show probar on main thread

```<code>private void ShowProgressBar(bool show) {
    RunOnUiThread(() => {
      ProgressBar probar=view.FindViewById<ProgressBar>(Resource.Id.progressBar1);
      probar.Visibility = show ? ViewStates.Visible : ViewStates.Invisible;
    });
}
</code>```

2) Show probar before starting task thread by calling ShowProgressBar(true)

```<code>btnref.Click += delegate {
    ShowProgressBar(true);
    System.Threading.ThreadStart th = new System.Threading.ThreadStart(imagesetting);
    Thread myThread = new Thread(th);
    myThread.Start();
 };
</code>```

3) Hide probar by calling  ShowProgressBar(false) at the end of imagesetting

```<code> private void imagesetting() {
    string uri = "example.com/xxx.svc" + Vid + "";

    *some code*

    ShowProgressBar(false);
 }
</code>```

Body:
I am using thread and progressbar in xamarin android. I am using the following code for progress. But the progressbar is still showing after the thread has completed.
Could anyone help me to resolve this:

ProgressBar probar=view.FindViewById<ProgressBar>(Resource.Id.progressBar1);
probar.Visibility = ViewStates.Invisible;
Button btnref = view.FindViewById<Button>(Resource.Id.btnrefresh);
    btnref.Click += delegate {
        probar.Visibility = ViewStates.Visible;
        System.Threading.ThreadStart th = new System.Threading.ThreadStart(imagesetting);
        Thread myThread = new Thread(th);
        myThread.Start();
        probar.Visibility = ViewStates.Invisible;
    };

   private void imagesetting() {
        string uri = "example.com/xxx.svc" + Vid + "";
    -----
    }

Thanks in Advance,
Manthiram C

Body:
1) Make method that hides/show probar on main thread

private void ShowProgressBar(bool show) {
    RunOnUiThread(() => {
      ProgressBar probar=view.FindViewById<ProgressBar>(Resource.Id.progressBar1);
      probar.Visibility = show ? ViewStates.Visible : ViewStates.Invisible;
    });
}

2) Show probar before starting task thread by calling ShowProgressBar(true)

btnref.Click += delegate {
    ShowProgressBar(true);
    System.Threading.ThreadStart th = new System.Threading.ThreadStart(imagesetting);
    Thread myThread = new Thread(th);
    myThread.Start();
 };

3) Hide probar by calling  ShowProgressBar(false) at the end of imagesetting

 private void imagesetting() {
    string uri = "example.com/xxx.svc" + Vid + "";

    *some code*

    ShowProgressBar(false);
 }


问:
How can I disable users in my active directory domain to access APIs secured with Azure Active Directory?
I have an AD app registration for an API in azure which I generate client secret keys for other applications to authenticate and access my API.  Each client gets a separate secret key.

What I did not realize with this setup is that normal users in the AD domain are also allowed to just log into the API.

How can I disable this so that just clients using the generated secret keys will have access?

答:
If web api app is protected by azure ad , you need to acquire access token to access that web api . If you want to deny some AAD users to access api app , you could firstly set User assignment required for accessing the api app :

Then assign a user or group to an enterprise app in Azure Active Directory , only assigned users could access that app .


答:
You must specify equal columns in your all UNION SELECT clause :</p>

```<code>   SELECT Vehicle_ID VehicleId, Total_Weight TotalWeight,date,bilty_No
          biltyNo,'' VehicleName
   FROM harvesting
   UNION ALL
   SELECT Vehicle_ID VehicleId, Total_Weight TotalWeight,date,Bilty_No
          biltyNo ,'' VehicleName
   FROM Blade_Harvesting
   UNION ALL
   SELECT Vehicle_ID VehicleId ,0 TotalWeight,'' date ,'' biltyNo
          ,Vehicle_Name VehicleName
   FROM Vehicle
</code>```

Title: Union 3 tables with specific column

Body:
You must specify equal columns in your all UNION SELECT clause :

   SELECT Vehicle_ID VehicleId, Total_Weight TotalWeight,date,bilty_No
          biltyNo,'' VehicleName
   FROM harvesting
   UNION ALL
   SELECT Vehicle_ID VehicleId, Total_Weight TotalWeight,date,Bilty_No
          biltyNo ,'' VehicleName
   FROM Blade_Harvesting
   UNION ALL
   SELECT Vehicle_ID VehicleId ,0 TotalWeight,'' date ,'' biltyNo
          ,Vehicle_Name VehicleName
   FROM Vehicle


问:
Applying padding to the head of table
Is there any way i can set padding to the thead alone of a table?</p>

答:
```<code>table th
{
padding:15px;
}
</code>```

Title: Applying padding to the head of table

Body:
table th
{
padding:15px;
}


问:
Can't find my.ini (mysql 5.7)
I've installed MySQL 5.7 and I'm trying to change the default setting written in my.ini file.

So, I followed the path that I found in Stackoverflow (MySQL\MySQL Server 5.7).

However, what I found was only a few folders, but not my.ini file.
I searched every folder, but I couldn't find it. Where is it?

答:
I found a solution  by myself. </p>

<p>What I've been doing so far was just keep searching MySQL\MySQL Server 5.7 path inside Program file folder.  However my.ini was in  mysql path located in Program Data folder, which is hidden in C drive.  So, anyone who are suffering from the same problem, just go to C drive and make all the folder visible and you will find my.ini. </p>

Title: Can't find my.ini (mysql 5.7)

Body:
I found a solution  by myself.

What I've been doing so far was just keep searching MySQL\MySQL Server 5.7 path inside Program file folder.  However my.ini was in  mysql path located in Program Data folder, which is hidden in C drive.  So, anyone who are suffering from the same problem, just go to C drive and make all the folder visible and you will find my.ini.


问:
404 errors after url rewrite with .htaccess
I'm using url rewriting in my website.

I've these url:

works

      example.com/_new/app/planning

      example.com/_new/app/user_info

  doesn't work (404)

      example.com/_new/try

      example.com/_new/features

Here my rules:

```<code>RewriteEngine On

# Removing extension
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

# example.com/app/[module]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^app/([^/]+)$ app.php?param1=$1 [L]

# example.com/app/[module]/[action]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^app/([^/]+)/([^/]+)$ app.php?param1=$1&param2=$2 [L]

# example.com/app/[module]/[action]/[type]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^app/([^/]+)/([^/]+)/([^/]+)$ app.php?param1=$1&param2=$2&param3=$3 [L]

# example.com/app/[module]/[action]/[type]/[id]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^app/([^/]+)/([^/]+)/([^/]+)/([^/]+)$ app.php?param1=$1&param2=$2&param3=$3&param4=$4 [L]
</code>```

Here the file structure:

```<code>/_new/
/_new/try.php
/_new/login.php
/_new/app.php
</code>```

The try.php and index.php should be shown as example.com/try or example.com/login.

The app.php loads module from another directory. This one should be:
example.com/app/module_name.

What's the problem ?

Thanks.

答:
In htaccess, the base URL example.com will be skipped in the matching, and in your file, the first regex ([^\.]+) will match /_new/try  and it tries to redirect you to a file /_new/try.php which does not exist, hence 404.

Make sure to test your regex before trying to use the URL, you can benefit from https://regex101.com/ to make your tests.

Body:
I'm using url rewriting in my website.

I've these url:

works

      example.com/_new/app/planning

      example.com/_new/app/user_info

  doesn't work (404)

      example.com/_new/try

      example.com/_new/features

Here my rules:

RewriteEngine On

# Removing extension
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

# example.com/app/[module]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^app/([^/]+)$ app.php?param1=$1 [L]

# example.com/app/[module]/[action]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^app/([^/]+)/([^/]+)$ app.php?param1=$1&param2=$2 [L]

# example.com/app/[module]/[action]/[type]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^app/([^/]+)/([^/]+)/([^/]+)$ app.php?param1=$1&param2=$2&param3=$3 [L]

# example.com/app/[module]/[action]/[type]/[id]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^app/([^/]+)/([^/]+)/([^/]+)/([^/]+)$ app.php?param1=$1&param2=$2&param3=$3&param4=$4 [L]

Here the file structure:

/_new/
/_new/try.php
/_new/login.php
/_new/app.php

The try.php and index.php should be shown as example.com/try or example.com/login.

The app.php loads module from another directory. This one should be:
example.com/app/module_name.

What's the problem ?

Thanks.


问:
Add My Order link active in customer account
Right now in default magento when customer login into his/her account then Active menu shown to customer is Account Dashboard

I want to show My orders when customer login into account.
I used this peace of code.

```<code><customer_account>
<reference name="customer_account_navigation">
            <action method="setActive"><name>orders</name><path>sales/order/history/</path></action>
        </reference>
</customer_account>
</code>```

but it didn't work. Please suggest me any solution or give me an alternate idea to do that.

答:
Open app\code\core\Mage\Customer\controllers\AccountController.php

Find code  $this->_loginPostRedirect() in public function loginPostAction() and
replace with $this->_redirect('sales/order/history/');

Body:
Right now in default magento when customer login into his/her account then Active menu shown to customer is Account Dashboard

I want to show My orders when customer login into account.
I used this peace of code.

<customer_account>
<reference name="customer_account_navigation">
            <action method="setActive"><name>orders</name><path>sales/order/history/</path></action>
        </reference>
</customer_account>

but it didn't work. Please suggest me any solution or give me an alternate idea to do that.


问:
Why NLTK Lemmatizer can't lemmatize some plural words?
I have tried to lemmatize a words from Quran Holy Book, but some words can't be lemmatized.

here's my sentence:

```<code>sentence = "Then bring ten surahs like it that have been invented and call upon for assistance whomever you can besides Allah if you should be truthful"
</code>```

that sentence is part of my txt dataset.
as you can see, there's "surahs" which is a plural form of "surah".
I've tried my codes:

```<code>def lemmatize(self, ayat):
    wordnet_lemmatizer = WordNetLemmatizer()
    result = []

    for i in xrange (len(ayat)):
        result.append(wordnet_lemmatizer.lemmatize(sentence[i],'v'))
    return result
</code>```

which when I run and print, the result is like this:

```<code>['bring', 'ten', 'surahs', 'like', u'invent', 'call', 'upon', 'assistance', 'whomever', 'besides', 'Allah', 'truthful']
</code>```

the 'surahs' isn't changed into 'surah'.

anybody can tell why? thanks.

答:
See

Stemming some plurals with wordnet lemmatizer doesn't work

Python NLTK Lemmatization of the word 'further' with wordnet

For most non-standard English word, WordNet Lemmatizer is not going to help much in getting the correct lemma, try a stemmer:

```<code>>>> from nltk.stem import PorterStemmer
>>> porter = PorterStemmer()
>>> porter.stem('surahs')
u'surah'
</code>```

Also, try the lemmatize_sent in earthy (an nltk wrapper, "shameless plug"):

```<code>>>> from earthy.nltk_wrappers import lemmatize_sent
>>> sentence = "Then bring ten surahs like it that have been invented and call upon for assistance whomever you can besides Allah if you should be truthful"
>>> lemmatize_sent(sentence)
[('Then', 'Then', 'RB'), ('bring', 'bring', 'VBG'), ('ten', 'ten', 'RP'), ('surahs', 'surahs', 'NNS'), ('like', 'like', 'IN'), ('it', 'it', 'PRP'), ('that', 'that', 'WDT'), ('have', 'have', 'VBP'), ('been', u'be', 'VBN'), ('invented', u'invent', 'VBN'), ('and', 'and', 'CC'), ('call', 'call', 'VB'), ('upon', 'upon', 'NN'), ('for', 'for', 'IN'), ('assistance', 'assistance', 'NN'), ('whomever', 'whomever', 'NN'), ('you', 'you', 'PRP'), ('can', 'can', 'MD'), ('besides', 'besides', 'VB'), ('Allah', 'Allah', 'NNP'), ('if', 'if', 'IN'), ('you', 'you', 'PRP'), ('should', 'should', 'MD'), ('be', 'be', 'VB'), ('truthful', 'truthful', 'JJ')]

>>> words, lemmas, tags = zip(*lemmatize_sent(sentence))
>>> lemmas
('Then', 'bring', 'ten', 'surahs', 'like', 'it', 'that', 'have', u'be', u'invent', 'and', 'call', 'upon', 'for', 'assistance', 'whomever', 'you', 'can', 'besides', 'Allah', 'if', 'you', 'should', 'be', 'truthful')

>>> from earthy.nltk_wrappers import pywsd_lemmatize
>>> pywsd_lemmatize('surahs')
'surahs'

>>> from earthy.nltk_wrappers import porter_stem
>>> porter_stem('surahs')
u'surah'
</code>```

Body:
I have tried to lemmatize a words from Quran Holy Book, but some words can't be lemmatized.

here's my sentence:

sentence = "Then bring ten surahs like it that have been invented and call upon for assistance whomever you can besides Allah if you should be truthful"

that sentence is part of my txt dataset.
as you can see, there's "surahs" which is a plural form of "surah".
I've tried my codes:

def lemmatize(self, ayat):
    wordnet_lemmatizer = WordNetLemmatizer()
    result = []

    for i in xrange (len(ayat)):
        result.append(wordnet_lemmatizer.lemmatize(sentence[i],'v'))
    return result

which when I run and print, the result is like this:

['bring', 'ten', 'surahs', 'like', u'invent', 'call', 'upon', 'assistance', 'whomever', 'besides', 'Allah', 'truthful']

the 'surahs' isn't changed into 'surah'.

anybody can tell why? thanks.

Body:
See

Stemming some plurals with wordnet lemmatizer doesn't work

Python NLTK Lemmatization of the word 'further' with wordnet

For most non-standard English word, WordNet Lemmatizer is not going to help much in getting the correct lemma, try a stemmer:

>>> from nltk.stem import PorterStemmer
>>> porter = PorterStemmer()
>>> porter.stem('surahs')
u'surah'

Also, try the lemmatize_sent in earthy (an nltk wrapper, "shameless plug"):

>>> from earthy.nltk_wrappers import lemmatize_sent
>>> sentence = "Then bring ten surahs like it that have been invented and call upon for assistance whomever you can besides Allah if you should be truthful"
>>> lemmatize_sent(sentence)
[('Then', 'Then', 'RB'), ('bring', 'bring', 'VBG'), ('ten', 'ten', 'RP'), ('surahs', 'surahs', 'NNS'), ('like', 'like', 'IN'), ('it', 'it', 'PRP'), ('that', 'that', 'WDT'), ('have', 'have', 'VBP'), ('been', u'be', 'VBN'), ('invented', u'invent', 'VBN'), ('and', 'and', 'CC'), ('call', 'call', 'VB'), ('upon', 'upon', 'NN'), ('for', 'for', 'IN'), ('assistance', 'assistance', 'NN'), ('whomever', 'whomever', 'NN'), ('you', 'you', 'PRP'), ('can', 'can', 'MD'), ('besides', 'besides', 'VB'), ('Allah', 'Allah', 'NNP'), ('if', 'if', 'IN'), ('you', 'you', 'PRP'), ('should', 'should', 'MD'), ('be', 'be', 'VB'), ('truthful', 'truthful', 'JJ')]

>>> words, lemmas, tags = zip(*lemmatize_sent(sentence))
>>> lemmas
('Then', 'bring', 'ten', 'surahs', 'like', 'it', 'that', 'have', u'be', u'invent', 'and', 'call', 'upon', 'for', 'assistance', 'whomever', 'you', 'can', 'besides', 'Allah', 'if', 'you', 'should', 'be', 'truthful')

>>> from earthy.nltk_wrappers import pywsd_lemmatize
>>> pywsd_lemmatize('surahs')
'surahs'

>>> from earthy.nltk_wrappers import porter_stem
>>> porter_stem('surahs')
u'surah'


问:
Springboot ErrorPageFilter issue
I am having a problem when deploying my .war file using springboot 1.4.0 to wildfly 10.  I got a strange error as follow.  I do not know what is going wrong.  I got this error all of the sudden since last week.  I saw some people had this same error, and suggest to turn off the ErrorPageFilter, but I afraid that might not be the root cause.  I do not know what is wrong and hence no idea how to fix this issue.  It would be much appreciated if someone can help to point out my error.  Thanks in advance.  </p>

```<code>ERROR ErrorPageFilter:208 - Cannot forward to error page for request [/form] as the response has already been committed. As a result, the response may have the wrong status code. If your application is running on WebSphere Application Server you may be able to resolve this problem by setting com.ibm.ws.webcontainer.invokeFlushAfterService to false
java.io.IOException: An established connection was aborted by the software in your host machine
at sun.nio.ch.SocketDispatcher.writev0(Native Method)
at sun.nio.ch.SocketDispatcher.writev(SocketDispatcher.java:55)
at sun.nio.ch.IOUtil.write(IOUtil.java:148)
at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:504)
at org.xnio.nio.NioSocketConduit.write(NioSocketConduit.java:162)
at io.undertow.conduits.AbstractFramedStreamSinkConduit.doWrite(AbstractFramedStreamSinkConduit.java:140)
at io.undertow.conduits.AbstractFramedStreamSinkConduit.flushQueuedData(AbstractFramedStreamSinkConduit.java:210)
at io.undertow.server.protocol.ajp.AjpServerResponseConduit.write(AjpServerResponseConduit.java:268)
at io.undertow.server.protocol.ajp.AjpServerResponseConduit.write(AjpServerResponseConduit.java:352)
at org.xnio.conduits.ConduitStreamSinkChannel.write(ConduitStreamSinkChannel.java:158)
at io.undertow.channels.DetachableStreamSinkChannel.write(DetachableStreamSinkChannel.java:179)
at io.undertow.server.HttpServerExchange$WriteDispatchChannel.write(HttpServerExchange.java:1993)
at org.xnio.channels.Channels.writeBlocking(Channels.java:152)
at io.undertow.servlet.spec.ServletOutputStreamImpl.write(ServletOutputStreamImpl.java:180)
at com.fasterxml.jackson.core.json.UTF8JsonGenerator._flushBuffer(UTF8JsonGenerator.java:1982)
at com.fasterxml.jackson.core.json.UTF8JsonGenerator._writeBytes(UTF8JsonGenerator.java:1071)
at com.fasterxml.jackson.core.json.UTF8JsonGenerator.writeFieldName(UTF8JsonGenerator.java:240)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:670)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:678)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:157)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:672)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:678)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:157)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:672)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:678)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:157)
at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:149)
at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:112)
at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:25)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:672)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:678)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:157)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:672)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:678)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:157)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:130)
at com.fasterxml.jackson.databind.ObjectWriter$Prefetch.serialize(ObjectWriter.java:1428)
at com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:930)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:267)
at org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:100)
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:232)
at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:198)
at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:81)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:130)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
at com.dbs.lp.component.form.config.JwtFilter.doFilter(JwtFilter.java:67)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at com.dbs.lp.component.form.config.LpCorsFilter.doFilter(LpCorsFilter.java:39)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:87)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:119)
at org.springframework.boot.web.support.ErrorPageFilter.access$000(ErrorPageFilter.java:61)
at org.springframework.boot.web.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:94)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:112)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:805)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
</code>```

答:
It seems you have to disable the ErrorPageFilter. You can do this setting this beans to your spring configuration: </p>

```<code>@Bean
public ErrorPageFilter errorPageFilter() {
    return new ErrorPageFilter();
}

@Bean
public FilterRegistrationBean disableSpringBootErrorFilter(ErrorPageFilter filter) {
    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
    filterRegistrationBean.setFilter(filter);
    filterRegistrationBean.setEnabled(false);
    return filterRegistrationBean;
}
</code>```

Title: Springboot ErrorPageFilter issue

Body:
I am having a problem when deploying my .war file using springboot 1.4.0 to wildfly 10.  I got a strange error as follow.  I do not know what is going wrong.  I got this error all of the sudden since last week.  I saw some people had this same error, and suggest to turn off the ErrorPageFilter, but I afraid that might not be the root cause.  I do not know what is wrong and hence no idea how to fix this issue.  It would be much appreciated if someone can help to point out my error.  Thanks in advance.

ERROR ErrorPageFilter:208 - Cannot forward to error page for request [/form] as the response has already been committed. As a result, the response may have the wrong status code. If your application is running on WebSphere Application Server you may be able to resolve this problem by setting com.ibm.ws.webcontainer.invokeFlushAfterService to false
java.io.IOException: An established connection was aborted by the software in your host machine
at sun.nio.ch.SocketDispatcher.writev0(Native Method)
at sun.nio.ch.SocketDispatcher.writev(SocketDispatcher.java:55)
at sun.nio.ch.IOUtil.write(IOUtil.java:148)
at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:504)
at org.xnio.nio.NioSocketConduit.write(NioSocketConduit.java:162)
at io.undertow.conduits.AbstractFramedStreamSinkConduit.doWrite(AbstractFramedStreamSinkConduit.java:140)
at io.undertow.conduits.AbstractFramedStreamSinkConduit.flushQueuedData(AbstractFramedStreamSinkConduit.java:210)
at io.undertow.server.protocol.ajp.AjpServerResponseConduit.write(AjpServerResponseConduit.java:268)
at io.undertow.server.protocol.ajp.AjpServerResponseConduit.write(AjpServerResponseConduit.java:352)
at org.xnio.conduits.ConduitStreamSinkChannel.write(ConduitStreamSinkChannel.java:158)
at io.undertow.channels.DetachableStreamSinkChannel.write(DetachableStreamSinkChannel.java:179)
at io.undertow.server.HttpServerExchange$WriteDispatchChannel.write(HttpServerExchange.java:1993)
at org.xnio.channels.Channels.writeBlocking(Channels.java:152)
at io.undertow.servlet.spec.ServletOutputStreamImpl.write(ServletOutputStreamImpl.java:180)
at com.fasterxml.jackson.core.json.UTF8JsonGenerator._flushBuffer(UTF8JsonGenerator.java:1982)
at com.fasterxml.jackson.core.json.UTF8JsonGenerator._writeBytes(UTF8JsonGenerator.java:1071)
at com.fasterxml.jackson.core.json.UTF8JsonGenerator.writeFieldName(UTF8JsonGenerator.java:240)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:670)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:678)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:157)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:672)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:678)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:157)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:672)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:678)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:157)
at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:149)
at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:112)
at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:25)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:672)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:678)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:157)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:672)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:678)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:157)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:130)
at com.fasterxml.jackson.databind.ObjectWriter$Prefetch.serialize(ObjectWriter.java:1428)
at com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:930)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:267)
at org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:100)
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:232)
at org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:198)
at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:81)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:130)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
at com.dbs.lp.component.form.config.JwtFilter.doFilter(JwtFilter.java:67)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at com.dbs.lp.component.form.config.LpCorsFilter.doFilter(LpCorsFilter.java:39)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:87)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:119)
at org.springframework.boot.web.support.ErrorPageFilter.access$000(ErrorPageFilter.java:61)
at org.springframework.boot.web.support.ErrorPageFilter$1.doFilterInternal(ErrorPageFilter.java:94)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.boot.web.support.ErrorPageFilter.doFilter(ErrorPageFilter.java:112)
at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:805)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

Body:
It seems you have to disable the ErrorPageFilter. You can do this setting this beans to your spring configuration:

@Bean
public ErrorPageFilter errorPageFilter() {
    return new ErrorPageFilter();
}

@Bean
public FilterRegistrationBean disableSpringBootErrorFilter(ErrorPageFilter filter) {
    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
    filterRegistrationBean.setFilter(filter);
    filterRegistrationBean.setEnabled(false);
    return filterRegistrationBean;
}


问:
How to crop center part of large image in iOS?
When a image is cropped from the center then crop image will take the aspect ratio of source image,But According to my requirement, aspect ratio will be change with new crop size.

I want to get exact center part of image with new aspect ratio.For example a large image is of size (320*480) then I want to crop center part of image of size (100,100) and aspect ratio will also be 100*100 ,No outer white or black part is required and image quality will be high.

Cropping function :

```<code>- (UIImage *)cropImage:(UIImage*)image andFrame:(CGRect)rect {

    //Note : rec is nothing but the image frame which u want to crop exactly.

    rect = CGRectMake(rect.origin.x*image.scale,
                      rect.origin.y*image.scale,
                      rect.size.width*image.scale,
                      rect.size.height*image.scale);

    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
    UIImage *result = [UIImage imageWithCGImage:imageRef
                                          scale:image.scale
                                    orientation:image.imageOrientation];
    CGImageRelease(imageRef);
    return result;
}
</code>```

Please help me.

答:
// Work this code

```<code>     -(UIImage *)croppedImage
    {
    UIImage *myImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [self.bezierPath closePath];
    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 0.0, 0.0);
    _b_image = self.bg_imageview.image;
    CGSize imageSize = _b_image.size;
    CGRect imageRect = CGRectMake(0, 0, imageSize.width, imageSize.height);
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, [[UIScreen mainScreen] scale]);
    [self.bezierPath addClip];
    [_b_image drawInRect:imageRect];

    UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
return croppedImage;
</code>```

}

Body:
When a image is cropped from the center then crop image will take the aspect ratio of source image,But According to my requirement, aspect ratio will be change with new crop size.

I want to get exact center part of image with new aspect ratio.For example a large image is of size (320*480) then I want to crop center part of image of size (100,100) and aspect ratio will also be 100*100 ,No outer white or black part is required and image quality will be high.

Cropping function :

- (UIImage *)cropImage:(UIImage*)image andFrame:(CGRect)rect {

    //Note : rec is nothing but the image frame which u want to crop exactly.

    rect = CGRectMake(rect.origin.x*image.scale,
                      rect.origin.y*image.scale,
                      rect.size.width*image.scale,
                      rect.size.height*image.scale);

    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
    UIImage *result = [UIImage imageWithCGImage:imageRef
                                          scale:image.scale
                                    orientation:image.imageOrientation];
    CGImageRelease(imageRef);
    return result;
}

Please help me.

Body:
// Work this code

     -(UIImage *)croppedImage
    {
    UIImage *myImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [self.bezierPath closePath];
    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 0.0, 0.0);
    _b_image = self.bg_imageview.image;
    CGSize imageSize = _b_image.size;
    CGRect imageRect = CGRectMake(0, 0, imageSize.width, imageSize.height);
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, [[UIScreen mainScreen] scale]);
    [self.bezierPath addClip];
    [_b_image drawInRect:imageRect];

    UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
return croppedImage;

}


问:
prints results only when string item index == list item index
I've been working on a little project of mine lately, but I've run into a problem that I'm stuck at. I've already checked various places, but I couldn't really find what I'm looking for. This is my code:

```<code>special_alphabet = [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u,
v, w, x, y, z]

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k','l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

name = input('Please insert your name: ')

item_alphabet = -1
item_special_alphabet = -1
index = -1

for item in name:
    item_alphabet = item_alphabet + 1
    item_special_alphabet = item_special_alphabet + 1
    index = index + 1

    if alphabet[item_alphabet] == name[index]:
        print(special_alphabet[item_special_alphabet])
</code>```

The special_alphabet list contains the special characters that I have in variables. I didn't display them because they're too long, but they're there.

The problem I'm having right now is that when I run this code and type in my input, it does actually check the 'name' (string) I've inserted, it just does it in order of the list(alphabet basically). So when I enter: Amine, it only returns the special character for A (because it's the first (0) in both the string and the list) and E (same reason, just it's fifth.)

What I'm looking for is how to make it go through the whole list without any order whatsoever and check all the items in it before running the if statement and printing out the special characters.
Thank you in advance.

答:
You can use str.maketrans() and str.translate() for these kinds of translation jobs:

```<code>trans_tab = str.maketrans(dict(zip(alphabet, special_alphabet)))
name = input('Please insert your name: ')
translated_name = name.translate(trans_tab)
print(translated_name)
</code>```

If you pass str.maketrans() a single dictionary argument that consists of strings of length 1 as keys and arbitrary length strings as values, it'll build you a translation table usable with str.translate(), which creates a new copy of the string where each character has been mapped through the given translation table.

For example:

```<code>In [15]: trans = str.maketrans({
    ...:     'A': 'A ',
    ...:     'm': 'M ',
    ...:     'i': 'I ',
    ...:     'n': 'N ',
    ...:     'e': 'E '
    ...: })

In [16]: input("> ").translate(trans)
> Amine
Out[16]: 'A M I N E '
</code>```

Body:
I've been working on a little project of mine lately, but I've run into a problem that I'm stuck at. I've already checked various places, but I couldn't really find what I'm looking for. This is my code:

special_alphabet = [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u,
v, w, x, y, z]

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k','l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

name = input('Please insert your name: ')

item_alphabet = -1
item_special_alphabet = -1
index = -1

for item in name:
    item_alphabet = item_alphabet + 1
    item_special_alphabet = item_special_alphabet + 1
    index = index + 1

    if alphabet[item_alphabet] == name[index]:
        print(special_alphabet[item_special_alphabet])

The special_alphabet list contains the special characters that I have in variables. I didn't display them because they're too long, but they're there.

The problem I'm having right now is that when I run this code and type in my input, it does actually check the 'name' (string) I've inserted, it just does it in order of the list(alphabet basically). So when I enter: Amine, it only returns the special character for A (because it's the first (0) in both the string and the list) and E (same reason, just it's fifth.)

What I'm looking for is how to make it go through the whole list without any order whatsoever and check all the items in it before running the if statement and printing out the special characters.
Thank you in advance.

Body:
You can use str.maketrans() and str.translate() for these kinds of translation jobs:

trans_tab = str.maketrans(dict(zip(alphabet, special_alphabet)))
name = input('Please insert your name: ')
translated_name = name.translate(trans_tab)
print(translated_name)

If you pass str.maketrans() a single dictionary argument that consists of strings of length 1 as keys and arbitrary length strings as values, it'll build you a translation table usable with str.translate(), which creates a new copy of the string where each character has been mapped through the given translation table.

For example:

In [15]: trans = str.maketrans({
    ...:     'A': 'A ',
    ...:     'm': 'M ',
    ...:     'i': 'I ',
    ...:     'n': 'N ',
    ...:     'e': 'E '
    ...: })

In [16]: input("> ").translate(trans)
> Amine
Out[16]: 'A M I N E '


问:
SQL 2005: NOLOCK hint dramatically increases reads. WTF?
I have a stored procedure that does a lot more reads when the NOLOCK hint is added to the query. I'm baffled - does anyone know why, please?

Details:
The query is:

```<code>SELECT * FROM dbo.<table-name> WITH (NOLOCK).
</code>```

It was doing 40,000 reads and there are less than 2,000 rows. I established that most of these reads are caused by 3 TEXT columns. (If I omit those it goes down to 59 reads!) But when I delete the WITH (NOLOCK) it goes from 40,000 reads to 13,000. I repeated this a few times because I thought I must have screwed up but it's really consistent both ways.

答:
NOLOCK reads data from transactions that have not been committed.

EDIT

Demo of NOLOCK read of uncommitted data.

```<code>create table table1 (id int, val int)
go

select * from table1 with ( NoLock)
begin tran
insert into table1 values (1,1)

--Switch to new query window
select * from table1 with ( NoLock)
--switch back
rollback tran
select * from table1 with ( NoLock)
</code>```

OwnerDisplayName: David Wimbush

Body:
I have a stored procedure that does a lot more reads when the NOLOCK hint is added to the query. I'm baffled - does anyone know why, please?

Details:
The query is:

SELECT * FROM dbo.
 WITH (NOLOCK).

It was doing 40,000 reads and there are less than 2,000 rows. I established that most of these reads are caused by 3 TEXT columns. (If I omit those it goes down to 59 reads!) But when I delete the WITH (NOLOCK) it goes from 40,000 reads to 13,000. I repeated this a few times because I thought I must have screwed up but it's really consistent both ways.

LastEditorDisplayName: rwmnau

Body:
NOLOCK reads data from transactions that have not been committed.

EDIT

Demo of NOLOCK read of uncommitted data.

create table table1 (id int, val int)
go

select * from table1 with ( NoLock)
begin tran
insert into table1 values (1,1)

--Switch to new query window
select * from table1 with ( NoLock)
--switch back
rollback tran
select * from table1 with ( NoLock)

OwnerDisplayName: cmsjr


问:
How do I address the element position when using filter in Swift
myData is an array of structs. I want to create a new array omitting the struct element in the second position.

```<code>var newData = myData.filter{$0 != 1 } // doesn't work
</code>```

答:
If you want to remove just 2nd object then instead of filter you can try like this.

```<code>var newData = myData
newData.remove(at: 1)
</code>```

If you still want answer with filter then you can make it like this.

```<code>var positionThatNeedToRemove = [1, 4, 7]
var newData = myData.enumerated().filter { !positionThatNeedToRemove.contains($0.offset) }.map { $0.element }
</code>```

Body:
myData is an array of structs. I want to create a new array omitting the struct element in the second position.

var newData = myData.filter{$0 != 1 } // doesn't work

Body:
If you want to remove just 2nd object then instead of filter you can try like this.

var newData = myData
newData.remove(at: 1)

If you still want answer with filter then you can make it like this.

var positionThatNeedToRemove = [1, 4, 7]
var newData = myData.enumerated().filter { !positionThatNeedToRemove.contains($0.offset) }.map { $0.element }


问:
Deploying Aurelia application to Azure
I have followed all the steps here to deploy my Aurelia application to Azure, however I am getting the following error when I try to access the application URL:

You do not have permission to view this directory or page.

My application is essentially the same as the skeleton app and has no server.js or node.js file.

Can anybody point me in the right direction on how to deploy my application?

答:
According the intrdocution:

Aurelia is a next generation UI framework.

Which means that the Aurelia is a fronted javascript library, and a Node.js server application, which should be based on a HTML+CSS application architecture. Need a index.html file in the root directory of your application at least. You can make a complete Aurelia application as mentioned at http://aurelia.io/hub.html#/doc/article/aurelia/framework/latest/quick-start/1, and deploy it to Azure.

Furthermore, we can leverage Custom Deployment Script to bundle the Javascript sources via gulp or babel, you can refer the answer of Custom startup command for Node.js app on Azure with Babel 6 for details.

Title: Deploying Aurelia application to Azure


问:
How to fix add to cart page refresh issue in magento?
I have created one woocommerce site in magento, I am facing one issue in add to cart page. how to add a product in cart without refreshing the page? . Please suggest.</p>

答:
You can use the ajax request for add to car withour refreashing the page.
See the below link for how to customize this functionality.

http://excellencemagentoblog.com/blog/2011/10/04/magento-add-product-to-cart-ajax/


问:
SQL Server where clause statement do not work on certain "columns"
I am creating a website in ASPX which can pull out a data from the database (LocalDB) using a where clause function. Currently, I am trying to pull out a column "Message" where user='xxx'.

Here is my statement:

```<code>protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=myConnectionString");

    SqlCommand command = new SqlCommand("SELECT Message FROM Enquiry WHERE User = 'abc'");
    command.Connection = conn;

    conn.Open();
    string value = (string)command.ExecuteScalar();
    conn.Close();

    Label1.Text = value;
}
</code>```

The problem is that it does not pull out any data if I used "User" in the where clause, however it does work if I use "Id" or other columns.

Does not work

```<code>SELECT Message
FROM Enquiry
WHERE User = 'abc';
</code>```

This works

```<code>SELECT Message
FROM Enquiry
WHERE Id = '1';
</code>```

I have tried to look for any misspelling but when using a break-point, the value returned is a null value. There is no spelling error whatsoever, does anyone encounter this before?

答:
Did you really use User as the name for your column?

If so the try this using this [User].

As far as I know USER is a reserved word from SQL Server.

It should be something like:

```<code>SELECT Message
FROM Enquiry
WHERE [User] = 'abc'
</code>```

Body:
I am creating a website in ASPX which can pull out a data from the database (LocalDB) using a where clause function. Currently, I am trying to pull out a column "Message" where user='xxx'.

Here is my statement:

protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=myConnectionString");

    SqlCommand command = new SqlCommand("SELECT Message FROM Enquiry WHERE User = 'abc'");
    command.Connection = conn;

    conn.Open();
    string value = (string)command.ExecuteScalar();
    conn.Close();

    Label1.Text = value;
}

The problem is that it does not pull out any data if I used "User" in the where clause, however it does work if I use "Id" or other columns.

Does not work

SELECT Message
FROM Enquiry
WHERE User = 'abc';

This works

SELECT Message
FROM Enquiry
WHERE Id = '1';

I have tried to look for any misspelling but when using a break-point, the value returned is a null value. There is no spelling error whatsoever, does anyone encounter this before?

Body:
Did you really use User as the name for your column?

If so the try this using this [User].

As far as I know USER is a reserved word from SQL Server.

It should be something like:

SELECT Message
FROM Enquiry
WHERE [User] = 'abc'


问:
How to display array in array on Highcharts? [JS]
I get data like this from the server:

```<code>data":[[1496640705,1583360,1583360,1583370,1583360],[1496640720,1583360,1583350,1583360,1583345],[1496640735,1583350,1583320,1583400,1583320]]
</code>```

My question is, how can I display this data on Highcharts? Every array first element is the Date for X axis, and only want the last data every array for the Y axis. How can I select these 2 elements for Highcharts?

答:
Every charts in highchart accepts data in different way.Create two separate array xAxis & yAxis from data array & provide their value to the highchart.

var data = [
    [1496640705, 1583360, 1583360, 1583370, 1583360],
    [1496640720, 1583360, 1583350, 1583360, 1583345],
    [1496640735, 1583350, 1583320, 1583400, 1583320]
  ],
  xAxis = [],
  yAxis = [];

data.forEach(function(item) {
  xAxis.push(item[0]);
  yAxis.push(item[item.length - 1])
})

console.log(xAxis, yAxis)```

Body:
I get data like this from the server:

data":[[1496640705,1583360,1583360,1583370,1583360],[1496640720,1583360,1583350,1583360,1583345],[1496640735,1583350,1583320,1583400,1583320]]

My question is, how can I display this data on Highcharts? Every array first element is the Date for X axis, and only want the last data every array for the Y axis. How can I select these 2 elements for Highcharts?


问:
Handling S3 Bucket Trigger Event in Lambda Using Python
The AWS Lambda handler has a signature of

```<code>def lambda_handler(event, context):
</code>```

However, I cannot find any documentation as to the event's structure when the trigger is an S3 Bucket receiving a put

I thought that it might be defined in the s3 console, but couldn't find that there.

Anyone have any leads?

答:
The event from S3 to Lambda function will be in json format as shown below,

```<code>{
   "Records":[
      {
         "eventVersion":"2.0",
         "eventSource":"aws:s3",
         "awsRegion":"us-east-1",
         "eventTime":The time, in ISO-8601 format, for example, 1970-01-01T00:00:00.000Z, when S3 finished processing the request,
         "eventName":"event-type",
         "userIdentity":{
            "principalId":"Amazon-customer-ID-of-the-user-who-caused-the-event"
         },
         "requestParameters":{
            "sourceIPAddress":"ip-address-where-request-came-from"
         },
         "responseElements":{
            "x-amz-request-id":"Amazon S3 generated request ID",
            "x-amz-id-2":"Amazon S3 host that processed the request"
         },
         "s3":{
            "s3SchemaVersion":"1.0",
            "configurationId":"ID found in the bucket notification configuration",
            "bucket":{
               "name":"bucket-name",
               "ownerIdentity":{
                  "principalId":"Amazon-customer-ID-of-the-bucket-owner"
               },
               "arn":"bucket-ARN"
            },
            "object":{
               "key":"object-key",
               "size":object-size,
               "eTag":"object eTag",
               "versionId":"object version if bucket is versioning-enabled, otherwise null",
               "sequencer": "a string representation of a hexadecimal value used to determine event sequence,
                   only used with PUTs and DELETEs"
            }
         }
      },
      {
          // Additional events
      }
   ]
}
</code>```

here is the link for aws documentation which can guide you. http://docs.aws.amazon.com/lambda/latest/dg/with-s3-example.html

Body:
The AWS Lambda handler has a signature of

def lambda_handler(event, context):

However, I cannot find any documentation as to the event's structure when the trigger is an S3 Bucket receiving a put

I thought that it might be defined in the s3 console, but couldn't find that there.

Anyone have any leads?

Body:
The event from S3 to Lambda function will be in json format as shown below,

{
   "Records":[
      {
         "eventVersion":"2.0",
         "eventSource":"aws:s3",
         "awsRegion":"us-east-1",
         "eventTime":The time, in ISO-8601 format, for example, 1970-01-01T00:00:00.000Z, when S3 finished processing the request,
         "eventName":"event-type",
         "userIdentity":{
            "principalId":"Amazon-customer-ID-of-the-user-who-caused-the-event"
         },
         "requestParameters":{
            "sourceIPAddress":"ip-address-where-request-came-from"
         },
         "responseElements":{
            "x-amz-request-id":"Amazon S3 generated request ID",
            "x-amz-id-2":"Amazon S3 host that processed the request"
         },
         "s3":{
            "s3SchemaVersion":"1.0",
            "configurationId":"ID found in the bucket notification configuration",
            "bucket":{
               "name":"bucket-name",
               "ownerIdentity":{
                  "principalId":"Amazon-customer-ID-of-the-bucket-owner"
               },
               "arn":"bucket-ARN"
            },
            "object":{
               "key":"object-key",
               "size":object-size,
               "eTag":"object eTag",
               "versionId":"object version if bucket is versioning-enabled, otherwise null",
               "sequencer": "a string representation of a hexadecimal value used to determine event sequence,
                   only used with PUTs and DELETEs"
            }
         }
      },
      {
          // Additional events
      }
   ]
}

here is the link for aws documentation which can guide you. http://docs.aws.amazon.com/lambda/latest/dg/with-s3-example.html


答:
A dictionary of alphabet and spacial alphabet may be a best design

in your case try;

```<code>for item in name:
    ind = alphabet.find(item)
    if ind != -1:
        print(special_alphabet[ind])
</code>```

Title: prints results only when string item index == list item index

Body:
A dictionary of alphabet and spacial alphabet may be a best design

in your case try;

for item in name:
    ind = alphabet.find(item)
    if ind != -1:
        print(special_alphabet[ind])


问:
Compare date (string) in PouchDB find
I have a CouchDB hosted, which has a date (string?) field that has values like "03-Mar-2007". I have an angular app which uses a pouch db to pull data from remote and do stuff.

I need to find records which have the date value less than current date.

I use below code but it does not work.

```<code> db.createIndex({
                index: {
                    //fields: ['Pincode', 'subscriberid']
                    fields: ['Pincode', 'IssueDtto']
                }
            })....
</code>```

I use 'find' to search records:

```<code>var cdate = getFormattedDate($scope.curdate);

function getFormattedDate(date) {
            var year = date.getFullYear();
            var month = (1 + date.getMonth()).toString();
            month = month.length > 1 ? month : '0' + month;
            var day = date.getDate().toString();
            day = day.length > 1 ? day : '0' + day;
            return day + '-' + monthNames[date.getMonth()] + '-' + year;
        }

 db.find({
    selector: {
    Pincode: { $eq: pin }
    ,IssueDtto: { $lt: cdate }
   }
</code>```

This however does not seem to work. What am I doing wrong? Please help.

Thanks

答:
I made a workaround, removed the 'date' field selector from db.find, just used only the other selector, got all docs and (manually) filtered rows. </p>

```<code>angular.forEach(r.docs, function (val) {
 var dt = new Date(val.IssueDtto);
 if (dt < $scope.curdate)
   $scope.todo.push(val);
 });
</code>```

Title: Compare date (string) in PouchDB find

Body:
I have a CouchDB hosted, which has a date (string?) field that has values like "03-Mar-2007". I have an angular app which uses a pouch db to pull data from remote and do stuff.

I need to find records which have the date value less than current date.

I use below code but it does not work.

 db.createIndex({
                index: {
                    //fields: ['Pincode', 'subscriberid']
                    fields: ['Pincode', 'IssueDtto']
                }
            })....

I use 'find' to search records:

var cdate = getFormattedDate($scope.curdate);

function getFormattedDate(date) {
            var year = date.getFullYear();
            var month = (1 + date.getMonth()).toString();
            month = month.length > 1 ? month : '0' + month;
            var day = date.getDate().toString();
            day = day.length > 1 ? day : '0' + day;
            return day + '-' + monthNames[date.getMonth()] + '-' + year;
        }

 db.find({
    selector: {
    Pincode: { $eq: pin }
    ,IssueDtto: { $lt: cdate }
   }

This however does not seem to work. What am I doing wrong? Please help.

Thanks

Body:
I made a workaround, removed the 'date' field selector from db.find, just used only the other selector, got all docs and (manually) filtered rows.

angular.forEach(r.docs, function (val) {
 var dt = new Date(val.IssueDtto);
 if (dt < $scope.curdate)
   $scope.todo.push(val);
 });


问:
Remove the duplicate blocks from callback function
I'm writing a node js program that has to follow the below properties.

Check if access token is available in session(session.user.accessToken), if that doesn't exist, console.log a message.

If the access token is available, check if there is session.attributes.isUserName, if it is there, console.log('The values are there');, if it is not there call the callback method, console.log('The values are there');.

Basically the code is getting duplicated.

Below is my code.

```<code>if (!session.user.accessToken) {
       console.log('Token is not available');
    } else {
        if (!session.attributes.isUserName) {
         getUserDetailsFromToken(session, function (err) {
            if (!err) {
               //print the user's data.
                console.log("UserName is " + session.attributes.userName);
            }
        });
        } else{
             //print the user's data.
             console.log("UserName is " + session.attributes.userName);
        }

        }
    }
</code>```

Here session.attributes.userName that we are printing is same, just that the call back getUserDetailsFromToken checks and sets a variable. Is there a way that I can get the console.log("UserName is " + session.attributes.userName); out of code and use it seperately? this is a sample code that I've provided, I've 126 lines of code in my application, those have to be duplicated, once inside callback (if condition), and another outside callback (else condition).

Please let me know how can I optimize this.

Thanks

答:
This is what I used to do

```<code>var feedback = () => {
    //print the user's data.
    console.log("UserName is " + session.attributes.userName);
}

if (!session.user.accessToken) {
   console.log('Token is not available');

} else {
    if (!session.attributes.isUserName) {
        getUserDetailsFromToken(session, function (err) {
            if (!err) feedback();
        });

    } else {
        feedback();
    }
}
</code>```

And just a suggestion, with some simple refactor on code it would looks cleaner, less if-else nested statements:

```<code>var feedback = () => {
    //print the user's data.
    console.log("UserName is " + session.attributes.userName);
}

do {
    if (!session.user.accessToken) {
        console.log('Token is not available');
        break;
    }

    if (session.attributes.isUserName) {
        feedback();
        break;
    }

    getUserDetailsFromToken(session, function (err) {
        if (!err) feedback();
    });

} while(0);
</code>```

Body:
I'm writing a node js program that has to follow the below properties.

Check if access token is available in session(session.user.accessToken), if that doesn't exist, console.log a message.

If the access token is available, check if there is session.attributes.isUserName, if it is there, console.log('The values are there');, if it is not there call the callback method, console.log('The values are there');.

Basically the code is getting duplicated.

Below is my code.

if (!session.user.accessToken) {
       console.log('Token is not available');
    } else {
        if (!session.attributes.isUserName) {
         getUserDetailsFromToken(session, function (err) {
            if (!err) {
               //print the user's data.
                console.log("UserName is " + session.attributes.userName);
            }
        });
        } else{
             //print the user's data.
             console.log("UserName is " + session.attributes.userName);
        }

        }
    }

Here session.attributes.userName that we are printing is same, just that the call back getUserDetailsFromToken checks and sets a variable. Is there a way that I can get the console.log("UserName is " + session.attributes.userName); out of code and use it seperately? this is a sample code that I've provided, I've 126 lines of code in my application, those have to be duplicated, once inside callback (if condition), and another outside callback (else condition).

Please let me know how can I optimize this.

Thanks

Body:
This is what I used to do

var feedback = () => {
    //print the user's data.
    console.log("UserName is " + session.attributes.userName);
}

if (!session.user.accessToken) {
   console.log('Token is not available');

} else {
    if (!session.attributes.isUserName) {
        getUserDetailsFromToken(session, function (err) {
            if (!err) feedback();
        });

    } else {
        feedback();
    }
}

And just a suggestion, with some simple refactor on code it would looks cleaner, less if-else nested statements:

var feedback = () => {
    //print the user's data.
    console.log("UserName is " + session.attributes.userName);
}

do {
    if (!session.user.accessToken) {
        console.log('Token is not available');
        break;
    }

    if (session.attributes.isUserName) {
        feedback();
        break;
    }

    getUserDetailsFromToken(session, function (err) {
        if (!err) feedback();
    });

} while(0);


答:
```<code>`User`
</code>```

Is Reserved word in sql.
You can try below code

```<code>SELECT Message FROM Enquiry where `User`='abc'
</code>```

Hope this will helps.

Title: SQL Server where clause statement do not work on certain "columns"

Body:
`User`

Is Reserved word in sql.
You can try below code

SELECT Message FROM Enquiry where `User`='abc'

Hope this will helps.