问:
How to get nested json data in an array and show in table view?
I have json like this
{

   "status":"Success",
   "code":"200",
   "menudetails":{

      "menu_id":"1001",
      "menuname":"Delux thali",
      "price":"$200.00",
      "bread":{

         "max":"1",
         "10":"Akki rotti",
         "11":"Sel roti"
      },
      "rice":{

         "max":"1",
         "14":"Jeera rice",
         "15":"Biryani",
         "16":"Fried rice"
      },
      "Vegitable":{

         "max":"2",
         "20":"Malai kofta",
         "21":"Shahi paneer",
         "22":"Palak paneer",
         "23":"Paneer do piaza"
      }
   },
   "message":"List of Tranasction",
   "Description":"List of Tranasction"
}
and i try to call this API

-(void)callApi  {

```<code>[SVProgressHUD showWithStatus:nil maskType:SVProgressHUDMaskTypeGradient];

NSMutableDictionary *finaljson = [NSMutableDictionary dictionary];

NSMutableDictionary *postParams = [NSMutableDictionary dictionary];
[postParams setObject:[NSNumber numberWithInt:kresto_id] forKey:@"resto_id"];
AppDelegate*apDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];

[postParams setObject:apDelegate.subCategoryID forKey:@"menu_id"];
NSMutableArray * arrjson = [NSMutableArray array];
[arrjson addObject:postParams];
[finaljson setObject:arrjson forKey:@"Data"];
//NSLog(@"Each time Signup postParam is = %@",finaljson);

NSError *error = nil;
NSData *postData = [NSJSONSerialization dataWithJSONObject:finaljson
                                                   options:kNilOptions
                                                     error:&error];
NSURL *url_request = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kBaseURL,kThaliDetail]];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url_request
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:60.0];

// HEADER...STARTS HERE .
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];

NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *  data, NSURLResponse * response, NSError * error) {

    if (error == nil) {  // success....

        NSError *jsonError;
        id response = [NSJSONSerialization JSONObjectWithData:data
                                                      options:kNilOptions
                                                        error:&jsonError];

        // get object after successful retrieving data !!!!
        dispatch_async(dispatch_get_main_queue(), ^{

            [SVProgressHUD dismiss];

            NSLog(@"output for Bussiness owner Login:%@",response);

            NSString* strStatus = [NSString stringWithFormat:@"%@",[response valueForKey:@"status"]];
            if ([strStatus isEqualToString:@"Success"])
            {

                array  = [ response valueForKey:@"menudetails"];
               // Ingrediant  = [ response valueForKey:@"menulist"];
                int currentCount = (int)array.count;
                NSLog(@"Scroll view coun = %d", currentCount);

                //tblView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;

                [tblView reloadData];

            }
            else
            {

            }
        });

    }else {
        // fail....
        [SVProgressHUD dismiss];
        NSLog(@"Error: %@",error);

        dispatch_async(dispatch_get_main_queue(), ^{
            //No network connectivity - This App requires an internet connection. Please enable the same to proceed

        });
    }

}];

[postDataTask resume];
</code>```

}

and table view code is

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

```<code>RestoCommonViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cellSubCategory"];

   [cell.lblSubcategoryName sizeToFit];

[cell.IngdntDiscription sizeToFit];

cell.lblSubcategoryName.text = [NSString stringWithFormat:@"%@",[[arayResponce objectAtIndex:indexPath.row] valueForKey:@"Vegitable"]];

cell.lblSubcategoryName.frame=CGRectMake(cell.lblSubcategoryName.frame.origin.x, cell.lblSubcategoryName.frame.origin.y, cell.lblSubcategoryName.frame.size.width,cell.lblSubcategoryName.frame.size.height);

cell.IngdntDiscription.text = [NSString stringWithFormat:@"%@",[[arayResponce objectAtIndex:indexPath.row] valueForKey:@"description"]];

cell.IngdntDiscription.frame=CGRectMake(20, 20, 20, 20);

cell.IngdntDiscription.frame=CGRectMake(cell.IngdntDiscription.frame.origin.x, cell.lblSubcategoryName.frame.origin.y+cell.lblSubcategoryName.frame.size.height, cell.IngdntDiscription.frame.size.width,cell.IngdntDiscription.frame.size.height);

cell.lblSubCategoryPrice.text = [NSString stringWithFormat:@"%@",[[arayResponce objectAtIndex:indexPath.row] valueForKey:@"price"]];
cell.btnIngredients.tag = indexPath.row;

return cell;
</code>```

答:
I don't know your base url,parameters.According to your output response

I created sample project.I form the same output which what you get from the response.I  get same response in my dictionary.From that I do the following thing.

First see my RestoCommonViewCell designing

Then

RestoCommonViewCell.h

```<code>#import <UIKit/UIKit.h>

@interface RestoCommonViewCell : UITableViewCell

@property (strong, nonatomic) IBOutlet UILabel *IngdntDiscription;
@property (strong, nonatomic) IBOutlet UILabel *lblSubCategoryPrice;
@property (strong, nonatomic) IBOutlet UILabel *lblSubcategoryName;
@end
</code>```

RestoCommonViewCell.m

```<code>#import "RestoCommonViewCell.h"

@implementation RestoCommonViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
</code>```

ViewController.h

```<code>#import <UIKit/UIKit.h>
#import "RestoCommonViewCell.h"

@interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>

@property (strong, nonatomic) IBOutlet UITableView *tblVwList;

@end
</code>```

ViewController.m

```<code>#import "ViewController.h"

@interface ViewController (){
    NSDictionary *dictJson;
    NSMutableArray *arrVeg;
}

@end

@implementation ViewController

@synthesize tblVwList;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    arrVeg = [[NSMutableArray alloc]init];
    dictJson = [[NSDictionary alloc]init];
    dictJson = @{
                    @"status": @"Success",
                    @"code": @"200",
                    @"menudetails" :
                    @{
                            @"menu_id": @"1001",
                            @"menuname": @"Delux thali",
                            @"price" : @"$200.00",
                            @"bread" :
                            @{
                                @"10": @"Akki rotti",
                                @"11": @"Sel roti",
                                @"max": @"1"
                            },
                            @"rice" :
                            @{
                                @"14": @"Jeera rice",
                                @"15": @"Biryani",
                                @"16": @"Fried rice",
                                @"max": @"1"
                            },
                            @"Vegitable" :
                            @{
                                @"20": @"Malai kofta",
                                @"21": @"Shahi paneer",
                                @"22": @"Palak paneer",
                                @"23": @"Paneer do piaza",
                                @"max": @"2"
                            }

                     },

                    @"message": @"List of Tranasction",
                    @"Description": @"List of Tranasction"
                };

    NSString *str20 = [[[dictJson objectForKey:@"menudetails"] objectForKey:@"Vegitable"] objectForKey:@"20"];
    NSString *str21 = [[[dictJson objectForKey:@"menudetails"] objectForKey:@"Vegitable"] objectForKey:@"21"];
    NSString *str22 = [[[dictJson objectForKey:@"menudetails"] objectForKey:@"Vegitable"] objectForKey:@"22"];
    NSString *str23 = [[[dictJson objectForKey:@"menudetails"] objectForKey:@"Vegitable"] objectForKey:@"23"];

    [arrVeg addObject:str20];
    [arrVeg addObject:str21];
    [arrVeg addObject:str22];
    [arrVeg addObject:str23];

    self.tblVwList.tableFooterView = [UIView new];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return arrVeg.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *CellIdentifier = @"cell";
    RestoCommonViewCell *cell = (RestoCommonViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil) {
        NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"RestoCommonViewCell" owner:nil options:nil];
        cell = [nibObjects objectAtIndex:0];

    }

    cell.lblSubcategoryName.text = arrVeg[indexPath.row];

    cell.IngdntDiscription.text = [NSString stringWithFormat:@"%@",[dictJson objectForKey:@"Description"]];

    cell.lblSubCategoryPrice.text = [NSString stringWithFormat:@"%@",[[dictJson objectForKey:@"menudetails"] objectForKey:@"price"]];

    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 150;
}

@end
</code>```

See the output below

Before you get the value from the Response using key, please post or paste your response in Online JSON Viewer text and view your response

I check your response in online json viewer and I get tree structured data.

First I copy and paste your response in text

Then I view the response.

Body:
I have json like this
{

   "status":"Success",
   "code":"200",
   "menudetails":{

      "menu_id":"1001",
      "menuname":"Delux thali",
      "price":"$200.00",
      "bread":{

         "max":"1",
         "10":"Akki rotti",
         "11":"Sel roti"
      },
      "rice":{

         "max":"1",
         "14":"Jeera rice",
         "15":"Biryani",
         "16":"Fried rice"
      },
      "Vegitable":{

         "max":"2",
         "20":"Malai kofta",
         "21":"Shahi paneer",
         "22":"Palak paneer",
         "23":"Paneer do piaza"
      }
   },
   "message":"List of Tranasction",
   "Description":"List of Tranasction"
}
and i try to call this API

-(void)callApi  {

[SVProgressHUD showWithStatus:nil maskType:SVProgressHUDMaskTypeGradient];

NSMutableDictionary *finaljson = [NSMutableDictionary dictionary];

NSMutableDictionary *postParams = [NSMutableDictionary dictionary];
[postParams setObject:[NSNumber numberWithInt:kresto_id] forKey:@"resto_id"];
AppDelegate*apDelegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];

[postParams setObject:apDelegate.subCategoryID forKey:@"menu_id"];
NSMutableArray * arrjson = [NSMutableArray array];
[arrjson addObject:postParams];
[finaljson setObject:arrjson forKey:@"Data"];
//NSLog(@"Each time Signup postParam is = %@",finaljson);

NSError *error = nil;
NSData *postData = [NSJSONSerialization dataWithJSONObject:finaljson
                                                   options:kNilOptions
                                                     error:&error];
NSURL *url_request = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kBaseURL,kThaliDetail]];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url_request
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:60.0];

// HEADER...STARTS HERE .
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];

NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *  data, NSURLResponse * response, NSError * error) {

    if (error == nil) {  // success....

        NSError *jsonError;
        id response = [NSJSONSerialization JSONObjectWithData:data
                                                      options:kNilOptions
                                                        error:&jsonError];

        // get object after successful retrieving data !!!!
        dispatch_async(dispatch_get_main_queue(), ^{

            [SVProgressHUD dismiss];

            NSLog(@"output for Bussiness owner Login:%@",response);

            NSString* strStatus = [NSString stringWithFormat:@"%@",[response valueForKey:@"status"]];
            if ([strStatus isEqualToString:@"Success"])
            {

                array  = [ response valueForKey:@"menudetails"];
               // Ingrediant  = [ response valueForKey:@"menulist"];
                int currentCount = (int)array.count;
                NSLog(@"Scroll view coun = %d", currentCount);

                //tblView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;

                [tblView reloadData];

            }
            else
            {

            }
        });

    }else {
        // fail....
        [SVProgressHUD dismiss];
        NSLog(@"Error: %@",error);

        dispatch_async(dispatch_get_main_queue(), ^{
            //No network connectivity - This App requires an internet connection. Please enable the same to proceed

        });
    }

}];

