问:
Is there a way to start windows installer and avoid the UAC popup
I need to run an *.msi file from within my c# application.  The install runs without a UI and must run unattended.  Is there a way to avoid the UAC popup window?</p>

答:
In the past I've created solutions that did things like:

1) Install lays down app and a windows service running as SYSTEM.

2) Application checks webservice for new version and downloads to a temp directory.

3) Application informs service that MSI is present in temp directory.

4) Service "blesses" MSI by performing msiexec /jm foo.msi /qn (published/assigned)

5) Service informs application that the MSI is now trusted.

6) Application performs installation of MSI without UAC prompt.  msiexec /i foo.msi /qn RESTARTAPP=1

This pattern requires the MSI to be fully compliant in terms of custom action scheduling / security sandboxing.  It's also advised the application quits as soon as launching the MSI as to get out of the way and to have a custom action conditioned with RESTARTAPP to relaunch the application to give it a seamless user experience.

I've thought about making this a FOSS project/pattern but the security considerations to ensure it's not abused are beyond what I want to deal with.


来源: stackexchange

问:
Implementing recursive feature elimination in Matlab
I am implementing a recursive feature elimination (RFE) algorithm in Matlab, and have the following algorithmic question:

Using RFE, I want to plot the number of features used for classification vs. classification accuracy. Now say I have 5 features, I am ranking them based on the weight a linear classifier is giving them (e.g. linear SVM). Which approach is correct:

Rank the features based on the train set k, and from this specific ranking I calculate the accuracy for using n in {1,...,5} features (so 5 calculations of the accuracy based on the ranking of the same train set)

or

Rank the features based on the train set, calculate the accuracy for a number n features, rank the features again based on the next train set, now calculate the accuracy for the features top n+1 features

It seems to me 1 is correct, because the same train set is used to calculate accuracies for 1,...,5 features, making it somewhat comparable - am I right?

答:
Features might have different effect on different datasets. Therefore, I would recommend you to implement the first approach that makes use of the same training set since you want to compare some features.

However, I am not sure whether the graph you want to plot makes sense and if it is related to Recursive Feature Elimination.  If you want to plot the number of features vs. classification accuracy you need to implement various feature sets and evaluate the model. For instance, if you have 3 features f1, f2 and f3 then you need to produce 7 feature sets;

