问:
How to properly use setZOrderMediaOverlay on Android?
Like many others, I am trying to draw 3D objects (using GLSurfaceView) on camera preview (using SurfaceView), along with some buttons placed on top. I actually got a prototype working, but I could not get the onResume working correctly. After a resume, GLSurfaceView stays behind and is not visible anymore. I know that it is working, because I can see the drawing fine if I remove the SurfaceView from the layout.

The target is Nexus One, running stock 2.3.3 ROM.

Here's the layout xml:

```<code><com.example.cameratest.GLPreview
        android:id="@+id/cubes"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>

<com.example.cameratest.Preview
        android:id="@+id/camera"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/buttongroup"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_gravity="right" android:gravity="center">

    <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:id="@+id/buttonClose"></Button>
    <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:id="@+id/buttonMode"></Button>
    <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:id="@+id/buttonCameraInfo"></Button>
</LinearLayout>
</code>```

All of this is wrapped in a <merge> block, but for some reason, I could not include it in the above  listing. Preview is the class that extends SurfaceView and implements the camera preview logic.

This works fine when the activity launches. After I launch another activity (for example, by pressing one of the buttons) and finish that activity, the main activity resumes but the 3D objects are not visible anymore.

I found this discussion where it is mentioned that setZOrderMediaOverlay() will help fix this z-ordering issue. Also, the Android document for setZOrderMediaOverlay() says this function should be called "before the surface view's containing window is attached to the window manager". I do not know how I should interpret that statement, so I put debug statements in the code to see the sequence of events. Here's how the GLSurfaceView code looks like:

```<code>
public class GLPreview extends GLSurfaceView
{
    private static final String TAG = "GLPreview";

    public GLPreview(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        // this.setZOrderMediaOverlay(true);
    }

    public void onPause()
    {
        super.onPause();
        Log.d(TAG, "GLPreview: OnPause");
    }

    public void onResume()
    {
        // this.setZOrderMediaOverlay(true);
        super.onResume();
        Log.d(TAG, "GLPreview: OnResume");
    }

    public void surfaceCreated(SurfaceHolder holder)
    {
        Log.d(TAG, "GLPreview: surfaceCreated");
        super.surfaceCreated(holder);
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h)
    {
        Log.d(TAG, String.format("GLPreview: surfaceChanged, format=%d, w=%d, h=%d", format, w, h));
        super.surfaceChanged(holder, format, w, h);
    }

    public void surfaceDestroyed(SurfaceHolder holder)
    {
        Log.d(TAG, "GLPreview: surfaceDestroyed");
        super.surfaceDestroyed(holder);
    }

    protected void onAttachedToWindow()
    {
        Log.d(TAG, "GLPreview: onAttachedToWindow");
        super.onAttachedToWindow();
    }

    protected void onDetachedFromWindow()
    {
        Log.d(TAG, "GLPreview: onDetachedFromWindow");
        super.onDetachedFromWindow();
    }

    protected void onWindowVisibilityChanged (int vis)
    {
        String newVisibility;
        switch (vis)
        {
            case View.GONE:
                newVisibility = "GONE";
                break;
            case View.INVISIBLE:
                newVisibility = "INVISIBLE";
                break;
            case View.VISIBLE:
                newVisibility = "VISIBLE";
                break;
            default:
                newVisibility = String.format("Unknown constant %d", vis);
        }

        Log.d(TAG, String.format("GLPreview: onWindowVisibilityChanged -> %s", newVisibility));
        super.onWindowVisibilityChanged(vis);
    }
}
</code>
```

Here's the sequence of events when I start the application:

```
GLPreview: OnResume
GLPreview: onAttachedToWindow
GLPreview: onWindowVisibilityChanged -> VISIBLE
GLPreview: surfaceCreated
GLPreview: surfaceChanged, format=1, w=800, h=480
```

So I assumed that setZOrderMediaOverlay() needs to be called in either onResume() or in the constructor. However, I tried various combinations of setZOrderMediaOverlay() with true or false, in the GLSurfaceView or the SurfaceView classes, but none of it helped with the problem.

I am relatively new when it comes to Android programming. I have come so far but at this point I need some help. If someone who used setZOrderMediaOverlay() successfully in this scenario and got it working with onResume() let me know how this needs to be done.

Thanks a lot in advance!

答:
I have struggled with the same issue for some time, but believe the code below now works. (It continues to work after pausing/ locking regardless of whether the camera is on or off).

Firstly, I haven't got any views etc defined in the layout file - they're created in code. The following is called from the main onCreate() method - Note the setZOrderMediaOverlay() on the augScreen.

I have done nothing special within onPause() or onResume() apart from passing onPause() and onResume() through to the augScreen.

```<code>        // 1 - Camera Preview
        camScreen = new CameraPreview(this);
        setContentView(camScreen, new LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

    // 2 - 3D object display
        augScreen = new AR_SurfaceView(this, getViewRange());
        addContentView(augScreen, new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        augScreen.setZOrderMediaOverlay(true);

    // 3 - Permanent overlay
    RelativeLayout overlayScreen = new OverlayView(this);
    addContentView(overlayScreen, new LayoutParams(
            LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    overlayScreen.setVisibility(View.VISIBLE);

    // 4 - UI buttons (toggleable)
        uiScreen = new UserInterfaceView(this);
        addContentView(uiScreen, new LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
</code>```

Body:
Like many others, I am trying to draw 3D objects (using GLSurfaceView) on camera preview (using SurfaceView), along with some buttons placed on top. I actually got a prototype working, but I could not get the onResume working correctly. After a resume, GLSurfaceView stays behind and is not visible anymore. I know that it is working, because I can see the drawing fine if I remove the SurfaceView from the layout.

The target is Nexus One, running stock 2.3.3 ROM.

Here's the layout xml:

<com.example.cameratest.GLPreview
        android:id="@+id/cubes"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>

<com.example.cameratest.Preview
        android:id="@+id/camera"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/buttongroup"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_gravity="right" android:gravity="center">

    <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:id="@+id/buttonClose"></Button>
    <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:id="@+id/buttonMode"></Button>
    <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:id="@+id/buttonCameraInfo"></Button>
</LinearLayout>

All of this is wrapped in a <merge> block, but for some reason, I could not include it in the above  listing. Preview is the class that extends SurfaceView and implements the camera preview logic.

This works fine when the activity launches. After I launch another activity (for example, by pressing one of the buttons) and finish that activity, the main activity resumes but the 3D objects are not visible anymore.

I found this discussion where it is mentioned that setZOrderMediaOverlay() will help fix this z-ordering issue. Also, the Android document for setZOrderMediaOverlay() says this function should be called "before the surface view's containing window is attached to the window manager". I do not know how I should interpret that statement, so I put debug statements in the code to see the sequence of events. Here's how the GLSurfaceView code looks like:

public class GLPreview extends GLSurfaceView
{
    private static final String TAG = "GLPreview";

    public GLPreview(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        // this.setZOrderMediaOverlay(true);
    }

    public void onPause()
    {
        super.onPause();
        Log.d(TAG, "GLPreview: OnPause");
    }

    public void onResume()
    {
        // this.setZOrderMediaOverlay(true);
        super.onResume();
        Log.d(TAG, "GLPreview: OnResume");
    }

    public void surfaceCreated(SurfaceHolder holder)
    {
        Log.d(TAG, "GLPreview: surfaceCreated");
        super.surfaceCreated(holder);
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h)
    {
        Log.d(TAG, String.format("GLPreview: surfaceChanged, format=%d, w=%d, h=%d", format, w, h));
        super.surfaceChanged(holder, format, w, h);
    }

    public void surfaceDestroyed(SurfaceHolder holder)
    {
        Log.d(TAG, "GLPreview: surfaceDestroyed");
        super.surfaceDestroyed(holder);
    }

    protected void onAttachedToWindow()
    {
        Log.d(TAG, "GLPreview: onAttachedToWindow");
        super.onAttachedToWindow();
    }

    protected void onDetachedFromWindow()
    {
        Log.d(TAG, "GLPreview: onDetachedFromWindow");
        super.onDetachedFromWindow();
    }

    protected void onWindowVisibilityChanged (int vis)
    {
        String newVisibility;
        switch (vis)
        {
            case View.GONE:
                newVisibility = "GONE";
                break;
            case View.INVISIBLE:
                newVisibility = "INVISIBLE";
                break;
            case View.VISIBLE:
                newVisibility = "VISIBLE";
                break;
            default:
                newVisibility = String.format("Unknown constant %d", vis);
        }

        Log.d(TAG, String.format("GLPreview: onWindowVisibilityChanged -> %s", newVisibility));
        super.onWindowVisibilityChanged(vis);
    }
}

Here's the sequence of events when I start the application:

GLPreview: OnResume
GLPreview: onAttachedToWindow
GLPreview: onWindowVisibilityChanged -> VISIBLE
GLPreview: surfaceCreated
GLPreview: surfaceChanged, format=1, w=800, h=480

So I assumed that setZOrderMediaOverlay() needs to be called in either onResume() or in the constructor. However, I tried various combinations of setZOrderMediaOverlay() with true or false, in the GLSurfaceView or the SurfaceView classes, but none of it helped with the problem.

I am relatively new when it comes to Android programming. I have come so far but at this point I need some help. If someone who used setZOrderMediaOverlay() successfully in this scenario and got it working with onResume() let me know how this needs to be done.

Thanks a lot in advance!

Body:
I have struggled with the same issue for some time, but believe the code below now works. (It continues to work after pausing/ locking regardless of whether the camera is on or off).

Firstly, I haven't got any views etc defined in the layout file - they're created in code. The following is called from the main onCreate() method - Note the setZOrderMediaOverlay() on the augScreen.