[postDataTask resume];

}

and table view code is

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

RestoCommonViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cellSubCategory"];

   [cell.lblSubcategoryName sizeToFit];

[cell.IngdntDiscription sizeToFit];

cell.lblSubcategoryName.text = [NSString stringWithFormat:@"%@",[[arayResponce objectAtIndex:indexPath.row] valueForKey:@"Vegitable"]];

cell.lblSubcategoryName.frame=CGRectMake(cell.lblSubcategoryName.frame.origin.x, cell.lblSubcategoryName.frame.origin.y, cell.lblSubcategoryName.frame.size.width,cell.lblSubcategoryName.frame.size.height);

cell.IngdntDiscription.text = [NSString stringWithFormat:@"%@",[[arayResponce objectAtIndex:indexPath.row] valueForKey:@"description"]];

cell.IngdntDiscription.frame=CGRectMake(20, 20, 20, 20);

cell.IngdntDiscription.frame=CGRectMake(cell.IngdntDiscription.frame.origin.x, cell.lblSubcategoryName.frame.origin.y+cell.lblSubcategoryName.frame.size.height, cell.IngdntDiscription.frame.size.width,cell.IngdntDiscription.frame.size.height);

cell.lblSubCategoryPrice.text = [NSString stringWithFormat:@"%@",[[arayResponce objectAtIndex:indexPath.row] valueForKey:@"price"]];
cell.btnIngredients.tag = indexPath.row;

return cell;

Body:
I don't know your base url,parameters.According to your output response

I created sample project.I form the same output which what you get from the response.I  get same response in my dictionary.From that I do the following thing.

First see my RestoCommonViewCell designing

Then

RestoCommonViewCell.h

#import <UIKit/UIKit.h>

@interface RestoCommonViewCell : UITableViewCell

@property (strong, nonatomic) IBOutlet UILabel *IngdntDiscription;
@property (strong, nonatomic) IBOutlet UILabel *lblSubCategoryPrice;
@property (strong, nonatomic) IBOutlet UILabel *lblSubcategoryName;
@end

RestoCommonViewCell.m

#import "RestoCommonViewCell.h"

@implementation RestoCommonViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end

ViewController.h

#import <UIKit/UIKit.h>
#import "RestoCommonViewCell.h"

@interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>

@property (strong, nonatomic) IBOutlet UITableView *tblVwList;

@end

ViewController.m

#import "ViewController.h"

@interface ViewController (){
    NSDictionary *dictJson;
    NSMutableArray *arrVeg;
}

@end

@implementation ViewController

@synthesize tblVwList;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    arrVeg = [[NSMutableArray alloc]init];
    dictJson = [[NSDictionary alloc]init];
    dictJson = @{
                    @"status": @"Success",
                    @"code": @"200",
                    @"menudetails" :
                    @{
                            @"menu_id": @"1001",
                            @"menuname": @"Delux thali",
                            @"price" : @"$200.00",
                            @"bread" :
                            @{
                                @"10": @"Akki rotti",
                                @"11": @"Sel roti",
                                @"max": @"1"
                            },
                            @"rice" :
                            @{
                                @"14": @"Jeera rice",
                                @"15": @"Biryani",
                                @"16": @"Fried rice",
                                @"max": @"1"
                            },
                            @"Vegitable" :
                            @{
                                @"20": @"Malai kofta",
                                @"21": @"Shahi paneer",
                                @"22": @"Palak paneer",
                                @"23": @"Paneer do piaza",
                                @"max": @"2"
                            }

                     },

                    @"message": @"List of Tranasction",
                    @"Description": @"List of Tranasction"
                };

    NSString *str20 = [[[dictJson objectForKey:@"menudetails"] objectForKey:@"Vegitable"] objectForKey:@"20"];
    NSString *str21 = [[[dictJson objectForKey:@"menudetails"] objectForKey:@"Vegitable"] objectForKey:@"21"];
    NSString *str22 = [[[dictJson objectForKey:@"menudetails"] objectForKey:@"Vegitable"] objectForKey:@"22"];
    NSString *str23 = [[[dictJson objectForKey:@"menudetails"] objectForKey:@"Vegitable"] objectForKey:@"23"];

    [arrVeg addObject:str20];
    [arrVeg addObject:str21];
    [arrVeg addObject:str22];
    [arrVeg addObject:str23];

    self.tblVwList.tableFooterView = [UIView new];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return arrVeg.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *CellIdentifier = @"cell";
    RestoCommonViewCell *cell = (RestoCommonViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil) {
        NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"RestoCommonViewCell" owner:nil options:nil];
        cell = [nibObjects objectAtIndex:0];

    }

    cell.lblSubcategoryName.text = arrVeg[indexPath.row];

    cell.IngdntDiscription.text = [NSString stringWithFormat:@"%@",[dictJson objectForKey:@"Description"]];

    cell.lblSubCategoryPrice.text = [NSString stringWithFormat:@"%@",[[dictJson objectForKey:@"menudetails"] objectForKey:@"price"]];

    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 150;
}

@end

See the output below

Before you get the value from the Response using key, please post or paste your response in Online JSON Viewer text and view your response

I check your response in online json viewer and I get tree structured data.

First I copy and paste your response in text

Then I view the response.


来源: stackexchange

问:
Complex and long single-job Jenkins Job Pipeline Builds: There yet?

TL;DR

Does it make sense to have one single Jenking Job Pipeline job for a full long-running deployment / "build" chain in the free Jenkins, given that resumable checkpoints are not available?

Prelude

I'm looking at the current incarnation of Jenkins' the open/free Pipeline Bundle.

I'll note that I think that what you get for free here is quite simply amazing, seeing as most of the stuff (workflow-jobs themselves, stage-view, ...) was only part of the commercial enterprise bundle of CloudBees a year or two back.

Single and Multiple Jobs

It also seems to me that given the stashing abilities and multi-node capabilities of the Jenkins Pipleine, it is -- and indeed is advertised as such -- possible to create a full and complete Build/Test/Bundle/Deploy chain in one single Jenkins job.

This is in contrast to the "historical"(?) Build Pipeline Plugin that let you split "stages" across multiple Jenkins Jobs. Orchestrating these jobs has always been abit of a hassle, not to mention passing artifacts between the jobs and controlling how they run on different nodes.

Repeat/Resume step

Except that what you do get from the Old Build Pipeline Plugin is being able to restart a "stage" (when it fails) -- this works because a "stage" is simply a Jenkins Job Run that you can repeat (and it will also run all the downstream stuff).

When Repeat/Resume is crucial

Our project's C++ Builds have compilation durations of hours, Automated Tests that run longer hours and finally packaging and setup creation that also isn't done in a few minutes.

If I do a "pipleine-build", if the setup creation at the end fails due to setup-creation related problems, I do not want to rebuild the project and re-run the unit tests. I want to fix the setup scripts and redo the setup creation, that would (hopefully) wrap up this run with success. ... Or, if some automated tests fail for, e.g., suspected build environment reasons, I want to fix the build environment and re-run my pipeline from the failed test forward, without doing a multi-hour recompilation first.

Checkpoint