```<code>f1, f2, f3
f1, f2
f1, f3
f2, f3
f1
f2
f3
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Features might have different effect on different datasets. Therefore, I would recommend you to implement the first approach that makes use of the same training set since you want to compare some features.

However, I am not sure whether the graph you want to plot makes sense and if it is related to Recursive Feature Elimination.  If you want to plot the number of features vs. classification accuracy you need to implement various feature sets and evaluate the model. For instance, if you have 3 features f1, f2 and f3 then you need to produce 7 feature sets;

f1, f2, f3
f1, f2
f1, f3
f2, f3
f1
f2
f3


问:
Access to WrappedArray elements
I have a spark dataframe and here is the schema:

```<code>|-- eid: long (nullable = true)
|-- age: long (nullable = true)
|-- sex: long (nullable = true)
|-- father: array (nullable = true)
|    |-- element: array (containsNull = true)
|    |    |-- element: long (containsNull = true)
</code>```

and a sample of rows:.

```<code>df.select(df['father']).show()
+--------------------+
|              father|
+--------------------+
|[WrappedArray(-17...|
|[WrappedArray(-11...|
|[WrappedArray(13,...|
+--------------------+
</code>```

and the type is

```<code>DataFrame[father: array<array<bigint>>]
</code>```

How can I have access to each element of inner array? For example -17 in the first row?
I tried different things like df.select(df['father'])(0)(0).show() but no luck.

答:
Another scala answer would look like this:</p>

```<code>df.select(col("father").getItem(0) as "father_0", col("father").getItem(1) as "father_1")
</code>```

Title: Access to WrappedArray elements

Body:
I have a spark dataframe and here is the schema:

|-- eid: long (nullable = true)
|-- age: long (nullable = true)
|-- sex: long (nullable = true)
|-- father: array (nullable = true)
|    |-- element: array (containsNull = true)
|    |    |-- element: long (containsNull = true)

and a sample of rows:.

df.select(df['father']).show()
+--------------------+
|              father|
+--------------------+
|[WrappedArray(-17...|
|[WrappedArray(-11...|
|[WrappedArray(13,...|
+--------------------+

and the type is

DataFrame[father: array<array<bigint>>]

How can I have access to each element of inner array? For example -17 in the first row?
I tried different things like df.select(df['father'])(0)(0).show() but no luck.

Body:
Another scala answer would look like this:

df.select(col("father").getItem(0) as "father_0", col("father").getItem(1) as "father_1")


问:
How to pass parameters to modal when i call it programmatically?
I call bootstrap modal programmatically like this

$('#confirmModal').modal()
```

<p>But when i do so, "event" in:</p>

<pre class="lang-js prettyprint-override"><code>$('#confirmModal').on('show.bs.modal', function (event) {
   var button = $(event.relatedTarget);
})
</code>```

doesn't have "relatedTarget" but i need it. How to pass it using $('#confirmModal').modal()

答:
Though it is not officially documented it is possible to pass a second argument to modal() which acts as the related target:

```<code>$('#confirmModal').modal('show', $('#someButton'));
</code>```

Then you can use the event handler as it would have been triggered by a button or whatever:

```<code>$('#confirmModal').on('show.bs.modal', function (event) {
   var button = event.relatedTarget; // should be set now
})
</code>```

This should work with at least with Bootstrap 3.3.x and I guess also with 4.0.x.

Body:
I call bootstrap modal programmatically like this

$('#confirmModal').modal()

But when i do so, "event" in:

$('#confirmModal').on('show.bs.modal', function (event) {
   var button = $(event.relatedTarget);
})

doesn't have "relatedTarget" but i need it. How to pass it using $('#confirmModal').modal()

Body:
Though it is not officially documented it is possible to pass a second argument to modal() which acts as the related target:

$('#confirmModal').modal('show', $('#someButton'));

Then you can use the event handler as it would have been triggered by a button or whatever:

$('#confirmModal').on('show.bs.modal', function (event) {
   var button = event.relatedTarget; // should be set now
})

This should work with at least with Bootstrap 3.3.x and I guess also with 4.0.x.


问:
Can a list of files / file be pushed / committed into GIT using Python?
Well I have the below code to list the files which were added / modified.

```<code>   import os
   import datetime as dt

   config_path = '/home/'
   now = dt.datetime.now()
   ago = now-dt.timedelta(minutes=30)

   for root, dirs,files in os.walk(config_path):
       for fname in files:
           path = os.path.join(root, fname)
           st = os.stat(path)
           mtime = dt.datetime.fromtimestamp(st.st_mtime)
           if mtime > ago:
                   print('File : %s Time : %s'%(path, mtime))
</code>```

I want those files to be pushed into GIT using Python. Is there any way to do it?

答:
You can just use GitPython library in order to work on git without leave python environment.

Using that library you can interact with a git repository both high-level like and low-level like (i.e. you can use it as a git wrapper or you can interact with your file as BLOBs, maybe your case).

Body:
Well I have the below code to list the files which were added / modified.

   import os
   import datetime as dt

   config_path = '/home/'
   now = dt.datetime.now()
   ago = now-dt.timedelta(minutes=30)

   for root, dirs,files in os.walk(config_path):
       for fname in files:
           path = os.path.join(root, fname)
           st = os.stat(path)
           mtime = dt.datetime.fromtimestamp(st.st_mtime)
           if mtime > ago:
                   print('File : %s Time : %s'%(path, mtime))

I want those files to be pushed into GIT using Python. Is there any way to do it?


问:
How to make HTTP DELETE method using urllib2?
Does urllib2 support DELETE or PUT method? If yes provide with any example please. I need to use piston API.

答:
Found following code from https://gist.github.com/kehr/0c282b14bfa35155deff34d3d27f8307 and it worked for me (Python 2.7.5):</p>

```<code>import urllib2

request = urllib2.Request(uri, data=data)
request.get_method = lambda: 'DELETE'
response = urllib2.urlopen(request)
</code>```

Body:
Found following code from https://gist.github.com/kehr/0c282b14bfa35155deff34d3d27f8307 and it worked for me (Python 2.7.5):

import urllib2

request = urllib2.Request(uri, data=data)
request.get_method = lambda: 'DELETE'
response = urllib2.urlopen(request)


问:
issue with understanding macros in C programming
what is the output of the below code if i give '1' as an input and why ?

FYI ::iam using gcc to build the code.

```<code>#include <stdio.h>
int main()
{
    // k integer to hold user input
    int k=0;

    scanf("%d",&k);

    switch(k)
    {
        case 1 :
        #define first_case
        break;
        case 2 :
         #define second_case
        break;
        case 3 :
         #define third_case
        break;
        case 4 :
        #define fourth_case
        break;
    }
</code>```

#ifdef first_case
        printf(" first_case\n");
  #endif

#ifdef second_case
        printf(" second_case\n");
  #endif

#ifdef third_case
        printf(" third_case\n");
 #endif

#ifdef fourth_case
        printf(" fourth_case\n");
 #endif

```<code>}
</code>```

答:
As others have said, a preprocessor macro cannot be set or altered at runtime, you just need an ordinary automatic variable.  For example:

```<code>int k=0;
int first_case = 0;   // 0 resolves to False
int second_case = 0;  // 0 resolves to False
int third_case = 0;   // 0 resolves to False
int fourth_case = 0;  // 0 resolves to False

scanf("%d",&k);
switch(k)
{
    case 1 :
        printf("case 1\n");
        first_case = 1;
        break;
    case 2 :
        second_case = 1;
        break;
    case 3 :
        third_case = 1;
        break;
    case 4 :
        fourth_case = 1;
        break;
}

if (first_case)
    printf("typed first_case\n");

if (second_case)
    printf("typed second_case\n");

if (third_case)
    printf("typed third_case\n");

if (fourth_case)
    printf("typed fourth_case\n");
</code>```

Having said that, you are doing the same test twice, so most would just use the case, probably with a default:

```<code>scanf("%d",&k);
switch(k)
{
    case 1 :
        printf("typed first_case\n");
        break;
    case 2 :
        printf("typed second_case\n");
        break;
    case 3 :
        printf("typed third_case\n");
        break;
    case 4 :
        printf("typed fourth_case\n");
        break;
    default :
        fprintf(stderr, "Invalid response: %d\n", k);
}
</code>```

Body:
what is the output of the below code if i give '1' as an input and why ?

FYI ::iam using gcc to build the code.

#include <stdio.h>
int main()
{
    // k integer to hold user input
    int k=0;

    scanf("%d",&k);

    switch(k)
    {
        case 1 :
        #define first_case
        break;
        case 2 :
         #define second_case
        break;
        case 3 :
         #define third_case
        break;
        case 4 :
        #define fourth_case
        break;
    }

#ifdef first_case
        printf(" first_case\n");
  #endif

#ifdef second_case
        printf(" second_case\n");
  #endif

#ifdef third_case
        printf(" third_case\n");
 #endif

#ifdef fourth_case
        printf(" fourth_case\n");
 #endif

}

Body:
As others have said, a preprocessor macro cannot be set or altered at runtime, you just need an ordinary automatic variable.  For example:

int k=0;
int first_case = 0;   // 0 resolves to False
int second_case = 0;  // 0 resolves to False
int third_case = 0;   // 0 resolves to False
int fourth_case = 0;  // 0 resolves to False

scanf("%d",&k);
switch(k)
{
    case 1 :
        printf("case 1\n");
        first_case = 1;
        break;
    case 2 :
        second_case = 1;
        break;
    case 3 :
        third_case = 1;
        break;
    case 4 :
        fourth_case = 1;
        break;
}

if (first_case)
    printf("typed first_case\n");

if (second_case)
    printf("typed second_case\n");

if (third_case)
    printf("typed third_case\n");

if (fourth_case)
    printf("typed fourth_case\n");

Having said that, you are doing the same test twice, so most would just use the case, probably with a default:

scanf("%d",&k);
switch(k)
{
    case 1 :
        printf("typed first_case\n");
        break;
    case 2 :
        printf("typed second_case\n");
        break;
    case 3 :
        printf("typed third_case\n");
        break;
    case 4 :
        printf("typed fourth_case\n");
        break;
    default :
        fprintf(stderr, "Invalid response: %d\n", k);
}


问:
NSView showing and hide SubView
In my applications i need to display and hide based upon some user action, i have done following

In interface definition, have added views like that

```<code>@interface MyWnd : NSWindowController {

    MyCustomView1 *pCtmView1;

    MyCustomView2 *pCtmView2;
}
</code>```

In source file have following relevant methods

```<code>-(void)CreateSubViews{

    NSRect subViewRect = [self GetSubViewRect];

    pCtmView1 = [[ MyCustomView1 alloc]initWithFrame:subViewRect]

    pCtmView2 = [[ MyCustomView2 alloc]initWithFrame:subViewRect]

    initially both view will be hidden

    [pCtmView1 setHidden:TRUE];
    [pCtmView2 setHidden:TRUE];

    [[self window] view addSubView:pCtmView1];
    [[self window] view addSubView:pCtmView2];
}

-(void)ShowSubView:(int)viewId{
  if(viewId == 0 ){
    [pCtmView1 setHidden:FALSE];
    [pCtmView1 setNeedDisplay:YES];
 }
 if(viewId == 1 ){
    [pCtmView2 setHidden:FALSE];
    [pCtmView2 setNeedDisplay:YES];
 }
}
</code>```

In Init Application i am Calling ShowSubView:0 and its working fine,
  but depend upon the some user action, i will call ShowSubView:1 and nothing is displayed &
  EXEC_BAD_ACCESS i could see in the gdb

  Please guide me, do i need to do something more to display the view

Thanks

答:
When your app crashes, look in the Debugger window—it'll tell you what your app was doing when it crashed.

You'll probably want to stop the debugger and re-run your app under Instruments's Zombies instrument. When the crash is because you messaged a dead object (which is the cause probably 80% of the time in Cocoa), the Zombies instrument will tell you what object that was and what killed it.

ContentLicense: CC BY-SA 2.5

Title: NSView showing and hide SubView

Body:
In my applications i need to display and hide based upon some user action, i have done following

In interface definition, have added views like that

@interface MyWnd : NSWindowController {

    MyCustomView1 *pCtmView1;

    MyCustomView2 *pCtmView2;
}

In source file have following relevant methods

-(void)CreateSubViews{

    NSRect subViewRect = [self GetSubViewRect];

    pCtmView1 = [[ MyCustomView1 alloc]initWithFrame:subViewRect]

    pCtmView2 = [[ MyCustomView2 alloc]initWithFrame:subViewRect]

    initially both view will be hidden

    [pCtmView1 setHidden:TRUE];
    [pCtmView2 setHidden:TRUE];

    [[self window] view addSubView:pCtmView1];
    [[self window] view addSubView:pCtmView2];
}

-(void)ShowSubView:(int)viewId{
  if(viewId == 0 ){
    [pCtmView1 setHidden:FALSE];
    [pCtmView1 setNeedDisplay:YES];
 }
 if(viewId == 1 ){
    [pCtmView2 setHidden:FALSE];
    [pCtmView2 setNeedDisplay:YES];
 }
}

In Init Application i am Calling ShowSubView:0 and its working fine,
  but depend upon the some user action, i will call ShowSubView:1 and nothing is displayed &
  EXEC_BAD_ACCESS i could see in the gdb

  Please guide me, do i need to do something more to display the view

Thanks


问:
Django user account creation confirmation email
I have a django project where I want to create users, and some time later be able to send a welcome email with a link inviting them to log in and set a password.

I'm using django-allauth. I found this SO question which shows how to call allauth's password reset form, which is close to what I need, except that:

I want to send a "welcome" email, which would be worded differently.

I want it to send them to a "welcome" page, which would be different to a password reset (although perhaps operate the same way in that it use a token etc...)

I'm thinking I could somehow hijack that, but am not sure how or where that email gets sent.

django-allauth docs mention the routes /accounts/password/set/ and /accounts/password/set/ but I can't access either without logging in first.

This is an existing project I inherited, and I do have a template for "/account/password_reset_from_key.html". Just not sure how it all gets wired together.

Has anyone done anything similar?

答:
You mention:

...and some time later be able to send a welcome email with a link inviting them to log in and set a password.

If sometime later, then you might be interested in queues like Celery to do that for you.

Here's an approach you might take:

Listen to the save django model signal on the User model. Send an email to a user whenever that is triggered (this will happen immediately. However with your "some time later" thing, then you add that sending to the user to a celery job queue for later

Send a dynamic email with html. With this, you can customize the design etc to your taste.


问:
Background Service Limitations Android and voip app
I am working on the voip app. I do all the logic regarding the signaling on background service. When user exists the app I am stoping the service. In this case, I am not connected to the server. When I am in this state, server is sending the push notification (FCM), I am starting the service and creating notification for incoming call or message. This is all good so far:)

I have read about the limitations for Oreo for backgrounding services and realize that now I need to start service in foreground while showing notification. Then I wanted to check how the Hangouts(google) does it, and of course they are running the service in the background when message is received. Am I missing something?

Thank you

答:
Visible activity = foreground

When user exists the app I am stoping the service

If this means that the service is running only when your app is visible to the user, then the process and the service is actually in the foreground and you shouldn't experience any problems with system killing your service:

An app is considered to be in the foreground if any of the following is true:

It has a visible activity, whether the activity is started or paused.

FCM received = foreground

Also, receiving high-priority FCM messages will put your app on temporary whitelist for background processing, and you will have more than enough time to do your processing at that time, or you can always start a foreground service after FCM is received - like a service that handles the call and should display a notification while running:

Under certain circumstances, a background app is placed on a temporary whitelist for several minutes. While an app is on the whitelist, it can launch services without limitation, and its background services are permitted to run. An app is placed on the whitelist when it handles a task that's visible to the user, such as:

Handling a high-priority Firebase Cloud Messaging (FCM) message.

Your app design - handling incoming calls by receiving priority FCM and then creating a foreground call service - seems reasonable.

Refer to the documentation which is really clear on these subjects.


问:
Array versus linked-list
Why would someone want to use a linked-list over an array?

Coding a linked-list is, no doubt, a bit more work than using an array and one may wonder what would justify the additional effort.

I think insertion of new elements is trivial in a linked-list but it's a major chore in an array. Are there other advantages to using a linked list to store a set of data versus storing it in an array?

This question is not a duplicate of this question because the other question is asking specifically about a particular Java class while this question is concerned with the general data structures.

答:
Why would someone want to use a linked-list over an array?

This is only one reason - if you need a linked list data structure and a programming language you are using is not supports a pointers.

OwnerDisplayName: Onorio Catenacci

Title: Array versus linked-list

LastEditorDisplayName: David Nehme


问:
Replace character of column value with string from another column in Pandas
```<code>name value_1
dd3   what, _ is
dd4   what, _ is
</code>```

How to replace '_' from value_1 column with whole string from name column?

Desired output for value_1 column

```<code>value_1
what, dd3 is
what, dd4 is
</code>```

I have tried with this:

```<code>df['value_1'] = df['value_1'].apply(lambda x:x.replace("_", df['name']))
</code>```

And I got this error :expected a string or other character buffer object

答:
Use apply with axis=1 for process by rows:

```<code>df['value_1'] = df.apply(lambda x:x['value_1'].replace("_", x['name']), axis=1)
print (df)
  name       value_1
0  dd3  what, dd3 is
1  dd4  what, dd4 is
</code>```

Body:
name value_1
dd3   what, _ is
dd4   what, _ is

How to replace '_' from value_1 column with whole string from name column?

Desired output for value_1 column

value_1
what, dd3 is
what, dd4 is

I have tried with this:

df['value_1'] = df['value_1'].apply(lambda x:x.replace("_", df['name']))

And I got this error :expected a string or other character buffer object

Body:
Use apply with axis=1 for process by rows:

df['value_1'] = df.apply(lambda x:x['value_1'].replace("_", x['name']), axis=1)
print (df)
  name       value_1
0  dd3  what, dd3 is
1  dd4  what, dd4 is


问:
Swift 4: Access Variables from DispatchQueue.main (Scope)
I have a CoreML Image Classification task, that takes the "live stream" from the iOS device's [video] camera and occurs in the background. Once objects have been been identified, and other app logic has occurred, I would like to update the UI's label with some of the data.

Can someone explain how the callout to DispatchQueue.main.asyc(execute: { }) is able to access the variable(s) I have been working with? I think this is essentially a scoping issue?

The code I am currently using:

```<code>func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {

    processCameraBuffer(sampleBuffer: sampleBuffer)

}

func processCameraBuffer(sampleBuffer: CMSampleBuffer) {

    let coreMLModel = Inceptionv3()

    if let model = try? VNCoreMLModel(for: coreMLModel.model) {
        let request = VNCoreMLRequest(model: model, completionHandler: { (request, error) in
            if let results = request.results as? [VNClassificationObservation] {

                var counter = 0
                var otherVar = 0

                for item in results[0...9] {

                    if item.identifier.contains("something") {
                        print("some app logic goes on here")
                        otherVar += 10 - counter
                    }
                    counter += 1

                }
                switch otherVar {
                case _ where otherVar >= 10:
                    DispatchQueue.main.async(execute: {
                        let displayVarFormatted = String(format: "%.2f", otherVar / 65 * 100)
                        self.labelPrediction.text = "\(counter): \(displayVarFormatted)%"
                    })
                default:
                    DispatchQueue.main.async(execute: {
                        self.labelPrediction.text = "No result!"
                    })
                }
            }
        })

            if let pixelBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) {
                let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:])
                do {
                    try handler.perform([request])
                } catch {
                    print(error.localizedDescription)
                }
            }
    }
}
</code>```

Its the self.labelPrediction.text = "" lines inside the switch statement that is causing the issue. This var is always 0 currently.

答:
It's not the matter of DispatchQueue. From processCameraBuffer(sampleBuffer:), your code update your UI before it get result.

To solve this, you need to use escaping closure. Your function should look like this.

```<code>func processCameraBuffer(sampleBuffer: CMSampleBuffer, completion: @escaping (Int, String) -> Void) {
    // 2.
    let request = VNCoreMLRequest(model: model, completionHandler: { (request, error) in

      DispatchQueue.main.async(execute: {
          // 3.
          let displayVarFormatted = String(format: "%.2f", otherVar / 65 * 100)
          completion(counter, displayVarFormatted)
      })
    }
}

func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
    // 1.
    processCameraBuffer(sampleBuffer) { counter, displayVarFormatted in
        /*
         This Closure will be executed from
         completion(counter, displayVarFormatted)
        */
        // 4.
        self.labelPrediction.text = "\(counter): \(displayVarFormatted)%"
    }
}
</code>```

Scope of variable is not a problem from here. You need to handle asynchronous task.

Capture occurs.

processCameraBuffer is called and VNCoreMLRequest executed.

You will get data and execute processCameraBuffer's completion block, by completion().

Update Label.

Body:
I have a CoreML Image Classification task, that takes the "live stream" from the iOS device's [video] camera and occurs in the background. Once objects have been been identified, and other app logic has occurred, I would like to update the UI's label with some of the data.

Can someone explain how the callout to DispatchQueue.main.asyc(execute: { }) is able to access the variable(s) I have been working with? I think this is essentially a scoping issue?

The code I am currently using:

func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {

    processCameraBuffer(sampleBuffer: sampleBuffer)

}

func processCameraBuffer(sampleBuffer: CMSampleBuffer) {

    let coreMLModel = Inceptionv3()

    if let model = try? VNCoreMLModel(for: coreMLModel.model) {
        let request = VNCoreMLRequest(model: model, completionHandler: { (request, error) in
            if let results = request.results as? [VNClassificationObservation] {

                var counter = 0
                var otherVar = 0

                for item in results[0...9] {

                    if item.identifier.contains("something") {
                        print("some app logic goes on here")
                        otherVar += 10 - counter
                    }
                    counter += 1

                }
                switch otherVar {
                case _ where otherVar >= 10:
                    DispatchQueue.main.async(execute: {
                        let displayVarFormatted = String(format: "%.2f", otherVar / 65 * 100)
                        self.labelPrediction.text = "\(counter): \(displayVarFormatted)%"
                    })
                default:
                    DispatchQueue.main.async(execute: {
                        self.labelPrediction.text = "No result!"
                    })
                }
            }
        })

            if let pixelBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) {
                let handler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:])
                do {
                    try handler.perform([request])
                } catch {
                    print(error.localizedDescription)
                }
            }
    }
}

Its the self.labelPrediction.text = "" lines inside the switch statement that is causing the issue. This var is always 0 currently.

Body:
It's not the matter of DispatchQueue. From processCameraBuffer(sampleBuffer:), your code update your UI before it get result.

To solve this, you need to use escaping closure. Your function should look like this.

func processCameraBuffer(sampleBuffer: CMSampleBuffer, completion: @escaping (Int, String) -> Void) {
    // 2.
    let request = VNCoreMLRequest(model: model, completionHandler: { (request, error) in

      DispatchQueue.main.async(execute: {
          // 3.
          let displayVarFormatted = String(format: "%.2f", otherVar / 65 * 100)
          completion(counter, displayVarFormatted)
      })
    }
}

func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
    // 1.
    processCameraBuffer(sampleBuffer) { counter, displayVarFormatted in
        /*
         This Closure will be executed from
         completion(counter, displayVarFormatted)
        */
        // 4.
        self.labelPrediction.text = "\(counter): \(displayVarFormatted)%"
    }
}

Scope of variable is not a problem from here. You need to handle asynchronous task.

Capture occurs.

processCameraBuffer is called and VNCoreMLRequest executed.

You will get data and execute processCameraBuffer's completion block, by completion().

Update Label.


问:
MySQL Multiple foreign keys pointing to same table
I have a table called teams  and a table called games.   teams has id, name, .....    the games has id, hteam_id, vteam_id, loc, ....    I want the hteam_id and vteam_id to each be foreign key into the teams table.  How do you do it</p>

答:
First Read This:

FOREIGN KEY Constraints

Example:

```<code>CREATE TABLE parent (id INT NOT NULL,
                     PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (id INT, parent_id INT,
                    INDEX par_ind (parent_id),
                    FOREIGN KEY (parent_id) REFERENCES parent(id)
                      ON DELETE CASCADE
) ENGINE=INNODB;
</code>```

Body:
First Read This:

FOREIGN KEY Constraints

Example:

CREATE TABLE parent (id INT NOT NULL,
                     PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (id INT, parent_id INT,
                    INDEX par_ind (parent_id),
                    FOREIGN KEY (parent_id) REFERENCES parent(id)
                      ON DELETE CASCADE
) ENGINE=INNODB;


问:
Django Test client.get() returns 302 code instead of 200
Running a test on a url returns 302 instead of 200. Yet testing the same urls in production with a redirect tester returns 200. Not really sure what's going on.

tests.py

```<code>def test_detail(self):
    response = self.client.get('/p/myproduct-detail.html')
    self.assertEqual(response.status_code, 200)
</code>```

urls.py

```<code>    url(r'^p/(?P<slug>[-\w\d]+).html$', main.views.product_detail,
        name='product-detail'),
</code>```

views.py

```<code>def product_detail(request, slug):
    stuff...
    return render(request, 'product-detail.html', {})
</code>```

If I add follow=True to client.get() I receive 200 code as expected.

答:
Print the value of response['location'] in your test before your assertEqual line. It will show you where the client is being redirected to (e.g. the login page).

```<code>def test_detail(self):
    response = self.client.get('/p/myproduct-detail.html')
    print(response['location'])
    self.assertEqual(response.status_code, 200)
</code>```

Body:
Running a test on a url returns 302 instead of 200. Yet testing the same urls in production with a redirect tester returns 200. Not really sure what's going on.

tests.py

def test_detail(self):
    response = self.client.get('/p/myproduct-detail.html')
    self.assertEqual(response.status_code, 200)

urls.py

    url(r'^p/(?P<slug>[-\w\d]+).html$', main.views.product_detail,
        name='product-detail'),

views.py

def product_detail(request, slug):
    stuff...
    return render(request, 'product-detail.html', {})

If I add follow=True to client.get() I receive 200 code as expected.

Body:
Print the value of response['location'] in your test before your assertEqual line. It will show you where the client is being redirected to (e.g. the login page).

def test_detail(self):
    response = self.client.get('/p/myproduct-detail.html')
    print(response['location'])
    self.assertEqual(response.status_code, 200)


问:
Using three points (x, y), How to find whether it is triangle or not
I have an assignment in codeforces which says:

Like all problem solvers, Ebram loves eating crepe! As we all know, crepe usually served in a triangular shape. Now Ebram wants to know how large can a crepe side be! So he tries to draw a triangle on a plane using three points and calculate the maximum length of the three sides of the triangle. But sometimes he falls asleep as he has been busy with the team preparing the training problems! As a result, the three points he uses may not form a triangle that could represent a piece of crepe! A triangle can represent a piece of crepe only if it has a positive area. So you are here to help Ebram! Given the coordinates Ebram used, determine whether they form a triangle that could represent a piece of crepe or not.

 Input:
Three integer coordinates (X,Y) that represent the three points Ebram used. Each point on a separate line.

Output: If the points form a triangle that can represent a piece of crepe, print the square of the maximum length of the three sides of the triangle. Otherwise print "Poor boy"

Examples

```<code>input
1 1
3 1
3 9
output
68
</code>```

```<code>input
 -10 8
  9 100
  3 8
  output
  8825
</code>```

```<code>input
7 3
3 3
19 3
output
Poor boy
</code>```

Here is my code that I used:

```<code>#include <iostream>
#include <cmath>
using namespace std;
int main () {
   double x1,y1,x2,y2,x3,y3;
    double area;
    double s1,s2,s3;
   double slope1, slope2;
cin >> x1 >> y1;
cin >> x2 >> y2;
cin >> x3 >> y3;
slope1 =((y2-y1)/(x2-x1));
slope2 =((y3-y2)/(x3-x2));
area = 0.5*abs(((x2-x1)*(y3-y1)-(x3-x1)*(y2-y1)));
if (slope1!=slope2 &&  (area)!=0){

    s1 = sqrt(((x1-x2)*(x1-x2))+((y1-y2)*(y1-y2)));
    s2 = sqrt(((x2-x3)*(x2-x3))+((y2-y3)*(y2-y3)));
    s3 = sqrt(((x1-x3)*(x1-x3))+((y1-y3)*(y1-y3)));
     if (s1 > s2 && s1 > s3)
        cout<<s1*s1<<endl;
     if (s2 > s1 && s2 > s3)
        cout<<s2*s2<<endl;
     if (s3 > s1 && s3 > s2)
        cout <<s3*s3<<endl;
}

else
    cout <<"Poor boy";
return 0;

}
</code>```

 First I find the slope1 and slope2 to check if the three points aren't at the same line. So If they're not equal it forms a triangle (crepe).
Using this:

```<code>slope1 =((y2-y1)/(x2-x1));
slope2 =((y3-y2)/(x3-x2));
</code>```

Then I wrote a relation to find the area of triangle using this formula:

```<code>area = 0.5*abs(((x2-x1)*(y3-y1)-(x3-x1)*(y2-y1)));
</code>```

Finally I put the if statements to find if it is a triangle or not and find the length of each side of the triangle then find the maximum length and print the square of it.

```<code>if (slope1!=slope2 &&  (area)!=0){

    s1 = sqrt(((x1-x2)*(x1-x2))+((y1-y2)*(y1-y2)));
    s2 = sqrt(((x2-x3)*(x2-x3))+((y2-y3)*(y2-y3)));
    s3 = sqrt(((x1-x3)*(x1-x3))+((y1-y3)*(y1-y3)));
     if (s1 > s2 && s1 > s3)
        cout<<s1*s1<<endl;
     if (s2 > s1 && s2 > s3)
        cout<<s2*s2<<endl;
     if (s3 > s1 && s3 > s2)
        cout <<s3*s3<<endl;
}

else
    cout <<"Poor boy";
return 0;

}
</code>```

 I tested the code in my compiler and it runs the i/o shown in the example perfectly fine. I submitted the code on codeforces but I stuck wrong answer at test 8 I don't know why?, and my code runs inputs and outputs fine. I will be very pleased if you help guys.

答:
As in Sani's answer, I recommend calculating the rise and run between each pair of points:

```<code>rise1 = y2 - y1
rise2 = y3 - y2
rise3 = y1 - y3

run1 = x2 - x1
run2 = x3 - x2
run3 = x1 - x3
</code>```

Also the same, I recommend checking whether any two points are coincident. Note that this is equivalent to what Sani's code is checking:

```<code>if (rise1 = run1 = 0) or (rise2 = run2 = 0) or (rise3 = run3 = 0) then
    print "Poor Boy"
    return 0
</code>```

Now, similar to Sani, we move on to checking whether the points are on a line. However, we can simplify the conditions to check somewhat. Note that, if no two points are on a vertical line, then the three points are on one line if the slopes between any two points are equal. That is, m1 = m2, m2 = m3, or m3 = m1, equivalently. We can check whether m1 = m2. This is true when rise1/run1 = rise2/run2, which is safe since we assume no points are on a vertical line. We can rearrange this to rise1 * run2 = rise2 * run1, again safely. If no two points are on a vertical line, this is the only check we need.

What if two points are on a vertical line? Then at least one of run1 and run2 will be zero. However, because we have already guaranteed no two points are coincident, we can be absolutely sure that if either of these is zero, the corresponding rise is non-zero. There are two other cases (besides no two points being on a vertical line):

Exactly two points are on a vertical line. Then either run1 or run2, but not both, are zero. Without loss of generality, assume run1 is zero. Then the condition rise1 * run2 = rise2 * run1 simplifies to rise1 * run2 = 0. Because we know rise1 is not zero, this is satisfied only if run2 = 0, which contradicts our assumed case. This means that, in this case, the condition we derived earlier will produce the correct result and identify the points as not being on the same line.

Three points are on a vertical line. Then both run1 and run2 are zero. Then the condition rise1 * run2 = rise2 * run1 simplifies to 0 = 0, which is always true. In this case, the condition will produce the correct result and identify three points as being on the same line.

Because the condition we derived for the case of no two points on a vertical line happens to produce the correct result for all other possible cases, we can use it in all cases (under the assumption no two points are coincident). Therefore, we don't need to check anything except rise1 * run2 = rise2 * run1:

```<code>if rise1 * run2 = rise2 * run1 then
    print "Poor Boy"
    return 0
</code>```

Now we know we have a triangle and need to return the largest of the three sides. We need the sum of squared differences of respective coordinates. Luckily, we already have the coordinate differences, so:

```<code>d1 = (rise1 * rise1) + (run1 * run1)
d2 = (rise2 * rise2) + (run2 * run2)
d3 = (rise3 * rise3) + (run3 * run3)
return max(d1, d2, d3)
</code>```

Body:
I have an assignment in codeforces which says:

Like all problem solvers, Ebram loves eating crepe! As we all know, crepe usually served in a triangular shape. Now Ebram wants to know how large can a crepe side be! So he tries to draw a triangle on a plane using three points and calculate the maximum length of the three sides of the triangle. But sometimes he falls asleep as he has been busy with the team preparing the training problems! As a result, the three points he uses may not form a triangle that could represent a piece of crepe! A triangle can represent a piece of crepe only if it has a positive area. So you are here to help Ebram! Given the coordinates Ebram used, determine whether they form a triangle that could represent a piece of crepe or not.

 Input:
Three integer coordinates (X,Y) that represent the three points Ebram used. Each point on a separate line.

Output: If the points form a triangle that can represent a piece of crepe, print the square of the maximum length of the three sides of the triangle. Otherwise print "Poor boy"

Examples

input
1 1
3 1
3 9
output
68

input
 -10 8
  9 100
  3 8
  output
  8825

input
7 3
3 3
19 3
output
Poor boy

Here is my code that I used:

#include <iostream>
#include <cmath>
using namespace std;
int main () {
   double x1,y1,x2,y2,x3,y3;
    double area;
    double s1,s2,s3;
   double slope1, slope2;
cin >> x1 >> y1;
cin >> x2 >> y2;
cin >> x3 >> y3;
slope1 =((y2-y1)/(x2-x1));
slope2 =((y3-y2)/(x3-x2));
area = 0.5*abs(((x2-x1)*(y3-y1)-(x3-x1)*(y2-y1)));
if (slope1!=slope2 &&  (area)!=0){

    s1 = sqrt(((x1-x2)*(x1-x2))+((y1-y2)*(y1-y2)));
    s2 = sqrt(((x2-x3)*(x2-x3))+((y2-y3)*(y2-y3)));
    s3 = sqrt(((x1-x3)*(x1-x3))+((y1-y3)*(y1-y3)));
     if (s1 > s2 && s1 > s3)
        cout<<s1*s1<<endl;
     if (s2 > s1 && s2 > s3)
        cout<<s2*s2<<endl;
     if (s3 > s1 && s3 > s2)
        cout <<s3*s3<<endl;
}

else
    cout <<"Poor boy";
return 0;

}

 First I find the slope1 and slope2 to check if the three points aren't at the same line. So If they're not equal it forms a triangle (crepe).
Using this:

slope1 =((y2-y1)/(x2-x1));
slope2 =((y3-y2)/(x3-x2));

Then I wrote a relation to find the area of triangle using this formula:

area = 0.5*abs(((x2-x1)*(y3-y1)-(x3-x1)*(y2-y1)));

Finally I put the if statements to find if it is a triangle or not and find the length of each side of the triangle then find the maximum length and print the square of it.

if (slope1!=slope2 &&  (area)!=0){

    s1 = sqrt(((x1-x2)*(x1-x2))+((y1-y2)*(y1-y2)));
    s2 = sqrt(((x2-x3)*(x2-x3))+((y2-y3)*(y2-y3)));
    s3 = sqrt(((x1-x3)*(x1-x3))+((y1-y3)*(y1-y3)));
     if (s1 > s2 && s1 > s3)
        cout<<s1*s1<<endl;
     if (s2 > s1 && s2 > s3)
        cout<<s2*s2<<endl;
     if (s3 > s1 && s3 > s2)
        cout <<s3*s3<<endl;
}

else
    cout <<"Poor boy";
return 0;

}

 I tested the code in my compiler and it runs the i/o shown in the example perfectly fine. I submitted the code on codeforces but I stuck wrong answer at test 8 I don't know why?, and my code runs inputs and outputs fine. I will be very pleased if you help guys.

Body:
As in Sani's answer, I recommend calculating the rise and run between each pair of points:

rise1 = y2 - y1
rise2 = y3 - y2
rise3 = y1 - y3

run1 = x2 - x1
run2 = x3 - x2
run3 = x1 - x3

Also the same, I recommend checking whether any two points are coincident. Note that this is equivalent to what Sani's code is checking:

if (rise1 = run1 = 0) or (rise2 = run2 = 0) or (rise3 = run3 = 0) then
    print "Poor Boy"
    return 0

Now, similar to Sani, we move on to checking whether the points are on a line. However, we can simplify the conditions to check somewhat. Note that, if no two points are on a vertical line, then the three points are on one line if the slopes between any two points are equal. That is, m1 = m2, m2 = m3, or m3 = m1, equivalently. We can check whether m1 = m2. This is true when rise1/run1 = rise2/run2, which is safe since we assume no points are on a vertical line. We can rearrange this to rise1 * run2 = rise2 * run1, again safely. If no two points are on a vertical line, this is the only check we need.

What if two points are on a vertical line? Then at least one of run1 and run2 will be zero. However, because we have already guaranteed no two points are coincident, we can be absolutely sure that if either of these is zero, the corresponding rise is non-zero. There are two other cases (besides no two points being on a vertical line):

Exactly two points are on a vertical line. Then either run1 or run2, but not both, are zero. Without loss of generality, assume run1 is zero. Then the condition rise1 * run2 = rise2 * run1 simplifies to rise1 * run2 = 0. Because we know rise1 is not zero, this is satisfied only if run2 = 0, which contradicts our assumed case. This means that, in this case, the condition we derived earlier will produce the correct result and identify the points as not being on the same line.

Three points are on a vertical line. Then both run1 and run2 are zero. Then the condition rise1 * run2 = rise2 * run1 simplifies to 0 = 0, which is always true. In this case, the condition will produce the correct result and identify three points as being on the same line.

Because the condition we derived for the case of no two points on a vertical line happens to produce the correct result for all other possible cases, we can use it in all cases (under the assumption no two points are coincident). Therefore, we don't need to check anything except rise1 * run2 = rise2 * run1:

if rise1 * run2 = rise2 * run1 then
    print "Poor Boy"
    return 0

Now we know we have a triangle and need to return the largest of the three sides. We need the sum of squared differences of respective coordinates. Luckily, we already have the coordinate differences, so:

d1 = (rise1 * rise1) + (run1 * run1)
d2 = (rise2 * rise2) + (run2 * run2)
d3 = (rise3 * rise3) + (run3 * run3)
return max(d1, d2, d3)


答:
UPDATE: similar to @jezrael's solution, but it should be bit faster for larger data sets (vectorized approach):

```<code>In [221]: df['value_1'] = (df.groupby('name')['value_1']
                             .transform(lambda x: x.str.replace('_', x.name)))

In [222]: df
Out[222]:
  name       value_1
0  dd3  what, dd3 is
1  dd4  what, dd4 is
</code>```

Old answer:

you can create a helper DF:

```<code>In [181]: x = df.value_1.str.split('_', expand=True)

In [192]: x
Out[192]:
        0    1
0  what,    is
1  what,    is
</code>```

then insert a new column into it:

```<code>In [182]: x.insert(1, 'name', df['name'])
</code>```

which yields:

```<code>In [194]: x
Out[194]:
        0 name    1
0  what,   dd3   is
1  what,   dd4   is
</code>```

and replace the original column:

```<code>In [183]: df['value_1'] = x.sum(1)

In [184]: df
Out[184]:
  name       value_1
0  dd3  what, dd3 is
1  dd4  what, dd4 is
</code>```

Title: Replace character of column value with string from another column in Pandas

Body:
UPDATE: similar to @jezrael's solution, but it should be bit faster for larger data sets (vectorized approach):

In [221]: df['value_1'] = (df.groupby('name')['value_1']
                             .transform(lambda x: x.str.replace('_', x.name)))

In [222]: df
Out[222]:
  name       value_1
0  dd3  what, dd3 is
1  dd4  what, dd4 is

Old answer:

you can create a helper DF:

In [181]: x = df.value_1.str.split('_', expand=True)

In [192]: x
Out[192]:
        0    1
0  what,    is
1  what,    is

then insert a new column into it:

In [182]: x.insert(1, 'name', df['name'])

which yields:

In [194]: x
Out[194]:
        0 name    1
0  what,   dd3   is
1  what,   dd4   is

and replace the original column:

In [183]: df['value_1'] = x.sum(1)

In [184]: df
Out[184]:
  name       value_1
0  dd3  what, dd3 is
1  dd4  what, dd4 is


问:
Laravel 5: Store artisan console table output in a variable
In Laravel 5 console commands, you can output a table like so:

```<code>$this->table($headers, $tableData);
</code>```

This is described here:
https://laravel.com/docs/5.1/artisan#writing-output

However this outputs it straight to the console.

How can I store it in a variable without sending the data to the console.

答:
You could use output buffering to catch the output.</p>

```<code>ob_start();
$this->table($headers, $tableData);
$table = ob_get_flush();
</code>```

Body:
In Laravel 5 console commands, you can output a table like so:

$this->table($headers, $tableData);

This is described here:
https://laravel.com/docs/5.1/artisan#writing-output

However this outputs it straight to the console.

How can I store it in a variable without sending the data to the console.

Body:
You could use output buffering to catch the output.

ob_start();
$this->table($headers, $tableData);
$table = ob_get_flush();


问:
Background image not loading
I am new to html/css and I do not understand why my background image is not showing up. This is part of a simple test CSS sheet and HTML code for a simple site. I am trying to add a background-image and I have done this once and it worked and I do not know why it does not work now.</p>

```<code>.timeline{
    width: 100%;
    height: 400px;
    display: inline-flex;
    background-image:url("img/back.jpg");
}
</code>```

答:
This works. Asuming your file path is correct.

```<code>.timeline{
width: 100%;
height: 400px;
display: inline-flex;
</code>```

background-image: url(img/back.jpg);}

Title: Background image not loading

Body:
I am new to html/css and I do not understand why my background image is not showing up. This is part of a simple test CSS sheet and HTML code for a simple site. I am trying to add a background-image and I have done this once and it worked and I do not know why it does not work now.

.timeline{
    width: 100%;
    height: 400px;
    display: inline-flex;
    background-image:url("img/back.jpg");
}

Body:
This works. Asuming your file path is correct.

.timeline{
width: 100%;
height: 400px;
display: inline-flex;

background-image: url(img/back.jpg);}


问:
Raising event from base class
I understand that one can raise an event in the class that the implementation declaration occurs, but I wish to raise the event at the base class level and have the derived class's  event be raised:

```<code>public interface IFoo
{
    event EventHandler<FooEventArgs> FooValueChanged;
    void RaiseFooValueChanged(IFooView sender, FooEventArgs  e);
}

[TypeDescriptionProvider(typeof(FooBaseImplementor))]
public abstract class FooBase : Control, IFoo
{
    public virtual event EventHandler<FooEventArgs> FooValueChanged;

    public void RaiseFooValueChanged(IFooView sender, FooEventArgs e)
    {
        FooValueChanged(sender, e);
    }
}
</code>```

I cannot have the FooValueChanged event abstract, because then the base class cannot raise  the event. Current the code runs, but the call FooValueChanged(sender, e) throws a NullReferenceException because it doesn't call the derived class's event, only that of the base class.

Where am I going wrong?

I can have the event and the raiser both abstract, but then I need to remember to call FooValueChanged(sender, e) in every single derived class. I'm trying to avoid this while being able to use the Visual Studio designer for derived controls.

答:
Note first, the event declaration that you are using is a short-hand notation in C#:

```<code>public event EventHandler Event;
public void RaiseEvent() {
    this.Event(this, new EventArgs());
}
</code>```

Is equivalent to:

```<code>private EventHandler backEndStorage;
public event EventHandler Event {
    add { this.backEndStorage += value; }
    remove { this.backEndStorage -= value; }
}
public void RaiseEvent() {
    this.backEndStorage(this, new EventArgs());
}
</code>```

Where backEndStorage is a multi-cast delegate.

Now you can rewrite your code:

```<code>public interface IFoo
{
    event EventHandler<FooEventArgs> FooValueChanged;
    void RaiseFooValueChanged(IFooView sender, FooEventArgs  e);
}

[TypeDescriptionProvider(typeof(FooBaseImplementor))]
public abstract class FooBase : Control, IFoo
{
    protected event EventHandler<FooEventArgs> backEndStorage;
    public event EventHandler<FooEventArgs> FooValueChanged {
        add { this.backEndStorage += value; }
        remove { this.backEndStorage -= value; }
    }

    public void RaiseFooValueChanged(IFooView sender, FooEventArgs e)
    {
        this.backEndStorage(sender, e);
    }
}

public class FooDerived : FooBase {
    public event EventHandler<FooEventArgs> AnotherFooValueChanged {
        add { this.backEndStorage += value; }
        remove { this.backEndStorage -= value; }
    }
}
</code>```

So now when events are added on the derived class, they will actually be added to the backEndStorage of the base class, hence allowing the base class to call the delegates registered in the derived class.

OwnerDisplayName: vanslly

Title: Raising event from base class

Body:
I understand that one can raise an event in the class that the implementation declaration occurs, but I wish to raise the event at the base class level and have the derived class's  event be raised:

public interface IFoo
{
    event EventHandler<FooEventArgs> FooValueChanged;
    void RaiseFooValueChanged(IFooView sender, FooEventArgs  e);
}

[TypeDescriptionProvider(typeof(FooBaseImplementor))]
public abstract class FooBase : Control, IFoo
{
    public virtual event EventHandler<FooEventArgs> FooValueChanged;

    public void RaiseFooValueChanged(IFooView sender, FooEventArgs e)
    {
        FooValueChanged(sender, e);
    }
}

I cannot have the FooValueChanged event abstract, because then the base class cannot raise  the event. Current the code runs, but the call FooValueChanged(sender, e) throws a NullReferenceException because it doesn't call the derived class's event, only that of the base class.

Where am I going wrong?

I can have the event and the raiser both abstract, but then I need to remember to call FooValueChanged(sender, e) in every single derived class. I'm trying to avoid this while being able to use the Visual Studio designer for derived controls.

LastEditorDisplayName: vanslly

Body:
Note first, the event declaration that you are using is a short-hand notation in C#:

public event EventHandler Event;
public void RaiseEvent() {
    this.Event(this, new EventArgs());
}

Is equivalent to:

private EventHandler backEndStorage;
public event EventHandler Event {
    add { this.backEndStorage += value; }
    remove { this.backEndStorage -= value; }
}
public void RaiseEvent() {
    this.backEndStorage(this, new EventArgs());
}

Where backEndStorage is a multi-cast delegate.

Now you can rewrite your code:

public interface IFoo
{
    event EventHandler<FooEventArgs> FooValueChanged;
    void RaiseFooValueChanged(IFooView sender, FooEventArgs  e);
}

[TypeDescriptionProvider(typeof(FooBaseImplementor))]
public abstract class FooBase : Control, IFoo
{
    protected event EventHandler<FooEventArgs> backEndStorage;
    public event EventHandler<FooEventArgs> FooValueChanged {
        add { this.backEndStorage += value; }
        remove { this.backEndStorage -= value; }
    }

    public void RaiseFooValueChanged(IFooView sender, FooEventArgs e)
    {
        this.backEndStorage(sender, e);
    }
}

public class FooDerived : FooBase {
    public event EventHandler<FooEventArgs> AnotherFooValueChanged {
        add { this.backEndStorage += value; }
        remove { this.backEndStorage -= value; }
    }
}

So now when events are added on the derived class, they will actually be added to the backEndStorage of the base class, hence allowing the base class to call the delegates registered in the derived class.

OwnerDisplayName: earlNameless


答:
You can add the two foreign key using this:</p>

```<code>alter table game add foreign key game_hteam_id(hteam_id) references teams(id)
    , add foreign key game_vteam_id(vteam_id) references teams(id);
</code>```

Title: MySQL Multiple foreign keys pointing to same table

Body: I have a table called teams  and a table called games.   teams has id, name, .....    the games has id, hteam_id, vteam_id, loc, ....    I want the hteam_id and vteam_id to each be foreign key into the teams table.  How do you do it

Body:
You can add the two foreign key using this:

alter table game add foreign key game_hteam_id(hteam_id) references teams(id)
    , add foreign key game_vteam_id(vteam_id) references teams(id);


问:
How to read nested JSONs for aggregations?
I am new to Spark.
All I want to do is, read nested jsons and group them based on a certain condition.
For example: If the json contains details of a person like his city and zipcode. I would want to group the people who belong the same city and zipcode.

I have progressed till reading the jsons into DataSet.
But I am not knowing how to group them.

My Nested JSON format is

```<code>{
  "entity": {
    "name": "SJ",
    "id": 31
  },
  "hierarchy": {
    "state": "TN",
    "city": "CBE"
  },
  "data": {}}
</code>```

This is the code I have written to read the nested json from file.

```<code>public void groupJsonString(SparkSession spark) {
    Dataset<Row> studentRecordDS = spark.read()
            .option("timestampFormat", "yyyy/MM/dd HH:mm:ss ZZ")
            .json("/home/shiney/Documents/NGA/sparkJsonFiles/*.json");
    StructType st = studentRecordDS.schema();

    List<StructType> nestedList = new ArrayList<>();
    for(StructField field : st.fields()) {
        nestedList.add((StructType)field.dataType());
    }

}
</code>```

答:
TL;DR Use spark.read.json (as you did) followed by "flatten" operator in select.

(I use Scala and leaving converting to Java as your home exercise :))

Let's use the sample of yours.

```<code>$ cat ../datasets/sample.json
{
  "entity": {
    "name": "SJ",
    "id": 31
  },
  "hierarchy": {
    "state": "TN",
    "city": "CBE"
  },
  "data": {}
}
</code>```

The code could be as follows (again it's Scala).

```<code>val entities = spark
  .read
  .option("multiLine", true)
  .json("../datasets/sample.json")
scala> entities.printSchema
root
 |-- entity: struct (nullable = true)
 |    |-- id: long (nullable = true)
 |    |-- name: string (nullable = true)
 |-- hierarchy: struct (nullable = true)
 |    |-- city: string (nullable = true)
 |    |-- state: string (nullable = true)
</code>```

Let's flatten entity and hierarchy top-level columns.

```<code>scala> entities.select("entity.*", "hierarchy.*").show
+---+----+----+-----+
| id|name|city|state|
+---+----+----+-----+
| 31|  SJ| CBE|   TN|
+---+----+----+-----+
</code>```

Aggregation should be a no-brainer now.

Body:
I am new to Spark.
All I want to do is, read nested jsons and group them based on a certain condition.
For example: If the json contains details of a person like his city and zipcode. I would want to group the people who belong the same city and zipcode.

I have progressed till reading the jsons into DataSet.
But I am not knowing how to group them.

My Nested JSON format is

{
  "entity": {
    "name": "SJ",
    "id": 31
  },
  "hierarchy": {
    "state": "TN",
    "city": "CBE"
  },
  "data": {}}

This is the code I have written to read the nested json from file.

public void groupJsonString(SparkSession spark) {
    Dataset<Row> studentRecordDS = spark.read()
            .option("timestampFormat", "yyyy/MM/dd HH:mm:ss ZZ")
            .json("/home/shiney/Documents/NGA/sparkJsonFiles/*.json");
    StructType st = studentRecordDS.schema();

    List<StructType> nestedList = new ArrayList<>();
    for(StructField field : st.fields()) {
        nestedList.add((StructType)field.dataType());
    }

}

Body:
TL;DR Use spark.read.json (as you did) followed by "flatten" operator in select.

(I use Scala and leaving converting to Java as your home exercise :))

Let's use the sample of yours.

$ cat ../datasets/sample.json
{
  "entity": {
    "name": "SJ",
    "id": 31
  },
  "hierarchy": {
    "state": "TN",
    "city": "CBE"
  },
  "data": {}
}

The code could be as follows (again it's Scala).

val entities = spark
  .read
  .option("multiLine", true)
  .json("../datasets/sample.json")
scala> entities.printSchema
root
 |-- entity: struct (nullable = true)
 |    |-- id: long (nullable = true)
 |    |-- name: string (nullable = true)
 |-- hierarchy: struct (nullable = true)
 |    |-- city: string (nullable = true)
 |    |-- state: string (nullable = true)

Let's flatten entity and hierarchy top-level columns.

scala> entities.select("entity.*", "hierarchy.*").show
+---+----+----+-----+
| id|name|city|state|
+---+----+----+-----+
| 31|  SJ| CBE|   TN|
+---+----+----+-----+

Aggregation should be a no-brainer now.


问:
when i send a push notification while my app is running,my app crashes
When i send a push notification while my app is running,my app crashes (via fire base console), but works just fine when my app is closed or running in the background.

答:
There are 2 main ways of getting a push notification from fire base

1) When application is in foreground (application is running or opened)

2) When application is in background  (application is not running or closed)

In  first case if you send push notification from fire base console the notification message and custom data payload is received in
public void onMessageReceived(RemoteMessage remoteMessage)

In short when application is in foreground onMessageReceived method will trigger always , notification data must be handled inside this method.

In second case if u send push notification from fire base console the notification message is received in system tray
and you can receive the data payload in the bundle extras of the launcher activity of your application.


问:
Inner join on the same table and based on the sum column subtract the dates
I am developing a report in C# with SQL Server. I have a table that has some documents numbers (BrojDok), I have dates of that rows and a column Saldo that is based on a SUM of two columns (dug and pot).

Here is an example of that query:

```<code>SELECT
    tblFinansijskiPodaci.Firma,
    tblFinansijskiPodaci.Konto, tblFinansijskiPodaci.NazivKonta,
    tblFinansijskiPodaci.NazFirme, tblFinansijskiPodaci.BrojDok,
    tblFinansijskiPodaci.DatumVal, tblFinansijskiPodaci.Valuta,
    SUM(tblFinansijskiPodaci.Duguje) AS dug,
    SUM(tblFinansijskiPodaci.Potrazuje)AS pot,
    SUM(IIf([tblFinansijskiPodaci].[Konto] Like '2%',
    [tblFinansijskiPodaci].[Duguje] -[tblFinansijskiPodaci].[Potrazuje],
    [tblFinansijskiPodaci].[Potrazuje] -[tblFinansijskiPodaci].[Duguje])) AS Saldo
</code>```

The result is:

I need to join the table on BrojDok.

For an example, if BrojDok is 1728, column Saldo Should be 0. The same is with 1379.

After that I need a column that represents number of days based on this: if Saldo is less then 0,it should be 0,

If Saldo is between 0 and 1,Saldo should be the difference between dates in days of that BrojDok - for BrojDok 1728 it should be 2016-05-05 - 2016-05-04,

Or if Saldo is greater than 1,Saldo should be the difference between todays date and the date in the table.

I have tried with CTE and subqueries,but my SUM columns get all messed up.This is what I have in CTE:

```<code>; WITH CTE AS
(
    SELECT
        a.Firma, a.Konto, a.NazivKonta, a.BrojDok,
        SUM(a.Duguje) AS dugA,
        SUM(a.Potrazuje) AS potA,
        SUM(IIF(a.[Konto] LIKE '2%', a.[Duguje] - a.[Potrazuje], a.[Potrazuje] - a.[Duguje])) AS SaldoA,
        SUM(b.Duguje) AS dugB,
        SUM(b.Potrazuje)AS potB,
        SUM(IIf(b.[Konto] Like '2%',b.[Potrazuje] - b.[Duguje], b.[Potrazuje] - b.[Duguje])) AS SaldoB
    FROM
        tblFinansijskiPodaci a
    JOIN
        tblFinansijskiPodaci b ON b.BrojDok = a.BrojDok
    WHERE
        a.Firma = 1 AND a.Konto = 2040
        AND a.Partner = 1137 AND b.Firma = 1
        AND b.Konto = 2040 AND b.Partner = 1137
    GROUP BY
        a.Firma, a.NazFirme, a.Konto, a.NazivKonta, a.BrojDok, a.DatumVal, a.Valuta
)
SELECT
    Firma, Konto, NazivKonta,
    BrojDok, potA, dugA, potB, dugB,
    SaldoA, SaldoB, SaldoB - SaldoA AS SaldoTotal
FROM
    CTE
ORDER BY
    Firma
</code>```

and this is the result that I get:

I really don't know where to go from here..Can someone help?

this is something what I would want to get:

also if saldo is <0, then I would subtract the dates with the same BrojDok in the table

答:
After some time I have managed to find to answer.It was actually quite simple,I just made it complicated. When you do the inner join correctly,and use the right columns for the max and min dates,you get what you need.

This is my query that works:

```<code>SELECT S2.FinID,S2.Firma,S2.Konto,S2.Partner,S2.NazFirme,S2.NazivKonta,S2.BrojDok,
S2.Valuta,S2.DatumVal,S2.dug,S2.pot,S2.Saldo,S2.MaxDate,S2.MinDate,S2.Saldo,S2.SaldoTotal,
IIF(S2.SaldoTotal>1,1,0) AS KonacnoProba,
IIF(S2.SaldoTotal>1,1,IIF(S2.SaldoTotal>0,DATEDIFF(day,S2.MinDate,S2.MaxDate),
DATEDIFF(day,S2.DatumVal,GETDATE()))) AS KP1,IIF(S2.SaldoTotal<=0,0,
IIF(S2.SaldoTotal<1,DATEDIFF(day,S2.MinDate,S2.MaxDate),
DATEDIFF(day,S2.DatumVal,GETDATE()))) AS Konacno
FROM
   (
     SELECT S1.FinID,S1.Firma,S1.Konto,S1.Partner,S1.NazFirme,S1.NazivKonta,S1.BrojDok,
     S1.Valuta,S1.DatumVal,S1.dug,S1.pot,S1.Saldo,S1.MaxDate,S1.MinDate,
     SUM(S1.Saldo) OVER (PARTITION BY S1.BrojDok ORDER BY S1.FinID) AS SaldoTotal
     FROM
         (
          SELECT t1.FinID, t1.Firma,t1.Konto,t1.Partner,t1.NazFirme,t1.NazivKonta,
          t1.BrojDok,t1.Valuta, t1.DatumVal,Sum(t1.Duguje) AS dug,
          Sum(t1.Potrazuje) AS pot,
          Sum(IIf(t1.[Konto] Like '2%',t1.[Duguje] -t1.[Potrazuje],t1.[Potrazuje]
          -t1.[Duguje])) AS Saldo,
          MAX(t2.DatumVal) as MaxDate,MIN(t2.DatumVal) as MinDate
          FROM tblFinansijskiPodaci t1
          inner join tblFinansijskiPodaci t2 ON t1.BrojDok = t2.BrojDok
          WHERE t1.Firma = 1
          AND t1.Konto = 2040 AND t1.Partner = 1137 AND t2.Firma = 1 AND t2.Konto = 2040
          AND t2.Partner = 1137
          GROUP BY t1.FinID, t1.Firma,t1.Konto,t1.Partner,t1.NazivKonta,t1.NazFirme,
          t1.BrojDok,t1.Valuta,t1.DatumVal
         ) AS S1
  ) AS S2
</code>```

Body:
I am developing a report in C# with SQL Server. I have a table that has some documents numbers (BrojDok), I have dates of that rows and a column Saldo that is based on a SUM of two columns (dug and pot).

Here is an example of that query:

SELECT
    tblFinansijskiPodaci.Firma,
    tblFinansijskiPodaci.Konto, tblFinansijskiPodaci.NazivKonta,
    tblFinansijskiPodaci.NazFirme, tblFinansijskiPodaci.BrojDok,
    tblFinansijskiPodaci.DatumVal, tblFinansijskiPodaci.Valuta,
    SUM(tblFinansijskiPodaci.Duguje) AS dug,
    SUM(tblFinansijskiPodaci.Potrazuje)AS pot,
    SUM(IIf([tblFinansijskiPodaci].[Konto] Like '2%',
    [tblFinansijskiPodaci].[Duguje] -[tblFinansijskiPodaci].[Potrazuje],
    [tblFinansijskiPodaci].[Potrazuje] -[tblFinansijskiPodaci].[Duguje])) AS Saldo

The result is:

I need to join the table on BrojDok.

For an example, if BrojDok is 1728, column Saldo Should be 0. The same is with 1379.

After that I need a column that represents number of days based on this: if Saldo is less then 0,it should be 0,

If Saldo is between 0 and 1,Saldo should be the difference between dates in days of that BrojDok - for BrojDok 1728 it should be 2016-05-05 - 2016-05-04,

Or if Saldo is greater than 1,Saldo should be the difference between todays date and the date in the table.

I have tried with CTE and subqueries,but my SUM columns get all messed up.This is what I have in CTE:

; WITH CTE AS
(
    SELECT
        a.Firma, a.Konto, a.NazivKonta, a.BrojDok,
        SUM(a.Duguje) AS dugA,
        SUM(a.Potrazuje) AS potA,
        SUM(IIF(a.[Konto] LIKE '2%', a.[Duguje] - a.[Potrazuje], a.[Potrazuje] - a.[Duguje])) AS SaldoA,
        SUM(b.Duguje) AS dugB,
        SUM(b.Potrazuje)AS potB,
        SUM(IIf(b.[Konto] Like '2%',b.[Potrazuje] - b.[Duguje], b.[Potrazuje] - b.[Duguje])) AS SaldoB
    FROM
        tblFinansijskiPodaci a
    JOIN
        tblFinansijskiPodaci b ON b.BrojDok = a.BrojDok
    WHERE
        a.Firma = 1 AND a.Konto = 2040
        AND a.Partner = 1137 AND b.Firma = 1
        AND b.Konto = 2040 AND b.Partner = 1137
    GROUP BY
        a.Firma, a.NazFirme, a.Konto, a.NazivKonta, a.BrojDok, a.DatumVal, a.Valuta
)
SELECT
    Firma, Konto, NazivKonta,
    BrojDok, potA, dugA, potB, dugB,
    SaldoA, SaldoB, SaldoB - SaldoA AS SaldoTotal
FROM
    CTE
ORDER BY
    Firma

and this is the result that I get:

I really don't know where to go from here..Can someone help?

this is something what I would want to get:

also if saldo is <0, then I would subtract the dates with the same BrojDok in the table

Body:
After some time I have managed to find to answer.It was actually quite simple,I just made it complicated. When you do the inner join correctly,and use the right columns for the max and min dates,you get what you need.

This is my query that works:

SELECT S2.FinID,S2.Firma,S2.Konto,S2.Partner,S2.NazFirme,S2.NazivKonta,S2.BrojDok,
S2.Valuta,S2.DatumVal,S2.dug,S2.pot,S2.Saldo,S2.MaxDate,S2.MinDate,S2.Saldo,S2.SaldoTotal,
IIF(S2.SaldoTotal>1,1,0) AS KonacnoProba,
IIF(S2.SaldoTotal>1,1,IIF(S2.SaldoTotal>0,DATEDIFF(day,S2.MinDate,S2.MaxDate),
DATEDIFF(day,S2.DatumVal,GETDATE()))) AS KP1,IIF(S2.SaldoTotal<=0,0,
IIF(S2.SaldoTotal<1,DATEDIFF(day,S2.MinDate,S2.MaxDate),
DATEDIFF(day,S2.DatumVal,GETDATE()))) AS Konacno
FROM
   (
     SELECT S1.FinID,S1.Firma,S1.Konto,S1.Partner,S1.NazFirme,S1.NazivKonta,S1.BrojDok,
     S1.Valuta,S1.DatumVal,S1.dug,S1.pot,S1.Saldo,S1.MaxDate,S1.MinDate,
     SUM(S1.Saldo) OVER (PARTITION BY S1.BrojDok ORDER BY S1.FinID) AS SaldoTotal
     FROM
         (
          SELECT t1.FinID, t1.Firma,t1.Konto,t1.Partner,t1.NazFirme,t1.NazivKonta,
          t1.BrojDok,t1.Valuta, t1.DatumVal,Sum(t1.Duguje) AS dug,
          Sum(t1.Potrazuje) AS pot,
          Sum(IIf(t1.[Konto] Like '2%',t1.[Duguje] -t1.[Potrazuje],t1.[Potrazuje]
          -t1.[Duguje])) AS Saldo,
          MAX(t2.DatumVal) as MaxDate,MIN(t2.DatumVal) as MinDate
          FROM tblFinansijskiPodaci t1
          inner join tblFinansijskiPodaci t2 ON t1.BrojDok = t2.BrojDok
          WHERE t1.Firma = 1
          AND t1.Konto = 2040 AND t1.Partner = 1137 AND t2.Firma = 1 AND t2.Konto = 2040
          AND t2.Partner = 1137
          GROUP BY t1.FinID, t1.Firma,t1.Konto,t1.Partner,t1.NazivKonta,t1.NazFirme,
          t1.BrojDok,t1.Valuta,t1.DatumVal
         ) AS S1
  ) AS S2


问:
How to store image captured using camera.takePicture(null,null,mPicture) so that it can be displayed it in next activity?
I am making a custom camera application in android. I capture the image using

camera.takePicture(null,null,mPicture)" and "Camera.PictureCallBack()

I want to store the image taken from the camera so that I can display it in the next activity. How can it be done?

```<code>    Camera.PictureCallback mPicture = new Camera.PictureCallback() {

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        File pictureFile = getOutputMediaFile();
        if (pictureFile == null) {
            return;
        }
        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);

            fos.close();
        } catch (FileNotFoundException e) {

        } catch (IOException e) {
        }
    }
};

private static File getOutputMediaFile() {
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            "MyCameraApp");
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d("MyCameraApp", "failed to create directory");
            return null;
        }
    }
    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
            .format(new Date());
    File mediaFile;
    mediaFile = new File(mediaStorageDir.getPath() + File.separator
            + "IMG_" + timeStamp + ".jpg");

    return mediaFile;
}
</code>```

答:
Pass uri in extras of your next activity intent

```<code>public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == SELECT_PICTURE_USING_CAMERA) {
            try {
               Intent i = new Intent(FirstActivity.this, SecondActivity.class);
               i.putExtra("uri",outputFileUri);
               startActivity(i);
            } catch (Exception ex) {
                Log.e("Exception", ex.toString());
            }
        }
    }
}
</code>```

then retrieve image in your second activity

```<code>Uri = getIntent().getExtras("uri");

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;

