问:
How can I send https request with .p12 certificate on Objective-C or Swift
I have a react-native project and I have to create Native module for https request with .p12 certification but I never use Objective-C (it's a little complicated) or Swift
I found a class for https request with certification it is but I didn't use this cause I don't have a .h file and my project folder;

MyBridge.h

```<code>#import "React/RCTBridgeModule.h"

@interface MyFirstBridge : NSObject <RCTBridgeModule>

@end
</code>```

MyBridge.m

```<code>#import "MyFirstBridge.h"
#import <React/RCTLog.h>

@implementation MyFirstBridge

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(sendGetRequest:(NSString *)urllocation:(NSString *)location)
{
  NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"GET"];
[request setURL:[NSURL URLWithString:url]];

NSError *error = nil;
NSHTTPURLResponse *responseCode = nil;

NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];

 if([responseCode statusCode] != 200){
    NSLog(@"Error getting %@, HTTP status code %i", url, [responseCode statusCode]);
    return nil;
}

  callback(@[[NSNull null], [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding]]);
}

@end
</code>```

It works as basic HTTP get request but when I tried https service I need to pin a certificate for each request. How can I send a HTTPS request for this case?

答:
I guess by using .p12 certificate, you are referring to establishing a mutual authentication between the client and the server. Basically, you have to go through the following steps (objective-c):

Create security objects required to authenticate the server (verify its signature against the root CA signature) and authenticate the client (provide the client certificate to the server to verify its signature as well). Load a .cer file of the CA and a .p12 file of the client.

Define the URL resource you want to retrieve and create NSURLConnection

Specify the authentication methods you want to handle (using NSURLConnectionDelegate callbacks)

Handle the authentication challenge (using NSURLConnectionDelegate callbacks)

Load Cert files (root CA Cert of the server + client key and certificate)

rootCertRef contains the CA Certificate (root certificate of the CA that signed the server certificate)

identity (SecIdentityRef) contains the client key and certificate required to authenticate the client with the server.

```<code>NSData *rootCertData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@”rootCert” ofType:@”cer”]];
SecCertificateRef rootCertRef = SecCertificateCreateWithData(kCFAllocatorDefault, (CFDataRef) rootCertData);

NSData *p12Data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@“clientCert" ofType:@"p12"]];
NSArray *item = nil;
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@“password", kSecImportExportPassphrase, nil];
SecPKCS12Import((CFDataRef) p12Data , (CFDictionaryRef)dict, (CFArrayRef *)item);
SecIdentityRef identity = (SecIdentityRef)[[item objectAtIndex:0] objectForKey:(id)kSecImportItemIdentity];
</code>```

Configure the URL (you already did it)

```<code>// Create the request.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];
</code>```

Create NSURLConnection >> set the delegate to self that must implement NSURLConnectionDelegate to be able to do customer authentication

```<code>// Create url connection and fire request asynchronously
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
</code>```

Enable server and client authentication in callback canAuthenticateAgainstProtectionSpace

```<code>- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
  if([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust])
    return YES;
  if([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodClientCertificate])
    return YES;
  return NO;
}
</code>```

Perform the mutual authentication requested by the server

```<code>-(void) connection:didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {

  //Authenticate the server
  if([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust]) { // Verify method

    SecTrustRef trust = [[challenge protectionSpace] serverTrust];         // Create trust object
    NSArray *trustArray = [NSArray arrayWithObjects:rootCertRef, nil];   // Add as many certificates as needed
    SecTrustSetAnchorCertificates(trust, (CFArrayRef) trustArray );        // Set trust anchors

    SecTrustResultType trustResult;                                        // Store trust result in this
    SecTrustEvaluate(trust, trustResult);                                  // Evaluate server trust
    if(trust_result == kSecTrustResultUnspecified) {
      NSURLCredential *credential = [NSURLCredential credentialForTrust:trust];
      [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
  } else {
    // handle error;
  }

  //Send client identity to server for client authentication
  if([[challenge protectionSpace] authenticationMethod] isEqualToString:NSURLAuthenticationMethodClientCertificate]) {
    NSURLCredential *credential = [NSURLCredential credentialWithIdentity:identity certificates:nil   persistence:NSURLCredentialPersistenceNone];
    [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
  }
}
</code>```

Body:
I have a react-native project and I have to create Native module for https request with .p12 certification but I never use Objective-C (it's a little complicated) or Swift
I found a class for https request with certification it is but I didn't use this cause I don't have a .h file and my project folder;

MyBridge.h

#import "React/RCTBridgeModule.h"

@interface MyFirstBridge : NSObject <RCTBridgeModule>

@end

MyBridge.m

#import "MyFirstBridge.h"
#import <React/RCTLog.h>

@implementation MyFirstBridge

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(sendGetRequest:(NSString *)urllocation:(NSString *)location)
{
  NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"GET"];
[request setURL:[NSURL URLWithString:url]];

NSError *error = nil;
NSHTTPURLResponse *responseCode = nil;

NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];

 if([responseCode statusCode] != 200){
    NSLog(@"Error getting %@, HTTP status code %i", url, [responseCode statusCode]);
    return nil;
}

  callback(@[[NSNull null], [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding]]);
}

@end

It works as basic HTTP get request but when I tried https service I need to pin a certificate for each request. How can I send a HTTPS request for this case?

Body:
I guess by using .p12 certificate, you are referring to establishing a mutual authentication between the client and the server. Basically, you have to go through the following steps (objective-c):

Create security objects required to authenticate the server (verify its signature against the root CA signature) and authenticate the client (provide the client certificate to the server to verify its signature as well). Load a .cer file of the CA and a .p12 file of the client.

Define the URL resource you want to retrieve and create NSURLConnection

Specify the authentication methods you want to handle (using NSURLConnectionDelegate callbacks)

Handle the authentication challenge (using NSURLConnectionDelegate callbacks)

Load Cert files (root CA Cert of the server + client key and certificate)

rootCertRef contains the CA Certificate (root certificate of the CA that signed the server certificate)

identity (SecIdentityRef) contains the client key and certificate required to authenticate the client with the server.

NSData *rootCertData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@”rootCert” ofType:@”cer”]];
SecCertificateRef rootCertRef = SecCertificateCreateWithData(kCFAllocatorDefault, (CFDataRef) rootCertData);

NSData *p12Data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@“clientCert" ofType:@"p12"]];
NSArray *item = nil;
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@“password", kSecImportExportPassphrase, nil];
SecPKCS12Import((CFDataRef) p12Data , (CFDictionaryRef)dict, (CFArrayRef *)item);
SecIdentityRef identity = (SecIdentityRef)[[item objectAtIndex:0] objectForKey:(id)kSecImportItemIdentity];

Configure the URL (you already did it)

// Create the request.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];

Create NSURLConnection >> set the delegate to self that must implement NSURLConnectionDelegate to be able to do customer authentication

// Create url connection and fire request asynchronously
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

Enable server and client authentication in callback canAuthenticateAgainstProtectionSpace

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
  if([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust])
    return YES;
  if([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodClientCertificate])
    return YES;
  return NO;
}

Perform the mutual authentication requested by the server

