问:
iOS: Reuse the TabBarController with removing some tabs of the old controller
I have a TabBarController with 5 items. I need to reuse this tab view in another place with removing some items. How can I do that. There is only isEnabled button for programmatically doing that. But I need to hide the tab items.

Case 1: Need to display all the tab items from storyboard

```<code>@IBAction func partialAction(_ sender: UIButton) {
    let  partialTabController = storyboard?.instantiateViewController(withIdentifier: "MainTabController") as! MainTabController
    partialTabController.selectedViewController = partialTabController.viewControllers?[3]

    present(partialTabController,animated: true,completion: nil)

}
</code>```

Case 2: Display only a few of the tabs in another section of the application

```<code>@IBAction func partialAction(_ sender: UIButton) {
    let  partialTabController = storyboard?.instantiateViewController(withIdentifier: "MainTabController") as! MainTabController
    partialTabController.selectedViewController = partialTabController.viewControllers?[3]

    // Can I remove some of the tab item using code here

    present(partialTabController,animated: true,completion: nil)

}
</code>```

答:
for Objective c
For set different tab bars on different screen by single TabBarController...
Create the extension class for UITabBarController and create the custom function  bar

```<code>   -(void)customTabBar {
[self.tabBar setBackgroundColor:[UIColor whiteColor]];  //[CommonFunctions colorWithRed:255.0 green:240.0 blue:237.0 alpha:1.0]];
[self.tabBar setBackgroundImage:[[UIImage alloc]init]];
UITabBar *tabBar = self.tabBar;
UITabBarItem *item0 = [tabBar.items objectAtIndex:0];
UITabBarItem *item1 = [tabBar.items objectAtIndex:1];
UITabBarItem *item2 = [tabBar.items objectAtIndex:2];
UITabBarItem *item3 = [tabBar.items objectAtIndex:3];
UITabBarItem *item4 = [tabBar.items objectAtIndex:4];

[item0 setTitle:@"Home"];
[item0 setImage:[[UIImage imageNamed:@"Home"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
[item0 setSelectedImage:[[UIImage imageNamed:@"Homeblue"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];

[item1 setTitle:@"Browse"];
[item1 setImage:[[UIImage imageNamed:@"Browse"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
[item1 setSelectedImage:[[UIImage imageNamed:@"Browseblue"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];

[item2 setTitle:@"Post"];
[item2 setImage:[[UIImage imageNamed:@"Post"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
[item2 setSelectedImage:[[UIImage imageNamed:@"Postblue"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
[item3 setTitle:@"Activity"];
[item3 setImage:[[UIImage imageNamed:@"Activity"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
[item3 setSelectedImage:[[UIImage imageNamed:@"Activityblue"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
[item4 setTitle:@"Profile"];
[item4 setImage:[[UIImage imageNamed:@"Profile"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
[item4 setSelectedImage:[[UIImage imageNamed:@"Profileblue"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];

[item0 setImageInsets:UIEdgeInsetsMake(3, 0, -3, 0)];
[item1 setImageInsets:UIEdgeInsetsMake(3, 0, -3, 0)];
[item2 setImageInsets:UIEdgeInsetsMake(3, 0, -3, 0)];
[item3 setImageInsets:UIEdgeInsetsMake(3, 0, -3, 0)];
[item4 setImageInsets:UIEdgeInsetsMake(3, 0, -3, 0)];
</code>```

}

Now you can create the class instance and use tab according to you ....

And create the instance of your class in appdelegate and create function for add tabs according to you

Create instance for extension class

```<code> @property (strong, nonatomic) CustomTabBarViewController *tabBarController;

  -(void)createTabBarContoller
{
  //Created all tabs controller to be the default for tabs
  UIViewController *viewController1 = [[HomeViewController alloc]
  initWithNibName:@"HomeViewController" bundle:nil];
   UINavigationController *navController1 = [[UINavigationController alloc] initWithRootViewController:viewController1];

  UIViewController *viewController2 = [[SaleViewController alloc] initWithNibName:@"SaleViewController" bundle:nil];
  UINavigationController *navController2 = [[UINavigationController alloc] initWithRootViewController:viewController2];

  UIViewController *viewController3 = [[SellCameraViewController alloc] initWithNibName:@"SellCameraViewController" bundle:nil];
  UINavigationController *navController3 = [[UINavigationController alloc] initWithRootViewController:viewController3];

  UIViewController *viewController4 = [[ActivityViewController alloc] initWithNibName:@"ActivityViewController" bundle:nil];
  UINavigationController *navController4 = [[UINavigationController alloc] initWithRootViewController:viewController4];

  UIViewController *viewController5 = [[MeViewController alloc] initWithNibName:@"MeViewController" bundle:nil];
  UINavigationController *navController5 = [[UINavigationController alloc] initWithRootViewController:viewController5];

  self.tabBarController = [[CustomTabBarViewController alloc] init];
  self.tabBarController.viewControllers = @[navController1, navController2, navController3, navController4, navController5];

  [self.tabBarController setDelegate:self];
  [self.tabBarController customTabBar];
  self.tabBarController.tabBar.layer.borderWidth = 0.50;
  self.tabBarController.tabBar.layer.borderColor = [UIColor colorWithRed:236.0/255.0 green:236.0/255.0 blue:236.0/255.0 alpha:1].CGColor;
  self.tabBarController.tabBar.clipsToBounds = true;

  [self.window setRootViewController:self.tabBarController];
}
</code>```

Actually i am using it swift also but right now i don't have swift code ...

Body:
I have a TabBarController with 5 items. I need to reuse this tab view in another place with removing some items. How can I do that. There is only isEnabled button for programmatically doing that. But I need to hide the tab items.

Case 1: Need to display all the tab items from storyboard

@IBAction func partialAction(_ sender: UIButton) {
    let  partialTabController = storyboard?.instantiateViewController(withIdentifier: "MainTabController") as! MainTabController
    partialTabController.selectedViewController = partialTabController.viewControllers?[3]

    present(partialTabController,animated: true,completion: nil)

}

Case 2: Display only a few of the tabs in another section of the application

@IBAction func partialAction(_ sender: UIButton) {
    let  partialTabController = storyboard?.instantiateViewController(withIdentifier: "MainTabController") as! MainTabController
    partialTabController.selectedViewController = partialTabController.viewControllers?[3]

    // Can I remove some of the tab item using code here

    present(partialTabController,animated: true,completion: nil)

}