final Bitmap capturedimage = BitmapFactory.decodeFile(uri, options);
imgPreview.setImageBitmap(capturedimage );
</code>```

Body:
I am making a custom camera application in android. I capture the image using

camera.takePicture(null,null,mPicture)" and "Camera.PictureCallBack()

I want to store the image taken from the camera so that I can display it in the next activity. How can it be done?

    Camera.PictureCallback mPicture = new Camera.PictureCallback() {

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        File pictureFile = getOutputMediaFile();
        if (pictureFile == null) {
            return;
        }
        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);

            fos.close();
        } catch (FileNotFoundException e) {

        } catch (IOException e) {
        }
    }
};

private static File getOutputMediaFile() {
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            "MyCameraApp");
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d("MyCameraApp", "failed to create directory");
            return null;
        }
    }
    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
            .format(new Date());
    File mediaFile;
    mediaFile = new File(mediaStorageDir.getPath() + File.separator
            + "IMG_" + timeStamp + ".jpg");

    return mediaFile;
}

Body:
Pass uri in extras of your next activity intent

public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == SELECT_PICTURE_USING_CAMERA) {
            try {
               Intent i = new Intent(FirstActivity.this, SecondActivity.class);
               i.putExtra("uri",outputFileUri);
               startActivity(i);
            } catch (Exception ex) {
                Log.e("Exception", ex.toString());
            }
        }
    }
}

then retrieve image in your second activity

Uri = getIntent().getExtras("uri");

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;

final Bitmap capturedimage = BitmapFactory.decodeFile(uri, options);
imgPreview.setImageBitmap(capturedimage );


问:
How can i update my table on server when i add new records in Mysql query browser on my locall pc?
I use Mysql query browser on my pc for data entry,appreciate that let me how can i update my table on server after enter new records in Mysql query browser? is there any way that we sync to table(on server and on client )and sending new records to server?

thanks

答:
It sounds as if you have 2 data stores - one local, and one remote. Your question doesn't explicitly state that you actually have 2 separate databases, only that you're using MySQL Query Browser. You mention the MySQL Query Browser is on your PC, but it's not clear which database(s) it's connecting to. Is it a local database? Remember: the MySQL Query Browser is just an application that connects to a MySQL database.

It sounds as if you're looking for replication between MySQL servers. You mention 'sending new records' to the 2nd server. Are you looking for delete & update operations to be synchronized as well? A bit more information/requirements are needed before deciding on a solution.

The MySQL docs on Replication will get you started on replication, if that's the solution you need. This assumes your database hosts are in a master-slave relationship. That is, there is one good copy of data, and the other is to be a mirror for the master.


问:
Java: Curious ImmutableList add
I don't understand this method implementation. It's

```<code>public static <T> List<T> add(List<T> list, T element) {
    final int size = list.size();
    if (size == 0) {
        return ImmutableList.of(element);
    } else if (list instanceof ImmutableList) {
        if (size == 1) {
            final T val = list.get(0);
            list = Lists.newArrayList();
            list.add(val);
        } else {
            list = Lists.newArrayList(list);
        }
    }
    list.add(element);
    return list;
}
</code>```

Why not a straightforward list.add(element)?

答:
The code is implementing adding to the list that's given. If the input list is an ImmutableList, it first creates a mutable list (since otherwise it can't add to it) and copies the elements to it. If it's not, it just uses the existing list.

It's a bit odd that it returns an ImmutableList if the list passed in is empty, but a (mutable) ArrayList if it's given a non-empty ImmutableList to add to, but perhaps that makes sense in the broader context of where and how it's used. But that inconsistency is definitely something I'd query in a code review.

Title: Java: Curious ImmutableList add

Body:
I don't understand this method implementation. It's

public static <T> List<T> add(List<T> list, T element) {
    final int size = list.size();
    if (size == 0) {
        return ImmutableList.of(element);
    } else if (list instanceof ImmutableList) {
        if (size == 1) {
            final T val = list.get(0);
            list = Lists.newArrayList();
            list.add(val);
        } else {
            list = Lists.newArrayList(list);
        }
    }
    list.add(element);
    return list;
}

Why not a straightforward list.add(element)?


问:
Add default values while merging tables in pandas
I'm reading two csv files with pandas.

```<code>df1= pd.read_csv('file_1.csv')
df2 = pd.read_csv('file_2.csv')
data =  pd.merge(df1, df2, on='id')
</code>```

The problem I'm facing is that the final data frame, data, has fewer rows since some id values are missing from both input files.What I'll like to do is to have a default value for all the cells in both cases, like:

```<code>data =  pd.merge(df1, df2, on='id',default_vaue=0)
</code>```

答:
You can use outer join and replace NaNs by 0:

Notice: All NaNs are replaced by 0, so NaNs in df1 or df2 are replaced too.

```<code>data = pd.merge(df1, df2, on='id',how='outer').fillna(0)
</code>```

Body:
I'm reading two csv files with pandas.

df1= pd.read_csv('file_1.csv')
df2 = pd.read_csv('file_2.csv')
data =  pd.merge(df1, df2, on='id')

The problem I'm facing is that the final data frame, data, has fewer rows since some id values are missing from both input files.What I'll like to do is to have a default value for all the cells in both cases, like:

data =  pd.merge(df1, df2, on='id',default_vaue=0)

Body:
You can use outer join and replace NaNs by 0:

Notice: All NaNs are replaced by 0, so NaNs in df1 or df2 are replaced too.

data = pd.merge(df1, df2, on='id',how='outer').fillna(0)


问:
Getting error while using dynamic SQL
I'm getting an error when I try to execute this statement

```<code>EXECUTE IMMEDIATE
               (   'CREATE TABLE DP.SD_NEW_TEST TABLESPACE DP_TS_TX_DATA INITRANS   10
                          PARTITION  BY RANGE (SALES_DATE)(
                          PARTITION  '''
                || Partition_name
                || ''' VALUES LESS THAN '''
                || MAX_DATET
                || ''' LOGGING
                        NOCOMPRESS
                        TABLESPACE DP_TS_TX_DATA INITRANS   10) AS SELECT * FROM DP.SALES_DATA WHERE 1=2'
</code>```

Here Partition_name,MAX_DATET values I'm fetching through other queries as part my procedure . Please suggest if i'm doing anything wrong here.

答:
I'm going to guess that the value of MAX_DATET is not formatted in an acceptable way. Basically you need to provide dates as a string with an appropriate data conversion.

The easier thing would be if MAX_DATET fitted the ANSI format, yyyy-mm-dd. Then all you would need is:

```<code>            || ''' VALUES LESS THAN date '''
            || MAX_DATET
            || ''' LOGGING
</code>```

Otherwise you'll need to code a to_date() call and provide the appropriate mask.

Dynamic SQL is hard, because it turns compilation errors into runtime errors. As the commenters say, sensible practice here would be to assemble the statement in a variable, which can be displayed through DBMS_OUTPUT. Debugging is always easier when we can see the code which is failing.

Title: Getting error while using dynamic SQL

Body:
I'm getting an error when I try to execute this statement

EXECUTE IMMEDIATE
               (   'CREATE TABLE DP.SD_NEW_TEST TABLESPACE DP_TS_TX_DATA INITRANS   10
                          PARTITION  BY RANGE (SALES_DATE)(
                          PARTITION  '''
                || Partition_name
                || ''' VALUES LESS THAN '''
                || MAX_DATET
                || ''' LOGGING
                        NOCOMPRESS
                        TABLESPACE DP_TS_TX_DATA INITRANS   10) AS SELECT * FROM DP.SALES_DATA WHERE 1=2'

Here Partition_name,MAX_DATET values I'm fetching through other queries as part my procedure . Please suggest if i'm doing anything wrong here.

Body:
I'm going to guess that the value of MAX_DATET is not formatted in an acceptable way. Basically you need to provide dates as a string with an appropriate data conversion.

The easier thing would be if MAX_DATET fitted the ANSI format, yyyy-mm-dd. Then all you would need is:

            || ''' VALUES LESS THAN date '''
            || MAX_DATET
            || ''' LOGGING

Otherwise you'll need to code a to_date() call and provide the appropriate mask.

Dynamic SQL is hard, because it turns compilation errors into runtime errors. As the commenters say, sensible practice here would be to assemble the statement in a variable, which can be displayed through DBMS_OUTPUT. Debugging is always easier when we can see the code which is failing.


问:
Joining 2 datasets in pandas

Hi everyone,
I'm having trouble joining 2 datatsets in Pandas. The 1st one contains how much each type of house was sold for in set month of the year, and the 2nd contains how many houses of each type were built in each year. I'm trying to combine the 2 in showing on each row: the year, the house type, an average price over the 12 months and how many houses of that type were built in that year. An issue is that years are shown in rows in the 1st dataset and columns in the 2nd, and i'm not sure how to deal with that. Another issue is trying to get the average price over the 12 months. I added a column at the end with average prices, but that included the year as well which is not good. Also, not sure how to get only the average price, without adding every single month to the dataset.
Any suggestions appreciated, thanks.

Dataset 1 contains sold houses:

```<code>Year type          Jan     Feb    Mar ... Dec
2016  Oakham       160000  165000
2016  Alvingham    155000  150000
2017  Oakham
2017  Alvingham
</code>```

Dataset 2 contains houses built:

```<code>               2015    2016    2017
Oakham          150     200     250
Alvingham        50      85
Chesam
</code>```

Expected output would be something like this:

```<code>YEAR    TYPE       AVERAGE PRICE       AMOUNT BUILT
2016    Oakham            175500                200
2017    Chesam            325000                 20
</code>```

答:
Here's one solution:

df1:

```<code>      Feb     Jan  Year       type
0  165000  160000  2016     Oakham
1  155000  150000  2016  Alvingham
2  165000  165000  2017     Oakham
3  165000  160000  2017  Alvingham
</code>```

df2:

```<code>           2015  2016  2017
Oakham      150   200   250
Alvingham    50    85    80
</code>```

First of all you have to calculate de average of price columns only:

df1['avg'] = df1.drop(['type', 'Year'], axis=1).mean(axis=1)
print(df1)

```<code>      Feb     Jan  Year       type       avg
0  165000  160000  2016     Oakham  162500.0
1  155000  150000  2016  Alvingham  152500.0
2  165000  165000  2017     Oakham  165000.0
3  165000  160000  2017  Alvingham  162500.0
</code>```

Now you just have to merge df1 with the unstacked version of df2:

```<code>df3 = pd.merge(left=df1[['type', 'Year', 'avg']],
               right=df2.unstack().reset_index(),
               left_on=['type', 'Year'],
               right_on=['level_1','level_0'])
</code>```

The output of print(df3) is:

```<code>        type  Year       avg  level_0    level_1    0
0     Oakham  2016  162500.0     2016     Oakham  200
1  Alvingham  2016  152500.0     2016  Alvingham   85
2     Oakham  2017  165000.0     2017     Oakham  250
3  Alvingham  2017  162500.0     2017  Alvingham   80
</code>```

Then you can drop unwanted columns and rename the others:

```<code>print(df3.drop(['level_0', 'level_1'],
                axis=1).rename(columns={0: 'AMOUNT BUILT',
                                        'avg': 'AVERAGE PRICE'}))
</code>```

The result is:

```<code>        type  Year  AVERAGE PRICE  AMOUNT BUILT
0     Oakham  2016       162500.0           200
1  Alvingham  2016       152500.0            85
2     Oakham  2017       165000.0           250
3  Alvingham  2017       162500.0            80
</code>```

Title: Joining 2 datasets in pandas

Body:
Hi everyone,
I'm having trouble joining 2 datatsets in Pandas. The 1st one contains how much each type of house was sold for in set month of the year, and the 2nd contains how many houses of each type were built in each year. I'm trying to combine the 2 in showing on each row: the year, the house type, an average price over the 12 months and how many houses of that type were built in that year. An issue is that years are shown in rows in the 1st dataset and columns in the 2nd, and i'm not sure how to deal with that. Another issue is trying to get the average price over the 12 months. I added a column at the end with average prices, but that included the year as well which is not good. Also, not sure how to get only the average price, without adding every single month to the dataset.
Any suggestions appreciated, thanks.

Dataset 1 contains sold houses:

Year type          Jan     Feb    Mar ... Dec
2016  Oakham       160000  165000
2016  Alvingham    155000  150000
2017  Oakham
2017  Alvingham

Dataset 2 contains houses built:

               2015    2016    2017
Oakham          150     200     250
Alvingham        50      85
Chesam

Expected output would be something like this:

YEAR    TYPE       AVERAGE PRICE       AMOUNT BUILT
2016    Oakham            175500                200
2017    Chesam            325000                 20

Body:
Here's one solution:

df1:

      Feb     Jan  Year       type
0  165000  160000  2016     Oakham
1  155000  150000  2016  Alvingham
2  165000  165000  2017     Oakham
3  165000  160000  2017  Alvingham

df2:

           2015  2016  2017
Oakham      150   200   250
Alvingham    50    85    80

First of all you have to calculate de average of price columns only:

df1['avg'] = df1.drop(['type', 'Year'], axis=1).mean(axis=1)
print(df1)

      Feb     Jan  Year       type       avg
0  165000  160000  2016     Oakham  162500.0
1  155000  150000  2016  Alvingham  152500.0
2  165000  165000  2017     Oakham  165000.0
3  165000  160000  2017  Alvingham  162500.0

Now you just have to merge df1 with the unstacked version of df2:

df3 = pd.merge(left=df1[['type', 'Year', 'avg']],
               right=df2.unstack().reset_index(),
               left_on=['type', 'Year'],
               right_on=['level_1','level_0'])

The output of print(df3) is:

        type  Year       avg  level_0    level_1    0
0     Oakham  2016  162500.0     2016     Oakham  200
1  Alvingham  2016  152500.0     2016  Alvingham   85
2     Oakham  2017  165000.0     2017     Oakham  250
3  Alvingham  2017  162500.0     2017  Alvingham   80

Then you can drop unwanted columns and rename the others:

print(df3.drop(['level_0', 'level_1'],
                axis=1).rename(columns={0: 'AMOUNT BUILT',
                                        'avg': 'AVERAGE PRICE'}))

The result is:

        type  Year  AVERAGE PRICE  AMOUNT BUILT
0     Oakham  2016       162500.0           200
1  Alvingham  2016       152500.0            85
2     Oakham  2017       165000.0           250
3  Alvingham  2017       162500.0            80


问:
Maven pull an old version of a transitive dependency
I've written a library I've written that depends upon Guava version 20.0 (the last version that is compatible with JDK 1.7)

I've then written an application that uses that library and also uk.org.lidalia:slf4j-test:1.2.0 (with test scope). slf4j-test has a dependency on version 14.0.1 of Guava.

My problem is that my application is seeing two different versions of Guava as transitive dependencies and picks the OLDER version. Now when I call certain methods in my Library I get Class or Method not found exceptions.

I can (and have) excluded Guava as a dependency of slf4j-test, which fixes the problem for now, but the problem will return if I introduce another dependency which uses Guava.

So my question is: Why would Maven pick the older version of a dependency and how do I always make it pick the latest versions.

答:
You cannot force Maven to always pick the latest version. But there are several things you can do:

If you declare the dependency in your own pom, this version always wins. So if you have a dependency on guava 20.0 in your pom, you will get exactly this.

If this is not suitable, you can put an entry into dependencyManagement which sets the version for guava. This will overwrite all transitively set versions (like the 14.0.1 in your example).

The Maven enforcer plugin has a rule that makes sure that all dependencies are evaluated to the latest version - but it does not pick that latest version, it only fails the build if it was not chosen. Then you need to choose it yourself by applying method (1) or (2) above.


问:
Swift passing method params Struct Decodable
,Swift 4 how can I pass Decodable Struct in method params and parse it in JSONDecoder()?
error:

Cannot invoke 'decode' with an argument list of type '(Decodable,
  from: Data)'