-(void) connection:didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {

  //Authenticate the server
  if([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust]) { // Verify method

    SecTrustRef trust = [[challenge protectionSpace] serverTrust];         // Create trust object
    NSArray *trustArray = [NSArray arrayWithObjects:rootCertRef, nil];   // Add as many certificates as needed
    SecTrustSetAnchorCertificates(trust, (CFArrayRef) trustArray );        // Set trust anchors

    SecTrustResultType trustResult;                                        // Store trust result in this
    SecTrustEvaluate(trust, trustResult);                                  // Evaluate server trust
    if(trust_result == kSecTrustResultUnspecified) {
      NSURLCredential *credential = [NSURLCredential credentialForTrust:trust];
      [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
  } else {
    // handle error;
  }

  //Send client identity to server for client authentication
  if([[challenge protectionSpace] authenticationMethod] isEqualToString:NSURLAuthenticationMethodClientCertificate]) {
    NSURLCredential *credential = [NSURLCredential credentialWithIdentity:identity certificates:nil   persistence:NSURLCredentialPersistenceNone];
    [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
  }
}


来源: stackexchange

问:
Why jframe hides taskbar when maximized?
I'm using setUndecorated(true); and getRootPane().setWindowDecorationStyle(JRootPane.FRAME); in my jFrame. This works great but now when I maximized my frame it spreads all over the window even taskbar is not visible. What can I do to make frame not to hide taskbar?

Also when I maximize minimize my frame multiple times the cursor is changed to  this <-> which is generally used change size of frame when cursor is on the border of frame. Is there anything I can do for this?

A small code then can reproduce the thing:

```<code>import javax.swing.JFrame;
import javax.swing.JRootPane;
public class Demo extends JFrame {
    public Demo() {
        setSize(250,125);
        setUndecorated(true);
        getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
        setVisible(true);
    }
    public static void main(String[] args) {
        new Demo();
    }
}
</code>```

答:
Fortega answer worked however, some part is not needed (or no longer needed with Java 8):

The Rectangle does not need to be saved.

The code does not take into account dual screen configuration. In particular, the GraphicsConfiguration will change if the window change screen.

As far as I tested, the only required override is setExtendedState.

When factoring dual screen configuration, at least on Windows, the below code does not work as intended:

```<code>Rectangle maxBounds = new Rectangle(screenInsets.left + screenSize.x,
                                    screenInsets.top + screenSize.y,
                                    screenSize.x + screenSize.width - screenInsets.right - screenInsets.left,
                                    screenSize.y + screenSize.height - screenInsets.bottom - screenInsets.top);
</code>```

On the following dual screen set up:

Left screen 1920x1080 (not primary), position: -1920, 0

Right screen 1920x1080 (primary), position: 0, 0

The maxBounds will contains negative x (-1920) but the setMaximizedBounds is somehow expecting a coordinate in the screen space (where (x,y) starts at (0,0)) , not the virtual screen:

It will set to setMaximizedBounds(x=-1920,y=0,width=1920,height=1050)

Windows will see the window on the left screen (because I have one taskbar per screen showing only window on that screen) however the window won't be shown on the screen because it is off bounds.

If the resolution of the screen, or worse, its scale factor (with a laptop, Windows 10 will apply a scale factor, ex: 25%, making the screen "not so" 1920x1080), then the above code does not adapt. For example, if my configuration have 3 screens with the right most being the primary, the window will badly display on the left and middle screen. I don't think I fixed this in the below code.

The following code work on Windows, with dual screen:

```<code>  @Override
  public synchronized void setExtendedState(final int state) {
    if ((state & Frame.MAXIMIZED_BOTH) == Frame.MAXIMIZED_BOTH) {
      final GraphicsConfiguration cfg = getGraphicsConfiguration();
      final Insets screenInsets = getToolkit().getScreenInsets(cfg);
      final Rectangle screenBounds = cfg.getBounds();
      final int x = screenInsets.left + screenBounds.x * 0;
      final int y = screenInsets.top + screenBounds.y * 0;
      final int w = screenBounds.width - screenInsets.right - screenInsets.left;
      final int h = screenBounds.height - screenInsets.bottom - screenInsets.top;
      final Rectangle maximizedBounds = new Rectangle(x, y, w, h);

      System.out.println("cfg (" + cfg + ") screen.{bounds: " + screenBounds + ", insets: " + screenInsets + ", maxBounds: " + maximizedBounds);

      super.setMaximizedBounds(maximizedBounds);
    }
    super.setExtendedState(state);
  }
</code>```

On a simple JFrame:

Maximizing on the left screen ("screen=0") will print cfg (D3DGraphicsConfig[dev=D3DGraphicsDevice[screen=0],pixfmt=0]) screen.{bounds: java.awt.Rectangle[x=-1920,y=0,width=1920,height=1080], insets: java.awt.Insets[top=0,left=0,bottom=30,right=0], maxBounds: java.awt.Rectangle[x=0,y=0,width=1920,height=1050]

Maximizing on the right screen ("screen=1") will print cfg (D3DGraphicsConfig[dev=D3DGraphicsDevice[screen=1],pixfmt=0]) screen.{bounds: java.awt.Rectangle[x=0,y=0,width=1920,height=1080], insets: java.awt.Insets[top=0,left=0,bottom=30,right=0], maxBounds: java.awt.Rectangle[x=0,y=0,width=1920,height=1050]

ContentLicense: CC BY-SA 3.0

Body:
I'm using setUndecorated(true); and getRootPane().setWindowDecorationStyle(JRootPane.FRAME); in my jFrame. This works great but now when I maximized my frame it spreads all over the window even taskbar is not visible. What can I do to make frame not to hide taskbar?

Also when I maximize minimize my frame multiple times the cursor is changed to  this <-> which is generally used change size of frame when cursor is on the border of frame. Is there anything I can do for this?

A small code then can reproduce the thing:

import javax.swing.JFrame;
import javax.swing.JRootPane;
public class Demo extends JFrame {
    public Demo() {
        setSize(250,125);
        setUndecorated(true);
        getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
        setVisible(true);
    }
    public static void main(String[] args) {
        new Demo();
    }
}

Body:
Fortega answer worked however, some part is not needed (or no longer needed with Java 8):

The Rectangle does not need to be saved.

The code does not take into account dual screen configuration. In particular, the GraphicsConfiguration will change if the window change screen.

As far as I tested, the only required override is setExtendedState.

When factoring dual screen configuration, at least on Windows, the below code does not work as intended:

Rectangle maxBounds = new Rectangle(screenInsets.left + screenSize.x,
                                    screenInsets.top + screenSize.y,
                                    screenSize.x + screenSize.width - screenInsets.right - screenInsets.left,
                                    screenSize.y + screenSize.height - screenInsets.bottom - screenInsets.top);

On the following dual screen set up:

Left screen 1920x1080 (not primary), position: -1920, 0

Right screen 1920x1080 (primary), position: 0, 0

The maxBounds will contains negative x (-1920) but the setMaximizedBounds is somehow expecting a coordinate in the screen space (where (x,y) starts at (0,0)) , not the virtual screen:

It will set to setMaximizedBounds(x=-1920,y=0,width=1920,height=1050)

Windows will see the window on the left screen (because I have one taskbar per screen showing only window on that screen) however the window won't be shown on the screen because it is off bounds.

If the resolution of the screen, or worse, its scale factor (with a laptop, Windows 10 will apply a scale factor, ex: 25%, making the screen "not so" 1920x1080), then the above code does not adapt. For example, if my configuration have 3 screens with the right most being the primary, the window will badly display on the left and middle screen. I don't think I fixed this in the below code.

The following code work on Windows, with dual screen:

  @Override
  public synchronized void setExtendedState(final int state) {
    if ((state & Frame.MAXIMIZED_BOTH) == Frame.MAXIMIZED_BOTH) {
      final GraphicsConfiguration cfg = getGraphicsConfiguration();
      final Insets screenInsets = getToolkit().getScreenInsets(cfg);
      final Rectangle screenBounds = cfg.getBounds();
      final int x = screenInsets.left + screenBounds.x * 0;
      final int y = screenInsets.top + screenBounds.y * 0;
      final int w = screenBounds.width - screenInsets.right - screenInsets.left;
      final int h = screenBounds.height - screenInsets.bottom - screenInsets.top;
      final Rectangle maximizedBounds = new Rectangle(x, y, w, h);

      System.out.println("cfg (" + cfg + ") screen.{bounds: " + screenBounds + ", insets: " + screenInsets + ", maxBounds: " + maximizedBounds);

      super.setMaximizedBounds(maximizedBounds);
    }
    super.setExtendedState(state);
  }

On a simple JFrame:

Maximizing on the left screen ("screen=0") will print cfg (D3DGraphicsConfig[dev=D3DGraphicsDevice[screen=0],pixfmt=0]) screen.{bounds: java.awt.Rectangle[x=-1920,y=0,width=1920,height=1080], insets: java.awt.Insets[top=0,left=0,bottom=30,right=0], maxBounds: java.awt.Rectangle[x=0,y=0,width=1920,height=1050]

Maximizing on the right screen ("screen=1") will print cfg (D3DGraphicsConfig[dev=D3DGraphicsDevice[screen=1],pixfmt=0]) screen.{bounds: java.awt.Rectangle[x=0,y=0,width=1920,height=1080], insets: java.awt.Insets[top=0,left=0,bottom=30,right=0], maxBounds: java.awt.Rectangle[x=0,y=0,width=1920,height=1050]

ContentLicense: CC BY-SA 4.0


问:
how do I trigger the click event on AVRoutePickerView using swift
Using AVRoutePickerView, I'm able to do the Airplay programmatically upon tapping the Airplay icon.
Now I want, on viewDidLoad it should initialize the AVRoutePickerView and even tap the airplay icon (no need to manually tap on icon).

Here's my small piece of code to display Airplay icon on UIView

let routePV = AVRoutePickerView(frame: CGRect(x: 30.0, y: 150.0,
  width: 30.0, height: 30.0))
            routePV = UIColor.clear

  self.view.addSubview(routePV)

I'm really not sure how to trigger tap on viewdidload ?

Thanks

答:
This is possible. However I must caution it is likely to be quite unexpected behavior to present this interface without user interaction. I’d recommend only doing this as a direct result of the user intending to present this interface.

Make sure you have added it to your view hierarchy.

```<code>let routePickerView = AVRoutePickerView()
view.addSubview(routePickerView)
</code>```

If desired, you can hide it.

```<code>routePickerView.isHidden = true
</code>```

Then to present the route picker interface, trigger touchUpInside on its UIButton:

```<code>if let routePickerButton = routePickerView.subviews.first(where: { $0 is UIButton }) as? UIButton {
    routePickerButton.sendActions(for: .touchUpInside)
}
</code>```

Do note that this could stop working in a future iOS release.

Body:
This is possible. However I must caution it is likely to be quite unexpected behavior to present this interface without user interaction. I’d recommend only doing this as a direct result of the user intending to present this interface.

Make sure you have added it to your view hierarchy.

let routePickerView = AVRoutePickerView()
view.addSubview(routePickerView)

If desired, you can hide it.

routePickerView.isHidden = true

Then to present the route picker interface, trigger touchUpInside on its UIButton:

if let routePickerButton = routePickerView.subviews.first(where: { $0 is UIButton }) as? UIButton {
    routePickerButton.sendActions(for: .touchUpInside)
}

Do note that this could stop working in a future iOS release.


问:
How to iterate through a tuple or list of functions and operate on their return values?
I have been working on module that supposedly accepts a generic tuple of coupled equations spits out the solution. Initially I tested it on the specific system of equations I am interested in, and it worked wonderfully. But then I tested it on a simpler system just to see if I had really achieved a function that is generic.

It seems like in the instance that worked, I'm able to pull each function from the list, insert the arguments, and operate on the return value.

In the case where it doesn't work, it looks like Python is classifying my functions as "generators", something that I can't do arithmetic on...

This code is also my first attempt at using *args and **kwargs, which is exciting, but maybe there is some error there too...

I am a relatively new programmer, who has learned mostly from copying and pasting from documentation and forums until my code works. Please be kind. If my question is ill formed, let me know how I can ask a better question. If you answer, please do so in the context of my knowledge level (or provide links to documentation if there is something that I need to research to understand your answer)

The first snippet is the original function to solve the problem:

```<code># Below is the standard representation of RK4, generalized to any system
# ** init is the solution vector y_(n-1) from the previous step
#    used to solve for the solution at the next step, y_n.
# ** t is the previous time step
# ** dfuncs is the vector field dy/dt = f(t,y)

def RK4(init, t, dfuncs, h):
    k1 = [ h*f(*init,t) for f in dfuncs ]
    args = [ r+0.5*kr for r,kr in zip((*init,t),(*k1, h)) ]
    k2 = [ h*f(*args) for f in dfuncs ]
    args = [ r+0.5*kr for r,kr in zip((*init,t),(*k2, h)) ]
    k3 = [ h*f(*args) for f in dfuncs ]
    args = [ r+kr for r,kr in zip((*init,t),(*k3, h)) ]
    k4 =[ h*f(*args) for f in dfuncs ]
    return (r+(k1r+2*k2r+2*k3r+k4r)/6 for r,k1r,k2r,k3r,k4r in
            zip(init,k1, k2, k3, k4))
</code>```

Here is the code that the function worked well for:

```<code> #The following three functions represent the three ODEs in question
    # dB/Dt =
    def fx(B, S, E, t):
        return (r_b*B*(1 -  (B*(pow(T, 2)
                        + pow(E, 2)))/(K*S*pow(E, 2)))
                        - (beta*pow(B, 2))/(pow((alpha*S),2)
                        + pow(B, 2)))
    #dS/dt =
    def fy(B, S, E, t):
        return r_s*S*(1 - (S*K_e) / (E*K_s))

    # dE/dt =
    def fz(B, S, E, t):
        return r_e*E*(1 - E/K_e) - (P*B*pow(E, 2))/(S*(pow(T,2) + pow(E, 2)))

    # set parameter values from Ludwig paper
    r_b = 1.52
    r_s = 0.095
    r_e = 0.92
    alpha = 1.11
    beta = 43200
    K = 355
    K_s = 25440
    K_e = 1
    P = 0.00195
    T = 0.1
    t_0 = 0.
    t_n = 50.
    Dt = .5
    steps=int(np.floor((t_n - t_0) / Dt))

    # initialize solution vectors
    t = steps * [0.0]
    B = steps * [0.0]
    S = steps * [0.0]
    E = steps * [0.0]

    #Set initial conditions
    B[0],S[0],E[0],t[0] = 1e-16, .075*K_s, 1., 0.

    # Solve the system using RK4
    for i in range(1, steps):
        B[i],S[i],E[i] = RK4((B[i - 1], S[i - 1], E[i - 1]), t[i - 1], (fx, fy, fz), Dt)
</code>```

And here is the simpler system that it failed on:

```<code>def dy(y, z, t):
    return y
def dz(y, z, t):
    return pow(z, 2)

t0 = 0
tn = 10
y0 = 1
z0 = 0
Dt = 0.01
steps = int(np.floor((tn - t0) / Dt))

y = steps * [0.0]
z = steps * [0.0]
t = steps * [0.0]

y[0] = y0
z[0] = z0
t[0] = t0

for i in range(1, steps):
    y[i] = RK4((y[i-1], z[i-1]), t[i-1], (dy, dz), Dt)
</code>```

With traceback:

```<code>Traceback (most recent call last):
  File "C:/Users/wesle/PycharmProjects/Budworms/basic.py", line 27, in <module>
    y[i] = RK4((y[i-1], z[i-1]), t[i-1], (dy, dz), Dt)
  File "C:\Users\wesle\PycharmProjects\Budworms\RK4.py", line 23, in RK4
    k1 = [ h*f(*init,t) for f in dfuncs ]
  File "C:\Users\wesle\PycharmProjects\Budworms\RK4.py", line 23, in <listcomp>
    k1 = [ h*f(*init,t) for f in dfuncs ]
TypeError: unsupported operand type(s) for *: 'float' and 'generator'
</code>```

答:
In the non working example you did not assign z[i].  This resulted in y[i] being assigned the entire output, which is a generator.  On later iterations, this y[i] is evaluated in the context of a float multiplication, which is what the error says.  I believe all you need to do is add z[i] like:

```<code>y[i], z[i] = RK4((y[i - 1], z[i - 1]), t[i - 1], (dy, dz), Dt)
</code>```

Body:
I have been working on module that supposedly accepts a generic tuple of coupled equations spits out the solution. Initially I tested it on the specific system of equations I am interested in, and it worked wonderfully. But then I tested it on a simpler system just to see if I had really achieved a function that is generic.

It seems like in the instance that worked, I'm able to pull each function from the list, insert the arguments, and operate on the return value.

In the case where it doesn't work, it looks like Python is classifying my functions as "generators", something that I can't do arithmetic on...

This code is also my first attempt at using *args and **kwargs, which is exciting, but maybe there is some error there too...

I am a relatively new programmer, who has learned mostly from copying and pasting from documentation and forums until my code works. Please be kind. If my question is ill formed, let me know how I can ask a better question. If you answer, please do so in the context of my knowledge level (or provide links to documentation if there is something that I need to research to understand your answer)

The first snippet is the original function to solve the problem:

# Below is the standard representation of RK4, generalized to any system
# ** init is the solution vector y_(n-1) from the previous step
#    used to solve for the solution at the next step, y_n.
# ** t is the previous time step
# ** dfuncs is the vector field dy/dt = f(t,y)

def RK4(init, t, dfuncs, h):
    k1 = [ h*f(*init,t) for f in dfuncs ]
    args = [ r+0.5*kr for r,kr in zip((*init,t),(*k1, h)) ]
    k2 = [ h*f(*args) for f in dfuncs ]
    args = [ r+0.5*kr for r,kr in zip((*init,t),(*k2, h)) ]
    k3 = [ h*f(*args) for f in dfuncs ]
    args = [ r+kr for r,kr in zip((*init,t),(*k3, h)) ]
    k4 =[ h*f(*args) for f in dfuncs ]
    return (r+(k1r+2*k2r+2*k3r+k4r)/6 for r,k1r,k2r,k3r,k4r in
            zip(init,k1, k2, k3, k4))

Here is the code that the function worked well for:

 #The following three functions represent the three ODEs in question
    # dB/Dt =
    def fx(B, S, E, t):
        return (r_b*B*(1 -  (B*(pow(T, 2)
                        + pow(E, 2)))/(K*S*pow(E, 2)))
                        - (beta*pow(B, 2))/(pow((alpha*S),2)
                        + pow(B, 2)))
    #dS/dt =
    def fy(B, S, E, t):
        return r_s*S*(1 - (S*K_e) / (E*K_s))

    # dE/dt =
    def fz(B, S, E, t):
        return r_e*E*(1 - E/K_e) - (P*B*pow(E, 2))/(S*(pow(T,2) + pow(E, 2)))

    # set parameter values from Ludwig paper
    r_b = 1.52
    r_s = 0.095
    r_e = 0.92
    alpha = 1.11
    beta = 43200
    K = 355
    K_s = 25440
    K_e = 1
    P = 0.00195
    T = 0.1
    t_0 = 0.
    t_n = 50.
    Dt = .5
    steps=int(np.floor((t_n - t_0) / Dt))

    # initialize solution vectors
    t = steps * [0.0]
    B = steps * [0.0]
    S = steps * [0.0]
    E = steps * [0.0]

    #Set initial conditions
    B[0],S[0],E[0],t[0] = 1e-16, .075*K_s, 1., 0.

    # Solve the system using RK4
    for i in range(1, steps):
        B[i],S[i],E[i] = RK4((B[i - 1], S[i - 1], E[i - 1]), t[i - 1], (fx, fy, fz), Dt)

And here is the simpler system that it failed on:

def dy(y, z, t):
    return y
def dz(y, z, t):
    return pow(z, 2)

t0 = 0
tn = 10
y0 = 1
z0 = 0
Dt = 0.01
steps = int(np.floor((tn - t0) / Dt))

y = steps * [0.0]
z = steps * [0.0]
t = steps * [0.0]

y[0] = y0
z[0] = z0
t[0] = t0

for i in range(1, steps):
    y[i] = RK4((y[i-1], z[i-1]), t[i-1], (dy, dz), Dt)

With traceback:

Traceback (most recent call last):
  File "C:/Users/wesle/PycharmProjects/Budworms/basic.py", line 27, in <module>
    y[i] = RK4((y[i-1], z[i-1]), t[i-1], (dy, dz), Dt)
  File "C:\Users\wesle\PycharmProjects\Budworms\RK4.py", line 23, in RK4
    k1 = [ h*f(*init,t) for f in dfuncs ]
  File "C:\Users\wesle\PycharmProjects\Budworms\RK4.py", line 23, in <listcomp>
    k1 = [ h*f(*init,t) for f in dfuncs ]
TypeError: unsupported operand type(s) for *: 'float' and 'generator'

Body:
In the non working example you did not assign z[i].  This resulted in y[i] being assigned the entire output, which is a generator.  On later iterations, this y[i] is evaluated in the context of a float multiplication, which is what the error says.  I believe all you need to do is add z[i] like:

y[i], z[i] = RK4((y[i - 1], z[i - 1]), t[i - 1], (dy, dz), Dt)


问:
Turning invite code to url discord rewrite
I set up a command on my bot to pull active invites from servers but cant seem to turn the results into a url.

Ive tried to turn {invites} to {invites.url} and it did'nt seem to work

@commands.is_owner()
    @commands.command()
    async def fi(self, ctx, id: int):
        server = self.bot.get_guild(id)
        invites = await server.invites()
        fetching = await ctx.send("Fetching Invites...")
        await fetching.edit(content=f"All Active Invites Codes: \n {invites}")
        await asyncio.sleep(8)
        await fetching.delete()
        # Fetches invite codes
```

答:
Guild.invites returns a list of Invites, so you need to get the url attribute of each Invite individually.

```<code>invites = await server.invites()
invites = [invite.url for invite in invites]
invites_message = "\n".join(invites)
await fetching.edit(content=f"All Active Invites Codes: \n{invites_message}")
</code>```

Body:
Guild.invites returns a list of Invites, so you need to get the url attribute of each Invite individually.

invites = await server.invites()
invites = [invite.url for invite in invites]
invites_message = "\n".join(invites)
await fetching.edit(content=f"All Active Invites Codes: \n{invites_message}")


问:
How can I subtract two values based on their ID in Excel
I'm creating a table that reads the ID and Revenue from two separate sheets (Sheet1 - ID1, Revenue1 & Sheet2 - ID2, Revenue2) and have created a formula to compare revenues based on ID. How can I subtract Revenue1 from Revenue2 if they are different?

I've tried just subtracting Revenue1 from Revenue2 from the same row, however not all of the ID's match up in that row

Here's the formula so far:

```<code>=IFERROR(IF(VLOOKUP(Sheet2!C2, Sheet1!C:J, 8, FALSE)=Sheet2!J2,
 "Matches", "Doesn't Match"), 0)
</code>```

Where it says "Doesn't Match" is where I'd like the subtraction to happen.

答:
```<code>=IFERROR(IF(VLOOKUP(Sheet2!C2, Sheet1!C:J, 8, FALSE)=Sheet2!J2,
         "Matches", VLOOKUP(Sheet2!C2, Sheet1!C:J, 8, FALSE)-Sheet2!J2), 0)
</code>```

Body:
I'm creating a table that reads the ID and Revenue from two separate sheets (Sheet1 - ID1, Revenue1 & Sheet2 - ID2, Revenue2) and have created a formula to compare revenues based on ID. How can I subtract Revenue1 from Revenue2 if they are different?

I've tried just subtracting Revenue1 from Revenue2 from the same row, however not all of the ID's match up in that row

Here's the formula so far:

=IFERROR(IF(VLOOKUP(Sheet2!C2, Sheet1!C:J, 8, FALSE)=Sheet2!J2,
 "Matches", "Doesn't Match"), 0)

Where it says "Doesn't Match" is where I'd like the subtraction to happen.


问:
Associating tables using Room database in Android Studio
How can I associate two tables so that I can create a database that sort of matches the image attached.

I understand that the experiment ID, Date, Name has to be part of the parent table, with the Trial #, Variable, and Result be the child table associated to the parent table. However, I'm not very sure how to implement this in Room Database persistence using Entity and Dao. Can someone show me how?

I want the results to be that if the user selects the experiment in a recyclerview, it will be lead to another activity showing inputs of Variable and Result to add trials at the top while displaying the results of just that experiment below using a Recyclerview.

答:
I believe the following Working Example is one of the ways that you can achieve what you want.

The Code

The Experiment Entity (table) Experiment.java

```<code>@Entity
public class Experiment {

    @PrimaryKey(autoGenerate = true)
    private long experimentId;
    private String experimentName;
    private String experimentDate;

    public Experiment() {
    }

    @Ignore
    public Experiment(String name, String date) {
        this.experimentName = name;
        this.experimentDate = date;
    }

    public long getExperimentId() {
        return experimentId;
    }

    public void setExperimentId(long experimentId) {
        this.experimentId = experimentId;
    }

    public String getExperimentName() {
        return experimentName;
    }

    public void setExperimentName(String experimentName) {
        this.experimentName = experimentName;
    }

    public String getExperimentDate() {
        return experimentDate;
    }

    public void setExperimentDate(String experimentDate) {
        this.experimentDate = experimentDate;
    }
}
</code>```

Nothing special except perhaps the @Ignore'd constructor (for convenience)

The Trial Entity Trial.java

```<code>@Entity
public class Trial {

    @PrimaryKey(autoGenerate = true)
    private long trialId;
    @ForeignKey(entity = Experiment.class, parentColumns = {BaseColumns._ID},childColumns = "parentExperiment", onDelete = ForeignKey.CASCADE, onUpdate = ForeignKey.CASCADE)
    private long parentExperiment;
    private String trialVariable;
    private String trialResult;

    public Trial() {
    }

    @Ignore
    public Trial(long parentExperimentId, String variable, String result) {
        this.parentExperiment = parentExperimentId;
        this.trialVariable = variable;
        this.trialResult = result;
    }

    public long getTrialId() {
        return trialId;
    }

    public void setTrialId(long trialId) {
        this.trialId = trialId;
    }

    public long getParentExperiment() {
        return parentExperiment;
    }

    public void setParentExperiment(long parentExperiment) {
        this.parentExperiment = parentExperiment;
    }

    public String getTrialVariable() {
        return trialVariable;
    }

    public void setTrialVariable(String trialVariable) {
        this.trialVariable = trialVariable;
    }

    public String getTrialResult() {
        return trialResult;
    }

    public void setTrialResult(String trialResult) {
        this.trialResult = trialResult;
    }
}
</code>```

Nothing special except perhaps the @Ignore'd constructor (for convenience)

Dao.java (combined for convenience)

```<code>public interface Dao {

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    long[] insertExperiments(Experiment... experiments);

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    long insertExperiment(Experiment experiment);

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    long[] insertTrials(Trial... trials);

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    long insertTrial(Trial trial);

    @Update(onConflict = OnConflictStrategy.IGNORE)
    int updateExperiments(Experiment... experiments);

    @Update(onConflict = OnConflictStrategy.IGNORE)
    int updateExperiment(Experiment experiment);

    @Update(onConflict = OnConflictStrategy.IGNORE)
    int updateTrials(Trial... trials);

    @Update(onConflict = OnConflictStrategy.IGNORE)
    int updateTrial(Trial trial);

    @Delete
    int deleteExperiments(Experiment... experiments);

    @Delete
    int deleteExperiment(Experiment experiment);

    @Delete
    int deleteTrials(Trial... trials);

    @Delete
    int deleteTrial(Trial trial);

    @Query("SELECT * FROM Experiment")
    List<Experiment> getAllexperiments();

    @Query("SELECT * FROM Experiment WHERE experimentDate BETWEEN :startdate AND :enddate")
    List<Experiment> getExperimentsInDateRange(String startdate, String enddate);

    @Query("SELECT * FROM Trial")
    List<Trial> getAllTrials();

    @Query("SELECT * FROM Experiment JOIN Trial ON parentExperiment = experimentId")
    List<TrialWithExperiment> getExperimentsWithTrials();

    public class TrialWithExperiment {
        private long experimentId;
        private String experimentName;
        private String experimentDate;
        private long trialId;
        private String trialVariable;
        private String trialResult;

        public long getExperimentId() {
            return experimentId;
        }

        public void setExperimentId(long experimentId) {
            this.experimentId = experimentId;
        }

        public String getExperimentName() {
            return experimentName;
        }

        public void setExperimentName(String experimentName) {
            this.experimentName = experimentName;
        }

        public String getExperimentDate() {
            return experimentDate;
        }

        public void setExperimentDate(String experimentDate) {
            this.experimentDate = experimentDate;
        }

        public void setTrialId(long trialId) {
            this.trialId = trialId;
        }

        public long getTrialId() {
            return trialId;
        }

        public String getTrialVariable() {
            return trialVariable;
        }

        public void setTrialVariable(String trialVariable) {
            this.trialVariable = trialVariable;
        }

        public String getTrialResult() {
            return trialResult;
        }

        public void setTrialResult(String trialResult) {
            this.trialResult = trialResult;
        }
    }
}
</code>```

Note the TrialWithExperiment class, this defines a combination of a Trial and it's owning Experiment.

Note how column names are distinct e.g. no just id but experimentId and trialId differentiates them.

Note the last @Query getExperimentsWithTrials() this will return a list of Trials with their experiments.

The @Database ExperimentDatabase.java

```<code>@Database(entities = {Experiment.class, Trial.class}, version = 1,exportSchema = false)
public abstract class ExperimentDatabase extends RoomDatabase {
    public abstract Dao getDao();
}
</code>```

Finally an activity that utilises the above :-

```<code>public class MainActivity extends AppCompatActivity {

    ExperimentDatabase mDB;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mDB = Room.databaseBuilder(this,ExperimentDatabase.class,"experimentdb").allowMainThreadQueries().build();
        mDB.getDao().insertExperiments(new Experiment[]{
                new Experiment("Experiment 1","2019-01-01"),
                new Experiment("Experiment 2", "2019-02-01")
        });
        List<Experiment> experiments = mDB.getDao().getExperimentsInDateRange("2019-01-01","2019-12-31");
        for (Experiment e: experiments) {
            Log.d("EXPERIMENTS", "Experiment is " + e.getExperimentName() + " on " + e.getExperimentDate());
        }

        experiments = mDB.getDao().getAllexperiments();
        for (Experiment e: experiments) {
            Log.d("EXPERIMENTS", "Experiment is " + e.getExperimentName() + " on " + e.getExperimentDate());
        }

        for (Experiment e: experiments) {
            mDB.getDao().insertTrial(
                    new Trial(
                            e.getExperimentId(),
                            "Variable for " + e.getExperimentName(),
                            "Result for Experiment on " + e.getExperimentDate()
                    )
            );
        }

        List<Trial> trials = mDB.getDao().getAllTrials();
        for (Trial t: trials ) {
            Log.d("TRIAL ",
                    "Trial is for ExperimentID " + String.valueOf(t.getParentExperiment()) +
                            "\n\tVariable = " + t.getTrialVariable() +
                            "Result = " + t.getTrialResult()
            );
        }

        List<Dao.TrialWithExperiment> trialsWithExperiments = mDB.getDao().getExperimentsWithTrials();

        for (Dao.TrialWithExperiment te:trialsWithExperiments) {
            Log.d(
                    "TRIALWITHEXPERIMENT",
                    "Experiment Name = " + te.getExperimentName() +
                            "\n\tExperiment Date = " + te.getExperimentDate() +
                            "\n\t\tTrial Variable = " + te.getTrialVariable() +
                            "\n\t\tTrial Result = " + te.getTrialResult()
            );

        }
    }
}
</code>```

This :-

Adds 2 experiments (every run)

Retrieves Experiments in a date range (this assumes an SQLite recognised date format) and outputs them to the log.

Retrieves all Experiments and outputs them to the log.

Uses the List of experiments to add a Trial to each experiment.

Retrieves all Trials and outputs them to the log.

Retrieves all Trials along with the parent Experiment and outputs them to the log.

The Result

```<code>05-28 10:19:42.770 5750-5750/? D/EXPERIMENTS: Experiment is Experiment 1 on 2019-01-01
05-28 10:19:42.770 5750-5750/? D/EXPERIMENTS: Experiment is Experiment 2 on 2019-02-01
05-28 10:19:42.776 5750-5750/? D/EXPERIMENTS: Experiment is Experiment 1 on 2019-01-01
05-28 10:19:42.776 5750-5750/? D/EXPERIMENTS: Experiment is Experiment 2 on 2019-02-01
05-28 10:19:42.786 5750-5750/? D/TRIAL: Trial is for ExperimentID 1
      Variable = Variable for Experiment 1Result = Result for Experiment on 2019-01-01
05-28 10:19:42.786 5750-5750/? D/TRIAL: Trial is for ExperimentID 2
      Variable = Variable for Experiment 2Result = Result for Experiment on 2019-02-01
05-28 10:19:42.787 5750-5750/? D/TRIALWITHEXPERIMENT: Experiment Name = Experiment 1
      Experiment Date = 2019-01-01
          Trial Variable = Variable for Experiment 1
          Trial Result = Result for Experiment on 2019-01-01
05-28 10:19:42.787 5750-5750/? D/TRIALWITHEXPERIMENT: Experiment Name = Experiment 2
      Experiment Date = 2019-02-01
          Trial Variable = Variable for Experiment 2
          Trial Result = Result for Experiment on 2019-02-01
</code>```

Alternative/Additional

Another approach could be to utilise @Relation to create an object per Experiment that includes a list of the related/associated Trial(s) in that object.

Expanding upon the above then the following could be added to Dao.java

```<code>@Query("SELECT * FROM  Experiment")
List<ExperimentWithTrials> getExperimentsAndTrials();

class ExperimentWithTrials {
    private long experimentId;
    private String experimentName;
    private String experimentDate;
    @Relation(parentColumn = "experimentId", entityColumn = "parentExperiment")
    List<Trial> trials;

    public long getExperimentId() {
        return experimentId;
    }

    public void setExperimentId(long experimentId) {
        this.experimentId = experimentId;
    }

    public String getExperimentName() {
        return experimentName;
    }

    public void setExperimentName(String experimentName) {
        this.experimentName = experimentName;
    }

    public String getExperimentDate() {
        return experimentDate;
    }

    public void setExperimentDate(String experimentDate) {
        this.experimentDate = experimentDate;
    }

    public List<Trial> getTrials() {
        return trials;
    }

    public void setTrials(List<Trial> trials) {
        this.trials = trials;
    }
}
</code>```

and then the following could be added to MainActivity.java

```<code>    List<Dao.ExperimentWithTrials> experimentsWithTrials = mDB.getDao().getExperimentsAndTrials();
    for (Dao.ExperimentWithTrials et: experimentsWithTrials ) {
        Log.d(
                "EXPERIMENTANDTRIALS",
                "Experiment Name = " + et.getExperimentName() +
                        "\n\tExperiment Date = " + et.getExperimentDate()
        );
        for (Trial t: et.getTrials()) {
            Log.d(
                    "TRIALFOREXPERIMENT",
                    "\t\tVariable = " + t.getTrialVariable() +
                            "\n\t\tResult = " + t.getTrialResult()
            );
        }
    }
}
</code>```

Note how the Trials are obtained via the looping through the list of Trials embedded with the ExperimentWithTrials object, as opposed to the list of combined Experiment and Trial data from the previous.

This probably to purer OO way.

However, SQLite wise this appears to be cumbersome/inefficient as it appears to run multiple queries. One to get the Experiments and then another to get the underlying Trials for each experiment.

Resultant additional output

```<code>05-28 13:05:35.052 6524-6524/? D/EXPERIMENTANDTRIALS: Experiment Name = Experiment 1
      Experiment Date = 2019-01-01
05-28 13:05:35.052 6524-6524/? D/TRIALFOREXPERIMENT:      Variable = Variable for Experiment 1
          Result = Result for Experiment on 2019-01-01
05-28 13:05:35.052 6524-6524/? D/EXPERIMENTANDTRIALS: Experiment Name = Experiment 2
      Experiment Date = 2019-02-01
05-28 13:05:35.052 6524-6524/? D/TRIALFOREXPERIMENT:      Variable = Variable for Experiment 2
          Result = Result for Experiment on 2019-02-01
</code>```

Note that for convenience all of the above has been run on the main thread (i.e .allowMainThreadQueries() has been used). If you follow recommendations the all database access would be via another thread, in which case the @Transaction annotation is advised for queries.

Body:
I believe the following Working Example is one of the ways that you can achieve what you want.

The Code

The Experiment Entity (table) Experiment.java

@Entity
public class Experiment {

    @PrimaryKey(autoGenerate = true)
    private long experimentId;
    private String experimentName;
    private String experimentDate;

    public Experiment() {
    }

    @Ignore
    public Experiment(String name, String date) {
        this.experimentName = name;
        this.experimentDate = date;
    }

    public long getExperimentId() {
        return experimentId;
    }

    public void setExperimentId(long experimentId) {
        this.experimentId = experimentId;
    }

    public String getExperimentName() {
        return experimentName;
    }

    public void setExperimentName(String experimentName) {
        this.experimentName = experimentName;
    }

    public String getExperimentDate() {
        return experimentDate;
    }

    public void setExperimentDate(String experimentDate) {
        this.experimentDate = experimentDate;
    }
}

Nothing special except perhaps the @Ignore'd constructor (for convenience)

The Trial Entity Trial.java

@Entity
public class Trial {

    @PrimaryKey(autoGenerate = true)
    private long trialId;
    @ForeignKey(entity = Experiment.class, parentColumns = {BaseColumns._ID},childColumns = "parentExperiment", onDelete = ForeignKey.CASCADE, onUpdate = ForeignKey.CASCADE)
    private long parentExperiment;
    private String trialVariable;
    private String trialResult;

    public Trial() {
    }

    @Ignore
    public Trial(long parentExperimentId, String variable, String result) {
        this.parentExperiment = parentExperimentId;
        this.trialVariable = variable;
        this.trialResult = result;
    }

    public long getTrialId() {
        return trialId;
    }

    public void setTrialId(long trialId) {
        this.trialId = trialId;
    }

    public long getParentExperiment() {
        return parentExperiment;
    }

    public void setParentExperiment(long parentExperiment) {
        this.parentExperiment = parentExperiment;
    }

    public String getTrialVariable() {
        return trialVariable;
    }

    public void setTrialVariable(String trialVariable) {
        this.trialVariable = trialVariable;
    }

    public String getTrialResult() {
        return trialResult;
    }

    public void setTrialResult(String trialResult) {
        this.trialResult = trialResult;
    }
}

Nothing special except perhaps the @Ignore'd constructor (for convenience)

Dao.java (combined for convenience)

public interface Dao {

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    long[] insertExperiments(Experiment... experiments);

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    long insertExperiment(Experiment experiment);

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    long[] insertTrials(Trial... trials);

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    long insertTrial(Trial trial);

    @Update(onConflict = OnConflictStrategy.IGNORE)
    int updateExperiments(Experiment... experiments);

    @Update(onConflict = OnConflictStrategy.IGNORE)
    int updateExperiment(Experiment experiment);

    @Update(onConflict = OnConflictStrategy.IGNORE)
    int updateTrials(Trial... trials);

    @Update(onConflict = OnConflictStrategy.IGNORE)
    int updateTrial(Trial trial);

    @Delete
    int deleteExperiments(Experiment... experiments);

    @Delete
    int deleteExperiment(Experiment experiment);

    @Delete
    int deleteTrials(Trial... trials);

    @Delete
    int deleteTrial(Trial trial);

    @Query("SELECT * FROM Experiment")
    List<Experiment> getAllexperiments();

    @Query("SELECT * FROM Experiment WHERE experimentDate BETWEEN :startdate AND :enddate")
    List<Experiment> getExperimentsInDateRange(String startdate, String enddate);

    @Query("SELECT * FROM Trial")
    List<Trial> getAllTrials();

    @Query("SELECT * FROM Experiment JOIN Trial ON parentExperiment = experimentId")
    List<TrialWithExperiment> getExperimentsWithTrials();

    public class TrialWithExperiment {
        private long experimentId;
        private String experimentName;
        private String experimentDate;
        private long trialId;
        private String trialVariable;
        private String trialResult;

        public long getExperimentId() {
            return experimentId;
        }

        public void setExperimentId(long experimentId) {
            this.experimentId = experimentId;
        }

        public String getExperimentName() {
            return experimentName;
        }

        public void setExperimentName(String experimentName) {
            this.experimentName = experimentName;
        }

        public String getExperimentDate() {
            return experimentDate;
        }

        public void setExperimentDate(String experimentDate) {
            this.experimentDate = experimentDate;
        }

        public void setTrialId(long trialId) {
            this.trialId = trialId;
        }

        public long getTrialId() {
            return trialId;
        }

        public String getTrialVariable() {
            return trialVariable;
        }

        public void setTrialVariable(String trialVariable) {
            this.trialVariable = trialVariable;
        }

        public String getTrialResult() {
            return trialResult;
        }

        public void setTrialResult(String trialResult) {
            this.trialResult = trialResult;
        }
    }
}

Note the TrialWithExperiment class, this defines a combination of a Trial and it's owning Experiment.

Note how column names are distinct e.g. no just id but experimentId and trialId differentiates them.

Note the last @Query getExperimentsWithTrials() this will return a list of Trials with their experiments.

The @Database ExperimentDatabase.java

@Database(entities = {Experiment.class, Trial.class}, version = 1,exportSchema = false)
public abstract class ExperimentDatabase extends RoomDatabase {
    public abstract Dao getDao();
}

Finally an activity that utilises the above :-

public class MainActivity extends AppCompatActivity {

    ExperimentDatabase mDB;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mDB = Room.databaseBuilder(this,ExperimentDatabase.class,"experimentdb").allowMainThreadQueries().build();
        mDB.getDao().insertExperiments(new Experiment[]{
                new Experiment("Experiment 1","2019-01-01"),
                new Experiment("Experiment 2", "2019-02-01")
        });
        List<Experiment> experiments = mDB.getDao().getExperimentsInDateRange("2019-01-01","2019-12-31");
        for (Experiment e: experiments) {
            Log.d("EXPERIMENTS", "Experiment is " + e.getExperimentName() + " on " + e.getExperimentDate());
        }

        experiments = mDB.getDao().getAllexperiments();
        for (Experiment e: experiments) {
            Log.d("EXPERIMENTS", "Experiment is " + e.getExperimentName() + " on " + e.getExperimentDate());
        }

        for (Experiment e: experiments) {
            mDB.getDao().insertTrial(
                    new Trial(
                            e.getExperimentId(),
                            "Variable for " + e.getExperimentName(),
                            "Result for Experiment on " + e.getExperimentDate()
                    )
            );
        }

        List<Trial> trials = mDB.getDao().getAllTrials();
        for (Trial t: trials ) {
            Log.d("TRIAL ",
                    "Trial is for ExperimentID " + String.valueOf(t.getParentExperiment()) +
                            "\n\tVariable = " + t.getTrialVariable() +
                            "Result = " + t.getTrialResult()
            );
        }

        List<Dao.TrialWithExperiment> trialsWithExperiments = mDB.getDao().getExperimentsWithTrials();

        for (Dao.TrialWithExperiment te:trialsWithExperiments) {
            Log.d(
                    "TRIALWITHEXPERIMENT",
                    "Experiment Name = " + te.getExperimentName() +
                            "\n\tExperiment Date = " + te.getExperimentDate() +
                            "\n\t\tTrial Variable = " + te.getTrialVariable() +
                            "\n\t\tTrial Result = " + te.getTrialResult()
            );

        }
    }
}

This :-

Adds 2 experiments (every run)

Retrieves Experiments in a date range (this assumes an SQLite recognised date format) and outputs them to the log.

Retrieves all Experiments and outputs them to the log.

Uses the List of experiments to add a Trial to each experiment.

Retrieves all Trials and outputs them to the log.

Retrieves all Trials along with the parent Experiment and outputs them to the log.

The Result

05-28 10:19:42.770 5750-5750/? D/EXPERIMENTS: Experiment is Experiment 1 on 2019-01-01
05-28 10:19:42.770 5750-5750/? D/EXPERIMENTS: Experiment is Experiment 2 on 2019-02-01
05-28 10:19:42.776 5750-5750/? D/EXPERIMENTS: Experiment is Experiment 1 on 2019-01-01
05-28 10:19:42.776 5750-5750/? D/EXPERIMENTS: Experiment is Experiment 2 on 2019-02-01
05-28 10:19:42.786 5750-5750/? D/TRIAL: Trial is for ExperimentID 1
      Variable = Variable for Experiment 1Result = Result for Experiment on 2019-01-01
05-28 10:19:42.786 5750-5750/? D/TRIAL: Trial is for ExperimentID 2
      Variable = Variable for Experiment 2Result = Result for Experiment on 2019-02-01
05-28 10:19:42.787 5750-5750/? D/TRIALWITHEXPERIMENT: Experiment Name = Experiment 1
      Experiment Date = 2019-01-01
          Trial Variable = Variable for Experiment 1
          Trial Result = Result for Experiment on 2019-01-01
05-28 10:19:42.787 5750-5750/? D/TRIALWITHEXPERIMENT: Experiment Name = Experiment 2
      Experiment Date = 2019-02-01
          Trial Variable = Variable for Experiment 2
          Trial Result = Result for Experiment on 2019-02-01

Alternative/Additional

Another approach could be to utilise @Relation to create an object per Experiment that includes a list of the related/associated Trial(s) in that object.

Expanding upon the above then the following could be added to Dao.java

@Query("SELECT * FROM  Experiment")
List<ExperimentWithTrials> getExperimentsAndTrials();

class ExperimentWithTrials {
    private long experimentId;
    private String experimentName;
    private String experimentDate;
    @Relation(parentColumn = "experimentId", entityColumn = "parentExperiment")
    List<Trial> trials;

    public long getExperimentId() {
        return experimentId;
    }

    public void setExperimentId(long experimentId) {
        this.experimentId = experimentId;
    }

    public String getExperimentName() {
        return experimentName;
    }

    public void setExperimentName(String experimentName) {
        this.experimentName = experimentName;
    }

    public String getExperimentDate() {
        return experimentDate;
    }

    public void setExperimentDate(String experimentDate) {
        this.experimentDate = experimentDate;
    }

    public List<Trial> getTrials() {
        return trials;
    }

    public void setTrials(List<Trial> trials) {
        this.trials = trials;
    }
}

and then the following could be added to MainActivity.java

    List<Dao.ExperimentWithTrials> experimentsWithTrials = mDB.getDao().getExperimentsAndTrials();
    for (Dao.ExperimentWithTrials et: experimentsWithTrials ) {
        Log.d(
                "EXPERIMENTANDTRIALS",
                "Experiment Name = " + et.getExperimentName() +
                        "\n\tExperiment Date = " + et.getExperimentDate()
        );
        for (Trial t: et.getTrials()) {
            Log.d(
                    "TRIALFOREXPERIMENT",
                    "\t\tVariable = " + t.getTrialVariable() +
                            "\n\t\tResult = " + t.getTrialResult()
            );
        }
    }
}

Note how the Trials are obtained via the looping through the list of Trials embedded with the ExperimentWithTrials object, as opposed to the list of combined Experiment and Trial data from the previous.

This probably to purer OO way.

However, SQLite wise this appears to be cumbersome/inefficient as it appears to run multiple queries. One to get the Experiments and then another to get the underlying Trials for each experiment.

Resultant additional output

05-28 13:05:35.052 6524-6524/? D/EXPERIMENTANDTRIALS: Experiment Name = Experiment 1
      Experiment Date = 2019-01-01
05-28 13:05:35.052 6524-6524/? D/TRIALFOREXPERIMENT:      Variable = Variable for Experiment 1
          Result = Result for Experiment on 2019-01-01
05-28 13:05:35.052 6524-6524/? D/EXPERIMENTANDTRIALS: Experiment Name = Experiment 2
      Experiment Date = 2019-02-01
05-28 13:05:35.052 6524-6524/? D/TRIALFOREXPERIMENT:      Variable = Variable for Experiment 2
          Result = Result for Experiment on 2019-02-01

Note that for convenience all of the above has been run on the main thread (i.e .allowMainThreadQueries() has been used). If you follow recommendations the all database access would be via another thread, in which case the @Transaction annotation is advised for queries.


问:
Using edit message in a telegram bot
I'm trying to edit messages in a telegram bot.
I'm using the following code. I can send messages with no problem, but the edit message part doesn't work. It just doesn't do anything!!

```<code>   <?php

if ($_SERVER['HTTPS'] != "on") {
$url = "https://". $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
header("Location: $url");
exit;
}

$botToken="XXXX...";
$website="https://api.telegram.org/bot".$botToken;

$content = file_get_contents("php://input");
$update = json_decode($content, true);
$chatId = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];

switch($message) {
    case("action"):
                sendMessage($chatId, "What should I do?");
    break;

    case("add"):
        editMessageText($chatId, "should I add?");

    break;

default:
    sendMessage($chatId, "default");
}

function sendMessage($chatId, $message) {

$url = $GLOBALS[website]."/sendMessage?    chat_id=".$chatId."&text=".urlencode($message)."&reply_markup".$reply1;
file_get_contents($url);
}

function editMessageText($chatId, $messageId, $message) {

$url = $GLOBALS[website]."/editMessageText?chat_id=".$chatId."&message_id=".$messageId."&text=".urlencode($message);
file_get_contents($url);

}

function file_get_contents_curl($url) {
$ch = curl_init();

curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

$data = curl_exec($ch);
curl_close($ch);

return $data;
}

?>
</code>```

Any idea about what can be wrong with it?
Thanks

答:
The official Telegram docs say:

Please note, that it is currently only possible to edit messages without reply_markup or with inline keyboards.

You may be able to use the editMessageReplyMarkup API.

Title: Using edit message in a telegram bot

Body:
I'm trying to edit messages in a telegram bot.
I'm using the following code. I can send messages with no problem, but the edit message part doesn't work. It just doesn't do anything!!

   <?php

if ($_SERVER['HTTPS'] != "on") {
$url = "https://". $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
header("Location: $url");
exit;
}

$botToken="XXXX...";
$website="https://api.telegram.org/bot".$botToken;

$content = file_get_contents("php://input");
$update = json_decode($content, true);
$chatId = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];

switch($message) {
    case("action"):
                sendMessage($chatId, "What should I do?");
    break;

    case("add"):
        editMessageText($chatId, "should I add?");

    break;

default:
    sendMessage($chatId, "default");
}

function sendMessage($chatId, $message) {

$url = $GLOBALS[website]."/sendMessage?    chat_id=".$chatId."&text=".urlencode($message)."&reply_markup".$reply1;
file_get_contents($url);
}

function editMessageText($chatId, $messageId, $message) {

$url = $GLOBALS[website]."/editMessageText?chat_id=".$chatId."&message_id=".$messageId."&text=".urlencode($message);
file_get_contents($url);

}

function file_get_contents_curl($url) {
$ch = curl_init();

curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

$data = curl_exec($ch);
curl_close($ch);

return $data;
}

?>

Any idea about what can be wrong with it?
Thanks


问:
How do I set a number of retry attempts in RabbitMQ?
I am using RabbitMQ and I have a queue that holds email messages. My consumer service de-queues messages and attempts to send them. If, for any reason, my consumer cannot send the message, I would like to re-queue the message to send again.

I realize I can do a basicNack and set the requeue flag to be true, however, I don't want to requeue the message indefinitely (say, if our email system goes down, I don't want to continuously requeue unsent messages). I would like to define a finite number of times that I can requeue the message to be sent again.

I can't set a field on the email message object, however, when I dequeue it and send a nack. The updated field is not present on the message in the queue.

Is there any other way in which I can approach this?

答:
Although this is an old question I think you can now easily do this with the combination of dead letter exchanges and the x-death header array added once a message is dead lettered:

The dead-lettering process adds an array to the header of each dead-lettered message named x-death. This array contains an entry for each dead lettering event, identified by a pair of {queue, reason}. Each such entry is a table that consists of several fields:

queue: the name of the queue the message was in before it was
dead-lettered

reason: reason for dead lettering, see below

time: the date and time the message was dead lettered as a 64-bit AMQP 0-9-1 timestamp

exchange - the exchange the message was published to (note that this will be a dead letter exchange if the message is dead lettered
multiple times)

routing-keys: the routing keys (including CC keys but excluding BCC ones) the message was published with

count: how many times this message was dead-lettered in this queue for this reason

original-expiration (if the message was dead-letterered due to per-message TTL): the original expiration property of the message. The
expiration property is removed from the message on dead-lettering in
order to prevent it from expiring again in any queues it is routed to.

Read this great article for more info

Check this diagram:


问:
How to check specific elements of a list for a string value?
So im coding Tic Tac Toe

Ive created the environment as a list of 9 elements as shown below -

```<code>board=[' ']*9
</code>```

I then place the X or O in the board

```<code>board[move-1] = 'X'
</code>```

which works fine

The issue I'm having is after placing the X or O, im not able to check for the win condition. The output always returns as false check the output here

```<code>if (board[0] and board[1] and board[2] == 'X') or (board[0] and board[1] and board[2] == 'O') :
    return winner==1
</code>```

in the above code even when index 0,1 and 2 are X, it returns winner as false.

I think this is a simple string handling issue but I'm not really sure. Any help would be appreciated.

答:
To cover vertical, horizontal and diagonal, you can build a list of axis positions for each direction and check if any of them map to XXX or OOO:

```<code>axes = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)]
win = any(board[a]+board[b]+board[c] in ["XXX","OOO"] for a,b,c in axes)
</code>```

If you want to make the computer play the game, you can create a move rating function that analyzes each playable positions and returns a number corresponding to how good the position is.

Here's an example:

```<code>from random import sample
axes = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)]

