问:
What is the different between Navigation.PushModalAsync() andNavigation.PushAsync() In Xamarin Forms?
Reason for ask this i got error when i use PushAsync in xamarin forms mvvm architecture

```<code>await Navigation.PushAsync(new Page2());
</code>```

Error is

I have corrected this error by changing PushAsync to PushModelAsync

```<code>await Navigation.PushModalAsync(new Page2());
</code>```

anyone has idea about what cause to this error?

i am calling PushModelAsync from ViewModel

```<code>public class Page1Model : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public INavigation Navigation { get; set; }
        public Command ContinueBtnClicked { get; }

        public Page1Model(INavigation navigation)
        {
            this.Navigation = navigation;
            this.ContinueBtnClicked = new Command(async () => await GotoPage2());
        }

        public async Task GotoPage2()
        {
            await Navigation.PushModalAsync(new Page2());
        }
    }
</code>```

答:
In your App.xaml.cs wrap your first page in a NavigationPage, like this: MainPage = new NavigationPage(new Page1());.

Now it will work. If you just have a single page, iOS doesn't know how to navigate to another page from there, so it needs a container page to handle navigation.

The reason the the modal variant works is because it spawns a new navigation stack and shows pages on top of everything else (hence modal).

Body:
Reason for ask this i got error when i use PushAsync in xamarin forms mvvm architecture

await Navigation.PushAsync(new Page2());

Error is

I have corrected this error by changing PushAsync to PushModelAsync

await Navigation.PushModalAsync(new Page2());

anyone has idea about what cause to this error?

i am calling PushModelAsync from ViewModel

public class Page1Model : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public INavigation Navigation { get; set; }
        public Command ContinueBtnClicked { get; }

        public Page1Model(INavigation navigation)
        {
            this.Navigation = navigation;
            this.ContinueBtnClicked = new Command(async () => await GotoPage2());
        }

        public async Task GotoPage2()
        {
            await Navigation.PushModalAsync(new Page2());
        }
    }


来源: stackexchange

问:
How can I identify when the iphone app is NOT opened due to a push notification?
I understand you can capture the fact that an app has opened due to a Push notification.

App not in the background = didFinishLaunchingWithOptions and evaluate launchOptions for "aps"

App in background = didReceiveRemoteNotification is called

Of course in didFinishLaunchingWithOptions I can also differentiate with opening the app normally via the icon by the absence of "aps"

However, if the app is in the background and is opened normally via the icon where can I identify this? There is no specific event method called on the delegate and I only get applicationWillEnterForeground which is called either way with no launchOptions to examine.

My scenario is the user gets a push (changing the badge number), closes it (app will not know about it now) and then later opens the app. The change in badge tells me in lieu of a push open that something has changed outside of the app requiring some behaviour.

Thx :)

答:
After some searching I found some discussion here about checking the application state.

http://www.nomadplanet.fr/2010/09/the-incomplete-implementation-of-push-notifications/

ContentLicense: CC BY-SA 2.5


问:
Preserve function context in Python
I'm having a function in Python that when being called first, reads the content of a file to a list and checks whether or not an element is within that list.

```<code>def is_in_file(element, path):
    with open(path, 'r') as f:
        lines = [line.strip() for line in f.readlines()]
    return element in lines
</code>```

When the function is being called again, however, the content of the file should not be read again; the function should instead remember the value of lines from the first call.

Is there a way to preserve the context of a function when calling the function again? I don't want to make lines global to not litter the above namespace. I guess it's quite similar to the use of a generator and the yield statement...

答:
Use the functools.lru_cache decorator to set up a helper function that reads in any given file only once and then stores the result.

```<code>from functools import lru_cache

@lru_cache(maxsize=1)
def read_once(path):
    with open(path) as f:
        print('reading {} ...'.format(path))
        return [line.strip() for line in f]

def in_file(element, path):
    return element in read_once(path)
</code>```

Demo:

```<code>>>> in_file('3', 'file.txt')
reading file.txt ...
True
>>> in_file('3', 'file.txt')
True
>>> in_file('3', 'anotherfile.txt')
reading anotherfile.txt ...
False
>>> in_file('3', 'anotherfile.txt')
False
</code>```

This has the serious advantage that in_file does not have to be called with the same file name every time.

You can adjust the maxsize argument to a higher number if you want more than one file to be cached at any given time.

Lastly: consider at set for the return value of read_once if all you are interested in are membership tests.

ContentLicense: CC BY-SA 3.0

Title: Preserve function context in Python

Body:
I'm having a function in Python that when being called first, reads the content of a file to a list and checks whether or not an element is within that list.

def is_in_file(element, path):
    with open(path, 'r') as f:
        lines = [line.strip() for line in f.readlines()]
    return element in lines

When the function is being called again, however, the content of the file should not be read again; the function should instead remember the value of lines from the first call.

Is there a way to preserve the context of a function when calling the function again? I don't want to make lines global to not litter the above namespace. I guess it's quite similar to the use of a generator and the yield statement...

Body:
Use the functools.lru_cache decorator to set up a helper function that reads in any given file only once and then stores the result.

from functools import lru_cache

@lru_cache(maxsize=1)
def read_once(path):
    with open(path) as f:
        print('reading {} ...'.format(path))
        return [line.strip() for line in f]

def in_file(element, path):
    return element in read_once(path)

Demo:

>>> in_file('3', 'file.txt')
reading file.txt ...
True
>>> in_file('3', 'file.txt')
True
>>> in_file('3', 'anotherfile.txt')
reading anotherfile.txt ...
False
>>> in_file('3', 'anotherfile.txt')
False

This has the serious advantage that in_file does not have to be called with the same file name every time.

You can adjust the maxsize argument to a higher number if you want more than one file to be cached at any given time.

Lastly: consider at set for the return value of read_once if all you are interested in are membership tests.


问:
ng-bootstrap and Angular 5 compatibility
Was ng-bootstrap already tested with Angular 5 and is it compatible ?

If not, any compatible ng-bootsrap angular 5 release planned ?

Thanks !

答:
UPDATE: I was not aware that there was a difference between ng-bootstrap and @ng-bootstrap on NPMjs. Of course @ng-bootstrap is what you are talking about, and this is currently dependent on Angular 4.

OLD ANSWER

ng-bootstrap is dependent on Angular 4.

I suggest moving to ngx-bootstrap (ng-bootstrap name change to 'x') that will support all future versions of Angular.

My reference is from the NPMjs page for ng-bootstrap writing that ng-bootstrap package changed name to ngx-bootstrap.


问:
Highcharts custom error handler
We are using highcharts to plot multiple charts on a single HTML page.

However one/some of the chart throw highchart error and we like to capture those error and show different error to user.
For this highcharts do provide custom error handler. But this custom error handler does not provide information about specific chart throwing that error.

Here that JS Fiddle provided by highcharts, which works fine for a chart :

```<code>Highcharts.error = function (code, true) {
// See
https://github.com/highcharts/highcharts/blob/master/errors/errors.xml
// for error id's
Highcharts.charts[0].renderer
    .text('Chart error ' + code)
    .attr({
        fill: 'red',
        zIndex: 20
    })
    .add()
    .align({
        align: 'center',
        verticalAlign: 'middle'
    }, null, 'plotBox');
};
</code>```

http://jsfiddle.net/gh/get/library/pure/highslide-software/highcharts.com/tree/master/samples/highcharts/chart/highcharts-error/

Any idea how can I use this custom error handler per chart?
I'm using new Highcharts.Charts(options) to create new chart, but don't see way to specify error handler per chart.

Additional info: Charts are refreshed/appended using data through APIs. User that configures chart also configures refresh interval and query to use for chart.

答:
Highcharts error function is not adjusted to have a chart context as an argument, because it can be executed in different contexts too.

For example: error number 16 occurs when Highcharts/Highstock is loaded second time in the same page. It has nothing to do with the chart, because it depends on script importing only.

The workaround I found requires some searching and and a little bit of coding.

Refer to this live demo: http://jsfiddle.net/kkulig/a8nun9aL/