```<code>struct JsonRespons: Codable {
    let uid: String
    let msisdn: String
    let APK: String
    let fname: String
    let lname: String
}

struct JsonResponsError: Decodable {
    let uid: String
    let error: String
}

extension UIView {

func phoneAuth(serverApi path:String, jsonStruct:Codable){
    let jsonUrlString = Globals.JOSN_API_URL + path
    guard let url = URL(string: jsonUrlString) else {
        return

    }

    URLSession.shared.dataTask(with: url) { (data, response, err) in
        guard err == nil else {
            return
        }

        guard let data = data else { return }

        do {
            let result = try JSONDecoder().decode(jsonStruct.self, from: data)
            self.handleJsonResult(resalt: result as AnyObject)

        } catch let jsonErr {
            print("Error serializing json:", jsonErr)
        }

    }.resume()
}

    func handleJsonResult(resalt:AnyObject){
        print(resalt)
    }

}
</code>```

答:
Adding Codable to the inheritance list for Landmark triggers an automatic conformance that satisfies all of the protocol requirements from Encodable and Decodable:

You can Use Codable

```<code>struct Landmark: Codable {
    var name: String
    var foundingYear: Int

    // Landmark now supports the Codable methods init(from:) and encode(to:),
    // even though they aren't written as part of its declaration.
}
</code>```

