问:
Get List inside List
I have a complex data structure and I had to create this short example for better understanding.

```<code>type alias People =
  { name : String
  , sex : String
  , phones : List Phone
  }

type alias Phone =
  { number : String
  , isActive : Bool
  }
</code>```

This structure populated:

```<code>people = [
  { name = "_me"
  , sex = "M"
  , phones = [
    { number = "(99) 99 9 9999-9999"
    , isActive = True
    }]
  },
  { name = "_you"
  , sex = "M"
  , phones = [
    { number = "(11) 11 1 1111-1111"
    , isActive = True
    },
    { number = "(22) 22 2 2222-2222"
    , isActive = False
    }]
  }]
</code>```

And I would like to get only the 'phones' from the 'people' list, as in the example below

```<code>phones = [
  { number = "(99) 99 9 9999-9999"
  , isActive = True
  },
  { number = "(11) 11 1 1111-1111"
  , isActive = True
  },
  { number = "(22) 22 2 2222-2222"
  , isActive = False
  }]
</code>```

I've been trying for 3 days, but to no avail.

答:
You can pull out all the phone numbers into a list by mapping over to get the phone number list of a person, then concatenating those phone number lists together:

getPhones : List People -> List Phone
getPhones = List.concat << List.map .phones
```

Title: Get List inside List

Body:
I have a complex data structure and I had to create this short example for better understanding.

type alias People =
  { name : String
  , sex : String
  , phones : List Phone
  }

type alias Phone =
  { number : String
  , isActive : Bool
  }

This structure populated:

people = [
  { name = "_me"
  , sex = "M"
  , phones = [
    { number = "(99) 99 9 9999-9999"
    , isActive = True
    }]
  },
  { name = "_you"
  , sex = "M"
  , phones = [
    { number = "(11) 11 1 1111-1111"
    , isActive = True
    },
    { number = "(22) 22 2 2222-2222"
    , isActive = False
    }]
  }]

And I would like to get only the 'phones' from the 'people' list, as in the example below

phones = [
  { number = "(99) 99 9 9999-9999"
  , isActive = True
  },
  { number = "(11) 11 1 1111-1111"
  , isActive = True
  },
  { number = "(22) 22 2 2222-2222"
  , isActive = False
  }]

I've been trying for 3 days, but to no avail.


来源: stackexchange

问:
django form without id=id_fieldname
I have the following form in django:

```<code>class Person(forms.Form):
    first_name = forms.CharField()
    last_name = forms.CharField()
    age = forms.IntegerField()
</code>```

When I render the form, the html output is the following:

```<code><input id="id_age" name="age" type="number">
</code>```

Is it possible to NOT include the input id?

My desired output would be:

```<code><input name="age" type="number">
</code>```

I don't want to change the id, i want the input to not have the id attribute at all.

答:
I can't imagine what difference it makes, but you can use the auto_id attribute when instantiating the form in your view to turn off IDs altogether.

```<code>form = Person(auto_id=False)
</code>```

ContentLicense: CC BY-SA 3.0

Title: django form without id=id_fieldname

Body:
I have the following form in django:

class Person(forms.Form):
    first_name = forms.CharField()
    last_name = forms.CharField()
    age = forms.IntegerField()

When I render the form, the html output is the following:

<input id="id_age" name="age" type="number">

Is it possible to NOT include the input id?

My desired output would be:

<input name="age" type="number">

I don't want to change the id, i want the input to not have the id attribute at all.

Body:
I can't imagine what difference it makes, but you can use the auto_id attribute when instantiating the form in your view to turn off IDs altogether.

form = Person(auto_id=False)


问:
About auto record and auto play with AVAudioPlayer&AVAudioRecorder
in .h file I wrote like this:

```<code>#import <UIKit/UIKit.h>
#import "SCListener.h"
#import <AVFoundation/AVFoundation.h>

@interface TalkingAndSayingViewController : UIViewController<AVAudioPlayerDelegate>
{

IBOutlet UIImageView *bkg;
IBOutlet UILabel *showVoulme;

SCListener *listener;

NSTimer *time;

BOOL listen;
NSString *audioPath;
AVAudioRecorder *recoder;
AVAudioPlayer *player;

int breakCount;

BOOL timeActive;

}
@property(nonatomic,assign)int roleIndex;
@end
</code>```

and in the .m file I wrote this:

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

[super viewDidLoad];

NSArray *searchPaths =  NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
audioPath = [[searchPaths objectAtIndex:0] stringByAppendingPathComponent:@"audio.wav"];
[audioPath retain];

listen = YES;

NSMutableDictionary *recordSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                       [NSNumber numberWithFloat: 44100.0],                 AVSampleRateKey,
                                       [NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
                                       [NSNumber numberWithInt: 1],                         AVNumberOfChannelsKey,
                                       [NSNumber numberWithInt: AVAudioQualityMax],         AVEncoderAudioQualityKey,
                                       nil];

NSString *imgName = [NSString stringWithFormat:@"role%d.png",self.roleIndex];
[bkg setImage:[UIImage imageNamed:imgName]];

recoder = [[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:audioPath] settings:recordSettings error:nil];
[recoder setMeteringEnabled:YES];

player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:audioPath] error:nil];
[player setNumberOfLoops:0];

AVAudioSession *audioSession = [[AVAudioSession sharedInstance] retain];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error: nil];
[audioSession setActive:YES error: nil];

time = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(CheckVolume) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:time forMode:NSDefaultRunLoopMode];

}

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
     timeActive = YES;
        listen = YES;
        NSLog(@"fihish playing, start listen");
}

-(void)CheckVolume

    {
        Float32 peak = [[SCListener sharedListener] peakPower];
        if(timeActive)
        {
            if(listen)
            {
                [showVoulme setText:[NSString stringWithFormat:@"%f",peak]];
                if(peak>0.3)
                {
                    listen = NO;
                    [recoder prepareToRecord];
                    [recoder record];
                    NSLog(@"start recording");
                }
            }

            else
            {
                if(peak<0.1)
                {
                    if(breakCount >= 5)
                    {
                        NSLog(@"start play");

                        [recoder stop];

                        player.delegate = self;
                        [player prepareToPlay];
                        [player play];
                        timeActive = NO;
                        breakCount = 0;
                    }
                    else
                        breakCount++;
                }
                else
                    breakCount = 0;
            }
        }
    }

-(void)viewWillDisappear:(BOOL)animated
{
    [recoder stop];
    [[SCListener sharedListener] stop];

    timeActive = NO;
}

-(void)viewDidAppear:(BOOL)animated
{
    timeActive = YES;

    [[SCListener sharedListener] listen];

    breakCount = 0;
}
</code>```

Here have some problems,
first:audioPlayerDidFinishPlaying  this function didn't do at all, and this code only can run to "start play", but the sound didn't play in fact, I used to use the recorder to check the volume when it's in the recording condition, but the peakPowerForChannel:0 only returns a static value of 0.00001, I have no idea to solve this problem, anyone can help me or send me a sample code of auto record and auto play? I really appreciate it. Thanks

答: Yeah, already 5 years past, and I still work with iOS dev, this problem been resolved in about one month after this question ask, and I never remembered to see this answer. I had made an app like talking tom just then. And already finished it, however, useless for me.</p>

Body:
in .h file I wrote like this:

#import <UIKit/UIKit.h>
#import "SCListener.h"
#import <AVFoundation/AVFoundation.h>

@interface TalkingAndSayingViewController : UIViewController<AVAudioPlayerDelegate>
{

IBOutlet UIImageView *bkg;
IBOutlet UILabel *showVoulme;

SCListener *listener;

NSTimer *time;

BOOL listen;
NSString *audioPath;
AVAudioRecorder *recoder;
AVAudioPlayer *player;

int breakCount;

BOOL timeActive;

}
@property(nonatomic,assign)int roleIndex;
@end

and in the .m file I wrote this:

- (void)viewDidLoad
{

[super viewDidLoad];

NSArray *searchPaths =  NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
audioPath = [[searchPaths objectAtIndex:0] stringByAppendingPathComponent:@"audio.wav"];
[audioPath retain];

listen = YES;

NSMutableDictionary *recordSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                       [NSNumber numberWithFloat: 44100.0],                 AVSampleRateKey,
                                       [NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
                                       [NSNumber numberWithInt: 1],                         AVNumberOfChannelsKey,
                                       [NSNumber numberWithInt: AVAudioQualityMax],         AVEncoderAudioQualityKey,
                                       nil];

NSString *imgName = [NSString stringWithFormat:@"role%d.png",self.roleIndex];
[bkg setImage:[UIImage imageNamed:imgName]];

recoder = [[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:audioPath] settings:recordSettings error:nil];
[recoder setMeteringEnabled:YES];

player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:audioPath] error:nil];
[player setNumberOfLoops:0];

AVAudioSession *audioSession = [[AVAudioSession sharedInstance] retain];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error: nil];
[audioSession setActive:YES error: nil];

time = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(CheckVolume) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:time forMode:NSDefaultRunLoopMode];

}

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
     timeActive = YES;
        listen = YES;
        NSLog(@"fihish playing, start listen");
}

