问:
VBA: Array cell reference Mismatch error
UPDATED 3/30

So I adjusted the code and it runs error free now but the issue is that it does not pull the correct data. X basically starts with cell(X,1) and goes on from there. How do I link X to the selected listbox options in the array?

OLD Message:
I have a userform that allows for multi-select of Countries and also Questions about that specific country. These are stored in arrCountries & arrQuestion respectively. This then feeds to my main sub which calls for a Web Query Import from the CIA World Factbook site. I keep however getting a mismatch error that I cannot seem to sort out how to get around:

If I had to guess it is because when I am filling the array from the listbox's it is just adding a string and not the cell reference that the string is located at (or I am completely wrong).

My worksheet has only 1 sheet when started called Countries and the Column A is the URL and Column B is the Country name. I have Defined Public arrCountry(), Public arrQuestion(), and Public X as variant.

Code here:

Userform Code when click okay:

```<code>'Handles when the user clicks okay
Private Sub cbOkay_Click()
    'Me.Hide
'Capture ticker selection(s) from list box.
Dim cI As Long
Dim cX As Long
Dim qI As Long
Dim qX As Long

'Stores the Countries selected into an array
If lbCountries.ListIndex <> -1 Then
    For cI = 0 To lbCountries.ListCount - 1
        If lbCountries.Selected(cI) Then
            ReDim Preserve arrCountry(cX)
            arrCountry(cX) = lbCountries.List(cI)
            cX = cX + 1
        End If
    Next cI
End If

If cX = 0 Then MsgBox "Please select at least one country to analyse."
'MsgBox Join(arrCountry, vbCrLf)

'Stores the Questions selected into an array
If lbQuestions.ListIndex <> -1 Then
    For qI = 0 To lbQuestions.ListCount - 1
        If lbQuestions.Selected(qI) Then
            ReDim Preserve arrQuestion(qX)
            arrQuestion(qX) = lbQuestions.List(qI)
            qX = qX + 1
        End If
    Next qI
End If

If qX = 0 Then MsgBox "Please select at least one question to analyse."

'MsgBox Join(arrQuestion, vbCrLf)

'Unload the form
Unload Me

cancel = False
End Sub
</code>```

The message boxes return the correctly selected Listbox items so I know they are being stored correctly.

The WebQuery Code I am getting the error on:

UPDATED CODE:

So I added a loop counter:

```<code>Sub webQueryimport(arrCountry())

Dim mystr As String
Dim X As Integer
Dim selected As Variant

For Each selected In arrCountry
    X = X + 1
Worksheets("Countries").Select
Worksheets("Countries").Activate
     mystr = Cells(X, 1)
     Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = selected

        With ActiveSheet.QueryTables.Add(Connection:=mystr, Destination:=Range("$A$1"))
            .WebSelectionType = xlEntirePage 'this tells VBA what to select and import
            .WebFormatting = xlWebFormattingNone 'this turns off web formatting, otherwise text is various sizes
            .Refresh BackgroundQuery:=False 'if commented out, doesn't add any data
        End With
Next selected

End Sub
</code>```

Again, now that loop works and will import but it always starts with the A1 no matter what is selected in the listbox and in arrCountries

Any thoughts/assistance would be great!

答:
Got it:

```<code>Sub webQueryimport(arrCountry())

Dim mystr As String
Dim X As Integer
Dim rng As Range
Dim selected As Variant

Set rng = Range("B1")

For Each selected In arrCountry()
    For X = 1 To 5 'rng.Offset(0, 0).End(xlDown).Rows.count
        Worksheets("Countries").Select
        Worksheets("Countries").Activate

        If Cells(X, 2).Value = selected Then
            mystr = Cells(X, 1).Value
            Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = selected

            With ActiveSheet.QueryTables.Add(Connection:=mystr, Destination:=Range("$A$1"))
                .WebSelectionType = xlEntirePage 'this tells VBA what to select and import
                .WebFormatting = xlWebFormattingNone 'this turns off web formatting, otherwise text is various sizes
                .Refresh BackgroundQuery:=False 'if commented out, doesn't add any data
            End With
        End If
      Next X
    Next selected
End Sub
</code>```

I needed to add in a counter and the IF statement to check to see if the value in the array matched the cell value in the sheet and then return the appropriate cell for the import.

Body:
UPDATED 3/30

So I adjusted the code and it runs error free now but the issue is that it does not pull the correct data. X basically starts with cell(X,1) and goes on from there. How do I link X to the selected listbox options in the array?

OLD Message:
I have a userform that allows for multi-select of Countries and also Questions about that specific country. These are stored in arrCountries & arrQuestion respectively. This then feeds to my main sub which calls for a Web Query Import from the CIA World Factbook site. I keep however getting a mismatch error that I cannot seem to sort out how to get around:

If I had to guess it is because when I am filling the array from the listbox's it is just adding a string and not the cell reference that the string is located at (or I am completely wrong).

My worksheet has only 1 sheet when started called Countries and the Column A is the URL and Column B is the Country name. I have Defined Public arrCountry(), Public arrQuestion(), and Public X as variant.

Code here:

Userform Code when click okay:

'Handles when the user clicks okay
Private Sub cbOkay_Click()
    'Me.Hide
'Capture ticker selection(s) from list box.
Dim cI As Long
Dim cX As Long
Dim qI As Long
Dim qX As Long

'Stores the Countries selected into an array
If lbCountries.ListIndex <> -1 Then
    For cI = 0 To lbCountries.ListCount - 1
        If lbCountries.Selected(cI) Then
            ReDim Preserve arrCountry(cX)
            arrCountry(cX) = lbCountries.List(cI)
            cX = cX + 1
        End If
    Next cI
End If

If cX = 0 Then MsgBox "Please select at least one country to analyse."
'MsgBox Join(arrCountry, vbCrLf)

'Stores the Questions selected into an array
If lbQuestions.ListIndex <> -1 Then
    For qI = 0 To lbQuestions.ListCount - 1
        If lbQuestions.Selected(qI) Then
            ReDim Preserve arrQuestion(qX)
            arrQuestion(qX) = lbQuestions.List(qI)
            qX = qX + 1
        End If
    Next qI
End If

If qX = 0 Then MsgBox "Please select at least one question to analyse."

'MsgBox Join(arrQuestion, vbCrLf)

'Unload the form
Unload Me

cancel = False
End Sub

The message boxes return the correctly selected Listbox items so I know they are being stored correctly.

The WebQuery Code I am getting the error on:

UPDATED CODE:

So I added a loop counter:

Sub webQueryimport(arrCountry())

Dim mystr As String
Dim X As Integer
Dim selected As Variant

For Each selected In arrCountry
    X = X + 1
Worksheets("Countries").Select
Worksheets("Countries").Activate
     mystr = Cells(X, 1)
     Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = selected

        With ActiveSheet.QueryTables.Add(Connection:=mystr, Destination:=Range("$A$1"))
            .WebSelectionType = xlEntirePage 'this tells VBA what to select and import
            .WebFormatting = xlWebFormattingNone 'this turns off web formatting, otherwise text is various sizes
            .Refresh BackgroundQuery:=False 'if commented out, doesn't add any data
        End With
Next selected

End Sub

Again, now that loop works and will import but it always starts with the A1 no matter what is selected in the listbox and in arrCountries

Any thoughts/assistance would be great!

Body:
Got it:

Sub webQueryimport(arrCountry())

Dim mystr As String
Dim X As Integer
Dim rng As Range
Dim selected As Variant

Set rng = Range("B1")

For Each selected In arrCountry()
    For X = 1 To 5 'rng.Offset(0, 0).End(xlDown).Rows.count
        Worksheets("Countries").Select
        Worksheets("Countries").Activate

        If Cells(X, 2).Value = selected Then
            mystr = Cells(X, 1).Value
            Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = selected

            With ActiveSheet.QueryTables.Add(Connection:=mystr, Destination:=Range("$A$1"))
                .WebSelectionType = xlEntirePage 'this tells VBA what to select and import
                .WebFormatting = xlWebFormattingNone 'this turns off web formatting, otherwise text is various sizes
                .Refresh BackgroundQuery:=False 'if commented out, doesn't add any data
            End With
        End If
      Next X
    Next selected
End Sub

I needed to add in a counter and the IF statement to check to see if the value in the array matched the cell value in the sheet and then return the appropriate cell for the import.


来源: stackexchange

问:
Get map object type - HERE maps
I am trying to get all marker objects from map and do stuff with them. However there are other map objects on the map. Is there any way to check whether the object is of Marker type? I cannot find this in API documentation.</p>

```<code>var objects = map.getObjects();

objects = objects.filter(function(item) {
    //return item is marker?
});
</code>```

答:
You could use the actual class (or base class if you want to get Markers and DomMarkers)?</p>