I have done nothing special within onPause() or onResume() apart from passing onPause() and onResume() through to the augScreen.

        // 1 - Camera Preview
        camScreen = new CameraPreview(this);
        setContentView(camScreen, new LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

    // 2 - 3D object display
        augScreen = new AR_SurfaceView(this, getViewRange());
        addContentView(augScreen, new LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        augScreen.setZOrderMediaOverlay(true);

    // 3 - Permanent overlay
    RelativeLayout overlayScreen = new OverlayView(this);
    addContentView(overlayScreen, new LayoutParams(
            LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    overlayScreen.setVisibility(View.VISIBLE);

    // 4 - UI buttons (toggleable)
        uiScreen = new UserInterfaceView(this);
        addContentView(uiScreen, new LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));


来源: stackexchange

问:
Count IF Function Equivalent
I have four columns: A Team, B Team, C Team, D Team.

Each row entry can contain either a Yes or No in each of the columns. For example like so:

```<code>A Team    B Team    C Team    D Team
------------------------------------
Yes       Yes       No        No
</code>```

I'm looking to create an additional column NumberofTeams that sums wherever there is a yes. So in this case it would return 2 - indicating that 2 teams are involved.

I was going to attempt it via a CASE function, but believe this would have to cover every single permutation?

```<code>select
    *,
    NumberofTeams = select case
                              when [A Team] = 'Yes' and [B Team] = 'Yes'
                                 then 2
                              when [A Team] = 'Yes' and [C Team] = 'Yes'
                                 then 2
</code>```

and so on.

If there's a 'cleaner' way?

答:
Here is one way to do it:</p>

```<code>select
    t.*,
    case when [A Team] = 'Yes' then 1 else 0 end
        + case when [B Team] = 'Yes' then 1 else 0 end
        + case when [C Team] = 'Yes' then 1 else 0 end
        + case when [D Team] = 'Yes' then 1 else 0 end
        as NumberOfTeams
from mytable t
</code>```

ContentLicense: CC BY-SA 4.0

Title: Count IF Function Equivalent

Body:
I have four columns: A Team, B Team, C Team, D Team.

Each row entry can contain either a Yes or No in each of the columns. For example like so:

A Team    B Team    C Team    D Team
------------------------------------
Yes       Yes       No        No

I'm looking to create an additional column NumberofTeams that sums wherever there is a yes. So in this case it would return 2 - indicating that 2 teams are involved.

I was going to attempt it via a CASE function, but believe this would have to cover every single permutation?

select
    *,
    NumberofTeams = select case
                              when [A Team] = 'Yes' and [B Team] = 'Yes'
                                 then 2
                              when [A Team] = 'Yes' and [C Team] = 'Yes'
                                 then 2

and so on.

If there's a 'cleaner' way?

Body:
Here is one way to do it:

select
    t.*,
    case when [A Team] = 'Yes' then 1 else 0 end
        + case when [B Team] = 'Yes' then 1 else 0 end
        + case when [C Team] = 'Yes' then 1 else 0 end
        + case when [D Team] = 'Yes' then 1 else 0 end
        as NumberOfTeams
from mytable t


问:
Ionic and phonegap barcode scanner app crash on android
My ionic app uses:

```<code>"@ionic-native/barcode-scanner": "^5.19.1",
"phonegap-plugin-barcodescanner": "^8.1.0",
</code>```

Android app crashes right away when i call barcode.scan funcion. I am doing everything like on the very basic example: https://ionicframework.com/docs/native/barcode-scanner

Note: I am testing this on android7 version at the moment. The phone is not very new but still not very old neither.
It crashes right after accepting camera permissions.

There is no err message in catch block or anything, app just crashes.
Has anyone experienced this or can help me investigate more logs ?

答:
I have found the issue, basicly it was missing com.google.zxing.client.android.SCAN from AndroidManifest.xml file:

```<code><activity android:configChanges="orientation|keyboardHidden" android:name="com.google.zxing.client.android.CaptureActivity" android:screenOrientation="landscape" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" android:windowSoftInputMode="stateAlwaysHidden">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
        <intent-filter>
            <action android:name="com.google.zxing.client.android.SCAN" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
</code>```

Not sure why the plugin installation did not added anything nor it was described in github, but It was requiring activity for the manifest file.

Body:
My ionic app uses:

"@ionic-native/barcode-scanner": "^5.19.1",
"phonegap-plugin-barcodescanner": "^8.1.0",

Android app crashes right away when i call barcode.scan funcion. I am doing everything like on the very basic example: https://ionicframework.com/docs/native/barcode-scanner

Note: I am testing this on android7 version at the moment. The phone is not very new but still not very old neither.
It crashes right after accepting camera permissions.

There is no err message in catch block or anything, app just crashes.
Has anyone experienced this or can help me investigate more logs ?

Body:
I have found the issue, basicly it was missing com.google.zxing.client.android.SCAN from AndroidManifest.xml file:

<activity android:configChanges="orientation|keyboardHidden" android:name="com.google.zxing.client.android.CaptureActivity" android:screenOrientation="landscape" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" android:windowSoftInputMode="stateAlwaysHidden">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
        <intent-filter>
            <action android:name="com.google.zxing.client.android.SCAN" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

Not sure why the plugin installation did not added anything nor it was described in github, but It was requiring activity for the manifest file.


问:
SQL Server not null column update with unique constraint
I have an existing table with 2 columns say [Employee_Id , Salary] with a few records in it.

I want to add a new column say Employee_Code which is

1 Not Null

2 Unique

Since the table already has some rows in it and the column is not nullable, I have to add a default value to it.

Since I am adding a unique constraint, adding a default value will not work.

How do I add a not null column to an existing table, having unique constraint?

答:
You can add IDENTITY column to a table if identity is not an issue for you.

ALTER TABLE tablename
ADD columnname INT IDENTITY(1, 1)

Example :

ALTER TABLE Employee
ADD empCode INT NOT NULL IDENTITY(1, 1)

ContentLicense: CC BY-SA 3.0


答:
Found my answer here: How to return count if column values conatains specific string in it

For anyone that's wondering:

```<code>SELECT
    col1, col2, col3, col4,
    (CASE WHEN col1 LIKE '%[_]X%' THEN 1 ELSE 0 END +
     CASE WHEN col2 LIKE '%[_]X%' THEN 1 ELSE 0 END +
     CASE WHEN col3 LIKE '%[_]X%' THEN 1 ELSE 0 END +
     CASE WHEN col4 LIKE '%[_]X%' THEN 1 ELSE 0 END) AS cnt
FROM yourTable
</code>```

Title: Count IF Function Equivalent

Body:
Found my answer here: How to return count if column values conatains specific string in it

For anyone that's wondering:

SELECT
    col1, col2, col3, col4,
    (CASE WHEN col1 LIKE '%[_]X%' THEN 1 ELSE 0 END +
     CASE WHEN col2 LIKE '%[_]X%' THEN 1 ELSE 0 END +
     CASE WHEN col3 LIKE '%[_]X%' THEN 1 ELSE 0 END +
     CASE WHEN col4 LIKE '%[_]X%' THEN 1 ELSE 0 END) AS cnt
FROM yourTable


问:
Is there a way (or workaround) to add tables from Google Sheets to a Google Slides presentation using app script?
I'm new to app script and coding in general.

I've written a script that uses an "on form submit" trigger to create a new folder in my drive, copy three (3) template files and drop them in there:

Two (2) of these are spreadsheets and the other is a Slides presentation.

I have tables in the spreadsheets that I want to embed and have update automatically into the presentation.

It looks like I can only embed charts from a spreadsheet into a presentation. Is this true?

If so, can I call on certain cells in the spreadsheet and get their values; then, place those in a pre-made table on the slides presentation?

Any other workarounds that I may be missing?

My group does this process any where between 8-30 times a day, so any way to automate this part of it would save a lot of time!

Thanks!

答:
A Table from Spreadsheet to Slide

```<code>function putTablesIntoSlides() {
  var pr=SlidesApp.openById('Presentation Id');
  var slide1_ObjectId=pr.getSlides()[1].getObjectId();//I was adding the table to slide[1];
  Logger.log(slide1_ObjectId);
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Sheet10');
  var rg=sh.getDataRange();
  var v=rg.getValues();
  //Create a table the size comes from Spreadsheet Data
  var request1={"createTable": {"elementProperties":{"pageObjectId": slide1_ObjectId},"rows": v.length,"columns": v[0].length}};
  var resp1=Slides.Presentations.batchUpdate({requests:request1}, pr.getId());
  //Setting up the data for adding text to the above table.
  var request2=[];
  for(var i=0;i<v.length;i++) {
    for(var j=0;j<v[i].length;j++) {
      request2.push({"insertText":{"objectId":resp1.replies[0].createTable.objectId,"cellLocation": {"rowIndex":i,"columnIndex":j},"text": v[i][j].toString()}});
    }
  }
  //Add test to all of the table cells
  var resp2=Slides.Presentations.batchUpdate({requests:request2}, pr.getId());
  Logger.log(JSON.stringify(resp1));
}
</code>```

This is my table data:

HDR1
HDR6
HDR2
HDR5
HDR4
HDR7
HDR8
HDR3

5
7
2
6
4
3
1
0

7
4
8
2
3
1
7
8

5
7
5
0
0
9
1
2

2
4
9
9
7
3
7
2

1
0
3
3
5
3
9
7

3
7
8
3
2
4
1
8

5
8
6
3
1
1
8
4

3
1
7
7
1
5
7
5

9
6
3
6
8
6
9
8

5
4
9
6
2
3
3
4

Google Slides API

SlidesApp

Body:
A Table from Spreadsheet to Slide

function putTablesIntoSlides() {
  var pr=SlidesApp.openById('Presentation Id');
  var slide1_ObjectId=pr.getSlides()[1].getObjectId();//I was adding the table to slide[1];
  Logger.log(slide1_ObjectId);
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Sheet10');
  var rg=sh.getDataRange();
  var v=rg.getValues();
  //Create a table the size comes from Spreadsheet Data
  var request1={"createTable": {"elementProperties":{"pageObjectId": slide1_ObjectId},"rows": v.length,"columns": v[0].length}};
  var resp1=Slides.Presentations.batchUpdate({requests:request1}, pr.getId());
  //Setting up the data for adding text to the above table.
  var request2=[];
  for(var i=0;i<v.length;i++) {
    for(var j=0;j<v[i].length;j++) {
      request2.push({"insertText":{"objectId":resp1.replies[0].createTable.objectId,"cellLocation": {"rowIndex":i,"columnIndex":j},"text": v[i][j].toString()}});
    }
  }
  //Add test to all of the table cells
  var resp2=Slides.Presentations.batchUpdate({requests:request2}, pr.getId());
  Logger.log(JSON.stringify(resp1));
}

This is my table data:

HDR1
HDR6
HDR2
HDR5
HDR4
HDR7
HDR8
HDR3

5
7
2
6
4
3
1
0

7
4
8
2
3
1
7
8

5
7
5
0
0
9
1
2

2
4
9
9
7
3
7
2

1
0
3
3
5
3
9
7

3
7
8
3
2
4
1
8

5
8
6
3
1
1
8
4

3
1
7
7
1
5
7
5

9
6
3
6
8
6
9
8

5
4
9
6
2
3
3
4

Google Slides API

SlidesApp


问:
Getting all my public posts using Facebook Graph API
How can i get all my facebook posts using python code and facebook graph api.
i have tried using this code:

```<code>import json
import facebook

def get_basic_info(token):

    graph = facebook.GraphAPI(token)

    profile = graph.get_object('me',fields='first_name,last_name,location,link,email')

    print(json.dumps(profile, indent=5))

def get_all_posts(token):
    graph = facebook.GraphAPI(token)
    events = graph.request('type=event&limit=10000')
    print(events)

def main():

    token = "my_token"
    #get_basic_info(token)
    get_all_posts(token)

if __name__ == '__main__':

    main()
</code>```

I am getting a error that says,
"GraphAPIError: (#33) This object does not exist or does not support this action".

Seems like all the other stackoverflow questions are very old and does not apply for the newest version of facebook graph API. I am not entirely sure whether u can do this using facebook graph api or not.
if this is not possible using this technique, is there any other way i can get my posts using python?
please note that function get_basic_info() is working perfectly.

答:
I assume you want to get user events: https://developers.facebook.com/docs/graph-api/reference/user/events/

Be aware:

This edge is only available to a limited number of approved apps. Unapproved apps querying this edge will receive an empty data set in response. You cannot request access to this edge at this time.

Either way, the API would not be type=event&limit=10000 but /me/events instead.

Body:
How can i get all my facebook posts using python code and facebook graph api.
i have tried using this code:

import json
import facebook

def get_basic_info(token):

    graph = facebook.GraphAPI(token)

    profile = graph.get_object('me',fields='first_name,last_name,location,link,email')

    print(json.dumps(profile, indent=5))

def get_all_posts(token):
    graph = facebook.GraphAPI(token)
    events = graph.request('type=event&limit=10000')
    print(events)

def main():

    token = "my_token"
    #get_basic_info(token)
    get_all_posts(token)

if __name__ == '__main__':

    main()

I am getting a error that says,
"GraphAPIError: (#33) This object does not exist or does not support this action".

Seems like all the other stackoverflow questions are very old and does not apply for the newest version of facebook graph API. I am not entirely sure whether u can do this using facebook graph api or not.
if this is not possible using this technique, is there any other way i can get my posts using python?
please note that function get_basic_info() is working perfectly.


问:
How can I create a function that takes a parameter of unknown type in C?
Say I have the following code:

```<code>struct test* t1;
t1 = get_t(1);
</code>```

... where get_t is:

```<code>struct test* get_t(int);
</code>```

How can I refactor the above code and put it in a function? Something like the following:

```<code>void r1(?* t, ?* (fn*)(int)) {
    t = fn(1);
}

/* ... */

struct test* t1;
r1(t1, &get_t);
</code>```

答: use void *param, a pointer to anything ... commonly used in glib as gpointer

Body:
Say I have the following code:

struct test* t1;
t1 = get_t(1);

... where get_t is:

struct test* get_t(int);

How can I refactor the above code and put it in a function? Something like the following:

void r1(?* t, ?* (fn*)(int)) {
    t = fn(1);
}

/* ... */

struct test* t1;
r1(t1, &get_t);


问:
Make WPF DataGrid create new item only after full-row commit
The code I am working on uses a WPF DataGrid to store a table of entries, bound to an ObservableCollection of items, with the possibility for the user to create new items using the blank row at the bottom of the table.

When the user selects a cell in the new row, right as they type their first keystroke, the DataGrid creates a new blank item and inserts it in the ObservableCollection. Once the user hits Enter or takes focus away from the cell, the new text is committed as an edit to the item.

Is there any way to change the behavior of the DataGrid so that it does not create a blank item before the user is done typing? Or, at least, does not add the blank item to the ObservableCollection until after the row is committed.

I'd like to make it so that new items are only added to the ObservableCollection after a full-row commit has occurred, meaning that each new item added to the Collection will already have data in it, instead of being inserted blank and then edited later.

I've searched high and low for an answer, but it appears that no one else is having this problem.

The reason why I want this functionality is that I am implementing an "Undo" feature in this DataGrid, but when new rows get added as blanks and then edited later, that always ends up counting as two changes, meaning the user needs to perform two "Undo" operations to remove a row they have just barely created. And that's not intuitive at all.

Thanks.

答:
In general it's normal behavior of DataGrid.

DataGrid calls Add() for the new collection item when you start editing the row

DataGrid automatically calls Remove() for the item when you hit Escape key or call CancelEdit() in any other way

There's nothing strange to support (ignore in code) collection items with blank/default values. As alternative you may add some proxy collection and commit its changes to main collection when Datagrid saves the Row data. As for me, first way is preferrable.


问:
Compare string without calling function in assembly?
Say I have two strings, I want to compare the string but don't want to call another function for true or false:

```<code>mov rsi, 0x4141414141414141
mov rdi, 0x6161616161616161
cmp rsi, rdi
// if true do here
// otherwise do here
// jmp back_up_to_cmp rsi, rdi
</code>```

The problem I have is that, I cannot call a function for either true or false. So, is there anyway to achieve my expectation?

Body:
Say I have two strings, I want to compare the string but don't want to call another function for true or false:

mov rsi, 0x4141414141414141
mov rdi, 0x6161616161616161
cmp rsi, rdi
// if true do here
// otherwise do here
// jmp back_up_to_cmp rsi, rdi

The problem I have is that, I cannot call a function for either true or false. So, is there anyway to achieve my expectation?

Body:
As pointed by @fuz, I could use relative jump to achieve what I wanted:

working complete code:

SECTION .text
global main

main:
mov rax, 1
mov rsi, 0x203e7475706e49
push rsi
mov rsi, rsp
mov rdx, 7
syscall

mov rax, 0
mov rdi, 0
mov rsi, rsp
mov rdx, 256
syscall

mov rax, 1
mov rsi, rsp

xor rdx, rdx
cmp byte [rsi + rdx], 0x0a
jz 0xc
inc rdx
jmp -0xe

syscall

mov rax, 60
syscall

I looked at the location in which my cmp was located at, calculated the difference and used the jmp to jump to that location:

0x0000000000001130 <+0>:     mov    $0x1,%eax
0x0000000000001135 <+5>:     movabs $0x203e7475706e49,%rsi
0x000000000000113f <+15>:    push   %rsi
0x0000000000001140 <+16>:    mov    %rsp,%rsi
0x0000000000001143 <+19>:    mov    $0x7,%edx
0x0000000000001148 <+24>:    syscall
0x000000000000114a <+26>:    mov    $0x0,%eax
0x000000000000114f <+31>:    mov    $0x0,%edi
0x0000000000001154 <+36>:    mov    %rsp,%rsi
0x0000000000001157 <+39>:    mov    $0x100,%edx
0x000000000000115c <+44>:    syscall
0x000000000000115e <+46>:    mov    $0x1,%eax
0x0000000000001163 <+51>:    mov    %rsp,%rsi
0x0000000000001166 <+54>:    xor    %rdx,%rdx
0x0000000000001169 <+57>:    cmpb   $0xa,(%rsi,%rdx,1)
0x000000000000116d <+61>:    je     0x117b <main+75>
0x0000000000001173 <+67>:    inc    %rdx
0x0000000000001176 <+70>:    jmpq   0x1169 <main+57>
0x000000000000117b <+75>:    syscall
0x000000000000117d <+77>:    mov    $0x3c,%eax
0x0000000000001182 <+82>:    syscall
0x0000000000001184 <+84>:    nopw   %cs:0x0(%rax,%rax,1)
0x000000000000118e <+94>:    xchg   %ax,%ax

So no more functions :) Thank you @fuz


问:
Can't get $(this) working in jQueryUI autocomplete
I'm trying to create a generic autocomplete script using jQueryUI. The autocomplete should work for every:

```<code><input type='text' class='autocomplete' id='foo'/>
<input type='text' class='autocomplete' id='bar'/>
...
</code>```

Now I'm trying to access 'foo' or 'bar' in the source function using $(this), but when alerting I always get 'undefined'.

```<code>$('input.autocomplete').autocomplete({
    source: function(req, add){
        var id = $(this).attr('id');
        alert(id);
    }
});
</code>```

What am I doing wrong?

答:
Literally this is the answer. not $('this') or $(this) just this

Example:

```<code>$(".peoplepicker").autocomplete({
    source: function (request, response) {
        var url = "/data/myResource";

        var thisControl = this.element; // <<---

        $.ajax({
            url: url,
            type: "GET",
            headers: {
                Accept: "application/json;odata=nometadata"
            },
            async: true,
            cache: false,
            beforeSend: function () {
                thisControl.parent().parent().find(".srchstat").hide();    // <<===
                thisControl.parent().parent().find(".searching").fadeIn(); // <<===
            },
... [snipped]
</code>```

Using thisControl = this.element; you can act on the target control later in the scope of thisControl. Like this:

```<code>thisControl.css("color","red");
</code>```

or

```<code>thisControl.parent().parent().find(".searching").fadeIn();
</code>```

I hope this helps. fwiw: this is how I have it working in my production app.

```<code>/* I am using: */
/*! jQuery v3.3.1
/*! jQuery UI - v1.12.1 - 2020-02-03
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to create a generic autocomplete script using jQueryUI. The autocomplete should work for every:

<input type='text' class='autocomplete' id='foo'/>
<input type='text' class='autocomplete' id='bar'/>
...

Now I'm trying to access 'foo' or 'bar' in the source function using $(this), but when alerting I always get 'undefined'.

$('input.autocomplete').autocomplete({
    source: function(req, add){
        var id = $(this).attr('id');
        alert(id);
    }
});

What am I doing wrong?

Body:
Literally this is the answer. not $('this') or $(this) just this

Example:

$(".peoplepicker").autocomplete({
    source: function (request, response) {
        var url = "/data/myResource";

        var thisControl = this.element; // <<---

        $.ajax({
            url: url,
            type: "GET",
            headers: {
                Accept: "application/json;odata=nometadata"
            },
            async: true,
            cache: false,
            beforeSend: function () {
                thisControl.parent().parent().find(".srchstat").hide();    // <<===
                thisControl.parent().parent().find(".searching").fadeIn(); // <<===
            },
... [snipped]

Using thisControl = this.element; you can act on the target control later in the scope of thisControl. Like this:

thisControl.css("color","red");

or

thisControl.parent().parent().find(".searching").fadeIn();

I hope this helps. fwiw: this is how I have it working in my production app.

/* I am using: */
/*! jQuery v3.3.1
/*! jQuery UI - v1.12.1 - 2020-02-03


问:
Fully Decentralized P2P?
I’m looking at creating a P2P system.  During initial research, I’m reading from Peer-to-Peer – Harnessing the Power of Disruptive Technologies.  That book states “a fully decentralized approach to instant messaging would not work on today's Internet.”  Mostly blaming firewalls and NATs.  The copyright is 2001.  Is this information old or still correct?</p>

答: The session messenger seem to have solved the issue with a truly decentralized p2p messenger by using a incentivized mixnet to relay and store messages. Its a fork of the Signal messenger with a mixnet added in. https://getsession.org -- whitepaper: https://getsession.org/wp-content/uploads/2020/02/Session-Whitepaper.pdf</p>

Title: Fully Decentralized P2P?


问:
WPF Window to edit the user.settings. Why values are not changing?
I'm working on a wpf window to edit the user settings.

This is what I did so far:

<ListView Grid.Row="1"
        ItemsSource="{Binding Source={x:Static properties:Settings.Default}, Path=PropertyValues}"
        HorizontalContentAlignment="Stretch" Background="LightGray"
        ScrollViewer.HorizontalScrollBarVisibility="Disabled">
    <ListView.ItemTemplate>
        <DataTemplate>
            <DockPanel HorizontalAlignment="Stretch"
                    IsEnabled="{Binding DataContext.Enabled, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}">

                <ContentControl VerticalContentAlignment="Center" Content="{Binding Path=PropertyValue}">
                    <ContentControl.Resources>
                        <ResourceDictionary>
                            <DataTemplate DataType="{x:Type sys:Boolean}">
                                <CheckBox IsChecked="{Binding Path=., Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
                            </DataTemplate>
                            <DataTemplate DataType="{x:Type sys:String}">
                                <TextBox Text="{Binding Path=., Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
                            </DataTemplate>
                            <DataTemplate DataType="{x:Type sys:Int32}">
                                <TextBox Text="{Binding Path=., Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
                            </DataTemplate>
                        </ResourceDictionary>
                    </ContentControl.Resources>
                </ContentControl>
            </DockPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
```

The values are showing but they're not updated in Properties.Settings.Default when I change and save them with Properties.Settings.Default.Save();.
Is the two way binding correct?

Thanks

答:
As suggested in the comments and in this answer, I need to encapsulate the System.Configuration.SettingsPropertyValue into a ViewModel that implements INotifyPropertyChanged. Otherwise the binding won't work.

ViewModel:

public class SettingsPropertyValueProxy : INotifyPropertyChanged
{
    public string Name { get; }
    public Type PropertyType => PropertyValue.GetType();
    public object PropertyValue
    {
        get
        {
            return Properties.Settings.Default[Name];
        }
        set
        {
            try
            {
                Properties.Settings.Default[Name] = Convert.ChangeType(value, PropertyType);
                Properties.Settings.Default.Save();
            }
            catch
            { }
        }
    }

    public SettingsPropertyValueProxy(string name)
    {
        Name = name;
        Properties.Settings.Default.PropertyChanged += (sender, e) => _OnPropertyChanged(e.PropertyName);
    }

    private void _OnPropertyChanged(string propertyName)
    {
        if (propertyName == Name) PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(PropertyValue)));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}
```

<p><strong>New Property to bind:</strong></p>

<pre class="lang-cs prettyprint-override"><code>public IEnumerable<SettingsPropertyValueProxy> Values { get; }
    = Properties.Settings.Default.Properties
    .Cast<SettingsProperty>()
    .Select(p => new SettingsPropertyValueProxy(p.Name))
    .OrderBy(p => p.Name)
    .ToArray();
</code>```

Correct View and Correct DataTemplates:

<ListView Grid.Row="1"
        ItemsSource="{Binding Path=Values}"
        HorizontalContentAlignment="Stretch" Background="LightGray"
        ScrollViewer.HorizontalScrollBarVisibility="Disabled">
    <ListView.ItemTemplate>
        <DataTemplate>
            <DockPanel HorizontalAlignment="Stretch"
                    IsEnabled="{Binding DataContext.Enabled, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}">

                <ContentControl VerticalContentAlignment="Center" Content="{Binding Path=PropertyValue}">
                    <ContentControl.Resources>
                        <ResourceDictionary>
                            <DataTemplate DataType="{x:Type sys:Boolean}">
                                <CheckBox IsChecked="{Binding Path=PropertyValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                                            DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DockPanel}}, Path=DataContext}"/>
                            </DataTemplate>
                            <DataTemplate DataType="{x:Type sys:String}">
                                <TextBox Text="{Binding Path=PropertyValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                                            DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DockPanel}}, Path=DataContext}"/>
                            </DataTemplate>
                            <DataTemplate DataType="{x:Type sys:Int32}">
                                <TextBox Text="{Binding Path=PropertyValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                                            DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DockPanel}}, Path=DataContext}"/>
                            </DataTemplate>
                        </ResourceDictionary>
                    </ContentControl.Resources>
                </ContentControl>
            </DockPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
```

Body:
I'm working on a wpf window to edit the user settings.

This is what I did so far:

<ListView Grid.Row="1"
        ItemsSource="{Binding Source={x:Static properties:Settings.Default}, Path=PropertyValues}"
        HorizontalContentAlignment="Stretch" Background="LightGray"
        ScrollViewer.HorizontalScrollBarVisibility="Disabled">
    <ListView.ItemTemplate>
        <DataTemplate>
            <DockPanel HorizontalAlignment="Stretch"
                    IsEnabled="{Binding DataContext.Enabled, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}">

                <ContentControl VerticalContentAlignment="Center" Content="{Binding Path=PropertyValue}">
                    <ContentControl.Resources>
                        <ResourceDictionary>
                            <DataTemplate DataType="{x:Type sys:Boolean}">
                                <CheckBox IsChecked="{Binding Path=., Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
                            </DataTemplate>
                            <DataTemplate DataType="{x:Type sys:String}">
                                <TextBox Text="{Binding Path=., Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
                            </DataTemplate>
                            <DataTemplate DataType="{x:Type sys:Int32}">
                                <TextBox Text="{Binding Path=., Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
                            </DataTemplate>
                        </ResourceDictionary>
                    </ContentControl.Resources>
                </ContentControl>
            </DockPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

The values are showing but they're not updated in Properties.Settings.Default when I change and save them with Properties.Settings.Default.Save();.
Is the two way binding correct?

Thanks

Body:
As suggested in the comments and in this answer, I need to encapsulate the System.Configuration.SettingsPropertyValue into a ViewModel that implements INotifyPropertyChanged. Otherwise the binding won't work.

ViewModel:

public class SettingsPropertyValueProxy : INotifyPropertyChanged
{
    public string Name { get; }
    public Type PropertyType => PropertyValue.GetType();
    public object PropertyValue
    {
        get
        {
            return Properties.Settings.Default[Name];
        }
        set
        {
            try
            {
                Properties.Settings.Default[Name] = Convert.ChangeType(value, PropertyType);
                Properties.Settings.Default.Save();
            }
            catch
            { }
        }
    }

    public SettingsPropertyValueProxy(string name)
    {
        Name = name;
        Properties.Settings.Default.PropertyChanged += (sender, e) => _OnPropertyChanged(e.PropertyName);
    }

    private void _OnPropertyChanged(string propertyName)
    {
        if (propertyName == Name) PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(PropertyValue)));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

New Property to bind:

public IEnumerable<SettingsPropertyValueProxy> Values { get; }
    = Properties.Settings.Default.Properties
    .Cast<SettingsProperty>()
    .Select(p => new SettingsPropertyValueProxy(p.Name))
    .OrderBy(p => p.Name)
    .ToArray();

Correct View and Correct DataTemplates:

<ListView Grid.Row="1"
        ItemsSource="{Binding Path=Values}"
        HorizontalContentAlignment="Stretch" Background="LightGray"
        ScrollViewer.HorizontalScrollBarVisibility="Disabled">
    <ListView.ItemTemplate>
        <DataTemplate>
            <DockPanel HorizontalAlignment="Stretch"
                    IsEnabled="{Binding DataContext.Enabled, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}">

                <Label Width="200" Content="{Binding Path=Name}"/>
                <Label Width="200" Content="{Binding Path=PropertyType}" Foreground="Gray" FontStyle="Italic"/>
                <!--<TextBox Text="{Binding Path=PropertyValue, Mode=TwoWay}"/>-->
                <ContentControl VerticalContentAlignment="Center" Content="{Binding Path=PropertyValue}">
                    <ContentControl.Resources>
                        <ResourceDictionary>
                            <DataTemplate DataType="{x:Type sys:Boolean}">
                                <CheckBox IsChecked="{Binding Path=PropertyValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                                            DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DockPanel}}, Path=DataContext}"/>
                            </DataTemplate>
                            <DataTemplate DataType="{x:Type sys:String}">
                                <TextBox Text="{Binding Path=PropertyValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                                            DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DockPanel}}, Path=DataContext}"/>
                            </DataTemplate>
                            <DataTemplate DataType="{x:Type sys:Int32}">
                                <TextBox Text="{Binding Path=PropertyValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                                            DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DockPanel}}, Path=DataContext}"/>
                            </DataTemplate>
                        </ResourceDictionary>
                    </ContentControl.Resources>
                </ContentControl>
            </DockPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>


问:
Get Specific Columns in HasOne relationship in Laravel Eloquent
Edit: Updated to hasOne in both classes

I have two tables, Store and Address. One Store has one address and one address is associated with only one store.

In my Store model, I have a hasOne relationship.

```<code>public function store_address(): HasOne
{
    return $this->hasOne(Address::class, 'id', 'address_id');
}
</code>```

And in Address model I have a hasOne:

```<code>public function store(): HasOne
{
    return $this->hasOne(Store::class, 'id', 'store_id');
}
</code>```

Now I want to join these two tables using Eloquent with() with select * from store but want specific columns from the address table.

```<code>Store::where('user_id', $user_id)
      ->select(\DB::raw('*')
      ->with(['store_address' => function($query) {
          return $query->select(['distance_to_user as distance']);
      }])
      ->orderBy('distance');
</code>```

However it's not returning the correct distance from the address table. How can I do that?

This is the error message I get:

```<code>Column not found: 1054 Unknown column 'distance' in 'order clause' (SQL: select *, from `store` where `store`.`user_id` = 12 and `store`.`deleted_at` is null order by `distance` asc)
</code>```

答:
I assume the structure of your tables

Addresses:

```<code>id | store_id| body | distance_to_user
----------------------------------------
 1 | 1       |China | 100
</code>```

and for Stores:

```<code>id | name
--------------
 1 | Store_01
</code>```

You should have Models like:

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Address extends Model
{
    //

    public function store()
    {
        return $this->belongsTo('App\Store');
    }
}
</code>```

and

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Store extends Model
{
    //
    public function address()
    {
        return $this->hasOne('App\Address');
    }
}
</code>```

now in your controller:

```<code>        public function index()
        {
            //return Store::with(['address' => function($q){
            //    $q->select('distance_to_user as distance','store_id');
            //    }])->get();

            return Store::leftJoin('addresses', 'addresses.store_id', '=', 'stores.id')

                 ->select('stores.id','stores.name','distance_to_user as distance')

                // OR use ->select('stores.*','addresses.id as address_id','distance_to_user as distance')

                ->orderBy('distance','Desc')

                ->get();
        }
</code>```

Body:
Edit: Updated to hasOne in both classes

I have two tables, Store and Address. One Store has one address and one address is associated with only one store.

In my Store model, I have a hasOne relationship.

public function store_address(): HasOne
{
    return $this->hasOne(Address::class, 'id', 'address_id');
}

And in Address model I have a hasOne:

public function store(): HasOne
{
    return $this->hasOne(Store::class, 'id', 'store_id');
}

Now I want to join these two tables using Eloquent with() with select * from store but want specific columns from the address table.

Store::where('user_id', $user_id)
      ->select(\DB::raw('*')
      ->with(['store_address' => function($query) {
          return $query->select(['distance_to_user as distance']);
      }])
      ->orderBy('distance');

However it's not returning the correct distance from the address table. How can I do that?

This is the error message I get:

Column not found: 1054 Unknown column 'distance' in 'order clause' (SQL: select *, from `store` where `store`.`user_id` = 12 and `store`.`deleted_at` is null order by `distance` asc)

Body:
I assume the structure of your tables

Addresses:

id | store_id| body | distance_to_user
----------------------------------------
 1 | 1       |China | 100

and for Stores:

id | name
--------------
 1 | Store_01

You should have Models like:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Address extends Model
{
    //

    public function store()
    {
        return $this->belongsTo('App\Store');
    }
}

and

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Store extends Model
{
    //
    public function address()
    {
        return $this->hasOne('App\Address');
    }
}

now in your controller:

        public function index()
        {
            //return Store::with(['address' => function($q){
            //    $q->select('distance_to_user as distance','store_id');
            //    }])->get();

            return Store::leftJoin('addresses', 'addresses.store_id', '=', 'stores.id')

                 ->select('stores.id','stores.name','distance_to_user as distance')

                // OR use ->select('stores.*','addresses.id as address_id','distance_to_user as distance')

                ->orderBy('distance','Desc')

                ->get();
        }


问:
generating licenses.licx
I've got a bit of a problem. I'm moving my source repository from one machine to another, and in the process I'm doing some culling of what's stored as I've learned more about creating/managing a repository since I started.

The problem is that we're using dxperience tools from devexpress and it uses the .net license system (licenses.licx). Originally I had this license in the repository, and I'm hearing that this isn't necessarily the best idea. So I haven't included it in the repository. But now, when I checkout the project from the repository on my machine (same machine that I was checking out to before the move), it's looking for the license file and not generating it as (I think) it should be.

答:
This file should be compiled into your deployment assemblies automatically by having licenses.licx included as an embedded resource.  Under the hood, Visual studio uses lc.exe to include this in your assemblies.

http://www.atalasoft.com/kb/Article.aspx?id=10103

OwnerDisplayName: SnOrfus

Title: generating licenses.licx

OwnerDisplayName: Chris Ballance


问:
How do I make a dotted/dashed line in Android?
I'm trying to make a dotted line. I'm using this right now for a solid line:

```<code>LinearLayout divider = new LinearLayout( this );
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, 2 );
divider.setLayoutParams( params );
divider.setBackgroundColor( getResources().getColor( R.color.grey ) );
</code>```

I need something like this, but dotted instead of solid. I'd like to avoid making hundreds of layouts alternating between a transparent layout and solid layout.

答:
I liked the solution from Ruidge, but I needed more control from XML. So I changed it to Kotlin and added attributes.

1) Copy the Kotlin class:

```<code>import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View

class DashedDividerView : View {
constructor(context: Context) : this(context, null, 0)
constructor(context: Context, attributeSet: AttributeSet) : this(context, attributeSet, 0)

companion object {
    const val DIRECTION_VERTICAL = 0
    const val DIRECTION_HORIZONTAL = 1
}

private var dGap = 5.25f
private var dWidth = 5.25f
private var dColor = Color.parseColor("#EE0606")
private var direction = DIRECTION_HORIZONTAL
private val paint = Paint()
private val path = Path()

constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
    context,
    attrs,
    defStyleAttr
) {
    val typedArray = context.obtainStyledAttributes(
        attrs,
        R.styleable.DashedDividerView,
        defStyleAttr,
        R.style.DashedDividerDefault
    )

    dGap = typedArray.getDimension(R.styleable.DashedDividerView_dividerDashGap, dGap)
    dWidth = typedArray.getDimension(R.styleable.DashedDividerView_dividerDashWidth, dWidth)
    dColor = typedArray.getColor(R.styleable.DashedDividerView_dividerDashColor, dColor)
    direction =
        typedArray.getInt(R.styleable.DashedDividerView_dividerDirection, DIRECTION_HORIZONTAL)

    paint.color = dColor
    paint.style = Paint.Style.STROKE
    paint.pathEffect = DashPathEffect(floatArrayOf(dWidth, dGap), 0f)
    paint.strokeWidth = dWidth

    typedArray.recycle()
}

override fun onDraw(canvas: Canvas) {
    super.onDraw(canvas)
    path.moveTo(0f, 0f)

    if (direction == DIRECTION_HORIZONTAL) {
        path.lineTo(measuredWidth.toFloat(), 0f)
    } else {
        path.lineTo(0f, measuredHeight.toFloat())
    }
    canvas.drawPath(path, paint)
}

}
</code>```

2) Create an attr file in the /res directory and add this

```<code> <declare-styleable name="DashedDividerView">
    <attr name="dividerDashGap" format="dimension" />
    <attr name="dividerDashWidth" format="dimension" />
    <attr name="dividerDashColor" format="reference|color" />
    <attr name="dividerDirection" format="enum">
        <enum name="vertical" value="0" />
        <enum name="horizontal" value="1" />
    </attr>