Alternative solution is

```<code>func phoneAuth(serverApi path: String, Completion block: @escaping ((Data) -> ())) {

    URLSession.shared.dataTask(with: URL(string: url)!) { (data, res, err) in

        if let d = data {
            block(d)
        }
    }.resume()
}
</code>```

Call a Methods

```<code>phoneAuth(serverApi: "yourUrl") { (data) in

    do {
        let result = try JSONDecoder().decode(YourDecodable.self, from: data)
    } catch let jsonErr {
        print("Error serializing json:", jsonErr)
    }
}
</code>```

Body:
,Swift 4 how can I pass Decodable Struct in method params and parse it in JSONDecoder()?
error:

Cannot invoke 'decode' with an argument list of type '(Decodable,
  from: Data)'

struct JsonRespons: Codable {
    let uid: String
    let msisdn: String
    let APK: String
    let fname: String
    let lname: String
}

struct JsonResponsError: Decodable {
    let uid: String
    let error: String
}

extension UIView {

func phoneAuth(serverApi path:String, jsonStruct:Codable){
    let jsonUrlString = Globals.JOSN_API_URL + path
    guard let url = URL(string: jsonUrlString) else {
        return

    }

    URLSession.shared.dataTask(with: url) { (data, response, err) in
        guard err == nil else {
            return
        }

        guard let data = data else { return }

        do {
            let result = try JSONDecoder().decode(jsonStruct.self, from: data)
            self.handleJsonResult(resalt: result as AnyObject)

        } catch let jsonErr {
            print("Error serializing json:", jsonErr)
        }

    }.resume()
}