I found the place in the code responsible for throwing the error 10 (the one you used in your example). I overwrote this function (see this doc page for more information about overwriting in Highcharts: https://www.highcharts.com/docs/extending-highcharts/extending-highcharts) and added a chart variable (from Highcharts.Axis.prototype.setTickInterval scope) as the third argument:

```<code>  if (
    axis.positiveValuesOnly &&
    !secondPass &&
    Math.min(axis.min, pick(axis.dataMin, axis.min)) <= 0
  ) { // #978
    H.error(10, 1, chart); // Can't plot negative values on log axis // MODIFIED LINE
  }
</code>```

It should be done for all errors you want to custom handle.

Now it can be used in custom Highcharts.error function:

```<code>Highcharts.error = function(code, stop, chart) {
  // See https://github.com/highcharts/highcharts/blob/master/errors/errors.xml
  // for error id's
  Highcharts.charts[0].renderer
    .text('Chart error ' + code + " on chart titled: " + chart.title.textStr)

    (...)
</code>```

You can add your own property in chart constructor options and find it in chart.options object.

Title: Highcharts custom error handler

Body:
We are using highcharts to plot multiple charts on a single HTML page.

However one/some of the chart throw highchart error and we like to capture those error and show different error to user.
For this highcharts do provide custom error handler. But this custom error handler does not provide information about specific chart throwing that error.

Here that JS Fiddle provided by highcharts, which works fine for a chart :

Highcharts.error = function (code, true) {
// See
https://github.com/highcharts/highcharts/blob/master/errors/errors.xml
// for error id's
Highcharts.charts[0].renderer
    .text('Chart error ' + code)
    .attr({
        fill: 'red',
        zIndex: 20
    })
    .add()
    .align({
        align: 'center',
        verticalAlign: 'middle'
    }, null, 'plotBox');
};

http://jsfiddle.net/gh/get/library/pure/highslide-software/highcharts.com/tree/master/samples/highcharts/chart/highcharts-error/

Any idea how can I use this custom error handler per chart?
I'm using new Highcharts.Charts(options) to create new chart, but don't see way to specify error handler per chart.

Additional info: Charts are refreshed/appended using data through APIs. User that configures chart also configures refresh interval and query to use for chart.

Body:
Highcharts error function is not adjusted to have a chart context as an argument, because it can be executed in different contexts too.

For example: error number 16 occurs when Highcharts/Highstock is loaded second time in the same page. It has nothing to do with the chart, because it depends on script importing only.

The workaround I found requires some searching and and a little bit of coding.

Refer to this live demo: http://jsfiddle.net/kkulig/a8nun9aL/

I found the place in the code responsible for throwing the error 10 (the one you used in your example). I overwrote this function (see this doc page for more information about overwriting in Highcharts: https://www.highcharts.com/docs/extending-highcharts/extending-highcharts) and added a chart variable (from Highcharts.Axis.prototype.setTickInterval scope) as the third argument:

  if (
    axis.positiveValuesOnly &&
    !secondPass &&
    Math.min(axis.min, pick(axis.dataMin, axis.min)) <= 0
  ) { // #978
    H.error(10, 1, chart); // Can't plot negative values on log axis // MODIFIED LINE
  }

It should be done for all errors you want to custom handle.

Now it can be used in custom Highcharts.error function:

Highcharts.error = function(code, stop, chart) {
  // See https://github.com/highcharts/highcharts/blob/master/errors/errors.xml
  // for error id's
  Highcharts.charts[0].renderer
    .text('Chart error ' + code + " on chart titled: " + chart.title.textStr)

    (...)

You can add your own property in chart constructor options and find it in chart.options object.


问:
How to clone scope in angularjs?
I have data as follow:

```<code>$scope.form= response.data.shooter;
oldData= response.data.shooter;
</code>```

I have an issue in here:

Both have the same object array.

When I delete any value from oldData, it is also getting removed from $scope.form.

The code is as follows:

```<code>$.each(oldData, function(i, e) {
  console.log(oldData[e], $scope.form[e]);
  oldData[e] = '';
  console.log(oldData[e], $scope.form[e]);
});
</code>```

I have searched regarding this, but no luck.

Can anyone tell me, how to create a replica of scope to handle it separately regardless of sync between two array objects i.e. independent replica of scope so that if I make changes in that replica should not affect in scope?

答:
Yes you can use angular.copy .For copy the object to other.

angular.copy(source, [destination]);

oldData = angular.copy($scope.form);

angular.copy($scope.leader, oldData);

both you can use

https://docs.angularjs.org/api/ng/function/angular.copy

also you can have a look at lodash and underscore

This library provide very nice to method .

ContentLicense: CC BY-SA 4.0

Title: How to clone scope in angularjs?

Body:
I have data as follow:

$scope.form= response.data.shooter;
oldData= response.data.shooter;

I have an issue in here:

Both have the same object array.

When I delete any value from oldData, it is also getting removed from $scope.form.

The code is as follows:

$.each(oldData, function(i, e) {
  console.log(oldData[e], $scope.form[e]);
  oldData[e] = '';
  console.log(oldData[e], $scope.form[e]);
});

I have searched regarding this, but no luck.

Can anyone tell me, how to create a replica of scope to handle it separately regardless of sync between two array objects i.e. independent replica of scope so that if I make changes in that replica should not affect in scope?


问:
Strange behavior with Observable results in Angular/Typescript
I have the following problem. Imagine a single Angular 2 service:

```<code>validate() {
        return this.http.get('api/validate', data); }
</code>```

When I am trying to consume the above API, everything is Okay with that:

```<code>this.ValidationService.validate().subscribe(result => {
            console.log('data returned from api', result);
        });
</code>```

and the result is an object:

```<code>{status: "success", data: {…}}
</code>```

However, what will drive me crazy is when I am trying:

```<code>this.ValidationService.validate().subscribe(result => {
                console.log('data returned from api', result.data);
            });
</code>```

Typescript complains there is no data property and there is a compilation error!! At the same time from the following I am getting true...

```<code>this.ValidationService.validate().subscribe(result => {
            console.log('data returned from api', result.hasOwnProperty('data'));
        });
</code>```

I also tried result['data']. It did not work as well. Any idea about what may happen?

答:
try this, add ?  to prevent errors  :</p>

```<code>console.log('data returned from api', result?.data);
</code>```

Body:
I have the following problem. Imagine a single Angular 2 service:

validate() {
        return this.http.get('api/validate', data); }

When I am trying to consume the above API, everything is Okay with that:

this.ValidationService.validate().subscribe(result => {
            console.log('data returned from api', result);
        });

and the result is an object:

{status: "success", data: {…}}

However, what will drive me crazy is when I am trying:

this.ValidationService.validate().subscribe(result => {
                console.log('data returned from api', result.data);
            });

Typescript complains there is no data property and there is a compilation error!! At the same time from the following I am getting true...

this.ValidationService.validate().subscribe(result => {
            console.log('data returned from api', result.hasOwnProperty('data'));
        });

I also tried result['data']. It did not work as well. Any idea about what may happen?

Body:
try this, add ?  to prevent errors  :

console.log('data returned from api', result?.data);


问:
Django form validation don't function
I try to put validations in my form but after I follow the official documentation and tutorials I don't obtain the solution.
This is my code:
(The variables of class are indented)

```<code>class QuestionForm(forms.Form):
subject = forms.CharField(widget=forms.Select(attrs={'class': 'select'},
                          choices=SUBJECTS_SELE),
                          label='Materia')
question = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
                           label='Pregunta',
                           max_length=5000)
answer = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
                         label='Respuesta correcta',
                         max_length=1000)
answerOne = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'rows': 1}),
                            label='Respuesta incorrecta',
                            max_length=1000,
                            required=True)

def clean_question(self):
     question = self.cleaned_data.get('question')
     a = "0"
     if not a in question:
         raise forms.ValidationError("Es obligatorio llenar este campo")
     return question

def clean_answer(self):
     answer = self.cleaned_data.get('answer')
     a = "0"
     if not a in answer:
         raise forms.ValidationError("Es obligatorio llenar este campo")
     return answer
</code>```

Also I have try this way:

```<code>def clean(self, *args, **kwargs):
        question = self.cleaned_data.get('question')
        answer = self.cleaned_data.get('answer')
        if question != "0":
            raise forms.ValidationError("Es obligatorio llenar este campo")
        if answer != "0":
            raise forms.ValidationError("Es obligatorio llenar este campo")
        return super(QuestionForm, self).clean(*args, **kwargs)
</code>```

In this case the view corresponding to this form is the following one:

```<code>def ayudanos(request):
    form = QuestionForm(request.POST or None)
    if form.is_valid():
        form_data = form.cleaned_data
        subject = form_data.get("subject")
        question = form_data.get("question")
        answer = form_data.get("answer")
        answerOne = form_data.get("answerOne")
        answerTwo = form_data.get("answerTwo")
        name = form_data.get("name")
        obj = QuestionSele.objects.create(subject=subject, question=question, answer=answer, answerOne=answerOne,
                                          answerTwo=answerTwo, name=name)
    context = {
        "form": form
    }
    return render(request, "ayudanos.html", context)
</code>```

Where the variables passed to the object is for save in a BBDD.

ACTUALIZED--------------------

After try the options people recommended my in the comments, I didn't see the validation message, and the moment I have remove the part of code which reload page after doing the form I could see the validation message.

my html and JavaScript:

```<code><div class="col-md-6">
        {% if form %}
        <form action="" method="POST" id="askFortm"> {% csrf_token %}
          {{ form.as_p }}
          <button class="btn btn-lg btn-primary enviar" id="enviar" type="submit" value="Enviar">Introducir otra
              pregunta</button>
          </form>
          {% endif %}
    </div>

<script>

    $(function() {
        var counter = 94;
        $( "#enviar" ).click(function() {
            counter = counter + 1;
                //alert(counter);
                localStorage.setItem("counter",counter);
                alert('Su pregunta ha sido enviada correctamente. ' +
                    'Envía otra y tendras más posibilidades de ganar los Airpods.');
            });
        $('#askFortm').on('submit', function(e) {
              e.preventDefault();
              setTimeout(function() {
                   window.location.reload();
              },0);
              this.submit();
        });
    });

    </script>
</code>```

I suppose that the problem can be relation with the reload page,  is possible I have to compare the csrf_token or something like this?
Can you help me, thanks.

答:
Finally I have solve this putting an HttpResponseRedirect in my views:</p>

```<code>def ayudanos(request):
form = QuestionForm(request.POST or None)
if form.is_valid():
    form_data = form.cleaned_data
    subject = form_data.get("subject")
    question = form_data.get("question")
    answer = form_data.get("answer")
    answerOne = form_data.get("answerOne")
    answerTwo = form_data.get("answerTwo")
    name = form_data.get("name")
    email = form_data.get("email")
    obj = QuestionSele.objects.create(subject=subject, question=question, answer=answer, answerOne=answerOne,
                                      answerTwo=answerTwo, name=name, email=email)
    return HttpResponseRedirect(reverse('ayudanos'))
context = {
    "form": form
}
return render(request, "ayudanos.html", context)
</code>```

Title: Django form validation don't function

Body:
I try to put validations in my form but after I follow the official documentation and tutorials I don't obtain the solution.
This is my code:
(The variables of class are indented)

class QuestionForm(forms.Form):
subject = forms.CharField(widget=forms.Select(attrs={'class': 'select'},
                          choices=SUBJECTS_SELE),
                          label='Materia')
question = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
                           label='Pregunta',
                           max_length=5000)
answer = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
                         label='Respuesta correcta',
                         max_length=1000)
answerOne = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'rows': 1}),
                            label='Respuesta incorrecta',
                            max_length=1000,
                            required=True)

def clean_question(self):
     question = self.cleaned_data.get('question')
     a = "0"
     if not a in question:
         raise forms.ValidationError("Es obligatorio llenar este campo")
     return question

def clean_answer(self):
     answer = self.cleaned_data.get('answer')
     a = "0"
     if not a in answer:
         raise forms.ValidationError("Es obligatorio llenar este campo")
     return answer

Also I have try this way:

def clean(self, *args, **kwargs):
        question = self.cleaned_data.get('question')
        answer = self.cleaned_data.get('answer')
        if question != "0":
            raise forms.ValidationError("Es obligatorio llenar este campo")
        if answer != "0":
            raise forms.ValidationError("Es obligatorio llenar este campo")
        return super(QuestionForm, self).clean(*args, **kwargs)

In this case the view corresponding to this form is the following one:

def ayudanos(request):
    form = QuestionForm(request.POST or None)
    if form.is_valid():
        form_data = form.cleaned_data
        subject = form_data.get("subject")
        question = form_data.get("question")
        answer = form_data.get("answer")
        answerOne = form_data.get("answerOne")
        answerTwo = form_data.get("answerTwo")
        name = form_data.get("name")
        obj = QuestionSele.objects.create(subject=subject, question=question, answer=answer, answerOne=answerOne,
                                          answerTwo=answerTwo, name=name)
    context = {
        "form": form
    }
    return render(request, "ayudanos.html", context)

Where the variables passed to the object is for save in a BBDD.

ACTUALIZED--------------------

After try the options people recommended my in the comments, I didn't see the validation message, and the moment I have remove the part of code which reload page after doing the form I could see the validation message.

my html and JavaScript:

        {% if form %}
        <form action="" method="POST" id="askFortm"> {% csrf_token %}
          {{ form.as_p }}
          <button class="btn btn-lg btn-primary enviar" id="enviar" type="submit" value="Enviar">Introducir otra
              pregunta</button>
          </form>
          {% endif %}

I suppose that the problem can be relation with the reload page,  is possible I have to compare the csrf_token or something like this?
Can you help me, thanks.