</declare-styleable>
</code>```

3) Add a style to the styles file

```<code> <style name="DashedDividerDefault">
    <item name="dividerDashGap">2dp</item>
    <item name="dividerDashWidth">2dp</item>
    <!-- or any color -->
    <item name="dividerDashColor">#EE0606</item>
    <item name="dividerDirection">horizontal</item>
</style>
</code>```

4) Now you can use the default style

```<code><!-- here will be your path to the class -->
<com.your.package.app.DashedDividerView
    android:layout_width="match_parent"
    android:layout_height="2dp"
    />
</code>```

or set attributes in XML

```<code><com.your.package.app.DashedDividerView
    android:layout_width="match_parent"
    android:layout_height="2dp"
    app:dividerDirection="horizontal"
    app:dividerDashGap="2dp"
    app:dividerDashWidth="2dp"
    app:dividerDashColor="@color/light_gray"/>
</code>```

Body:
I'm trying to make a dotted line. I'm using this right now for a solid line:

LinearLayout divider = new LinearLayout( this );
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, 2 );
divider.setLayoutParams( params );
divider.setBackgroundColor( getResources().getColor( R.color.grey ) );

I need something like this, but dotted instead of solid. I'd like to avoid making hundreds of layouts alternating between a transparent layout and solid layout.

Body:
I liked the solution from Ruidge, but I needed more control from XML. So I changed it to Kotlin and added attributes.

1) Copy the Kotlin class:

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View

class DashedDividerView : View {
constructor(context: Context) : this(context, null, 0)
constructor(context: Context, attributeSet: AttributeSet) : this(context, attributeSet, 0)

companion object {
    const val DIRECTION_VERTICAL = 0
    const val DIRECTION_HORIZONTAL = 1
}

private var dGap = 5.25f
private var dWidth = 5.25f
private var dColor = Color.parseColor("#EE0606")
private var direction = DIRECTION_HORIZONTAL
private val paint = Paint()
private val path = Path()

constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
    context,
    attrs,
    defStyleAttr
) {
    val typedArray = context.obtainStyledAttributes(
        attrs,
        R.styleable.DashedDividerView,
        defStyleAttr,
        R.style.DashedDividerDefault
    )

    dGap = typedArray.getDimension(R.styleable.DashedDividerView_dividerDashGap, dGap)
    dWidth = typedArray.getDimension(R.styleable.DashedDividerView_dividerDashWidth, dWidth)
    dColor = typedArray.getColor(R.styleable.DashedDividerView_dividerDashColor, dColor)
    direction =
        typedArray.getInt(R.styleable.DashedDividerView_dividerDirection, DIRECTION_HORIZONTAL)

    paint.color = dColor
    paint.style = Paint.Style.STROKE
    paint.pathEffect = DashPathEffect(floatArrayOf(dWidth, dGap), 0f)
    paint.strokeWidth = dWidth

    typedArray.recycle()
}

override fun onDraw(canvas: Canvas) {
    super.onDraw(canvas)
    path.moveTo(0f, 0f)

    if (direction == DIRECTION_HORIZONTAL) {
        path.lineTo(measuredWidth.toFloat(), 0f)
    } else {
        path.lineTo(0f, measuredHeight.toFloat())
    }
    canvas.drawPath(path, paint)
}

}

2) Create an attr file in the /res directory and add this

 <declare-styleable name="DashedDividerView">
    <attr name="dividerDashGap" format="dimension" />
    <attr name="dividerDashWidth" format="dimension" />
    <attr name="dividerDashColor" format="reference|color" />
    <attr name="dividerDirection" format="enum">
        <enum name="vertical" value="0" />
        <enum name="horizontal" value="1" />
    </attr>
</declare-styleable>

3) Add a style to the styles file

 <style name="DashedDividerDefault">
    <item name="dividerDashGap">2dp</item>
    <item name="dividerDashWidth">2dp</item>
    <!-- or any color -->
    <item name="dividerDashColor">#EE0606</item>
    <item name="dividerDirection">horizontal</item>
</style>

4) Now you can use the default style

<!-- here will be your path to the class -->
<com.your.package.app.DashedDividerView
    android:layout_width="match_parent"
    android:layout_height="2dp"
    />

or set attributes in XML

<com.your.package.app.DashedDividerView
    android:layout_width="match_parent"
    android:layout_height="2dp"
    app:dividerDirection="horizontal"
    app:dividerDashGap="2dp"
    app:dividerDashWidth="2dp"
    app:dividerDashColor="@color/light_gray"/>


问:
Loop function through dataframe, differentiate, and then combine per column in original dataframe
I'm trying to use the package ballr to collect some datafrom basketballreference. I'm trying to use the NBASeasonTeamByYear function to collect the season results of teams across multiple seasons. That is I want every team's data for the years 2017 to 2020, before combining the dataframes into 2 larger ones seperated by conference.

I first made a dataframe with each team's code and conference

```<code>league_teams <- data.frame("team" = c("ATL", "BOS", "NJN", "CHA", "CHI", "CLE", "DAL", "DEN",
                                  "DET", "GSW", "HOU", "IND", "LAC", "LAL", "MEM", "MIA",
                                  "MIL", "MIN", "NOH", "NYK", "OKC", "ORL", "PHI", "PHO",
                                  "POR", "SAC", "SAS", "TOR", "UTA", "WAS"),
                       "conference" = c("East", "East", "East", "East", "East", "East", "West",
                                        "West", "East", "West", "West", "East", "West", "West",
                                        "West", "East", "East", "West", "West", "East", "West",
                                        "East", "East", "West", "West", "West", "West", "East",
                                        "West", "East"))