```<code>var markers = objects.filter(function(item) {
  return (item instanceof H.map.AbstractMarker);
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Get map object type - HERE maps

Body:
I am trying to get all marker objects from map and do stuff with them. However there are other map objects on the map. Is there any way to check whether the object is of Marker type? I cannot find this in API documentation.

var objects = map.getObjects();

objects = objects.filter(function(item) {
    //return item is marker?
});

Body:
You could use the actual class (or base class if you want to get Markers and DomMarkers)?

var markers = objects.filter(function(item) {
  return (item instanceof H.map.AbstractMarker);
}


问:
How can I create a deep neural network which has a capability to take a decision for hypothesis?
Basically, I am interested in solving a hypothesis problem, where I am only aware of the data distribution of a null hypothesis and don't know anything about the alternative case.

My concern is how should I train my deep neural network so that it can classify or recognise whether a particular sample data has a similar distribution as in null hypothesis case or it's from another class(An alternative Hypothesis case).

According to my understanding, It's different from a binary classification (one vs all case), because in that case, we know what data we are going to tackle, but here in my case alternative hypothesis case can follow any data distribution.

Here I am giving you an example situation, what I want exactly

Suppose I want to predict that a person is likely to have cancer or not

e.g

I have a data set of the factors that cause cancer like,

Parameter A=1,Parameter B=3.87,Parameter C=5.6,Has cancer = yes

But I don't have a data set where

Parameter A=2,Parameter B=1.87,Parameter C=2.6,Has cancer = No

Can be anything like this

Means I don't know about anything which leads to a conclusion of not having cancer, can I still train my model to recognise whether a person has cancer?

答:
If you are sure enough that the alternative hypothesis data come from different distribution than the null hypothesis, you can try unsupervised learning algorithm. i.e a K-mean or a GMM with the right number of cluster could yield a great separation of the data. You can then assign label to the second class data and train a classifier using it.

This a general approach of semi-supervised learning.

Another idea would be to consider the alternative hypothesis data as outliers and use anomalie detection algorithm to find you second class data point. This is much more difficult to achieve and rely heavily on the supposition that data comes from really different distribution.


问:
pop_back() not working
I have the following main program that creates a Stack object, fills it with doubles and then pops them. The code files fine, but the pop_back() part does not seem to work, while s.back() does return the correct value. How is this possible?

```<code>#include "Stack.h"
#include <iostream>
#include <deque>
using namespace std;
int main() {

  Stack<double> s(0,0.0);

  // Write doubles into Stack
  int i ;
  for (i=0 ; i<15 ; i++) {

    s.push(i*i) ;

  }

  // Read doubles back from fifo
  while (!s.empty()) {
    double val = s.pop() ;
    std::cout << "Popping value " << val << " from stack" << std::endl ;

  }

  return 0 ;

}
</code>```

My header file looks like this, where I have omitted parts which are not relevant to the question.

```<code>#ifndef STACK_H
#define STACK_H

#include <iostream>
#include <deque>

template<class T>
class Stack {

public:

  Stack(int len, T defval): s(len+1, defval) {

    return;
}

~Stack() {

    //delete [] s;
}

void push(T c) {

    s.push_back(c);

}

T pop() {

    return s.back();
    s.pop_back();

}

private:

  std::deque<T> s; //Array<T> s;

};

#endif
</code>```

答:
```<code>T pop() {
    return s.back();
//  ^^^^^

    s.pop_back(); // <- unreachable!
}
</code>```

When you return from a function, all the subsequent instruction will never be executed.

Store s.back()'s result in a temporary variable instead:

```<code>T pop() {
    auto back = s.back();
    s.pop_back();
    return back;
}
</code>```

Title: pop_back() not working

Body:
I have the following main program that creates a Stack object, fills it with doubles and then pops them. The code files fine, but the pop_back() part does not seem to work, while s.back() does return the correct value. How is this possible?

#include "Stack.h"
#include <iostream>
#include <deque>
using namespace std;
int main() {

  Stack<double> s(0,0.0);

  // Write doubles into Stack
  int i ;
  for (i=0 ; i<15 ; i++) {

    s.push(i*i) ;

  }

  // Read doubles back from fifo
  while (!s.empty()) {
    double val = s.pop() ;
    std::cout << "Popping value " << val << " from stack" << std::endl ;

  }

  return 0 ;

}

My header file looks like this, where I have omitted parts which are not relevant to the question.

#ifndef STACK_H
#define STACK_H

#include <iostream>
#include <deque>

template<class T>
class Stack {

public:

  Stack(int len, T defval): s(len+1, defval) {

    return;
}

~Stack() {

    //delete [] s;
}

void push(T c) {

    s.push_back(c);

}

T pop() {

    return s.back();
    s.pop_back();

}

private:

  std::deque<T> s; //Array<T> s;

};

#endif

Body:
T pop() {
    return s.back();
//  ^^^^^

    s.pop_back(); // <- unreachable!
}

When you return from a function, all the subsequent instruction will never be executed.

Store s.back()'s result in a temporary variable instead:

T pop() {
    auto back = s.back();
    s.pop_back();
    return back;
}


问:
input check box need to be in checked at first in ng2
This below is that i am expecting to be evaluated,but,this input checkbox need to be in ticked (visually) condition when its all loaded.
But, as of now, it is not happening. on this code, my functionality working fine, additionally, i need this update on this checkbox in ng2. On loading of all checkboxes need to be in ticked condition(visually, true in technical), if i change the value that should be updated to ngModel.

Any clue, pls?

```<code><input type="checkbox" value="{{item.file.name}}" [(ngModel)]="item['checked']" id="myCheck" (change)="itemRemovelist(item, item['checked'])">
</code>```

答: Add a checked attribute to your checkbox [checked]="item['checked']". So if your item checked value is true onload the checkbox will be checked. Hope this helps you.</p>

Body:
This below is that i am expecting to be evaluated,but,this input checkbox need to be in ticked (visually) condition when its all loaded.
But, as of now, it is not happening. on this code, my functionality working fine, additionally, i need this update on this checkbox in ng2. On loading of all checkboxes need to be in ticked condition(visually, true in technical), if i change the value that should be updated to ngModel.

Any clue, pls?

<input type="checkbox" value="{{item.file.name}}" [(ngModel)]="item['checked']" id="myCheck" (change)="itemRemovelist(item, item['checked'])">


问:
Not receiving claims from WSO2 Identity Server (v5.1.0) when used with Oauth2
I am using WSO2 Identity Server as the identity provider for our websites. The websites are being developed in ASP.net and we are using in-built Owin-Katana framework along with Oauth 2 to authenticate users. I could access SCIM REST Api's to create new users and their claims into WSO2. The claims were added under the dialect "urn:scim:schemas:core:1.0". I need to retrieve those claims while authenticating the user via Oauth 2. The service provider setup doesn't allow me to select claims from the dialect "urn:scim:schemas:core:1.0".

Is there an way I can retrieve the claims I have added to the user? The answer here suggest that we install an upgraded version of WSO2. Is that the only solution?

My Owin setup is (using NuGet package Owin.Security.Providers.WSO2):

```<code>app.UseWSO2Authentication(new WSO2AuthenticationOptions()
{
    BaseUrl = "https://identityserver:9443/",
    CallbackPath = new PathString("/Account/ExternalLoginConfirmation"),
    ClientId = "xxxxxxxxx",
    ClientSecret = "yyyyyyyyy"
});
</code>```

答:
As point 1 says in this link you need to pick claims that have a mapping between the "http://wso2.org/oidc/claim" dialect to "http://wso2.org/claims" dialect.

Mapping is checked from Mapped Attribute value of each claim. Say Email claim in http://wso2.org/oidc/claim dialect and Email claim in http://wso2.org/claims dialect has the Mapped attribute as mail, try mapping the mail attribute to the required claim in urn:scim:schemas:core:1.0 dialect. When requesting claims in the service provider, request the claim in http://wso2.org/oidc/claim dialect which has the Mapped Attribute value to your claim.

Hope this would help.

Body:
I am using WSO2 Identity Server as the identity provider for our websites. The websites are being developed in ASP.net and we are using in-built Owin-Katana framework along with Oauth 2 to authenticate users. I could access SCIM REST Api's to create new users and their claims into WSO2. The claims were added under the dialect "urn:scim:schemas:core:1.0". I need to retrieve those claims while authenticating the user via Oauth 2. The service provider setup doesn't allow me to select claims from the dialect "urn:scim:schemas:core:1.0".

Is there an way I can retrieve the claims I have added to the user? The answer here suggest that we install an upgraded version of WSO2. Is that the only solution?

My Owin setup is (using NuGet package Owin.Security.Providers.WSO2):

app.UseWSO2Authentication(new WSO2AuthenticationOptions()
{
    BaseUrl = "https://identityserver:9443/",
    CallbackPath = new PathString("/Account/ExternalLoginConfirmation"),
    ClientId = "xxxxxxxxx",
    ClientSecret = "yyyyyyyyy"
});


问:
secure or encrypt smarty plugins
I am working on CMS system using smarty. The one cms system could support multiple websites with multiple websites, multiple templates, multiple plugins and components...

Client can register and create his website using pre existing templates and choose components to display them on that template.

My Question is that How i can make those component secure or encrypted. so if client take his site away from the server to another server, he won't able to use those module, components etc. or atleast these would expire after certain time..

I am going to create these components using smarty plugins.

Is there any solution in php, smarty ?

答: Zend Server offers such a function.</p>

ContentLicense: CC BY-SA 2.5

Title: secure or encrypt smarty plugins

Body: Zend Server offers such a function.


问:
Excel accepts some characters whereas OpenXml has error
i have a string that i want to export on excel file with openxml component in C#. My text has '\u001f' character and openxml has error with this character. error text: "hexadecimal value 0x1f, is an invalid character".

i copy that test directly to excel and no problem and copy is success.

Does OpenXml have configs for solving this problem or How i can solve this problem.

thanks.

答:
You need to write it using the format _xHHHH_ where H represents a hexadecimal character. In your particular instance you need to set the value to "_x001F_".

From the documentation for a Cell Value:

The possible values for this element are defined by the ST_Xstring simple type (§22.9.2.19).

In turn, the ST_Xstring (taken from the ECMA-376 standard) is documented as:

22.9.2.19 ST_Xstring (Escaped String)

  String of characters with support for escaped invalid-XML characters.
  For all characters which cannot be represented in XML as defined by the XML 1.0 specification, the characters
  are escaped using the Unicode numerical character representation escape character format xHHHH, where H
  represents a hexadecimal character in the character's value. [Example: The Unicode character 8 is not permitted
  in an XML 1.0 document, so it must be escaped as x0008. end example]


问:
Showing Splash screen in android apps
Have you ever seen the page in many apps that before launching the first activity appears and somehow it is like a waiting page ?! I am beginner to android and when I click on my apps , first a blank white page appears then after 3 seconds main activity comes out . but in many apps there is a kind of customised page before the first activity that is like a progress bar or sth . how can I customise that not so beautiful blank page before starting my app?! Thanx in advance . </p>

答:
You can use the Splash Screen for this
Working code:

```<code>public class Mainsplash extends Activity {

     /** Duration of wait **/
    private final int SPLASH_DISPLAY_LENGTH = 3000;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.splashscreen);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        /* New Handler to start the Menu-Activity
         * and close this Splash-Screen after some seconds.*/
        new Handler().postDelayed(new Runnable(){
            @Override
            public void run() {
                /* Create an Intent that will start the Menu-Activity. */
                Intent mainIntent = new Intent(Mainsplash.this,MainActivity.class);
                Mainsplash.this.startActivity(mainIntent);
                Mainsplash.this.finish();
            }
        }, SPLASH_DISPLAY_LENGTH);
    }

}
</code>```

Xml code:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/load_src"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/splashimg"
    android:gravity="center"
    android:orientation="vertical" >

  <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/ll_v1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
      android:layout_alignParentBottom="true"
         >

        <ProgressBar
            android:id="@+id/prg"

            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>
    </RelativeLayout>

</LinearLayout>
</code>```