Body:
Finally I have solve this putting an HttpResponseRedirect in my views:

def ayudanos(request):
form = QuestionForm(request.POST or None)
if form.is_valid():
    form_data = form.cleaned_data
    subject = form_data.get("subject")
    question = form_data.get("question")
    answer = form_data.get("answer")
    answerOne = form_data.get("answerOne")
    answerTwo = form_data.get("answerTwo")
    name = form_data.get("name")
    email = form_data.get("email")
    obj = QuestionSele.objects.create(subject=subject, question=question, answer=answer, answerOne=answerOne,
                                      answerTwo=answerTwo, name=name, email=email)
    return HttpResponseRedirect(reverse('ayudanos'))
context = {
    "form": form
}
return render(request, "ayudanos.html", context)


问:
Cordova "Error mounting to image" and "No devices found to debug" on Remote Build to Mac using Xcode
I am trying to debug my cordova project on an iPhone using a remote build on my mac. The build is successful but when trying to deploy I get the following two error messages:

Failed to launch iOS remote for build

  C:\Flex\Trunk\Flex.Net\Flex.Net.MobileHybrid\bld\ios\Release\buildInfo.json`
  to http://[ipadress]:port/cordova :  Http 404: Error mounting
  developer disk image

Regarding this error, this is what I've already tried and has not helped:

Restarting all devices

Making sure that I actually have a disk image for each iOS by checking in folder Finder > Xcode > Show Package Contents > Developer > Platforms > DeviceSupport.

Downloading latest XCode, Cordova and iOS (10.0.2) on my phone.

Using a phone with a lower version iOS (9.3).

Failed to Debug iOS remote for build
  C:\Flex\Trunk\Flex.Net\Flex.Net.MobileHybrid\bld\ios\Release\buildInfo.json
  to http://[ipadress]:port/cordova :
      Http 500: No devices found to debug. Please ensure that a device is connected and awake and retry.

And in regards to this error, what I've tried is the following:

Making sure all different kinds of apple developer certificates are as they should be. I have also tried to debug the device on XCode on my Mac, which works fine.

I have tried restarting all devices involved and update everything (xcode, visual studio, iOS, cordova, plugins etc), and tried registering a different iPhone as well.

Does anyone have any idea as to what might be causing this? I feel like I have tried almost everything.

答:
I tried Zelina's solution, I got this message Error: libimobiledevice HEAD-45fda81 already installed and somehow it continued to fail (Http 404 and 500).

So I followed these steps in my MAC terminal:

brew uninstall ideviceinstaller

brew uninstall --ignore-dependencies --force libimobiledevice

brew update && brew install libimobiledevice --HEAD && brew install ideviceinstaller ios-webkit-debug-proxy

brew upgrade ios-webkit-debug-proxy

If you don't get any installation errors, try to debug with VS2015 again and this time it should work.

I hope it helps someone out there as I spent way too long to find this solution and I know the frustration.


问:
How to delete values from first table by using name of the second sql
I have a table groups

```<code>group_id | name_group
1          ISI
2          IZI
</code>```

And a table students

```<code>id | first_name | last_name | group_id
6    Bob          Surname1    1
17   John         Surname2    2
</code>```

How can I delete all information from student table by using groups.name?

i.e. I need query which select all students with the same group_id which is equivalent to name.

```<code>group_id 1 = 'ISI'
group_id 2 = 'IZI'
</code>```

And a query must delete exactly by name.

答:
There are different ways. A simple one, could be selecting the Id of the group and deleting from there. Example:

```<code>DECLARE
@name as nvarchar(20) = 'myName'

-- we display the data just for check
SELECT s.*, g.group_id
FROM students s ON g.group_id = s.group_id
WHERE g.name_group = @name

--we look the group id and delete the matches with students
DELETE
FROM students
WHERE group_id in (SELECT group_id FROM groups WHERE name_group = @name)
</code>```

PD: This basic approach could work on both: MySQL and MSSQL.

Body:
I have a table groups

group_id | name_group
1          ISI
2          IZI

And a table students

id | first_name | last_name | group_id
6    Bob          Surname1    1
17   John         Surname2    2

How can I delete all information from student table by using groups.name?

i.e. I need query which select all students with the same group_id which is equivalent to name.

group_id 1 = 'ISI'
group_id 2 = 'IZI'

And a query must delete exactly by name.

Body:
There are different ways. A simple one, could be selecting the Id of the group and deleting from there. Example:

DECLARE
@name as nvarchar(20) = 'myName'

-- we display the data just for check
SELECT s.*, g.group_id
FROM students s ON g.group_id = s.group_id
WHERE g.name_group = @name

--we look the group id and delete the matches with students
DELETE
FROM students
WHERE group_id in (SELECT group_id FROM groups WHERE name_group = @name)

PD: This basic approach could work on both: MySQL and MSSQL.


问:
R caret: Maximizing sensitivity for manually defined positive class for training (classification),
Short Version:

Is there a way to instruct caret to train a regression-model

Using a user defined label as "positive class label"?

Optimize the model for sensitivity during training (instead of ROC)?

Long Version:

I have a dataframe

```<code>> feature1 <-                 c(1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0)
> feature2 <-                 c(1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1)
> feature3 <-                 c(0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0)
> TARGET <- factor(make.names(c(1,0,1,1,0,0,1,0,1,1,1,0,1,0,0,0,1,0,1,1)))
> df <- data.frame(feature1, feature2, feature3, TARGET)
</code>```

And model training is implemented like

```<code>> ctrl <- trainControl(
+     method="repeatedcv",
+     repeats = 2)
>
> tuneGrid <- expand.grid(k = c(2,5,7))
>
> tune <- train(
+     TARGET ~ .,
+     metric = '???',
+     maximize = TRUE,
+     data = df,
+     method = "knn",
+     trControl = ctrl,
+     preProcess = c("center","scale"),
+     tuneGrid = tuneGrid
+ )
> sclasses <- predict(tune, newdata = df)
> df$PREDICTION <- make.names(factor(sclasses), unique = FALSE, allow_ = TRUE)
</code>```

I want to maximize the sensitivity = precision = A / ( A + C )

Where Event (in the image) should be in my case X1 = action taken. But caret uses X0 = no action taken.

I can set the positive class for my confusion matrix by using the positive argument like

```<code>> confusionMatrix(df$PREDICTION, df$TARGET, positive = "X1")
</code>```

But is there any way to set this while training (maximizing sensitivity)?

I already checked if there is another metric fitting my need, but I wasn't able to find one in the documentation. Do I have to implement my own summaryFunction for trainControl?

Thanks!

答:
As far as I know, there is no direct way to specify this in the training (I have been searching for this myself for a while now). However, I found a workaround: you can just reorder the levels of the target variable in the dataframe. As the training algorithm will take the first encountered level as the positive class by default, this solves your problem. Just add this simple line of code and that does the trick:</p>

```<code>TARGET <- factor(make.names(c(1,0,1,1,0,0,1,0,1,1,1,0,1,0,0,0,1,0,1,1)))
TARGET <- relevel(TARGET, "X1")
</code>```

Body:
Short Version:

Is there a way to instruct caret to train a regression-model

Using a user defined label as "positive class label"?

Optimize the model for sensitivity during training (instead of ROC)?

Long Version:

I have a dataframe

> feature1 <-                 c(1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0)
> feature2 <-                 c(1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1)
> feature3 <-                 c(0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0)
> TARGET <- factor(make.names(c(1,0,1,1,0,0,1,0,1,1,1,0,1,0,0,0,1,0,1,1)))
> df <- data.frame(feature1, feature2, feature3, TARGET)

And model training is implemented like

> ctrl <- trainControl(
+     method="repeatedcv",
+     repeats = 2)
>
> tuneGrid <- expand.grid(k = c(2,5,7))
>
> tune <- train(
+     TARGET ~ .,
+     metric = '???',
+     maximize = TRUE,
+     data = df,
+     method = "knn",
+     trControl = ctrl,
+     preProcess = c("center","scale"),
+     tuneGrid = tuneGrid
+ )
> sclasses <- predict(tune, newdata = df)
> df$PREDICTION <- make.names(factor(sclasses), unique = FALSE, allow_ = TRUE)

I want to maximize the sensitivity = precision = A / ( A + C )

Where Event (in the image) should be in my case X1 = action taken. But caret uses X0 = no action taken.

I can set the positive class for my confusion matrix by using the positive argument like

> confusionMatrix(df$PREDICTION, df$TARGET, positive = "X1")

But is there any way to set this while training (maximizing sensitivity)?

I already checked if there is another metric fitting my need, but I wasn't able to find one in the documentation. Do I have to implement my own summaryFunction for trainControl?

Thanks!

Body:
As far as I know, there is no direct way to specify this in the training (I have been searching for this myself for a while now). However, I found a workaround: you can just reorder the levels of the target variable in the dataframe. As the training algorithm will take the first encountered level as the positive class by default, this solves your problem. Just add this simple line of code and that does the trick:

TARGET <- factor(make.names(c(1,0,1,1,0,0,1,0,1,1,1,0,1,0,0,0,1,0,1,1)))
TARGET <- relevel(TARGET, "X1")


问:
Why does my Arquillian Drone functional test not work on GitLab CI?
A test which runs fine locally fails on gitlab.com's GitLab CI shared runners (the MCVE is at https://gitlab.com/krichter/gitlab-ci-file-creation, the log at https://gitlab.com/krichter/gitlab-ci-file-creation/-/jobs/40064276) because during the extraction of the Arquillian webdriver a directory cannot be created or is considered inexisting by Java (see details below):

```<code>Nov 13, 2017 7:31:32 AM org.glassfish.deployment.admin.DeployCommand execute
INFO: 664320b4-384a-414a-b0b4-546937428842 was successfully deployed in 7,496 milliseconds.
Nov 13, 2017 7:31:33 AM org.arquillian.spacelift.Spacelift$SpaceliftInstance <init>
INFO: Initialized Spacelift from defaults, workspace: /builds/krichter/gitlab-ci-file-creation, cache: /root/.spacelift/cache
Drone: downloading phantomjs-2.1.1-linux-x86_64.tar.bz2 from https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2 to /root/.arquillian/drone/phantomjs/2.1.1/phantomjs-2.1.1-linux-x86_64.tar.bz2
................
Nov 13, 2017 7:31:34 AM org.jboss.arquillian.core.impl.ObserverImpl resolveArguments
WARNING: Argument 1 for UpdateTestResultBeforeAfter.update is null. It won't be invoked.
Nov 13, 2017 7:31:34 AM org.jboss.arquillian.core.impl.ObserverImpl resolveArguments
WARNING: Argument 1 for UpdateTestResultBeforeAfter.update is null. It won't be invoked.
Nov 13, 2017 7:31:34 AM org.jboss.arquillian.core.impl.ObserverImpl resolveArguments
WARNING: Argument 1 for ReusableRemoteWebDriverExtension.destroyLastRemoteWebDriver is null. It won't be invoked.
Nov 13, 2017 7:31:35 AM com.sun.enterprise.admin.cli.embeddable.DeployerImpl undeploy
INFO: 664320b4-384a-414a-b0b4-546937428842 was successfully undeployed
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 19.022 sec <<< FAILURE! - in richtercloud.gitlab.ci.file.creation.GitLabCIIT
testSomething(richtercloud.gitlab.ci.file.creation.GitLabCIIT)  Time elapsed: 2.195 sec  <<< ERROR!
java.lang.IllegalStateException: Something bad happened when Drone was trying to download and prepare a binary. For more information see the cause.
    at org.jboss.arquillian.drone.webdriver.binary.handler.AbstractBinaryHandler.checkAndSetBinary(AbstractBinaryHandler.java:62)
    at org.jboss.arquillian.drone.webdriver.factory.PhantomJSDriverFactory.getCapabilities(PhantomJSDriverFactory.java:99)
    at org.jboss.arquillian.drone.webdriver.factory.PhantomJSDriverFactory.createInstance(PhantomJSDriverFactory.java:72)
    at org.jboss.arquillian.drone.webdriver.factory.PhantomJSDriverFactory.createInstance(PhantomJSDriverFactory.java:37)
    at org.jboss.arquillian.drone.webdriver.factory.WebDriverFactory.createInstance(WebDriverFactory.java:127)
    at org.jboss.arquillian.drone.webdriver.factory.WebDriverFactory.createInstance(WebDriverFactory.java:38)
    at org.jboss.arquillian.drone.impl.DroneConfigurator$1.createInstance(DroneConfigurator.java:112)
    at org.jboss.arquillian.drone.impl.CachingCallableImpl.call(CachingCallableImpl.java:44)
    at org.jboss.arquillian.core.impl.threading.ThreadedExecutorService$ContextualCallable.call(ThreadedExecutorService.java:89)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalStateException: The phantomJS binary is not present on the expected path target/drone/1c947d57fce2f21ce0b43fe2ed7cd361/phantomjs-2.1.1-linux-x86_64/bin/phantomjs
    at org.jboss.arquillian.drone.webdriver.binary.handler.PhantomJSDriverBinaryHandler.prepare(PhantomJSDriverBinaryHandler.java:56)
    at org.jboss.arquillian.drone.webdriver.binary.handler.AbstractBinaryHandler.downloadAndPrepare(AbstractBinaryHandler.java:226)
    at org.jboss.arquillian.drone.webdriver.binary.handler.AbstractBinaryHandler.downloadAndPrepare(AbstractBinaryHandler.java:208)
    at org.jboss.arquillian.drone.webdriver.binary.handler.AbstractBinaryHandler.downloadAndPrepare(AbstractBinaryHandler.java:175)
    at org.jboss.arquillian.drone.webdriver.binary.handler.AbstractBinaryHandler.checkAndSetBinary(AbstractBinaryHandler.java:60)
    ... 12 more