league_teams$team <- as.character(league_teams$team)
league_teams$conference <- as.factor(league_teams$conference)
</code>```

Now I'm having trouble writing the loop that first uses the function for each unique team using their code and the years I want before combining them irregardless of year but within each conference.

I started with this

```<code>   for (team in league_teams) {

  team_2017 <- NBASeasonTeamByYear(team = team, 2017)
  team_2017$season <- as.factor(2017)
  team_2017$team <- as.factor(team)

}
</code>```

The latter lines illustrating that I want to add 2 columns one for the respective year and one for the respective team code, but not only for 2017 but all the way through 2020. Though I'm having trouble writing the loop and think I use rbind to combine them later on but I'm unsure how to do so and discriminate by conference in the original dataframe I made.

答:
Consider generalizing your process in a user-defined method and pass params with expand.grid (all combinations) and Map (elementwise loop):

```<code>nba_df_build <- function(yr, team, conf) {
  # base::TRANSFORM OR dplyr::MUTATE
  transform(NBASeasonTeamByYear(team = team, season = yr),
            season = as.factor(yr),
            team = as.factor(team),
            conference = as.factor(conf))
}

params_df <- expand.grid(year = 2017:2020,
                         team = league_teams$team,
                         conference = league_teams$conference)

df_list <- Map(nba_df_build, params_df$year, params_df$team, params_df$conference)