Body:
for Objective c
For set different tab bars on different screen by single TabBarController...
Create the extension class for UITabBarController and create the custom function  bar

   -(void)customTabBar {
[self.tabBar setBackgroundColor:[UIColor whiteColor]];  //[CommonFunctions colorWithRed:255.0 green:240.0 blue:237.0 alpha:1.0]];
[self.tabBar setBackgroundImage:[[UIImage alloc]init]];
UITabBar *tabBar = self.tabBar;
UITabBarItem *item0 = [tabBar.items objectAtIndex:0];
UITabBarItem *item1 = [tabBar.items objectAtIndex:1];
UITabBarItem *item2 = [tabBar.items objectAtIndex:2];
UITabBarItem *item3 = [tabBar.items objectAtIndex:3];
UITabBarItem *item4 = [tabBar.items objectAtIndex:4];

[item0 setTitle:@"Home"];
[item0 setImage:[[UIImage imageNamed:@"Home"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
[item0 setSelectedImage:[[UIImage imageNamed:@"Homeblue"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];

[item1 setTitle:@"Browse"];
[item1 setImage:[[UIImage imageNamed:@"Browse"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
[item1 setSelectedImage:[[UIImage imageNamed:@"Browseblue"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];

[item2 setTitle:@"Post"];
[item2 setImage:[[UIImage imageNamed:@"Post"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
[item2 setSelectedImage:[[UIImage imageNamed:@"Postblue"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
[item3 setTitle:@"Activity"];
[item3 setImage:[[UIImage imageNamed:@"Activity"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
[item3 setSelectedImage:[[UIImage imageNamed:@"Activityblue"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
[item4 setTitle:@"Profile"];
[item4 setImage:[[UIImage imageNamed:@"Profile"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
[item4 setSelectedImage:[[UIImage imageNamed:@"Profileblue"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];

[item0 setImageInsets:UIEdgeInsetsMake(3, 0, -3, 0)];
[item1 setImageInsets:UIEdgeInsetsMake(3, 0, -3, 0)];
[item2 setImageInsets:UIEdgeInsetsMake(3, 0, -3, 0)];
[item3 setImageInsets:UIEdgeInsetsMake(3, 0, -3, 0)];
[item4 setImageInsets:UIEdgeInsetsMake(3, 0, -3, 0)];

}

Now you can create the class instance and use tab according to you ....

And create the instance of your class in appdelegate and create function for add tabs according to you

Create instance for extension class

 @property (strong, nonatomic) CustomTabBarViewController *tabBarController;

  -(void)createTabBarContoller
{
  //Created all tabs controller to be the default for tabs
  UIViewController *viewController1 = [[HomeViewController alloc]
  initWithNibName:@"HomeViewController" bundle:nil];
   UINavigationController *navController1 = [[UINavigationController alloc] initWithRootViewController:viewController1];

  UIViewController *viewController2 = [[SaleViewController alloc] initWithNibName:@"SaleViewController" bundle:nil];
  UINavigationController *navController2 = [[UINavigationController alloc] initWithRootViewController:viewController2];

  UIViewController *viewController3 = [[SellCameraViewController alloc] initWithNibName:@"SellCameraViewController" bundle:nil];
  UINavigationController *navController3 = [[UINavigationController alloc] initWithRootViewController:viewController3];

  UIViewController *viewController4 = [[ActivityViewController alloc] initWithNibName:@"ActivityViewController" bundle:nil];
  UINavigationController *navController4 = [[UINavigationController alloc] initWithRootViewController:viewController4];

  UIViewController *viewController5 = [[MeViewController alloc] initWithNibName:@"MeViewController" bundle:nil];
  UINavigationController *navController5 = [[UINavigationController alloc] initWithRootViewController:viewController5];

  self.tabBarController = [[CustomTabBarViewController alloc] init];
  self.tabBarController.viewControllers = @[navController1, navController2, navController3, navController4, navController5];

  [self.tabBarController setDelegate:self];
  [self.tabBarController customTabBar];
  self.tabBarController.tabBar.layer.borderWidth = 0.50;
  self.tabBarController.tabBar.layer.borderColor = [UIColor colorWithRed:236.0/255.0 green:236.0/255.0 blue:236.0/255.0 alpha:1].CGColor;
  self.tabBarController.tabBar.clipsToBounds = true;

  [self.window setRootViewController:self.tabBarController];
}

Actually i am using it swift also but right now i don't have swift code ...


来源: stackexchange

问:
effective use of python shutil copy2
if we take a look at a file copy function, we can see there are several exceptions to handle. A good example is here: http://msdn.microsoft.com/en-us/library/9706cfs5.aspx

my question is if i use python shutil copy2, what should I pay attention to cope with various exceptions (source file not found, access not authorized, etc.)?

e.g.

```<code>def copy_file (self):
    if not os.path.isdir(dest_path):
        os.makedirs(dest_path)
    shutil.copy2(src_path, dest_path)
</code>```

what should i do to the above function?

答:
You may just need handle the IOError exception that may be caused due to any permissions or Invalid destination name issue.

```<code>try:
    shutil.copy(src,dst)
except IOError as e:
    print e
</code>```

The other exceptions mentioned in the MSDN article seems to fall under the same IOError in python. The FileNotFound and DirectoryNotFound are not really applicable as shutil.copy will create the destination if it not already exists. Also, I find that happening of OSError are also remote this in case.

ContentLicense: CC BY-SA 3.0

Title: effective use of python shutil copy2

Body:
if we take a look at a file copy function, we can see there are several exceptions to handle. A good example is here: http://msdn.microsoft.com/en-us/library/9706cfs5.aspx

my question is if i use python shutil copy2, what should I pay attention to cope with various exceptions (source file not found, access not authorized, etc.)?

e.g.

def copy_file (self):
    if not os.path.isdir(dest_path):
        os.makedirs(dest_path)
    shutil.copy2(src_path, dest_path)

what should i do to the above function?

Body:
You may just need handle the IOError exception that may be caused due to any permissions or Invalid destination name issue.

try:
    shutil.copy(src,dst)
except IOError as e:
    print e

The other exceptions mentioned in the MSDN article seems to fall under the same IOError in python. The FileNotFound and DirectoryNotFound are not really applicable as shutil.copy will create the destination if it not already exists. Also, I find that happening of OSError are also remote this in case.

ContentLicense: CC BY-SA 2.5


问:
Returning dictionary as JSON and successfully accessing it's contents withing JS function - C#
I have a Dictionary named finalDictionary which is created by consolidating multiple Dictionaries.
This is the piece of code which I use to create this Dictionary:

```<code>Dictionary<string, Dictionary<DateTime, int>> finalDictionary= new Dictionary<string, Dictionary<DateTime, int>>();

finalDictionary.Add("Data1", listData1.ToDictionary(x => x.Date, y => y.Value));
finalDictionary.Add("Data2", listData2.ToDictionary(x => x.Date, y => y.Value));
finalDictionary.Add("Data3", listData3.ToDictionary(x => x.Date, y => y.Value));
</code>```

NOTE: listData1, listData2 and listData3 are all anonymous lists which I'm converting into dictionaries in the above code.

Here's the sample format for each of these dictionaries: (let's consider for Data1)

```<code>Key : 'Data1'
Value :
        [0] {[6/14/2015 12:00:00 AM, 1]}
        [1] {[6/21/2015 12:00:00 AM, 0]}
        [2] {[6/28/2015 12:00:00 AM, 0]}
        [3] {[7/5/2015 12:00:00 AM, 0]}
        [4] {[7/12/2015 12:00:00 AM, 0]}
        [5] {[7/19/2015 12:00:00 AM, 0]}
        [6] {[7/26/2015 12:00:00 AM, 0]}
</code>```

So each of the dates above are again Key part and those numbers are Value part.

I return this Dictionary i.e finalDictionary as a JSON result from my controller method as follows :

```<code>return Json(new { Result = "OK", Records = obj.GetDetails()}, JsonRequestBehavior.AllowGet);
</code>```

But when this is returned back to my calling JS ajax it fails throwing the below Internal Server 500 error:

```<code>jqXHR = {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}, textStatus = "error", errorThrown = "Internal Server Error //and so on
</code>```

Here's my JS code :

```<code>function loadDetails() {

    $.ajax({
        type: 'GET',
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        cache: false,
        url: _WebRoot() + '/Charts/GetDetails',
        success: function (response, textStatus, jqXHR) {
            prepareData(response.Records, 'Text Title');
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert('Error - ' + errorThrown);
        }
    });
}
</code>```

What modifications do I need to make it work?

NOTE : I receive the above mentioned error after the data is returned from the Controller and reaches the JS method

答:
Converting the datatype of 'Key' ("Date" in my case) element to String fixed the issue.
Initially the "Date" was of DateTime DataType.

Hence when I was returning my above mentioned dictionary as a JSONResult from controller the JS method throwed an error as it was unable to stringify or serialize this dictionary.

So it's advisable to change your Dictionary's 'Key' element's datatype to String or set them as Objects.

Here's the error message I was able to debug out (providing this error message as it might help other's who may face such similar issues) :

```<code>Unhandled Exception: System.ArgumentException: Type 'System.Collections.Generic. Dictionary`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[ChatData, Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' is not supported for serialization/deserialization of a dictionary, keys must be strings or objects.
</code>```

Body:
I have a Dictionary named finalDictionary which is created by consolidating multiple Dictionaries.
This is the piece of code which I use to create this Dictionary:

Dictionary<string, Dictionary<DateTime, int>> finalDictionary= new Dictionary<string, Dictionary<DateTime, int>>();

finalDictionary.Add("Data1", listData1.ToDictionary(x => x.Date, y => y.Value));
finalDictionary.Add("Data2", listData2.ToDictionary(x => x.Date, y => y.Value));
finalDictionary.Add("Data3", listData3.ToDictionary(x => x.Date, y => y.Value));

NOTE: listData1, listData2 and listData3 are all anonymous lists which I'm converting into dictionaries in the above code.

Here's the sample format for each of these dictionaries: (let's consider for Data1)

Key : 'Data1'
Value :
        [0] {[6/14/2015 12:00:00 AM, 1]}
        [1] {[6/21/2015 12:00:00 AM, 0]}
        [2] {[6/28/2015 12:00:00 AM, 0]}
        [3] {[7/5/2015 12:00:00 AM, 0]}
        [4] {[7/12/2015 12:00:00 AM, 0]}
        [5] {[7/19/2015 12:00:00 AM, 0]}
        [6] {[7/26/2015 12:00:00 AM, 0]}

So each of the dates above are again Key part and those numbers are Value part.

I return this Dictionary i.e finalDictionary as a JSON result from my controller method as follows :

return Json(new { Result = "OK", Records = obj.GetDetails()}, JsonRequestBehavior.AllowGet);

But when this is returned back to my calling JS ajax it fails throwing the below Internal Server 500 error:

jqXHR = {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}, textStatus = "error", errorThrown = "Internal Server Error //and so on

Here's my JS code :

function loadDetails() {

    $.ajax({
        type: 'GET',
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        cache: false,
        url: _WebRoot() + '/Charts/GetDetails',
        success: function (response, textStatus, jqXHR) {
            prepareData(response.Records, 'Text Title');
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert('Error - ' + errorThrown);
        }
    });
}

What modifications do I need to make it work?

NOTE : I receive the above mentioned error after the data is returned from the Controller and reaches the JS method

Body:
Converting the datatype of 'Key' ("Date" in my case) element to String fixed the issue.
Initially the "Date" was of DateTime DataType.

Hence when I was returning my above mentioned dictionary as a JSONResult from controller the JS method throwed an error as it was unable to stringify or serialize this dictionary.

So it's advisable to change your Dictionary's 'Key' element's datatype to String or set them as Objects.

Here's the error message I was able to debug out (providing this error message as it might help other's who may face such similar issues) :

Unhandled Exception: System.ArgumentException: Type 'System.Collections.Generic. Dictionary`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[ChatData, Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' is not supported for serialization/deserialization of a dictionary, keys must be strings or objects.


问:
AutoComplete txtfield from array items in Objective c
I have a textfield in which whenever user type it shows related items from array in tableView to select any of them but when user type anything in small keyword it does not show the array. when user enter any word in capital letters as store in an array it shows the array.

i want that when user enter any word whether in small or capital letter it should show the table view containing array. Following is my code,

```<code>    -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    NSLog(@"Range:%@",NSStringFromRange(range));
    NSLog(@"%@",textField.text);

    NSString *passcode = [textField.text stringByReplacingCharactersInRange:range withString:string];

    NSLog(@"%@",passcode);

    NSPredicate *predicate = [NSPredicate predicateWithFormat: @"SELF CONTAINS %@",passcode];

    carArray = [_staticCarArray filteredArrayUsingPredicate:predicate];

    city = [_staticCarArrays filteredArrayUsingPredicate:predicate];

    NSLog(@"%@", carArray);
    NSLog(@"%@", city);

    if ([carArray count]==0) {
        _carTable.hidden = TRUE;
    }else{
        _carTable.hidden = FALSE;
    }

    if ([city count]==0) {
        _autotable.hidden = TRUE;
    }else{
        _autotable.hidden = FALSE;
    }

    [_carTable reloadData];
    [_autotable reloadData];

    return TRUE;

}
</code>```

答:
For case insenstive search Replace

```<code>NSPredicate *predicate = [NSPredicate predicateWithFormat: @"SELF CONTAINS %@",passcode];
</code>```

with

```<code>NSPredicate *predicate = [NSPredicate predicateWithFormat: @"SELF CONTAINS[c] %@",passcode];
</code>```

Here, [c] indicates case insensitive comparison.

Body:
I have a textfield in which whenever user type it shows related items from array in tableView to select any of them but when user type anything in small keyword it does not show the array. when user enter any word in capital letters as store in an array it shows the array.

i want that when user enter any word whether in small or capital letter it should show the table view containing array. Following is my code,

    -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    NSLog(@"Range:%@",NSStringFromRange(range));
    NSLog(@"%@",textField.text);

    NSString *passcode = [textField.text stringByReplacingCharactersInRange:range withString:string];

    NSLog(@"%@",passcode);

    NSPredicate *predicate = [NSPredicate predicateWithFormat: @"SELF CONTAINS %@",passcode];

    carArray = [_staticCarArray filteredArrayUsingPredicate:predicate];

    city = [_staticCarArrays filteredArrayUsingPredicate:predicate];

    NSLog(@"%@", carArray);
    NSLog(@"%@", city);

    if ([carArray count]==0) {
        _carTable.hidden = TRUE;
    }else{
        _carTable.hidden = FALSE;
    }

    if ([city count]==0) {
        _autotable.hidden = TRUE;
    }else{
        _autotable.hidden = FALSE;
    }

    [_carTable reloadData];
    [_autotable reloadData];

    return TRUE;

}

Body:
For case insenstive search Replace

NSPredicate *predicate = [NSPredicate predicateWithFormat: @"SELF CONTAINS %@",passcode];

with

NSPredicate *predicate = [NSPredicate predicateWithFormat: @"SELF CONTAINS[c] %@",passcode];

Here, [c] indicates case insensitive comparison.


问:
How to create an object from a JSON file in Node.js
I have dowloaded a json file which contains a lot of information that I do not need for my end purpose of rendering a table to a html page containing just some of the items of the data.

the data.json looks like

```<code>{ "events": [
 {
  "id": "181101322507029",
  "name": "Carnival Special",
  "type": "public",
  "coverPicture": "https://scontent.xx.fbcdn.net/v/t1.0.jpg?oh=b9eC",
  "profilePicture": "https://scontent.xx.fbcdn.net/v/t1.0-jpg?oh=32c4574",
  "description": "Lots and lots of info blah blah",
  "distance": "1546",
  "startTime": "2017-11-18T22:00:00+0000",
  "endTime": "2017-11-19T03:00:00+0000",
  "timeFromNow": 476169,
  "isCancelled": false,
  "isDraft": false,
  "category": null,
  "ticketing": {
    "ticket_uri": "https://nicevenue.co.uk/event/lime-of-your-life/"
  },
  "place": {
    "id": "517137361697082",
    "name": "Nice Venue",
    "location": {
      "city": "Nice City",
      "country": "United Kingdom",
      "latitude": 66.3445334,
      "longitude": -4.7356667928,
      "street": "The Blah Blah, Blah, Blah Road",
      "zip": "AB1 2CD"
    }
  },
  "stats": {
    "attending": 68,
    "declined": 0,
    "maybe": 177,
    "noreply": 336
  },
  "venue": {
    "id": "517137361697082",
    "name": "Nice Venue",
    "about": "Situated in the blah blah aims to provide a friendly atmosphere, gourmet food and fine cocktails.",
    "emails": [
      "nicevenue@googlemail.com"
    ],
    "coverPicture": "https://scontent.xx.fbcdn.net/v/t31.0-8/s78_o.jpg?oh=8f62cb6CB2",
    "profilePicture": "https://scontent.xx.fbcdn.net/v/t1.0-1/c0.16n.jpg?oh=8ef5df00f31&oe=5AAF3935",
    "category": "Bar",
    "categoryList": [
      "Bar",
      "Restaurant"
    ],
    "location": {
      "city": "Nice City",
      "country": "United Kingdom",
      "latitude": 65.138604292331,
      "longitude": -9.73566d867928,
      "street": "The Blah Blah, Blah, Blah Road",
      "zip": "AB1 2CD"
    }
  }
},
{
  "id": "1896504087342309",
  "name": "Mr Tea  + Dj Dr SJ",
  "type": "public",events
"
"
etc....
</code>```

I need to iterate through this data and create a new object (or array) like

```<code>{"id": 123456 [
 {
  "StartTime": "2017-11-18T22:00:00+0000",
  "description": "Lots and lots of info blah blah",
  "place": {
     "id": "517137361697082",
     "name": "Nice Venue",
     "location": {
     "city": "Nice City",
    "country": "United Kingdom",
    "latitude": 66.3445334,
    "longitude": -4.7356667928,
    "street": "The Blah Blah, Blah, Blah Road",
    "zip": "AB1 2CD"
 }]
 }
</code>```

I would then like to iterate through this object using an express template to render the info to a table tag in the html.

I have looked at For in loops with hasProperty or by using low-dash _.Map  but I don't really understand if I am doing this correctly or even going about what I am trying to do in the best way. Thanks

答:
If you are using ES6 or above you can do something like that to create a new array with the new object:

If you aren't using ES6, the lodash will have the _map

I will keep it simple by using this example of converting firstname to name:

var test = {
    "students": [
        {
            "firstname": "ian",
            "age": 25
        },
         {
            "firstname": "Rick",
            "age": 25
        }
    ]
}

var newList = test.students.map(data => ({
  name: data.firstname ,
  age: data.age
}));

console.log(newList)```

Body:
I have dowloaded a json file which contains a lot of information that I do not need for my end purpose of rendering a table to a html page containing just some of the items of the data.

the data.json looks like

{ "events": [
 {
  "id": "181101322507029",
  "name": "Carnival Special",
  "type": "public",
  "coverPicture": "https://scontent.xx.fbcdn.net/v/t1.0.jpg?oh=b9eC",
  "profilePicture": "https://scontent.xx.fbcdn.net/v/t1.0-jpg?oh=32c4574",
  "description": "Lots and lots of info blah blah",
  "distance": "1546",
  "startTime": "2017-11-18T22:00:00+0000",
  "endTime": "2017-11-19T03:00:00+0000",
  "timeFromNow": 476169,
  "isCancelled": false,
  "isDraft": false,
  "category": null,
  "ticketing": {
    "ticket_uri": "https://nicevenue.co.uk/event/lime-of-your-life/"
  },
  "place": {
    "id": "517137361697082",
    "name": "Nice Venue",
    "location": {
      "city": "Nice City",
      "country": "United Kingdom",
      "latitude": 66.3445334,
      "longitude": -4.7356667928,
      "street": "The Blah Blah, Blah, Blah Road",
      "zip": "AB1 2CD"
    }
  },
  "stats": {
    "attending": 68,
    "declined": 0,
    "maybe": 177,
    "noreply": 336
  },
  "venue": {
    "id": "517137361697082",
    "name": "Nice Venue",
    "about": "Situated in the blah blah aims to provide a friendly atmosphere, gourmet food and fine cocktails.",
    "emails": [
      "nicevenue@googlemail.com"
    ],
    "coverPicture": "https://scontent.xx.fbcdn.net/v/t31.0-8/s78_o.jpg?oh=8f62cb6CB2",
    "profilePicture": "https://scontent.xx.fbcdn.net/v/t1.0-1/c0.16n.jpg?oh=8ef5df00f31&oe=5AAF3935",
    "category": "Bar",
    "categoryList": [
      "Bar",
      "Restaurant"
    ],
    "location": {
      "city": "Nice City",
      "country": "United Kingdom",
      "latitude": 65.138604292331,
      "longitude": -9.73566d867928,
      "street": "The Blah Blah, Blah, Blah Road",
      "zip": "AB1 2CD"
    }
  }
},
{
  "id": "1896504087342309",
  "name": "Mr Tea  + Dj Dr SJ",
  "type": "public",events
"
"
etc....

I need to iterate through this data and create a new object (or array) like

{"id": 123456 [
 {
  "StartTime": "2017-11-18T22:00:00+0000",
  "description": "Lots and lots of info blah blah",
  "place": {
     "id": "517137361697082",
     "name": "Nice Venue",
     "location": {
     "city": "Nice City",
    "country": "United Kingdom",
    "latitude": 66.3445334,
    "longitude": -4.7356667928,
    "street": "The Blah Blah, Blah, Blah Road",
    "zip": "AB1 2CD"
 }]
 }

I would then like to iterate through this object using an express template to render the info to a table tag in the html.

I have looked at For in loops with hasProperty or by using low-dash _.Map  but I don't really understand if I am doing this correctly or even going about what I am trying to do in the best way. Thanks


问:
Hue/Hive user root is not allowed to impersonate Hue
Situation:
I have set up Hive, Hue and Hadoop in different Docker Containers. In the same Docker network. I created a Container for each 1 Hadoop Namenode, 2 Datanodes,1 Hue instance, 1 Hive Server and a Postgres Metastore. I was able to configure a hue proxy user in the hdfs-site.xml of the namenode and can browse the filesystem via webhdfs. For Hive however I get the error within Hue:

```<code>Failed to open new session: java.lang.RuntimeException:
org.apache.hadoop.ipc.RemoteException
(org.apache.hadoop.security.authorize.AuthorizationException):
User: root is not allowed to impersonate hue
</code>```

I am able to create Hive tables in Hive or write to them from within Sparkjobs for example.

What I've tried so far:

I've tried adding properties like

hive.server2.proxy.user = hue

hive.server2.enable.impersonation=true

hadoop.proxyuser.hue.hosts=*

hive.server2.authentication=NONE

in different configuration files like:

core-site.xml in hdfs-namenode configuration folder

core-site.xml in hive-hadoop folder

hdfs-site.xml in both

hive-site.xml in hive-conf folder

Most of this was suggested in similar questions but it does not seem up to-date anymore. For some properties Hive says: Property unknown

What I need clarification on:

What is the right file to add the configuration to ?

What is the right property to add ?

Do I have to add some configuration to hue regarding the metastore ?

Additional Information:
 - Hive Version: 2.3.1
 - Hive Hadoop Version: 2.7.4
 - Hadoop Cluster Version: 2.7.2 (I think version difference should not be the problem here ?!)

Hue Version: 4 (gethue/hue:latest form docker-hub)

The full error log here

Hive configuration here

HDFS-site configuration here

答:
Okay I found a solution that works:

Add the following properties to the hadoop namenodes and datanodes core-site.xml:

```<code><property>
  <name>hadoop.proxyuser.root.groups</name>
  <value>*</value>
</property>
<property>
  <name>hadoop.proxyuser.root.hosts</name>
  <value>*</value>
</property>
</code>```

Furthermore you need to set the path to Hive config if Hive is running on another machine/container in the hue .ini file and copy the hive-config folder to your hue container/machine.

Note that in the Hue docs the configuration for WebHdfs is done in the hdfs-site.xml and the hive configuration is done in hive-site.xml

Body:
Situation:
I have set up Hive, Hue and Hadoop in different Docker Containers. In the same Docker network. I created a Container for each 1 Hadoop Namenode, 2 Datanodes,1 Hue instance, 1 Hive Server and a Postgres Metastore. I was able to configure a hue proxy user in the hdfs-site.xml of the namenode and can browse the filesystem via webhdfs. For Hive however I get the error within Hue:

Failed to open new session: java.lang.RuntimeException:
org.apache.hadoop.ipc.RemoteException
(org.apache.hadoop.security.authorize.AuthorizationException):
User: root is not allowed to impersonate hue

I am able to create Hive tables in Hive or write to them from within Sparkjobs for example.

What I've tried so far:

I've tried adding properties like

hive.server2.proxy.user = hue

hive.server2.enable.impersonation=true

hadoop.proxyuser.hue.hosts=*

hive.server2.authentication=NONE

in different configuration files like:

core-site.xml in hdfs-namenode configuration folder

core-site.xml in hive-hadoop folder

hdfs-site.xml in both

hive-site.xml in hive-conf folder

Most of this was suggested in similar questions but it does not seem up to-date anymore. For some properties Hive says: Property unknown

What I need clarification on:

What is the right file to add the configuration to ?

What is the right property to add ?

Do I have to add some configuration to hue regarding the metastore ?

Additional Information:
 - Hive Version: 2.3.1
 - Hive Hadoop Version: 2.7.4
 - Hadoop Cluster Version: 2.7.2 (I think version difference should not be the problem here ?!)

Hue Version: 4 (gethue/hue:latest form docker-hub)

The full error log here

Hive configuration here

HDFS-site configuration here

Body:
Okay I found a solution that works:

Add the following properties to the hadoop namenodes and datanodes core-site.xml:

<property>
  <name>hadoop.proxyuser.root.groups</name>
  <value>*</value>
</property>
<property>
  <name>hadoop.proxyuser.root.hosts</name>
  <value>*</value>
</property>

Furthermore you need to set the path to Hive config if Hive is running on another machine/container in the hue .ini file and copy the hive-config folder to your hue container/machine.

Note that in the Hue docs the configuration for WebHdfs is done in the hdfs-site.xml and the hive configuration is done in hive-site.xml


问:
CSS3 Background Gradient Overlay HTML5 Video
I want to apply a CSS3 gradient overlay to a video. I have a feeling this could be to do with z-indexing / stack orders so here is my code.

Div structure:

```<code><div class="wrapper">
    <div class="gradient">
        <video></video>
    </div>
</div>
</code>```

The CSS I'm using is a background-image radial gradient:

```<code>.gradient {
        background-image:
        radial-gradient(
            circle at 36% 48%, #000000,
            rgba(11, 39, 65, 0.32) 87%,
            rgba(0, 0, 0, 0.0)
        );
    }
</code>```

The styling is applied to the gradient div along with position: relative; and z-index: 10; to make the gradient overlay the video.

The gradient doesn't appear at all - how is this achievable?

答:
```<code><div class="wrapper">
    <video></video>
    <div class="gradient">
    </div>
</div>
</code>```

Move the video out of the gradient div, now position the gradient over the video with position: absolute and because you have z-index: 10; it should cover the video properly.

One issue with this solution that you will most likely run into if you actually give the .gradient  fixed height & width it will cover the video controls and they won't be clickable.

Body:
I want to apply a CSS3 gradient overlay to a video. I have a feeling this could be to do with z-indexing / stack orders so here is my code.

Div structure:

        <video></video>

The CSS I'm using is a background-image radial gradient:

.gradient {
        background-image:
        radial-gradient(
            circle at 36% 48%, #000000,
            rgba(11, 39, 65, 0.32) 87%,
            rgba(0, 0, 0, 0.0)
        );
    }

The styling is applied to the gradient div along with position: relative; and z-index: 10; to make the gradient overlay the video.

The gradient doesn't appear at all - how is this achievable?

Body:
<div class="wrapper">
    <video></video>
    <div class="gradient">
    </div>
</div>

Move the video out of the gradient div, now position the gradient over the video with position: absolute and because you have z-index: 10; it should cover the video properly.

One issue with this solution that you will most likely run into if you actually give the .gradient  fixed height & width it will cover the video controls and they won't be clickable.


问:
Most recent tag before tip in mercurial
I mark releases with hg tag <version-number>.  When I release a bugfix, I don't want to increment the version number, but I want to use the most recent version number during the build process.  If I run hg tags, it will show tip first, then the version numbers in descending order.  I can get it running hg tags | head -n2 | tail -n1.  I wonder if there is a more elegant, pure mercurial way to get it.

答:
Use the ParentRevSpecExtension: https://www.mercurial-scm.org/wiki/ParentrevspecExtension

It allows you to say tip~1.

EDIT: Sorry, that doesn't answer the question.

Title: Most recent tag before tip in mercurial


问:
Sql Joining 3 Tables Query for Loan Total Result
I have to get the total of Customer Loan from 3 tables the two tables are given loan to sum and the other subtract the paid amount and the tables have Customer ID in common. so far I can get the result only if the Customer ID exist in all tables but if it doesn't exist in one table I won't get Customer in my result. or I get NULL customer IDs when I anchor to the customer.

```<code>SELECT
  AS1.C_ID AS [Customer ID],
  ISNULL(AS1.OldCustomerLoan, 0) AS [Old Loan],
  ISNULL(AS2.NewGivenLoan, 0) AS [New Given Loan],
  ISNULL(AS3.LoanPaid, 0) AS [PaidLoanAmount],
  (ISNULL(AS1.OldCustomerLoan, 0) +
  ISNULL(AS2.NewGivenLoan, 0) -
  ISNULL(AS3.LoanPaid,0) ) AS Total
FROM
  Customer C
  LEFT OUTER JOIN
   (SELECT
       MOC.C_ID,
       SUM(MOC.Quantity) AS OldCustomerLoan
    FROM
       Money_On_Customer MOC (NOLOCK)
    GROUP BY
       MOC.C_ID) AS1
    ON c.C_Id = AS1.C_Id
   LEFT OUTER JOIN
(SELECT
       NGL.C_ID
       ,SUM(NGL.G_Take_Loan) AS NewGivenLoan
    FROM
       Given_Loan NGL
    GROUP BY
       NGL.C_ID) AS2
    ON c.C_Id = AS2.C_Id
LEFT OUTER JOIN
   (SELECT
       GLP.C_ID, SUM(GLP.G_P_Loan) AS LoanPaid
    FROM
       Given_Loan_Paid GLP
    GROUP BY
       GLP.C_ID ) AS3
ON c.C_Id = AS3.C_Id
</code>```

Here Is a picture of my two results:

When I get NULL Customer IDs

When I don't get All the Customers

答:
You need to use c.c_id for the first column

In order to only get records where they exist in at least one of the tables you can add this to you query, just put you current query in place of the dots, and add the leftid col

```<code>Select *
From
(Select c.c_id custonerid,
        Coalesce(Coalesce(as1.c_id,as2.c_id),as3.c_id) leftid,......
 From ....
) ilv
Where leftid is not null
</code>```

You might be able to just add

```<code>Where coalesce(coalesce(as1.c_id,as2.c_id),as3.c_id) is not null
</code>```

To then end of your query

Body:
I have to get the total of Customer Loan from 3 tables the two tables are given loan to sum and the other subtract the paid amount and the tables have Customer ID in common. so far I can get the result only if the Customer ID exist in all tables but if it doesn't exist in one table I won't get Customer in my result. or I get NULL customer IDs when I anchor to the customer.

SELECT
  AS1.C_ID AS [Customer ID],
  ISNULL(AS1.OldCustomerLoan, 0) AS [Old Loan],
  ISNULL(AS2.NewGivenLoan, 0) AS [New Given Loan],
  ISNULL(AS3.LoanPaid, 0) AS [PaidLoanAmount],
  (ISNULL(AS1.OldCustomerLoan, 0) +
  ISNULL(AS2.NewGivenLoan, 0) -
  ISNULL(AS3.LoanPaid,0) ) AS Total
FROM
  Customer C
  LEFT OUTER JOIN
   (SELECT
       MOC.C_ID,
       SUM(MOC.Quantity) AS OldCustomerLoan
    FROM
       Money_On_Customer MOC (NOLOCK)
    GROUP BY
       MOC.C_ID) AS1
    ON c.C_Id = AS1.C_Id
   LEFT OUTER JOIN
(SELECT
       NGL.C_ID
       ,SUM(NGL.G_Take_Loan) AS NewGivenLoan
    FROM
       Given_Loan NGL
    GROUP BY
       NGL.C_ID) AS2
    ON c.C_Id = AS2.C_Id
LEFT OUTER JOIN
   (SELECT
       GLP.C_ID, SUM(GLP.G_P_Loan) AS LoanPaid
    FROM
       Given_Loan_Paid GLP
    GROUP BY
       GLP.C_ID ) AS3
ON c.C_Id = AS3.C_Id

Here Is a picture of my two results:

When I get NULL Customer IDs

When I don't get All the Customers

Body:
You need to use c.c_id for the first column

In order to only get records where they exist in at least one of the tables you can add this to you query, just put you current query in place of the dots, and add the leftid col

Select *
From
(Select c.c_id custonerid,
        Coalesce(Coalesce(as1.c_id,as2.c_id),as3.c_id) leftid,......
 From ....
) ilv
Where leftid is not null

You might be able to just add

Where coalesce(coalesce(as1.c_id,as2.c_id),as3.c_id) is not null

To then end of your query


问:
solution: ts file defined in parent/parallel folder to give import in child module
I have defined directive inside app folder since it is common directive and trying to use in child module project which is inside app/dashboard/project
folder so when I am trying to import it in my child module it is giving can not file module error. same happened when I try to use any service defined in top module and to import in child module.

```<code>import { CpLoopDecorator }  from '../app.facets.directive';
[ts] Cannot find module '../app.facets.directive'.
</code>```

solution:
It is just issue with relative path so once I did ../../app.facets.directive it started giving reference of file since I was importing it in child module

答: Check the relative path to the file '../app.facets.directive' and check that the file name is correct.

Body:
I have defined directive inside app folder since it is common directive and trying to use in child module project which is inside app/dashboard/project
folder so when I am trying to import it in my child module it is giving can not file module error. same happened when I try to use any service defined in top module and to import in child module.

import { CpLoopDecorator }  from '../app.facets.directive';
[ts] Cannot find module '../app.facets.directive'.

solution:
It is just issue with relative path so once I did ../../app.facets.directive it started giving reference of file since I was importing it in child module


问:
How to get the first numbers in a SQL string
I need to get the first number(s) in a string:

1-2-3 --> 1

45-6  --> 45

777 8 --> 777

9ab10 --> 9

How can I do that with SQL?

答:
see
Turning a Comma Separated string into individual rows it can help you to separate the string' and then check by IsNumber</p>


问:
Objective-c, method declaration in .h and private property in .m confusion
I am reading a this tutorial in which he declared a method in cell .h file which accept a block but did not implement the method in .m class, he declared a private property with same name as method @property (copy, nonatomic) void (^didTapButtonBlock)(id sender);

what is this practice? only declaring a method in .h and making a private property in .m

I tried to do it simply like this

I created a method in .h file

```<code>-(void)xyz:(NSString*)string;
</code>```

in .m file

```<code>@property (nonatomic, strong) NSString *string;
</code>```

But Xcode giving warning Method definition for 'xyz' not found

Kindly tell what is going behind the scene?

答:
He's exposing the setter method for the block variable, but keeping the getter private, if you notice, the method have the word set, which is the setter method for a property

This is how you can do the same:

```<code>-(void)setXyz:(NSString*)xyz;
</code>```

and in .m:

```<code>@property (nonatomic, strong) NSString *xyz;
</code>```

This way is to make sure other class cannot get the property instance, but can give it value

Body:
I am reading a this tutorial in which he declared a method in cell .h file which accept a block but did not implement the method in .m class, he declared a private property with same name as method @property (copy, nonatomic) void (^didTapButtonBlock)(id sender);

what is this practice? only declaring a method in .h and making a private property in .m

I tried to do it simply like this

I created a method in .h file

-(void)xyz:(NSString*)string;

in .m file

@property (nonatomic, strong) NSString *string;

But Xcode giving warning Method definition for 'xyz' not found

Kindly tell what is going behind the scene?

Body:
He's exposing the setter method for the block variable, but keeping the getter private, if you notice, the method have the word set, which is the setter method for a property

This is how you can do the same:

-(void)setXyz:(NSString*)xyz;

and in .m:

@property (nonatomic, strong) NSString *xyz;

This way is to make sure other class cannot get the property instance, but can give it value


问:
HTTP basic authorization in rails
I need to send Username and password in header of the request and get some json as response using HTTP basic authorization.
I have set username and password in the controller using

http_basic_authenticate_with name: "dhh", password: "secret", except: :index

how should i send them using http header?
someone please help

答:
Well I am not sure if I understood your question correctly, but you can bypass http basic auth like this:

https://username:password@domain.com

And after that just return data you need in your controller.

Title: HTTP basic authorization in rails


问:
How does the Flyweight pattern in Java work with respect to memory management?
I feel like I have an ok grasp on the design pattern, however I can't seem to get my head around one thing and it doesn't seem to be exactly explained in the resources I've looked at.

That question is, how is the data common, without the data being static, considering the objects are separate entities?

https://www.tutorialspoint.com/design_pattern/flyweight_pattern.htm

In this example, I cannot figure out where the optimisation is occurring, as it looks as if the objects are just being created each time as normal.

```<code>Circle circle = (Circle)ShapeFactory.getCircle(getRandomColor());
circle.setX(getRandomX());
circle.setY(getRandomY());
circle.setRadius(100);
circle.draw();
</code>```

This code block seems like my best guess as the first line retrieves from the HashMap a circle with a certain colour, but this creates a new instance of a circle, with no lasting reference to the colour of the circle.

Therefore, unless I'm mistaken, there is no actual shared data, so I am unsure of how this provides benefits other than maybe during creation.

答:
The ShapeFactory in your linked example will create one Circle per color:

```<code>import java.util.HashMap;

public class ShapeFactory {
   private static final HashMap<String, Shape> circleMap = new HashMap();

   public static Shape getCircle(String color) {
      Circle circle = (Circle)circleMap.get(color);

      if(circle == null) {
         circle = new Circle(color);
         circleMap.put(color, circle);
         System.out.println("Creating circle of color : " + color);
      }
      return circle;
   }
}
</code>```

If no Circle with a specified color exists, it will create a new Circle object and store this instance in the circleMap hashmap. If a Circle with a specific color already exists, it will return the already existing instance from the circleMap.

This is also explained in the text:

ShapeFactory has a HashMap of Circle having key as color of the Circle object. Whenever a request comes to create a circle of particular color to ShapeFactory, it checks the circle object in its HashMap, if object of Circle found, that object is returned otherwise a new object is created, stored in hashmap for future use, and returned to client.

This is also evident in the output shown in the tutorial:

```<code>Creating circle of color : Black
Circle: Draw() [Color : Black, x : 36, y :71, radius :100
Creating circle of color : Green
Circle: Draw() [Color : Green, x : 27, y :27, radius :100
Creating circle of color : White
Circle: Draw() [Color : White, x : 64, y :10, radius :100
Creating circle of color : Red
Circle: Draw() [Color : Red, x : 15, y :44, radius :100
Circle: Draw() [Color : Green, x : 19, y :10, radius :100
Circle: Draw() [Color : Green, x : 94, y :32, radius :100
Circle: Draw() [Color : White, x : 69, y :98, radius :100
</code>```

Each colored Circle is only created once, but modified many times.

I agree that the tutorial doesn't really show the benefit of a Flyweight though. The main point of the flyweight is to externalise shared state. The usual examples I know use character properties in a document.

Instead of having one Character with position, font, size and textDecoration, you would externalize the latter three, thereby reducing the memory needed for each Character instance:

This is some text.

In the line above, the individual characters would only need to store their position, but the formatting is the same, so that can be externalised to a single flyweight object.

This is some bold text.

In the line above, you'd have two flyweights. One for the regular text and another for the four bold character instances.

Body:
I feel like I have an ok grasp on the design pattern, however I can't seem to get my head around one thing and it doesn't seem to be exactly explained in the resources I've looked at.

That question is, how is the data common, without the data being static, considering the objects are separate entities?

https://www.tutorialspoint.com/design_pattern/flyweight_pattern.htm

In this example, I cannot figure out where the optimisation is occurring, as it looks as if the objects are just being created each time as normal.

Circle circle = (Circle)ShapeFactory.getCircle(getRandomColor());
circle.setX(getRandomX());
circle.setY(getRandomY());
circle.setRadius(100);
circle.draw();

This code block seems like my best guess as the first line retrieves from the HashMap a circle with a certain colour, but this creates a new instance of a circle, with no lasting reference to the colour of the circle.

Therefore, unless I'm mistaken, there is no actual shared data, so I am unsure of how this provides benefits other than maybe during creation.

Body:
The ShapeFactory in your linked example will create one Circle per color:

import java.util.HashMap;

public class ShapeFactory {
   private static final HashMap<String, Shape> circleMap = new HashMap();

   public static Shape getCircle(String color) {
      Circle circle = (Circle)circleMap.get(color);

      if(circle == null) {
         circle = new Circle(color);
         circleMap.put(color, circle);
         System.out.println("Creating circle of color : " + color);
      }
      return circle;
   }
}

If no Circle with a specified color exists, it will create a new Circle object and store this instance in the circleMap hashmap. If a Circle with a specific color already exists, it will return the already existing instance from the circleMap.

This is also explained in the text:

ShapeFactory has a HashMap of Circle having key as color of the Circle object. Whenever a request comes to create a circle of particular color to ShapeFactory, it checks the circle object in its HashMap, if object of Circle found, that object is returned otherwise a new object is created, stored in hashmap for future use, and returned to client.

This is also evident in the output shown in the tutorial:

Creating circle of color : Black
Circle: Draw() [Color : Black, x : 36, y :71, radius :100
Creating circle of color : Green
Circle: Draw() [Color : Green, x : 27, y :27, radius :100
Creating circle of color : White
Circle: Draw() [Color : White, x : 64, y :10, radius :100
Creating circle of color : Red
Circle: Draw() [Color : Red, x : 15, y :44, radius :100
Circle: Draw() [Color : Green, x : 19, y :10, radius :100
Circle: Draw() [Color : Green, x : 94, y :32, radius :100
Circle: Draw() [Color : White, x : 69, y :98, radius :100

Each colored Circle is only created once, but modified many times.

I agree that the tutorial doesn't really show the benefit of a Flyweight though. The main point of the flyweight is to externalise shared state. The usual examples I know use character properties in a document.

Instead of having one Character with position, font, size and textDecoration, you would externalize the latter three, thereby reducing the memory needed for each Character instance:

This is some text.

In the line above, the individual characters would only need to store their position, but the formatting is the same, so that can be externalised to a single flyweight object.

This is some bold text.

In the line above, you'd have two flyweights. One for the regular text and another for the four bold character instances.


问:
Magento - Child theme starting point
I've recently started to learn Magento (very recently) - and I followed this link to get started on XAMPP https://magenticians.com/install-magento-2-on-localhost-using-xampp/

I now have a localhost setup of XAMPP, and would like to start making changes to the site. I have read that you need to create a 'child-theme' but really unsure of where to start on this.

I can see 2 themes at C:\xampp\htdocs\magento\vendor\magento\theme-frontend-luma
but can't see any at C:\xampp\htdocs\magento\app\design\frontend

Does anyone have a pointer in the right direction? or even a version with populated content/a child theme ready to edit?

Sorry and thanks in advance

答:
you need follwing file for making child theme

```<code>app> design> forntend> <Vendor> / <Theme_Child> /
</code>```

1- composer.json (optional in case parent have)

2- registration.php

3- media folder  (with preview image)

4- Magento_Theme

5- etc

6- view.xml

Title: Magento - Child theme starting point

Body:
you need follwing file for making child theme

app> design> forntend> <Vendor> / <Theme_Child> /

1- composer.json (optional in case parent have)

2- registration.php

3- media folder  (with preview image)

4- Magento_Theme

5- etc

6- view.xml


问:
RestClient for Elastic Search
I am trying to fetch data from Elastic search cluster.
Index Name  : testIndex
Type : testType
host : localhost
port : 8080

I want to use Elastic Search 5.4 version and using RestClient I would like to fetch data using multimatch query.

Sample Query would look something like this.

```<code>GET testIndex/testType/_search
{
  "query": {
    "multi_match": {
      "query":"slabs",
      "fields": ["field1","field2"]
    }
  }
}
</code>```

What would be the best way to do that ?  Is it possible that I can use QueryBuilder to build queries and use that with rest client.

答:
The QueryBuilder for the RestClient will be available when version 6 is released. There will be a Low Level and a High Level REST Client. The High Level REST client will support the QueryBuilder. You can already play around with it here:

QueryBuilder with High Level REST Client

Until then, the QueryBuilder is not available for the REST Client so with version 5.4 you need to build the queries yourself. There a many ways to do this.

One way is to use a language template like jTwig. A very nice example on how to do this is explained by Jettro Coenradie here.

Title: RestClient for Elastic Search

Body:
I am trying to fetch data from Elastic search cluster.
Index Name  : testIndex
Type : testType
host : localhost
port : 8080

I want to use Elastic Search 5.4 version and using RestClient I would like to fetch data using multimatch query.

Sample Query would look something like this.

GET testIndex/testType/_search
{
  "query": {
    "multi_match": {
      "query":"slabs",
      "fields": ["field1","field2"]
    }
  }
}

What would be the best way to do that ?  Is it possible that I can use QueryBuilder to build queries and use that with rest client.


问:
Using kajiki in TG2.1
the recently released turbogears 2.1 mentioned about the support of kajiki, a genshi-like templating engine, but i cant find any resource on how to get started to use tg2.1 with kajiki. any ideas?</p>

答:
I enabled Kajiki in a TG 2.1 project by changing the <projectname>/config/app_cfg.py file.
After the line

```<code>base_config.renderers.append('genshi')
</code>```

just add

```<code>base_config.renderers.append('kajiki')
</code>```

You can later use a Kajiki template from any of your actions by decorating it with something like

```<code> @expose('kajiki:projectname.templates.sometemplate')
</code>```

You can also set Kajiki as the default template language by changing the base_config.default_renderer assignment in app_cfg.py. If you do this, you won't need the kajiki: prefix when decorating, e.g.,

```<code>@expose('projectname.templates.sometemplate')
</code>```

will suffice.

After this works for you, changing setup.py to add a Kajiki dependency is probably all you need in order to have a working project. The only thing I haven't tried as yet is i18n; I'll probably update this answer when I do.

Title: Using kajiki in TG2.1

Body:
I enabled Kajiki in a TG 2.1 project by changing the <projectname>/config/app_cfg.py file.
After the line

base_config.renderers.append('genshi')

just add

base_config.renderers.append('kajiki')

You can later use a Kajiki template from any of your actions by decorating it with something like

 @expose('kajiki:projectname.templates.sometemplate')

You can also set Kajiki as the default template language by changing the base_config.default_renderer assignment in app_cfg.py. If you do this, you won't need the kajiki: prefix when decorating, e.g.,

@expose('projectname.templates.sometemplate')

will suffice.

After this works for you, changing setup.py to add a Kajiki dependency is probably all you need in order to have a working project. The only thing I haven't tried as yet is i18n; I'll probably update this answer when I do.


问:
Python Matplotlib generate graph from CSV
I have a CSV file which contains two columns of data, the first column is time in the 24 hour format, i.e. 13h20m10s.

I am trying to pull this data out and plot it in a a graph using matplotlib. I have this line of code:

```<code>data = np.genfromtxt('graph.csv', dtype='str', delimiter =',', skip_header=0, usecols=[0], autostrip='true')

x = [mdates.date2num(dt.datetime.strptime(x[0], '%Hh:%Mm:%Ss')) for x in data]
print(x)
y = np.loadtxt('graph.csv', delimiter=',', skiprows=0,usecols=[1])
print(y)
</code>```

However when I run it I get the error

"ValueError: time data '1' does no match format '%Hh:%Mm%Ss'

if I change the code for the x data to:

```<code>x = [mdates.date2num(dt.datetime.strptime(x[0], '%H')) for x in data]
</code>```

the script will run, but my time values are then wrong... obviously.

Can anyone help with why it will not plot correctly?

答:
The problem is the : marks. You don't have those in the time column you describe</p>

```<code>import datetime as dt
dateString='13h20m10s'
date_with_format = dt.datetime.strptime(dateString,'%Hh%Mm%Ss')
</code>```

Body:
I have a CSV file which contains two columns of data, the first column is time in the 24 hour format, i.e. 13h20m10s.

I am trying to pull this data out and plot it in a a graph using matplotlib. I have this line of code:

data = np.genfromtxt('graph.csv', dtype='str', delimiter =',', skip_header=0, usecols=[0], autostrip='true')

x = [mdates.date2num(dt.datetime.strptime(x[0], '%Hh:%Mm:%Ss')) for x in data]
print(x)
y = np.loadtxt('graph.csv', delimiter=',', skiprows=0,usecols=[1])
print(y)

However when I run it I get the error

"ValueError: time data '1' does no match format '%Hh:%Mm%Ss'

if I change the code for the x data to:

x = [mdates.date2num(dt.datetime.strptime(x[0], '%H')) for x in data]

the script will run, but my time values are then wrong... obviously.

Can anyone help with why it will not plot correctly?

Body:
The problem is the : marks. You don't have those in the time column you describe

import datetime as dt
dateString='13h20m10s'
date_with_format = dt.datetime.strptime(dateString,'%Hh%Mm%Ss')


答:
Try this

add a sibling to video make its position:absolute and add z-index

.wrapper {
    position: relative;
    width: 100%;
    height: 100%;
    //padding: 20px;
    border-radius: 5px;
    background-attachment: scroll;
    overflow: hidden;
}
.wrapper video {
    min-width: 100%;
    min-height: 100%;
    position: relative;
    z-index: 1;
}
.wrapper .overlay {
    height: 100%;
    width: 100%;
    position: absolute;
    top: 0px;
    left: 0px;
    z-index: 2;
   background-image:
        radial-gradient(
            circle at 36% 48%, #000000,
            rgba(11, 39, 65, 0.32) 87%,
            rgba(0, 0, 0, 0.0)
        );
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
<div class="overlay"></div>
    <div class="gradient">
        <video>
          //your video
        </video>
    </div>
</div></code>```

Title: CSS3 Background Gradient Overlay HTML5 Video

Body:
Try this

add a sibling to video make its position:absolute and add z-index

.wrapper {
    position: relative;
    width: 100%;
    height: 100%;
    //padding: 20px;
    border-radius: 5px;
    background-attachment: scroll;
    overflow: hidden;
}
.wrapper video {
    min-width: 100%;
    min-height: 100%;
    position: relative;
    z-index: 1;
}
.wrapper .overlay {
    height: 100%;
    width: 100%;
    position: absolute;
    top: 0px;
    left: 0px;
    z-index: 2;
   background-image:
        radial-gradient(
            circle at 36% 48%, #000000,
            rgba(11, 39, 65, 0.32) 87%,
            rgba(0, 0, 0, 0.0)
        );
}

<div class="wrapper">
<div class="overlay"></div>
    <div class="gradient">
        <video>
          //your video
        </video>
    </div>
</div>


问:
Will clearInterval stop queued interval execution
Let's say I have these this

```<code>myInterval=setInterval(funcA,50);

function funcA(){
  //Some code that takes longer than 50ms to run
}

setTimeout(function(){clearInterval(myInterval);},10000}
</code>```

Let's say funcA always takes longer than 50ms to make it simple. Naturally, many funcA runs will pile up and be queued. Will clearInterval remove those queued runs or just stop queuing new ones?

I did make a fiddle to test it, and it turns out clearInterval stops all future execution, even those that have already be queued. I just need to confirm this behavior is consistent (across browsers/platforms).

var myInterval=setInterval(funcA,20);

setTimeout(function(){
  clearInterval(myInterval);

  console.log('Clearing interval at ' + Date.now());

},400);

var lastRunTimeStamp=0;

function funcA(){
  while(Date.now()<lastRunTimeStamp+25){}
  lastRunTimeStamp=Date.now();
  console.log('Run at ' + lastRunTimeStamp);
}```

--Update--

The queued execution assumption in this question is incorrect, please check T.J. Crowder answer for an explanation.

答:
Naturally, many funcA runs will pile up and be queued.

No, they won't, because of the way the repeated timer works. Timer behavior in browsers is (now) specified by the WHAT-WG "HTML5" specification. Queuing the next task is done as part of the previous task, after your callback has completed, not separately from it; details here. So there will only be one outstanding task at a time (after it's been queued, before the JavaScript engine can pick it up and work on it).

Will clearInterval remove those queued runs or just stop queuing new ones?

No*, but it doesn't have to. The first step in the task queued by the timer system is to see if the timer is still on the list of active timers; if it isn't, the task terminates before calling your callback. So it's as though clearInterval removed the task (e.g., your formerly-queued callback doesn't get run), but not because clearInterval cleared it (instead, it's because the task checked).

It's easy to test and prove the behavior: Just schedule a timer, then busy-wait for longer than its interval, then clear it:

var counter = 0;
var timer = setInterval(function() {
  ++counter;
  console.log("timer fired:", counter);
  if (counter == 1) {
    setTimeout(busyWaitAndClear, 0);
  }
}, 500); // Every 500ms
function busyWaitAndClear() { // Obviously never really do this
  var done = Date.now() + 1000;
  while (done > Date.now()) {
    // wait
  }
  clearInterval(timer);
  console.log("timer cleared");
}```

Note that the timer only fires once, and doesn't fire a second time even though presumably at least one task to fire it was queued while we busy-waited.

* ("No" - The description of clearInterval doesn't say anything about reading into the pending tasks list and removing tasks queued by the interval but not yet picked up.)

Body:
Let's say I have these this

myInterval=setInterval(funcA,50);

function funcA(){
  //Some code that takes longer than 50ms to run
}

setTimeout(function(){clearInterval(myInterval);},10000}

Let's say funcA always takes longer than 50ms to make it simple. Naturally, many funcA runs will pile up and be queued. Will clearInterval remove those queued runs or just stop queuing new ones?

I did make a fiddle to test it, and it turns out clearInterval stops all future execution, even those that have already be queued. I just need to confirm this behavior is consistent (across browsers/platforms).

var myInterval=setInterval(funcA,20);

setTimeout(function(){
  clearInterval(myInterval);

  console.log('Clearing interval at ' + Date.now());

},400);

var lastRunTimeStamp=0;

function funcA(){
  while(Date.now()<lastRunTimeStamp+25){}
  lastRunTimeStamp=Date.now();
  console.log('Run at ' + lastRunTimeStamp);
}

--Update--

The queued execution assumption in this question is incorrect, please check T.J. Crowder answer for an explanation.

Body:
Naturally, many funcA runs will pile up and be queued.

No, they won't, because of the way the repeated timer works. Timer behavior in browsers is (now) specified by the WHAT-WG "HTML5" specification. Queuing the next task is done as part of the previous task, after your callback has completed, not separately from it; details here. So there will only be one outstanding task at a time (after it's been queued, before the JavaScript engine can pick it up and work on it).

Will clearInterval remove those queued runs or just stop queuing new ones?

No*, but it doesn't have to. The first step in the task queued by the timer system is to see if the timer is still on the list of active timers; if it isn't, the task terminates before calling your callback. So it's as though clearInterval removed the task (e.g., your formerly-queued callback doesn't get run), but not because clearInterval cleared it (instead, it's because the task checked).

It's easy to test and prove the behavior: Just schedule a timer, then busy-wait for longer than its interval, then clear it:

var counter = 0;
var timer = setInterval(function() {
  ++counter;
  console.log("timer fired:", counter);
  if (counter == 1) {
    setTimeout(busyWaitAndClear, 0);
  }
}, 500); // Every 500ms
function busyWaitAndClear() { // Obviously never really do this
  var done = Date.now() + 1000;
  while (done > Date.now()) {
    // wait
  }
  clearInterval(timer);
  console.log("timer cleared");
}

Note that the timer only fires once, and doesn't fire a second time even though presumably at least one task to fire it was queued while we busy-waited.

* ("No" - The description of clearInterval doesn't say anything about reading into the pending tasks list and removing tasks queued by the interval but not yet picked up.)

ContentLicense: CC BY-SA 4.0


问:
ng test fail after adding 'ng2-dateime '
I have added ng2-datetime module in my Angular 4 project.

Now problem I am facing with ng test.

Currently it throws error like below.

```<code>'Cannot find name 'jQuery'
'Cannot find name '$'
</code>```

EDIT:

I did tried same way as most of answer below which is adding below lines in typings.d.ts

```<code>declare var jQuery: any;
declare var $: any;
</code>```

this will start 'ng test' but it will throw error while making build using ng build --prod.

```<code>Cannot redeclare block-scoped variable 'jQuery'
Cannot redeclare block-scoped variable '$'
</code>```

TIA

答:
I didn't added 'jQuery' in 'types' section in tsconfig.spec.json file.

After this it started working.

Body:
I have added ng2-datetime module in my Angular 4 project.

Now problem I am facing with ng test.

Currently it throws error like below.

'Cannot find name 'jQuery'
'Cannot find name '$'

EDIT:

I did tried same way as most of answer below which is adding below lines in typings.d.ts

declare var jQuery: any;
declare var $: any;

this will start 'ng test' but it will throw error while making build using ng build --prod.

Cannot redeclare block-scoped variable 'jQuery'
Cannot redeclare block-scoped variable '$'

TIA


问:
Using kinect with python on a raspberry pi 3, is there a better/faster way for more fps?
I recently got a kinect camera to work on a raspberry pi 3 using libfreenect and pygame following this guy's work and I'm getting around 13fps but I was wondering if theres a better/faster way to get more fps or is it just a hardware limitation?

Here is the code right now:

```<code>from freenect import sync_get_depth as get_depth
import pygame
import numpy
import sys

def make_gamma():
    num_pix = 2048 # there's 2048 different possible depth values
    npf = float(num_pix)
    _gamma = numpy.empty((num_pix, 3), dtype=numpy.uint16)
    for i in xrange(num_pix):
        if i < 950:
            a = numpy.array([255, 0, 0], dtype=numpy.uint8)
        else:
            a = numpy.array([0, 0, 0], dtype=numpy.uint8)

        _gamma[i] = a
    return _gamma

fpsClock = pygame.time.Clock()
FPS = 30 # kinect only outputs 30 fps
disp_size = (640, 480)
pygame.init()
screen = pygame.display.set_mode(disp_size)
pygame.display.set_caption('Kinect depth display')
font = pygame.font.Font('/usr/share/fonts/truetype/freefont/FreeSerif.ttf', 32)

gamma = make_gamma()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    fps_text = "FPS: {0:.2f}".format(fpsClock.get_fps())

    # draw the pixels
    depth = numpy.rot90(get_depth()[0])
    pixels = gamma[depth]
    temp_surface = pygame.Surface(disp_size)
    pygame.surfarray.blit_array(temp_surface, pixels)
    pygame.transform.scale(temp_surface, disp_size, screen)
    screen.blit(font.render(fps_text, 1, (255, 255, 255)), (30, 30))
    pygame.display.flip()
    fpsClock.tick(FPS)
</code>```

答: You can use the C/C++ native code to read frames and stream them via system pipe. You will need to encode depth data into hexadecimal values and print them to console. </p>

Body:
I recently got a kinect camera to work on a raspberry pi 3 using libfreenect and pygame following this guy's work and I'm getting around 13fps but I was wondering if theres a better/faster way to get more fps or is it just a hardware limitation?

Here is the code right now:

from freenect import sync_get_depth as get_depth
import pygame
import numpy
import sys

def make_gamma():
    num_pix = 2048 # there's 2048 different possible depth values
    npf = float(num_pix)
    _gamma = numpy.empty((num_pix, 3), dtype=numpy.uint16)
    for i in xrange(num_pix):
        if i < 950:
            a = numpy.array([255, 0, 0], dtype=numpy.uint8)
        else:
            a = numpy.array([0, 0, 0], dtype=numpy.uint8)

        _gamma[i] = a
    return _gamma

fpsClock = pygame.time.Clock()
FPS = 30 # kinect only outputs 30 fps
disp_size = (640, 480)
pygame.init()
screen = pygame.display.set_mode(disp_size)
pygame.display.set_caption('Kinect depth display')
font = pygame.font.Font('/usr/share/fonts/truetype/freefont/FreeSerif.ttf', 32)

gamma = make_gamma()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    fps_text = "FPS: {0:.2f}".format(fpsClock.get_fps())

    # draw the pixels
    depth = numpy.rot90(get_depth()[0])
    pixels = gamma[depth]
    temp_surface = pygame.Surface(disp_size)
    pygame.surfarray.blit_array(temp_surface, pixels)
    pygame.transform.scale(temp_surface, disp_size, screen)
    screen.blit(font.render(fps_text, 1, (255, 255, 255)), (30, 30))
    pygame.display.flip()
    fpsClock.tick(FPS)


问:
How to avoid Rails scaffold to place model into namespace
Rails 3 scaffold generator places model classes inside namespace.
Example:

```<code>rails generate scaffold admin/portfolio
</code>```

But I want only controllers and views to be placed inside admin namespace.

How can I avoid that?

答:
You can do this now on Rails (or at least on 5.1) using the following command:

```<code>rails g scaffold_controller admin/portfolio --model-name=Portfolio
</code>```

By specifying --model-name Rails does not automatically tries to guess the model name.

Body:
Rails 3 scaffold generator places model classes inside namespace.
Example:

rails generate scaffold admin/portfolio

But I want only controllers and views to be placed inside admin namespace.

How can I avoid that?

Body:
You can do this now on Rails (or at least on 5.1) using the following command:

rails g scaffold_controller admin/portfolio --model-name=Portfolio

By specifying --model-name Rails does not automatically tries to guess the model name.


问:
Sending image file via HTTP post prepends unwanted characters to the file
I'm trying to send a simple image file to a lambda function. Once it gets to the function I need to turn it into a buffer and then manipulate it. Right now when data is received there are a bunch of characters prepended to the data:

```<code>"body": "--X-INSOMNIA-BOUNDARY\r\nContent-Disposition: form-data; name=\"image\"; filename=\"americanflag.png\"\r\nContent-Type: image/png\r\n\r\n�PNG\r\n\n\rIHDR0�\b�;BIDATx��]u|����{g��.H\b^h�F)PJ�������Www﫻P���\"E��$!nk3���3�l���{��=�L�����=��=�|)����ٿ)��\"�$��q�����\r���'s��4����֦M��\"C�y��*U�YbUEc����|�ƼJ���@�=�/ �6���OD�p�����[�Q�D��\b�<hheB��&2���}�F�*�1M�u������BR�%\b�1RD�Q�������Q��}��R )%ĉ�Idv�݌髝�S��_W�Z�xSaZ��p�5k�{�|�\\�?
</code>```

I have no idea how to handle that. My plan has just been to create a buffer as you normally would in Node:Buffer.from(data, 'utf8'). But it's throwing an error

Things I've tried:
I've been testing the function with Insomniac and Postman, both with the same result.

I've gone with both a multipart/form and binary file for the body
of the request.

I've tried multiple image files.

I've set the header of content-type to image/png and other file
types.

I've removed the headers.

I know that I could upload the files to S3 and that would be much easier but it negates the point of what I'm writing. I don't want to store the images I just want to manipulate them and then discard them.

This is what the response looks like when I send it back to myself.

Edit: The full code is uploaded. Again, I'm not sending via node at this very moment. It's simply through Postman/Insomniac. If the answer is simply "write your own encoder" then please put that as an answer.

答:
Because you did not upload full code so based on my best prediction I post an answer here. There are probably any of the solutions may help to you.

Encoding Base64 Strings:

```<code>'use strict';
let data = '`stackoverflow.com`';
let buff = new Buffer(data);
let base64data = buff.toString('base64');
console.log('"' + data + '" converted to Base64 is "' + base64data + '"');
</code>```

Decoding Base64 Strings:

```<code>'use strict';
let data = 'YHN0YWNrb3ZlcmZsb3cuY29tYA==';
let buff = new Buffer(data, 'base64');
let text = buff.toString('ascii');
console.log('"' + data + '" converted from Base64 to ASCII is "' + text + '"');
</code>```

Encoding binary data to base64 string:

```<code>'use strict';
const fs = require('fs');
let buff = fs.readFileSync('image-log.png');
let base64data = buff.toString('base64');
console.log('Image converted to base 64 is:\n\n' + base64data);
</code>```

Decoding Base64 Strings to Binary Data:

```<code>'use strict';
const fs = require('fs');
let data = 'encoded binary  string';
let buff = new Buffer(data, 'base64');
fs.writeFileSync('image-log.png', buff);
console.log('Base64 image data converted to file: image-log.png');
</code>```

Base64 encoding is the way to converting binary data into plain ASCII text. It is a very useful format for communicating between one or more systems that cannot easily handle binary data, like images in HTML markup or web requests.

In Node.js the Buffer object can be used to encode and decode Base64 strings to and from many other formats, allowing you to easily convert data back and forth as needed.

Body:
I'm trying to send a simple image file to a lambda function. Once it gets to the function I need to turn it into a buffer and then manipulate it. Right now when data is received there are a bunch of characters prepended to the data:

"body": "--X-INSOMNIA-BOUNDARY\r\nContent-Disposition: form-data; name=\"image\"; filename=\"americanflag.png\"\r\nContent-Type: image/png\r\n\r\n�PNG\r\n\n\rIHDR0�\b�;BIDATx��]u|����{g��.H\b^h�F)PJ�������Www﫻P���\"E��$!nk3���3�l���{��=�L�����=��=�|)����ٿ)��\"�$��q�����\r���'s��4����֦M��\"C�y��*U�YbUEc����|�ƼJ���@�=�/ �6���OD�p�����[�Q�D��\b�<hheB��&2���}�F�*�1M�u������BR�%\b�1RD�Q�������Q��}��R )%ĉ�Idv�݌髝�S��_W�Z�xSaZ��p�5k�{�|�\\�?

I have no idea how to handle that. My plan has just been to create a buffer as you normally would in Node:Buffer.from(data, 'utf8'). But it's throwing an error

Things I've tried:
I've been testing the function with Insomniac and Postman, both with the same result.

I've gone with both a multipart/form and binary file for the body
of the request.

I've tried multiple image files.

I've set the header of content-type to image/png and other file
types.

I've removed the headers.

I know that I could upload the files to S3 and that would be much easier but it negates the point of what I'm writing. I don't want to store the images I just want to manipulate them and then discard them.

This is what the response looks like when I send it back to myself.

Edit: The full code is uploaded. Again, I'm not sending via node at this very moment. It's simply through Postman/Insomniac. If the answer is simply "write your own encoder" then please put that as an answer.

Body:
Because you did not upload full code so based on my best prediction I post an answer here. There are probably any of the solutions may help to you.

Encoding Base64 Strings:

'use strict';
let data = '`stackoverflow.com`';
let buff = new Buffer(data);
let base64data = buff.toString('base64');
console.log('"' + data + '" converted to Base64 is "' + base64data + '"');

Decoding Base64 Strings:

'use strict';
let data = 'YHN0YWNrb3ZlcmZsb3cuY29tYA==';
let buff = new Buffer(data, 'base64');
let text = buff.toString('ascii');
console.log('"' + data + '" converted from Base64 to ASCII is "' + text + '"');

Encoding binary data to base64 string:

'use strict';
const fs = require('fs');
let buff = fs.readFileSync('image-log.png');
let base64data = buff.toString('base64');
console.log('Image converted to base 64 is:\n\n' + base64data);

Decoding Base64 Strings to Binary Data:

'use strict';
const fs = require('fs');
let data = 'encoded binary  string';
let buff = new Buffer(data, 'base64');
fs.writeFileSync('image-log.png', buff);
console.log('Base64 image data converted to file: image-log.png');

Base64 encoding is the way to converting binary data into plain ASCII text. It is a very useful format for communicating between one or more systems that cannot easily handle binary data, like images in HTML markup or web requests.

In Node.js the Buffer object can be used to encode and decode Base64 strings to and from many other formats, allowing you to easily convert data back and forth as needed.


问:
Pass results of querySelectorAll to EventTarget.addEventListener
I want to do something like:

```<code>open Webapi.Dom;

let addListener = (element) =>
    EventTarget.addEventListener("click", onSubscribeClick, EventTarget.asEventTarget(element));

let addOrRemoveListeners = (handler, ()) => {
    let elements = Document.querySelectorAll({j|[$subscriptionIdAttr]|j}, document);
    Js.Array.forEach(handler, NodeListRe.toArray(elements) |> Js.Array.map(Element.ofNode))
  };

let addListeners = addOrRemoveListeners(addListener);

let removeListeners = addOrRemoveListeners(removeListener);
</code>```

But I get an error in addOrRemoveListeners(addListener);:

```<code>This is:
  (Dom.eventTarget) => unit
But somewhere wanted:
  (Dom.node) => unit
</code>```

How should I convert from Dom.eventTarget to Dom.node?

Edit: I ended up with this:

```<code>let addListener = Element.addEventListener("click", onSubscribeClick);
let removeListener = Element.removeEventListener("click", onSubscribeClick);
let addOrRemoveListeners = (handler, ()) => {
  let elements = Document.querySelectorAll({j|[$(subscriptionIdAttr)]|j}, document);
  let () =
    elements
    |> NodeListRe.toArray
    |> Array.map(Element.ofNode)
    |> Array.to_list
    |> List.filter(Js.Option.isSome)
    |> List.map(Js.Option.getExn)
    |> List.iter(handler);
  ()
};
let addListeners = addOrRemoveListeners(addListener);
let removeListeners = addOrRemoveListeners(removeListener);
</code>```

答:
Short answer:

```<code>external eventTargetToNode : Dom.eventTarget => Dom.node = "%identity";
</code>```

An eventTarget can be almost anything, and there's unfortunately no good way of figuring out what it is. In JavaScript it's simply inferred by the user based on context (It might be possible to carry that context around in a type parameter, but that's off in the future somewhere).

So for the moment you'll have to make an unsafe cast to get what you need.

(BTW, you can use Element.addEventListener to avoid the cast from element to eventTarget)

Body:
I want to do something like:

open Webapi.Dom;

let addListener = (element) =>
    EventTarget.addEventListener("click", onSubscribeClick, EventTarget.asEventTarget(element));

let addOrRemoveListeners = (handler, ()) => {
    let elements = Document.querySelectorAll({j|[$subscriptionIdAttr]|j}, document);
    Js.Array.forEach(handler, NodeListRe.toArray(elements) |> Js.Array.map(Element.ofNode))
  };

let addListeners = addOrRemoveListeners(addListener);

let removeListeners = addOrRemoveListeners(removeListener);

But I get an error in addOrRemoveListeners(addListener);:

This is:
  (Dom.eventTarget) => unit
But somewhere wanted:
  (Dom.node) => unit

How should I convert from Dom.eventTarget to Dom.node?

Edit: I ended up with this:

let addListener = Element.addEventListener("click", onSubscribeClick);
let removeListener = Element.removeEventListener("click", onSubscribeClick);
let addOrRemoveListeners = (handler, ()) => {
  let elements = Document.querySelectorAll({j|[$(subscriptionIdAttr)]|j}, document);
  let () =
    elements
    |> NodeListRe.toArray
    |> Array.map(Element.ofNode)
    |> Array.to_list
    |> List.filter(Js.Option.isSome)
    |> List.map(Js.Option.getExn)
    |> List.iter(handler);
  ()
};
let addListeners = addOrRemoveListeners(addListener);
let removeListeners = addOrRemoveListeners(removeListener);

Body:
Short answer:

external eventTargetToNode : Dom.eventTarget => Dom.node = "%identity";

An eventTarget can be almost anything, and there's unfortunately no good way of figuring out what it is. In JavaScript it's simply inferred by the user based on context (It might be possible to carry that context around in a type parameter, but that's off in the future somewhere).

So for the moment you'll have to make an unsafe cast to get what you need.

(BTW, you can use Element.addEventListener to avoid the cast from element to eventTarget)


问:
Vuejs vee validate validating all form inputs
Am mtrying to validate all inputs via

```<code> this.validator.validateAll().then((result) => {
               console.log(result)
            }).catch(() => {
                // something went wrong (non-validation related).
                return false;
            });
</code>```

But am getting an error

```<code> Cannot read property 'then' of undefined
</code>```

When i check on

```<code>console.log(this.validator)
</code>```

the function validateAll doesn't exists.Previously the above was working untill today

The following is my package.json dependency

```<code> "devDependencies": {
     "vue": "^2.1.10"
  },

  "dependencies": {
    "vee-validate": "^2.0.0-rc.21",
   }
</code>```

What could be wrong as it started throwing errors after running

```<code>npm install vee-validate --save
</code>```

What do i need to do as it was previously working?

答:
This.validator means you want to access to a Vue component property. But the plugin use this.$validator wich is an injected property by the plugin itself.

http://vee-validate.logaretm.com/examples.html#validate-form

Body:
Am mtrying to validate all inputs via

 this.validator.validateAll().then((result) => {
               console.log(result)
            }).catch(() => {
                // something went wrong (non-validation related).
                return false;
            });

But am getting an error

 Cannot read property 'then' of undefined

When i check on

console.log(this.validator)

the function validateAll doesn't exists.Previously the above was working untill today

The following is my package.json dependency

 "devDependencies": {
     "vue": "^2.1.10"
  },

  "dependencies": {
    "vee-validate": "^2.0.0-rc.21",
   }

What could be wrong as it started throwing errors after running

npm install vee-validate --save

What do i need to do as it was previously working?


问:
Where are google home cards displayed if not using smartphone?
On amazon alexa, cards are displayed in the amazon alexa app or on the screen of an echo show ?). If I call my google actions on my smartphone, I am also able to view the cards. But what happens if I use a different non-screen surface, like the google home? Do the cards appear in the google home app anywhere or do they just get lost?</p>

答:
Cards (and other visual elements you can add) aren't shown if the surface you're currently interacting with doesn't support them. This is intentional since the user may not expect them there and might open the app later and be surprised.

You can always check what surfaces are being supported in your current conversation by using app.getAvailableSurfaces() or the equivalent JSON properties. If you need to show the user something, you can prompt them to change to a surface that supports display by using app.askForNewSurface(). See the documentation about Surface Capabilities for detailed information.

In general, it is a good design to expect the user to only interact with their voice and to require visual information only minimally. Visual information should be used to supplement and enhance the voice as much as possible.


问:
Detailed guidance about WCF Security
Guys, I'm looking for some detailed guidance about WCF Security. I've read Juval Lowy's book and WCF Security Guide, but I'm still looking for verbose manual.
I'm especially interested how some WCF security options influence on SOAP messages (cause clients of my services aren't .NET applications).

Could you point to any similar books/blogs/articles?

答:
You have already read two main sources. You can also check official WCF Service Interoperability site. It contains some white papers which are not related only to security. But if you really want to dive deep into WCF interoperability, learn to use Fiddler, WCF tracing and message logging and study WS-Security specifications.

I also recommend Yaron Naveh's blog.

Title: Detailed guidance about WCF Security


问:
Loader during Unity IAP Callback
I want to put loader in between dialog boxes come up for the purchase. What is the way for this?

Because when game player press Buy button, he should require to wait for 5 to 10 second depends on internet speed and server response and this process happed 2 to 3 times because multiple dialogs come up within screen.

So in this case, may be player can leave the screen. I want to put the loader so that game player realise that some processing is running in background, he required to wait for some time.

At present I was following completely this code for Unity IAP setup.
Integrating Unity IAP In Your Game

答:
I assume this is for mobile platform but even if its not still the following can be considered:

Simple solution is to create a full screen Image (UI/Panel) object in your UI to block clicks. I would use Animator component (with triggers) to display this panel in front of other UI when there is a background process running.

public class Loader : MonoBehaviour
{
    public static Loader Instance;
    Animator m_Animator;

    public bool Loading {get; private set;}

    void Awake()
    {
        Instance = this; // However make sure there is only one object containing this script in the scene all time.
    }

    void Start()
    {
        //This gets the Animator, which should be attached to the GameObject you are intending to animate.
        m_Animator = gameObject.GetComponent<Animator>();
        Loading = false;
    }

    public void Show()
    {
        Loading = true;
        m_Animator.SetBool("Loading", Loading); // this will show the panel.

    }

    public void Hide()
    {
        Loading = false;
        m_Animator.SetBool("Loading", Loading); // this will hide the panel.
    }
}
```

<p>Then in any script which manipulates UI:</p>

<pre class="lang-c# prettyprint-override"><code>public void BuyButtonClicked()
{
    Loader.Instance.Show();
    // process time taking stuff
    Loader.Instance.Hide();
}
</code>```

You can also create any kind of loading animation as child of panel object using simple images and animation tool inside Unity (for example rotating animation (use fidget spinner, its cool)).

And in case of Android where user have option to leave screen by pressing OS back button you can prevent going back by checking if any loading is in progress by following example:

// code for back button
void Update()
{
    if (Input.GetKeyDown(KeyCode.Escape))
    {
        BackButtonPressed();
    }
}

void BackButtonPressed()
{
    if(Loader.Instance.Loading)
        return;
    // use back button event. (For example to leave screen)
}
```

Hope this helps ;)

Title: Loader during Unity IAP Callback

Body:
I assume this is for mobile platform but even if its not still the following can be considered:

Simple solution is to create a full screen Image (UI/Panel) object in your UI to block clicks. I would use Animator component (with triggers) to display this panel in front of other UI when there is a background process running.

public class Loader : MonoBehaviour
{
    public static Loader Instance;
    Animator m_Animator;

    public bool Loading {get; private set;}

    void Awake()
    {
        Instance = this; // However make sure there is only one object containing this script in the scene all time.
    }

    void Start()
    {
        //This gets the Animator, which should be attached to the GameObject you are intending to animate.
        m_Animator = gameObject.GetComponent<Animator>();
        Loading = false;
    }

    public void Show()
    {
        Loading = true;
        m_Animator.SetBool("Loading", Loading); // this will show the panel.

    }

    public void Hide()
    {
        Loading = false;
        m_Animator.SetBool("Loading", Loading); // this will hide the panel.
    }
}

Then in any script which manipulates UI:

public void BuyButtonClicked()
{
    Loader.Instance.Show();
    // process time taking stuff
    Loader.Instance.Hide();
}

You can also create any kind of loading animation as child of panel object using simple images and animation tool inside Unity (for example rotating animation (use fidget spinner, its cool)).

And in case of Android where user have option to leave screen by pressing OS back button you can prevent going back by checking if any loading is in progress by following example:

// code for back button
void Update()
{
    if (Input.GetKeyDown(KeyCode.Escape))
    {
        BackButtonPressed();
    }
}

void BackButtonPressed()
{
    if(Loader.Instance.Loading)
        return;
    // use back button event. (For example to leave screen)
}

Hope this helps ;)


问:
Bootstrap Container centered vertically
My page is made of a navbar and a container containing two panels.

I want to vertically center my container. The navbar has to stay on top.

Right now I have this :

I want to achieve this :

Here's my code :

HTML

```<code><body>

  <nav class="navbar transparent navbar-static-top">

    <div class="navbar-header">
      <p>Welcome</p>
    </div>

  </nav>

  <div class="container d-flex h-100">

    <div class="row justify-content-center align-self-center">

      <!-- 1st panel -->
      <div class="col-md-4 mb-4" id="panel">

        <div class="panel panel-default1">

          <div class="panel-body">

            <p>Blablabla</p>

          </div>
          <!-- panel body -->
        </div>
        <!-- panel-default1-->
      </div>
      <!-- col md 4 -->

      <!-- 2nd panel -->

      <div class="col-md-8 col-md-8" id="panel2">

        <div class="panel panel-default2">

          <div class="panel-body">

            <p>Blablabla</p>

          </div>
          <!-- panel-body -->

        </div>
        <!-- panel-default2-->

      </div>
      <!-- col md 8 -->

    </div>
    <!-- row -->

  </div>
  <!-- container-->

</body>
</code>```

CSS

```<code>html {
  overflow: hidden;
  height: 100%;
}

body {
  overflow: hidden;
  width: 100%;
  height: 100%;
  margin: 0px;
  padding: 0px;
}

.panel-default1 {
  padding-top: 8px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 400px;
  width: 100%;
  overflow: hidden;
  margin: 0 auto;
  position: relative;
}

.panel-default2 {
  padding-top: 10px;
  padding-right: -15px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 400px;
  width: 100%;
  margin: 0 auto;
  position: relative;
}
</code>```

I haven't been successful in center the container vertically.

Please advise a clean and working solution.

答:
You can use these class:

to body  d-flex,flex-column

to the container m-auto

CSS applied in the snippet, body tag already produced by the snippet , not abble to access and add classes to it

/* these below can be applied through classes .d-flex,flex-column,m-auto , .. */
body {
  display: flex;
  flex-flow: column;
  height: 100vh;
}

.container {
  margin: auto;
}
/* end update */

/* removed a few things that did not seem useful, add back what you really need /
html {
  height: 100%;
}

body {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px;
}

.panel-default1 {
  padding: 8px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 100px;
}

.panel-default2 {
  padding: 10px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">

<nav class="navbar transparent navbar-static-top">

  <div class="navbar-header">
    <p>Welcome</p>
  </div>

</nav>

<div class="container d-flex h-100">

  <div class="row justify-content-center align-self-center">

    <!-- 1st panel -->
    <div class="col-md-4 mb-4" id="panel">

      <div class="panel panel-default1">

        <div class="panel-body">

          <p>Blablabla</p>

        </div>
        <!-- panel body -->
      </div>
      <!-- panel-default1-->
    </div>
    <!-- col md 4 -->

    <!-- 2nd panel -->

    <div class="col-md-8 col-md-8" id="panel2">

      <div class="panel panel-default2">

        <div class="panel-body">

          <p>Blablabla</p>

        </div>
        <!-- panel-body -->

      </div>
      <!-- panel-default2-->

    </div>
    <!-- col md 8 -->

  </div>
  <!-- row -->

</div>
<!-- container--></code>```

Title: Bootstrap Container centered vertically

Body:
My page is made of a navbar and a container containing two panels.

I want to vertically center my container. The navbar has to stay on top.

Right now I have this :

I want to achieve this :

Here's my code :

HTML

Welcome

Blablabla

Blablabla

CSS

html {
  overflow: hidden;
  height: 100%;
}

body {
  overflow: hidden;
  width: 100%;
  height: 100%;
  margin: 0px;
  padding: 0px;
}

.panel-default1 {
  padding-top: 8px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 400px;
  width: 100%;
  overflow: hidden;
  margin: 0 auto;
  position: relative;
}

.panel-default2 {
  padding-top: 10px;
  padding-right: -15px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 400px;
  width: 100%;
  margin: 0 auto;
  position: relative;
}

I haven't been successful in center the container vertically.

Please advise a clean and working solution.

Body:
You can use these class:

to body  d-flex,flex-column

to the container m-auto

CSS applied in the snippet, body tag already produced by the snippet , not abble to access and add classes to it

/* these below can be applied through classes .d-flex,flex-column,m-auto , .. */
body {
  display: flex;
  flex-flow: column;
  height: 100vh;
}

.container {
  margin: auto;
}
/* end update */

/* removed a few things that did not seem useful, add back what you really need /
html {
  height: 100%;
}

body {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px;
}

.panel-default1 {
  padding: 8px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 100px;
}

.panel-default2 {
  padding: 10px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 100px;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">

<nav class="navbar transparent navbar-static-top">

  <div class="navbar-header">
    <p>Welcome</p>
  </div>

</nav>

<div class="container d-flex h-100">

  <div class="row justify-content-center align-self-center">

    <!-- 1st panel -->
    <div class="col-md-4 mb-4" id="panel">

      <div class="panel panel-default1">

        <div class="panel-body">

          <p>Blablabla</p>

        </div>
        <!-- panel body -->
      </div>
      <!-- panel-default1-->
    </div>
    <!-- col md 4 -->

    <!-- 2nd panel -->

    <div class="col-md-8 col-md-8" id="panel2">

      <div class="panel panel-default2">

        <div class="panel-body">

          <p>Blablabla</p>

        </div>
        <!-- panel-body -->

      </div>
      <!-- panel-default2-->

    </div>
    <!-- col md 8 -->

  </div>
  <!-- row -->

</div>
<!-- container-->