-(void)CheckVolume

    {
        Float32 peak = [[SCListener sharedListener] peakPower];
        if(timeActive)
        {
            if(listen)
            {
                [showVoulme setText:[NSString stringWithFormat:@"%f",peak]];
                if(peak>0.3)
                {
                    listen = NO;
                    [recoder prepareToRecord];
                    [recoder record];
                    NSLog(@"start recording");
                }
            }

            else
            {
                if(peak<0.1)
                {
                    if(breakCount >= 5)
                    {
                        NSLog(@"start play");

                        [recoder stop];

                        player.delegate = self;
                        [player prepareToPlay];
                        [player play];
                        timeActive = NO;
                        breakCount = 0;
                    }
                    else
                        breakCount++;
                }
                else
                    breakCount = 0;
            }
        }
    }

-(void)viewWillDisappear:(BOOL)animated
{
    [recoder stop];
    [[SCListener sharedListener] stop];

    timeActive = NO;
}

-(void)viewDidAppear:(BOOL)animated
{
    timeActive = YES;

    [[SCListener sharedListener] listen];

    breakCount = 0;
}

Here have some problems,
first:audioPlayerDidFinishPlaying  this function didn't do at all, and this code only can run to "start play", but the sound didn't play in fact, I used to use the recorder to check the volume when it's in the recording condition, but the peakPowerForChannel:0 only returns a static value of 0.00001, I have no idea to solve this problem, anyone can help me or send me a sample code of auto record and auto play? I really appreciate it. Thanks


问:
How to get notified (trigger a lambda) when user registers with an authentication provider like fb
My goal is to create a user in my user table with the data from the fresh facebook auth.
The closest thing I found is within Identity Pool settings:

But it's not the event I had in mind. I want a trigger only when a new user comes in.

答:
Once I didn't found such trigger and it looks that there were no changes since. And you don't know on a client side is it a registration or login.

You can only make workaround like create a dataset and store some information there (e.g. first_login), based on which you could do your stuff.

There is a similar thread you could check.


问:
Comparing two paths in python
Consider:

```<code>path1 = "c:/fold1/fold2"
list_of_paths = ["c:\\fold1\\fold2","c:\\temp\\temp123"]

if path1 in list_of_paths:
    print "found"
</code>```

I would like the if statement to return True, but it evaluates to False,
since it is a string comparison.

How to compare two paths irrespective of the forward or backward slashes they have? I'd prefer not to use the replace function to convert both strings to a common format.

答:
If you are using python-3, you can use pathlib to achieve your goal:</p>

```<code>import pathlib
path1 = pathlib.Path("c:/fold1/fold2")
list_of_paths = [pathlib.Path(path) for path in ["c:\\fold1\\fold2","c:\\temp\\temp123"]]
assert path1 in list_of_paths
</code>```

ContentLicense: CC BY-SA 4.0

Title: Comparing two paths in python

Body:
Consider:

path1 = "c:/fold1/fold2"
list_of_paths = ["c:\\fold1\\fold2","c:\\temp\\temp123"]

if path1 in list_of_paths:
    print "found"

I would like the if statement to return True, but it evaluates to False,
since it is a string comparison.

How to compare two paths irrespective of the forward or backward slashes they have? I'd prefer not to use the replace function to convert both strings to a common format.

Body:
If you are using python-3, you can use pathlib to achieve your goal:

import pathlib
path1 = pathlib.Path("c:/fold1/fold2")
list_of_paths = [pathlib.Path(path) for path in ["c:\\fold1\\fold2","c:\\temp\\temp123"]]
assert path1 in list_of_paths


问:
Mongo DB Authentication 3.0.4
I am having an issue with mongo db 3.0.4 that randomly started happening today. The authentication stopped working randomly without any user action on our part. Our setup is easy. One application, one database. I take the application out of the equation and I still get the same result. Here are the steps I am taking. Reinstalled mongo and pointed the logpath and dbpath to a new folder to start from scratch.

Create the config file.

```<code>logpath=c:\data\logs\mongod.log
dbpath=c:\data\db
</code>```

Log in to mongo shell and run this command.

```<code>db.createUser({user: "admin",pwd: "admin", roles: [ { role: "userAdminAnyDatabase", db: "admin" }]})
</code>```

Add the auth=true in the config file.

```<code>auth=true
</code>```

Restart the mongodb service.

Start up mongo shell with

```<code>mongo -u admin -p admin --authenticationDatabase admin
</code>```

Then I get the Error 18 Authentication failed.

I am really lost for words. Any help would be greatly appreciated.

Thanks

答:
Before create the user, you need to change the db and create it in admin db.

Disable auth

Enter to mongo shell

Change db to admin ('use admin')

now create the user.

Enable the auth again (with auth or mongodb-keyfile)

Enter mongo shell with:

```<code>mongo -u admin -p admin --authenticationDatabase admin
</code>```

Title: Mongo DB Authentication 3.0.4

Body:
I am having an issue with mongo db 3.0.4 that randomly started happening today. The authentication stopped working randomly without any user action on our part. Our setup is easy. One application, one database. I take the application out of the equation and I still get the same result. Here are the steps I am taking. Reinstalled mongo and pointed the logpath and dbpath to a new folder to start from scratch.

Create the config file.

logpath=c:\data\logs\mongod.log
dbpath=c:\data\db

Log in to mongo shell and run this command.

db.createUser({user: "admin",pwd: "admin", roles: [ { role: "userAdminAnyDatabase", db: "admin" }]})

Add the auth=true in the config file.

auth=true

Restart the mongodb service.

Start up mongo shell with

mongo -u admin -p admin --authenticationDatabase admin

Then I get the Error 18 Authentication failed.

I am really lost for words. Any help would be greatly appreciated.

Thanks

Body:
Before create the user, you need to change the db and create it in admin db.

Disable auth

Enter to mongo shell

Change db to admin ('use admin')

now create the user.

Enable the auth again (with auth or mongodb-keyfile)

Enter mongo shell with:

mongo -u admin -p admin --authenticationDatabase admin


问:
How to get data passed from PUT method
I am creating an API for Laravel. I use the PUT method for updating data.

I send data with Postman using the PUT method. In my controller, I got an empty array. How to access the passed data?

In my route, I have:

```<code>Route::put('vehicletypes/{id}','API\VehicletypeController@update');
</code>```

In my controller:

```<code>public function update(Request $request, $id){

print_r($request->all()); exit;

}
</code>```

How to get the data passed in PUT method?

答:
Laravel cheats because html forms only support GET and POST, but it does understand a real PUT/PATCH request.

The problem looks like lies in Symfony it can't parse the data if it's multipart/form-data, as an alternative try using x-www-form-urlencoded content disposition.

Title: How to get data passed from PUT method

Body:
I am creating an API for Laravel. I use the PUT method for updating data.

I send data with Postman using the PUT method. In my controller, I got an empty array. How to access the passed data?

In my route, I have:

Route::put('vehicletypes/{id}','API\VehicletypeController@update');

In my controller:

public function update(Request $request, $id){

print_r($request->all()); exit;

}

How to get the data passed in PUT method?


问:
Stepping into a function, but not into the evaluation of the arguments with VS2017
If often encounter following situation:

```<code> int HelperFunction(int somevalue)
 {
    ...
 }

 void FunctionToDebug(int somearg)
 {
    ...
 }

    ...
    SomeFunction();
 >> FunctionToDebug(HelperFunction(somevalue))
    ...
</code>```

Now I'm stepping through my code and I arrive at the function call marked with >> in the code snippet above.

When I use the "step into" command, the debugger will first step into HelperFunction and then into FunctionToDebug  which is expected but which can be annoying e.g. if HelperFunction is fully debugged.

Is there some functionality or trick that would allow me to step directly into FunctionToDebug without stepping into the functions called during the evaluation of the arguments (HelperFunction here)?

EDIT

Its not really a duplicate of this:

Is there a way to automatically avoiding stepping into certain functions in Visual Studio?

as I'd like to decide on the spot if I want to step into the arguments or not, but it's interesting anyway though.

答: What about setting a one shot (if available) breakpoint into FunctionToDebug and letting the code run?</p>

Body:
If often encounter following situation:

 int HelperFunction(int somevalue)
 {
    ...
 }

 void FunctionToDebug(int somearg)
 {
    ...
 }

    ...
    SomeFunction();
 >> FunctionToDebug(HelperFunction(somevalue))
    ...

Now I'm stepping through my code and I arrive at the function call marked with >> in the code snippet above.

When I use the "step into" command, the debugger will first step into HelperFunction and then into FunctionToDebug  which is expected but which can be annoying e.g. if HelperFunction is fully debugged.

Is there some functionality or trick that would allow me to step directly into FunctionToDebug without stepping into the functions called during the evaluation of the arguments (HelperFunction here)?

EDIT

Its not really a duplicate of this:

Is there a way to automatically avoiding stepping into certain functions in Visual Studio?

as I'd like to decide on the spot if I want to step into the arguments or not, but it's interesting anyway though.


问:
is it possible pinging through nat from outside the nat inside?
is it possible to send an echo-request to a host set behind nat
after. all the echo-request doesn't hold a port for the destination host so if there are several hosts using the same external ip address how will the nat be able to forward the echo-request to a specific host</p>

答:
Most modern NAT/packet filtering implementations are stateful. That means they have a wider concept of the word connection than the older stateless variants. That allows them to handle more complex protocols that use additional connections (e.g. FTP), as well as connection-less protocols like ICMP.