def isWin(board):
    return any(board[a]+board[b]+board[c] in ["XXX","OOO"] for a,b,c in axes)

def rating(position,play,board,level=3**6): # 3**6=Invincible, 3**4=hard, 3**1=Easy
    if board[position] != " " or level < 3: return 0
    newBoard = board[:position]+[play]+board[position+1:]
    if isWin(newBoard): return level*2
    nextRatings = [rating(p,"XO"[play=="X"],newBoard,level/3) for p in range(9)]
    return level-max(nextRatings,key=abs)

while True:
    board = [" "]*9
    player,computer = sample("XOXO",2)
    while True:
        for r in range(0,9,3):
            print("("+") (".join(board[r:r+3])+")",list(range(r+1,r+4)))
        available = [str(p+1) for p in range(9) if board[p] == " "]
        if isWin(board) or not available : break
        player = "XO"[player=="X"]
        if player == computer:
            position = max(sample(range(9),9),key=lambda p:rating(p,computer,board))
            print(f"Computer plays {player} at {position+1}")
        else:
            while True:
                position = input(f"Position to play for {player}: ")
                if position not in available: print("Invalid position")
                else : position = int(position)-1; break
        board[position] = player
    print( f"{player}'s WIN !!!\n" if isWin(board) else "DRAW.\n")