final_df <- do.call(rbind, df_list)
#final_df <- dplyr::bind_rows(df_list)
</code>```

And for any splitting of data frames:

```<code># LIST OF TWO CONFERENCE DATA FRAMES
conference_dfs <- split(final_df, final_df$conference)

# LIST OF FOUR SEASON DATA FRAMES
season_dfs <- split(final_df, final_df$season)

# LIST OF THIRTY TEAM DATA FRAMES
team_dfs <- split(final_df, final_df$team)
</code>```

Body:
I'm trying to use the package ballr to collect some datafrom basketballreference. I'm trying to use the NBASeasonTeamByYear function to collect the season results of teams across multiple seasons. That is I want every team's data for the years 2017 to 2020, before combining the dataframes into 2 larger ones seperated by conference.

I first made a dataframe with each team's code and conference

league_teams <- data.frame("team" = c("ATL", "BOS", "NJN", "CHA", "CHI", "CLE", "DAL", "DEN",
                                  "DET", "GSW", "HOU", "IND", "LAC", "LAL", "MEM", "MIA",
                                  "MIL", "MIN", "NOH", "NYK", "OKC", "ORL", "PHI", "PHO",
                                  "POR", "SAC", "SAS", "TOR", "UTA", "WAS"),
                       "conference" = c("East", "East", "East", "East", "East", "East", "West",
                                        "West", "East", "West", "West", "East", "West", "West",
                                        "West", "East", "East", "West", "West", "East", "West",
                                        "East", "East", "West", "West", "West", "West", "East",
                                        "West", "East"))
league_teams$team <- as.character(league_teams$team)
league_teams$conference <- as.factor(league_teams$conference)

Now I'm having trouble writing the loop that first uses the function for each unique team using their code and the years I want before combining them irregardless of year but within each conference.

I started with this

   for (team in league_teams) {

  team_2017 <- NBASeasonTeamByYear(team = team, 2017)
  team_2017$season <- as.factor(2017)
  team_2017$team <- as.factor(team)

}

The latter lines illustrating that I want to add 2 columns one for the respective year and one for the respective team code, but not only for 2017 but all the way through 2020. Though I'm having trouble writing the loop and think I use rbind to combine them later on but I'm unsure how to do so and discriminate by conference in the original dataframe I made.

Body:
Consider generalizing your process in a user-defined method and pass params with expand.grid (all combinations) and Map (elementwise loop):

nba_df_build <- function(yr, team, conf) {
  # base::TRANSFORM OR dplyr::MUTATE
  transform(NBASeasonTeamByYear(team = team, season = yr),
            season = as.factor(yr),
            team = as.factor(team),
            conference = as.factor(conf))
}

params_df <- expand.grid(year = 2017:2020,
                         team = league_teams$team,
                         conference = league_teams$conference)

df_list <- Map(nba_df_build, params_df$year, params_df$team, params_df$conference)

final_df <- do.call(rbind, df_list)
#final_df <- dplyr::bind_rows(df_list)

And for any splitting of data frames:

# LIST OF TWO CONFERENCE DATA FRAMES
conference_dfs <- split(final_df, final_df$conference)

# LIST OF FOUR SEASON DATA FRAMES
season_dfs <- split(final_df, final_df$season)

# LIST OF THIRTY TEAM DATA FRAMES
team_dfs <- split(final_df, final_df$team)


问:
Reactjs Router is causing Array to become undefined
So I am trying to fetch JSON data from server running on another port in my pc using axios and renders it on homepage. I want to setup Router to components. But whenever I wrap Router around my components It causes Array recipeslists to become undefined (see below console output) and hence I can not map that Array in my Allrecipes Component But without any Router it works fine.

App.js's code is as follows

import React, { useState , useEffect} from 'react'
import { BrowserRouter as Router, Route } from "react-router-dom"
import "bootstrap/dist/css/bootstrap.min.css"

import Navbar from './components/Navbar'
import Allrecipes from './components/Allrecipes'
import Createrecipe from './components/Createrecipe'
import axios from 'axios'

const App = () => {
    const [recipeslists,setRecipes] = useState([])
    const [filterRecipe,setFilterRecipe] = useState([])
    const [search,setSearch] = useState('')
    console.log("in app")

    useEffect(()=>{
        console.log("useEffect")
        axios.get('http://localhost:3001/api/recipes')
        .then(response => {
            console.log(response.data)
            return response.data
        })
        .then( recipeslist => {
            console.log(recipeslist,"recipes")
            setRecipes(recipeslist)
            setFilterRecipe(recipeslist)
        })
        .catch((err) => console.log(err))
    },[])

    function handlechange(event){
        var query = event.target.value.toLowerCase()
        setSearch(query)

        var filter_recipes = filterRecipe.filter((recipe) =>
            recipe.dish_name.toLowerCase().includes(query)
        )

        setRecipes(filter_recipes)
    }

    return (
        <Router>

                <Navbar handlechange={handlechange}  search={search}/>
                <Allrecipes recipeslists={recipeslists} />

            <Route path="/" exact component={Allrecipes} />
            <Route path="/recipes/create" exact component={Createrecipe} />
        </Router>
    )

}
export default App

```