And also in Manifest file

```<code><activity
            android:name=".Mainsplash"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
</code>```

use the intent filter for that  splash activity to make it launch first

hope this helps

Title: Showing Splash screen in android apps

Body:
You can use the Splash Screen for this
Working code:

public class Mainsplash extends Activity {

     /** Duration of wait **/
    private final int SPLASH_DISPLAY_LENGTH = 3000;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.splashscreen);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        /* New Handler to start the Menu-Activity
         * and close this Splash-Screen after some seconds.*/
        new Handler().postDelayed(new Runnable(){
            @Override
            public void run() {
                /* Create an Intent that will start the Menu-Activity. */
                Intent mainIntent = new Intent(Mainsplash.this,MainActivity.class);
                Mainsplash.this.startActivity(mainIntent);
                Mainsplash.this.finish();
            }
        }, SPLASH_DISPLAY_LENGTH);
    }

}

Xml code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/load_src"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/splashimg"
    android:gravity="center"
    android:orientation="vertical" >

  <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/ll_v1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
      android:layout_alignParentBottom="true"
         >

        <ProgressBar
            android:id="@+id/prg"

            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>
    </RelativeLayout>

</LinearLayout>

And also in Manifest file

<activity
            android:name=".Mainsplash"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

use the intent filter for that  splash activity to make it launch first

hope this helps


问:
How to get result from Google OAuth API if user close browser window?
I create WPF application which uses Google API Client Library for .NET.
Following the sample, I wrote the code below:

```<code>        var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            Secrets,
            new[] { "https://www.googleapis.com/auth/contacts.readonly" },
            "user",
            CancellationToken.None,
            new FileDataStore(TokenStorageName)).Result;
</code>```

Calling of AuthorizeAsync method opens new browser window/tab with login form.
Problem appears if user just close browser window or tab. I never get result of this call.

Can I some how handle this situation ?

Should I change source code of AuthorizeAsync(...) ?

答:
See GoogleWebAuthorizationBroker.AuthorizeAsync() hangs if browser closed

It's not possible, in general, to detect the user closing the browser tab/window. And using a cancellationToken currently does not work, #968 filed to fix.

Body:
I create WPF application which uses Google API Client Library for .NET.
Following the sample, I wrote the code below:

        var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            Secrets,
            new[] { "https://www.googleapis.com/auth/contacts.readonly" },
            "user",
            CancellationToken.None,
            new FileDataStore(TokenStorageName)).Result;

Calling of AuthorizeAsync method opens new browser window/tab with login form.
Problem appears if user just close browser window or tab. I never get result of this call.

Can I some how handle this situation ?

Should I change source code of AuthorizeAsync(...) ?


问:
What does it mean in Swift: 'case .success(let dict):'
In Swift PromiseKit library there's Alamofire example using a bit strange syntax:

```<code>func login(completionHandler: (NSDictionary?, ErrorProtocol?) -> Void    {
    Alamofire.request(.GET, url, parameters: ["foo": "bar"])
        .validate()
        .responseJSON { response in
            switch response.result {
            case .success(let dict):
                completionHandler(dict, nil)
            case .failure(let error):
                completionHandler(nil, error)
            }
        }
}
</code>```

response is an Alamofire enum describing two cases with associated values:

```<code>public enum Result<Value> {
    case success(Value)
    case failure(Error)
(...)
</code>```

What I don't get is what does let mean in each case: line and where does the dict (or error) come from? Is this syntactic sugar for something more verbose but less confusing?

答: In Swift, enums can have associated values (docs). This means, that you can associate an object with cases. The part (let dict) simply means - take the associated value, and put in in a let constant named dict.

Body:
In Swift PromiseKit library there's Alamofire example using a bit strange syntax:

func login(completionHandler: (NSDictionary?, ErrorProtocol?) -> Void    {
    Alamofire.request(.GET, url, parameters: ["foo": "bar"])
        .validate()
        .responseJSON { response in
            switch response.result {
            case .success(let dict):
                completionHandler(dict, nil)
            case .failure(let error):
                completionHandler(nil, error)
            }
        }
}

response is an Alamofire enum describing two cases with associated values:

public enum Result<Value> {
    case success(Value)
    case failure(Error)
(...)

What I don't get is what does let mean in each case: line and where does the dict (or error) come from? Is this syntactic sugar for something more verbose but less confusing?


问:
How to conditionally insert a record in table B during insert into table A in PostgreSQL?
Given the following structure:

Table A (aliases):

```<code>user_id | alias
---------------
   1      john
   2      peter
</code>```

user_id references id in users.

Table B (users):

```<code>  id | password_hash | ...
---------------------------
   1        ...        ...
   2        ...        ...
</code>```

(the idea is that users can have multiple aliases all of which point to the same main user account record)

I would like to do the following operation: given an alias, password, ... record:

if alias exists in aliases, update the corresponding password in users

if alias does not exist, create a new user in users with the given password and insert a row into aliases pointing to this new record.

How can I do that in a single query in Postgres?

Something along the lines of

```<code>WITH (
  INSERT INTO users(id, password, ...) VALUES(DEFAULT, password, ...) RETURNING id
)
INSERT INTO aliases(user_id, alias) VALUES(id, alias)
  ON CONFLICT {delete the temp row in users and update the one with the
               known user_id instead}
</code>```

答:
Note: I'll assume that alias is the primary key (but at least, it's a unique key) of aliases.

Unfortunately, because the unique column (alias) is not on the target table (of the UPSERT), you cannot do this with a single INSERT ... ON CONFLICT ... statement.

First, you'll need to define the foreign key on aliases.user_id (which refers to the users.id column) to be DEFERRABLE (it can be INITIALLY IMMEDIATE though).

After that, these statements should be able to run (despite any concurrent modifications to these tables):

```<code>set constraints fk_aliases_user_id deferred;

with params(alias, pwd) as (
  values ('john', 'pass3'),
         ('jane', 'pass4')
),
inserted_alias as (
  insert into aliases(alias, user_id)
  select      alias, coalesce((select user_id
                               from   aliases a
                               where  a.alias = p.alias),
                              nextval('users_id_seq'))
  from        params p
  on conflict (alias) do nothing
  returning   *
)
insert into users(id, password_hash)
select      coalesce(i.user_id, a.user_id),
            crypt(p.pwd, gen_salt('bf'))
from        params p
left join   inserted_alias i using (alias)
left join   aliases a using (alias)
on conflict (id) do update
set         password_hash = excluded.password_hash;

set constraints fk_aliases_user_id immediate;
</code>```

Notes:

I used the crypt() function form the pgcrypto module to generate password_hash from plain passwords. I hope you're doing something similar.

This may cause gaps in the users_id_seq when the concurrency is high, but should always succeed (and I minimized the chances for that with the coalesce() part of the first insert).

You can leave the set constraints statements, if your foreign key is INITIALLY DEFERRED.

http://rextester.com/YDY89070

Your other option is to use PL/pgSQL and a retry loop (what was the official recommendation before the ON CONFLICT support was added).

Edit: it seems immediate constraints are not checked between CTE boundaries (however, I have not found any evidence for this in the docs, yet), so the set constraints statements & to make the foreign key deferrable is not needed.

http://rextester.com/IUSM65192

Body:
Given the following structure:

Table A (aliases):

user_id | alias
---------------
   1      john
   2      peter

user_id references id in users.

Table B (users):

  id | password_hash | ...
---------------------------
   1        ...        ...
   2        ...        ...

(the idea is that users can have multiple aliases all of which point to the same main user account record)

I would like to do the following operation: given an alias, password, ... record:

if alias exists in aliases, update the corresponding password in users

if alias does not exist, create a new user in users with the given password and insert a row into aliases pointing to this new record.

How can I do that in a single query in Postgres?

Something along the lines of

WITH (
  INSERT INTO users(id, password, ...) VALUES(DEFAULT, password, ...) RETURNING id
)
INSERT INTO aliases(user_id, alias) VALUES(id, alias)
  ON CONFLICT {delete the temp row in users and update the one with the
               known user_id instead}

Body:
Note: I'll assume that alias is the primary key (but at least, it's a unique key) of aliases.