</code>```

The rating() function goest through possible moves recursively returning a value that is smaller and smaller based on the number of moves needed to reach the end of game.  Each level's value is added or subtracted depending on which player's turn it is

Body:
So im coding Tic Tac Toe

Ive created the environment as a list of 9 elements as shown below -

board=[' ']*9

I then place the X or O in the board

board[move-1] = 'X'

which works fine

The issue I'm having is after placing the X or O, im not able to check for the win condition. The output always returns as false check the output here

if (board[0] and board[1] and board[2] == 'X') or (board[0] and board[1] and board[2] == 'O') :
    return winner==1

in the above code even when index 0,1 and 2 are X, it returns winner as false.

I think this is a simple string handling issue but I'm not really sure. Any help would be appreciated.

Body:
To cover vertical, horizontal and diagonal, you can build a list of axis positions for each direction and check if any of them map to XXX or OOO:

axes = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)]
win = any(board[a]+board[b]+board[c] in ["XXX","OOO"] for a,b,c in axes)

If you want to make the computer play the game, you can create a move rating function that analyzes each playable positions and returns a number corresponding to how good the position is.

Here's an example:

from random import sample
axes = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)]

def isWin(board):
    return any(board[a]+board[b]+board[c] in ["XXX","OOO"] for a,b,c in axes)

def rating(position,play,board,level=3**6): # 3**6=Invincible, 3**4=hard, 3**1=Easy
    if board[position] != " " or level < 3: return 0
    newBoard = board[:position]+[play]+board[position+1:]
    if isWin(newBoard): return level*2
    nextRatings = [rating(p,"XO"[play=="X"],newBoard,level/3) for p in range(9)]
    return level-max(nextRatings,key=abs)

while True:
    board = [" "]*9
    player,computer = sample("XOXO",2)
    while True:
        for r in range(0,9,3):
            print("("+") (".join(board[r:r+3])+")",list(range(r+1,r+4)))
        available = [str(p+1) for p in range(9) if board[p] == " "]
        if isWin(board) or not available : break
        player = "XO"[player=="X"]
        if player == computer:
            position = max(sample(range(9),9),key=lambda p:rating(p,computer,board))
            print(f"Computer plays {player} at {position+1}")
        else:
            while True:
                position = input(f"Position to play for {player}: ")
                if position not in available: print("Invalid position")
                else : position = int(position)-1; break
        board[position] = player
    print( f"{player}'s WIN !!!\n" if isWin(board) else "DRAW.\n")

The rating() function goest through possible moves recursively returning a value that is smaller and smaller based on the number of moves needed to reach the end of game.  Each level's value is added or subtracted depending on which player's turn it is


问:
Chain of promises in javascript with ajax calls
I have a function (f1) which I want to get called only after two ajax calls (say a1 and a2) are done. a2 should be called only after a1 is done. Following is the sequence of operation =

```<code>$.when(a1 and a2) {
   f1
}
</code>```

I tried the following code snippet -

```<code>$.when(a1a2()).done(function(){
  f1();
}

var a1a2 = function(){
  return $.when(a1()).done(function() {
    if (<check for a few variables a1 sets>) {
      // another ajax call for which f1 should wait
      return a2();
    } else {
      // random function for which f1 shouldn't wait
      f2();
    }
  });
}
</code>```

In the above code, f1 is waiting for a1 to finish but it is not waiting for a2 to finish.

I tried the following code snippet as well (but this also just waits for a1 to finish) -

```<code>var a1a2 = function(){
  var retVal = new Promise(function(){
    a1().then(function(){
      if (<check for a few variables a1 sets>) {
        return a2();
      } else {
        // random function for which f1 shouldn't wait
        f2();
      }
    });
  });
}
</code>```

I have looked at other similar questions but an not able to devise a solution. Can someone please help?

答:
First of all, your Promise code is faulty, because you're not creating a Promise correctly

```<code>new Promise(function(resolve, reject) {
    // in here you call resolve or reject otherwise Promise is forever pending
});
</code>```

However, since a1 returns a Promise (as do all the functions, I'm assuming) you don't need to create a promise

So, your code would be

```<code>a1()
.then(function() {
    if (somecondition == true) {
        return a2();
    } else {
        f2(); // since there's no return here, there's no "wait" for the promise f2 returns
    }
})
.then(function() {
    return f1();
})
</code>```

To illustrate the above, here's your code once with condition true, and then with condition false

Take note of the "time stamps" for the console output

// dummy code to set up some promises
const dummy = (x, d=1000) => {
    console.log(performance.now(), 'start', x);
    return new Promise(resolve => setTimeout(() => {
        console.log(performance.now(), 'end', x);
        resolve(x);
    }, d));
};

const a1 = () => dummy('a1');
const a2 = () => dummy('a2');
const f1 = () => dummy('f1');
const f2 = () => dummy('f2', 3000);

// end dummy code

console.log('wait for a2');
a1()
.then(function() {
    if (true) {
        return a2();
    } else {
        // random function for which f1 shouldn't wait
        f2();
    }
})
.then(function() {
    return f1();
})
.then(() => {
    console.log('dont wait for f2');
    a1()
    .then(function() {
        if (false) {
            return a2();
        } else {
            // random function for which f1 shouldn't wait
            f2();
        }
    })
    .then(function() {
        f1();
    });
});```

However! If f2 is a function that has no asynchrony then there is no way * to prevent f1 from being called after f2 finish - because that's how javascript works

* - I guess you could put it in a setTimeout, then f2 would execute after f1 begins (again, assuming f1 has some asynchrony, otherwise f2 would begin after f1 ends)

Body:
I have a function (f1) which I want to get called only after two ajax calls (say a1 and a2) are done. a2 should be called only after a1 is done. Following is the sequence of operation =

$.when(a1 and a2) {
   f1
}

I tried the following code snippet -

$.when(a1a2()).done(function(){
  f1();
}

var a1a2 = function(){
  return $.when(a1()).done(function() {
    if (<check for a few variables a1 sets>) {
      // another ajax call for which f1 should wait
      return a2();
    } else {
      // random function for which f1 shouldn't wait
      f2();
    }
  });
}

In the above code, f1 is waiting for a1 to finish but it is not waiting for a2 to finish.

I tried the following code snippet as well (but this also just waits for a1 to finish) -

var a1a2 = function(){
  var retVal = new Promise(function(){
    a1().then(function(){
      if (<check for a few variables a1 sets>) {
        return a2();
      } else {
        // random function for which f1 shouldn't wait
        f2();
      }
    });
  });
}

I have looked at other similar questions but an not able to devise a solution. Can someone please help?

Body:
First of all, your Promise code is faulty, because you're not creating a Promise correctly

new Promise(function(resolve, reject) {
    // in here you call resolve or reject otherwise Promise is forever pending
});

However, since a1 returns a Promise (as do all the functions, I'm assuming) you don't need to create a promise

So, your code would be

a1()
.then(function() {
    if (somecondition == true) {
        return a2();
    } else {
        f2(); // since there's no return here, there's no "wait" for the promise f2 returns
    }
})
.then(function() {
    return f1();
})

To illustrate the above, here's your code once with condition true, and then with condition false

Take note of the "time stamps" for the console output

// dummy code to set up some promises
const dummy = (x, d=1000) => {
    console.log(performance.now(), 'start', x);
    return new Promise(resolve => setTimeout(() => {
        console.log(performance.now(), 'end', x);
        resolve(x);
    }, d));
};

const a1 = () => dummy('a1');
const a2 = () => dummy('a2');
const f1 = () => dummy('f1');
const f2 = () => dummy('f2', 3000);

// end dummy code

console.log('wait for a2');
a1()
.then(function() {
    if (true) {
        return a2();
    } else {
        // random function for which f1 shouldn't wait
        f2();
    }
})
.then(function() {
    return f1();
})
.then(() => {
    console.log('dont wait for f2');
    a1()
    .then(function() {
        if (false) {
            return a2();
        } else {
            // random function for which f1 shouldn't wait
            f2();
        }
    })
    .then(function() {
        f1();
    });
});

However! If f2 is a function that has no asynchrony then there is no way * to prevent f1 from being called after f2 finish - because that's how javascript works

* - I guess you could put it in a setTimeout, then f2 would execute after f1 begins (again, assuming f1 has some asynchrony, otherwise f2 would begin after f1 ends)


问:
Long vector error when running Random Forest on small dataframe
I am trying to run a RandomForest on a dataset with 390343 rows in R with the randomForest package.I am getting this error :

Error in randomForest.default(m, y, ...) :
  long vectors (argument 24) are not supported in .Fortran

As my number of rows is very small comapred to 2^31, I am unable to figure out the cause of the error.

The summary of the data being used is :

```<code>summary(train1)
</code>```

I am running this on R version 3.0.2 (2013-09-25) on a 64 bit Windows server 2012 with 128 GB RAM and a Intel Xeon CPU(E5-2690 v2)

The command used to run the RF is

```<code>RFmod<-randomForest(Train_flag~., data=train1,ntree=3000,
                mtry=4,replace=TRUE,keep.forest=TRUE,importance=TRUE)
</code>```

答: Try using proximity = FALSE. When this parameter is set to TRUE, the algorithm computes the proximity matrix, which can be an issue when the dataframes are too big.

Body:
I am trying to run a RandomForest on a dataset with 390343 rows in R with the randomForest package.I am getting this error :

Error in randomForest.default(m, y, ...) :
  long vectors (argument 24) are not supported in .Fortran

As my number of rows is very small comapred to 2^31, I am unable to figure out the cause of the error.

The summary of the data being used is :

summary(train1)

I am running this on R version 3.0.2 (2013-09-25) on a 64 bit Windows server 2012 with 128 GB RAM and a Intel Xeon CPU(E5-2690 v2)

The command used to run the RF is

RFmod<-randomForest(Train_flag~., data=train1,ntree=3000,
                mtry=4,replace=TRUE,keep.forest=TRUE,importance=TRUE)


问:
Why does multimap allow duplicate key-value pairs?
EDIT: Please note, I'm NOT asking why multimap can't contain duplicate keys.

What's the rationale behind multimap allowing duplicate key-value pairs? (not keys)

```<code>#include <map>
#include <string>
#include <iostream>

int
main(int argc, char** argv)
{
    std::multimap<std::string, std::string> m;
    m.insert(std::make_pair("A", "B"));
    m.insert(std::make_pair("A", "B"));
    m.insert(std::make_pair("A", "C"));
    std::cout << m.size() << std::endl;
    return 0;
}
</code>```

This printed 3, which somewhat surprised me, I expected multimap to behave like a set of pairs, so I was expecting 2.

Intuitively, it's not consistent with C++ std::map behaviour, where insert does not always change the map (as opposed to operator[]).

Is there a rationale behind it, or it's just arbitrary?

答:
My reasoning is multimap is based on the Key lookup/insertion and not on the value. So whether the value on duplicate keys is the same or not does not play a part when elements are being inserted.

23.3.2 Class template multimap

1 A multimap is a kind of associative
  container that supports equivalent
  keys (possibly containing multiple
  copies of the same key value) and
  provides for fast retrieval of values
  of another type T based on the keys.

Body:
EDIT: Please note, I'm NOT asking why multimap can't contain duplicate keys.

What's the rationale behind multimap allowing duplicate key-value pairs? (not keys)

#include <map>
#include <string>
#include <iostream>

int
main(int argc, char** argv)
{
    std::multimap<std::string, std::string> m;
    m.insert(std::make_pair("A", "B"));
    m.insert(std::make_pair("A", "B"));
    m.insert(std::make_pair("A", "C"));
    std::cout << m.size() << std::endl;
    return 0;
}

This printed 3, which somewhat surprised me, I expected multimap to behave like a set of pairs, so I was expecting 2.

Intuitively, it's not consistent with C++ std::map behaviour, where insert does not always change the map (as opposed to operator[]).

Is there a rationale behind it, or it's just arbitrary?


问:
How can I kill all jobs of a user without logging out?
Currently, I use this command:

pkill -u username

But this also logs me out of the server.

How can I kill all the jobs belonging to a user without logging out?

答:
This is obsolete and unportable but works for me in debian.</p>

```<code>skill -u username
</code>```

Body:
This is obsolete and unportable but works for me in debian.

skill -u username