<p><code>Allrecipes.js</code> code is as follow</p>

<pre class="lang-js prettyprint-override"><code>import React from "react"
import Recipe from './Recipe'

const Allrecipes = (props) => {
    const {recipeslists} = props
    console.log(recipeslists,"*** recipes array in Allrecipes***")

    return (
        <div className="recipecontainer">
               {recipeslists.map( recipeitem => <Recipe key={recipeitem.id} recipeitem={recipeitem} />)}
        </div>
    )
}

export default Allrecipes
</code>```

Output of above code in console:

Output in console without using Router:

Explain me,

why Router is causing Array to become undefined? or it is another bug I am unknown of?

If this is wrong implementation or method of using Router in Reactjs , then what is the correct way to do it?

Thank You. I would appreciate your any help!

答:
Instead of using the component prop, pass the component as a child:

<Route path="/" exact>
  <Allrecipes recipeslists={recipeslists} />
</Route>
```

<p>That is the recommended way of rendering components in the route.</p>

<p>However, you could also use <code>render</code> if you'd like:</p>

<pre class="lang-js prettyprint-override"><code><Route path="/" exact render={(routeProps) => {
  <Allrecipes recipeslists={recipeslists} {...routeProps} />
}} />
</code>```

You just can't use the component prop because with that you're only passing a component reference (Allrecipes), not an instance (<Allrecipes />) of the component to which you can pass props.

Body:
So I am trying to fetch JSON data from server running on another port in my pc using axios and renders it on homepage. I want to setup Router to components. But whenever I wrap Router around my components It causes Array recipeslists to become undefined (see below console output) and hence I can not map that Array in my Allrecipes Component But without any Router it works fine.

App.js's code is as follows

import React, { useState , useEffect} from 'react'
import { BrowserRouter as Router, Route } from "react-router-dom"
import "bootstrap/dist/css/bootstrap.min.css"

import Navbar from './components/Navbar'
import Allrecipes from './components/Allrecipes'
import Createrecipe from './components/Createrecipe'
import axios from 'axios'

const App = () => {
    const [recipeslists,setRecipes] = useState([])
    const [filterRecipe,setFilterRecipe] = useState([])
    const [search,setSearch] = useState('')
    console.log("in app")

    useEffect(()=>{
        console.log("useEffect")
        axios.get('http://localhost:3001/api/recipes')
        .then(response => {
            console.log(response.data)
            return response.data
        })
        .then( recipeslist => {
            console.log(recipeslist,"recipes")
            setRecipes(recipeslist)
            setFilterRecipe(recipeslist)
        })
        .catch((err) => console.log(err))
    },[])

    function handlechange(event){
        var query = event.target.value.toLowerCase()
        setSearch(query)

        var filter_recipes = filterRecipe.filter((recipe) =>
            recipe.dish_name.toLowerCase().includes(query)
        )

        setRecipes(filter_recipes)
    }

    return (
        <Router>

                <Navbar handlechange={handlechange}  search={search}/>
                <Allrecipes recipeslists={recipeslists} />

            <Route path="/" exact component={Allrecipes} />
            <Route path="/recipes/create" exact component={Createrecipe} />
        </Router>
    )

}
export default App

Allrecipes.js code is as follow

import React from "react"
import Recipe from './Recipe'

const Allrecipes = (props) => {
    const {recipeslists} = props
    console.log(recipeslists,"*** recipes array in Allrecipes***")

    return (

               {recipeslists.map( recipeitem => <Recipe key={recipeitem.id} recipeitem={recipeitem} />)}

    )
}

export default Allrecipes

Output of above code in console:

Output in console without using Router:

Explain me,

why Router is causing Array to become undefined? or it is another bug I am unknown of?

If this is wrong implementation or method of using Router in Reactjs , then what is the correct way to do it?

Thank You. I would appreciate your any help!

Body:
Instead of using the component prop, pass the component as a child:

<Route path="/" exact>
  <Allrecipes recipeslists={recipeslists} />
</Route>

That is the recommended way of rendering components in the route.

However, you could also use render if you'd like:

<Route path="/" exact render={(routeProps) => {
  <Allrecipes recipeslists={recipeslists} {...routeProps} />
}} />

You just can't use the component prop because with that you're only passing a component reference (Allrecipes), not an instance (<Allrecipes />) of the component to which you can pass props.


问:
How to scrape url's from a website with python beautiful-soup?
I was trying to scrape some url's from a particular link, I used beautiful-soup for scraping those links, but I'm not able to scrape those links. Here I'm attaching the code which I have used. Actually, I want to scrape the urls from the class "fxs_aheadline_tiny"

```<code>import requests
from bs4 import BeautifulSoup