In the case of ICMP packets, echo requests contain an ID field that is preserved in the reply. While its 16 bits are somewhat restrictive, it allows in conjuction with the source IP address from the IP header to have a reasonably high confidence on which echo request each reply corresponds to.

EDIT:

As for targeting specific hosts behind a NAT implementation, that is not generally possible. You might be able to:

Redirect all ICMP traffic to one internal host to monitor that one host only.

Use the "pad" data bytes of the echo request packet to provide some kind of host identifier. For example, the -p option of ping on some Linux systems allows setting that field. This is by no means standard, though.

In general, NAT is supposed to hide the hosts behind it from the world, with the exception of any forwarded IP connections.

ContentLicense: CC BY-SA 2.5


问:
how to have multiple $http call inside of a ng-repeat
i tried to retrieve two data, one from the API and from my json, when i make the call i receive just the second call on my view.

json 1

```<code>[
    {
        "id": 1,
        "img":"images/clientlogos/21747.jpg"
    },
    {
        "id": 2,
        "img": "images/clientlogos/FMI.png"
        }
]
</code>```

jason @ from APi call

```<code>[
    {
        "id": 1,
        "name": "Enough",
        "forecasted": 22,
        "budget": 40,
        "hoursspent": 3.53999997675419,
        "currentcosts": 965.393393660635,
        "xerototal": 2800
    },
    {
        "id": 2,
        "name": "Fad Ltd",
        "forecasted": 96.5,
        "budget": 300,
        "hoursspent": 199.91000029631,
        "currentcosts": 66234.589716303,
        "xerototal": 176472
    },
]
</code>```

my factory

```<code>app.factory('myFactory', function($http){
  return{
client: function(callback){
        $http({
          method: "GET",
          url: "http://www.outleading.co.za/api/api/clientdashboarddata",
          cache:true
        }).then(callback);
    },
list: function(callback){
        $http({
          method: "GET",
          url: "data/Client.json",
          cache:true
        }).then(callback);
    }
  };
});
</code>```

my controller

```<code>    app.controller('myController', function ($scope, $http, myFactory) {
      myFactory.client(function (response) {
        var data = response.data;
        $scope.myClients = data;
      })
      myFactory.list(function(response){
        var data= response.data;
        $scope.myClients= data;
      })
        };
      }
    })
</code>```

my html

inside my ng-repeat i want to get{{client.img}} from my json and {{client.clientname}} from the api call

```<code><div class="card client-card" ng-repeat="client in myClients>
                <div class="client-logo">
                     <img ng-src="{{client.img}}" alt="{{client.name}}">
                </div>
        </div>
</code>```

so Any help will be much appreaciated.

答:
Modify factory to return promise it gives you flexibility

```<code>app.factory('myFactory', function ($http) {
    return {
        client: function () {
            return $http({
                method: "GET",
                url: "http://www.outleading.co.za/api/api/clientdashboarddata",
                cache: true
            });
        },
        list: function () {
            return $http({
                method: "GET",
                url: "data/Client.json",
                cache: true
            });
        }
    };
});
</code>```

Use $q.all() and wait for all promises to complete

```<code>app.controller('myController', function ($scope, $http, myFactory, $q) {
    $q.qll(myFactory.client(), myFactory.list()).then(function (result) {
        $scope.myClients = result[0].data;
        var images = result[1].data;

        $scope.myClients.forEach(function(client){
            // find index of image for client
            var idx= images.findIndex(function(x){
                return x.id == client.id
            });

            client.name = images[idx].name;
        })
    });
});
</code>```

Body:
i tried to retrieve two data, one from the API and from my json, when i make the call i receive just the second call on my view.

json 1

[
    {
        "id": 1,
        "img":"images/clientlogos/21747.jpg"
    },
    {
        "id": 2,
        "img": "images/clientlogos/FMI.png"
        }
]

jason @ from APi call

[
    {
        "id": 1,
        "name": "Enough",
        "forecasted": 22,
        "budget": 40,
        "hoursspent": 3.53999997675419,
        "currentcosts": 965.393393660635,
        "xerototal": 2800
    },
    {
        "id": 2,
        "name": "Fad Ltd",
        "forecasted": 96.5,
        "budget": 300,
        "hoursspent": 199.91000029631,
        "currentcosts": 66234.589716303,
        "xerototal": 176472
    },
]

my factory

app.factory('myFactory', function($http){
  return{
client: function(callback){
        $http({
          method: "GET",
          url: "http://www.outleading.co.za/api/api/clientdashboarddata",
          cache:true
        }).then(callback);
    },
list: function(callback){
        $http({
          method: "GET",
          url: "data/Client.json",
          cache:true
        }).then(callback);
    }
  };
});

my controller

    app.controller('myController', function ($scope, $http, myFactory) {
      myFactory.client(function (response) {
        var data = response.data;
        $scope.myClients = data;
      })
      myFactory.list(function(response){
        var data= response.data;
        $scope.myClients= data;
      })
        };
      }
    })

my html

inside my ng-repeat i want to get{{client.img}} from my json and {{client.clientname}} from the api call

so Any help will be much appreaciated.

Body:
Modify factory to return promise it gives you flexibility

app.factory('myFactory', function ($http) {
    return {
        client: function () {
            return $http({
                method: "GET",
                url: "http://www.outleading.co.za/api/api/clientdashboarddata",
                cache: true
            });
        },
        list: function () {
            return $http({
                method: "GET",
                url: "data/Client.json",
                cache: true
            });
        }
    };
});

Use $q.all() and wait for all promises to complete

app.controller('myController', function ($scope, $http, myFactory, $q) {
    $q.qll(myFactory.client(), myFactory.list()).then(function (result) {
        $scope.myClients = result[0].data;
        var images = result[1].data;

        $scope.myClients.forEach(function(client){
            // find index of image for client
            var idx= images.findIndex(function(x){
                return x.id == client.id
            });

            client.name = images[idx].name;
        })
    });
});


问:
How does git reset <filename> work?
There are 2 statements about git reset that are true but I find them contradictory given my limited knowledge of how Git works.

Is there a way to reconcile the 2 statements?

Statement 1:
Git reset file1 will un-add file1 from the staging area.

This is the command to use when you added file1 to staging and you changed your mind and want to remove it from the staging area.

Statement 2:
Git reset file1 will copy files from HEAD to the staging area.

According to statement 2, git reset adds files to the staging area.

So how do the files become removed from the staging area when they were just copied to it from HEAD?

答:
HEAD refers to the head of the current branch, i.e. the newest commit. When you change a file, the file in your working copy differs from HEAD. Staging that difference means copying the file from the working copy into the staging area.

Unstaging means removing a difference against the HEAD from the staging area. Hence unstaging is done by copying the state from HEAD back into staging area.

Title: How does git reset <filename> work?


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

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

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

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

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

答: you can use os.system() or os.popen() to call git </p>

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

   import os
   import datetime as dt

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

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

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


问:
iOS simulator taking 2-3 minutes every-time for starting/invoking
I have set up appium on mac for iOS automation.

It is taking 2-3 minutes everytime to start the simulator.

Most of the sections they said it will take time only first time but here it is taking time everytime

It was a waste of time to wait so much after every execution.

Few links have said to set newCommandTimeout as the capability but that doesn't work.

I am using below version

appium-desktop-1.2.7-mac

Xcode 8.1

Simulator iPhone 7 Plus

MacOS Sierra Version 10.12

Any workaround will be helpful :)

答:
Check Reset Strategies

if you add capability noReset=true, your simulator will be started only once


问:
Need to pass array to route and controller
I need to pass array to route and controller from view.

I get the error:

Missing required parameters for [Route: actBook] [URI: bookfromindex/actBook/{id}/{array}].

I have my route defined as:

```<code>Route::get('/bookfromindex/actBook/{id}/{array}', 'BookController@actBook')->name('actBook');
</code>```

My controller function is defined as:

```<code>public function actBook(Request $request, $id, $array){
</code>```

And I call this route in my view using:

```<code><a href="{{ route('actBook', $room->id, $array) }}" class="btn btn-default">დაჯავშნა</a>
</code>```

How do I prevent this error?

答:
Just change -

```<code><a href="{{ route('actBook', $room->id, $array) }}" class="btn btn-default">დაჯავშნა</a>
</code>```

to -

```<code><a href="{{ route('actBook', $room->id, serialize($array)) }}" class="btn btn-default">დაჯავშნა</a>
</code>```

Body:
I need to pass array to route and controller from view.

I get the error:

Missing required parameters for [Route: actBook] [URI: bookfromindex/actBook/{id}/{array}].

I have my route defined as:

Route::get('/bookfromindex/actBook/{id}/{array}', 'BookController@actBook')->name('actBook');

My controller function is defined as:

public function actBook(Request $request, $id, $array){

And I call this route in my view using:

id, $array) }}" class="btn btn-default">დაჯავშნა

How do I prevent this error?

Body:
Just change -

<a href="{{ route('actBook', $room->id, $array) }}" class="btn btn-default">დაჯავშნა</a>

to -

<a href="{{ route('actBook', $room->id, serialize($array)) }}" class="btn btn-default">დაჯავშნა</a>


问:
Django - importing dynamically
I'm trying to do a dynamic import of a python module in django.  I have two different apps that I want to import from, and I want to replace these import statements:

```<code>from app1.forms import App1ProfileForm
from app2.forms import App2ProfileForm
</code>```