Unfortunately, because the unique column (alias) is not on the target table (of the UPSERT), you cannot do this with a single INSERT ... ON CONFLICT ... statement.

First, you'll need to define the foreign key on aliases.user_id (which refers to the users.id column) to be DEFERRABLE (it can be INITIALLY IMMEDIATE though).

After that, these statements should be able to run (despite any concurrent modifications to these tables):

set constraints fk_aliases_user_id deferred;

with params(alias, pwd) as (
  values ('john', 'pass3'),
         ('jane', 'pass4')
),
inserted_alias as (
  insert into aliases(alias, user_id)
  select      alias, coalesce((select user_id
                               from   aliases a
                               where  a.alias = p.alias),
                              nextval('users_id_seq'))
  from        params p
  on conflict (alias) do nothing
  returning   *
)
insert into users(id, password_hash)
select      coalesce(i.user_id, a.user_id),
            crypt(p.pwd, gen_salt('bf'))
from        params p
left join   inserted_alias i using (alias)
left join   aliases a using (alias)
on conflict (id) do update
set         password_hash = excluded.password_hash;

set constraints fk_aliases_user_id immediate;

Notes:

I used the crypt() function form the pgcrypto module to generate password_hash from plain passwords. I hope you're doing something similar.

This may cause gaps in the users_id_seq when the concurrency is high, but should always succeed (and I minimized the chances for that with the coalesce() part of the first insert).

You can leave the set constraints statements, if your foreign key is INITIALLY DEFERRED.

http://rextester.com/YDY89070

Your other option is to use PL/pgSQL and a retry loop (what was the official recommendation before the ON CONFLICT support was added).

Edit: it seems immediate constraints are not checked between CTE boundaries (however, I have not found any evidence for this in the docs, yet), so the set constraints statements & to make the foreign key deferrable is not needed.

http://rextester.com/IUSM65192


问:
Multiple Includes() in EF Core
I have an extension method that lets you generically include data in EF:

```<code>public static IQueryable<T> IncludeMultiple<T>(this IQueryable<T> query, params Expression<Func<T, object>>[] includes)
    where T : class
{
    if (includes != null)
    {
        query = includes.Aggregate(query, (current, include) => current.Include(include));
    }
    return query;
}
</code>```

This allows me to have methods in my repository like this:

```<code>public Patient GetById(int id, params Expression<Func<Patient, object>>[] includes)
{
    return context.Patients
        .IncludeMultiple(includes)
        .FirstOrDefault(x => x.PatientId == id);
}
</code>```

I believe the extension method worked before EF Core, but now including "children" is done like this:

```<code>var blogs = context.Blogs
    .Include(blog => blog.Posts)
        .ThenInclude(post => post.Author);
</code>```

Is there a way to alter my generic extension method to support EF Core's new ThenInclude() practice?

答:
For posterity, another less eloquent, but simpler solution that makes use of the Include() overload that uses navigationPropertyPath:

```<code>public static class BlogIncludes
{
    public const string Posts = "Posts";
    public const string Author = "Posts.Author";
}

internal static class DataAccessExtensions
{
    internal static IQueryable<T> IncludeMultiple<T>(this IQueryable<T> query,
        params string[] includes) where T : class
    {
        if (includes != null)
        {
            query = includes.Aggregate(query, (current, include) => current.Include(include));
        }
        return query;
    }
}

public Blog GetById(int ID, params string[] includes)
{
    var blog = context.Blogs
        .Where(x => x.BlogId == id)
        .IncludeMultiple(includes)
        .FirstOrDefault();
    return blog;
}
</code>```

And the repository call is:

```<code>var blog = blogRepository.GetById(id, BlogIncludes.Posts, BlogIncludes.Author);
</code>```

Title: Multiple Includes() in EF Core

Body:
I have an extension method that lets you generically include data in EF:

public static IQueryable<T> IncludeMultiple<T>(this IQueryable<T> query, params Expression<Func<T, object>>[] includes)
    where T : class
{
    if (includes != null)
    {
        query = includes.Aggregate(query, (current, include) => current.Include(include));
    }
    return query;
}

This allows me to have methods in my repository like this:

public Patient GetById(int id, params Expression<Func<Patient, object>>[] includes)
{
    return context.Patients
        .IncludeMultiple(includes)
        .FirstOrDefault(x => x.PatientId == id);
}

I believe the extension method worked before EF Core, but now including "children" is done like this:

var blogs = context.Blogs
    .Include(blog => blog.Posts)
        .ThenInclude(post => post.Author);

Is there a way to alter my generic extension method to support EF Core's new ThenInclude() practice?

Body:
For posterity, another less eloquent, but simpler solution that makes use of the Include() overload that uses navigationPropertyPath:

public static class BlogIncludes
{
    public const string Posts = "Posts";
    public const string Author = "Posts.Author";
}

internal static class DataAccessExtensions
{
    internal static IQueryable<T> IncludeMultiple<T>(this IQueryable<T> query,
        params string[] includes) where T : class
    {
        if (includes != null)
        {
            query = includes.Aggregate(query, (current, include) => current.Include(include));
        }
        return query;
    }
}

public Blog GetById(int ID, params string[] includes)
{
    var blog = context.Blogs
        .Where(x => x.BlogId == id)
        .IncludeMultiple(includes)
        .FirstOrDefault();
    return blog;
}

And the repository call is:

var blog = blogRepository.GetById(id, BlogIncludes.Posts, BlogIncludes.Author);


问:
Help in sql query
I have a table:

```<code>ID  Title   Date
30   1     10/10/2010
20   1     10/11/2010
40   2     01/01/2010
</code>```

i need a way to select distinct titles with max dates.

so when title is 1, i should have the second row selected since the date in the 1st row is smaller than the date in the second row.

as a result the query should return:

```<code>20 1 10/11/2010
40 2 01/01/2010
</code>```

答:
```<code>select max(ID) as ID, max(Date), Title
from table
group by Title
</code>```

should do the trick

Title: Help in sql query

Body:
I have a table:

ID  Title   Date
30   1     10/10/2010
20   1     10/11/2010
40   2     01/01/2010

i need a way to select distinct titles with max dates.

so when title is 1, i should have the second row selected since the date in the 1st row is smaller than the date in the second row.

as a result the query should return:

20 1 10/11/2010
40 2 01/01/2010

Body:
select max(ID) as ID, max(Date), Title
from table
group by Title

should do the trick


问:
Import a string value from first loop to second loop in template?
Is it able to import a string value from first loop to second loop in template?

In second loop, "mydata.data.room" should be mydata.A.room, mydata.B.room, mydata.C.room and mydata.D.room

In dictionary

```<code>{'mydata': {u'A': {'room': [u'1-1']},
            u'B': {'room': [u'1-1', u'1-2']},
            u'C': {'room': [u'1-1', u'1-2', u'1-3']},
            u'D': {'room': [u'1-1']}}
</code>```

In template

```<code>{% for data in mydata %}
    <div id="{{ data }}" class="tab-pane fade">
    {% for room in mydata.data.room  %}
            <h3>{{ room }}</h3>
            <p>Some content.</p>
    {% endfor %}
    </div>
{% endfor %}
</code>```

答:
Try this</p>

```<code>{% for i,j in mydata.items %}
    <div id="{{ i }}" class="tab-pane fade">
    {% for room in j.room  %}
        <h3>{{ room }}</h3>
        <p>Some content.</p>
    {% endfor %}
    </div>
{% endfor %}
</code>```

Body:
Is it able to import a string value from first loop to second loop in template?

In second loop, "mydata.data.room" should be mydata.A.room, mydata.B.room, mydata.C.room and mydata.D.room

In dictionary