It so happens that the New Jenkins Job Pipeline bundle does have the ability to start from a checkpoint. Except: It's part of the Enterprise Bundle which means it's not free. (I'll note that I'd be fine with giving money to CloudBees, but I'm not fine with moving a use-as-many-nodes-as-you-like-and-also-be-able-to-just-do-testruns-wherever-you-like open software to a restricted licensed software where I have to keep track of number of nodes, make sure test environments can even be setup license-wise, etc.)

The Question: No checkpoint - means still multijob?

So, given that for me the New Jenkins Job Pipeline doesn't have the ability to resume from a failed step, it seems I'm back to square one and I have to split my longer-running stuff into multiple jobs anyway.

This then begs the question whether the Jenkins Job Pipleine is really the best tool for the job -- if I have to orchestrate multiple jobs and I want to streamline and automate this on the creation side, I could just as well use the Job DSL Plugin to maintain all these jobs from a single point -- and then the question is whether "free style" jobs wouldn't do the job just as well.

On the other hand I might be missing something here and there is another good single Job approach for this?

I'll note the Replay option for a Pipeline run looks promising, if a bit crude ...

答:
CloudBees has recently decided to open source the checkpoint plugin, as you can see in the linked issue on the Jenkins Jira that is listed in the comments.

I haven't seen a publicly released version of the plugin yet, though.

ContentLicense: CC BY-SA 3.0


问:
Where to find the youtube API Key?
I followed all the steps. I selected my desired API (YouTube Data API) and created a project.
I am searching now for about 20 minutes but I can't find the API Key?
My user interface is in german, is it possible that it is named to something else than API Key? Maybe Clientschlüssel (Client Key) ?

This is all I found:

There is also a JSON object, but no API Key:

```<code>var myInfos = {
    "web":{
        "client_id":"censored",
        "project_id":"censored",
        "auth_uri":"https://accounts.google.com/o/oauth2/auth",
        "token_uri":"https://accounts.google.com/o/oauth2/token",
        "auth_provider_x509_cert_url":"censored",
        "client_secret":"censored",
        "redirect_uris":["https://localhost/ex/YouTube/index.html"],
        "javascript_origins":["http://localhost"]
    }
}
</code>```

答:
Just to walk through this again to make sure you have done it properly.

Make sure you have a Google account.

Log into the developer console at: https://console.developers.google.com/

Create a project

THEN, select YouTube data API

Click create credentials on the right hand side of the screen.

Choose where you will call the API from

Pick public or User.

Obtain your API Key.

Optional: restrict your key.

I just walked though all of this and have been given a key myself.

Title: Where to find the youtube API Key?

Body:
I followed all the steps. I selected my desired API (YouTube Data API) and created a project.
I am searching now for about 20 minutes but I can't find the API Key?
My user interface is in german, is it possible that it is named to something else than API Key? Maybe Clientschlüssel (Client Key) ?

This is all I found:

There is also a JSON object, but no API Key:

var myInfos = {
    "web":{
        "client_id":"censored",
        "project_id":"censored",
        "auth_uri":"https://accounts.google.com/o/oauth2/auth",
        "token_uri":"https://accounts.google.com/o/oauth2/token",
        "auth_provider_x509_cert_url":"censored",
        "client_secret":"censored",
        "redirect_uris":["https://localhost/ex/YouTube/index.html"],
        "javascript_origins":["http://localhost"]
    }
}


问:
Gremlin: Select Vertices that have edges that share a property
This is in gremlin-scala. I have the traversal at a Vertex point (which is what '_' stands for below:

```<code> _.as("vertex").outE().as("outEdge").in().inE().as("inEdge")
.select("inEdge","outEdge").by("fullName")
.where("inEdge", P.eq("outEdge")).select("vertex")
</code>```

But I am getting an error referencing the .in() after the .as("outEdge") statement:

```<code>Error:(55, 40) Cannot prove that org.apache.tinkerpop.gremlin.structure.Edge <:< gremlin.scala.Vertex.
</code>```

Can anyone help me figure out what is going wrong here, and more importantly, is this the correct way to find Vertices that have a matching property on its edges?

Thanks in advance.

答:
I think that syntax is incorrect. Change:

```<code>_.as("vertex").outE().as("outEdge").in()
</code>```

to

```<code>_.as("vertex").outE().as("outEdge").inV()
</code>```

when you do outE() you are on an edge, so you must traverse to a Vertex which would be either inV() (the vertex adjacent to where you started), outV() (the vertex you started from since you traversed outE(), or bothV() which would yield both the vertices at either end of the edge.

I think your method for comparing properties makes sense. Someone else might post a way to simplify further.

Body:
This is in gremlin-scala. I have the traversal at a Vertex point (which is what '_' stands for below:

 _.as("vertex").outE().as("outEdge").in().inE().as("inEdge")
.select("inEdge","outEdge").by("fullName")
.where("inEdge", P.eq("outEdge")).select("vertex")

But I am getting an error referencing the .in() after the .as("outEdge") statement:

Error:(55, 40) Cannot prove that org.apache.tinkerpop.gremlin.structure.Edge <:< gremlin.scala.Vertex.

Can anyone help me figure out what is going wrong here, and more importantly, is this the correct way to find Vertices that have a matching property on its edges?

Thanks in advance.

Body:
I think that syntax is incorrect. Change:

_.as("vertex").outE().as("outEdge").in()

to

_.as("vertex").outE().as("outEdge").inV()

when you do outE() you are on an edge, so you must traverse to a Vertex which would be either inV() (the vertex adjacent to where you started), outV() (the vertex you started from since you traversed outE(), or bothV() which would yield both the vertices at either end of the edge.

I think your method for comparing properties makes sense. Someone else might post a way to simplify further.


问:
REST API, multi-language design
I'm designing a REST API(for the first time) and I'm with many doubts on how to handle the multi-language on a POST request.

The example is an Ad submission.

My Option 1:

Parameters (..., ..., title_en, title_pt, description_en, description_pt)

The POST Request (Name, Value)

```<code>some_field1, "some text1"
some_field2, "some text2"
title_en, "Some Title"
title_pt, "Algum Titulo"
description_en, "Some Description"
description_pt, "Alguma Descrição"
</code>```

My Option 2:

Parameters(..., ..., titles, descriptions)

The POST Request (Name, Value)

```<code>some_field1, "some text1"
some_field2, "some text2"
titles, [{"en":"Some Title","pt":"Algum Titulo"}]
descriptions, [{"en":"Some Description","pt":"Alguma Descrição"}]
</code>```

My question: What is the correct way to do it in a REST API?

Best Regards,
André

答:
There is no 'correct' way to do it - instead it is a matter of what format your data will be queried that is easiest to work with.

From a object oriented perspective option 2 would be WAY easier to work with because you would not have to do any string manipulation on the field names to determine which language you want to work with.

That being said this third option would be even more usable from an object oriented perspective:

```<code>some_field1, "some text1"
some_field2, "some text2"
titles, [{"language":"en","value":"Some Title"},{"language":"pt",value":"Algum Titulo"}]
descriptions, [{"language":"en","value":"Some Description"},{"language":"pt","value":"Alguma Descrição"}]
</code>```

Title: REST API, multi-language design

Body:
I'm designing a REST API(for the first time) and I'm with many doubts on how to handle the multi-language on a POST request.

The example is an Ad submission.

My Option 1:

Parameters (..., ..., title_en, title_pt, description_en, description_pt)

The POST Request (Name, Value)

some_field1, "some text1"
some_field2, "some text2"
title_en, "Some Title"
title_pt, "Algum Titulo"
description_en, "Some Description"
description_pt, "Alguma Descrição"

My Option 2:

Parameters(..., ..., titles, descriptions)

The POST Request (Name, Value)

some_field1, "some text1"
some_field2, "some text2"
titles, [{"en":"Some Title","pt":"Algum Titulo"}]
descriptions, [{"en":"Some Description","pt":"Alguma Descrição"}]

My question: What is the correct way to do it in a REST API?

Best Regards,
André

Body:
There is no 'correct' way to do it - instead it is a matter of what format your data will be queried that is easiest to work with.

From a object oriented perspective option 2 would be WAY easier to work with because you would not have to do any string manipulation on the field names to determine which language you want to work with.

That being said this third option would be even more usable from an object oriented perspective:

some_field1, "some text1"
some_field2, "some text2"
titles, [{"language":"en","value":"Some Title"},{"language":"pt",value":"Algum Titulo"}]
descriptions, [{"language":"en","value":"Some Description"},{"language":"pt","value":"Alguma Descrição"}]


问:
cURL with the real server IP while using CloudFlare
Our partners have whitelisted our server IP so we can send them cURL requests with new client data but their CRM returns Error: IP address of a connected platform is not allowed probably because the headers contain a CloudFlare IP rather than the real IP of our server which we asked to whitelist.

Is there a way to reveal our real server IP with a cURL request?

```<code>            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, 'http://clients.domain.com/api');

            curl_setopt($curl, CURLOPT_POST, TRUE);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);

            $res = curl_exec($curl);
            return $res;
</code>```

Tried this with no success:

```<code>    curl_setopt($curl, CURLOPT_HEADER, FALSE);
    curl_setopt($curl, CURLOPT_INTERFACE, '1.1.1.1');
</code>```

And:

```<code>curl_setopt($curl, CURLOPT_HTTPHEADER, array("REMOTE_ADDR: 1.1.1.1, HTTP_X_FORWARDED_FOR: 1.1.1.1"));
</code>```

EDIT: their logs show an IPv6 IP instead of the IPv4 server IP and it looks like this: 2a02:7aa0:1201::xxxx:xxxxafter some investigation it appears that this IPv6 IP is hosted by out hosting company and after whitelisting it everything started working.
Any thoughts on why cURL send out some strange IPv6 instead of real server IPv4?

答:
yeah well, if clients.domain.com is going through CF's proxy, then you could  connect directly to the server, and probably just fake the host header. as of PHP 7.0.7, this can be done as

curl_setopt_array($ch,array(
CURLOPT_URL=>'http://clients.domain.com/api',//to set the host
CURLOPT_CONNECT_TO=>'::8.8.8.8:80'
));

- but replace :80  with :443 if you're connecting with httpS

and replace 8.8.8.8  with the real server's IP (not the cloudflare IP)

or if you're not on PHP 7.0.7+ yet, in older versions, you can do

curl_setopt_array($ch,array(
CURLOPT_URL=>'http://8.8.8.8/api',
CURLOPT_HTTPHEADER=>array('Host: clients.domain.com')
));

(again, replace 8.8.8.8 with the real server's IP, not the cloudflare IP)
to set the host header manually. im not sure that will work properly with http Location redirects and CURLOPT_FOLLOWLOCATION, though, so you might have to handle Location http redirects manually

Body:
Our partners have whitelisted our server IP so we can send them cURL requests with new client data but their CRM returns Error: IP address of a connected platform is not allowed probably because the headers contain a CloudFlare IP rather than the real IP of our server which we asked to whitelist.

Is there a way to reveal our real server IP with a cURL request?

            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, 'http://clients.domain.com/api');

            curl_setopt($curl, CURLOPT_POST, TRUE);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);

            $res = curl_exec($curl);
            return $res;

Tried this with no success:

    curl_setopt($curl, CURLOPT_HEADER, FALSE);
    curl_setopt($curl, CURLOPT_INTERFACE, '1.1.1.1');

And:

curl_setopt($curl, CURLOPT_HTTPHEADER, array("REMOTE_ADDR: 1.1.1.1, HTTP_X_FORWARDED_FOR: 1.1.1.1"));

EDIT: their logs show an IPv6 IP instead of the IPv4 server IP and it looks like this: 2a02:7aa0:1201::xxxx:xxxxafter some investigation it appears that this IPv6 IP is hosted by out hosting company and after whitelisting it everything started working.
Any thoughts on why cURL send out some strange IPv6 instead of real server IPv4?


问:
MySQL Sort Order - Collation?
I'm having a difficult time sorting a char field in MySQL. The problem is that accented characters get mixed up with un-accented characters.  For example:

```<code>Abc
Ábd
Acc
</code>```

I thought it may have something to do with collation.  So I changed the collation of my table to utf8-ut8_bin, after reading this post.  Actually, I altered the table several times to various collations.  No cigar.

I should also add that, I don't mind the order of the sort as long as the sort doesn't result in a mixed list.  In other words, this is fine:

```<code>Ábd
Abc
Acc
</code>```

and so is this:

```<code>Abc
Acc
Ábd
</code>```

Looking forward to your response.

答:
@newtower had a good starting point, but neither he, nor the 'Community' realized that it was inconclusive.  So I am providing an answer that should 'fix' it:

unicode_ci (and virtually all other collations):

```<code>SET NAMES utf8 COLLATE utf8_unicode_ci;

SELECT GROUP_CONCAT(l SEPARATOR '=') AS gc
  FROM (
    SELECT 'A' as l  UNION ALL
    SELECT 'á' as l  UNION ALL
    SELECT 'A' as l              ) ls
  GROUP BY l
  ORDER BY gc;

+--------+
| gc     |
+--------+
| A=á=A  |
+--------+
</code>```

bin:

```<code>SET NAMES utf8 COLLATE utf8_bin;

SELECT GROUP_CONCAT(l SEPARATOR '=') AS gc
  FROM (
    SELECT 'A' as l  UNION ALL
    SELECT 'á' as l  UNION ALL
    SELECT 'A' as l              ) ls
  GROUP BY l
  ORDER BY gc;

+------+
| gc   |
+------+
| A=A  |
| á    |
+------+
</code>```

(You could add a DISTINCT in the GROUP_CONCAT to avoid the dup A.)

And here is a full rundown of the utf8 collations (using that technique):  http://mysql.rjweb.org/utf8_collations.html

Suggest you click "Affects Me" on https://bugs.mysql.com/bug.php?id=58797

Title: MySQL Sort Order - Collation?

Body:
I'm having a difficult time sorting a char field in MySQL. The problem is that accented characters get mixed up with un-accented characters.  For example:

Abc
Ábd
Acc

I thought it may have something to do with collation.  So I changed the collation of my table to utf8-ut8_bin, after reading this post.  Actually, I altered the table several times to various collations.  No cigar.

I should also add that, I don't mind the order of the sort as long as the sort doesn't result in a mixed list.  In other words, this is fine:

Ábd
Abc
Acc

and so is this:

Abc
Acc
Ábd

Looking forward to your response.

Body:
@newtower had a good starting point, but neither he, nor the 'Community' realized that it was inconclusive.  So I am providing an answer that should 'fix' it:

unicode_ci (and virtually all other collations):

SET NAMES utf8 COLLATE utf8_unicode_ci;

SELECT GROUP_CONCAT(l SEPARATOR '=') AS gc
  FROM (
    SELECT 'A' as l  UNION ALL
    SELECT 'á' as l  UNION ALL
    SELECT 'A' as l              ) ls
  GROUP BY l
  ORDER BY gc;

+--------+
| gc     |
+--------+
| A=á=A  |
+--------+

bin:

SET NAMES utf8 COLLATE utf8_bin;

SELECT GROUP_CONCAT(l SEPARATOR '=') AS gc
  FROM (
    SELECT 'A' as l  UNION ALL
    SELECT 'á' as l  UNION ALL
    SELECT 'A' as l              ) ls
  GROUP BY l
  ORDER BY gc;

+------+
| gc   |
+------+
| A=A  |
| á    |
+------+

(You could add a DISTINCT in the GROUP_CONCAT to avoid the dup A.)

And here is a full rundown of the utf8 collations (using that technique):  http://mysql.rjweb.org/utf8_collations.html

Suggest you click "Affects Me" on https://bugs.mysql.com/bug.php?id=58797


问:
React Router changing params doesn't fire componentWillRecieveProps
The Problem: Changing the parameters of a <Route /> component does not update the component it is rendering. The route change is shown in the URL bar, but directly rendering {this.props.match.params.id} shows the old :id and not the new one reflected in the URL bar.

Update: I fixed this by moving the <BrowserRouter /> out from the index.js file and into the App.js file. It is no longer the direct child of Provider and is instead the child of the App component. No clue why this makes everything suddenly work.

What I am doing: I have a <Link to="/user/11" /> that goes from user/7 (or any current ID) to a /user/11

The componentWillReceiveProps(newProps) of the component it is rendering is not fired.(This component is connected using react-redux if that helps any. I tried applying withRouter around the connection and that did not help)

If I manually refresh the page in chrome (using CTRL-R or the refresh button) the page shows the new data, rendering the "new" param.

TLDR: Switching from /user/7 to /user/11 does not fire that componentWillRecieveProps function and therefore leaving the component displaying the old state

Question: What am I doing incorrectly here that causes componentWillReceiveProps to not fire.

I am using react-router v4 and the latest create-react-app

This is my CWRP function:

```<code>componentWillReceiveProps(newProps) {
  console.log("getProps")

  this.props.getUser(newProps.match.params.id)

  if (newProps.match.params.id == newProps.currentUser.id) {
    this.setState({ user: "currentUser" })
  } else {
    this.setState({ user: "selectedUser" })
  }
}
</code>```

This is the full code of my component: https://gist.github.com/Connorelsea/c5c14e7c54994292bef2852475fc6b43

I was following the solution here and it did not seem to work for me. Component does not remount when route parameters change

答: You'll need to use React Router Redux</p>

Body:
The Problem: Changing the parameters of a <Route /> component does not update the component it is rendering. The route change is shown in the URL bar, but directly rendering {this.props.match.params.id} shows the old :id and not the new one reflected in the URL bar.

Update: I fixed this by moving the <BrowserRouter /> out from the index.js file and into the App.js file. It is no longer the direct child of Provider and is instead the child of the App component. No clue why this makes everything suddenly work.

What I am doing: I have a <Link to="/user/11" /> that goes from user/7 (or any current ID) to a /user/11

The componentWillReceiveProps(newProps) of the component it is rendering is not fired.(This component is connected using react-redux if that helps any. I tried applying withRouter around the connection and that did not help)

If I manually refresh the page in chrome (using CTRL-R or the refresh button) the page shows the new data, rendering the "new" param.

TLDR: Switching from /user/7 to /user/11 does not fire that componentWillRecieveProps function and therefore leaving the component displaying the old state

Question: What am I doing incorrectly here that causes componentWillReceiveProps to not fire.

I am using react-router v4 and the latest create-react-app

This is my CWRP function:

componentWillReceiveProps(newProps) {
  console.log("getProps")

  this.props.getUser(newProps.match.params.id)

  if (newProps.match.params.id == newProps.currentUser.id) {
    this.setState({ user: "currentUser" })
  } else {
    this.setState({ user: "selectedUser" })
  }
}

This is the full code of my component: https://gist.github.com/Connorelsea/c5c14e7c54994292bef2852475fc6b43

I was following the solution here and it did not seem to work for me. Component does not remount when route parameters change

Body: You'll need to use React Router Redux


问:
Improving CD Pipeline with Service fabric
We have web API's build on service fabric as well as some web projects in web apps in Azure. We want to easily swap back to the older version of the applications at our deployments and improve the CD pipeline.

So what come up with is creating an other app for staging for service fabric and route traffic whether that's gradually move users to the instance of the new version, or just flip a switch and send all your traffic to the new version all at once.

We need a solution that would both support Webapps and Service fabric.
  Providing patterns and experience for stateful services would be
  great.

References

A.Web Apps Slot swapping

https://azure.microsoft.com/en-us/resources/videos/azure-websites-deployment-slots-for-staging-sites/

B.Continuous Delivery Pipeline

PS:
I know that swaps don't make sense for stateful services. So rolling upgrades are must if we want to keep your data and keep it consistent.

答: Consider using Azure Api Management, which now has proper support for Service Fabric (check their trello). It should solve the versioning for both as it is external and agnostic to the underlying tech, except it doesn't provide the gradual increase in traffic.</p>


问:
Background: transparent does not work
I try to use background-color transparent for my task (can see in image) , but its not useful . Background-transparent do nothing , its show li's background-color .

I try many ways but its not working . What can i do ?

Thanks in advance .

HTML:

```<code><div>
   <ul>
      <li>...</li>
      <li>...</li>
      <li>...</li>
      <li>...</li>
      <li>...</li>
   </ul>

   <span class="left-arrow-winners"></span>
   <span class="right-arrow-winners" ></span>
<div>
</code>```

CSS:

```<code>li {
    display: inline-block;
    box-sizing: border-box;
    margin: 0 12px;
    padding: 4px 12px;
    background-color: rgba(230, 229, 220, 0.75);
    transition: all 250ms;
    border-radius: 4px;
}

.left-arrow-winners ,
.right-arrow-winners {
    cursor: pointer;
    font: 18px/32px icomoon;
    position: absolute;
    top: 4px;
}

.left-arrow-winners {
    left: 0
}

.right-arrow-winners {
    right: 0
}

.left-arrow-winners:before {
    content: "\e92a";
}

.right-arrow-winners:before {
    content: "\e92b";
}
</code>```

答:
Might be you have not set the transparency style in the correct html tag.
As you said, after applying transparency, you are getting background color of li's tag, so try to set transparency in the li tag.

Note that if we apply transparency in any element, it is obvious that the particular DOM element's background color gets transparent and we can see the background color of its parent element(in your case, the parent element is li).

To make the gradient as transparent, set the opacity which is 4th parameter of rgba() to 0, which is marked as bold letter here,

background: linear-gradient(to right, rgba(230, 229, 220, 0.75) 0, rgba(0, 0, 0, 0) 75%);

In the below example, I tried to show 2 ways, might be one which you want.

ul{
  list-style:none;
  padding:0;
  margin:0;
}

ul li a {
    display: inline-block;
    color: white;
    float:left;
    margin:5px;
}

li{
  display: inline-block;
    box-sizing: border-box;
    margin: 0 12px;
    padding: 4px 12px;
    background-color: rgba(230, 229, 220, 0.75);
    transition: all 250ms;
    border-radius: 4px;
}

.transparentBackground{
background: linear-gradient(to right, rgba(230, 229, 220, 0.75) 0, rgba(0, 0, 0, 0) 75%);
background: -webkit-linear-gradient(to right, rgba(230, 229, 220, 0.75) 0, rgba(0, 0, 0, 0) 75%); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(to right, rgba(230, 229, 220, 0.75) 0, rgba(0, 0, 0, 0) 75%); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(to right, rgba(230, 229, 220, 0.75) 0, rgba(0, 0, 0, 0) 75%); /* For Firefox 3.6 to 15 */
}

body{
  background:linear-gradient(to right, red 0, yellow 75%);
  background:-webkit-linear-gradient(to right, red 0, yellow 75%);
  background:-o-linear-gradient(to right, red 0, yellow 75%);
  background:-moz-linear-gradient(to right, red 0, yellow 75%);
}

.transparentBackground1{
background-color: transparent;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <ul class="menu-content">
    <li>Link 1</li>
    <li>Link 2</li>
    <li class="transparentBackground">Link 3    >></li>
  </ul>
  <br/>
  <ul class="menu-content">
    <li>Link 1</li>
    <li>Link 2</li>
    <li>Link 3</li>
    <li class="transparentBackground1">>></li>
  </ul>
</body></code>```

Title: Background: transparent does not work

Body:
I try to use background-color transparent for my task (can see in image) , but its not useful . Background-transparent do nothing , its show li's background-color .

I try many ways but its not working . What can i do ?

Thanks in advance .

HTML:

...

...

...

...

...

CSS:

li {
    display: inline-block;
    box-sizing: border-box;
    margin: 0 12px;
    padding: 4px 12px;
    background-color: rgba(230, 229, 220, 0.75);
    transition: all 250ms;
    border-radius: 4px;
}

.left-arrow-winners ,
.right-arrow-winners {
    cursor: pointer;
    font: 18px/32px icomoon;
    position: absolute;
    top: 4px;
}

.left-arrow-winners {
    left: 0
}

.right-arrow-winners {
    right: 0
}

.left-arrow-winners:before {
    content: "\e92a";
}

.right-arrow-winners:before {
    content: "\e92b";
}

Body:
Might be you have not set the transparency style in the correct html tag.
As you said, after applying transparency, you are getting background color of li's tag, so try to set transparency in the li tag.

Note that if we apply transparency in any element, it is obvious that the particular DOM element's background color gets transparent and we can see the background color of its parent element(in your case, the parent element is li).

To make the gradient as transparent, set the opacity which is 4th parameter of rgba() to 0, which is marked as bold letter here,

background: linear-gradient(to right, rgba(230, 229, 220, 0.75) 0, rgba(0, 0, 0, 0) 75%);

In the below example, I tried to show 2 ways, might be one which you want.

ul{
  list-style:none;
  padding:0;
  margin:0;
}

ul li a {
    display: inline-block;
    color: white;
    float:left;
    margin:5px;
}

li{
  display: inline-block;
    box-sizing: border-box;
    margin: 0 12px;
    padding: 4px 12px;
    background-color: rgba(230, 229, 220, 0.75);
    transition: all 250ms;
    border-radius: 4px;
}

.transparentBackground{
background: linear-gradient(to right, rgba(230, 229, 220, 0.75) 0, rgba(0, 0, 0, 0) 75%);
background: -webkit-linear-gradient(to right, rgba(230, 229, 220, 0.75) 0, rgba(0, 0, 0, 0) 75%); /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(to right, rgba(230, 229, 220, 0.75) 0, rgba(0, 0, 0, 0) 75%); /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(to right, rgba(230, 229, 220, 0.75) 0, rgba(0, 0, 0, 0) 75%); /* For Firefox 3.6 to 15 */
}

body{
  background:linear-gradient(to right, red 0, yellow 75%);
  background:-webkit-linear-gradient(to right, red 0, yellow 75%);
  background:-o-linear-gradient(to right, red 0, yellow 75%);
  background:-moz-linear-gradient(to right, red 0, yellow 75%);
}

.transparentBackground1{
background-color: transparent;
}

<body>
  <ul class="menu-content">
    <li><a href="#">Link 1</a></li>
    <li><a href="#">Link 2</a></li>
    <li class="transparentBackground"><a href="#">Link 3  &nbsp;&nbsp;>></a></li>
  </ul>
  <br/>
  <ul class="menu-content">
    <li><a href="#">Link 1</a></li>
    <li><a href="#">Link 2</a></li>
    <li><a href="#">Link 3</a></li>
    <li class="transparentBackground1"><a href="#">>></a></li>
  </ul>
</body>


问:
How to listen to dev/binder?
In Android is dev/binder also for layers communication responsible. Is it possible to listen to messages? I know that they must be decoded than, but how can I get this messages. For example if an app send a message to became an Geolocation. I have also root on my android device.

答:
@Adrian, some good work w.r.t the problem has been done by other developer/researchers, so you could make use of their results.

First of all, I'd recommend to look at the great work of Jonathan Levin (a.k.a Technologeeks), namely his book on the Android internals that recently became free and could be accessed at the book's companion website: newandroidbook.com. From there you'll get links, description and usage examples to

bindump

that is a simple derivative of the service command, which obtains a handle to the system service of choice, and then inspects its own entry in the /sys/kernel/debug/binder/proc directory. Because all the binder debug data is world readable, you can run this tool on unrooted devices as well.

jtrace, an augmented version of strace, whose one of the advantages over strace is

binder message parsing (auto detected).

Another great work, done by Opersys (with Karim Yaghmour), that is definitely worth noting and looking at is

Binder Explorer

This tool works as an app, or along with HTML GUI, to show a graphical view of connections in real time.

Title: How to listen to dev/binder?


问:
Read file from resources folder in Spring Boot
I'm using Spring Boot and json-schema-validator. I'm trying to read a file called jsonschema.json from the resources folder. I've tried a few different ways but I can't get it to work. This is my code.

```<code>ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("jsonschema.json").getFile());
JsonNode mySchema = JsonLoader.fromFile(file);
</code>```

This is the location of the file.

And here I can see the file in the classes folder.

But when I run the code I get the following error.

```<code>jsonSchemaValidator error: java.io.FileNotFoundException: /home/user/Dev/Java/Java%20Programs/SystemRoutines/target/classes/jsonschema.json (No such file or directory)
</code>```

What is it I'm doing wrong in my code?

答:
Very short answer: you are looking for the resource in the scope of a classloader's class instead of your target class. This should work:

File file = new File(getClass().getResource("jsonschema.json").getFile());
JsonNode mySchema = JsonLoader.fromFile(file);
```
<p>Also, that might be helpful reading:</p>
<ul>
<li>What is the difference between Class.getResource() and ClassLoader.getResource()?</li>
<li>Strange behavior of Class.getResource() and ClassLoader.getResource() in executable jar</li>
<li>Loading resources using getClass().getResource()</li>
</ul>
<p>P.S. there is a case when a project compiled on one machine and after that launched on another or inside Docker. In such a scenario path to your resource folder would be invalid and you would need to get it in runtime:</p>
<pre class="lang-java prettyprint-override"><code>ClassPathResource res = new ClassPathResource("jsonschema.json");
File file = new File(res.getPath());
JsonNode mySchema = JsonLoader.fromFile(file);
</code>```

Update from 2020

On top of that if you want to read resource file as a String, for example in your tests, you can use these static utils methods:

public static String getResourceFileAsString(String fileName) {
    InputStream is = getResourceFileAsInputStream(fileName);
    if (is != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        return (String)reader.lines().collect(Collectors.joining(System.lineSeparator()));
    } else {
        throw new RuntimeException("resource not found");
    }
}

public static InputStream getResourceFileAsInputStream(String fileName) {
    ClassLoader classLoader = {CurrentClass}.class.getClassLoader();
    return classLoader.getResourceAsStream(fileName);
}
```
<p>Example of usage:</p>
<pre class="lang-java prettyprint-override"><code>String soapXML = getResourceFileAsString("some_folder_in_resources/SOPA_request.xml");
</code>```

Body:
I'm using Spring Boot and json-schema-validator. I'm trying to read a file called jsonschema.json from the resources folder. I've tried a few different ways but I can't get it to work. This is my code.

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("jsonschema.json").getFile());
JsonNode mySchema = JsonLoader.fromFile(file);

This is the location of the file.

And here I can see the file in the classes folder.

But when I run the code I get the following error.

jsonSchemaValidator error: java.io.FileNotFoundException: /home/user/Dev/Java/Java%20Programs/SystemRoutines/target/classes/jsonschema.json (No such file or directory)

What is it I'm doing wrong in my code?

Body:
Very short answer: you are looking for the resource in the scope of a classloader's class instead of your target class. This should work:

File file = new File(getClass().getResource("jsonschema.json").getFile());
JsonNode mySchema = JsonLoader.fromFile(file);

Also, that might be helpful reading:

What is the difference between Class.getResource() and ClassLoader.getResource()?

Strange behavior of Class.getResource() and ClassLoader.getResource() in executable jar

Loading resources using getClass().getResource()

P.S. there is a case when a project compiled on one machine and after that launched on another or inside Docker. In such a scenario path to your resource folder would be invalid and you would need to get it in runtime:

ClassPathResource res = new ClassPathResource("jsonschema.json");
File file = new File(res.getPath());
JsonNode mySchema = JsonLoader.fromFile(file);

Update from 2020

On top of that if you want to read resource file as a String, for example in your tests, you can use these static utils methods:

public static String getResourceFileAsString(String fileName) {
    InputStream is = getResourceFileAsInputStream(fileName);
    if (is != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        return (String)reader.lines().collect(Collectors.joining(System.lineSeparator()));
    } else {
        throw new RuntimeException("resource not found");
    }
}

public static InputStream getResourceFileAsInputStream(String fileName) {
    ClassLoader classLoader = {CurrentClass}.class.getClassLoader();
    return classLoader.getResourceAsStream(fileName);
}

Example of usage:

String soapXML = getResourceFileAsString("some_folder_in_resources/SOPA_request.xml");

ContentLicense: CC BY-SA 4.0


问:
How to avoid Java OutofMemoryError Heap Space in loop with StringBuilder?
Here is my code that throws java.lang.OutOfMemoryError: Java heap space:

```<code>StringBuilder sb = new StringBuilder();
    for (int i = 0; i< ranks.size(); i++) {
        Map<String, String> map = ranks.get(i);
        sb.append("SELECT ");
        int iter = 0;
        for (String key : map.keySet()) {
            if (key.equals("ware_md5")) {
                sb.append("'").append(map.get(key)).append(" ' AS ").append(key);
            }
            else {
                sb.append(map.get(key)).append(" AS ").append(key);
            }
            if (iter < map.keySet().size() - 1) {
                sb.append(",");
            }
            iter++;
        }
        if (i < ranks.size() - 1) {
            sb.append(" UNION ALL ");
        }

    }
    return sb.toString();
</code>```

'ranks' ArrayList contains about 30 000 values

Is there any way to rewrite this peace of code to avoid this error ?

答: Launch the JVM with a larger heap.  java -Xmx256M as an example, for an example with a 256MB heap.</p>

Body:
Here is my code that throws java.lang.OutOfMemoryError: Java heap space:

StringBuilder sb = new StringBuilder();
    for (int i = 0; i< ranks.size(); i++) {
        Map<String, String> map = ranks.get(i);
        sb.append("SELECT ");
        int iter = 0;
        for (String key : map.keySet()) {
            if (key.equals("ware_md5")) {
                sb.append("'").append(map.get(key)).append(" ' AS ").append(key);
            }
            else {
                sb.append(map.get(key)).append(" AS ").append(key);
            }
            if (iter < map.keySet().size() - 1) {
                sb.append(",");
            }
            iter++;
        }
        if (i < ranks.size() - 1) {
            sb.append(" UNION ALL ");
        }

    }
    return sb.toString();

'ranks' ArrayList contains about 30 000 values

Is there any way to rewrite this peace of code to avoid this error ?


问:
Programmatic way to call go tools
Is there a way to call the Go tools (like go build) programmatically from within another Go program with a library call and to get more structured output compared to the text output from the command line invocation?

答:
Within another go program it is possible to execute console commands using the os/exec package like so:

```<code>func main (){
   cmd := exec.Command("go run lib/main.go")
   if err := cmd.Run(); err != nil{
       log.Fatal(err)
   }
}
</code>```

I don't see this being very useful though.

Title: Programmatic way to call go tools

Body:
Within another go program it is possible to execute console commands using the os/exec package like so:

func main (){
   cmd := exec.Command("go run lib/main.go")
   if err := cmd.Run(); err != nil{
       log.Fatal(err)
   }
}

I don't see this being very useful though.


问:
LinkedIn, 401, Unable to verify access token
I used this guide to built a showcase - sign in with LinkedIn into a specific site.
Everything worked perfectly until I demonstarted it in front of a wide audience and it broke down :-( It was a great FAIL and I want to know why. Here is what I do:

1.On the sign in page the user may click a Sign in with LinkedIn button and is redirected to similar link:

```<code>https://www.linkedin.com/oauth/v2/authorization?redirect_uri=[my_callback]&client_id=[my_client_id]&response_type=code&state=[securely_random]&scope=r_basicprofile%20r_emailaddress
</code>```

2.The user allows the application and is sent back to my_callback

3.In my_callback I make a POST to https://www.linkedin.com/oauth/v2/accessToken in order to obtain an access token. I use the code sent by LinkedIn, correct client ID and secret. Everything is OK, e.g the response might be:

```<code>{
    "access_token": [access_token],
    "expires_in": 5184000
}
</code>```

4.I make authenticated requests to fetch the profile data from endpoint https://www.linkedin.com/v1/people/~:(firstName,lastName,email_address)

Headers:

```<code>x-li-format: json
Authorization: Bearer [access_token]
</code>```

I started to get an error 401 occasionally, e.g.:

```<code>{
  "errorCode": 0,
  "message": "Unable to verify access token",
  "requestId": "YX21AN6NZG",
  "status": 401,
  "timestamp": 1483732371224
}
</code>```

It seems that some of the requests randomly passed nevertheless...

Additional details:

The user is logged in LinkedIn

The user is administrator for the LinkedIn application

I have checked the limitations (throttle limits) at in the application. Available at https://www.linkedin.com/developer/apps. Everything which can be seen is green.

I have tried all advices and hacks from this question

My app is not live

I'm puzzled!

Question: Any obvious mistake?

Question: Is there any hidden throttle limits (or security instruments) for the limitation of the number of access tokens for specific user/app combination? (I'm always using the same user and I tested pretty aggressively before the big FAIL)

UPDATE: In the next two days the Sign in started working smoothly again as described above. No 401-s anymore... :-X I've made no changes to the code base. So is this some kind of throttle limit or just LI was in a bad mood on Friday?

答:
I have an access-token that worked to get data through the API, however now it has stopped working. I've carefully read LinkedIn's documentation: https://developer.linkedin.com/docs/oauth2 and have come up with why this can happen.

The docs state, that the user's session is linked with the access-token. Therefore, logging out of the session means the access-token is invalidated. This makes sense because it's exactly what I see happening.

The oauth2 expired-at is just a timestamp of the ultimate time this access-token will be valid. But it can be invalidated at any moment apparently.

Other oauth2 implementations show features for refreshing the access-token, Linkedin does not provide such feature. Therefore a user has to refresh it manually every time. Not sure if this is by design or they haven't got around to it yet. Overall their API feels pretty out-dated.

Body:
I used this guide to built a showcase - sign in with LinkedIn into a specific site.
Everything worked perfectly until I demonstarted it in front of a wide audience and it broke down :-( It was a great FAIL and I want to know why. Here is what I do:

1.On the sign in page the user may click a Sign in with LinkedIn button and is redirected to similar link:

https://www.linkedin.com/oauth/v2/authorization?redirect_uri=[my_callback]&client_id=[my_client_id]&response_type=code&state=[securely_random]&scope=r_basicprofile%20r_emailaddress

2.The user allows the application and is sent back to my_callback

3.In my_callback I make a POST to https://www.linkedin.com/oauth/v2/accessToken in order to obtain an access token. I use the code sent by LinkedIn, correct client ID and secret. Everything is OK, e.g the response might be:

{
    "access_token": [access_token],
    "expires_in": 5184000
}

4.I make authenticated requests to fetch the profile data from endpoint https://www.linkedin.com/v1/people/~:(firstName,lastName,email_address)

Headers:

x-li-format: json
Authorization: Bearer [access_token]

I started to get an error 401 occasionally, e.g.:

{
  "errorCode": 0,
  "message": "Unable to verify access token",
  "requestId": "YX21AN6NZG",
  "status": 401,
  "timestamp": 1483732371224
}

It seems that some of the requests randomly passed nevertheless...

Additional details:

The user is logged in LinkedIn

The user is administrator for the LinkedIn application

I have checked the limitations (throttle limits) at in the application. Available at https://www.linkedin.com/developer/apps. Everything which can be seen is green.

I have tried all advices and hacks from this question

My app is not live

I'm puzzled!

Question: Any obvious mistake?

Question: Is there any hidden throttle limits (or security instruments) for the limitation of the number of access tokens for specific user/app combination? (I'm always using the same user and I tested pretty aggressively before the big FAIL)

UPDATE: In the next two days the Sign in started working smoothly again as described above. No 401-s anymore... :-X I've made no changes to the code base. So is this some kind of throttle limit or just LI was in a bad mood on Friday?


问:
Will PDF 2.0 compatible with PDF 1.x
Will a valid PDF 1.x document be a valid PDF 2.0 document? Will PDF 1.x readers gracefully accept PDF 2.0 documents?</p>

答:
Those who worked on PDF 2.0 in ISO made great effort to be as compatible with present-day implementations as possible and to break as little as we could possibly do. Some changes (like adding UTF-8 string object support) weren't possible in a means that is totally backward-compatible. Most changes, however, are clarifications to the standard and updates to better align the ISO standard to the behaviors of implementations. For example, the section on Tagged PDF was rewritten in a way that is much clearer and easier to understand, and includes a new tag set for PDF 2.0 that does not match the PDF 1.7 tag set. However, the PDF 2.0 tag set is not the default - the default remains the PDF 1.7 tag namespace - so that Tagged PDF files can be promoted to PDF 2.0 without the tags needing to be rewritten.

PDF 2.0 is an evolution of the PDF standard, not a drastic change to the specification. It does include some new capabilities - such as the ability to specify string objects in UTF-8 format - that PDF 1.7 viewers will not be able to handle correctly. However, most PDF 1.7 viewers should handle most PDF 2.0 files perfectly well. In this respect, your comparison to PDF 1.6 vs. PDF 1.7 is a fair comparison: viewers that don't know about PDF 2.0 revisions or features will either ignore these or not handle these correctly. However, I expect most PDF 2.0 files will be written in a way where they are compatible with present-day PDF 1.7 viewing implementations.

If you're interested in more information, Peter Wyatt's presentation at PDF Days Europe 2017 can be downloaded from https://www.pdfa.org/wp-content/uploads/2017/05/PDF20Keynote.pdf ; or you can watch it via https://youtu.be/AR4lGlDh9Ac.

Disclaimer: I am the chairman of the PDF Association

Title: Will PDF 2.0 compatible with PDF 1.x


问:
Glitchy widths when using transitions on pseudo element with background images in Bootstrap grid
Hard to explain what I'm seeing. Included a fiddle to show. When I'm hovering over some of the divs, there is a 'glitch' on the edge of other divs in the grid. Almost seems as if the width is changing for a second then back again. Again, it's difficult to explain. Please see the fiddle in 2 or 3 column layout.

https://jsfiddle.net/riegersn/q2g9gxk3/3/

```<code>.project::before {
  content: '';
  position: absolute;
  left: -100%;
  top: 0;
  width: 200%;
  height: 100%;
  background-position: left center;
  background-repeat: repeat-x;
  background-size: contain;
  background-image: inherit;
  transition: transform 0.2s ease-out;
}

.project:hover::before {
  transform: translateX(50%);
}
</code>```

答:
Well that's a fun one.

I will be totally honest and say I am not really sure why this works (so maybe someone else will come along with a better answer), but adding transform-style: preserve-3d fixed the problem for me:

```<code>.project::before {
  transform-style: preserve-3d;
}
</code>```

Body:
Hard to explain what I'm seeing. Included a fiddle to show. When I'm hovering over some of the divs, there is a 'glitch' on the edge of other divs in the grid. Almost seems as if the width is changing for a second then back again. Again, it's difficult to explain. Please see the fiddle in 2 or 3 column layout.

https://jsfiddle.net/riegersn/q2g9gxk3/3/

.project::before {
  content: '';
  position: absolute;
  left: -100%;
  top: 0;
  width: 200%;
  height: 100%;
  background-position: left center;
  background-repeat: repeat-x;
  background-size: contain;
  background-image: inherit;
  transition: transform 0.2s ease-out;
}

.project:hover::before {
  transform: translateX(50%);
}

Body:
Well that's a fun one.

I will be totally honest and say I am not really sure why this works (so maybe someone else will come along with a better answer), but adding transform-style: preserve-3d fixed the problem for me:

.project::before {
  transform-style: preserve-3d;
}


问:
Excel VBA - delay for fraction of second while still using Excel and other applications
I write chemical plant simulations in VBA for Excel. I currently use the Application.OnTime method to delay for 1 second. The simulation procedure runs each second. This allows me to change values in the spreadsheet and do other things on the computer while the simulation is running.

However, I would like to run the simulation procedure faster than 1 second. Application.wait prevents me from doing anything else to the spreadsheet while waiting.

答:
You can try using the DoEvents function which yields execution. This allows you to perform tasks while the process runs and counts in the background.
Couple this with a Timer function which yields milliseconds (at least on Windows, MAC resolution is 1s).

Perfect example in the official docs:
https://msdn.microsoft.com/en-us/library/office/gg264522.aspx


问:
R extract terminal node info from partykit decision tree
I have created a constparty decision tree (customized split rules) and print out the tree result. The result looks like this:

```<code>Fitted party:
[1] root
|   [2] value.a < 1651: 0.067 (n = 1419, err = 88.6)
|   [3] value.a >= 1651: 0.571 (n = 7, err = 1.7)
</code>```

I am trying to extract terminal node info
(the yval: 0.067 and 0.571;
the n on each node: 1419 and 7;
and err: 88.6 and 1.7) and put them into a list while having the corresponding node id (node ID 2 and 3) so that I can utilize those info later.

I have been looking into partykit functions for a while and could not find a function that could help me extracting those info I just listed.

Could someone help me please?  Thank you!

答:
As usual there are several approaches to obtain the information you are looking for. The technical way for extracting the info stored in a particular node is to use nodeapply(object, ids, info_node) where info_node returns a list of information stored in the respective node.

However, in the terminal nodes of constparty objects there is nothing stored. Instead, the whole distribution of the response by fitted node is stored and can be extracted by fitted(object). This contains a data frame with the observed (response) the (fitted) node and the observation (weights) (if any). And then you can easily use tapply() or aggregate() or something like that to compute node-wise means etc.

Alternatively, you can convert the constparty object to a simpleparty object which stores the printed information in the nodes and extract it.

A worked example for both strategies is a simple regression tree for the cars data:

```<code>library("partykit")
data("cars", package = "datasets")
ct <- ctree(dist ~ speed, data = cars)
</code>```

Then you can easily compute node-wise means by

```<code>with(fitted(ct), tapply(`(response)`, `(fitted)`, mean))
##        3        4        5
## 18.20000 39.75000 65.26316
</code>```

Of course, you can replace mean by any other summary statistic you are interested in.

The nodeapply() for the simpleparty can be obtained by:

```<code>nodeapply(as.simpleparty(ct), ids = nodeids(ct, terminal = TRUE), info_node)
## $`3`
## $`3`$prediction
## [1] 18.2
##
## $`3`$n
##  n
## 15
##
## $`3`$error
## [1] 1176.4
##
## $`3`$distribution
## NULL
##
## $`3`$p.value
## NULL
##
##
## $`4`
## $`4`$prediction
## [1] 39.75
## ...
</code>```

Body:
I have created a constparty decision tree (customized split rules) and print out the tree result. The result looks like this:

Fitted party:
[1] root
|   [2] value.a < 1651: 0.067 (n = 1419, err = 88.6)
|   [3] value.a >= 1651: 0.571 (n = 7, err = 1.7)

I am trying to extract terminal node info
(the yval: 0.067 and 0.571;
the n on each node: 1419 and 7;
and err: 88.6 and 1.7) and put them into a list while having the corresponding node id (node ID 2 and 3) so that I can utilize those info later.

I have been looking into partykit functions for a while and could not find a function that could help me extracting those info I just listed.

Could someone help me please?  Thank you!

Body:
As usual there are several approaches to obtain the information you are looking for. The technical way for extracting the info stored in a particular node is to use nodeapply(object, ids, info_node) where info_node returns a list of information stored in the respective node.

However, in the terminal nodes of constparty objects there is nothing stored. Instead, the whole distribution of the response by fitted node is stored and can be extracted by fitted(object). This contains a data frame with the observed (response) the (fitted) node and the observation (weights) (if any). And then you can easily use tapply() or aggregate() or something like that to compute node-wise means etc.

Alternatively, you can convert the constparty object to a simpleparty object which stores the printed information in the nodes and extract it.

A worked example for both strategies is a simple regression tree for the cars data:

library("partykit")
data("cars", package = "datasets")
ct <- ctree(dist ~ speed, data = cars)

Then you can easily compute node-wise means by

with(fitted(ct), tapply(`(response)`, `(fitted)`, mean))
##        3        4        5
## 18.20000 39.75000 65.26316

Of course, you can replace mean by any other summary statistic you are interested in.

The nodeapply() for the simpleparty can be obtained by:

nodeapply(as.simpleparty(ct), ids = nodeids(ct, terminal = TRUE), info_node)
## $`3`
## $`3`$prediction
## [1] 18.2
##
## $`3`$n
##  n
## 15
##
## $`3`$error
## [1] 1176.4
##
## $`3`$distribution
## NULL
##
## $`3`$p.value
## NULL
##
##
## $`4`
## $`4`$prediction
## [1] 39.75
## ...


问:
{w is in {a,b}*|w contains b only in some odds position}
I need the DFA and the regular expression for this language.

I think the DFA is this but the Regular expression I get is this ((aUb)a)* and I think it's not correct.

答:
Using the DFA to regex conversion now and I think I got it:

((aa|ba)*a)|((aa|ba)*b)|(aa|ba)*

Simplified as @Bergi said:

(aa|ba)*|(a|b|ε)


问:
appending and removing an image on toggle
I am appending which is positioned correctly when a li is clicked.  My code works nicely although it keeps adding images to the page because i am not removing them when the li is toggled.  Any ideas?</p>

```<code>$("#offering li").click(function() {
            $(this).find("ul").animate({height: "toggle"}, 500);
            $(this).append('<img width="286" height="15" class="offeringselected" alt="Selected" src="images/bg-offering-li-selected.png">');
            $(this).toggleClass('current');
    });
</code>```

答:
You can use the .toggle() event method, passing it two functions which will be alternated on clicks.

```<code>$("#offering li").toggle(function() {
        $(this).find("ul").animate({height: "toggle"}, 500);
        $(this).addClass('current')
               .append('<img width="286" height="15" class="offeringselected" alt="Selected" src="images/bg-offering-li-selected.png">');
},function() {
        $(this).removeClass('current')
               .children('img.offeringselected').remove();
});
</code>```

Or perhaps it would be better to put the image in the page coming from the server, then just show and hide it.

To do this, you could use the other version of .toggle() that performs a show/hide.

```<code>$("#offering li").click(function() {
        $(this).find("ul").animate({height: "toggle"}, 500);
        $(this).toggleClass('current')
               .children('img.offeringselected').toggle(); // show/hide the img
});
</code>```

Hardcode the image into the
, and give it an initial display:none in CSS.

ContentLicense: CC BY-SA 2.5

Body:
I am appending which is positioned correctly when a li is clicked.  My code works nicely although it keeps adding images to the page because i am not removing them when the li is toggled.  Any ideas?

$("#offering li").click(function() {
            $(this).find("ul").animate({height: "toggle"}, 500);
            $(this).append('');
            $(this).toggleClass('current');
    });

Body:
You can use the .toggle() event method, passing it two functions which will be alternated on clicks.

$("#offering li").toggle(function() {
        $(this).find("ul").animate({height: "toggle"}, 500);
        $(this).addClass('current')
               .append('<img width="286" height="15" class="offeringselected" alt="Selected" src="images/bg-offering-li-selected.png">');
},function() {
        $(this).removeClass('current')
               .children('img.offeringselected').remove();
});

Or perhaps it would be better to put the image in the page coming from the server, then just show and hide it.

To do this, you could use the other version of .toggle() that performs a show/hide.

$("#offering li").click(function() {
        $(this).find("ul").animate({height: "toggle"}, 500);
        $(this).toggleClass('current')
               .children('img.offeringselected').toggle(); // show/hide the img
});

Hardcode the image into the <li>, and give it an initial display:none in CSS.


问:
Beyond compare remote with local file
I want to compare two text files one on remote the other local. With diff I would do that with

```<code>ssh user@login "cat myfile.txt" | diff - local.txt
</code>```

Is there a way to perform the same comparison using Beyond Compare? If I do

```<code>ssh user@login "cat myfile.txt" | bcompare - local.txt
</code>```

I get only the local file displayed.

答:
Beyond Compare Pro includes built-in SFTP support, so you can pass an SFTP URL directly to it as a command-line argument.

```<code>bcompare local.txt sftp://user:password@server/folder/file.txt
</code>```

If you don't provide a password in the URL, Beyond Compare will prompt you for a password.

```<code>bcompare local.txt sftp://user@server/folder/file.txt
</code>```

Title: Beyond compare remote with local file

Body:
I want to compare two text files one on remote the other local. With diff I would do that with

ssh user@login "cat myfile.txt" | diff - local.txt

Is there a way to perform the same comparison using Beyond Compare? If I do

ssh user@login "cat myfile.txt" | bcompare - local.txt

I get only the local file displayed.

Body:
Beyond Compare Pro includes built-in SFTP support, so you can pass an SFTP URL directly to it as a command-line argument.

bcompare local.txt sftp://user:password@server/folder/file.txt

If you don't provide a password in the URL, Beyond Compare will prompt you for a password.

bcompare local.txt sftp://user@server/folder/file.txt


问:
Ruby on Rails: split string into hash and insert it to a json
I have a model that looks something like:

```<code>  :created_at => Tue, 06 Jun 2017 15:34:32 UTC +00:00,
  :updated_at => Tue, 06 Jun 2017 15:34:35 UTC +00:00,
     :metrics => {
                "metric_a" => 10756,
                "metric_b" => "",
                "metric_c" => 6.67267607666759
},
  :status => "working"
</code>```

With the  metrics field as a json.

And I want to split a string such as:

```<code>"Home/Personal Finance=37.00%=55,Computers/Internet/Web Design and Development=13.77%=48,News=8.64%=45,Arts/Television=5.23%=42,Arts/Music=2.99%=39,News/Current Events=2.66%=38,Society/Issues=2.47%=38,Computers/Internet/On the Web=2.46%=38,Business/Investing=1.76%=36,Society=1.70%=36"
</code>```

To be named categories under the metrics field so that each category will hold two numbers, the percentage and the number that follows it.
So in the example above it would look like:

```<code>  :created_at => Tue, 06 Jun 2017 15:34:32 UTC +00:00,
  :updated_at => Tue, 06 Jun 2017 15:34:35 UTC +00:00,
     :metrics => {
                "metric_a" => 10756,
                "metric_b" => "",
                "metric_c" => 6.67267607666759
                "categories" => {
            "Home/Personal Finance": [37.00,55],
            "Computers/Internet/Web Design and Development": [13.77,48],
            ...
            }

},
  :status => "working"
</code>```

Basically I want to save the two numbers for each category (maybe there's a better way to store them by the way?).

Either way can split the string with .split(",") but what next?

答:
Regex is a good option here. Assuming that your category names will never have =, % or , as a character, you could do:

```<code>categories_string = "Home/Personal Finance=37.00%=55,Computers/Internet/Web Design and Development=13.77%=48,News=8.64%=45,Arts/Television=5.23%=42,Arts/Music=2.99%=39,News/Current Events=2.66%=38,Society/Issues=2.47%=38,Computers/Internet/On the Web=2.46%=38,Business/Investing=1.76%=36,Society=1.70%=36"

categories_string.scan(/(.+?)=(.+?)%=(.+?),/).map do |x,y,z|
  { x => [y.to_f, z.to_i] }
end.reduce Hash.new, :merge

#=> {"Home/Personal Finance"=>[37.0, 55], "Computers/Internet/Web Design and Development"=>[13.77, 48], "News"=>[8.64, 45], "Arts/Television"=>[5.23, 42], "Arts/Music"=>[2.99, 39], "News/Current Events"=>[2.66, 38], "Society/Issues"=>[2.47, 38], "Computers/Internet/On the Web"=>[2.46, 38], "Business/Investing"=>[1.76, 36]}
</code>```

Body:
I have a model that looks something like:

  :created_at => Tue, 06 Jun 2017 15:34:32 UTC +00:00,
  :updated_at => Tue, 06 Jun 2017 15:34:35 UTC +00:00,
     :metrics => {
                "metric_a" => 10756,
                "metric_b" => "",
                "metric_c" => 6.67267607666759
},
  :status => "working"

With the  metrics field as a json.

And I want to split a string such as:

"Home/Personal Finance=37.00%=55,Computers/Internet/Web Design and Development=13.77%=48,News=8.64%=45,Arts/Television=5.23%=42,Arts/Music=2.99%=39,News/Current Events=2.66%=38,Society/Issues=2.47%=38,Computers/Internet/On the Web=2.46%=38,Business/Investing=1.76%=36,Society=1.70%=36"

To be named categories under the metrics field so that each category will hold two numbers, the percentage and the number that follows it.
So in the example above it would look like:

  :created_at => Tue, 06 Jun 2017 15:34:32 UTC +00:00,
  :updated_at => Tue, 06 Jun 2017 15:34:35 UTC +00:00,
     :metrics => {
                "metric_a" => 10756,
                "metric_b" => "",
                "metric_c" => 6.67267607666759
                "categories" => {
            "Home/Personal Finance": [37.00,55],
            "Computers/Internet/Web Design and Development": [13.77,48],
            ...
            }

},
  :status => "working"

Basically I want to save the two numbers for each category (maybe there's a better way to store them by the way?).

Either way can split the string with .split(",") but what next?

Body:
Regex is a good option here. Assuming that your category names will never have =, % or , as a character, you could do:

categories_string = "Home/Personal Finance=37.00%=55,Computers/Internet/Web Design and Development=13.77%=48,News=8.64%=45,Arts/Television=5.23%=42,Arts/Music=2.99%=39,News/Current Events=2.66%=38,Society/Issues=2.47%=38,Computers/Internet/On the Web=2.46%=38,Business/Investing=1.76%=36,Society=1.70%=36"

categories_string.scan(/(.+?)=(.+?)%=(.+?),/).map do |x,y,z|
  { x => [y.to_f, z.to_i] }
end.reduce Hash.new, :merge

#=> {"Home/Personal Finance"=>[37.0, 55], "Computers/Internet/Web Design and Development"=>[13.77, 48], "News"=>[8.64, 45], "Arts/Television"=>[5.23, 42], "Arts/Music"=>[2.99, 39], "News/Current Events"=>[2.66, 38], "Society/Issues"=>[2.47, 38], "Computers/Internet/On the Web"=>[2.46, 38], "Business/Investing"=>[1.76, 36]}


问:
Rails: Stripe appears to work but no charge is created
I have a rails app where Stripe is set up similar to this documentation.  When I hit the "Pay With Card" button and enter the test card information it says it's successful, then gives me an error message saying:

```<code>No route matches [POST] "/charges/new"
</code>```

Even though my routes are like this:

```<code>resources :charges
get 'charges/shipping'
get 'charges/address'
post 'charges/update_order'
</code>```

My charges_controller reads like this:

```<code>class ChargesController < ApplicationController

   ...

  def new
    @order = current_order
  end

  def create
    # Amount in cents
    @amount = current_order.total * 100
    @user = current_user
    @order = current_order

    if @user.stripe_customer_id
      customer = @user.stripe_customer_id
    else
      customer = Stripe::Customer.create(
        :email => params[:stripeEmail],
        :source  => params[:stripeToken]
      )
      @user.update_attributes(stripe_customer_id: customer.id)
    end
    @order.update_attributes(order_status_id: 2)
    @order.update_attributes(date_placed: DateTime.now)
    # OrderMailer.order_placed(@order.user, @order).deliver_now
    session[:order_id] = nil

    charge = Stripe::Charge.create(
      :customer    => @user.stripe_customer_id,
      :amount      => @amount.to_i,
      :description => 'Rails Stripe customer',
      :currency    => 'usd'
    )

  rescue Stripe::CardError => e
    flash[:error] = e.message
    redirect_to new_charge_path
  end

  private

  def order_params
    params.permit(:subtotal, :tax, :shipping, :total, :order_status_id, :user_id, :date_placed, :shipping_choice)
  end
end
</code>```

If I manually insert a post "charges/new" into the routes.rb it says it's successful, but it redirects to the same page (indicating a Stripe::CardError) and no charge registers in the stripe dashboard.

Can anyone see where I'm going wrong?

答: Without seeing your client side code, I can't be sure - but it sounds like your client side code is trying to POST to /charges/new - which doesn't exist - so it's failing.  I'd suggest you update your client side code to POST to the route you want to have handle that, and then continue debugging from there.

Body:
I have a rails app where Stripe is set up similar to this documentation.  When I hit the "Pay With Card" button and enter the test card information it says it's successful, then gives me an error message saying:

No route matches [POST] "/charges/new"

Even though my routes are like this:

resources :charges
get 'charges/shipping'
get 'charges/address'
post 'charges/update_order'

My charges_controller reads like this:

class ChargesController < ApplicationController

   ...

  def new
    @order = current_order
  end

  def create
    # Amount in cents
    @amount = current_order.total * 100
    @user = current_user
    @order = current_order

    if @user.stripe_customer_id
      customer = @user.stripe_customer_id
    else
      customer = Stripe::Customer.create(
        :email => params[:stripeEmail],
        :source  => params[:stripeToken]
      )
      @user.update_attributes(stripe_customer_id: customer.id)
    end
    @order.update_attributes(order_status_id: 2)
    @order.update_attributes(date_placed: DateTime.now)
    # OrderMailer.order_placed(@order.user, @order).deliver_now
    session[:order_id] = nil

    charge = Stripe::Charge.create(
      :customer    => @user.stripe_customer_id,
      :amount      => @amount.to_i,
      :description => 'Rails Stripe customer',
      :currency    => 'usd'
    )

  rescue Stripe::CardError => e
    flash[:error] = e.message
    redirect_to new_charge_path
  end

  private

  def order_params
    params.permit(:subtotal, :tax, :shipping, :total, :order_status_id, :user_id, :date_placed, :shipping_choice)
  end
end

If I manually insert a post "charges/new" into the routes.rb it says it's successful, but it redirects to the same page (indicating a Stripe::CardError) and no charge registers in the stripe dashboard.

Can anyone see where I'm going wrong?


问:
do <something> N times (declarative syntax)
Is there a way in Javascript to write something like this easily:

```<code>[1,2,3].times do {
  something();
}
</code>```

Any library that might support some similar syntax maybe?

Update: to clarify - I would like something() to be called 1,2 and 3 times respectively for each array element iteration

答:
```<code>const loop (fn, times) => {
  if (!times) { return }
  fn()
  loop(fn, times - 1)
}

loop(something, 3)
</code>```

Body:
Is there a way in Javascript to write something like this easily:

[1,2,3].times do {
  something();
}

Any library that might support some similar syntax maybe?

Update: to clarify - I would like something() to be called 1,2 and 3 times respectively for each array element iteration


问:
R apply KS Test to 2 Matrices Row by Row
I have two matrices A & B in R with equal number of rows, but different number of columns.

I want to run a Kolomogrov-Smirnov test with row by row with each matrix. That is, the first test would be ks.test(as.vector(A[1,]), as.vector(B[1,]), the second would be ks.test(as.vector(A[2,]), as.vector(B[2,]) and so on. Ideally, storing the resulting of each test in a vector or dataframe.

I figured mapply would be appropriate but it keeps giving me way more results than expected. I think it is performing the tests element by element instead of row by row. This is my code chunk:
mapply(ks.test, x=A, y=B)

Just testing the first row does not work as expected when I simply run:
mapply(ks.test, x=as.vector(A[1,]), y=as.vector(B[1,]))

How can I get the desired output of N p-values where N is the number of rows of my original matrices.?

This is what the first rows of each of my matrices looks like:

> A[1,]

```<code>[1] 0 0 0 0 0 0 0 0 0
</code>```

> B[1,]

```<code> V1  V2  V3  V4  V5  V6  V7  V8  V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20 V21 V22 V23 V24 V25 V26 V27 V28 V29 V30 V31 V32 V33 V34 V35 V36
  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0
</code>```

答:
You can get what you want with sapply used on the row indices

```<code>sapply(1:nrow(A), function(i) ks.test(as.vector(A[i,]), as.vector(B[i,])))
</code>```

actually, it looks like the only interesting part is the p values so this could be simplified with

```<code>sapply(1:nrow(A), function(i) ks.test(as.vector(A[i,]), as.vector(B[i,]))$p)
[1] 0.01587302 0.01587302 0.01587302 0.01587302
</code>```

Body:
I have two matrices A & B in R with equal number of rows, but different number of columns.

I want to run a Kolomogrov-Smirnov test with row by row with each matrix. That is, the first test would be ks.test(as.vector(A[1,]), as.vector(B[1,]), the second would be ks.test(as.vector(A[2,]), as.vector(B[2,]) and so on. Ideally, storing the resulting of each test in a vector or dataframe.

I figured mapply would be appropriate but it keeps giving me way more results than expected. I think it is performing the tests element by element instead of row by row. This is my code chunk:
mapply(ks.test, x=A, y=B)

Just testing the first row does not work as expected when I simply run:
mapply(ks.test, x=as.vector(A[1,]), y=as.vector(B[1,]))

How can I get the desired output of N p-values where N is the number of rows of my original matrices.?

This is what the first rows of each of my matrices looks like:

> A[1,]

[1] 0 0 0 0 0 0 0 0 0

> B[1,]

 V1  V2  V3  V4  V5  V6  V7  V8  V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20 V21 V22 V23 V24 V25 V26 V27 V28 V29 V30 V31 V32 V33 V34 V35 V36
  0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0   0

Body:
You can get what you want with sapply used on the row indices

sapply(1:nrow(A), function(i) ks.test(as.vector(A[i,]), as.vector(B[i,])))

actually, it looks like the only interesting part is the p values so this could be simplified with

sapply(1:nrow(A), function(i) ks.test(as.vector(A[i,]), as.vector(B[i,]))$p)
[1] 0.01587302 0.01587302 0.01587302 0.01587302


问:
Not able to get contents of JSON / Array in PHP
new to php.... can't seem to get the contents of this array... ie. trying to do: $key = var0  and  $value = string0

This is what I am trying the following, with no success:

```<code>$getJSON = [
    {
        "item0": [
            {"var0":"string0"},
            {"var1":"string1"},
            {"var2":"string2"},
            {"var3":"string3"}
        ]
    }
]

$arr = json_decode( $getJSON, true );

$test1 = $arr[0]['item0']['var0'];
$test2 = $arr['item0']['var0'];
</code>```

答:
First of all fix your json part:

```<code>$json = '{
    "item0": [
        {"var0": "string0"},
        {"var1": "string1"},
        {"var2": "string2"},
        {"var3": "string3"}
    ]
}';
</code>```

Now if you var_dump the json_decoded content with

```<code>json_decode($json, JSON_PRETTY_PRINT);
</code>```

you will obtain

```<code>array(1) {

'item0' =>
  array(4) {
    [0] =>
    array(1) {
      'var0' =>
      string(7) "string0"
    }
    [1] =>
    array(1) {
      'var1' =>
      string(7) "string1"
    }
    [2] =>
    array(1) {
      'var2' =>
      string(7) "string2"
    }
    [3] =>
    array(1) {
      'var3' =>
      string(7) "string3"
    }
  }
}
</code>```

This means that you can get values with:

```<code>$decoded = json_decode($json, true);

var_dump($decoded['item0'][0]['var0']);
</code>```

Body:
new to php.... can't seem to get the contents of this array... ie. trying to do: $key = var0  and  $value = string0

This is what I am trying the following, with no success:

$getJSON = [
    {
        "item0": [
            {"var0":"string0"},
            {"var1":"string1"},
            {"var2":"string2"},
            {"var3":"string3"}
        ]
    }
]

$arr = json_decode( $getJSON, true );

$test1 = $arr[0]['item0']['var0'];
$test2 = $arr['item0']['var0'];

Body:
First of all fix your json part:

$json = '{
    "item0": [
        {"var0": "string0"},
        {"var1": "string1"},
        {"var2": "string2"},
        {"var3": "string3"}
    ]
}';

Now if you var_dump the json_decoded content with

json_decode($json, JSON_PRETTY_PRINT);

you will obtain

array(1) {

'item0' =>
  array(4) {
    [0] =>
    array(1) {
      'var0' =>
      string(7) "string0"
    }
    [1] =>
    array(1) {
      'var1' =>
      string(7) "string1"
    }
    [2] =>
    array(1) {
      'var2' =>
      string(7) "string2"
    }
    [3] =>
    array(1) {
      'var3' =>
      string(7) "string3"
    }
  }
}

This means that you can get values with:

$decoded = json_decode($json, true);

var_dump($decoded['item0'][0]['var0']);


问:
sqlite3 in Node.js does not return the lastID from INSERT callback
```<code>db.run("INSERT INTO test VALUES (?)", [testVal], function(err) {
      console.log(err);
      console.log(this.lastId);
      console.log(this);
})
</code>```

err - return null,
this.lastID - return undefined,
this - return Window object

How do I get the last insert identifier?

答:
Actually you have to use the lastID (capital D).

```<code>db.run("INSERT INTO foo ...", function(err) {
    // err is null if insertion was successful
    console.warn("inserted id:", this.**lastID**);
});
</code>```

Source: https://github.com/mapbox/node-sqlite3/issues/206

Body:
db.run("INSERT INTO test VALUES (?)", [testVal], function(err) {
      console.log(err);
      console.log(this.lastId);
      console.log(this);
})

err - return null,
this.lastID - return undefined,
this - return Window object

How do I get the last insert identifier?

Body:
Actually you have to use the lastID (capital D).

db.run("INSERT INTO foo ...", function(err) {
    // err is null if insertion was successful
    console.warn("inserted id:", this.**lastID**);
});

Source: https://github.com/mapbox/node-sqlite3/issues/206