I am dynamically able to create the strings App1ProfileForm and App2ProfileForm and then instantiate them like so:

```<code>globals()[form]()
</code>```

I tried following some of the instructions in this post: Dynamically import class by name for static access

and so I tried doing this:

```<code>theModule = __import__("app1.forms.App1ProfileForm")
</code>```

but I'm getting an error that says No module named App1ProfileForm

EDIT:::
Ok I tried this code:

```<code> theModule = __import__("app1")
    print theModule
    theClass = getattr(theModule,'forms')
    print theClass
    theForm = getattr(theClass,'App1ProfileForm')
    print theForm
    theForm.initialize()
</code>```

but I get an error that type object 'App1ProfileForm' has no attribute 'initialize'

答:
I don't quite know how you're generting the string to import. I'll assume you generate the whole "path". Try this:</p>

```
def import_from_strings(paths):
  ret = []
  for path in paths:
    module_name, class_name = path.rsplit('.', 1)
    module = __import__(module_name, globals(), locals(), [class_name], -1)
    ret.append(getattr(module, class_name))
  return ret
```

Title: Django - importing dynamically

Body:
I'm trying to do a dynamic import of a python module in django.  I have two different apps that I want to import from, and I want to replace these import statements:

from app1.forms import App1ProfileForm
from app2.forms import App2ProfileForm

I am dynamically able to create the strings App1ProfileForm and App2ProfileForm and then instantiate them like so:

globals()[form]()

I tried following some of the instructions in this post: Dynamically import class by name for static access

and so I tried doing this:

theModule = __import__("app1.forms.App1ProfileForm")

but I'm getting an error that says No module named App1ProfileForm

EDIT:::
Ok I tried this code:

 theModule = __import__("app1")
    print theModule
    theClass = getattr(theModule,'forms')
    print theClass
    theForm = getattr(theClass,'App1ProfileForm')
    print theForm
    theForm.initialize()

but I get an error that type object 'App1ProfileForm' has no attribute 'initialize'

Body:
I don't quite know how you're generting the string to import. I'll assume you generate the whole "path". Try this:

def import_from_strings(paths):
  ret = []
  for path in paths:
    module_name, class_name = path.rsplit('.', 1)
    module = __import__(module_name, globals(), locals(), [class_name], -1)
    ret.append(getattr(module, class_name))
  return ret


问:
jQuery validation form if input submit is clicked and checkbox is checked
I have a php page in which a user can publish or save his content. before submitting his data (with global array POST), I want to make some input required only if the corrispective checkbox is checked and the input #publish is clicked (not input #save)

My HTML code

```<code><form id="myForm">
    <input type="checkbox" id="page1" name="selected[]" value="page1" />
    <input type="checkbox" id="page2" name="selected[]" value="page2" />

    <input type="text" id="titlePag1" name="titlePag1" value=""/>
    <input type="text" id="textPag1" name="textPag1" value=""/>

    <input type="text" id="titlePag2" name="titlePag2" value=""/>
    <input type="text" id="textPag2" name="textPag2" value=""/>

    <input type="submit" id="save" name="save" value="Save">
    <input type="submit" id="publish" name="publish" value="publish">
</form>
</code>```

exemple: if checkbox #page2 is checked and i click #publish, #titlePag2 and #textPage2 are required. Else they aren't required.

I'm using jquery validation form, and a solution for the submit (#publish) could be:

```<code>jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$('#myForm').validate({
rules: {
    titlePag1: {
        required: function(element) {
            return $("#publish").val() != "";
        }
    },

    textPag1: {
        required: function(element) {
            return $("#publish").val() != "";
        }
    }
}
});
</code>```

How can i set another rule for the checkbox checked?

答:
```<code>checkBox: {
    required: function(element) {
        return $("#checkbox").attr("checked");
    }
}
</code>```

Body:
I have a php page in which a user can publish or save his content. before submitting his data (with global array POST), I want to make some input required only if the corrispective checkbox is checked and the input #publish is clicked (not input #save)

My HTML code

<form id="myForm">
    <input type="checkbox" id="page1" name="selected[]" value="page1" />
    <input type="checkbox" id="page2" name="selected[]" value="page2" />

    <input type="text" id="titlePag1" name="titlePag1" value=""/>
    <input type="text" id="textPag1" name="textPag1" value=""/>

    <input type="text" id="titlePag2" name="titlePag2" value=""/>
    <input type="text" id="textPag2" name="textPag2" value=""/>

    <input type="submit" id="save" name="save" value="Save">
    <input type="submit" id="publish" name="publish" value="publish">
</form>

exemple: if checkbox #page2 is checked and i click #publish, #titlePag2 and #textPage2 are required. Else they aren't required.

I'm using jquery validation form, and a solution for the submit (#publish) could be:

jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$('#myForm').validate({
rules: {
    titlePag1: {
        required: function(element) {
            return $("#publish").val() != "";
        }
    },

    textPag1: {
        required: function(element) {
            return $("#publish").val() != "";
        }
    }
}
});

How can i set another rule for the checkbox checked?


问:
How to change label value to be like password field value?
i'm having password like value to be set into label to be shown as ***(as per characters).

```<code><label>password</label>
</code>```

Output of this shown like below,because label value whatever it is.

```<code>password
</code>```

Expected result:

********

In my case its should be converted like ******** (as per no of characters).

Am newbie to js. Any one suggest me key points to do this.

How to convert this to be number of * values as per characters?

答:
You cant store ***** in a label and also a the value of the password, you can use a input with visibility: hidden like:

```<code><input type="password" name="pwd" style="visibility: hidden"></input>
<label id="lblPwd"></label>
</code>```

And treat it in javascript to show same value in the label.

Or you can use an input and set the css to show like a label:

```<code><style type="text/css">

.label{
    background:rgba(0,0,0,0);
    border:none;
}

</style>

<input type="password" class="label" disabled/>
</code>```

Body:
i'm having password like value to be set into label to be shown as ***(as per characters).

password

Output of this shown like below,because label value whatever it is.

password

Expected result:

********

In my case its should be converted like ******** (as per no of characters).

Am newbie to js. Any one suggest me key points to do this.

How to convert this to be number of * values as per characters?

Body:
You cant store ***** in a label and also a the value of the password, you can use a input with visibility: hidden like:

<input type="password" name="pwd" style="visibility: hidden"></input>
<label id="lblPwd"></label>

And treat it in javascript to show same value in the label.

Or you can use an input and set the css to show like a label:

<style type="text/css">

.label{
    background:rgba(0,0,0,0);
    border:none;
}

</style>

<input type="password" class="label" disabled/>


问:
How to create EC2 instance where image stored in Amazon S3 in the form of chunks
I am new to the Amazon EC2 service and having some knowledge on Amazon S3 storage service. I uploaded data to s3 using multipart upload. Now my data is present in an S3 bucket. I want to create an EC2 instance from that data(data doesnot presented in the form of single image, it was stored like chunks)

How can I implement this scenario?

How to send data from S3 to AMI instance

答:
For launching an EC2 instance you will need an Amazon Machine Image (AMI). An AMI is stored in S3 but you cannot access it directly. You can read more about AMIs here.

Regarding what you want to do (if I understand it correctly) you should run an EC2 instance from one of the existing AMIs (e.g. Ubuntu), configure it as you want, and create an image out of it. Later, using this image you can launch clones of that machine.


问:
Use multiple value for "size" validator in Laravel 5.3 requests
like in title, is there a way to check my form value against two specific values? I need to validate a field of 11 or 15 characters, I wonder if I need to use a regex pattern or it can be achieved with "Size" validator.

Thank you for your help

答:
I have a similar situation where i wanted to validate between two dimensions (height) for an image.
There are ways I guess of using custom validations for this as described in the following link
https://laravel.com/docs/5.3/validation#custom-validation-rules

But due to time limitations, i had settled with the following option of setting a between type of condition with the help of min_height & max_height. Agreed there is a loophole with this but it kind of was not an issue in my case.

```<code>'web_image'=>'mimes:jpg,jpeg,gif,png|dimensions:width=1280, min_height=495, max_height=1706'
</code>```

Hope this helps.

Body:
I have a similar situation where i wanted to validate between two dimensions (height) for an image.
There are ways I guess of using custom validations for this as described in the following link
https://laravel.com/docs/5.3/validation#custom-validation-rules

But due to time limitations, i had settled with the following option of setting a between type of condition with the help of min_height & max_height. Agreed there is a loophole with this but it kind of was not an issue in my case.

'web_image'=>'mimes:jpg,jpeg,gif,png|dimensions:width=1280, min_height=495, max_height=1706'

Hope this helps.


问:
Accessing properties across pages in AEM HTL (Sightly)
I have a carousel component, whose slide content will be the content from another page, accessed via reference component. I want to get some properties authored in the carousel to be accessible inside the referenced page. i.e. I have Page A- with a Carousel accessing PageB through reference component. I want to get proeprties from PageA in PageB. Can this be achieved?</p>

答: Sure it can, you will need to lookup/query the content and find pages where PageB is included, then get the properties of those pages (there might be more than one) and merge them. It will have to be custom code though as this is not available out-of-the-box as of AEM 6.3.


问:
Call subclass constructor from parent in Java
so I'm learning about java inheritance and I just ran into a situation I don't know how to solve.