Nov 13, 2017 7:31:36 AM org.jboss.arquillian.core.impl.ObserverImpl resolveArguments
WARNING: Argument 1 for SeleniumServerExecutor.stopSeleniumServer is null. It won't be invoked.
Nov 13, 2017 7:31:36 AM org.glassfish.admin.mbeanserver.JMXStartupService shutdown
INFO: JMXStartupService and JMXConnectors have been shut down.
JdbcRuntimeExtension,  getAllSystemRAResourcesAndPools = [GlassFishConfigBean.org.glassfish.jdbc.config.JdbcResource, GlassFishConfigBean.org.glassfish.jdbc.config.JdbcResource, GlassFishConfigBean.org.glassfish.jdbc.config.JdbcConnectionPool, GlassFishConfigBean.org.glassfish.jdbc.config.JdbcConnectionPool, GlassFishConfigBean.org.glassfish.jdbc.config.JdbcConnectionPool, GlassFishConfigBean.org.glassfish.jdbc.config.JdbcResource]
Nov 13, 2017 7:31:36 AM com.sun.enterprise.v3.server.AppServerStartup stop
INFO: Shutdown procedure finished
</code>```

I'm using

```<code><dependencies>
    [...]
    <dependency>
        <groupId>org.jboss.shrinkwrap.descriptors</groupId>
        <artifactId>shrinkwrap-descriptors-api-javaee</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.arquillian.junit</groupId>
        <artifactId>arquillian-junit-container</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.jboss.shrinkwrap.resolver</groupId>
        <artifactId>shrinkwrap-resolver-depchain</artifactId>
        <type>pom</type>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.arquillian.graphene</groupId>
        <artifactId>graphene-webdriver</artifactId>
        <version>2.2.0</version>
        <type>pom</type>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>htmlunit-driver</artifactId>
    </dependency>
    <dependency>
        <groupId>net.sourceforge.htmlunit</groupId>
        <artifactId>htmlunit</artifactId>
        <version>2.24</version>
    </dependency>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
    </dependency>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-firefox-driver</artifactId>
    </dependency>
<!--        <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>20.0</version>
    </dependency>-->
    <dependency>
        <groupId>ru.yandex.qatools.ashot</groupId>
        <artifactId>ashot</artifactId>
        <version>1.5.3</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.2</version>
    </dependency>
</dependencies>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.jboss.arquillian</groupId>
            <artifactId>arquillian-bom</artifactId>
            <version>1.1.13.Final</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.arquillian.selenium</groupId>
            <artifactId>selenium-bom</artifactId>
            <version>3.7.0</version>
                <!-- - 3.3.1, 3.2.0 and 3.1.0 cause   required: java.util.function.Function<? super org.openqa.selenium.WebDriver,V>
                        found: org.openqa.selenium.support.ui.ExpectedCondition<org.openqa.selenium.WebElement>
                        reason: cannot infer type-variable(s) V
                        (argument mismatch; org.openqa.selenium.support.ui.ExpectedCondition<org.openqa.selenium.WebElement> cannot be converted to java.util.function.Function<? super org.openqa.selenium.WebDriver,V>)
                - 3.0.1 causes java.lang.IllegalAccessError: tried to access class org.openqa.selenium.os.ExecutableFinder from class org.openqa.selenium.phantomjs.PhantomJSDriverService when using phantomjs driver
                - 3.6.0 causes `Unrecognized platform: linux-unknown-64bit`
                    which one is supposed to work around using 3.5.3
                    <ref>https://github.com/SeleniumHQ/selenium/issues/4781</ref>-->
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.arquillian.extension</groupId>
            <artifactId>arquillian-drone-bom</artifactId>
            <version>2.1.0</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<profiles>
    <profile>
        <id>arquillian-glassfish-embedded</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <dependencies>
            <dependency>
                <groupId>org.jboss.arquillian.container</groupId>
                <artifactId>arquillian-glassfish-embedded-3.1</artifactId>
                <version>1.0.1</version>
            </dependency>
            <dependency>
                <groupId>fish.payara.extras</groupId>
                <artifactId>payara-embedded-all</artifactId>
                <version>4.1.2.174-SNAPSHOT</version>
                    <!-- - 4.1.2.173 causes `java.lang.NoClassDefFoundError: fish/payara/nucleus/healthcheck/stuck/StuckThreadsStore`
                            - 4.1.2.172 causes `Caused by: java.lang.ClassNotFoundException: fish.payara.notification.eventbus.EventbusMessage` -->
                <scope>test</scope>
            </dependency>
        </dependencies>
        <build>
            <testResources>
                <testResource>
                    <directory>src/test/resources</directory>
                </testResource>
                <testResource>
                    <directory>src/test/resources-glassfish-embedded</directory>
                </testResource>
            </testResources>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.12</version>
                    <configuration>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>
</code>```

and activated the profile.

I downloaded, extracted and investigated phantomjs-2.1.1-linux-x86_64.tar.bz2 from http://phantomjs.org/download.html and verified that phantomjs-2.1.1-linux-x86_64/examples/colorwheel.js exists inside it. Arquillian Drone Webdriver uses the MD5 sum 1c947d57fce2f21ce0b43fe2ed7cd361 as target directory which matches the one of the downloaded .tar.bz2.

The error is located in Arquillian Spacelift which is used by Arquillian Drone to extract the phantomjs driver and which you can't see from the stacktrace because Spacelift ignores failures of directory creation (see https://github.com/arquillian/arquillian-spacelift/pull/34 for details and a proposed fix which you can use by specifying

```<code>- git clone --branch file_utils_mkdir https://github.com/krichter722/arquillian-spacelift.git && cd arquillian-spacelift && mvn --batch-mode install && cd ..
</code>```

in the main job in .gitlab-ci.yml and changing the Spacelift dependency from 1.0.2 to 1.0.3-SNAPSHOT in the POM.

Changing the Spacelift source in the same way as described above and adding explicit directory creation and touch statements and even using Python from within Java to make sure the directory is created with

```<code>int pythonDebugReturncode = Runtime.getRuntime().exec(new String[] {"python3",
        "-c",
        String.format("'import os;os.makedirs(\"%s\");'",
                file.getParentFile().getAbsoluteFile().getAbsolutePath())}).waitFor();
System.out.println("pythonDebugReturncode: "+pythonDebugReturncode);
pythonDebugReturncode = Runtime.getRuntime().exec(new String[] {"python3",
        "-c",
        String.format("'from pathlib import Path;Path(\"%s\").touch();'",
                file.getAbsoluteFile().getAbsolutePath())}).waitFor();
System.out.println("pythonDebugReturncode: "+pythonDebugReturncode);
</code>```

result in 0s being printed as returncodes, but the directory use with the relative path to fail in Java code.

I tried the docker images ubuntu:xenial, ubuntu:trusty, ubuntu:artful, debian:sid and debian:buster. Afaik only Linux-based systems can be used as docker images. I don't have hope to get more insight by testing more images.

I experience

```<code>java.net.UnknownHostException: runner-3bd5f424-project-4630314-concurrent-0: runner-3bd5f424-project-4630314-concurrent-0: Temporary failure in name resolution
    at java.net.InetAddress.getLocalHost(InetAddress.java:1505)