{'mydata': {u'A': {'room': [u'1-1']},
            u'B': {'room': [u'1-1', u'1-2']},
            u'C': {'room': [u'1-1', u'1-2', u'1-3']},
            u'D': {'room': [u'1-1']}}

In template

{% for data in mydata %}

    {% for room in mydata.data.room  %}

{{ room }}

Some content.

    {% endfor %}

{% endfor %}

Body:
Try this

{% for i,j in mydata.items %}
    <div id="{{ i }}" class="tab-pane fade">
    {% for room in j.room  %}
        <h3>{{ room }}</h3>
        <p>Some content.</p>
    {% endfor %}
    </div>
{% endfor %}


问:
HTML 5 Geo Location Prompt in Chrome
Just starting to get into HTML 5 and an testing out geo location...liking it so far. I am hitting a bit of a speed bump though...when I try to get my geo location, chrome automatically blocks the page from getting my location. This does not happen at other sites such as the site below:

http://html5demos.com/geo

The scripts I'm using:

```<code><script type="text/javascript" JavaScript" SRC="geo.js"></script>
<script type="text/javascript" JavaScript" SRC="Utility.js"></script>
<script type="text/javascript" JavaScript" SRC="jquery.js"></script>
<script type="text/javascript" JavaScript" SRC="modernizr.js"></script>

function get_location() {

        if (geo_position_js.init()) {
            geo_position_js.getCurrentPosition(show_map, handle_error);
        }

    }
    function show_map(position) {
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;

        alert("lat:" + latitude + " long:" + longitude);

    }
    function handle_error(err) {
        alert(err.code);
        if (err.code == 1) {
            // user said no!
        }
    }

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(show_map, handle_error);
    } else {
        error('not supported');
    }
</code>```

I am testing this out from a local directory on my machine, so there isn't really a "domain" like "http://whatever.com/mytestpage.html". Is this why I am not getting prompted? If so, is it possible to force the browswer to request permission to get the user's geo location and is it possible in my scenario?

答: The easiest way is to click on the area left to the address bar and change location settings there. It allows to set location options even for file:///

Title: HTML 5 Geo Location Prompt in Chrome

Body:
Just starting to get into HTML 5 and an testing out geo location...liking it so far. I am hitting a bit of a speed bump though...when I try to get my geo location, chrome automatically blocks the page from getting my location. This does not happen at other sites such as the site below:

http://html5demos.com/geo

The scripts I'm using:

function get_location() {

        if (geo_position_js.init()) {
            geo_position_js.getCurrentPosition(show_map, handle_error);
        }

    }
    function show_map(position) {
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;

        alert("lat:" + latitude + " long:" + longitude);

    }
    function handle_error(err) {
        alert(err.code);
        if (err.code == 1) {
            // user said no!
        }
    }

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(show_map, handle_error);
    } else {
        error('not supported');
    }

I am testing this out from a local directory on my machine, so there isn't really a "domain" like "http://whatever.com/mytestpage.html". Is this why I am not getting prompted? If so, is it possible to force the browswer to request permission to get the user's geo location and is it possible in my scenario?


问:
Eclipse fails to open .vue files in Web Page Editor
I would like to open .vue files as regular HTML files in Eclipse. I tried to to right click a .vue file and then Open WithWeb Page Editor. I've also linked .vue in the preferences as a new file association to the Web Page Editor.

Doing exactly the above steps leads to the following error after opening the file. It also throws a NullPointerException:

Failed to create the part's controls

Is this a bug in Eclipse or am I doing something wrong?

My Eclipse version is:

```<code>Eclipse Java EE IDE for Web Developers.

Version: Neon.3 Release (4.6.3)
Build id: 20170314-1500
</code>```

I've seen in the Error Log, that the following message appears, after opening a .vue file in the Web Page Editor:

```<code>eclipse.buildId=4.6.3.M20170301-0400
java.version=1.8.0_92
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=de_CH
Framework arguments:  -product org.eclipse.epp.package.jee.product -product org.eclipse.epp.package.jee.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.jee.product -data file:/C:/Users/sebsc/eclipse-workspace/ -product org.eclipse.epp.package.jee.product

org.eclipse.jst.pagedesigner
Error
Wed Mar 29 19:27:35 CEST 2017
Unable to display palette for App.vue.  Unknown content type for file.
</code>```

Here is the stack trace of the NullPointerException:

```<code>java.lang.NullPointerException
    at org.eclipse.wst.sse.ui.StructuredTextEditor.createModelDependentFields(StructuredTextEditor.java:1503)
    at org.eclipse.wst.sse.ui.StructuredTextEditor.update(StructuredTextEditor.java:3156)
    at org.eclipse.jst.pagedesigner.editors.HTMLEditor.sash_createAndAddDesignSourcePage(HTMLEditor.java:297)
    at org.eclipse.jst.pagedesigner.editors.HTMLEditor.createPages(HTMLEditor.java:458)
    at org.eclipse.ui.part.MultiPageEditorPart.createPartControl(MultiPageEditorPart.java:363)
    at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.createPartControl(CompatibilityPart.java:150)
    at org.eclipse.ui.internal.e4.compatibility.CompatibilityEditor.createPartControl(CompatibilityEditor.java:99)
    at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.create(CompatibilityPart.java:340)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55)
    at org.eclipse.e4.core.internal.di.InjectorImpl.processAnnotated(InjectorImpl.java:966)
    at org.eclipse.e4.core.internal.di.InjectorImpl.processAnnotated(InjectorImpl.java:931)
    at org.eclipse.e4.core.internal.di.InjectorImpl.inject(InjectorImpl.java:151)
    at org.eclipse.e4.core.internal.di.InjectorImpl.internalMake(InjectorImpl.java:375)
    at org.eclipse.e4.core.internal.di.InjectorImpl.make(InjectorImpl.java:294)
    at org.eclipse.e4.core.contexts.ContextInjectionFactory.make(ContextInjectionFactory.java:162)
    at org.eclipse.e4.ui.internal.workbench.ReflectionContributionFactory.createFromBundle(ReflectionContributionFactory.java:105)
    at org.eclipse.e4.ui.internal.workbench.ReflectionContributionFactory.doCreate(ReflectionContributionFactory.java:74)
    at org.eclipse.e4.ui.internal.workbench.ReflectionContributionFactory.create(ReflectionContributionFactory.java:56)
    at org.eclipse.e4.ui.workbench.renderers.swt.ContributedPartRenderer.createWidget(ContributedPartRenderer.java:129)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.createWidget(PartRenderingEngine.java:975)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.safeCreateGui(PartRenderingEngine.java:651)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.safeCreateGui(PartRenderingEngine.java:757)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.access$0(PartRenderingEngine.java:728)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$2.run(PartRenderingEngine.java:722)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.createGui(PartRenderingEngine.java:706)
    at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer.showTab(StackRenderer.java:1317)
    at org.eclipse.e4.ui.workbench.renderers.swt.LazyStackRenderer$1.handleEvent(LazyStackRenderer.java:72)
    at org.eclipse.e4.ui.services.internal.events.UIEventHandler$1.run(UIEventHandler.java:40)
    at org.eclipse.swt.widgets.Synchronizer.syncExec(Synchronizer.java:233)
    at org.eclipse.ui.internal.UISynchronizer.syncExec(UISynchronizer.java:145)
    at org.eclipse.swt.widgets.Display.syncExec(Display.java:4821)
    at org.eclipse.e4.ui.internal.workbench.swt.E4Application$1.syncExec(E4Application.java:211)
    at org.eclipse.e4.ui.services.internal.events.UIEventHandler.handleEvent(UIEventHandler.java:36)
    at org.eclipse.equinox.internal.event.EventHandlerWrapper.handleEvent(EventHandlerWrapper.java:201)
    at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:197)
    at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:1)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148)
    at org.eclipse.equinox.internal.event.EventAdminImpl.dispatchEvent(EventAdminImpl.java:135)
    at org.eclipse.equinox.internal.event.EventAdminImpl.sendEvent(EventAdminImpl.java:78)
    at org.eclipse.equinox.internal.event.EventComponent.sendEvent(EventComponent.java:39)
    at org.eclipse.e4.ui.services.internal.events.EventBroker.send(EventBroker.java:94)
    at org.eclipse.e4.ui.internal.workbench.UIEventPublisher.notifyChanged(UIEventPublisher.java:60)
    at org.eclipse.emf.common.notify.impl.BasicNotifierImpl.eNotify(BasicNotifierImpl.java:374)
    at org.eclipse.e4.ui.model.application.ui.impl.ElementContainerImpl.setSelectedElement(ElementContainerImpl.java:173)
    at org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.showElementInWindow(ModelServiceImpl.java:617)
    at org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.bringToTop(ModelServiceImpl.java:581)
    at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.delegateBringToTop(PartServiceImpl.java:770)
    at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.bringToTop(PartServiceImpl.java:401)
    at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.showPart(PartServiceImpl.java:1214)
    at org.eclipse.ui.internal.WorkbenchPage.busyOpenEditor(WorkbenchPage.java:3261)
    at org.eclipse.ui.internal.WorkbenchPage.access$25(WorkbenchPage.java:3176)
    at org.eclipse.ui.internal.WorkbenchPage$10.run(WorkbenchPage.java:3158)
    at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70)
    at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:3153)
    at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:3117)
    at org.eclipse.ui.actions.OpenWithMenu.openEditor(OpenWithMenu.java:324)
    at org.eclipse.ui.actions.OpenWithMenu.lambda$0(OpenWithMenu.java:180)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4418)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4236)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3824)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022)
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150)
    at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1519)
</code>```

答:
You can find the window --> preferences-->editors as the picture shows:

If you do not set up, eclipse can not recognize the suffix of the file name do not know what way to use it

Body:
I would like to open .vue files as regular HTML files in Eclipse. I tried to to right click a .vue file and then Open WithWeb Page Editor. I've also linked .vue in the preferences as a new file association to the Web Page Editor.

Doing exactly the above steps leads to the following error after opening the file. It also throws a NullPointerException:

Failed to create the part's controls

Is this a bug in Eclipse or am I doing something wrong?

My Eclipse version is:

Eclipse Java EE IDE for Web Developers.

Version: Neon.3 Release (4.6.3)
Build id: 20170314-1500

I've seen in the Error Log, that the following message appears, after opening a .vue file in the Web Page Editor:

eclipse.buildId=4.6.3.M20170301-0400
java.version=1.8.0_92
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=de_CH
Framework arguments:  -product org.eclipse.epp.package.jee.product -product org.eclipse.epp.package.jee.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.jee.product -data file:/C:/Users/sebsc/eclipse-workspace/ -product org.eclipse.epp.package.jee.product

org.eclipse.jst.pagedesigner
Error
Wed Mar 29 19:27:35 CEST 2017
Unable to display palette for App.vue.  Unknown content type for file.