What I'm trying to do is to call a subclass constructor from the superclass. I don't know if this makes any sense, but I'll try to explain myself with an example.

```<code>public class Phone {
    private String brand;
    private int weight;

    public Phone(String brand, int weight) {
        this.brand = brand;
        this.weight = weight;
    }

    public Phone(String brand, int weight, String tech) {
        // Here it is where I'm stuck
        // Call SmartPhone constructor with all the parameters
    }
}
</code>```

```<code>public class SmartPhone extends Phone {
    private String tech;

    public SmartPhone(String Brand, int weight, String tech) {
        super(brand, weight);
        this.tech = tech;
    }
}
</code>```

Why would I want to do that?

I would like to be able to not have to deal with SmartPhone in the main.

I'd like to be able to do:

```<code>Phone nokia = new Phone("Nokia", 295); // <- Regular Phone Instance
Phone iphone = new Phone("iPhone", 368, "4G"); // <- SmartPhone instance
</code>```

答:
Calling the constructor of a subclass within the constructor of the base class is not possible. There are various reasons for this but one is that a constructor of a derived class calls, implicitely or explicitly, a constructor of the base class. This would cause an infinite loop.

What you could do, is the following: Create a static method within the base class that decides what instance should be created.

```<code>public class Phone
{
  ...

  public static Phone createPhone(String brand, int weight, String tech)
  {
    if (tech == null)
      return (new Phone(brand, weight));
    else
      return (new SmartPhone(brand, weight, tech));
  }

  ...

}
</code>```

Body:
so I'm learning about java inheritance and I just ran into a situation I don't know how to solve.

What I'm trying to do is to call a subclass constructor from the superclass. I don't know if this makes any sense, but I'll try to explain myself with an example.

public class Phone {
    private String brand;
    private int weight;

    public Phone(String brand, int weight) {
        this.brand = brand;
        this.weight = weight;
    }

    public Phone(String brand, int weight, String tech) {
        // Here it is where I'm stuck
        // Call SmartPhone constructor with all the parameters
    }
}

public class SmartPhone extends Phone {
    private String tech;

    public SmartPhone(String Brand, int weight, String tech) {
        super(brand, weight);
        this.tech = tech;
    }
}

Why would I want to do that?

I would like to be able to not have to deal with SmartPhone in the main.

I'd like to be able to do:

Phone nokia = new Phone("Nokia", 295); // <- Regular Phone Instance
Phone iphone = new Phone("iPhone", 368, "4G"); // <- SmartPhone instance

Body:
Calling the constructor of a subclass within the constructor of the base class is not possible. There are various reasons for this but one is that a constructor of a derived class calls, implicitely or explicitly, a constructor of the base class. This would cause an infinite loop.

What you could do, is the following: Create a static method within the base class that decides what instance should be created.

public class Phone
{
  ...

  public static Phone createPhone(String brand, int weight, String tech)
  {
    if (tech == null)
      return (new Phone(brand, weight));
    else
      return (new SmartPhone(brand, weight, tech));
  }

  ...

}


问:
How to ensure my Google Home Assistant application is not rejected?

During our testing, we were unable to complete at least one of the behaviors or actions advertised by your app. Please make sure that a user can complete all core conversational flows listed in your registration information or recommended by your app.

Thank you for submitting your assistant app for review!

During testing, your app was unable to complete a function detailed in the app’s description. The reviewer interacted with the app by saying: “how many iphones were sold in the UK?” and app replied “I didn't get that. Can you try with other question?" and left conversation.

How can I resolve the above point to approve my Google Assistant action skills?

答:
Without seeing the code in question or the intent you think should be handling this in Dialogflow, it is pretty difficult - but we can generalize.

It sounds like you have two issues:

Your fallback intent that generated the "I didn't get that" message is closing the conversation. This means that either the "close conversation" checkbox is checked in Dialogflow, you're using the app.tell() method when you should be using app.ask() instead, or the JSON you're sending back has close conversation set to true.

You don't have an intent to handle the question about how many iPhones were sold in the UK. This could be because you just don't list anything like that as a sample phrase, or the two parameters (the one for object type and the one for location) aren't using entity types that would match.


问:
What are the concerns of using Crate.io as a primary datastore?
If I am correct, crate (crate.io) is backed by Elasticsearch (Lucene). Weren't there a few articles a month ago that said that ES lost some writes under heavy load? Are there any other concerns?</p>

答:
I am currently evaluating Crate.io as a primary datastore for work. As the above answer is vague and unspecific, maybe it's time for an update on this question here. There is a Dec.2016 keynote presentation out there from the Jepsen author Kyle Kingsbury on Youtube who investigated Crate.io for some problems with the resiliency in Elasticsearch. The first 8 minutes are introduction, the Crate.io part is from 23:50 till 31:10.

For those of you who don't want to watch the full video, here is a short summary.
First, the test setup. They set up databases and a random pattern of clients with random queries. Also, they voluntarily introduced problems for the databases, like network partitioning. Secondly, the results. According to Kingsbury, there are two issues with ES resiliency. Both of them carry on to Crate.io. Let's get to the details...

Dirty reads

The first one -  ES #20031 - is that ES may cause dirty reads, divergence and lost updates if network partitions occur. As of now - December 2017 - this issue is still open. In my opinion, it is possible for the same problems to occur if a node is unresponsive for extremely heavy duty, like during extensive querying, reindexing or garbage collection.

Lost updates

According to Kingsbury, there is another problem ("Can promote stale binaries") with ES that cause updates to get completely lost when network partitioning occurs. It has been tagged as #20384 and there is kind of a fix which Kingsbury summarizes as "partial". So, ES may still cause lost data upon writing.

What does ES say?

On the official site of ES about resiliency, only one of the two problems - #20384 - is mentioned. It has been marked as solved in the version 5.0 release notes, although the official site says that there is only a partial fix.

What does Crate.io say?

On the Crate.io documentation on resiliency, there is a list of known problems with Crate.io resiliency. The ES bug #20384 is commented as partially fixed and still causing an open problem. The ES bug #20031 is not mentioned. However, there is a paragraph about an issue with networking partition which Crate.io marked as fixed - so the official page is kind of inconclusive here.

Conclusion

Kingsbury concluded in December 2016 that Crate.io should not be used as the primary data store. It could be used of course as a replication of your primary data to benefit from the time series database features that Crate.io offers. He also suggests that for machine data where 5% data loss is not a severe problem, Crate.io is a viable option as primary store.
It is my impression that some bugs Kingsbury reported may have been fixed but not all.


问:
Correct way of writing down the attribute list of tuples of floats?
I'm new to UML modeling and I need to write down the attribute of a class that is a list of tuples of floats. How detailed does the attribute section need to be? Here is a code sample for further explanation:

```<code># floats
x1 = 1.0
y1 = 1.0

x2 = 1.1
y2 = 1.1

x3 = 1.2
y3 = 1.2

# tuples of floats
tup1 = (x1,y1)
tup2 = (x2,y2)
tup3 = (x3,y3)

# list of tuples of floats / attribute of my class
points = [tup1,tup2,tup3]
</code>```

The tuples represent points in 2d-space (x- and y-coordinate). What would the attribute of "points" look like?

I thought of different possibilities, but I'm not really satisfied with them:

points : tuple[2..*]

points : float[2..*][2]

I'm lost! Any help is appreciated.

答:
The solution of @ Geert Bellekens solved your point, but you can try a model closest to your code.

Tuple does not exist in UML.

The solution is to define a DataType containing two values.

The difference between DataType and a Class is that a DataType does not have "id", two DataType with the same value are equivalent.

If you have a class Person with name, and age, two instances with the same name and the same age are different: there "ids" are different.

In the schema, Point properties are public to avoid complexity and because this is a DataType but this is "my" choice.

Body:
I'm new to UML modeling and I need to write down the attribute of a class that is a list of tuples of floats. How detailed does the attribute section need to be? Here is a code sample for further explanation:

# floats
x1 = 1.0
y1 = 1.0

x2 = 1.1
y2 = 1.1

x3 = 1.2
y3 = 1.2

# tuples of floats
tup1 = (x1,y1)
tup2 = (x2,y2)
tup3 = (x3,y3)

# list of tuples of floats / attribute of my class
points = [tup1,tup2,tup3]

The tuples represent points in 2d-space (x- and y-coordinate). What would the attribute of "points" look like?

I thought of different possibilities, but I'm not really satisfied with them:

points : tuple[2..*]

points : float[2..*][2]

I'm lost! Any help is appreciated.


问:
Saving dtype = datetime[ns] data array to text using numpy gives unexpected results
I've extracted some data from a data frame and want to save it as a text file

```<code># df is my dataframe with col1, col2...., as column headers
X = df.col1[df['col3']<35].unique()
X[0:3]
>>array(['1998-01-07T11:00:00.000000000', '1998-01-06T23:00:00.000000000',
   '1998-01-28T11:00:00.000000000'], dtype='datetime64[ns]')
np.savetxt('filename', X, delimiter=' ', header='Some Header')
</code>```

I'm expected it to save the dates but instead, the file contains the first few lines as:

```<code># Some Header
8.841708000000000000e+17
8.841276000000000000e+17
8.859852000000000000e+1
</code>```

What am I missing here?

答:
savetxt's default format for each field is '%.18e', which is a floating point format.  Add the fmt argument to change the format, e.g.