    func handleJsonResult(resalt:AnyObject){
        print(resalt)
    }

}

Body:
Adding Codable to the inheritance list for Landmark triggers an automatic conformance that satisfies all of the protocol requirements from Encodable and Decodable:

You can Use Codable

struct Landmark: Codable {
    var name: String
    var foundingYear: Int

    // Landmark now supports the Codable methods init(from:) and encode(to:),
    // even though they aren't written as part of its declaration.
}

Alternative solution is

func phoneAuth(serverApi path: String, Completion block: @escaping ((Data) -> ())) {

    URLSession.shared.dataTask(with: URL(string: url)!) { (data, res, err) in

        if let d = data {
            block(d)
        }
    }.resume()
}

Call a Methods

phoneAuth(serverApi: "yourUrl") { (data) in

    do {
        let result = try JSONDecoder().decode(YourDecodable.self, from: data)
    } catch let jsonErr {
        print("Error serializing json:", jsonErr)
    }
}

ContentLicense: CC BY-SA 4.0


问:
PHP filters combining into one SQL query
I'm trying to filter through my database according to filters done by visitors.

```<code>$query = "select * from Sheet1 where";

//filter query start
if (!empty($brand)) {
  $branddata = implode("','", $brand);
  //testing removing query
  $query .= " Brand in('$branddata') and";
}

if (!empty($model)) {
  $modeldata = implode("','", $model);
  //testing removing query
  $query .= " Model in('$modeldata') and";
}

/* if(!empty($model) && empty($brand)){

} */

if (!empty($spower) && !empty($epower)) {
  $query .= " Power>='$spower' and Power<='$epower' and";
}

if (!empty($sprice) && !empty($eprice)) {
  $query .= " Doors>='$sprice' and Doors<='$eprice'";
}

$rs = mysqli_query($conn, $query) or die("Error : " . mysqli_error($conn));
</code>```