Here is the stack trace of the NullPointerException:

java.lang.NullPointerException
    at org.eclipse.wst.sse.ui.StructuredTextEditor.createModelDependentFields(StructuredTextEditor.java:1503)
    at org.eclipse.wst.sse.ui.StructuredTextEditor.update(StructuredTextEditor.java:3156)
    at org.eclipse.jst.pagedesigner.editors.HTMLEditor.sash_createAndAddDesignSourcePage(HTMLEditor.java:297)
    at org.eclipse.jst.pagedesigner.editors.HTMLEditor.createPages(HTMLEditor.java:458)
    at org.eclipse.ui.part.MultiPageEditorPart.createPartControl(MultiPageEditorPart.java:363)
    at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.createPartControl(CompatibilityPart.java:150)
    at org.eclipse.ui.internal.e4.compatibility.CompatibilityEditor.createPartControl(CompatibilityEditor.java:99)
    at org.eclipse.ui.internal.e4.compatibility.CompatibilityPart.create(CompatibilityPart.java:340)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:55)
    at org.eclipse.e4.core.internal.di.InjectorImpl.processAnnotated(InjectorImpl.java:966)
    at org.eclipse.e4.core.internal.di.InjectorImpl.processAnnotated(InjectorImpl.java:931)
    at org.eclipse.e4.core.internal.di.InjectorImpl.inject(InjectorImpl.java:151)
    at org.eclipse.e4.core.internal.di.InjectorImpl.internalMake(InjectorImpl.java:375)
    at org.eclipse.e4.core.internal.di.InjectorImpl.make(InjectorImpl.java:294)
    at org.eclipse.e4.core.contexts.ContextInjectionFactory.make(ContextInjectionFactory.java:162)
    at org.eclipse.e4.ui.internal.workbench.ReflectionContributionFactory.createFromBundle(ReflectionContributionFactory.java:105)
    at org.eclipse.e4.ui.internal.workbench.ReflectionContributionFactory.doCreate(ReflectionContributionFactory.java:74)
    at org.eclipse.e4.ui.internal.workbench.ReflectionContributionFactory.create(ReflectionContributionFactory.java:56)
    at org.eclipse.e4.ui.workbench.renderers.swt.ContributedPartRenderer.createWidget(ContributedPartRenderer.java:129)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.createWidget(PartRenderingEngine.java:975)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.safeCreateGui(PartRenderingEngine.java:651)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.safeCreateGui(PartRenderingEngine.java:757)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.access$0(PartRenderingEngine.java:728)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$2.run(PartRenderingEngine.java:722)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.createGui(PartRenderingEngine.java:706)
    at org.eclipse.e4.ui.workbench.renderers.swt.StackRenderer.showTab(StackRenderer.java:1317)
    at org.eclipse.e4.ui.workbench.renderers.swt.LazyStackRenderer$1.handleEvent(LazyStackRenderer.java:72)
    at org.eclipse.e4.ui.services.internal.events.UIEventHandler$1.run(UIEventHandler.java:40)
    at org.eclipse.swt.widgets.Synchronizer.syncExec(Synchronizer.java:233)
    at org.eclipse.ui.internal.UISynchronizer.syncExec(UISynchronizer.java:145)
    at org.eclipse.swt.widgets.Display.syncExec(Display.java:4821)
    at org.eclipse.e4.ui.internal.workbench.swt.E4Application$1.syncExec(E4Application.java:211)
    at org.eclipse.e4.ui.services.internal.events.UIEventHandler.handleEvent(UIEventHandler.java:36)
    at org.eclipse.equinox.internal.event.EventHandlerWrapper.handleEvent(EventHandlerWrapper.java:201)
    at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:197)
    at org.eclipse.equinox.internal.event.EventHandlerTracker.dispatchEvent(EventHandlerTracker.java:1)
    at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
    at org.eclipse.osgi.framework.eventmgr.ListenerQueue.dispatchEventSynchronous(ListenerQueue.java:148)
    at org.eclipse.equinox.internal.event.EventAdminImpl.dispatchEvent(EventAdminImpl.java:135)
    at org.eclipse.equinox.internal.event.EventAdminImpl.sendEvent(EventAdminImpl.java:78)
    at org.eclipse.equinox.internal.event.EventComponent.sendEvent(EventComponent.java:39)
    at org.eclipse.e4.ui.services.internal.events.EventBroker.send(EventBroker.java:94)
    at org.eclipse.e4.ui.internal.workbench.UIEventPublisher.notifyChanged(UIEventPublisher.java:60)
    at org.eclipse.emf.common.notify.impl.BasicNotifierImpl.eNotify(BasicNotifierImpl.java:374)
    at org.eclipse.e4.ui.model.application.ui.impl.ElementContainerImpl.setSelectedElement(ElementContainerImpl.java:173)
    at org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.showElementInWindow(ModelServiceImpl.java:617)
    at org.eclipse.e4.ui.internal.workbench.ModelServiceImpl.bringToTop(ModelServiceImpl.java:581)
    at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.delegateBringToTop(PartServiceImpl.java:770)
    at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.bringToTop(PartServiceImpl.java:401)
    at org.eclipse.e4.ui.internal.workbench.PartServiceImpl.showPart(PartServiceImpl.java:1214)
    at org.eclipse.ui.internal.WorkbenchPage.busyOpenEditor(WorkbenchPage.java:3261)
    at org.eclipse.ui.internal.WorkbenchPage.access$25(WorkbenchPage.java:3176)
    at org.eclipse.ui.internal.WorkbenchPage$10.run(WorkbenchPage.java:3158)
    at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70)
    at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:3153)
    at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:3117)
    at org.eclipse.ui.actions.OpenWithMenu.openEditor(OpenWithMenu.java:324)
    at org.eclipse.ui.actions.OpenWithMenu.lambda$0(OpenWithMenu.java:180)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4418)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4236)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3824)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022)
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150)
    at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:693)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:610)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1519)


问:
Angular 2 service method is not accessible
I have following files and trying to access the service method loginMethod. Kindly help, i have wasted my 2 days on this error. I am new in Angular 2.

app.module

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { LoginComponent } from './Login/login.component';

import { LoginService } from './Login/login.service';

import 'rxjs/Rx'; //Load all features

@NgModule({
    imports: [BrowserModule, FormsModule, HttpModule],
    declarations: [AppComponent, LoginComponent],
    providers: [LoginService],
    bootstrap: [AppComponent]
})

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

app.component

```<code>import { Component } from '@angular/core';
import { LoginComponent } from './Login/login.Component';

@Component({
    selector: 'pm-app',
    template:

`<div>
                <h1>Success</h1>
                <pm-login></pm-login>
                </div>`
})

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

login.component

```<code>import { Component, OnInit } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import { LoginService } from './login.service';

// Observable class extensions
import 'rxjs/add/observable/of';
// Observable operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';

@Component({
    selector: 'pm-login',
    template: `<div>
                    <h1>Login</h1>
                    <input type="text" placeholder="User Name"/><br/>
                    <input type="Password" placeholder="Password"/><br/>
                    <input type="button" title="Login" value="Login" (click)='loginClick()' />
                </div>`,
    providers: [LoginService]
})

export class LoginComponent {
    constructor() { }

    private _loginService: LoginService;
    private _loginRes: boolean;

    loginClick() {
        alert("login component");
        this._loginService.loginMethod().subscribe(resLogin => this._loginRes = resLogin);
    }

    ngOnInit() {
        this.loginClick();
        this._loginService.alertMethod();
    }
}
</code>```

login.service

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

@Injectable()
export class LoginService {
    constructor()
    { }
    private _http: Http;
    private _apiUrl: string = 'http://localhost:13131/api/Account/Get';
    private headers = new Headers({ 'Content-Type': 'application/json' });

    alertMethod()
    {
        alert("alert Method");
    }

    loginMethod()  {
        alert('Login Service');
        return this._http.get(this._apiUrl)
            .map((response: Response) => response.json()).catch(this.handleError);

    }

    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error); // for demo purposes only
        return Promise.reject(error.message || error);
    }
}
</code>```

答:
change you code to this;

```<code>export class LoginComponent {
    constructor(private _loginService: LoginService) { }

    private _loginRes: boolean;
</code>```

And also change this

```<code>export class LoginService {
    constructor(private _http: Http)
    { }
</code>```

This is how DI works.

Body:
I have following files and trying to access the service method loginMethod. Kindly help, i have wasted my 2 days on this error. I am new in Angular 2.

app.module

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { LoginComponent } from './Login/login.component';

import { LoginService } from './Login/login.service';

import 'rxjs/Rx'; //Load all features

@NgModule({
    imports: [BrowserModule, FormsModule, HttpModule],
    declarations: [AppComponent, LoginComponent],
    providers: [LoginService],
    bootstrap: [AppComponent]
})

export class AppModule { }

app.component

import { Component } from '@angular/core';
import { LoginComponent } from './Login/login.Component';

@Component({
    selector: 'pm-app',
    template:

`

Success

                <pm-login></pm-login>

`
})

export class AppComponent {
}

login.component

import { Component, OnInit } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import { LoginService } from './login.service';

// Observable class extensions
import 'rxjs/add/observable/of';
// Observable operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';

@Component({
    selector: 'pm-login',
    template: `

Login

                    <input type="text" placeholder="User Name"/>

                    <input type="Password" placeholder="Password"/>

                    <input type="button" title="Login" value="Login" (click)='loginClick()' />

`,
    providers: [LoginService]
})