```<code>np.savetxt('filename', X, fmt='%s', delimiter=' ', header='Some Header')
</code>```

Body:
I've extracted some data from a data frame and want to save it as a text file

# df is my dataframe with col1, col2...., as column headers
X = df.col1[df['col3']<35].unique()
X[0:3]
>>array(['1998-01-07T11:00:00.000000000', '1998-01-06T23:00:00.000000000',
   '1998-01-28T11:00:00.000000000'], dtype='datetime64[ns]')
np.savetxt('filename', X, delimiter=' ', header='Some Header')

I'm expected it to save the dates but instead, the file contains the first few lines as:

# Some Header
8.841708000000000000e+17
8.841276000000000000e+17
8.859852000000000000e+1

What am I missing here?

Body:
savetxt's default format for each field is '%.18e', which is a floating point format.  Add the fmt argument to change the format, e.g.

np.savetxt('filename', X, fmt='%s', delimiter=' ', header='Some Header')


问:
How to make any control shape irregular in c#
how to make any control of win application transparent. i want that i will assign a background image for the target control and will invoke a routine and that routine will create that control transparent in such a way that only image will visible. as a example suppose image has assign to picture box. the picture shape is not square rather irregular. if i can make picture box transparent then user will see the image only. basically i want to make a picture box or any control irregular shape. how to achieve it through code in c#.

thanks

答:
In WPF, transparency is quasi for free. For the image-element, assign a png-image with an alpha mask and the image will be rendered with active transparency.

For controls with an solid background, you generally have to set the Background to a transparent Brush:

If you want to make a whole window partial transparent, you have to remove the border, set the window style to none, set the background brush to a transparent brush, and set the AllowsTransparency-property of the window to true.


问:
Symfony Twig Form Theming of specific fields
I have a custom form field type and an associated form theme for it. On one page I have a lot of these fields, but one of the fields in particular I want to change.

Is there any way to theme certain fields of the same type (and in the same file) differently?

A simplified example:

form_fields.html.twig: (local theming file)

```<code>{% block my_dropdown_row %}
<div>
    {{ form_label(form) }}
    {{ form_widget(form) }}
    {{ form_errors(form) }}
</div>
{% endblock %}
</code>```