url = 'https://www.fxstreet.com/news?q=&hPP=17&idx=FxsIndexPro&p=0&dFR%5BTags%5D%5B0%5D=EURUSD'
r1 = requests.get(url)
coverpage = r1.content
soup1 = BeautifulSoup(coverpage, 'html.parser')
coverpage_news = soup1.find_all('h4', class_='fxs_aheadline_tiny')
print(coverpage_news)
</code>```

Thank you

答:
I would use Selenium.
Please, try this code:

```<code>from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options

#open driver
driver= webdriver.Chrome(ChromeDriverManager().install())
driver.get('https://www.fxstreet.com/news?q=&hPP=17&idx=FxsIndexPro&p=0&dFR%5BTags%5D%5B0%5D=EURUSD')

# Use ChroPath to identify the xpath for the 'page hits'
pagehits=driver.find_element_by_xpath("//div[@class='ais-hits']")

# search for all a tags
links=pagehits.find_elements_by_tag_name("a")

# For each link get the href
for link in links:
    print(link.get_attribute('href'))
</code>```

It exactly does what you want: it takes out all urls/links on your search page (that means also the links to the authors pages).

You could even consider automating the browser and moving through the search page results. See for this the Selenium documentation:https://selenium-python.readthedocs.io/

Hope this helps

Body:
I was trying to scrape some url's from a particular link, I used beautiful-soup for scraping those links, but I'm not able to scrape those links. Here I'm attaching the code which I have used. Actually, I want to scrape the urls from the class "fxs_aheadline_tiny"

import requests
from bs4 import BeautifulSoup

url = 'https://www.fxstreet.com/news?q=&hPP=17&idx=FxsIndexPro&p=0&dFR%5BTags%5D%5B0%5D=EURUSD'
r1 = requests.get(url)
coverpage = r1.content
soup1 = BeautifulSoup(coverpage, 'html.parser')
coverpage_news = soup1.find_all('h4', class_='fxs_aheadline_tiny')
print(coverpage_news)

Thank you

Body:
I would use Selenium.
Please, try this code:

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options

#open driver
driver= webdriver.Chrome(ChromeDriverManager().install())
driver.get('https://www.fxstreet.com/news?q=&hPP=17&idx=FxsIndexPro&p=0&dFR%5BTags%5D%5B0%5D=EURUSD')

# Use ChroPath to identify the xpath for the 'page hits'
pagehits=driver.find_element_by_xpath("//div[@class='ais-hits']")

# search for all a tags
links=pagehits.find_elements_by_tag_name("a")

# For each link get the href
for link in links:
    print(link.get_attribute('href'))

It exactly does what you want: it takes out all urls/links on your search page (that means also the links to the authors pages).

You could even consider automating the browser and moving through the search page results. See for this the Selenium documentation:https://selenium-python.readthedocs.io/

Hope this helps


问:
Resize background image in div using css
Below css sets an individual background on two divs; the images repeat themselves if they do not fit into the div size.

How can I stretch the images using css to fit into space required by div ?

```<code><style type="text/css">
#contentMain {
  margin-bottom: 5%;
  margin-top: 10%;
  margin-left: 10%;
  margin-right: 10%;
  background: url( /jQuery/mypage/img/background1.png )
}
#page1 {
  background: url( /jQuery/mypage/img/background2.png )
}
</style>
</code>```

答:
i would recommend using this:

```<code>  background-repeat:no-repeat;
  background-image: url(your file location here);
  background-size:cover;(will only work with css3)
</code>```

hope it helps :D

And if this doesnt support your needs just say it:
i can make a jquery for multibrowser support.

Body:
i would recommend using this:

  background-repeat:no-repeat;
  background-image: url(your file location here);
  background-size:cover;(will only work with css3)

hope it helps :D

And if this doesnt support your needs just say it:
i can make a jquery for multibrowser support.


问:
How to patch Dto to Entity?
I have a controller that accepts a dto object. I need to change the fields that are present in the dto object.

```<code>@PatchMapping(value = "/update/{uuid}")
    public ResponseEntity<UserDto> update(
            @RequestBody UserDto userDto,
            @PathVariable("uuid")UUID uuid) throws UserNotFoundException {
        User updatedUser = userService.update(
                userMapper.userDtoToUser(userDto),
                uuid
        );
        return .....
    }
</code>```

But a userService can only accept entities. I need to use mapper dto -> entity. But the entity cannot have empty fields that come in dto (Let's say that you need to change only one field). What to do in this situation? I know that the controller should not contain logic

答:
As you say the controller should not contain logic, so for this Spring has an interface, the interface is Validator

There are pros and cons for considering validation as business logic, and Spring offers a design for validation (and data binding) that does not exclude either one of them. Specifically validation should not be tied to the web tier, should be easy to localize and it should be possible to plug in any validator available. Considering the above, Spring has come up with a Validator interface that is both basic ands eminently usable in every layer of an application.

This is what you need to do:

Spring features a Validator interface that you can use to validate objects. The Validator interface works using an Errors object so that while validating, validators can report validation failures to the Errors object.

we have a DTO to which we will validate the fields:

```<code>public class Person {
    private String name;
    private int age;

    // the usual getters and setters...
}
</code>```

To do validations we must implement Validator interface:

```<code>    public class PersonValidator implements Validator {

    /**
     * This Validator validates *just* Person instances
     */
    public boolean supports(Class clazz) {
        return Person.class.equals(clazz);
    }

    public void validate(Object obj, Errors e) {
        if (supports(obj.getClass())) {
            ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
            Person p = (Person) obj;
            if (p.getAge() < 0) {
                e.rejectValue("age", "negativevalue");
            } else if (p.getAge() > 110) {
                e.rejectValue("age", "too.darn.old");
            }
        }
    }
}
</code>```

If the DTO passes all validations you can map the DTO to an Entity object

You can find more information here Spring Validator

Title: How to patch Dto to Entity?

Body:
I have a controller that accepts a dto object. I need to change the fields that are present in the dto object.

@PatchMapping(value = "/update/{uuid}")
    public ResponseEntity<UserDto> update(
            @RequestBody UserDto userDto,
            @PathVariable("uuid")UUID uuid) throws UserNotFoundException {
        User updatedUser = userService.update(
                userMapper.userDtoToUser(userDto),
                uuid
        );
        return .....
    }

But a userService can only accept entities. I need to use mapper dto -> entity. But the entity cannot have empty fields that come in dto (Let's say that you need to change only one field). What to do in this situation? I know that the controller should not contain logic

Body:
As you say the controller should not contain logic, so for this Spring has an interface, the interface is Validator

There are pros and cons for considering validation as business logic, and Spring offers a design for validation (and data binding) that does not exclude either one of them. Specifically validation should not be tied to the web tier, should be easy to localize and it should be possible to plug in any validator available. Considering the above, Spring has come up with a Validator interface that is both basic ands eminently usable in every layer of an application.

This is what you need to do:

Spring features a Validator interface that you can use to validate objects. The Validator interface works using an Errors object so that while validating, validators can report validation failures to the Errors object.

we have a DTO to which we will validate the fields:

public class Person {
    private String name;
    private int age;

    // the usual getters and setters...
}

To do validations we must implement Validator interface:

    public class PersonValidator implements Validator {

    /**
     * This Validator validates *just* Person instances
     */
    public boolean supports(Class clazz) {
        return Person.class.equals(clazz);
    }

    public void validate(Object obj, Errors e) {
        if (supports(obj.getClass())) {
            ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
            Person p = (Person) obj;
            if (p.getAge() < 0) {
                e.rejectValue("age", "negativevalue");
            } else if (p.getAge() > 110) {
                e.rejectValue("age", "too.darn.old");
            }
        }
    }
}

If the DTO passes all validations you can map the DTO to an Entity object

You can find more information here Spring Validator


问:
Why does this fail using HashMap In Java?
```<code>import java.util.HashMap;

public class Main {
    public static void main(String[] args) {

        //Use inputs from https://pastebin.com/DMQ6xqKe and assign to s * t, as stackoverflow limited character use
        String s = "";
        String t = "";

        System.out.println(isAnagram(s, t));
    }