The result I wish to get is a sql query that works and has correct syntax. Such as select * from Sheet1 where Doors>='$sprice' and Doors<='$eprice', if the visitor is filtering by price.

Currently, my code is made so that it simply adds a certain string to the variable. This means that if you don't filter by model, it skips model, because the model variable is empty. The problem comes to if you filter by power, the SQL will become select * from Sheet1 where Power>='$spower' and Power<='$epower' and. Obviously this doesn't work, so I need help in making the code make sure it works for every combination of filters.

答:
I would do it this way</p>

```<code>$filters=array();

if(!empty($brand)){
          $branddata =implode("','",$brand);
          //testing removing query
          $filters[]= " Brand in('$branddata')";
      }

if(!empty($model)){
          $modeldata =implode("','",$model);
          //testing removing query
          $filters[]= " Model in('$modeldata') and";
      }

  if(!empty($spower) && !empty($epower)){
          $filters[]= " Power>='$spower' and Power<='$epower' and";
      }

  if(!empty($sprice) && !empty($eprice)){
          $filters[]= " Doors>='$sprice' and Doors<='$eprice'";
      }

$query = "select * from Sheet1 where";

foreach ($filters as $filter) {
$query.=' AND '.$filter;

}

 $rs = mysqli_query($conn,$query) or die("Error : ".mysqli_error($conn));
</code>```