export class LoginComponent {
    constructor() { }

    private _loginService: LoginService;
    private _loginRes: boolean;

    loginClick() {
        alert("login component");
        this._loginService.loginMethod().subscribe(resLogin => this._loginRes = resLogin);
    }

    ngOnInit() {
        this.loginClick();
        this._loginService.alertMethod();
    }
}

login.service

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

@Injectable()
export class LoginService {
    constructor()
    { }
    private _http: Http;
    private _apiUrl: string = 'http://localhost:13131/api/Account/Get';
    private headers = new Headers({ 'Content-Type': 'application/json' });

    alertMethod()
    {
        alert("alert Method");
    }

    loginMethod()  {
        alert('Login Service');
        return this._http.get(this._apiUrl)
            .map((response: Response) => response.json()).catch(this.handleError);

    }

    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error); // for demo purposes only
        return Promise.reject(error.message || error);
    }
}

Body:
change you code to this;

export class LoginComponent {
    constructor(private _loginService: LoginService) { }

    private _loginRes: boolean;

And also change this

export class LoginService {
    constructor(private _http: Http)
    { }

This is how DI works.


问:
Can't import MySQL database due to syntax error
But why?
I've imported it in OS X and on another Linux machine,
this one however plain refuses..

Where am I going wrong?

Output:

mysql> mysql -u root -p explore < /tmp/explore.sql;

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'mysql -u root -p explore < /tmp/explore.sql' at line 1

答:
You are trying to run a shell command from the MySQL command line interpreter. You need to run that from BASH (or any other shell), no the MYSQL command prompt.

Like this in Linux:

```<code>$ mysql -u root -p explore < /tmp/explore.sql;
</code>```

Like this in Windows:

```<code>C:\> mysql -u root -p explore < c:\tmp\explore.sql;
</code>```

Body:
You are trying to run a shell command from the MySQL command line interpreter. You need to run that from BASH (or any other shell), no the MYSQL command prompt.

Like this in Linux:

$ mysql -u root -p explore < /tmp/explore.sql;

Like this in Windows:

C:\> mysql -u root -p explore < c:\tmp\explore.sql;


问:
PHP from associative array to User Class

I know that I can cast an associative array to object doing this:

```<code>$user = (object) $_POST["user"];
</code>```

I have a class User that has method getName, getEmail etc.
If I do

```<code>$user = (object) $_POST["user"];
$user->getName();
</code>```

It gives this error

```<code>Fatal error: Call to undefined method stdClass::getName()
</code>```

Can I do something like this?

```<code>$user = (user) $_POST["user"];
</code>```

Thank you

答:
You can use something like this

```<code><?php
  Class User{
      protected $name;
      public function setName($name){
         $this->name = $name;
      }
      public function getName(){
         return $this->name;
      }
  }
$arr = ["name"=>"Niklesh"];
$abc = new User;
$abc->setName($arr["name"]);
var_dump($abc);
var_dump($abc->getName());
?>
</code>```

Demo : https://eval.in/765496

Body:
I know that I can cast an associative array to object doing this:

$user = (object) $_POST["user"];

I have a class User that has method getName, getEmail etc.
If I do

$user = (object) $_POST["user"];
$user->getName();

It gives this error

Fatal error: Call to undefined method stdClass::getName()

Can I do something like this?

$user = (user) $_POST["user"];

Thank you

Body:
You can use something like this

<?php
  Class User{
      protected $name;
      public function setName($name){
         $this->name = $name;
      }
      public function getName(){
         return $this->name;
      }
  }
$arr = ["name"=>"Niklesh"];
$abc = new User;
$abc->setName($arr["name"]);
var_dump($abc);
var_dump($abc->getName());
?>

Demo : https://eval.in/765496


问:
Using isGranted inside a Symfony voter
Sometimes, I have a page where I want to react to a complex combination of different rules, which altogether amount to just a single thing: 'can the current user do this?'.

At the moment, most of those checks are directly within my controller, so I'd have for example:

```<code>if($this->isGranted('DRAFT_EDITOR', $draft) && $now < $deadline && $draft->getStatus() != Draft::STATUS_FINAL) {...}
</code>```

Those sorts of if conditions get pretty long, and could potentially end up being repeated throughout the code, all achieving precisely the same thing. So I wanted to abstract these out into Voters, so that I could just say:

```<code>if($this->isGranted('DRAFT_CAN_EDIT') {}
</code>```

That would then go to a DraftCanEdit voter which would encapsulate all those checks from the IF statement at the top of this post in one place, and make it easy to change the rules for what makes a draft editable, harder to accidentally miss a condition or mess one up somewhere and create vulnerabilities, etc.

The problem is that voters can't call isGranted(), because it's considered a circular reference just to inject into a voter the security.authorization_checker service.

To me, a Voter calling isGranted seems semantically fine as a form of voter inheritance, and so long as the Voter doesn't support the attribute/subject that it passes to isGranted, shouldn't actually result in any kind of circular reference issues.

Of course, I could duplicate the DraftEditorVoter logic inside the DraftCanEditVoter, or I could instantiate a DraftEditorVoter inside DraftCanEditVoter, but neither of these seem ideal, not just for reasons of code duplication but also because I actually have two voters that, together, determine if someone is a DRAFT_EDITOR or not.

I also am aware I could encapsulate the IF conditions by just making my own non-Voter object and using it directly like that but think that may be a bit of an anti-pattern.

答:
From my point of view, you can do two things:

I was curious about your problem, so I searched the docs. This way, I came across this part of the docs, the AccessDecisionManager: http://symfony.com/doc/current/security/voters.html#checking-for-roles-inside-a-voter. I bet, you can use it to check your DraftEditorVoter

You could inject your DraftEditorVoter into the DraftCanEditVoter. This way, you can use its voteOnAttribute method without creating a dependency loop. Everything you need to call it is already passed to your voter so parameters shouldn't be a problem.

Title: Using isGranted inside a Symfony voter

Body:
Sometimes, I have a page where I want to react to a complex combination of different rules, which altogether amount to just a single thing: 'can the current user do this?'.

At the moment, most of those checks are directly within my controller, so I'd have for example:

if($this->isGranted('DRAFT_EDITOR', $draft) && $now < $deadline && $draft->getStatus() != Draft::STATUS_FINAL) {...}

Those sorts of if conditions get pretty long, and could potentially end up being repeated throughout the code, all achieving precisely the same thing. So I wanted to abstract these out into Voters, so that I could just say:

if($this->isGranted('DRAFT_CAN_EDIT') {}

That would then go to a DraftCanEdit voter which would encapsulate all those checks from the IF statement at the top of this post in one place, and make it easy to change the rules for what makes a draft editable, harder to accidentally miss a condition or mess one up somewhere and create vulnerabilities, etc.

The problem is that voters can't call isGranted(), because it's considered a circular reference just to inject into a voter the security.authorization_checker service.

To me, a Voter calling isGranted seems semantically fine as a form of voter inheritance, and so long as the Voter doesn't support the attribute/subject that it passes to isGranted, shouldn't actually result in any kind of circular reference issues.

Of course, I could duplicate the DraftEditorVoter logic inside the DraftCanEditVoter, or I could instantiate a DraftEditorVoter inside DraftCanEditVoter, but neither of these seem ideal, not just for reasons of code duplication but also because I actually have two voters that, together, determine if someone is a DRAFT_EDITOR or not.

I also am aware I could encapsulate the IF conditions by just making my own non-Voter object and using it directly like that but think that may be a bit of an anti-pattern.


问:
Github Pages - Organisation site not showing up
I created an organisation (<orgname>) on github. In that organisation I added a repo named <orgname>.github.io. In that repo, I added an index.html and fired up https://<orgname>.github.io but I kept getting a 404 status.

Why?

答:
I figured by accident that a README.md file is mandatory for Github to host the site. Once a README was added, the site loaded immediately.

If I had followed the tuts in pages.github.com, I wouldn't have wasted time. But I started working on a site from my previous experience and a README seemed not so important.


问:
Kendo grid add new entry
I have two pages in which there is one grid in each page. When I press a custom button of one grid I need to open the add new entry of the other grid in the other page.

I will explain it with my situation I have two pages customers and enquiries in each page having one grid. The customer grid is having a custom command add enquiry. When I press this button I should open the add new Enquiry of the enquiries grid in the enquiries page.

Thanks in advance for any help.

答:
It is actually quite simple just call grid.addRow() method after routing to that page as shown below

```<code>var grid = $("#gridId").data("kendoGrid");
grid.addRow();
</code>```

This will open the add new entry.

Title: Kendo grid add new entry

Body:
It is actually quite simple just call grid.addRow() method after routing to that page as shown below

var grid = $("#gridId").data("kendoGrid");
grid.addRow();

This will open the add new entry.


问:
Using Notepad++ to compile Java code
I've been trying to set up Notepad++ as a little Java environment, mainly for learning Java as I was having some difficulty getting a simple program to work with NetBeans, unfortunately all the advice on setting up Notepad++ to call the Java code is not working.

I guess notepad++ has changed or the Java development Kit has been massively modified because all examples I have used result in errors, even though there is little room for error.

to begin I found this site:
http://blog.sanaulla.info/2008/07/25/using-notepad-to-compile-and-run-java-programs/

this is the code to run Javac to compile the code:

```<code>javac “$(FILE_NAME)”
</code>```

and

```<code>java “$(NAME_PART)”
</code>```

to run the resulted byte code, however this has absolutely no success at all anymore. Java is properly setup and I can call the Java program to do its thing through CMD.

Using a plugin called npp and called through F6 and run with this code (given in the comments) succeeds in compiling the Java program into the correct .class file, however the command failed in running the program

```<code>cd “$(CURRENT_DIRECTORY)”
javac $(FILE_NAME)
java $(NAME_PART)
</code>```

errors from the console in Notepad++ are:

```<code>java.lang.NoClassDefFoundError: first
Caused by: java.lang.ClassNotFoundException: first
  at java.net.URLClassLoader$1.run(Unknown Source)
  at java.security.AccessController.doPrivileged(Native Method)
  at java.net.URLClassLoader.findClass(Unknown Source)
  at java.lang.ClassLoader.loadClass(Unknown Source)
  at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
  at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: first.  Program will exit.
Exception in thread "main"
</code>```

I figured setting up Notepad++ to compile and run the code would be easy and fun, but its seems all documentation on the internet is outdated as nothing works.

I would like a easy way to compile and run Java code from within Notepad++

I could just used CMD but i'd rather it be more integrated into notepad++

Thanks for any possible help. cheers :)

EDIT: I'm using the latest version of Java, notepad++ and have Windows 7

EDIT 2: the code:

```<code> //A Very Simple Example
 class ExampleProgram {

   public static void main(String[] args){

        System.out.println("I'm a Simple Program");
   }
 }
</code>```

答:
Probably changing the last line to:

```<code>java -cp . $(NAME_PART)
</code>```

will work for you. The problem is that you aren't setting up the classpath.

Notepad++ will be fine for compiling a single file project. For anything more than this you will need an IDE or at least integrate with ant instead of java compiler.

Title: Using Notepad++ to compile Java code

Body:
I've been trying to set up Notepad++ as a little Java environment, mainly for learning Java as I was having some difficulty getting a simple program to work with NetBeans, unfortunately all the advice on setting up Notepad++ to call the Java code is not working.

I guess notepad++ has changed or the Java development Kit has been massively modified because all examples I have used result in errors, even though there is little room for error.

to begin I found this site:
http://blog.sanaulla.info/2008/07/25/using-notepad-to-compile-and-run-java-programs/

this is the code to run Javac to compile the code:

javac “$(FILE_NAME)”

and

java “$(NAME_PART)”

to run the resulted byte code, however this has absolutely no success at all anymore. Java is properly setup and I can call the Java program to do its thing through CMD.

Using a plugin called npp and called through F6 and run with this code (given in the comments) succeeds in compiling the Java program into the correct .class file, however the command failed in running the program

cd “$(CURRENT_DIRECTORY)”
javac $(FILE_NAME)
java $(NAME_PART)

errors from the console in Notepad++ are:

java.lang.NoClassDefFoundError: first
Caused by: java.lang.ClassNotFoundException: first
  at java.net.URLClassLoader$1.run(Unknown Source)
  at java.security.AccessController.doPrivileged(Native Method)
  at java.net.URLClassLoader.findClass(Unknown Source)
  at java.lang.ClassLoader.loadClass(Unknown Source)
  at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
  at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: first.  Program will exit.
Exception in thread "main"

I figured setting up Notepad++ to compile and run the code would be easy and fun, but its seems all documentation on the internet is outdated as nothing works.

I would like a easy way to compile and run Java code from within Notepad++

I could just used CMD but i'd rather it be more integrated into notepad++

Thanks for any possible help. cheers :)

EDIT: I'm using the latest version of Java, notepad++ and have Windows 7

EDIT 2: the code:

 //A Very Simple Example
 class ExampleProgram {

   public static void main(String[] args){

        System.out.println("I'm a Simple Program");
   }
 }

Body:
Probably changing the last line to:

java -cp . $(NAME_PART)

will work for you. The problem is that you aren't setting up the classpath.

Notepad++ will be fine for compiling a single file project. For anything more than this you will need an IDE or at least integrate with ant instead of java compiler.


问:
Not able to convert image from url into byte array
I am new to android and I need to save image from url into db and fetch it from db. I an converting image from link into byte array but getting the following error:

Cannot Resolve ByteArrayBuffer

This is the code:

```<code> private byte[] getLogoImage(String url){
    try {
             URL imageUrl = new URL(url);
             URLConnection ucon = imageUrl.openConnection();

             InputStream is = ucon.getInputStream();
             BufferedInputStream bis = new BufferedInputStream(is);

             ByteArrayBuffer baf = new ByteArrayBuffer(500);
             int current = 0;
             while ((current = bis.read()) != -1) {
                     baf.append((byte) current);
             }

             return baf.toByteArray();
     } catch (Exception e) {
             Log.d("ImageManager", "Error: " + e.toString());
     }
     return null;
}
</code>```

答:
Update your method getLogoImage() as below.

Use AsyncTask and call this method from doInBackground().

Here is the working code. Try this:

```<code>private byte[] getLogoImage(String url) {

    try {

        URL imageUrl = new URL(url);
        URLConnection ucon = imageUrl.openConnection();

        InputStream is = ucon.getInputStream();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int read = 0;

        while ((read = is.read(buffer, 0, buffer.length)) != -1) {
            baos.write(buffer, 0, read);
        }

        baos.flush();

        return  baos.toByteArray();

    } catch (Exception e) {
        Log.d("ImageManager", "Error: " + e.toString());
    }

    return null;
}
</code>```

Body:
I am new to android and I need to save image from url into db and fetch it from db. I an converting image from link into byte array but getting the following error:

Cannot Resolve ByteArrayBuffer

This is the code:

 private byte[] getLogoImage(String url){
    try {
             URL imageUrl = new URL(url);
             URLConnection ucon = imageUrl.openConnection();

             InputStream is = ucon.getInputStream();
             BufferedInputStream bis = new BufferedInputStream(is);

             ByteArrayBuffer baf = new ByteArrayBuffer(500);
             int current = 0;
             while ((current = bis.read()) != -1) {
                     baf.append((byte) current);
             }

             return baf.toByteArray();
     } catch (Exception e) {
             Log.d("ImageManager", "Error: " + e.toString());
     }
     return null;
}

Body:
Update your method getLogoImage() as below.

Use AsyncTask and call this method from doInBackground().

Here is the working code. Try this:

private byte[] getLogoImage(String url) {

    try {

        URL imageUrl = new URL(url);
        URLConnection ucon = imageUrl.openConnection();

        InputStream is = ucon.getInputStream();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int read = 0;

        while ((read = is.read(buffer, 0, buffer.length)) != -1) {
            baos.write(buffer, 0, read);
        }

        baos.flush();

        return  baos.toByteArray();

    } catch (Exception e) {
        Log.d("ImageManager", "Error: " + e.toString());
    }

    return null;
}


问:
Relation of c# name space and file
How is a C# namespace related to the physical representation of the program in files and folders?

When one uses a using directive, e.g.:

```<code>using MyNameSpace;
</code>```

Where does does the C# compiler look for that namespace? Is there some documentation which covers the relationship of logical entities like namespaces and classes with their physical representations?

My .csproj file just contains

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

</Project>
</code>```

Nevertheless it seems to compile all .cs files in the project. I am using Visual Studio Code and want to understand the magic that is going on.

答:
Unlike Java, the compiler does not require the files to follow the same structure as the namespace, nor does it require the filename to match the class name.

I think it's still good style to name your files the same as the class name, which is what VisualStudio defaults to when you use the new class wizard.  If you create a class in a folder in your project, VisualStudio will also default to a namespace that combines the base namespace with the folder name.

Title: Relation of c# name space and file

Body:
How is a C# namespace related to the physical representation of the program in files and folders?

When one uses a using directive, e.g.:

using MyNameSpace;

Where does does the C# compiler look for that namespace? Is there some documentation which covers the relationship of logical entities like namespaces and classes with their physical representations?

My .csproj file just contains

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>

</Project>

Nevertheless it seems to compile all .cs files in the project. I am using Visual Studio Code and want to understand the magic that is going on.


问:
How to Get And List All files from a Github Repository
I am trying to list all files from a Github repository.

```<code>def listFiles(self, filepath):
    git = githubHandler(GH_USERNAME, GH_PASSWORD)
    gh, repo, branch = git.connect_to_github()
    tree = branch.commit.commit.tree.recurse()
    print repo.blob
    print branch
</code>```

So far I can only output the repo branch and name.
Any ideas?

答:
So this is how I solved it after struggling for a while:</p>

```<code>def list_filenames(self, filepath):
    git = githubHandler(GH_USERNAME, GH_PASSWORD)
    gh, repo, branch = git.connect_to_github()
    tree = branch.commit.commit.tree.recurse()
    for filename in tree.tree:
        print("[*] Found file {0}".format(filename.path))
        print filename.path
    return None
</code>```

Body:
I am trying to list all files from a Github repository.

def listFiles(self, filepath):
    git = githubHandler(GH_USERNAME, GH_PASSWORD)
    gh, repo, branch = git.connect_to_github()
    tree = branch.commit.commit.tree.recurse()
    print repo.blob
    print branch

So far I can only output the repo branch and name.
Any ideas?

Body:
So this is how I solved it after struggling for a while:

def list_filenames(self, filepath):
    git = githubHandler(GH_USERNAME, GH_PASSWORD)
    gh, repo, branch = git.connect_to_github()
    tree = branch.commit.commit.tree.recurse()
    for filename in tree.tree:
        print("[*] Found file {0}".format(filename.path))
        print filename.path
    return None