</code>```

but I assume it's irrelevant for the issue since network filesystems aren't involved and name resolution during permission gaining isn't used since the build runs as root user.

答:
Arquillian Spacelift or Arquillian Drone Webdriver fail to resolve the working directory which isn't changed if Maven is started in an aggregator project root and the Maven basedir consistently. I reported this at https://issues.jboss.org/browse/ARQ-2154.

This means that one has to split the normal run of mvn install into on run doing the compilation with -DskipTests=true -DskipITs=true and then change the directory to the submodule directory and run mvn verify.

Body:
A test which runs fine locally fails on gitlab.com's GitLab CI shared runners (the MCVE is at https://gitlab.com/krichter/gitlab-ci-file-creation, the log at https://gitlab.com/krichter/gitlab-ci-file-creation/-/jobs/40064276) because during the extraction of the Arquillian webdriver a directory cannot be created or is considered inexisting by Java (see details below):

Nov 13, 2017 7:31:32 AM org.glassfish.deployment.admin.DeployCommand execute
INFO: 664320b4-384a-414a-b0b4-546937428842 was successfully deployed in 7,496 milliseconds.
Nov 13, 2017 7:31:33 AM org.arquillian.spacelift.Spacelift$SpaceliftInstance <init>
INFO: Initialized Spacelift from defaults, workspace: /builds/krichter/gitlab-ci-file-creation, cache: /root/.spacelift/cache
Drone: downloading phantomjs-2.1.1-linux-x86_64.tar.bz2 from https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2 to /root/.arquillian/drone/phantomjs/2.1.1/phantomjs-2.1.1-linux-x86_64.tar.bz2
................
Nov 13, 2017 7:31:34 AM org.jboss.arquillian.core.impl.ObserverImpl resolveArguments
WARNING: Argument 1 for UpdateTestResultBeforeAfter.update is null. It won't be invoked.
Nov 13, 2017 7:31:34 AM org.jboss.arquillian.core.impl.ObserverImpl resolveArguments
WARNING: Argument 1 for UpdateTestResultBeforeAfter.update is null. It won't be invoked.
Nov 13, 2017 7:31:34 AM org.jboss.arquillian.core.impl.ObserverImpl resolveArguments
WARNING: Argument 1 for ReusableRemoteWebDriverExtension.destroyLastRemoteWebDriver is null. It won't be invoked.
Nov 13, 2017 7:31:35 AM com.sun.enterprise.admin.cli.embeddable.DeployerImpl undeploy
INFO: 664320b4-384a-414a-b0b4-546937428842 was successfully undeployed
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 19.022 sec <<< FAILURE! - in richtercloud.gitlab.ci.file.creation.GitLabCIIT
testSomething(richtercloud.gitlab.ci.file.creation.GitLabCIIT)  Time elapsed: 2.195 sec  <<< ERROR!
java.lang.IllegalStateException: Something bad happened when Drone was trying to download and prepare a binary. For more information see the cause.
    at org.jboss.arquillian.drone.webdriver.binary.handler.AbstractBinaryHandler.checkAndSetBinary(AbstractBinaryHandler.java:62)
    at org.jboss.arquillian.drone.webdriver.factory.PhantomJSDriverFactory.getCapabilities(PhantomJSDriverFactory.java:99)
    at org.jboss.arquillian.drone.webdriver.factory.PhantomJSDriverFactory.createInstance(PhantomJSDriverFactory.java:72)
    at org.jboss.arquillian.drone.webdriver.factory.PhantomJSDriverFactory.createInstance(PhantomJSDriverFactory.java:37)
    at org.jboss.arquillian.drone.webdriver.factory.WebDriverFactory.createInstance(WebDriverFactory.java:127)
    at org.jboss.arquillian.drone.webdriver.factory.WebDriverFactory.createInstance(WebDriverFactory.java:38)
    at org.jboss.arquillian.drone.impl.DroneConfigurator$1.createInstance(DroneConfigurator.java:112)
    at org.jboss.arquillian.drone.impl.CachingCallableImpl.call(CachingCallableImpl.java:44)
    at org.jboss.arquillian.core.impl.threading.ThreadedExecutorService$ContextualCallable.call(ThreadedExecutorService.java:89)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalStateException: The phantomJS binary is not present on the expected path target/drone/1c947d57fce2f21ce0b43fe2ed7cd361/phantomjs-2.1.1-linux-x86_64/bin/phantomjs
    at org.jboss.arquillian.drone.webdriver.binary.handler.PhantomJSDriverBinaryHandler.prepare(PhantomJSDriverBinaryHandler.java:56)
    at org.jboss.arquillian.drone.webdriver.binary.handler.AbstractBinaryHandler.downloadAndPrepare(AbstractBinaryHandler.java:226)
    at org.jboss.arquillian.drone.webdriver.binary.handler.AbstractBinaryHandler.downloadAndPrepare(AbstractBinaryHandler.java:208)
    at org.jboss.arquillian.drone.webdriver.binary.handler.AbstractBinaryHandler.downloadAndPrepare(AbstractBinaryHandler.java:175)
    at org.jboss.arquillian.drone.webdriver.binary.handler.AbstractBinaryHandler.checkAndSetBinary(AbstractBinaryHandler.java:60)
    ... 12 more

Nov 13, 2017 7:31:36 AM org.jboss.arquillian.core.impl.ObserverImpl resolveArguments
WARNING: Argument 1 for SeleniumServerExecutor.stopSeleniumServer is null. It won't be invoked.
Nov 13, 2017 7:31:36 AM org.glassfish.admin.mbeanserver.JMXStartupService shutdown
INFO: JMXStartupService and JMXConnectors have been shut down.
JdbcRuntimeExtension,  getAllSystemRAResourcesAndPools = [GlassFishConfigBean.org.glassfish.jdbc.config.JdbcResource, GlassFishConfigBean.org.glassfish.jdbc.config.JdbcResource, GlassFishConfigBean.org.glassfish.jdbc.config.JdbcConnectionPool, GlassFishConfigBean.org.glassfish.jdbc.config.JdbcConnectionPool, GlassFishConfigBean.org.glassfish.jdbc.config.JdbcConnectionPool, GlassFishConfigBean.org.glassfish.jdbc.config.JdbcResource]
Nov 13, 2017 7:31:36 AM com.sun.enterprise.v3.server.AppServerStartup stop
INFO: Shutdown procedure finished

I'm using

<dependencies>
    [...]
    <dependency>
        <groupId>org.jboss.shrinkwrap.descriptors</groupId>
        <artifactId>shrinkwrap-descriptors-api-javaee</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.arquillian.junit</groupId>
        <artifactId>arquillian-junit-container</artifactId>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.jboss.shrinkwrap.resolver</groupId>
        <artifactId>shrinkwrap-resolver-depchain</artifactId>
        <type>pom</type>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.jboss.arquillian.graphene</groupId>
        <artifactId>graphene-webdriver</artifactId>
        <version>2.2.0</version>
        <type>pom</type>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>htmlunit-driver</artifactId>
    </dependency>
    <dependency>
        <groupId>net.sourceforge.htmlunit</groupId>
        <artifactId>htmlunit</artifactId>
        <version>2.24</version>
    </dependency>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
    </dependency>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-firefox-driver</artifactId>
    </dependency>

    <dependency>
        <groupId>ru.yandex.qatools.ashot</groupId>
        <artifactId>ashot</artifactId>
        <version>1.5.3</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.2</version>
    </dependency>
</dependencies>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.jboss.arquillian</groupId>
            <artifactId>arquillian-bom</artifactId>
            <version>1.1.13.Final</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.arquillian.selenium</groupId>
            <artifactId>selenium-bom</artifactId>
            <version>3.7.0</version>

            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.jboss.arquillian.extension</groupId>
            <artifactId>arquillian-drone-bom</artifactId>
            <version>2.1.0</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<profiles>
    <profile>
        <id>arquillian-glassfish-embedded</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <dependencies>
            <dependency>
                <groupId>org.jboss.arquillian.container</groupId>
                <artifactId>arquillian-glassfish-embedded-3.1</artifactId>
                <version>1.0.1</version>
            </dependency>
            <dependency>
                <groupId>fish.payara.extras</groupId>
                <artifactId>payara-embedded-all</artifactId>
                <version>4.1.2.174-SNAPSHOT</version>

                <scope>test</scope>
            </dependency>
        </dependencies>
        <build>
            <testResources>
                <testResource>
                    <directory>src/test/resources</directory>
                </testResource>
                <testResource>
                    <directory>src/test/resources-glassfish-embedded</directory>
                </testResource>
            </testResources>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.12</version>
                    <configuration>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>

and activated the profile.

I downloaded, extracted and investigated phantomjs-2.1.1-linux-x86_64.tar.bz2 from http://phantomjs.org/download.html and verified that phantomjs-2.1.1-linux-x86_64/examples/colorwheel.js exists inside it. Arquillian Drone Webdriver uses the MD5 sum 1c947d57fce2f21ce0b43fe2ed7cd361 as target directory which matches the one of the downloaded .tar.bz2.

The error is located in Arquillian Spacelift which is used by Arquillian Drone to extract the phantomjs driver and which you can't see from the stacktrace because Spacelift ignores failures of directory creation (see https://github.com/arquillian/arquillian-spacelift/pull/34 for details and a proposed fix which you can use by specifying

- git clone --branch file_utils_mkdir https://github.com/krichter722/arquillian-spacelift.git && cd arquillian-spacelift && mvn --batch-mode install && cd ..

in the main job in .gitlab-ci.yml and changing the Spacelift dependency from 1.0.2 to 1.0.3-SNAPSHOT in the POM.

Changing the Spacelift source in the same way as described above and adding explicit directory creation and touch statements and even using Python from within Java to make sure the directory is created with

int pythonDebugReturncode = Runtime.getRuntime().exec(new String[] {"python3",
        "-c",
        String.format("'import os;os.makedirs(\"%s\");'",
                file.getParentFile().getAbsoluteFile().getAbsolutePath())}).waitFor();
System.out.println("pythonDebugReturncode: "+pythonDebugReturncode);
pythonDebugReturncode = Runtime.getRuntime().exec(new String[] {"python3",
        "-c",
        String.format("'from pathlib import Path;Path(\"%s\").touch();'",
                file.getAbsoluteFile().getAbsolutePath())}).waitFor();
System.out.println("pythonDebugReturncode: "+pythonDebugReturncode);

result in 0s being printed as returncodes, but the directory use with the relative path to fail in Java code.

I tried the docker images ubuntu:xenial, ubuntu:trusty, ubuntu:artful, debian:sid and debian:buster. Afaik only Linux-based systems can be used as docker images. I don't have hope to get more insight by testing more images.

I experience

java.net.UnknownHostException: runner-3bd5f424-project-4630314-concurrent-0: runner-3bd5f424-project-4630314-concurrent-0: Temporary failure in name resolution
    at java.net.InetAddress.getLocalHost(InetAddress.java:1505)

but I assume it's irrelevant for the issue since network filesystems aren't involved and name resolution during permission gaining isn't used since the build runs as root user.


问:
How can I write the docker -it option in Dockerfile?
I want create a Dockerfile for CMD line:

```<code>docker run --rm -it -v $(pwd):/data -p 8080:80 klokantech/openmaptiles-server
</code>```

How I do -it in Dockerfile?

答:
You can pass a string instead of an array in CMD Dockerfile instruction.
So you can type:

```<code>CMD "docker run --rm -it -v $(pwd):/data -p 8080:80 klokantech/openmaptiles-server"
</code>```

Otherwise "-it" should be an element of CMD array.

Body:
I want create a Dockerfile for CMD line:

docker run --rm -it -v $(pwd):/data -p 8080:80 klokantech/openmaptiles-server

How I do -it in Dockerfile?

Body:
You can pass a string instead of an array in CMD Dockerfile instruction.
So you can type:

CMD "docker run --rm -it -v $(pwd):/data -p 8080:80 klokantech/openmaptiles-server"

Otherwise "-it" should be an element of CMD array.


问:
How to find the negative weight between two adjacent nodes in python
Hi i have a big text file with format like this:

```<code>1  3  1
2  3  -1
5  7  1
6  1  -1
3  2  -1
</code>```

the first column is the starting node, the second column the ending node and the third column shows the sign between two nodes. So i have positive and negative signs.
Im reading the graph with the code below:

```<code>G = nx.Graph()
G = nx.read_edgelist('network.txt', delimiter='\t', nodetype=int, data=(('weight', int),))
print(nx.info(G))
</code>```

I also found a function to find the neighbors of a specific node:

```<code>list1 = list(G.neigbors(1))
</code>```

So i have a list with the adjacency nodes of node 1. How can a find the sign between the node 1 and each adjacency node? (For example that edge between 1-3 has sign 1, the edge 1-5 has sign -1 etc)

答:
An example for node 1:

```<code>n_from = 1
for n_to in G.neighbors(n_from):
    sign = G[n_from][n_to]['weight']

    print('edge from {} to {} has sign {}'.format(
        n_from, n_to, sign))