    public static boolean isAnagram(String s, String t) {
        HashMap<Character, Integer> sMap = new HashMap<>();
        HashMap<Character, Integer> tMap = new HashMap<>();

        if(s.length() != t.length())
        {
            return false;
        }

        for(int i = 0; i < s.length(); i++)
        {
            if(sMap.containsKey(s.charAt(i)))
            {
                sMap.replace(s.charAt(i), sMap.get(s.charAt(i)) + 1);
            }
            else
            {
                sMap.put(s.charAt(i), 1);
            }
        }

        for(int i = 0; i < t.length(); i++)
        {
            if(tMap.containsKey(t.charAt(i)))
            {
                tMap.replace(t.charAt(i), tMap.get(t.charAt(i)) + 1);
            }
            else
            {
                tMap.put(t.charAt(i), 1);
            }
        }

        //FAILS BUT WHY!?!??!?
        for(int i = 0; i < s.length(); i++)
        {
            System.out.println("outside " + sMap.get(s.charAt(i)) + " compared to " + tMap.get(s.charAt(i)));
            if(sMap.get(s.charAt(i)) != tMap.get(s.charAt(i)))
            {
                System.out.println(sMap.get(s.charAt(i)) + " compared to " + tMap.get(s.charAt(i)));
                return false;
            }
        }

        //PASSES BUT PREVIOUS FAILS?!!?!??!
        // if(!sMap.equals(tMap))
        // {
        //     return false;
        // }

        return true;
    }
}
</code>```

This code fails but the commented code using .equals works. I don't really understand. Logged the values, they matched but the check fails saying different values.

答:
The == operator compares two object references. The equals method of type Object does the same, but some classes override that method with new functionality. For example, "x" == "x" has the potential to fail, if they are different objects. "x".equals("x") would be true.

```<code>String x = "@";
String y = x;
x == y; // true, its the same reference.
</code>```

Hope this helped?

Body:
import java.util.HashMap;

public class Main {
    public static void main(String[] args) {

        //Use inputs from https://pastebin.com/DMQ6xqKe and assign to s * t, as stackoverflow limited character use
        String s = "";
        String t = "";

        System.out.println(isAnagram(s, t));
    }

    public static boolean isAnagram(String s, String t) {
        HashMap<Character, Integer> sMap = new HashMap<>();
        HashMap<Character, Integer> tMap = new HashMap<>();

        if(s.length() != t.length())
        {
            return false;
        }

        for(int i = 0; i < s.length(); i++)
        {
            if(sMap.containsKey(s.charAt(i)))
            {
                sMap.replace(s.charAt(i), sMap.get(s.charAt(i)) + 1);
            }
            else
            {
                sMap.put(s.charAt(i), 1);
            }
        }

        for(int i = 0; i < t.length(); i++)
        {
            if(tMap.containsKey(t.charAt(i)))
            {
                tMap.replace(t.charAt(i), tMap.get(t.charAt(i)) + 1);
            }
            else
            {
                tMap.put(t.charAt(i), 1);
            }
        }

        //FAILS BUT WHY!?!??!?
        for(int i = 0; i < s.length(); i++)
        {
            System.out.println("outside " + sMap.get(s.charAt(i)) + " compared to " + tMap.get(s.charAt(i)));
            if(sMap.get(s.charAt(i)) != tMap.get(s.charAt(i)))
            {
                System.out.println(sMap.get(s.charAt(i)) + " compared to " + tMap.get(s.charAt(i)));
                return false;
            }
        }

        //PASSES BUT PREVIOUS FAILS?!!?!??!
        // if(!sMap.equals(tMap))
        // {
        //     return false;
        // }

        return true;
    }
}

This code fails but the commented code using .equals works. I don't really understand. Logged the values, they matched but the check fails saying different values.

Body:
The == operator compares two object references. The equals method of type Object does the same, but some classes override that method with new functionality. For example, "x" == "x" has the potential to fail, if they are different objects. "x".equals("x") would be true.

String x = "@";
String y = x;
x == y; // true, its the same reference.

Hope this helped?


问:
R package fails devtools::check, because "could not find function" even though the function is imported in NAMESPACE
Trying to build my first R package using roxygen2 and devtools. I have added a function that uses %>% and mutate in the @examples section. When I run check() it fails, because it cannot find the function %>% or mutate.

Based on this, this, and this I have tried the following:

I have #' importFrom magrittr %>% and #' importFrom dplyr mutate in the function's .R file. I also have magrittr and dplyr under Imports: in the DESCRIPTION file. After running document(), my NAMESPACE file contains importFrom(dplyr,mutate) and importFrom(magrittr,"%>%").

minimal R/test.R file:

```<code>#' Conditional mutate
#'
#' \code{mutate_cond} mutates the \code{data.frame} only on the rows that
#' satisfy the condition.
#'
#' @param .data \code{data.frame}
#' @param condition expression with the condition to be evaluated
#' @param ... arguments passed to \code{mutate}
#' @param envir environment inherited from \code{parent.frame()}
#'
#' @return \code{data.frame}
#' @importFrom dplyr mutate
#' @importFrom magrittr %>%
#'
#' @examples
#' data(iris)
#' iris %>%
#'    mutate(aux = 0) %>%
#'    mutate_cond(Petal.Length > 1.3,aux = 3)
#'
#' @export
mutate_cond <- function(.data, condition, ..., envir = parent.frame()) {
  condition <- eval(substitute(condition), .data, envir)
  .data[condition, ] <- .data[condition, ] %>% mutate(...)
  .data
}
</code>```

minimal DESCRIPTION file:

```<code>Package: test
Version: 0.1
Date: 2019-06-07
Title: Functions
Description: Some functions I use.
Author: me
Maintainer: me <myemail@email.com>
Encoding: UTF-8
License: GPL-3
Imports: dplyr, magrittr
</code>```

NAMESPACE generated with document():

```<code># Generated by roxygen2: do not edit by hand

export(mutate_cond)
importFrom(dplyr,mutate)
importFrom(magrittr,"%>%")
</code>```

I expect this example code to run successfully and pass check(). Instead I get this error message:

```<code>❯ checking examples ... ERROR
  Running examples in ‘test-Ex.R’ failed
  The error most likely occurred in:

  > base::assign(".ptime", proc.time(), pos = "CheckExEnv")
  > ### Name: mutate_cond
  > ### Title: Conditional mutate
  > ### Aliases: mutate_cond
  >
  > ### ** Examples
  >
  > data(iris)
  > iris %>%
  +    mutate(aux = 0) %>%
  +    mutate_cond(Petal.Length > 1.3,aux = 3)
  Error in iris %>% mutate(aux = 0) %>% mutate_cond(Petal.Length > 1.3,  :
    could not find function "%>%"
  Execution halted

1 error ✖ | 0 warnings ✔ | 0 notes ✔

</code>```

Also, if I add require(dplyr) and require(magrittr) to the @examples section the error goes away or if I remove the whole @examples section the error goes away.

Why won't this package pass check()?

Thank you!

答: Running usethis::use_pipe() in the console will do the trick as well.

Body:
Trying to build my first R package using roxygen2 and devtools. I have added a function that uses %>% and mutate in the @examples section. When I run check() it fails, because it cannot find the function %>% or mutate.

Based on this, this, and this I have tried the following:

I have #' importFrom magrittr %>% and #' importFrom dplyr mutate in the function's .R file. I also have magrittr and dplyr under Imports: in the DESCRIPTION file. After running document(), my NAMESPACE file contains importFrom(dplyr,mutate) and importFrom(magrittr,"%>%").

minimal R/test.R file:

#' Conditional mutate
#'
#' \code{mutate_cond} mutates the \code{data.frame} only on the rows that
#' satisfy the condition.
#'
#' @param .data \code{data.frame}
#' @param condition expression with the condition to be evaluated
#' @param ... arguments passed to \code{mutate}
#' @param envir environment inherited from \code{parent.frame()}
#'
#' @return \code{data.frame}
#' @importFrom dplyr mutate
#' @importFrom magrittr %>%
#'
#' @examples
#' data(iris)
#' iris %>%
#'    mutate(aux = 0) %>%
#'    mutate_cond(Petal.Length > 1.3,aux = 3)
#'
#' @export
mutate_cond <- function(.data, condition, ..., envir = parent.frame()) {
  condition <- eval(substitute(condition), .data, envir)
  .data[condition, ] <- .data[condition, ] %>% mutate(...)
  .data
}

minimal DESCRIPTION file:

Package: test
Version: 0.1
Date: 2019-06-07
Title: Functions
Description: Some functions I use.
Author: me
Maintainer: me <myemail@email.com>
Encoding: UTF-8
License: GPL-3
Imports: dplyr, magrittr

NAMESPACE generated with document():

# Generated by roxygen2: do not edit by hand

export(mutate_cond)
importFrom(dplyr,mutate)
importFrom(magrittr,"%>%")

I expect this example code to run successfully and pass check(). Instead I get this error message:

❯ checking examples ... ERROR
  Running examples in ‘test-Ex.R’ failed
  The error most likely occurred in:

  > base::assign(".ptime", proc.time(), pos = "CheckExEnv")
  > ### Name: mutate_cond
  > ### Title: Conditional mutate
  > ### Aliases: mutate_cond
  >
  > ### ** Examples
  >
  > data(iris)
  > iris %>%
  +    mutate(aux = 0) %>%
  +    mutate_cond(Petal.Length > 1.3,aux = 3)
  Error in iris %>% mutate(aux = 0) %>% mutate_cond(Petal.Length > 1.3,  :
    could not find function "%>%"
  Execution halted

1 error ✖ | 0 warnings ✔ | 0 notes ✔

Also, if I add require(dplyr) and require(magrittr) to the @examples section the error goes away or if I remove the whole @examples section the error goes away.

Why won't this package pass check()?

Thank you!


问:
How can I add API Key authentication to oData Connector?
I am brand new to Power BI and am looking to find a way to connect to an oData service that requires an API Key. I was asked to create an oData connector but I am open to other ideas as well.

I've never written a connector. When I try connecting to the endpoint using the built in connector, I cannot connect with a Web API key because an API key name is provided. The things I've found on the web do not make sense to me as a lot of them require the advanced editor. The advanced editor is disabled for me for some reason. Any guidance would be wonderful.

答:
Figured it out:</p>

```<code>let
        theData = OData.Feed(
            "<API URL>",
            null,
            [
                Headers =
                [
                    #"ApiKey" = "<YOUR API KEY>"
                ]
            ]
        ),
        JSONTable = Json.Document(theData),
        message = "Hello World!"
    in
        JSONTable;
</code>```

Body:
Figured it out:

let
        theData = OData.Feed(
            "<API URL>",
            null,
            [
                Headers =
                [
                    #"ApiKey" = "<YOUR API KEY>"
                ]
            ]
        ),
        JSONTable = Json.Document(theData),
        message = "Hello World!"
    in
        JSONTable;