In my form template (all these fields have the same type - my_dropdown

```<code>{{ form_row(form.selectionA) }}
{{ form_row(form.selectionB) }}
{{ form_row(form.selectionC) }}
{{ form_row(form.final_selection) }}
</code>```

How can I style the final field differently to the others? There is a lot of code in these widgets so less duplication the better.

答:
Old question and already answered, but would be nice to have more detailed info.

```<code>{% form_theme form _self %}

    {% block _product_name_widget %}
    <div class="text_widget">
        {{ block('form_widget_simple') }}
    </div>
{% endblock %}

{{ form_widget(form.name) }}
</code>```

Where block name _product_name_widget stands for

_ form type(block prefix)_ form item name_render function

http://symfony.com/doc/current/form/form_customization.html#how-to-customize-an-individual-field

Body:
I have a custom form field type and an associated form theme for it. On one page I have a lot of these fields, but one of the fields in particular I want to change.

Is there any way to theme certain fields of the same type (and in the same file) differently?

A simplified example:

form_fields.html.twig: (local theming file)

{% block my_dropdown_row %}

    {{ form_label(form) }}
    {{ form_widget(form) }}
    {{ form_errors(form) }}

{% endblock %}

In my form template (all these fields have the same type - my_dropdown

{{ form_row(form.selectionA) }}
{{ form_row(form.selectionB) }}
{{ form_row(form.selectionC) }}
{{ form_row(form.final_selection) }}

How can I style the final field differently to the others? There is a lot of code in these widgets so less duplication the better.

Body:
Old question and already answered, but would be nice to have more detailed info.

{% form_theme form _self %}

    {% block _product_name_widget %}
    <div class="text_widget">
        {{ block('form_widget_simple') }}
    </div>
{% endblock %}

{{ form_widget(form.name) }}

Where block name _product_name_widget stands for

_ form type(block prefix)_ form item name_render function

http://symfony.com/doc/current/form/form_customization.html#how-to-customize-an-individual-field


问:
YouTube quotas exceeded
I'm developer and I want to upload a video using the YouTube Data API v3, but it always return the error code "quotas exceeded". I never succeeded upload a video so it's strange...

Do you have a solution for this problem or support address mail to contact in order to solve the problem ?

I send to the API that video with attachment:

```<code>curl --request POST \
     --url 'https://www.googleapis.com/upload/youtube/v3/videos?part=snippet%2Cstatus' \
     --header 'authorization: Bearer MyAccessToken' \
     --header 'cache-control: no-cache' \
     --header 'content-type: application/octet-stream'
</code>```

Here is the error:

```<code>{
      "error": {
            "errors": [{
                    "domain": "youtube.quota",
                    "reason": "quotaExceeded",
                    "message": "The request cannot be completed because you have exceeded your <a href=\"/youtube/v3/getting-started#quota\">quota</a>."
            }],
      "code": 403,
      "message": "The request cannot be completed because you have exceeded your <a href=\"/youtube/v3/getting-started#quota\">quota</a>."
     }
}
</code>```

答:
Hello for resolve the problem you must use accessToken an apiClient and not that of the console oAuth Google. Api Client Youtube
When I use accessToken of this console not working... :) Google oAuth Console</p>

Title: YouTube quotas exceeded

Body:
I'm developer and I want to upload a video using the YouTube Data API v3, but it always return the error code "quotas exceeded". I never succeeded upload a video so it's strange...

Do you have a solution for this problem or support address mail to contact in order to solve the problem ?

I send to the API that video with attachment:

curl --request POST \
     --url 'https://www.googleapis.com/upload/youtube/v3/videos?part=snippet%2Cstatus' \
     --header 'authorization: Bearer MyAccessToken' \
     --header 'cache-control: no-cache' \
     --header 'content-type: application/octet-stream'

Here is the error:

{
      "error": {
            "errors": [{
                    "domain": "youtube.quota",
                    "reason": "quotaExceeded",
                    "message": "The request cannot be completed because you have exceeded your quota."
            }],
      "code": 403,
      "message": "The request cannot be completed because you have exceeded your quota."
     }
}


问:
Can't open png, saved with Chrome
Recently I started studying Android development. To get myself started I'm trying to develop a simple app to track my favorite coffee cups. To this end, I thought I'd download the images (sample) of the cups from the official website. The good news is that I can right-click and save them as .png files and Android (Studio) can display them. The challenge I have is that I can't open these png's (e.g. to view or edit) in any other program. I've tried Windows Paint, Photo viewer, IE, GIMP... none work. The only program I can view the images with is Chrome. Of course this doesn't help me edit them.

I've searched for answers, but can't find any.
I've tried renaming to .webp and .jpg, hoping this could do the trick.
I've tried online file type identifier (checkfiletype.com), which then indicates it's a RIFF file, which doesn't seem very helpful, since it is an image and no audio.
When I download the images via e.g. Firefox or IE, I get different file formats, which seem to be significantly larger file size, so I'd prefer to use the Chrome downloads.

I'm out of options. Would anyone know how to get these files opened/edited?
Preferably I'd be able to open with GIMP. At the moment however I'd even be happy to simply settle to be able to view them outside of Chrome.

答:
Despite the extension, it is not a PNG but a Web/P image:

```<code>14:21:51 tmp/ >identify -verbose Sample-9148239937566.png
identify: delegate failed `"dwebp" -pam "%i" -o "%o"' @ error/delegate.c/InvokeDelegate/1310.
identify: unable to open image `/tmp/magick-30698uSxzl_4IFlIA': No such file or directory @ error/blob.c/OpenBlob/2712.
identify: unable to open file `/tmp/magick-30698uSxzl_4IFlIA': No such file or directory @ error/constitute.c/ReadImage/540.
14:22:10 tmp/ >file Sample-9148239937566.png
Sample-9148239937566.png: RIFF (little-endian) data, Web/P image
</code>```

To open it with Gimp you would need a plugin.

Application that determine filetype based on magic number can open them without problem (if they support the format). Others (like Firefox) need to see the proper file extension (rename the file to *.webp).

Title: Can't open png, saved with Chrome

Body:
Despite the extension, it is not a PNG but a Web/P image:

14:21:51 tmp/ >identify -verbose Sample-9148239937566.png
identify: delegate failed `"dwebp" -pam "%i" -o "%o"' @ error/delegate.c/InvokeDelegate/1310.
identify: unable to open image `/tmp/magick-30698uSxzl_4IFlIA': No such file or directory @ error/blob.c/OpenBlob/2712.
identify: unable to open file `/tmp/magick-30698uSxzl_4IFlIA': No such file or directory @ error/constitute.c/ReadImage/540.
14:22:10 tmp/ >file Sample-9148239937566.png
Sample-9148239937566.png: RIFF (little-endian) data, Web/P image

To open it with Gimp you would need a plugin.

Application that determine filetype based on magic number can open them without problem (if they support the format). Others (like Firefox) need to see the proper file extension (rename the file to *.webp).


问:
Wrong syntax of condition in when in xslt
I am making a condition in when element, and I am having errors while validating file. I think the problem is with '<' elements but I do not know how that should looks like. issue/volume and issue/number, these are values from nodes</p>

```<code><xsl:when test="issue/volume='3' and issue/number < 4 or issue/volume < 3">...</xsl:when>
</code>```

答:
You should really have said what error messages you got, but for the particular code sample you have shown you do need to escape the < symbols as <

```<code><xsl:when test="issue/volume='3' and issue/number < 4 or issue/volume < 3">...</xsl:when>
</code>```

Or, if you are using XSLT 2.0, you can use lt instead

```<code><xsl:when test="issue/volume='3' and issue/number lt 4 or issue/volume lt 3">...</xsl:when>
</code>```

Body:
I am making a condition in when element, and I am having errors while validating file. I think the problem is with '<' elements but I do not know how that should looks like. issue/volume and issue/number, these are values from nodes

<xsl:when test="issue/volume='3' and issue/number < 4 or issue/volume < 3">...</xsl:when>

Body:
You should really have said what error messages you got, but for the particular code sample you have shown you do need to escape the < symbols as &lt;

<xsl:when test="issue/volume='3' and issue/number &lt; 4 or issue/volume &lt; 3">...</xsl:when>

Or, if you are using XSLT 2.0, you can use lt instead

<xsl:when test="issue/volume='3' and issue/number lt 4 or issue/volume lt 3">...</xsl:when>


问:
D3JS background line chart
I might be googling wrong, but I was wondering if it's possible to create a background (image or color) beneath the line. I would like to create something as the image below.

I have created a chart, looks something like this with the example data:

But this is how I imagined it to look a like (don't mind the colors).

See jsFiddle

```<code> var svg,lineGen;

    makeChart();
    function makeChart(){
    // example data
    mobileData = [
    { "uur" : "00", "pageviews":"20"},
    { "uur" : "01", "pageviews":"26"},
    { "uur" : "02", "pageviews":"10"},
    { "uur" : "03", "pageviews":"30"},
    { "uur" : "04", "pageviews":"40"},
    { "uur" : "05", "pageviews":"50"},
    ]

    tabletData = [
    { "uur" : "00", "pageviews":"50"},
    { "uur" : "01", "pageviews":"20"},
    { "uur" : "02", "pageviews":"10"},
    { "uur" : "03", "pageviews":"35"},
    { "uur" : "04", "pageviews":"45"},
    { "uur" : "05", "pageviews":"10"},
    ]

        var WIDTH = 1200,
            HEIGHT = 200,
            MARGINS = {
                    top:20,
                right:20,
                bottom:20,
                left:50
            }
         svg = d3.select("#visualisation"),
            WIDTH = 1200,
            HEIGHT = 200,
            MARGINS = {
                top: 20,
                right: 20,
                bottom: 20,
                left: 50
            },
            xScale = d3.scale.linear().range([MARGINS.left,WIDTH-MARGINS.right]).domain([00,23]),

            yScale = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([00,50]),

            xAxis = d3.svg.axis()
                .scale(xScale)
                .ticks(24)

            yAxis = d3.svg.axis()
                .scale(yScale)
                .ticks(10)
                .tickPadding(20)
                .orient("left");

        svg.append("svg:g")
            .attr("class","axis")
            .attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
            .call(xAxis);

        svg.append("svg:g")
            .attr("class","axis axis-y")
            .attr("transform", "translate(" + (MARGINS.left) + ",0)")
            .call(yAxis);

         lineGen = d3.svg.line()
            .x(function(d){
                return xScale(d.uur);
            })
            .y(function(d){
                return yScale(d.pageviews);
            });

        svg.append('svg:path')
            .attr('d', lineGen(mobileData))
            .attr('stroke','orange')
            .attr('stroke-width',2)
            .attr('fill','none');

        svg.append('svg:path')
            .attr('d', lineGen(tabletData))
            .attr('stroke','deeppink')
            .attr('stroke-width',2)
            .attr('fill','none');
    }
</code>```

答:
You can do it with area. Just add this code:

```<code>var area = d3.svg.area()
  .x(function(d) { return xScale(d.uur); })
  .y(function(d) { return yScale(d.pageviews); })
  .y1(function(d) { return HEIGHT - MARGINS.bottom });

 svg.append("path")
  .attr("fill", "yellow")
  .attr("d", area(mobileData));
</code>```

I forked your fiddle, check it in action.

Title: D3JS background line chart

Body:
I might be googling wrong, but I was wondering if it's possible to create a background (image or color) beneath the line. I would like to create something as the image below.

I have created a chart, looks something like this with the example data:

But this is how I imagined it to look a like (don't mind the colors).

See jsFiddle

 var svg,lineGen;

    makeChart();
    function makeChart(){
    // example data
    mobileData = [
    { "uur" : "00", "pageviews":"20"},
    { "uur" : "01", "pageviews":"26"},
    { "uur" : "02", "pageviews":"10"},
    { "uur" : "03", "pageviews":"30"},
    { "uur" : "04", "pageviews":"40"},
    { "uur" : "05", "pageviews":"50"},
    ]

    tabletData = [
    { "uur" : "00", "pageviews":"50"},
    { "uur" : "01", "pageviews":"20"},
    { "uur" : "02", "pageviews":"10"},
    { "uur" : "03", "pageviews":"35"},
    { "uur" : "04", "pageviews":"45"},
    { "uur" : "05", "pageviews":"10"},
    ]

        var WIDTH = 1200,
            HEIGHT = 200,
            MARGINS = {
                    top:20,
                right:20,
                bottom:20,
                left:50
            }
         svg = d3.select("#visualisation"),
            WIDTH = 1200,
            HEIGHT = 200,
            MARGINS = {
                top: 20,
                right: 20,
                bottom: 20,
                left: 50
            },
            xScale = d3.scale.linear().range([MARGINS.left,WIDTH-MARGINS.right]).domain([00,23]),

            yScale = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([00,50]),

            xAxis = d3.svg.axis()
                .scale(xScale)
                .ticks(24)

            yAxis = d3.svg.axis()
                .scale(yScale)
                .ticks(10)
                .tickPadding(20)
                .orient("left");

        svg.append("svg:g")
            .attr("class","axis")
            .attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")")
            .call(xAxis);

        svg.append("svg:g")
            .attr("class","axis axis-y")
            .attr("transform", "translate(" + (MARGINS.left) + ",0)")
            .call(yAxis);

         lineGen = d3.svg.line()
            .x(function(d){
                return xScale(d.uur);
            })
            .y(function(d){
                return yScale(d.pageviews);
            });

        svg.append('svg:path')
            .attr('d', lineGen(mobileData))
            .attr('stroke','orange')
            .attr('stroke-width',2)
            .attr('fill','none');

        svg.append('svg:path')
            .attr('d', lineGen(tabletData))
            .attr('stroke','deeppink')
            .attr('stroke-width',2)
            .attr('fill','none');
    }

Body:
You can do it with area. Just add this code:

var area = d3.svg.area()
  .x(function(d) { return xScale(d.uur); })
  .y(function(d) { return yScale(d.pageviews); })
  .y1(function(d) { return HEIGHT - MARGINS.bottom });

 svg.append("path")
  .attr("fill", "yellow")
  .attr("d", area(mobileData));

I forked your fiddle, check it in action.


问:
Wrong number of file count being returned from directory
I have a method which searches the top directory for any files and returns the count which is as follows:

```<code>public int AttachmentCountItemDirectory(string directoryPath)
{
   int fileCount = 0;
   if (Directory.Exists(directoryPath))
       fileCount = Directory.GetFiles(directoryPath, "*", SearchOption.TopDirectoryOnly).Length;

   return fileCount;
}
</code>```

The above method works great when there's 1 or more files in the directory. The issue I am facing is when there are no files the count is still 1 for some weird reason. I have enabled Show Hidden files, folders, and drives and from the image below it's clear there is no file.

Am I missing something obvious here? Can someone tell me where I'm going wrong please

答:
You commented

It was thumbs.db

So the original question is answered.

My suggestion was to apply a filter to return only relevant files

Can i supply multiple filters at once? The filters I want to apply
  are: pdf,doc,docx,xls,xlsx,jpeg,png

Yes, you can use LINQ:

```<code>public int AttachmentCountItemDirectory(string directoryPath)
{
   string[] attExt = {".pdf",".doc",".docx",".xls",".xlsx",".jpeg",".png"};
   return Directory.EnumerateFiles(directoryPath)
     .Count(f => attExt.Contains(Path.GetExtension(f), StringComparer.InvariantCultureIgnoreCase));
}
</code>```

I would not return 0 if an invalid path is passed to the method. I throw an exception then.

Body:
I have a method which searches the top directory for any files and returns the count which is as follows:

public int AttachmentCountItemDirectory(string directoryPath)
{
   int fileCount = 0;
   if (Directory.Exists(directoryPath))
       fileCount = Directory.GetFiles(directoryPath, "*", SearchOption.TopDirectoryOnly).Length;

   return fileCount;
}

The above method works great when there's 1 or more files in the directory. The issue I am facing is when there are no files the count is still 1 for some weird reason. I have enabled Show Hidden files, folders, and drives and from the image below it's clear there is no file.

Am I missing something obvious here? Can someone tell me where I'm going wrong please

Body:
You commented

It was thumbs.db

So the original question is answered.

My suggestion was to apply a filter to return only relevant files

Can i supply multiple filters at once? The filters I want to apply
  are: pdf,doc,docx,xls,xlsx,jpeg,png

Yes, you can use LINQ:

public int AttachmentCountItemDirectory(string directoryPath)
{
   string[] attExt = {".pdf",".doc",".docx",".xls",".xlsx",".jpeg",".png"};
   return Directory.EnumerateFiles(directoryPath)
     .Count(f => attExt.Contains(Path.GetExtension(f), StringComparer.InvariantCultureIgnoreCase));
}

I would not return 0 if an invalid path is passed to the method. I throw an exception then.


问:
How can I exclude beans from certain contexts in Spring?
I have a project that mixes Spring Batch with Spring Web. It's primarily a Spring Batch project that runs jobs, but we've got a few REST endpoints on there, and the Spring Batch Admin Manager module as well. Our base project has its own (primary) application context, but the Admin Manager project we've included in the POM effectively creates its own context as well.

One of my classes is a @RestController which means it automatically gets instantiated by both contexts. This controller has a couple of @Autowired dependencies, which is fine when the first context runs because it finds them all. But when the second context runs, it fails to find those dependencies and so the app fails to launch properly.

But because this second context is created automatically, behind the scenes, from that aforementioned Sping Batch Admin Manager project, I don't really have control over it. Is there some way I can manually specify in my @RestController that it should be excluded from all but my primary context?

答:
You can use one of the @Conditional annotations

E.g. @ConditionalOnClass or @ConditionalOnMissingClass or @ConditionalOnBean or @ConditionalOnMissingBean

So your controller just checks whether there is classes/beans which is required to run the endpoint

Read more here


问:
bootstrap 4 modal-header trying to get badge aligned on right
I'm trying to get the "Banana Score" badge to float right, but to no avail. Does anyone know if this is even possible in Bootstrap 4.

I've tried all sorts of variations around flex, the best I had was a hack using columns, but this looks worse than the example below.

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"  crossorigin="anonymous">

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

Customer
            Banana Score  4

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

```

答:
Without Css , using bootstrap html classes.

Header 5 (#exampleModalLabel) : add CSS class col-md-10 or w-100

adds:

col-md-10 = position: relative; width: 100%; min-height: 1px; padding-right: 15px; padding-left: 15px;

OR

w-100 = width: 100%;

span (#test) : add (2) CSS classes mt-1 float-right

adds:

mt-1 = margin-top: 1px;

float-right = float: right;

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"  crossorigin="anonymous">

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

Customer
            Banana Score  4

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

```

Body:
Without Css , using bootstrap html classes.

Header 5 (#exampleModalLabel) : add CSS class col-md-10 or w-100

adds:

col-md-10 = position: relative; width: 100%; min-height: 1px; padding-right: 15px; padding-left: 15px;

OR

w-100 = width: 100%;

span (#test) : add (2) CSS classes mt-1 float-right

adds:

mt-1 = margin-top: 1px;

float-right = float: right;

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"  crossorigin="anonymous">

    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">

          <h5 class="modal-title col-md-10" id="exampleModalLabel">Customer
            <span id="test" class="badge badge-secondary mt-1 float-right">Banana Score  <span class="badge badge-light">4</span></span></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">

      </div>
      <div class="modal-footer">

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>


问:
Database repository dependencies in Hexagonal Architecture
i'm migrating a nTier architecture into an hexagonal one.
My domain is well defined now, and I have interfaces for all infrastructure dependencies.
Looking at database repositories, I have several databases and there is one class implementing each repo, in the Infra side.
My question is about what should be the correct approach about DB dependency:

1- To have one interface on domain side to deal with data access and then rely on Infrastructure implementation and have there one class as entry point for all database repositories, like a facade, from where all repository implementations will be called. This approach is the same I already have in nTier application, the facade and the repos are the current Database Layers.

2- Have interfaces for each database I need on Domain side. Each interface will be implemented on Infra side to access the corresponding DB. It keeps layers thin, but this aproach add Data management logic to the Domain. The Domain should not care where the data is, the Infra should deal with this. If some data is moved to another database then the corresponding interface needs to changed on Domain side (to move the method exposing this data to another interface for example)

let me know,

答:
That's a good question. I had the same dilemma in one application, and I decided going for the first option you expose:

Just one port for access data, the domain doesn't care about the origin of the data, no matter which database the data is stored. And in the adapter I have a facade to forward the request to the correct database. In fact in my case the resulting data maybe a mix from the two databases.

But I think the other option is valid too, if we consider the databases as external systems our app have to talk to. Our app must know which secondary actors must communicate with, and in that case, each one would have a port at the domain.

Anyway, I think 1st option is more "correct", because a port in hexagonal architecture is the purppose of the communication, being the purppose in this case "retrieving data". In this talk Alistair Cockburn explains it. He says the ports must be named by their intention, saying what they are for. A port is for ...ing something.

Talk "Alistair in the Hexagon":

https://www.youtube.com/watch?v=th4AgBcrEHA

https://www.youtube.com/watch?v=iALcE8BPs94

https://www.youtube.com/watch?v=DAe0Bmcyt-4


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

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

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

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

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

答:
I prefer to use

```<code>subprocess.check_output(['git', 'push'], stderr=subprocess.STDOUT)
</code>```

as it suppresses the output and only complains when an error has occured.

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

   import os
   import datetime as dt

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

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

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

Body:
I prefer to use

subprocess.check_output(['git', 'push'], stderr=subprocess.STDOUT)

as it suppresses the output and only complains when an error has occured.


问:
How to refresh "Tasks" in Eclipse?
I inherited a program with a lot of //TODO: messages, which i expected would show up under Tasks.

Unfortunately, that pane is empty. Is there a way to refresh it for the current project?

答: If it is the "Eclipse IDE for C/C++ Developers" you are using then "Project -> C/C++ Index -> Rebuild" will do the trick rather than Project clean/build.</p>

Title: How to refresh "Tasks" in Eclipse?


问:
Process command "arp -a" on android?
I'm trying to call "arp -a" on my android device, but since it only works for pc - how do i change this? Is there a way to access a list of the ip-addresses, that arp -a gives you, but on android instead?

My code is like this on the android device:

```<code>try {

        Process process = Runtime.getRuntime().exec("arp -a");
        process.waitFor();
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        int i = 0;
        while (reader.ready()) {
            i++;
            String ip = reader.readLine();
            if (i >= 4) {
                ip = ip.substring(2, 15) + "\n";
            }
        }
    } catch (IOException | InterruptedException ioe) {
        ioe.printStackTrace();
    }
</code>```

答: Install busybox and some terminal emulator, connect to Wi-Fi and you are done.</p>

Title: Process command "arp -a" on android?

Body:
I'm trying to call "arp -a" on my android device, but since it only works for pc - how do i change this? Is there a way to access a list of the ip-addresses, that arp -a gives you, but on android instead?

My code is like this on the android device:

try {

        Process process = Runtime.getRuntime().exec("arp -a");
        process.waitFor();
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        int i = 0;
        while (reader.ready()) {
            i++;
            String ip = reader.readLine();
            if (i >= 4) {
                ip = ip.substring(2, 15) + "\n";
            }
        }
    } catch (IOException | InterruptedException ioe) {
        ioe.printStackTrace();
    }


问:
Bluetooth Low Energy Device Simulator/Emulator
For quite some time now, I have had a keen interest with the Bluetooth Low Energy (BLE) Protocol version 4.0 and how it works. I have developed an android application that would serve as a central device to the BLE peripheral device. The problem is the BLE device is not yet ready and I would like to know if there is a simulator or an emulator for BLE devices that can interact with my android application installed in my smartphone.</p>

答:
The easiest way to do that without any specific additional HW is to use another Android or iOS mobile phone acting as a peripheral emulating the BLE device that's not ready yet. Thus, you'll be able to test your Central role Android app in a simple way.

All you have to do is download one of the following apps for example, set up your services and characteristics and start playing.

[Android]: nRF Connect for Mobile

[iOS]: nRF Connect for Mobile or LightBlue


问:
How do we get maximum value from table without using Max,Min or Order by Clause in SQL Server 2005?
I have one table has Salary has 3 columns and I want to get maximum value from this table without using Max, Min or order by clause.

Data

Salary has three fields - ID,Name,Amount
value of Amount - 100,70,80,400,300

I need to get value of 400 from this data.

I know Select max(Amount) from Salary, But i need without max,min or Order by clause.

Thanks in advance.

答:
```<code>declare @amount int

SELECT @amount = CASE WHEN @amount > amount THEN @amount ELSE amount END
FROM yourtable

select @amount
</code>```

This is most definitely not an optimization though as (assuming an index on amount) MAX could stop scanning after the first result whereas this must scan all records.

It is still more efficient than this though

```<code>SELECT *
FROM salary s1
WHERE NOT EXISTS(SELECT * FROM salary s2 WHERE s2.amount  > s1.amount)
</code>```

Which in turn is massively more efficient than ALL

Body:
declare @amount int

SELECT @amount = CASE WHEN @amount > amount THEN @amount ELSE amount END
FROM yourtable

select @amount

This is most definitely not an optimization though as (assuming an index on amount) MAX could stop scanning after the first result whereas this must scan all records.

It is still more efficient than this though

SELECT *
FROM salary s1
WHERE NOT EXISTS(SELECT * FROM salary s2 WHERE s2.amount  > s1.amount)

Which in turn is massively more efficient than ALL