</code>```

which prints, for the example input you gave:

edge from 1 to 3 has sign 1

  edge from 1 to 6 has sign -1

A similar approach, treating G[n_from] as a dict:

```<code>n_from = 1
for n_to, e_data in G[n_from].items():
    sign = e_data['weight']
    # then print
</code>```

You can alternatively use Graph.get_edge_data, as such:

```<code>e_data = G.get_edge_data(n_from, n_to)
sign = e_data.get('weight')
</code>```

Body:
Hi i have a big text file with format like this:

1  3  1
2  3  -1
5  7  1
6  1  -1
3  2  -1

the first column is the starting node, the second column the ending node and the third column shows the sign between two nodes. So i have positive and negative signs.
Im reading the graph with the code below:

G = nx.Graph()
G = nx.read_edgelist('network.txt', delimiter='\t', nodetype=int, data=(('weight', int),))
print(nx.info(G))

I also found a function to find the neighbors of a specific node:

list1 = list(G.neigbors(1))

So i have a list with the adjacency nodes of node 1. How can a find the sign between the node 1 and each adjacency node? (For example that edge between 1-3 has sign 1, the edge 1-5 has sign -1 etc)

Body:
An example for node 1:

n_from = 1
for n_to in G.neighbors(n_from):
    sign = G[n_from][n_to]['weight']

    print('edge from {} to {} has sign {}'.format(
        n_from, n_to, sign))

which prints, for the example input you gave:

edge from 1 to 3 has sign 1

  edge from 1 to 6 has sign -1

A similar approach, treating G[n_from] as a dict:

n_from = 1
for n_to, e_data in G[n_from].items():
    sign = e_data['weight']
    # then print

You can alternatively use Graph.get_edge_data, as such:

e_data = G.get_edge_data(n_from, n_to)
sign = e_data.get('weight')


问:
How to create dynamic filter in AngularJS?
```<code>data = {key:0, Name:"Arun", key:1, Name:"Ajay", key:3, Name:"Ashok"}

function dynamicfilter(data, fieldName, filtervalue){
    $filter('filter')(data, { fieldName: filtervalue });
}
</code>```

How to do the dynamic filter in AngularJS. I tried like this it's not working.

But If I give field name static like

```<code> function dynamicfilter(data, filtervalue){
        $filter('filter')(data, { Key: filtervalue });
    }
</code>```

It's working. May I know how set dynamic field filter inside controller in AngularJS?

答:
you can use somthing like this

<input type="text" [(ngModel)]="search1" value="" class = "form-control" id = "search" />

<ng-container *ngFor="let app1 of apps">

         {{app1.name}}
          {{app1.login}}

    </ng-container>```

Body:
data = {key:0, Name:"Arun", key:1, Name:"Ajay", key:3, Name:"Ashok"}

function dynamicfilter(data, fieldName, filtervalue){
    $filter('filter')(data, { fieldName: filtervalue });
}

How to do the dynamic filter in AngularJS. I tried like this it's not working.

But If I give field name static like

 function dynamicfilter(data, filtervalue){
        $filter('filter')(data, { Key: filtervalue });
    }

It's working. May I know how set dynamic field filter inside controller in AngularJS?

Body:
you can use somthing like this

<input type="text" [(ngModel)]="search1" value="" class = "form-control" id = "search" />

<ng-container *ngFor="let app1 of apps">
      <tr  *ngIf="!search1 || app1.name.includes(search1)">
         <td>{{app1.name}}<td>
          <td>{{app1.login}}<td>
      </tr>
    </ng-container>


问:
Tabular Model in Azure Portal Won't Open in Visual Studios
I have a Tabular model in Azure Analysis Services that I created by importing a .pbix. It loaded the model perfectly, but when I try to open the model in Visual Studio nothing happens. When I click on Open in Excel it creates a .odc file and when I click on Open in Power BI it creates a .pbix file. You can see below the options:

Screenshot:

I would like to open it in Visual Studios. Has anyone else ran into this problem or does anyone else have a solution?

Any help would be appreciated.

Thanks!

答:
Well, it looks like the Open in Visual Studio button is now working. The next day, it now downloads a .zip file that contains a .SMPROJ file and a .BIM file. Not sure why it wasn't working yesterday, maybe the model needs some time after it is created to be able to be loaded into Visual Studios. If anybody knows why, then post, to help anyone else in the future.

Thanks


问:
Find out what thread opened fd
I've been searching for a solution on Linux to find out what thread first aquired a fd but no luck for now.

```<code>/proc/pid/task/
</code>```

shows the fd to be available to each thread, which makes sense since descriptors are available troughout the whole process space.

```<code>lsof
</code>```

is of course not of much help either for this usecase.

The program is very complex, and strace or gdb won't help either, there are tons of closed source libraries  used. File path is known but does not help since I don't have access to the code in the libaries. I suspect the fd leak is due to some race condition that occurrs very very rarely and I need to trace the thread that did opened the file.

One solution that would be  easy to implement would be for me to add a log in the kernel file open handler or in the c library, but for good reasons I'm not able to alter nor the kernel neither the standard library.

Some suggestions?

答:
If you have kernel symbols available use SystemTap:

sudo stap -e 'probe syscall.open.return { \
               printf("tid=%d, fd=%d\n", tid(), $return) }'

Title: Find out what thread opened fd

Body:
I've been searching for a solution on Linux to find out what thread first aquired a fd but no luck for now.

/proc/pid/task/

shows the fd to be available to each thread, which makes sense since descriptors are available troughout the whole process space.

lsof

is of course not of much help either for this usecase.

The program is very complex, and strace or gdb won't help either, there are tons of closed source libraries  used. File path is known but does not help since I don't have access to the code in the libaries. I suspect the fd leak is due to some race condition that occurrs very very rarely and I need to trace the thread that did opened the file.

One solution that would be  easy to implement would be for me to add a log in the kernel file open handler or in the c library, but for good reasons I'm not able to alter nor the kernel neither the standard library.

Some suggestions?


答:
I think you miss .json() to get the body of the response:

```<code>this.ValidationService.validate().subscribe(result => {
  console.log('data returned from api', result.json());
});
</code>```

If it's that I think it's better to move .json() to your service to don't have many .json() everywhere in your code:

```<code>validate() {
  return this.http.get('api/validate', data).map(res => res.json());
}
</code>```

Title: Strange behavior with Observable results in Angular/Typescript

Body:
I think you miss .json() to get the body of the response:

this.ValidationService.validate().subscribe(result => {
  console.log('data returned from api', result.json());
});

If it's that I think it's better to move .json() to your service to don't have many .json() everywhere in your code:

validate() {
  return this.http.get('api/validate', data).map(res => res.json());
}


问:
Drawing on a transparent image using Java SWT
How do I create an in-memory fully transparent SWT image and draw a black line on it with antialias enabled?

I expect the result to include only black color and alpha values ranging from 0 to 255 due to antialias...

I googled and tried everything that I could... is this possible at all?

答:
To scale with transparency, I've found that I have to manually set the alpha byte array as shown below.  So the alpha ends up with nearest-neighbor anti aliasing.</p>

```<code>public static Image scaleImage(Device device, Image orig, int scaledWidth, int scaledHeight) {
    Rectangle origBounds = orig.getBounds();
    if (origBounds.width == scaledWidth && origBounds.height == scaledHeight) {
        return orig;
    }

    ImageData origData = orig.getImageData();
    ImageData imData = new ImageData(scaledWidth, scaledHeight, origData.depth, origData.palette);
    if (origData.alphaData != null) {
        imData.alphaData = new byte[imData.width * imData.height];
        for (int row = 0; row < imData.height; row++) {
            for (int col = 0; col < imData.width; col++) {
                int origRow = row * origData.height / imData.height;
                int origCol = col * origData.width / imData.width;
                byte origAlpha = origData.alphaData[origRow * origData.width + origCol];
                imData.alphaData[row * imData.width + col] = origAlpha;
            }
        }
    }
    final Image scaled = new Image(device, imData);
    GC gc = new GC(scaled);
    gc.setAntialias(SWT.ON);
    gc.setInterpolation(SWT.HIGH);
    gc.setBackground(device.getSystemColor(SWT.COLOR_WHITE));
    gc.fillRectangle(0, 0, scaledWidth, scaledHeight);
    gc.drawImage(orig, 0, 0, origBounds.width, origBounds.height, 0, 0, scaledWidth, scaledHeight);
    gc.dispose();
    return scaled;
}
</code>```

Body:
To scale with transparency, I've found that I have to manually set the alpha byte array as shown below.  So the alpha ends up with nearest-neighbor anti aliasing.

public static Image scaleImage(Device device, Image orig, int scaledWidth, int scaledHeight) {
    Rectangle origBounds = orig.getBounds();
    if (origBounds.width == scaledWidth && origBounds.height == scaledHeight) {
        return orig;
    }

    ImageData origData = orig.getImageData();
    ImageData imData = new ImageData(scaledWidth, scaledHeight, origData.depth, origData.palette);
    if (origData.alphaData != null) {
        imData.alphaData = new byte[imData.width * imData.height];
        for (int row = 0; row < imData.height; row++) {
            for (int col = 0; col < imData.width; col++) {
                int origRow = row * origData.height / imData.height;
                int origCol = col * origData.width / imData.width;
                byte origAlpha = origData.alphaData[origRow * origData.width + origCol];
                imData.alphaData[row * imData.width + col] = origAlpha;
            }
        }
    }
    final Image scaled = new Image(device, imData);
    GC gc = new GC(scaled);
    gc.setAntialias(SWT.ON);
    gc.setInterpolation(SWT.HIGH);
    gc.setBackground(device.getSystemColor(SWT.COLOR_WHITE));
    gc.fillRectangle(0, 0, scaledWidth, scaledHeight);
    gc.drawImage(orig, 0, 0, origBounds.width, origBounds.height, 0, 0, scaledWidth, scaledHeight);
    gc.dispose();
    return scaled;
}