Body:
I'm trying to filter through my database according to filters done by visitors.

$query = "select * from Sheet1 where";

//filter query start
if (!empty($brand)) {
  $branddata = implode("','", $brand);
  //testing removing query
  $query .= " Brand in('$branddata') and";
}

if (!empty($model)) {
  $modeldata = implode("','", $model);
  //testing removing query
  $query .= " Model in('$modeldata') and";
}

/* if(!empty($model) && empty($brand)){

} */

if (!empty($spower) && !empty($epower)) {
  $query .= " Power>='$spower' and Power<='$epower' and";
}

if (!empty($sprice) && !empty($eprice)) {
  $query .= " Doors>='$sprice' and Doors<='$eprice'";
}

$rs = mysqli_query($conn, $query) or die("Error : " . mysqli_error($conn));

The result I wish to get is a sql query that works and has correct syntax. Such as select * from Sheet1 where Doors>='$sprice' and Doors<='$eprice', if the visitor is filtering by price.

Currently, my code is made so that it simply adds a certain string to the variable. This means that if you don't filter by model, it skips model, because the model variable is empty. The problem comes to if you filter by power, the SQL will become select * from Sheet1 where Power>='$spower' and Power<='$epower' and. Obviously this doesn't work, so I need help in making the code make sure it works for every combination of filters.

Body:
I would do it this way

$filters=array();

if(!empty($brand)){
          $branddata =implode("','",$brand);
          //testing removing query
          $filters[]= " Brand in('$branddata')";
      }

if(!empty($model)){
          $modeldata =implode("','",$model);
          //testing removing query
          $filters[]= " Model in('$modeldata') and";
      }

  if(!empty($spower) && !empty($epower)){
          $filters[]= " Power>='$spower' and Power<='$epower' and";
      }

  if(!empty($sprice) && !empty($eprice)){
          $filters[]= " Doors>='$sprice' and Doors<='$eprice'";
      }

$query = "select * from Sheet1 where";

foreach ($filters as $filter) {
$query.=' AND '.$filter;

}

 $rs = mysqli_query($conn,$query) or die("Error : ".mysqli_error($conn));