问:
Are Swift variables atomic?
In Objective-C you have a distinction between atomic and nonatomic properties:

```<code>@property (nonatomic, strong) NSObject *nonatomicObject;
@property (atomic, strong) NSObject *atomicObject;
</code>```

From my understanding you can read and write properties defined as atomic from multiple threads safely, while writing and accessing nonatomic properties or ivars from multiple threads at the same time can result in undefined behavior, including bad access errors.

So if you have a variable like this in Swift:

```<code>var object: NSObject
</code>```

Can I read and write to this variable in parallel safely? (Without considering the actual meaning of doing this).

答:
Details

Xcode 9.1, Swift 4

Xcode 10.2.1 (10E1001), Swift 5

Links

apple.developer.com Dispatch

Grand Central Dispatch (GCD) and
Dispatch Queues in Swift 3

Creating Thread-Safe Arrays in
Swift

Mutexes and closure capture in Swift

Implemented types

QueueSafeValue - a universal wrapper that provides safe multi-threaded access to values

AtomicArray

AtomicInteger

AtomicValue

Main Idea

```<code>class Example {

    private lazy var semaphore = DispatchSemaphore(value: 1)

    func executeThreadSafeFunc1() {
        // Lock access. Only first thread can execute code below.
        // Other threads will wait until semaphore.signal() will execute
        semaphore.wait()
        // your code
        semaphore.signal()         // Unlock access
    }

    func executeThreadSafeFunc2() {
        // Lock access. Only first thread can execute code below.
        // Other threads will wait until semaphore.signal() will execute
        semaphore.wait()
        DispatchQueue.global(qos: .background).async {
            // your code
            self.semaphore.signal()         // Unlock access
        }
    }
}
</code>```

Sample of atomic access

```<code>class Atomic {

    let dispatchGroup = DispatchGroup()
    private var variable = 0

    // Usage of semaphores

    func semaphoreSample() {

        // value: 1 - number of threads that have simultaneous access to the variable
        let atomicSemaphore = DispatchSemaphore(value: 1)
        variable = 0

        runInSeveralQueues { dispatchQueue  in
            // Only (value) queqes can run operations betwen atomicSemaphore.wait() and atomicSemaphore.signal()
            // Others queues await their turn
            atomicSemaphore.wait()            // Lock access until atomicSemaphore.signal()
            self.variable += 1
            print("\(dispatchQueue), value: \(self.variable)")
            atomicSemaphore.signal()          // Unlock access
        }

        notifyWhenDone {
            atomicSemaphore.wait()           // Lock access until atomicSemaphore.signal()
            print("variable = \(self.variable)")
            atomicSemaphore.signal()         // Unlock access
        }
    }

    // Usage of sync of DispatchQueue

    func dispatchQueueSync() {
        let atomicQueue = DispatchQueue(label: "dispatchQueueSync")
        variable = 0

        runInSeveralQueues { dispatchQueue  in

            // Only queqe can run this closure (atomicQueue.sync {...})
            // Others queues await their turn
            atomicQueue.sync {
                self.variable += 1
                print("\(dispatchQueue), value: \(self.variable)")
            }
        }

        notifyWhenDone {
            atomicQueue.sync {
                print("variable = \(self.variable)")
            }
        }
    }

    // Usage of objc_sync_enter/objc_sync_exit

    func objcSync() {
        variable = 0

        runInSeveralQueues { dispatchQueue  in

            // Only one queqe can run operations betwen objc_sync_enter(self) and objc_sync_exit(self)
            // Others queues await their turn
            objc_sync_enter(self)                   // Lock access until objc_sync_exit(self).
            self.variable += 1
            print("\(dispatchQueue), value: \(self.variable)")
            objc_sync_exit(self)                    // Unlock access
        }

        notifyWhenDone {
            objc_sync_enter(self)                   // Lock access until objc_sync_exit(self)
            print("variable = \(self.variable)")
            objc_sync_exit(self)                    // Unlock access
        }
    }
}

// Helpers

extension Atomic {

    fileprivate func notifyWhenDone(closure: @escaping ()->()) {
        dispatchGroup.notify(queue: .global(qos: .utility)) {
            closure()
            print("All work done")
        }
    }

    fileprivate func runInSeveralQueues(closure: @escaping (DispatchQueue)->()) {

        async(dispatch: .main, closure: closure)
        async(dispatch: .global(qos: .userInitiated), closure: closure)
        async(dispatch: .global(qos: .utility), closure: closure)
        async(dispatch: .global(qos: .default), closure: closure)
        async(dispatch: .global(qos: .userInteractive), closure: closure)
    }

    private func async(dispatch: DispatchQueue, closure: @escaping (DispatchQueue)->()) {

        for _ in 0 ..< 100 {
            dispatchGroup.enter()
            dispatch.async {
                let usec = Int(arc4random()) % 100_000
                usleep(useconds_t(usec))
                closure(dispatch)
                self.dispatchGroup.leave()
            }
        }
    }
}
</code>```

Usage

```<code>Atomic().semaphoreSample()
//Atomic().dispatchQueueSync()
//Atomic().objcSync()
</code>```

Result

Title: Are Swift variables atomic?

Body:
In Objective-C you have a distinction between atomic and nonatomic properties:

@property (nonatomic, strong) NSObject *nonatomicObject;
@property (atomic, strong) NSObject *atomicObject;

From my understanding you can read and write properties defined as atomic from multiple threads safely, while writing and accessing nonatomic properties or ivars from multiple threads at the same time can result in undefined behavior, including bad access errors.

So if you have a variable like this in Swift:

var object: NSObject

Can I read and write to this variable in parallel safely? (Without considering the actual meaning of doing this).

Body:
Details

Xcode 9.1, Swift 4

Xcode 10.2.1 (10E1001), Swift 5

Links

apple.developer.com Dispatch

Grand Central Dispatch (GCD) and
Dispatch Queues in Swift 3

Creating Thread-Safe Arrays in
Swift

Mutexes and closure capture in Swift

Implemented types

QueueSafeValue - a universal wrapper that provides safe multi-threaded access to values

AtomicArray

AtomicInteger

AtomicValue

Main Idea

class Example {

    private lazy var semaphore = DispatchSemaphore(value: 1)

    func executeThreadSafeFunc1() {
        // Lock access. Only first thread can execute code below.
        // Other threads will wait until semaphore.signal() will execute
        semaphore.wait()
        // your code
        semaphore.signal()         // Unlock access
    }

    func executeThreadSafeFunc2() {
        // Lock access. Only first thread can execute code below.
        // Other threads will wait until semaphore.signal() will execute
        semaphore.wait()
        DispatchQueue.global(qos: .background).async {
            // your code
            self.semaphore.signal()         // Unlock access
        }
    }
}

Sample of atomic access

class Atomic {

    let dispatchGroup = DispatchGroup()
    private var variable = 0

    // Usage of semaphores

    func semaphoreSample() {

        // value: 1 - number of threads that have simultaneous access to the variable
        let atomicSemaphore = DispatchSemaphore(value: 1)
        variable = 0

        runInSeveralQueues { dispatchQueue  in
            // Only (value) queqes can run operations betwen atomicSemaphore.wait() and atomicSemaphore.signal()
            // Others queues await their turn
            atomicSemaphore.wait()            // Lock access until atomicSemaphore.signal()
            self.variable += 1
            print("\(dispatchQueue), value: \(self.variable)")
            atomicSemaphore.signal()          // Unlock access
        }

        notifyWhenDone {
            atomicSemaphore.wait()           // Lock access until atomicSemaphore.signal()
            print("variable = \(self.variable)")
            atomicSemaphore.signal()         // Unlock access
        }
    }

    // Usage of sync of DispatchQueue

    func dispatchQueueSync() {
        let atomicQueue = DispatchQueue(label: "dispatchQueueSync")
        variable = 0

        runInSeveralQueues { dispatchQueue  in

            // Only queqe can run this closure (atomicQueue.sync {...})
            // Others queues await their turn
            atomicQueue.sync {
                self.variable += 1
                print("\(dispatchQueue), value: \(self.variable)")
            }
        }

        notifyWhenDone {
            atomicQueue.sync {
                print("variable = \(self.variable)")
            }
        }
    }

    // Usage of objc_sync_enter/objc_sync_exit

    func objcSync() {
        variable = 0

        runInSeveralQueues { dispatchQueue  in

            // Only one queqe can run operations betwen objc_sync_enter(self) and objc_sync_exit(self)
            // Others queues await their turn
            objc_sync_enter(self)                   // Lock access until objc_sync_exit(self).
            self.variable += 1
            print("\(dispatchQueue), value: \(self.variable)")
            objc_sync_exit(self)                    // Unlock access
        }

        notifyWhenDone {
            objc_sync_enter(self)                   // Lock access until objc_sync_exit(self)
            print("variable = \(self.variable)")
            objc_sync_exit(self)                    // Unlock access
        }
    }
}

// Helpers

extension Atomic {

    fileprivate func notifyWhenDone(closure: @escaping ()->()) {
        dispatchGroup.notify(queue: .global(qos: .utility)) {
            closure()
            print("All work done")
        }
    }

    fileprivate func runInSeveralQueues(closure: @escaping (DispatchQueue)->()) {

        async(dispatch: .main, closure: closure)
        async(dispatch: .global(qos: .userInitiated), closure: closure)
        async(dispatch: .global(qos: .utility), closure: closure)
        async(dispatch: .global(qos: .default), closure: closure)
        async(dispatch: .global(qos: .userInteractive), closure: closure)
    }

    private func async(dispatch: DispatchQueue, closure: @escaping (DispatchQueue)->()) {

        for _ in 0 ..< 100 {
            dispatchGroup.enter()
            dispatch.async {
                let usec = Int(arc4random()) % 100_000
                usleep(useconds_t(usec))
                closure(dispatch)
                self.dispatchGroup.leave()
            }
        }
    }
}

Usage

Atomic().semaphoreSample()
//Atomic().dispatchQueueSync()
//Atomic().objcSync()

Result


问:
Is this a good practice for EF Database First?
Me and my colleague had recently a discussion on good practices in EF.
So i show one of mine.

He said it is a little bit muddler.

My practice consist in modify the autogenerated class in a specific way.
This is my starting model:

```<code>namespace PCServer.Data
{
    using System;
    using System.Collections.Generic;

    public partial class Post: IEntity
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Message { get; set; }
        public DateTime Date { get; set; }

        public virtual Post ParentPost { get; set; }
        public virtual AspNetUser Author { get; set; }
    }
}
</code>```

I like to extend it in this way:

```<code>public partial class Post
    {
        //This class "do" something, like adding a post or deleting a post
        public static class Do
        {
            public static void AddPost(ref ApplicationDbContext context, string postMessage)
            {
                //Create a post
                Post p = new Post();
                p.Title = "This is an example!";
                p.message = postMessage;
                p.Date = DateTime.UtcNow;

                //Adding to context
                BaseService.Add(post, out context);
            }

            public static void DeletePost(ref ApplicationDbContext context, int postId)
            {
                PostRepository postRepo = new PostRepository(context);

                postRepo.GetById(postId);

                //Removing from context
                BaseService.Remove(post, out context);
            }
        }

        //This class "Get" something, like all posts
        public static class Get
        {
            public static void GetPosts()
            {
                using(ApplicationDbContext context = new ApplicationDbContext())
                {
                    PostRepository postRepo = new PostRepository(context);
                    return postRepo.GetAllPosts();
                }
            }
        }

        //This class "Set" something, like title of the post or the post itself maybe
        public static class Set
        {
            public static void Title(ref ApplicationDbContext context, int postId, string title)
            {
                PostRepository postRepo = new PostRepository(context);
                Post post = postRepo.GetById(postId);
                post.Title = title;

                BaseService.Update(post, out context);
            }

            public static void ChangePost(ref ApplicationDbContext context, int postId, Post post)
            {
                PostRepository postRepo = new PostRepository(context);
                Post dbPost = postRepo.GetById(postId);
                dbPost = post;

                BaseService.Update(dbPost, out context);
            }
        }
    }
</code>```

So, when i must to do something with an Entity, i can (for example only):

```<code>ApplicationDbContext c = new ApplicationDbContext();

Post.Do.AddPost(ref c,"Hi!");
IEnumerable<Post> posts = Post.Get.GetPosts();

Post.Set.Title(ref c,100,"Changing title!");
</code>```

And after all:

```<code>await BaseService.CommitAsync<Post>(c);
</code>```

SO.
What do you think? Would you use it? Why?

Thank you and sorry for long post.

答:
One of the advantages of any design pattern is that of comprehensibility to others. Me: How are you designing your Web Services? You: We're using the repository pattern. Me: Ok, I understand that.

Whilst this is by no means a comprehensive answer, it goes a long way to understanding where to look for things and where things need changing when you're asked to make an update.

What you have is a design pattern that you like to use, but you should ask yourself whether it is easily comprehensible by others.

For example, you have a class named "Do". As a name, this gives no indication whatsoever as to what the class is for. Your comment indicates that it "does something", but is anyone else going to intuitively understand what goes in there? Adding and Deleting are obviously "doing" things, but why isn't Getting or Setting? This may make sense to you, but others may see things differently.

I'm assuming you are working in a team. If your team is going to adopt this as a pattern, then everyone needs to agree to use it, and to do that, everyone needs to understand intuitively how it works, and more importantly, how to extend it. If they don't, then you will start getting methods in your Do class that you don't think should be there, and you will be putting methods in other classes that other people can't find because they don't have the same mental model as you as to how this works. It does not take long for things to get messy if everyone is doing things differently.

With respect to extending Entities with partial classes, I would avoid this myself. Entities have a clearly defined responsibility, and by adding code to them, you are assigning extra responsibilities (c.f. the Single Responsibility Principle). Admittedly, your extra code is all separated into separate static sub classes, but if that is the case, why not simply make them classes in their own right and move them somewhere else in your application?

In terms of the classes themselves, static classes with static methods are going to make unit testing extremely difficult, and there's no reason why they should be static, so I would definitely change that. Of course now you have to instantiate them to use them, which presents more of an argument for moving them somewhere else.

On a more technical point, what is BaseService doing? You are creating a context, passing it by reference (why?) to AddPost (for example), and then using it as an out parameter in BaseService.Add. I'm not sure what's going on here, but it looks wrong.

As a pattern, I would say it needs work, but simply by attempting to have a pattern, you are heading in the right direction.

You haven't mentioned what your colleague thinks is 'good practice' but I suggest that you continue discussing this until you agree. Decide what you are trying to achieve, and what pattern best fits that. Maybe there is an established pattern that fits, but try not to overengineer it. My experience tells me that the more I try to abstract away from Entity Framework, the harder it can be to use some of it's more powerful features.

Body:
Me and my colleague had recently a discussion on good practices in EF.
So i show one of mine.

He said it is a little bit muddler.

My practice consist in modify the autogenerated class in a specific way.
This is my starting model:

namespace PCServer.Data
{
    using System;
    using System.Collections.Generic;

    public partial class Post: IEntity
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Message { get; set; }
        public DateTime Date { get; set; }

        public virtual Post ParentPost { get; set; }
        public virtual AspNetUser Author { get; set; }
    }
}

I like to extend it in this way:

public partial class Post
    {
        //This class "do" something, like adding a post or deleting a post
        public static class Do
        {
            public static void AddPost(ref ApplicationDbContext context, string postMessage)
            {
                //Create a post
                Post p = new Post();
                p.Title = "This is an example!";
                p.message = postMessage;
                p.Date = DateTime.UtcNow;

                //Adding to context
                BaseService.Add(post, out context);
            }

            public static void DeletePost(ref ApplicationDbContext context, int postId)
            {
                PostRepository postRepo = new PostRepository(context);

                postRepo.GetById(postId);

                //Removing from context
                BaseService.Remove(post, out context);
            }
        }

        //This class "Get" something, like all posts
        public static class Get
        {
            public static void GetPosts()
            {
                using(ApplicationDbContext context = new ApplicationDbContext())
                {
                    PostRepository postRepo = new PostRepository(context);
                    return postRepo.GetAllPosts();
                }
            }
        }

        //This class "Set" something, like title of the post or the post itself maybe
        public static class Set
        {
            public static void Title(ref ApplicationDbContext context, int postId, string title)
            {
                PostRepository postRepo = new PostRepository(context);
                Post post = postRepo.GetById(postId);
                post.Title = title;

                BaseService.Update(post, out context);
            }

            public static void ChangePost(ref ApplicationDbContext context, int postId, Post post)
            {
                PostRepository postRepo = new PostRepository(context);
                Post dbPost = postRepo.GetById(postId);
                dbPost = post;

                BaseService.Update(dbPost, out context);
            }
        }
    }

So, when i must to do something with an Entity, i can (for example only):

ApplicationDbContext c = new ApplicationDbContext();

Post.Do.AddPost(ref c,"Hi!");
IEnumerable<Post> posts = Post.Get.GetPosts();

Post.Set.Title(ref c,100,"Changing title!");

And after all:

await BaseService.CommitAsync<Post>(c);

SO.
What do you think? Would you use it? Why?

Thank you and sorry for long post.


问:
Node Sass does not yet support your current environment: Linux 64-bit with false
Getting this error on Arch Linux with node-sass. I'm using it with gulp-sass.

```<code>Node Sass does not yet support your current environment: Linux 64-bit with false
</code>```

Versions

```<code>$ gulp -v
[19:43:15] CLI version 3.9.1
[19:43:15] Local version 3.9.1

$ npm -v
3.9.0
</code>```

Node

```<code>$ node -v
v6.2.0
</code>```

Even using this command npm rebuild node-sass is not changing anything.

答: You should also check your version of nodejs. I was on a version 9 of node js which isn't officially supported at this time of writing. Reverting back to version 6.11.4 fixed the issue for me.

Body:
Getting this error on Arch Linux with node-sass. I'm using it with gulp-sass.

Node Sass does not yet support your current environment: Linux 64-bit with false

Versions

$ gulp -v
[19:43:15] CLI version 3.9.1
[19:43:15] Local version 3.9.1

$ npm -v
3.9.0

Node

$ node -v
v6.2.0

Even using this command npm rebuild node-sass is not changing anything.


问:
Not able to set new value for an AngularJS custom directive isolated scope property
I'm creating a very simple custom directive and trying to pass a simple string variable from the parent scope to the custom directive isolated scope by using the '<' symbol. Then, I try to assign a new value to the variable in my custom directive controller and display the new value in the template but it's still displaying the old value.

Here is my parent controller:

```<code>    (function(){
      angular.module("app").controller("ctrl", ctrl);

      function ctrl(){
        ctrl = this;
        ctrl.fullname = "Paul G.";
      }
    })()
</code>```

Here is my custom directive:

```<code>    (function () {
      'use strict';
      angular.module('app').directive('dir', dir);
      function dir() {
        return {
          scope:{
            name:'<',
          },
          bindToController: true,
          template: `<h1>I'm a directive</h1>
                    <h1>Name: {{vm.name}}</h1>`
          ,
          controller: function($scope){
            this.name = "Tony J";
          },
          controllerAs:'vm'
      };
     }
   })();
</code>```

Here is my Html:

```<code>    <!DOCTYPE html>
        <html ng-app="app">

        <head>
         <meta charset="utf-8" />
         <script
 src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js" data-semver="1.5.11"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-resource/1.6.4/angular-resource.js"></script>
    <script src="app.js"></script>
    <script src="ctrl.js"></script>
    <script src="directive.js"></script>
  </head>

  <body ng-controller="ctrl as $ctrl">
    <p>Hello {{$ctrl.fullname}}!</p>
    <dir name="$ctrl.fullname"></dir>
    </div>
  </body>

</html>
</code>```

The output is below:

However, I expected it see Name: Tony J in the output.

答:
I'm not aware of < (one way data binding) as an option for the scope property of a directive, this works with components in the property bindings.

If you want to do one way data binding in your isolated directive scope you can use the @ symbol instead.

Body:
I'm creating a very simple custom directive and trying to pass a simple string variable from the parent scope to the custom directive isolated scope by using the '<' symbol. Then, I try to assign a new value to the variable in my custom directive controller and display the new value in the template but it's still displaying the old value.

Here is my parent controller:

    (function(){
      angular.module("app").controller("ctrl", ctrl);

      function ctrl(){
        ctrl = this;
        ctrl.fullname = "Paul G.";
      }
    })()

Here is my custom directive:

    (function () {
      'use strict';
      angular.module('app').directive('dir', dir);
      function dir() {
        return {
          scope:{
            name:'<',
          },
          bindToController: true,
          template: `
I'm a directive

Name: {{vm.name}}
`
          ,
          controller: function($scope){
            this.name = "Tony J";
          },
          controllerAs:'vm'
      };
     }
   })();

Here is my Html:

    <!DOCTYPE html>

         <meta charset="utf-8" />

Hello {{$ctrl.fullname}}!

    <dir name="$ctrl.fullname"></dir>

The output is below:

However, I expected it see Name: Tony J in the output.