问:
Python splitting code into functions
Sorry about the length of this but I figured more info is better than not enough!!

I'm trying to split the (working) piece of Python code into functions to make it clearer / easier to use but am coming unstuck as soon as i move stuff into functions. It's basically a password generator which tries to only output a password to the user once the password qualifies as having a character from all 4 categories in it. (Lowercase, uppercase, numbers and symbols).

```<code>import random
import string
lowerasciis = string.ascii_letters[0:26]
upperasciis = string.ascii_letters[26:]
numberedstrings = str(1234567809)
symbols = "!@$%^&*()[]"
password_length = int(raw_input("Please enter a password length: "))

while True:
    lowerasscii_score = 0
    upperascii_score = 0
    numberedstring_score = 0
    symbol_score = 0
    password_as_list = []

    while len(password_as_list) < password_length:
        char = random.choice(lowerasciis+upperasciis+numberedstrings+symbols)
        password_as_list.append(char)
    for x in password_as_list:
        if x in lowerasciis:
            lowerasscii_score +=1
        elif x in upperasciis:
            upperascii_score +=1
        elif x in numberedstrings:
            numberedstring_score +=1
        elif x in symbols:
            symbol_score +=1
# a check for the screen. Each cycle of the loop should display a new score:
    print lowerasscii_score, upperascii_score, numberedstring_score, symbol_score

    if lowerasscii_score >= 1 and upperascii_score >= 1 and numberedstring_score >= 1 and symbol_score >=1:
        password = "".join(password_as_list)
        print password
        break
</code>```

And here is my attempt at splitting it. When i try to run the below it complains of "UnboundLocalError: local variable 'upperascii_score' referenced before assignment" in the scorepassword_as_a_list() function

```<code>import random
import string
lowerasciis = string.ascii_letters[0:26]
upperasciis = string.ascii_letters[26:]
numberedstrings = str(1234567809)
symbols = "!@$%^&*()[]"
password_length = int(raw_input("Please enter a password length: "))
lowerasscii_score = 0
upperascii_score = 0
numberedstring_score = 0
symbol_score = 0
password_as_list = []

def genpassword_as_a_list():
    while len(password_as_list) < password_length:
        char = random.choice(lowerasciis+upperasciis+numberedstrings+symbols)
        password_as_list.append(char)

def scorepassword_as_a_list():
    for x in password_as_list:
        if x in lowerasciis:
            lowerasscii_score +=1
        elif x in upperasciis:
            upperascii_score +=1
        elif x in numberedstrings:
            numberedstring_score +=1
        elif x in symbols:
            symbol_score +=1
    # give user feedback about password's score in 4 categories
    print lowerasscii_score, upperascii_score, numberedstring_score, symbol_score

def checkscore():
    if lowerasscii_score >= 1 and upperascii_score >= 1 and numberedstring_score >= 1 and symbol_score >=1:
        return 1
    else:
        return 0

def join_and_printpassword():
    password = "".join(password_as_list)
    print password

while True:
    genpassword_as_a_list()
    scorepassword_as_a_list()
    if checkscore() == 1:
        join_and_printpassword()
        break
</code>```

答:
The primary issue here is that you need to keep track of the scope of the various variables that you're using. In general, one of the advantages of splitting your code into functions (if done properly) is that you can reuse code without worrying about whether any initial states have been modified somewhere else. To be concrete, in your particular example, even if you got things working right (using global variables), every time you called one of your functions, you'd have to worry that e.g. lowerassci_score was not getting reset to 0.

Instead, you should accept anything that your function needs to run as parameters and output some return value, without manipulating global variables. In general, this idea is known as "avoiding side-effects." Here is your example re-written with this in mind:

```<code>import random
import string
lowerasciis = string.ascii_letters[0:26]
upperasciis = string.ascii_letters[26:]
numberedstrings = str(1234567809)
symbols = "!@$%^&*()[]"

def genpassword_as_a_list(password_length):
    password_as_list = []
    while len(password_as_list) < password_length:
        char = random.choice(lowerasciis+upperasciis+numberedstrings+symbols)
        password_as_list.append(char)
    return password_as_list

def scorepassword_as_a_list(password_as_list):
    lowerasscii_score = 0
    upperascii_score = 0
    numberedstring_score = 0
    symbol_score = 0
    for x in password_as_list:
        if x in lowerasciis:
            lowerasscii_score +=1
        elif x in upperasciis:
            upperascii_score +=1
        elif x in numberedstrings:
            numberedstring_score +=1
        elif x in symbols:
            symbol_score +=1
    # give user feedback about password's score in 4 categories
    return (
        lowerasscii_score, upperascii_score, numberedstring_score,
        symbol_score
    )

def checkscore(
        lowerasscii_score, upperascii_score, numberedstring_score,
        symbol_score):
    if lowerasscii_score >= 1 and upperascii_score >= 1 and numberedstring_score >= 1 and symbol_score >=1:
        return 1
    else:
        return 0

def join_and_printpassword(password_as_list):
    password = "".join(password_as_list)
    print password

password_length = int(raw_input("Please enter a password length: "))

while True:
    password_list = genpassword_as_a_list(password_length)
    current_score = scorepassword_as_a_list(password_list)
    if checkscore(*current_score) == 1:
        join_and_printpassword(password_list)
        break
</code>```

A few notes on this:

Notice that the "score" variables are introduced inside the scorepassword_as_list function and (based on the scoping rules) are local to that function. We get them out of the function by passing them out as a return value.

I've used just a bit of magic near the end with *current_score. Here, the asterisk is used as the "splat" or "unpack" operator. I could just as easily have written checkscore(current_score[0], current_score[1], current_score[2], current_score[3]); they mean the same thing.

It would probably be useful to read up a bit more on variable scoping and namespaces in Python. Here's one guide, but there may be better ones out there.

Title: Python splitting code into functions

Body:
Sorry about the length of this but I figured more info is better than not enough!!

I'm trying to split the (working) piece of Python code into functions to make it clearer / easier to use but am coming unstuck as soon as i move stuff into functions. It's basically a password generator which tries to only output a password to the user once the password qualifies as having a character from all 4 categories in it. (Lowercase, uppercase, numbers and symbols).

import random
import string
lowerasciis = string.ascii_letters[0:26]
upperasciis = string.ascii_letters[26:]
numberedstrings = str(1234567809)
symbols = "!@$%^&*()[]"
password_length = int(raw_input("Please enter a password length: "))

while True:
    lowerasscii_score = 0
    upperascii_score = 0
    numberedstring_score = 0
    symbol_score = 0
    password_as_list = []

    while len(password_as_list) < password_length:
        char = random.choice(lowerasciis+upperasciis+numberedstrings+symbols)
        password_as_list.append(char)
    for x in password_as_list:
        if x in lowerasciis:
            lowerasscii_score +=1
        elif x in upperasciis:
            upperascii_score +=1
        elif x in numberedstrings:
            numberedstring_score +=1
        elif x in symbols:
            symbol_score +=1
# a check for the screen. Each cycle of the loop should display a new score:
    print lowerasscii_score, upperascii_score, numberedstring_score, symbol_score

    if lowerasscii_score >= 1 and upperascii_score >= 1 and numberedstring_score >= 1 and symbol_score >=1:
        password = "".join(password_as_list)
        print password
        break

And here is my attempt at splitting it. When i try to run the below it complains of "UnboundLocalError: local variable 'upperascii_score' referenced before assignment" in the scorepassword_as_a_list() function

import random
import string
lowerasciis = string.ascii_letters[0:26]
upperasciis = string.ascii_letters[26:]
numberedstrings = str(1234567809)
symbols = "!@$%^&*()[]"
password_length = int(raw_input("Please enter a password length: "))
lowerasscii_score = 0
upperascii_score = 0
numberedstring_score = 0
symbol_score = 0
password_as_list = []

def genpassword_as_a_list():
    while len(password_as_list) < password_length:
        char = random.choice(lowerasciis+upperasciis+numberedstrings+symbols)
        password_as_list.append(char)

def scorepassword_as_a_list():
    for x in password_as_list:
        if x in lowerasciis:
            lowerasscii_score +=1
        elif x in upperasciis:
            upperascii_score +=1
        elif x in numberedstrings:
            numberedstring_score +=1
        elif x in symbols:
            symbol_score +=1
    # give user feedback about password's score in 4 categories
    print lowerasscii_score, upperascii_score, numberedstring_score, symbol_score

def checkscore():
    if lowerasscii_score >= 1 and upperascii_score >= 1 and numberedstring_score >= 1 and symbol_score >=1:
        return 1
    else:
        return 0

def join_and_printpassword():
    password = "".join(password_as_list)
    print password

while True:
    genpassword_as_a_list()
    scorepassword_as_a_list()
    if checkscore() == 1:
        join_and_printpassword()
        break

Body:
The primary issue here is that you need to keep track of the scope of the various variables that you're using. In general, one of the advantages of splitting your code into functions (if done properly) is that you can reuse code without worrying about whether any initial states have been modified somewhere else. To be concrete, in your particular example, even if you got things working right (using global variables), every time you called one of your functions, you'd have to worry that e.g. lowerassci_score was not getting reset to 0.

Instead, you should accept anything that your function needs to run as parameters and output some return value, without manipulating global variables. In general, this idea is known as "avoiding side-effects." Here is your example re-written with this in mind:

import random
import string
lowerasciis = string.ascii_letters[0:26]
upperasciis = string.ascii_letters[26:]
numberedstrings = str(1234567809)
symbols = "!@$%^&*()[]"

def genpassword_as_a_list(password_length):
    password_as_list = []
    while len(password_as_list) < password_length:
        char = random.choice(lowerasciis+upperasciis+numberedstrings+symbols)
        password_as_list.append(char)
    return password_as_list

def scorepassword_as_a_list(password_as_list):
    lowerasscii_score = 0
    upperascii_score = 0
    numberedstring_score = 0
    symbol_score = 0
    for x in password_as_list:
        if x in lowerasciis:
            lowerasscii_score +=1
        elif x in upperasciis:
            upperascii_score +=1
        elif x in numberedstrings:
            numberedstring_score +=1
        elif x in symbols:
            symbol_score +=1
    # give user feedback about password's score in 4 categories
    return (
        lowerasscii_score, upperascii_score, numberedstring_score,
        symbol_score
    )

def checkscore(
        lowerasscii_score, upperascii_score, numberedstring_score,
        symbol_score):
    if lowerasscii_score >= 1 and upperascii_score >= 1 and numberedstring_score >= 1 and symbol_score >=1:
        return 1
    else:
        return 0

def join_and_printpassword(password_as_list):
    password = "".join(password_as_list)
    print password

password_length = int(raw_input("Please enter a password length: "))

while True:
    password_list = genpassword_as_a_list(password_length)
    current_score = scorepassword_as_a_list(password_list)
    if checkscore(*current_score) == 1:
        join_and_printpassword(password_list)
        break

A few notes on this:

Notice that the "score" variables are introduced inside the scorepassword_as_list function and (based on the scoping rules) are local to that function. We get them out of the function by passing them out as a return value.

I've used just a bit of magic near the end with *current_score. Here, the asterisk is used as the "splat" or "unpack" operator. I could just as easily have written checkscore(current_score[0], current_score[1], current_score[2], current_score[3]); they mean the same thing.

It would probably be useful to read up a bit more on variable scoping and namespaces in Python. Here's one guide, but there may be better ones out there.


来源: stackexchange

问:
How to data bind from view to view model in Xamarin?
I have a question on how to bind from entry tag/view to view model using a class. I'm having a null value whenever I try to submit the data going to my view model class.

Here is the code for the view:

```<code>Entry Text="{Binding User.UserName, Mode=TwoWay}"/>
<Entry Text="{Binding User.Password, Mode=TwoWay}"/>

<Button Text="Login" Command="{Binding LoginCommand}"/>
</code>```

Here is the code for the view model(constructor part):

```<code> public LoginPageViewModel(IApiService apiService, INavigationService navigationService)
    {
        this.apiService = apiService;
        this.navigationService = navigationService;
        LoginCommand = new DelegateCommand(Login);
    }
</code>```

In the view model, I have also a class for the username and password where it uses the model of User:

```<code> private Users user;
    public Users User
    {
        get { return user; }
        set { SetProperty(ref user, value); }
    }
</code>```

Here is the model for the Users:

```<code>public class Users : BindableObject
{
    private string username;

    public string UserName
    {
        get { return username; }
        set { username = value; }
    }

    private string password;

    public string Password
    {
        get { return password; }
        set { password = value; }
    }

}
</code>```

Every time I tried to hit the submit button, I get the null value when I tried to debug my code.

```<code>private async void Login()
    {
        var test = User.UserName;

        bool success = await apiService.LoginAsync(User);
</code>```

Thank you for your help on my Xamarin project.

答:
You need to create a new instance of User at your viewmodel constructor.</p>

```<code>public LoginPageViewModel(IApiService apiService, INavigationService navigationService)
    {
        this.apiService = apiService;
        this.navigationService = navigationService;
        LoginCommand = new DelegateCommand(Login);

        this.User = new Users();
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a question on how to bind from entry tag/view to view model using a class. I'm having a null value whenever I try to submit the data going to my view model class.

Here is the code for the view:

Entry Text="{Binding User.UserName, Mode=TwoWay}"/>
<Entry Text="{Binding User.Password, Mode=TwoWay}"/>

<Button Text="Login" Command="{Binding LoginCommand}"/>

Here is the code for the view model(constructor part):

 public LoginPageViewModel(IApiService apiService, INavigationService navigationService)
    {
        this.apiService = apiService;
        this.navigationService = navigationService;
        LoginCommand = new DelegateCommand(Login);
    }

In the view model, I have also a class for the username and password where it uses the model of User:

 private Users user;
    public Users User
    {
        get { return user; }
        set { SetProperty(ref user, value); }
    }

Here is the model for the Users:

public class Users : BindableObject
{
    private string username;

    public string UserName
    {
        get { return username; }
        set { username = value; }
    }

    private string password;

    public string Password
    {
        get { return password; }
        set { password = value; }
    }

}

Every time I tried to hit the submit button, I get the null value when I tried to debug my code.

private async void Login()
    {
        var test = User.UserName;

        bool success = await apiService.LoginAsync(User);

Thank you for your help on my Xamarin project.

Body:
You need to create a new instance of User at your viewmodel constructor.

public LoginPageViewModel(IApiService apiService, INavigationService navigationService)
    {
        this.apiService = apiService;
        this.navigationService = navigationService;
        LoginCommand = new DelegateCommand(Login);

        this.User = new Users();
    }


问:
C++ access member of a struct inside a union
I'm trying to write a C++ program for an Atmel Microcontroller.

I need to use some of the functions that were already written in the ASF library, and I'm doing this by copying some of the code into C++ functions.

I get this error on compilation:

'union Pm' has no member named 'PM_CPUMASK'

The Pm type union looks something like this:

```<code>typedef union {
 struct {
    ....
 } bf;
 struct {
  ....
  RwReg   PM_CPUMASK;
  ....
 } reg;
} Pm;`
</code>```

In the ASF code, the member PM_CPUMASK is accessed like this:

```<code>unsigned int mask = *(&PM->PM_CPUMASK + busId);
</code>```

But I get an error. I think this is valid in C, but in C++ I would need to access the named struct and then the actual member. Using *(&PM->reg.PM_CPUMASK...) I get no error, but is there a way to activate this style of member accessing in C++ compiler?

BTW, there's no naming conflicts in the members of the 2 structs.
Thanks.

答:
I would guess that you copy-pasted the code and then modified it. The original code was something like this

```<code>typedef union {
 struct {
    ....
 };
 struct {
  ....
  RwReg   PM_CPUMASK;
  ....
 };
} Pm;
</code>```

What is anonymous struct, that is a compiler extension, and there is no default extensions like this for C++ compiler, see here.

And then you added names to those structs. That is why you have to use another identifier to access the member.

Sorry if my guessing is wrong. But the point is that you have to use an additional name there.

Body:
I'm trying to write a C++ program for an Atmel Microcontroller.

I need to use some of the functions that were already written in the ASF library, and I'm doing this by copying some of the code into C++ functions.

I get this error on compilation:

'union Pm' has no member named 'PM_CPUMASK'

The Pm type union looks something like this:

typedef union {
 struct {
    ....
 } bf;
 struct {
  ....
  RwReg   PM_CPUMASK;
  ....
 } reg;
} Pm;`

In the ASF code, the member PM_CPUMASK is accessed like this:

unsigned int mask = *(&PM->PM_CPUMASK + busId);

But I get an error. I think this is valid in C, but in C++ I would need to access the named struct and then the actual member. Using *(&PM->reg.PM_CPUMASK...) I get no error, but is there a way to activate this style of member accessing in C++ compiler?

BTW, there's no naming conflicts in the members of the 2 structs.
Thanks.

Body:
I would guess that you copy-pasted the code and then modified it. The original code was something like this

typedef union {
 struct {
    ....
 };
 struct {
  ....
  RwReg   PM_CPUMASK;
  ....
 };
} Pm;

What is anonymous struct, that is a compiler extension, and there is no default extensions like this for C++ compiler, see here.

And then you added names to those structs. That is why you have to use another identifier to access the member.

Sorry if my guessing is wrong. But the point is that you have to use an additional name there.


问:
Handsontable, custom text editor, copy/paste issue
I have a table with two columns: name and code. I have created a simple custom editor for code column. The idea is, when user double clicks on the cell, the custom dialog with code editor opens. I have implemented it and posted the simplified example here:

Link to plunker

However, I have one issue with copy/paste functionality: if I use my editor, edit some code for the cell, press “Save”, the "code" column value seems to be correctly saved. But when I select this cell and press Ctrl+C, the value is not copied.

The question is: is it a bug in handsontable or I have just missed something, while implementing the custom editor? How should I change my custom editor to make the copy-paste functionality working properly.

The code of editor:

```<code>var ScriptEditor = Handsontable.editors.TextEditor.prototype.extend();

ScriptEditor.prototype.getValue = function () {
    return this.TEXTAREA.value;
};

ScriptEditor.prototype.setValue = function (value) {
    this.TEXTAREA.value = value;
};

ScriptEditor.prototype.open = function () {

    var self = this;

    this.instance.deselectCell();

    var value = self.instance.getDataAtCell(self.row, self.col);
    var decodedCode = decodeURI(value);

    var success = function (resultCode) {
        var encodedCode = encodeURI(resultCode);

        self.instance.setDataAtCell(self.row, self.col, encodedCode, 'edit');
        self.instance.selectCell(self.row, self.col);
    };

    openEditor(decodedCode)
            .then(success);

};

ScriptEditor.prototype.focus = function () {
    Handsontable.editors.TextEditor.prototype.focus.apply(this, arguments);
};

ScriptEditor.prototype.close = function () {

};

var openEditor = function (codeToEdit) {

    var deferred = $q.defer();

    var dialog = ngDialog.open({
        template: 'editorTemplate.htm',
        className: 'ngdialog-theme-default',
        controllerAs: "editor",
        controller: function () {
            var vm = this;
            vm.inputCode = codeToEdit;
            vm.submitChanges = function () {
                dialog.close();
                deferred.resolve(vm.inputCode);
            };
        }
    });

    return deferred.promise;
};
</code>```

Specs:
Angular version: 1.6.1
Handsontable version: 0.31.2
Chrome version: Version 58.0.3029.81

答:
I have posted an issue on handsontable github repositiory and received there the answer. Link to issue: here

Solution:
Like the member of handsontable team has suggested, in open function before opening my dialog I call this.instance.deselectCell();. However, with this solution, the problem was, that if I press Enter my code editor dialog, not the new line is inserted, but the next cell in handsontable is selected. Then, I have wrappped the call in setTimeout() and it is worked.

Link to plunker:
here

The working code is:

```<code>ScriptEditor.prototype.open = function () {

    var self = this;

    setTimeout(function () {
        self.instance.deselectCell();
    });

    var value = self.instance.getDataAtCell(self.row, self.col);
    var decodedCode = decodeURI(value);

    var success = function (resultCode) {
        var encodedCode = encodeURI(resultCode);
        self.instance.setDataAtCell(self.row, self.col, encodedCode, 'edit');
        self.instance.selectCell(self.row, self.col);
    };

    openEditor(decodedCode)
        .then(success);

};
</code>```

Body:
I have a table with two columns: name and code. I have created a simple custom editor for code column. The idea is, when user double clicks on the cell, the custom dialog with code editor opens. I have implemented it and posted the simplified example here:

Link to plunker

However, I have one issue with copy/paste functionality: if I use my editor, edit some code for the cell, press “Save”, the "code" column value seems to be correctly saved. But when I select this cell and press Ctrl+C, the value is not copied.

The question is: is it a bug in handsontable or I have just missed something, while implementing the custom editor? How should I change my custom editor to make the copy-paste functionality working properly.

The code of editor:

var ScriptEditor = Handsontable.editors.TextEditor.prototype.extend();

ScriptEditor.prototype.getValue = function () {
    return this.TEXTAREA.value;
};

ScriptEditor.prototype.setValue = function (value) {
    this.TEXTAREA.value = value;
};

ScriptEditor.prototype.open = function () {

    var self = this;

    this.instance.deselectCell();

    var value = self.instance.getDataAtCell(self.row, self.col);
    var decodedCode = decodeURI(value);

    var success = function (resultCode) {
        var encodedCode = encodeURI(resultCode);

        self.instance.setDataAtCell(self.row, self.col, encodedCode, 'edit');
        self.instance.selectCell(self.row, self.col);
    };

    openEditor(decodedCode)
            .then(success);

};

ScriptEditor.prototype.focus = function () {
    Handsontable.editors.TextEditor.prototype.focus.apply(this, arguments);
};

ScriptEditor.prototype.close = function () {

};

var openEditor = function (codeToEdit) {

    var deferred = $q.defer();

    var dialog = ngDialog.open({
        template: 'editorTemplate.htm',
        className: 'ngdialog-theme-default',
        controllerAs: "editor",
        controller: function () {
            var vm = this;
            vm.inputCode = codeToEdit;
            vm.submitChanges = function () {
                dialog.close();
                deferred.resolve(vm.inputCode);
            };
        }
    });

    return deferred.promise;
};

Specs:
Angular version: 1.6.1
Handsontable version: 0.31.2
Chrome version: Version 58.0.3029.81

Body:
I have posted an issue on handsontable github repositiory and received there the answer. Link to issue: here

Solution:
Like the member of handsontable team has suggested, in open function before opening my dialog I call this.instance.deselectCell();. However, with this solution, the problem was, that if I press Enter my code editor dialog, not the new line is inserted, but the next cell in handsontable is selected. Then, I have wrappped the call in setTimeout() and it is worked.

Link to plunker:
here

The working code is:

ScriptEditor.prototype.open = function () {

    var self = this;

    setTimeout(function () {
        self.instance.deselectCell();
    });

    var value = self.instance.getDataAtCell(self.row, self.col);
    var decodedCode = decodeURI(value);

    var success = function (resultCode) {
        var encodedCode = encodeURI(resultCode);
        self.instance.setDataAtCell(self.row, self.col, encodedCode, 'edit');
        self.instance.selectCell(self.row, self.col);
    };

    openEditor(decodedCode)
        .then(success);

};


问:
Django rest framework: how to turn off/on pagination in ModelViewSet
I'm using Django REST framework with djangorestframework-csv with default pagination settings, but when request is with format "CSV", there is no need in paginaion. Is possible to disable pagination with:

pagination_class = None

it's possible to change it dynamically?

```<code>class ObjectViewSet(BaseViewSet, viewsets.ModelViewSet):

    queryset = Object.objects.none()
    serializer_class = ObjectSerializer
    pagination_class = None # if format is "CSV"
    # pagination_class = None # if fromat isn't "CSV"
</code>```

Thanks.

答:
Solution is:

```<code>class PaginatedCSVRenderer (CSVRenderer):
    results_field = 'results'

    def render(self, data, *args, **kwargs):
        if not isinstance(data, list):
            data = data.get(self.results_field, [])
        return super(PaginatedCSVRenderer, self).render(data, *args, **kwargs)
</code>```

and than:

```<code>class ObjectViewSet(BaseViewSet, viewsets.ModelViewSet):

    queryset = Object.objects.none()
    serializer_class = ObjectSerializer
    renderer_classes =  (JSONRenderer, PaginatedCSVRenderer)
</code>```

and delete from settings:

```<code>   'PAGE_SIZE': 10,
</code>```

Body:
I'm using Django REST framework with djangorestframework-csv with default pagination settings, but when request is with format "CSV", there is no need in paginaion. Is possible to disable pagination with:

pagination_class = None

it's possible to change it dynamically?

class ObjectViewSet(BaseViewSet, viewsets.ModelViewSet):

    queryset = Object.objects.none()
    serializer_class = ObjectSerializer
    pagination_class = None # if format is "CSV"
    # pagination_class = None # if fromat isn't "CSV"

Thanks.

Body:
Solution is:

class PaginatedCSVRenderer (CSVRenderer):
    results_field = 'results'

    def render(self, data, *args, **kwargs):
        if not isinstance(data, list):
            data = data.get(self.results_field, [])
        return super(PaginatedCSVRenderer, self).render(data, *args, **kwargs)

and than:

class ObjectViewSet(BaseViewSet, viewsets.ModelViewSet):

    queryset = Object.objects.none()
    serializer_class = ObjectSerializer
    renderer_classes =  (JSONRenderer, PaginatedCSVRenderer)

and delete from settings:

   'PAGE_SIZE': 10,


问:
vue.js v-for list not updating
I have this list:

```<code><ul id="tab">
    <li v-for="list in names">
        {{ list.personName }}
    </li>
</ul>
</code>```

And then I have this vue object:

```<code>var vm = new Vue ({
    el: '#tab',
        data: {
            names: //an object array coming from the server
        }
    });
</code>```

So the 'names' data is updated and given information from the server. However, when the names are updated/change, it is not reflected on the client side list. The items that appear in the list only reflect the items that were there when the page initially loaded.

In the vue.js developer tools in Google Chrome, I can always see the updated 'names' data, but it just doesn't reflect on the DOM itself.

EDIT1:
What's in the 'name's:

```<code>names: Array[2]
    0: Object
    _id: "580aeafd017fbfb81a3a794d"
    personName: "hi"

    1: Object
   _id: "580c4455ccc9e39c21f02434"
   personName: "test"
</code>```

EDIT2

So I'm using node.js, and transferring the data live from node to the client via socket.io like this:

```<code>socket.on('userDocument', function(userDocument) {
    var vm= new Vue ({
        el: '#tab',
        data: {
            names: //an object array coming from the server
        }
    });
});
</code>```

答:
Array change detection is a bit tricky in Vue. Most of the in place array methods are working as expected (i.e. doing a splice in your $data.names array would work), but assigining values directly (i.e. $data.names[0] = 'Joe') would not update the reactively rendered components.
Depending on how you process the server side results you might need to think about these options described in the in vue documentation: Array Change Detection.

Some ideas to explore:

using the v-bind:key="some_id" to have better

using the push to add new elements

using Vue.set(example1.items, indexOfItem, newValue) (also mentioned by Artokun)

Title: vue.js v-for list not updating

Body:
I have this list:

        {{ list.personName }}

And then I have this vue object:

var vm = new Vue ({
    el: '#tab',
        data: {
            names: //an object array coming from the server
        }
    });

So the 'names' data is updated and given information from the server. However, when the names are updated/change, it is not reflected on the client side list. The items that appear in the list only reflect the items that were there when the page initially loaded.

In the vue.js developer tools in Google Chrome, I can always see the updated 'names' data, but it just doesn't reflect on the DOM itself.

EDIT1:
What's in the 'name's:

names: Array[2]
    0: Object
    _id: "580aeafd017fbfb81a3a794d"
    personName: "hi"

    1: Object
   _id: "580c4455ccc9e39c21f02434"
   personName: "test"

EDIT2

So I'm using node.js, and transferring the data live from node to the client via socket.io like this:

socket.on('userDocument', function(userDocument) {
    var vm= new Vue ({
        el: '#tab',
        data: {
            names: //an object array coming from the server
        }
    });
});

ContentLicense: CC BY-SA 4.0


问:
Unable to find explicit activity class and force close application
When I launch my application, it force closes and when I debug my program I kept getting error messages. I have 2 activities, the Authentication (where User log in) and Mainpage (this is the page when the user is logged in).

The problem here is when i'm not logged in, I can still log in. If i'm logged in it should take me to Mainpage (Activity), but now the error [see below] shows up.

This is from the stack trace:

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{com.blocktrekacademy.officialblocktrek/com.blocktrekacademy.officialblocktrek.Authentication}: android.content.ActivityNotFoundException: Unable to find explicit activity class {/com.blocktrekacademy.officialblocktrek.Mainpage}; have you declared this activity in your AndroidManifest.xml?
Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {/com.blocktrekacademy.officialblocktrek.Mainpage}; have you declared this activity in your AndroidManifest.xml?
</code>```

This is the Application tag in my AndroidManifest.xml:

```<code><application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".Authentication"
            android:label="@string/title_activity_authentication"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Mainpage"
            android:label="@string/title_activity_mainpage"
            android:theme="@style/AppTheme.NoActionBar"
            android:screenOrientation="portrait"></activity>
    </application>
</code>```

Note:

My classes extends AppCompatActivity

Tried Solutions:

I tried adding android:name=".Authentication" on Application, but that gives me this error:

```<code>'com.blocktrekacademy.officialblocktrek.Authentication' is not assignable to 'android.app.Application'
</code>```

on AndroidManifest.xml, and these errors on logcat:

```<code>java.lang.RuntimeException: Unable to instantiate application com.blocktrekacademy.officialblocktrek.Authentication: java.lang.ClassCastException: com.blocktrekacademy.officialblocktrek.Authentication cannot be cast to android.app.Application
Caused by: java.lang.ClassCastException: com.blocktrekacademy.officialblocktrek.Authentication cannot be cast to android.app.Application
</code>```

I'm really a newbie on Android Development :(

答:
Hi @user7994637 try doing this in your AndroidManifest.xml

```<code><application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".officialblocktrek.Authentication"
            android:label="@string/title_activity_authentication"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".officialblocktrek.Mainpage"
            android:label="@string/title_activity_mainpage"
            android:theme="@style/AppTheme.NoActionBar"
            android:screenOrientation="portrait"></activity>
    </application>
</code>```

I guess your activity is inside package "officialblocktrek", hence it crashing so I updated your manifest. Hope it helps.

Body:
When I launch my application, it force closes and when I debug my program I kept getting error messages. I have 2 activities, the Authentication (where User log in) and Mainpage (this is the page when the user is logged in).

The problem here is when i'm not logged in, I can still log in. If i'm logged in it should take me to Mainpage (Activity), but now the error [see below] shows up.

This is from the stack trace:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.blocktrekacademy.officialblocktrek/com.blocktrekacademy.officialblocktrek.Authentication}: android.content.ActivityNotFoundException: Unable to find explicit activity class {/com.blocktrekacademy.officialblocktrek.Mainpage}; have you declared this activity in your AndroidManifest.xml?
Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {/com.blocktrekacademy.officialblocktrek.Mainpage}; have you declared this activity in your AndroidManifest.xml?

This is the Application tag in my AndroidManifest.xml:

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".Authentication"
            android:label="@string/title_activity_authentication"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Mainpage"
            android:label="@string/title_activity_mainpage"
            android:theme="@style/AppTheme.NoActionBar"
            android:screenOrientation="portrait"></activity>
    </application>

Note:

My classes extends AppCompatActivity

Tried Solutions:

I tried adding android:name=".Authentication" on Application, but that gives me this error:

'com.blocktrekacademy.officialblocktrek.Authentication' is not assignable to 'android.app.Application'

on AndroidManifest.xml, and these errors on logcat:

java.lang.RuntimeException: Unable to instantiate application com.blocktrekacademy.officialblocktrek.Authentication: java.lang.ClassCastException: com.blocktrekacademy.officialblocktrek.Authentication cannot be cast to android.app.Application
Caused by: java.lang.ClassCastException: com.blocktrekacademy.officialblocktrek.Authentication cannot be cast to android.app.Application

I'm really a newbie on Android Development :(

Body:
Hi @user7994637 try doing this in your AndroidManifest.xml

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".officialblocktrek.Authentication"
            android:label="@string/title_activity_authentication"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".officialblocktrek.Mainpage"
            android:label="@string/title_activity_mainpage"
            android:theme="@style/AppTheme.NoActionBar"
            android:screenOrientation="portrait"></activity>
    </application>

I guess your activity is inside package "officialblocktrek", hence it crashing so I updated your manifest. Hope it helps.


问:
HTML extend height of div

div.div1 {
  position: relative;
  border: 1px solid black;
  height: 100px;
  width: 100px;
  padding: 10px;
}

div.div2 {
  background-color: gray;
  border: 1px solid black;
  padding: 10px;
}

div.div3 {
  position: absolute;
  border: 1px solid red;
  height: 20px;
  width: 20px;
  bottom: 10px;
  left: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="div1">
  <div class="div2">Test 123</div>
  <div class="div3">A</div>
</div></code>```

I use the above code to display a big div with two divs in it. For the first one I use position: absolute to place it on bottom left of the div.

How can I extend the height of the second gray one so that it's 5 pixels above the first, but without having to measure its exact height in pixel (like the pic below)? I can set height: 50px; for example but is there another way?

答:
I would use a flexbox approach rather than absolute positioning (comments in css below)

div.div1 {

  display: flex;
  flex-direction:column;
  /* add the above styles*/

  border: 1px solid black;
  min-height: 100px;         /*I would also change this to min-height otherwise it may cause issues if your text goes to 2 lines*/
  width: 100px;
  padding: 10px;
}

div.div2 {
  flex-grow:1;        /* make div grow to fill the space */
  margin-bottom:5px;  /* minus the amount of margin you wanted */

  background-color: gray;
  border: 1px solid black;
  padding: 10px;
}

div.div3 {
  /* remove absolute positioning */
  border: 1px solid red;
  height: 20px;
  width: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="div1">
  <div class="div2">Test 123</div>
  <div class="div3">A</div>
</div></code>```

Title: HTML extend height of div

Body:
div.div1 {
  position: relative;
  border: 1px solid black;
  height: 100px;
  width: 100px;
  padding: 10px;
}

div.div2 {
  background-color: gray;
  border: 1px solid black;
  padding: 10px;
}

div.div3 {
  position: absolute;
  border: 1px solid red;
  height: 20px;
  width: 20px;
  bottom: 10px;
  left: 10px;
}

Test 123

A

I use the above code to display a big div with two divs in it. For the first one I use position: absolute to place it on bottom left of the div.

How can I extend the height of the second gray one so that it's 5 pixels above the first, but without having to measure its exact height in pixel (like the pic below)? I can set height: 50px; for example but is there another way?

Body:
I would use a flexbox approach rather than absolute positioning (comments in css below)

div.div1 {

  display: flex;
  flex-direction:column;
  /* add the above styles*/

  border: 1px solid black;
  min-height: 100px;         /*I would also change this to min-height otherwise it may cause issues if your text goes to 2 lines*/
  width: 100px;
  padding: 10px;
}

div.div2 {
  flex-grow:1;        /* make div grow to fill the space */
  margin-bottom:5px;  /* minus the amount of margin you wanted */

  background-color: gray;
  border: 1px solid black;
  padding: 10px;
}

div.div3 {
  /* remove absolute positioning */
  border: 1px solid red;
  height: 20px;
  width: 20px;
}

<div class="div1">
  <div class="div2">Test 123</div>
  <div class="div3">A</div>
</div>


问:
MonoDevelop Error: Unknown MSBuild failure. Please try building the project again
Just installed MonoDevelop and I tried to compile a simple "Hello World".
Code I used:

```<code>using System;

public class HelloWorld
{
    static public void Main ()
    {
        Console.WriteLine ("Hello Mono World");
    }
}
</code>```

The error that I get is :

```<code>EmptyCSharpFile.csproj(1,1): Error: Unknown MSBuild failure. Please try building the project again (EmptyCSharpFile)
</code>```

My system info:
Ubuntu 16.04 LTS , updated
The MonoDevelop and mono are freshly installed.
Mono JIT compiler version 5.0.1.1
MonoDevelop Version 5.10
I can use mcs and run it but can't use monodevelop to run it.
I did read these similar topics but no response yet:
MonoDevelop Failure "Unknown MSBuild Failure" on Linux ;
C# compile Unknown MSBuild error MonoDevelop Linux ; https://askubuntu.com/questions/73630/could-not-obtain-c-compiler-error-when-using-monodevelop

答:
I too had the same problem when I first installed it , I assume you went straight to file -> new-> file-> general -> emptyc# file.

Instead of that, go to file->new-> solution  from there choose Console C# project or simply press ctrl + shift + N choose next ,and give project name, by default the new project has  a simple hello world program run it, this time it will work.(it worked for me)

Body:
Just installed MonoDevelop and I tried to compile a simple "Hello World".
Code I used:

using System;

public class HelloWorld
{
    static public void Main ()
    {
        Console.WriteLine ("Hello Mono World");
    }
}

The error that I get is :

EmptyCSharpFile.csproj(1,1): Error: Unknown MSBuild failure. Please try building the project again (EmptyCSharpFile)

My system info:
Ubuntu 16.04 LTS , updated
The MonoDevelop and mono are freshly installed.
Mono JIT compiler version 5.0.1.1
MonoDevelop Version 5.10
I can use mcs and run it but can't use monodevelop to run it.
I did read these similar topics but no response yet:
MonoDevelop Failure "Unknown MSBuild Failure" on Linux ;
C# compile Unknown MSBuild error MonoDevelop Linux ; https://askubuntu.com/questions/73630/could-not-obtain-c-compiler-error-when-using-monodevelop


问:
Appveyor different pipes build vs pr
As AppVeyor does not pass secure env variables to PR builds. How can you split the the yml file to do different things.
Such as on a PR build I only want to run test_scripts. On branch on master I want it to run the build_scripts as to make artifacts.

I tried

```<code>   branches
    only:
     - master
</code>```

but I can't seem to run build_scripts specifically there.

Basically on a merge into master I do a yarn release that builds the exe.  But right now a PR build it runs test_scripts and build_scripts

I'm building a Node project in appveyor specific to windows.

答:
You can use APPVEYOR_PULL_REQUEST_NUMBER environment variable in your script logic. For example IF ($env:APPVEYOR_PULL_REQUEST_NUMBER) will evaluate to false in non-pr build.

For a full list of built-in environment valuables please look here

Title: Appveyor different pipes build vs pr

Body:
As AppVeyor does not pass secure env variables to PR builds. How can you split the the yml file to do different things.
Such as on a PR build I only want to run test_scripts. On branch on master I want it to run the build_scripts as to make artifacts.

I tried

   branches
    only:
     - master

but I can't seem to run build_scripts specifically there.

Basically on a merge into master I do a yarn release that builds the exe.  But right now a PR build it runs test_scripts and build_scripts

I'm building a Node project in appveyor specific to windows.


问:
Scale Image with Center crop by maintaining Aspect Ratio using CSS
I want to create Image gallery like Mobile gallery . each Image should be in square box inside main container.

Image shouldn't be stretched instead crop or clip at maximum.
now i stretch image with aspect ratio using this code,

```<code>img {
  max-width : 150px;
  max-height : 150px;
}
</code>```

it gives me minimized thumbnail of each image. but i want to make all inside square box with center clipped or cropped image.

here is the example i want,

答:
Here is the solution how i achieved it... it keeps aspect ratio and bring image into center as like what i want...</p>

```<code>.scale-image {
  object-fit: cover;
  width: 150px;
  height: 150px;
}
</code>```

Body:
I want to create Image gallery like Mobile gallery . each Image should be in square box inside main container.

Image shouldn't be stretched instead crop or clip at maximum.
now i stretch image with aspect ratio using this code,

img {
  max-width : 150px;
  max-height : 150px;
}

it gives me minimized thumbnail of each image. but i want to make all inside square box with center clipped or cropped image.

here is the example i want,

Body:
Here is the solution how i achieved it... it keeps aspect ratio and bring image into center as like what i want...

.scale-image {
  object-fit: cover;
  width: 150px;
  height: 150px;
}


问:
Which version (debug/release - notoptimised/optimised) is better to study c++ comparing with assembly?
I have worked on C++ earlier but don't have that much knowledge on basics. So started learning it from basics (I found comparing code with assembly and learning is a fun and I find I could understand the actual concept better)

I was suggested by few to learn a optimized version of assembly rather than non-optimized version?
But I'm literally confused with the optimized version assembly? which is preferred for learning basics (while comparing with assembly).

I'm using Visual Studio Community 2015

Please help!!!

答:
It depends on what you want to see. Unoptimized code will more closely follow your code and will probably be more understandable. While when you enable optimizations, you might see what the compiler is really   doing with your code. For example in the code below, the compiler will optimize everything out and leave just the return value computed at compile time.

```<code>int myFunc() {
    int x = 30;
    x = x + 12;
    return x;
}
</code>```

So my answer is to use both.

Body:
It depends on what you want to see. Unoptimized code will more closely follow your code and will probably be more understandable. While when you enable optimizations, you might see what the compiler is really   doing with your code. For example in the code below, the compiler will optimize everything out and leave just the return value computed at compile time.

int myFunc() {
    int x = 30;
    x = x + 12;
    return x;
}

So my answer is to use both.


问:
MobileFirst 7.1 Server Access Denied when using WL.Client.connect API
We got this error message when using WL.Client.connect API

The server error logs:

[ERROR   ] FWLSE0020E: Ajax request exception: Cannot find application environment, application=test, version=1.0, environment=iphone [project WLTestConnect]

[ERROR   ] FWLSE0117E: Error code: 1, error description: INTERNAL_ERROR, error message: FWLSE0069E: An internal error occurred during gadget request  [project WLTestConnect]Cannot find application environment, application=test, version=1.0, environment=iphone, User Identity {wl_antiXSRFRealm=null, wl_authenticityRealm=null, wl_directUpdateRealm=null, wl_remoteDisableRealm=null, SampleAppRealm=null, wl_deviceNoProvisioningRealm=null, SubscribeServlet=null, wl_anonymousUserRealm=null, wl_deviceAutoProvisioningRealm=null}. [project WLTestConnect]
                                                                                com.worklight.common.log.filters.ErrorFilter

[ERROR   ] FWLSE0335E: Authorization failed: ClientId f5ac9a8cda443cfca33d1e7f926a71f90f8c67a1 was not found on the server. [project WLTestConnect]

Here's the scenario:

Create Hello MobileFirst project in workspace A.

Deploy the project to local MobileFirst Server in workspace A.

Deploy Hello MobileFirst App to iphone and then use WL.Client.connect API. We got connect success callback.

Export this MobileFirst project which named WLTestConnect.

The iPhone device(iOS 10.2.1) still running.

Switching to the new Workspace B.

Import WLTestConnect project to Workspace B.

Deploy WLTestConnect project to local MobileFirst server.

Use WL.Client.connect in iPhone device and we got the access denied error.

MobileFirst version : 7.1.0.00-20151214-1857 & 7.1.0.00-20170608-1107

Is there a way to avoid access denied?

答:
We have found a workaround for the problem:

set worklight.properties file

mfp.session.independent=false

comment the "#mfp.attrStore.type=database"

then connect success!


问:
Cut JS string present in an array at every occurrance of a particular substring and append to same array
Note:
At this point in time, I'm unable to word the question title better. If someone is able to put it accross better, please go right ahead!

What I have:

```<code>var array = ["authentication.$.order", "difference.$.user.$.otherinformation", ... , ...]
</code>```

What I need:

```<code>["authentication", "authentication.$", "authentication.$.order",
"difference", "difference.$", "difference.$.user", "difference.$.user.$",
"difference.$.user.$.otherinformation"]
</code>```

Basically, wherevever I see .$., I need to preserve it, then append everything before the occourrence of .$. along with everything before the occourrence of .$

Example:

difference.$.user.$.otherinformation should be parsed to contain:

```<code>difference
difference.$
difference.$.user
difference.$.user.$
difference.$.user.$.otherinformation
</code>```

I'm strongly feeling that some sort of recursion is to be involved here, but have not progressed in that direction yet.

Below is my implementation for the same, but unfortunately, my when my substring matches the first occourrence of .$., it stops and does not proceed to further check for other occurrences of .$. in the same string.

How best can I take this to closure?

Current flawed implementation:

```<code>for(var i=0; i<array.length; i++){
    //  next, replace all array field references with $ as that is what autoform's pick() requires
    //  /\.\d+\./g,".$." ==> replace globally .[number]. with .$.
    array[i] = array[i].replace(/\.\d+\./g,".$.");
        if(array[i].substring(0, array[i].lastIndexOf('.$.'))){
            console.log("Substring without .$.  " + array[i].substring(0, array[i].indexOf('.$.')));
            console.log("Substring with .$ " + array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
            array.push(array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
            array.push(array[i].substring(0, array[i].indexOf('.$.')));
            }
        }
    // finally remove any duplicates if any
    array = _.uniq(array);
</code>```

答:
I used a Regex expression to grab everything until the last occurrence of .$ and the chopped it, until there was nothing left. Reverse at the end.

```<code>let results = [];
let found = true;

const regex = /^(.*)\.\$/g;
let str = `difference.\$.user.\$.otherinformation`;
let m;

results.push(str);
while(found) {
    found = false;
    while ((m = regex.exec(str)) !== null) {
        // This is necessary to avoid infinite loops with zero-width matches
        if (m.index === regex.lastIndex) {
            regex.lastIndex++;
        }

        if(m.length > 0) {
            found = true;
            results.push(m[0]);
            str = m[1];
        }
    }
}
results.push(str);
results = results.reverse();
// Concat this onto another array and keep concatenating for the other strings
console.log(results);
</code>```

You will just need to loop this over your array, store the results in a temp array and keep concatenating them onto a final array.

https://jsfiddle.net/9pa3hr46/

Body:
Note:
At this point in time, I'm unable to word the question title better. If someone is able to put it accross better, please go right ahead!

What I have:

var array = ["authentication.$.order", "difference.$.user.$.otherinformation", ... , ...]

What I need:

["authentication", "authentication.$", "authentication.$.order",
"difference", "difference.$", "difference.$.user", "difference.$.user.$",
"difference.$.user.$.otherinformation"]

Basically, wherevever I see .$., I need to preserve it, then append everything before the occourrence of .$. along with everything before the occourrence of .$

Example:

difference.$.user.$.otherinformation should be parsed to contain:

difference
difference.$
difference.$.user
difference.$.user.$
difference.$.user.$.otherinformation

I'm strongly feeling that some sort of recursion is to be involved here, but have not progressed in that direction yet.

Below is my implementation for the same, but unfortunately, my when my substring matches the first occourrence of .$., it stops and does not proceed to further check for other occurrences of .$. in the same string.

How best can I take this to closure?

Current flawed implementation:

for(var i=0; i<array.length; i++){
    //  next, replace all array field references with $ as that is what autoform's pick() requires
    //  /\.\d+\./g,".$." ==> replace globally .[number]. with .$.
    array[i] = array[i].replace(/\.\d+\./g,".$.");
        if(array[i].substring(0, array[i].lastIndexOf('.$.'))){
            console.log("Substring without .$.  " + array[i].substring(0, array[i].indexOf('.$.')));
            console.log("Substring with .$ " + array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
            array.push(array[i].substring(0, array[i].indexOf('.$.')).concat(".$"));
            array.push(array[i].substring(0, array[i].indexOf('.$.')));
            }
        }
    // finally remove any duplicates if any
    array = _.uniq(array);

Body:
I used a Regex expression to grab everything until the last occurrence of .$ and the chopped it, until there was nothing left. Reverse at the end.

let results = [];
let found = true;

const regex = /^(.*)\.\$/g;
let str = `difference.\$.user.\$.otherinformation`;
let m;

results.push(str);
while(found) {
    found = false;
    while ((m = regex.exec(str)) !== null) {
        // This is necessary to avoid infinite loops with zero-width matches
        if (m.index === regex.lastIndex) {
            regex.lastIndex++;
        }

        if(m.length > 0) {
            found = true;
            results.push(m[0]);
            str = m[1];
        }
    }
}
results.push(str);
results = results.reverse();
// Concat this onto another array and keep concatenating for the other strings
console.log(results);

You will just need to loop this over your array, store the results in a temp array and keep concatenating them onto a final array.

https://jsfiddle.net/9pa3hr46/


问:
wso2apim configure scopes with roles that have white spaces
I had tried configure scopes with wso2apim, but my ldap groups has spaces in their names, someone already had that problem?

Someone know how to fix this problem?

Thank you

答:
I discovered what is the problem, in the package: org.wso2.carbon.apimgt.impl.handlers

The class ScopesIssuer, has the line code:

```<code>List<String> roleList = new ArrayList<String>(Arrays.asList(roles.replaceAll(" ", "").split(",")));
</code>```

Where the role list suffer a replace and all spaces are removed from the list, this cause problems with groups with white spaces, I have replace this logic and resolv that problem.

Version: APIM 1.9.1

Thank you.

Body:
I discovered what is the problem, in the package: org.wso2.carbon.apimgt.impl.handlers

The class ScopesIssuer, has the line code:

List<String> roleList = new ArrayList<String>(Arrays.asList(roles.replaceAll(" ", "").split(",")));

Where the role list suffer a replace and all spaces are removed from the list, this cause problems with groups with white spaces, I have replace this logic and resolv that problem.

Version: APIM 1.9.1

Thank you.


问:
Not getting output for simple java program to find greatest prime factor
```<code>class LargestPrimeFactor{
    public static void main(String args[]){
        long p=0L;
        long n=600851475143L;
        for(long i=2L;i<(n/2);i++){
            if((BigInteger.valueOf(i)).isProbablePrime(1)){
                if(n%i==0){
                    p=i;
                }
            }
        }
        System.out.println(p);
    }
}
</code>```

It's problem 3 from Project Euler. I compiled it and no errors showed up. But am not getting any output. Whats the reason?

答:
EDITED

The int data type can store values upto 2,147,483,647. To store numbers beyond that, use long.

```<code>long n = 600851475143L;
</code>```

Not 600851475143 L, as that one space before L causes the system to not register it.

Also, int i in the for loop should be long i.

Body:
class LargestPrimeFactor{
    public static void main(String args[]){
        long p=0L;
        long n=600851475143L;
        for(long i=2L;i<(n/2);i++){
            if((BigInteger.valueOf(i)).isProbablePrime(1)){
                if(n%i==0){
                    p=i;
                }
            }
        }
        System.out.println(p);
    }
}

It's problem 3 from Project Euler. I compiled it and no errors showed up. But am not getting any output. Whats the reason?

Body:
EDITED

The int data type can store values upto 2,147,483,647. To store numbers beyond that, use long.

long n = 600851475143L;

Not 600851475143 L, as that one space before L causes the system to not register it.

Also, int i in the for loop should be long i.


问:
Register a CustomConverter in a MongoTemplate with Spring Boot
How can I register a custom converter in my MongoTemplate with Spring Boot? I would like to do this only using annotations if possible.</p>

答:
If you only want to override the custom converters portion of the Spring Boot configuration, you only need to create a configuration class that provides a @Bean for the custom converters.  This is handy if you don't want to override all of the other Mongo settings (URI, database name, host, port, etc.) that Spring Boot has wired in for you from your application.properties file.

    @Configuration
    public class MongoConfig
    {

        @Bean
        public CustomConversions customConversions()
        {
            List<Converter<?, ?>> converterList = new ArrayList<Converter<?, ?>>();
            converterList.add(new MyCustomWriterConverter());
            return new CustomConversions(converterList);
        }
    }
```

<p>This will also only work if you've enabled AutoConfiguration and excluded the DataSourceAutoConfig:</p>

<pre class="lang-java prettyprint-override"><code>@SpringBootApplication(scanBasePackages = {"com.mypackage"})
@EnableMongoRepositories(basePackages = {"com.mypackage.repository"})
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
public class MyApplication
{

    public static void main(String[] args)
    {
        SpringApplication.run(MyApplication.class, args);
    }
}
</code>```

In this case, I'm setting a URI in the application.properties file and using Spring data repositories:

```<code>#mongodb settings
spring.data.mongodb.uri=mongodb://localhost:27017/mydatabase
spring.data.mongodb.repositories.enabled=true
</code>```

Body:
If you only want to override the custom converters portion of the Spring Boot configuration, you only need to create a configuration class that provides a @Bean for the custom converters.  This is handy if you don't want to override all of the other Mongo settings (URI, database name, host, port, etc.) that Spring Boot has wired in for you from your application.properties file.

    @Configuration
    public class MongoConfig
    {

        @Bean
        public CustomConversions customConversions()
        {
            List<Converter<?, ?>> converterList = new ArrayList<Converter<?, ?>>();
            converterList.add(new MyCustomWriterConverter());
            return new CustomConversions(converterList);
        }
    }

This will also only work if you've enabled AutoConfiguration and excluded the DataSourceAutoConfig:

@SpringBootApplication(scanBasePackages = {"com.mypackage"})
@EnableMongoRepositories(basePackages = {"com.mypackage.repository"})
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
public class MyApplication
{

    public static void main(String[] args)
    {
        SpringApplication.run(MyApplication.class, args);
    }
}

In this case, I'm setting a URI in the application.properties file and using Spring data repositories:

#mongodb settings
spring.data.mongodb.uri=mongodb://localhost:27017/mydatabase
spring.data.mongodb.repositories.enabled=true


问:
Android get resource from context's theme programmatically (without direct access to "R")
I split my code into two project to have some kind of SDK with functionalities common to all my future projects.

So I'm having the problem of retrieving values in XML files of one project from the other. For instance, I had to retrieve a color in styles.xml, a custom one (that I defined in attrs.xml, named "iconColor"). Here's what I did:

```<code>TypedValue typedValue = new TypedValue();
Resources.Theme theme = context.getTheme();
int colorIdentifier = context.getResources().getIdentifier("iconColor", "attr", context.getPackageName());
if (theme.resolveAttribute(colorIdentifier, typedValue, true)) {
    return typedValue.data;
}
else {
    return 0;
}
</code>```

and it's working fine from one project to another. Now for another purpose, I wanted to retrieve the colorPrimary of my context's theme. I tweaked my code to have a generic function, here's how it is now:

```<code>/**
 * Retrieves a resource from context's theme using the resource id
 *
 * @param resId the resource id, ie. android.R.attr.colorPrimary
 * @return the resource value, or null if not found
 */
public @Nullable Integer getResourceFromTheme(int resId) {
    Integer result = null;

    TypedValue typedValue = new TypedValue();
    Resources.Theme theme = context.getTheme();
    if (theme.resolveAttribute(resId, typedValue, true)) {
        result = typedValue.data;
    }

    return result;
}

/**
 * Retrieves a resource from context's theme using the resource name
 *
 * @param resName the resource name, ie. "colorPrimary"
 * @return the resource value, or null if not found
 */
public @Nullable Integer getResourceFromTheme(@NonNull String resName) {
    int resId = context.getResources().getIdentifier(resName, "attr", context.getPackageName());
    return getResourceFromTheme(resId);
}
</code>```

so that I could, in theory retrieve custom as well as native properties using android.R. However, if it's still working fo my costom iconColor property, I can't retrieve colorPrimary, it's returning incorrect data. Even weirder, I got different values when I try to use one method or the other, which means I got the code wrong:

答: Okay so the functions are working fine but I made two mistakes, xxxx is a ColorRes and aaaa/bbbb are ColorInt, and I was calling my function with android.R.attr.colorPrimary instead of R.attr.colorPrimary.</p>

Body:
I split my code into two project to have some kind of SDK with functionalities common to all my future projects.

So I'm having the problem of retrieving values in XML files of one project from the other. For instance, I had to retrieve a color in styles.xml, a custom one (that I defined in attrs.xml, named "iconColor"). Here's what I did:

TypedValue typedValue = new TypedValue();
Resources.Theme theme = context.getTheme();
int colorIdentifier = context.getResources().getIdentifier("iconColor", "attr", context.getPackageName());
if (theme.resolveAttribute(colorIdentifier, typedValue, true)) {
    return typedValue.data;
}
else {
    return 0;
}

and it's working fine from one project to another. Now for another purpose, I wanted to retrieve the colorPrimary of my context's theme. I tweaked my code to have a generic function, here's how it is now:

/**
 * Retrieves a resource from context's theme using the resource id
 *
 * @param resId the resource id, ie. android.R.attr.colorPrimary
 * @return the resource value, or null if not found
 */
public @Nullable Integer getResourceFromTheme(int resId) {
    Integer result = null;

    TypedValue typedValue = new TypedValue();
    Resources.Theme theme = context.getTheme();
    if (theme.resolveAttribute(resId, typedValue, true)) {
        result = typedValue.data;
    }

    return result;
}

/**
 * Retrieves a resource from context's theme using the resource name
 *
 * @param resName the resource name, ie. "colorPrimary"
 * @return the resource value, or null if not found
 */
public @Nullable Integer getResourceFromTheme(@NonNull String resName) {
    int resId = context.getResources().getIdentifier(resName, "attr", context.getPackageName());
    return getResourceFromTheme(resId);
}

so that I could, in theory retrieve custom as well as native properties using android.R. However, if it's still working fo my costom iconColor property, I can't retrieve colorPrimary, it's returning incorrect data. Even weirder, I got different values when I try to use one method or the other, which means I got the code wrong:


问:
Is it OK for Scrapy's request_fingerprint method to return None?
I'd like to override Scrapy's default RFPDupefilter class as follows:

```<code>from scrapy.dupefilters import RFPDupeFilter

class URLDupefilter(RFPDupeFilter):

    def request_fingerprint(self, request):
        if not request.url.endswith('.xml'):
            return request.url
</code>```

The rationale is that I would like to make the requests.seen 'human-readable' by using the scraped URLs (which are sufficiently unique) rather than a hash. However, I would like to omit URLs ending with .xml (which correspond to sitemap pages).

Like this, the request_fingerprint method will return None if the requests URL ends with .xml. Is this a valid implementation of a dupefilter?

答:
If you look into request_seen() method of DupeFilter class you can see how scrapy compares fingerprints:

```<code>def request_seen(self, request):
    fp = self.request_fingerprint(request)
    if fp in self.fingerprints:
        return True
    self.fingerprints.add(fp)
    if self.file:
        self.file.write(fp + os.linesep)
</code>```

fp in self.fingerprints, in your case this would resolve to None in {None}, since your fingerprint is None and self.fingerprints is a set type object. This is valid python and resolves properly.

So yes, you can return None.

Edit: However this will let through first xml response, since the fingerprints set will not have None fingerprint in it yet. Ideally you want to fix request_seen method in your dupefilter as well to simply return False if fingerprint is None.

Body:
I'd like to override Scrapy's default RFPDupefilter class as follows:

from scrapy.dupefilters import RFPDupeFilter

class URLDupefilter(RFPDupeFilter):

    def request_fingerprint(self, request):
        if not request.url.endswith('.xml'):
            return request.url

The rationale is that I would like to make the requests.seen 'human-readable' by using the scraped URLs (which are sufficiently unique) rather than a hash. However, I would like to omit URLs ending with .xml (which correspond to sitemap pages).

Like this, the request_fingerprint method will return None if the requests URL ends with .xml. Is this a valid implementation of a dupefilter?

Body:
If you look into request_seen() method of DupeFilter class you can see how scrapy compares fingerprints:

def request_seen(self, request):
    fp = self.request_fingerprint(request)
    if fp in self.fingerprints:
        return True
    self.fingerprints.add(fp)
    if self.file:
        self.file.write(fp + os.linesep)

fp in self.fingerprints, in your case this would resolve to None in {None}, since your fingerprint is None and self.fingerprints is a set type object. This is valid python and resolves properly.

So yes, you can return None.

Edit: However this will let through first xml response, since the fingerprints set will not have None fingerprint in it yet. Ideally you want to fix request_seen method in your dupefilter as well to simply return False if fingerprint is None.


问:
Java: Strange result after decompiling
I have a strange jar file, it contains some class that when I use JD Decompiler, it show a segment like this:

```<code>public final void a(ak aa) {
    this.jdField_a_of_type_Ak = aa;
}

public final void a(cn ccn) {
  this.jdField_a_of_type_Cn = ccn;
}

public final cN a() {
  return this.jdField_a_of_type_CN;
}

public final void a() {
  super.b();
}

public final boolean a() {
    return this.jdField_a_of_type_Boolean;
}
</code>```

I just wonder why a/an compiler/obfuscator can product a class byte code like that, I mean the method signature. Did any one know a obfuscator can do this?

答: ... An obfuscator produces method names/signatures like this because that's its job. Any obfuscator should work for this purpose.</p>

Title: Java: Strange result after decompiling

Body:
I have a strange jar file, it contains some class that when I use JD Decompiler, it show a segment like this:

public final void a(ak aa) {
    this.jdField_a_of_type_Ak = aa;
}

public final void a(cn ccn) {
  this.jdField_a_of_type_Cn = ccn;
}

public final cN a() {
  return this.jdField_a_of_type_CN;
}

public final void a() {
  super.b();
}

public final boolean a() {
    return this.jdField_a_of_type_Boolean;
}

I just wonder why a/an compiler/obfuscator can product a class byte code like that, I mean the method signature. Did any one know a obfuscator can do this?

ContentLicense: CC BY-SA 2.5


问:
How include 3rd party jars in maven project (compile, build, package) where adding local maven repo is not an option?
We have a git project that has some 3rd party jars which are not available in any Maven repo and are in a "lib" folder in the project. I need to include them for compiling, building and then package them into the WAR in WEB-INF/lib.

I cannot add them as a local maven repo from the command line because this projects needs to be buildable for anyone cloning the repo without requiring them to run extra commands (I have no way around this requirement).

I saw some people suggesting System scope but that then Maven won't package them into your WAR:

```<code><dependency>
    <groupId>com.roufid.tutorials</groupId>
    <artifactId>example-app</artifactId>
    <version>1.0</version>
    <scope>system</scope>
    <systemPath>${basedir}/lib/yourJar.jar</systemPath>
</dependency>
</code>```

How do I get these jars to be used for compiling/inspection, building and then packaged into the WAR?

答:
I'll assume you've verified that whatever mechanism you might use to distribute these jars would be in compliance with the relevant licenses.  If it would, then it seems there would be little reason for the jars' creators not to provide for official Maven distribution, so your best option might be to lobby for them to do that.  But if not, and yet for some reason they'll allow for you distributing the jar (either through cloning of your repo, or via a separate Maven repo you maintain):

There are several ways.  I give preference to approaches that don't put the jars in the git repo.

Publish a Maven Repo

So it's possible to host a public-facing repo and serve the artifacts that way.  The pom can add your public-facing repo to the build, so that those who clone can build without having to run any special commands.

Running your own repo isn't terribly difficult.  The OSS versions of Nexus or Artifactory jFrog would probably be perfectly capable.

But, if we're assuming the authors' refusal to publish their own jars via Maven means they don't want them distributed that way, then there's no reason to spend much time on the details of this option.  So moving on...

Distribution in the Git Repo

I guess this is what you're doing, though again if Maven distribution violates the license I'd make sure you're splitting hairs the right way in thinking that this doesn't.

So the question would be how to get Maven to deal with the artifacts distributed in this way, and again there are some options.

Your objection to putting the jars in the local repo is that it would require extra commands of the user; but actually this could be automated in the "validate" phase of the build.  Binding install:install-file to the validate phase should work.

Alternately, your objection to using system scope is that the file isn't copied into the final war.  You might be able to use the dependency plugin to force the issue, but I'm not sure of that.  What I am sure of is you could treat the directory containing the jars as a web resource with suitable configuration in the war plugin.  (You'd want it to be treated as unfiltered and to map to the WEB-INF/lib folder.)

In any case, if you distribute jars (or other large binaries) in the git repo, I strongly recommend you look at git lfs.  This will require one-time configuration by each of your users, but it will prevent your repo from gradually becoming bloated and unusable.

Body:
We have a git project that has some 3rd party jars which are not available in any Maven repo and are in a "lib" folder in the project. I need to include them for compiling, building and then package them into the WAR in WEB-INF/lib.

I cannot add them as a local maven repo from the command line because this projects needs to be buildable for anyone cloning the repo without requiring them to run extra commands (I have no way around this requirement).

I saw some people suggesting System scope but that then Maven won't package them into your WAR:

<dependency>
    <groupId>com.roufid.tutorials</groupId>
    <artifactId>example-app</artifactId>
    <version>1.0</version>
    <scope>system</scope>
    <systemPath>${basedir}/lib/yourJar.jar</systemPath>
</dependency>

How do I get these jars to be used for compiling/inspection, building and then packaged into the WAR?


问:
Bootstrap3 datetime picker 24Hours option not working
I am using bootstrap 3 datetime picker from the  link in
eonasdan.github
but when I try to set an option for use24Hours I see a console error in line 1477 where key is the use24Hours?

```<code> throw new TypeError('option ' + key + ' is not recognized!');
</code>```

I am using version /*! version : 4.17.37 for bootstrap-datetimepicker.js

Here is how I am creating my datetime picker in javsacript.

```<code>("#mydiv").datetimepicker({ use24Hours: false });
</code>```

I also tried small case for use24Hours as follows

```<code>("#mydiv").datetimepicker({ use24hours: false });
</code>```

Based on the Answer  that is the way to do it. What is wrong with mine?

Just as a note:
I can't use
format:HH:mm because I that would change the whole datetime picker to just use the time format. but what I want is to keep the date format as of the current language I selected fr,us...etc but alter the time as I want regardless of the culture.

答:
For those still looking for an answer, just change the format to HH:mm

```<code>$("#id").datetimepicker({
    format: 'DD/MM/YYYY HH:mm'
});
</code>```

Note: I've also swapped the months and days around as that makes more sense to me

Body:
I am using bootstrap 3 datetime picker from the  link in
eonasdan.github
but when I try to set an option for use24Hours I see a console error in line 1477 where key is the use24Hours?

 throw new TypeError('option ' + key + ' is not recognized!');

I am using version /*! version : 4.17.37 for bootstrap-datetimepicker.js

Here is how I am creating my datetime picker in javsacript.

("#mydiv").datetimepicker({ use24Hours: false });

I also tried small case for use24Hours as follows

("#mydiv").datetimepicker({ use24hours: false });

Based on the Answer  that is the way to do it. What is wrong with mine?

Just as a note:
I can't use
format:HH:mm because I that would change the whole datetime picker to just use the time format. but what I want is to keep the date format as of the current language I selected fr,us...etc but alter the time as I want regardless of the culture.

Body:
For those still looking for an answer, just change the format to HH:mm

$("#id").datetimepicker({
    format: 'DD/MM/YYYY HH:mm'
});

Note: I've also swapped the months and days around as that makes more sense to me


问:
Error occured in Retrofit connection
My interface  </p>

```<code>@POST("/insert.php")
void  login(Callback<Response> callback);
</code>```

<p>Java code  </p>

```<code>Retrofit adapter = new Retrofit.Builder()
                       .baseUrl(ROOT_URL) //Setting the Root URL
                       .addConverterFactory(GsonConverterFactory.create())
                       .build(); //Finally building the adapter

Register_Retrofit api = adapter.create(Register_Retrofit.class);

api.login( new Callback<Response>() {
    public void onResponse(Call<Response> call, Response<Response> response) {

    }

    public void onFailure(Call<Response> call, Throwable t) {

    }

});
</code>```

答:
Your login method return void, so you need to define it like this:

```<code>@POST("/insert.php")
Call<Void> login();
</code>```

Then, to call the login method try this:

```<code>Retrofit adapter = new Retrofit.Builder()
                       .baseUrl(ROOT_URL) //Setting the Root URL
                       .addConverterFactory(GsonConverterFactory.create())
                       .build(); //Finally building the adapter

Register_Retrofit api = adapter.create(Register_Retrofit.class);
Call<Void> loginCall = api.login();
loginCall.enqueue(new Callback<Void>() {
     public void onResponse(Call<Void> call, Response<Void> response) {
          ...
     }

     public void onFailure(Call<Void> call, Throwable t) {
          ...
     }
});
</code>```

Title: Error occured in Retrofit connection

Body:
My interface

@POST("/insert.php")
void  login(Callback<Response> callback);

Java code

Retrofit adapter = new Retrofit.Builder()
                       .baseUrl(ROOT_URL) //Setting the Root URL
                       .addConverterFactory(GsonConverterFactory.create())
                       .build(); //Finally building the adapter

Register_Retrofit api = adapter.create(Register_Retrofit.class);

api.login( new Callback<Response>() {
    public void onResponse(Call<Response> call, Response<Response> response) {

    }

    public void onFailure(Call<Response> call, Throwable t) {

    }

});

Body:
Your login method return void, so you need to define it like this:

@POST("/insert.php")
Call<Void> login();

Then, to call the login method try this:

Retrofit adapter = new Retrofit.Builder()
                       .baseUrl(ROOT_URL) //Setting the Root URL
                       .addConverterFactory(GsonConverterFactory.create())
                       .build(); //Finally building the adapter

Register_Retrofit api = adapter.create(Register_Retrofit.class);
Call<Void> loginCall = api.login();
loginCall.enqueue(new Callback<Void>() {
     public void onResponse(Call<Void> call, Response<Void> response) {
          ...
     }

     public void onFailure(Call<Void> call, Throwable t) {
          ...
     }
});


问:
Converting Date column to ODBC canonical format in SQL Server 2005
I'm dealing with the issue of converting a Date column to an ODBC canonical format in my Microsoft SQL Server 2008.

I have the following SQL query in php:

```<code>$sql_query = "UPDATE [$connectionInfo[Database]].[dbo].[log_record] SET [lock]='0' WHERE CONVERT [Date] = '".json_encode($value['Date']['date'])."'
</code>```

Basically, the part '".json_encode($value['Date']['date'])."' works and is printed as '"2017-06-01 00:00:00"'. But it's the [Date] column that's the problem. How can I compare them? It generates the following error:

error: Conversion failed when converting date and/or time from
  character string. query: UPDATE [dba_sql].[dbo].[log_record] SET
  [lock]='0' WHERE [Date] = '"2017-06-01 00:00:00"'

I attempted the following, but in vain:

```<code>$sql_query = "UPDATE [$connectionInfo[Database]].[dbo].[log_record] SET [lock]='0' WHERE CONVERT CONVERT(varchar, Date, 120) = '".json_encode($value['Date']['date'])."'
</code>```

答:
Get rid of the double quotes, and remove the convert hanging in your code. There is no need to convert the date in your table to a character type for your comparison.

The following is valid: select convert(date,'2017-06-01 00:00:00')

This is not: select convert(date,'"2017-06-01 00:00:00"')

rextester demo: http://rextester.com/NUNAD13593

Also note: The only truly safe formats for date/time literals in SQL Server, at least for datetime and smalldatetime, are: YYYYMMDD and YYYY-MM-DDThh:mm:ss[.nnn]

Reference: Bad habits to kick : mis-handling date / range queries - Aaron Bertrand

For example, if you have a language setting that implicitly sets the dateformat to dmy, then the same input for two different conversions can yield different output, if not an error:

```<code>set language 'british';
select toDatatype = 'datetime' ,val = convert(char(10),convert(datetime,'2017-06-01 00:00:00'),120)
union all
select toDatatype = 'date', val = convert(char(10),convert(date,'2017-06-01 00:00:00'),120)
</code>```

returns:

```<code>+------------+------------+
| toDatatype |    val     |
+------------+------------+
| datetime   | 2017-01-06 |
| date       | 2017-06-01 |
+------------+------------+
</code>```

and select convert(datetime,'2017-06-13') would return an error where as select convert(date,'2017-06-13') would return 2017-06-13.

Body:
I'm dealing with the issue of converting a Date column to an ODBC canonical format in my Microsoft SQL Server 2008.

I have the following SQL query in php:

$sql_query = "UPDATE [$connectionInfo[Database]].[dbo].[log_record] SET [lock]='0' WHERE CONVERT [Date] = '".json_encode($value['Date']['date'])."'

Basically, the part '".json_encode($value['Date']['date'])."' works and is printed as '"2017-06-01 00:00:00"'. But it's the [Date] column that's the problem. How can I compare them? It generates the following error:

error: Conversion failed when converting date and/or time from
  character string. query: UPDATE [dba_sql].[dbo].[log_record] SET
  [lock]='0' WHERE [Date] = '"2017-06-01 00:00:00"'

I attempted the following, but in vain:

$sql_query = "UPDATE [$connectionInfo[Database]].[dbo].[log_record] SET [lock]='0' WHERE CONVERT CONVERT(varchar, Date, 120) = '".json_encode($value['Date']['date'])."'

Body:
Get rid of the double quotes, and remove the convert hanging in your code. There is no need to convert the date in your table to a character type for your comparison.

The following is valid: select convert(date,'2017-06-01 00:00:00')

This is not: select convert(date,'"2017-06-01 00:00:00"')

rextester demo: http://rextester.com/NUNAD13593

Also note: The only truly safe formats for date/time literals in SQL Server, at least for datetime and smalldatetime, are: YYYYMMDD and YYYY-MM-DDThh:mm:ss[.nnn]

Reference: Bad habits to kick : mis-handling date / range queries - Aaron Bertrand

For example, if you have a language setting that implicitly sets the dateformat to dmy, then the same input for two different conversions can yield different output, if not an error:

set language 'british';
select toDatatype = 'datetime' ,val = convert(char(10),convert(datetime,'2017-06-01 00:00:00'),120)
union all
select toDatatype = 'date', val = convert(char(10),convert(date,'2017-06-01 00:00:00'),120)

returns:

+------------+------------+
| toDatatype |    val     |
+------------+------------+
| datetime   | 2017-01-06 |
| date       | 2017-06-01 |
+------------+------------+

and select convert(datetime,'2017-06-13') would return an error where as select convert(date,'2017-06-13') would return 2017-06-13.


问:
Filter a Pandas DataFrame Through a Dictionary
I have a pandas dataframe with a number of columns. (Please see the table below.) Each column belongs to a group categorization G1-G4. This mapping of groups is in a data dictionary. If I want to filter the columns in the pandas dataframe based on the grouping data dictionary, for example to filter out all G3 and produce the resulting table below, what is the most efficient way of doing this?

Thank you.

答:
Say the DataFrame is:

```<code>In [7]: df = pd.DataFrame({'T1': [1], 'T2': [2], 'T3': [3], 'T4': [4], 'T5': [5]})

In [8]: df
Out[8]:
   T1  T2  T3  T4  T5
0   1   2   3   4   5
</code>```

And say the filtering dict is:

```<code>In [9]: filter_dict = {'T1': 'G1', 'T2': 'G3', 'T3': 'G3', 'T4': 'G1', 'T5': 'G2'}
</code>```

You can select all columns except those belonging to G3 like this:

```<code>In [6]: df[[col_name for col_name, group in filter_dict.items() if group != 'G3']]
Out[6]:
   T5  T4  T1
0   5   4   1
</code>```

Body:
Say the DataFrame is:

In [7]: df = pd.DataFrame({'T1': [1], 'T2': [2], 'T3': [3], 'T4': [4], 'T5': [5]})

In [8]: df
Out[8]:
   T1  T2  T3  T4  T5
0   1   2   3   4   5

And say the filtering dict is:

In [9]: filter_dict = {'T1': 'G1', 'T2': 'G3', 'T3': 'G3', 'T4': 'G1', 'T5': 'G2'}

You can select all columns except those belonging to G3 like this:

In [6]: df[[col_name for col_name, group in filter_dict.items() if group != 'G3']]
Out[6]:
   T5  T4  T1
0   5   4   1


问:
Count lines within a Fortran loop
I have a time series data that goes from 0 to 15000 lines and a few columns. I want to separate the data in intervals of 60 seconds and count the amount of data that are inside each interval.

I created a do loop that correctly creates the intervals of 60s from the beggining to the end of the file, however, I don't know how to count the number of lines that are inside each interval.

The end result that I'm looking for is to have two columns as a result:
interval number and number of lines.

Here is what I got so far:

```<code>program flash_selection

implicit none

integer i, zero, qtd, cellnumb, flashcell, tipo, segment

real time, Etrig, xtrig, ytrig, ztrig, poscharge, negq, chargeneutr

open(1,file='my_file.txt',status='OLD')

read(1,*)

do

read(1,*,end=100) qtd, time, cellnumb, flashcell, tipo, segment, Etrig, xtrig, ytrig, ztrig, poscharge, negq, chargeneutr

do i = 1, 420

open(2,file='test.txt')

if (time .GE. (i-1)*60 .AND. time .LT. i*60) then

write(2,*) qtd, time, tipo, segment, Etrig, xtrig, ytrig, ztrig, poscharge, negq, chargeneutr

end if

end do
end do
</code>```

The IF statement correctly separates the data according to what I wanted, the only thing left is to know the amount of lines that there are on each interval of 60.

答:
Just add a counter variable.  Increment counter every time through the loop.  When the IF test is successful, print out counter and then set it back to zero.

(BTW -- not sure you want your OPEN statement inside the loops.  And you should use file numbers greater than 10.)

Title: Count lines within a Fortran loop

Body:
I have a time series data that goes from 0 to 15000 lines and a few columns. I want to separate the data in intervals of 60 seconds and count the amount of data that are inside each interval.

I created a do loop that correctly creates the intervals of 60s from the beggining to the end of the file, however, I don't know how to count the number of lines that are inside each interval.

The end result that I'm looking for is to have two columns as a result:
interval number and number of lines.

Here is what I got so far:

program flash_selection

implicit none

integer i, zero, qtd, cellnumb, flashcell, tipo, segment

real time, Etrig, xtrig, ytrig, ztrig, poscharge, negq, chargeneutr

open(1,file='my_file.txt',status='OLD')

read(1,*)

do

read(1,*,end=100) qtd, time, cellnumb, flashcell, tipo, segment, Etrig, xtrig, ytrig, ztrig, poscharge, negq, chargeneutr

do i = 1, 420

open(2,file='test.txt')

if (time .GE. (i-1)*60 .AND. time .LT. i*60) then

write(2,*) qtd, time, tipo, segment, Etrig, xtrig, ytrig, ztrig, poscharge, negq, chargeneutr

end if

end do
end do

The IF statement correctly separates the data according to what I wanted, the only thing left is to know the amount of lines that there are on each interval of 60.


问:
Django: maintaining server side data whilst obtaining POST request?
I'm new to Django and now that I have complete the 7 part tutorial I am trying to learn more while making my own application.

One part of my application takes input from the user and then requires some non-trivial server-side calculation (e.g. the user will experience some wait) before producing the output. So instead of calculating everything all at once, I would like to have several small forms, each sending data to the server calculating part and waiting until it receives the next. For example:

my_app: will have a form which asks the user for three numbers, it will subtract the first from 100, then add the second number to the result, and finally multiply the new result by the third input:

e.g.

my form

1st: 5

2ed: 7

3rd: 2

result: (((100 - 5) + 7) * 2) = 204

While the above example is trivial, what I am doing will take some time (but, if it is not the first field, is dependent on the results from the previous result).

I learned how to properly have a view post to itself here:
Django: proper way to handle form with POST to the same page

So how can I have this serial calculation happen as the user enters the data for each part of the form? (and wait until the previous result is calculated or until the user posts the next information before continuing)

答:
My first answer would be "stash the responses in sessions". So something like this:

question1.py

```<code>if form.is_valid():
    request.session['height'] = height_calc(form.cleaned_data['height'])
</code>```

question2.py:

```<code>if form.is_valid():
    request.session['weight'] = weight_calc(request.session['height'],
                                            form.cleaned_data['weight'])
</code>```

question3.py:

```<code>if form.is_valid():
    # now we have everything so do the final calculation
    final_result = final_calc(request.session['height'],
                              request.session['weight'],
                              form.cleaned_data['favorite_color'])
</code>```

Body:
My first answer would be "stash the responses in sessions". So something like this:

question1.py

if form.is_valid():
    request.session['height'] = height_calc(form.cleaned_data['height'])

question2.py:

if form.is_valid():
    request.session['weight'] = weight_calc(request.session['height'],
                                            form.cleaned_data['weight'])

question3.py:

if form.is_valid():
    # now we have everything so do the final calculation
    final_result = final_calc(request.session['height'],
                              request.session['weight'],
                              form.cleaned_data['favorite_color'])


问:
How to prevent auto-closing of console after the execution of batch file
What command can I put at the end of a batch file to prevent auto-closing of the console after the execution of the file?</p>

答:
I know I'm late but my preferred way is:

```<code>:programend
pause>nul
GOTO programend
</code>```

In this way the user cannot exit using enter.

Body:
I know I'm late but my preferred way is:

:programend
pause>nul
GOTO programend

In this way the user cannot exit using enter.


问:
Magnific-popup: how to get image url from ?
Is it possible to force magnific-popup to get image url from 'src' attribute of img tag? This way there would be no need to wrap img with a tags.
I tried the code below, but it doesn't work. Returned error is 'undefined' url.

```<code><script type="text/javascript">
  $(document).ready(function(){
    $('div.gallery').magnificPopup({delegate: 'img'.attr('src') , type: 'image', gallery:{enabled:true}
    });
  });
</script>
</code>```

Anyways, is there any option to do with 'img' only, without 'a' tags?
Thanks!

答:
With magnificPopup 1.1.0

now you have to do like this if you want it to work.

```<code>   $(document).ready(function() {
        $('.myClass').magnificPopup({
            type: 'image',
            callbacks: {
                elementParse: function(item) {
                    item.src = item.el.attr('src');
                }
            }
        });
    });
</code>```

Title: Magnific-popup: how to get image url from <img src="...">?

Body:
Is it possible to force magnific-popup to get image url from 'src' attribute of img tag? This way there would be no need to wrap img with a tags.
I tried the code below, but it doesn't work. Returned error is 'undefined' url.

Anyways, is there any option to do with 'img' only, without 'a' tags?
Thanks!

Body:
With magnificPopup 1.1.0

now you have to do like this if you want it to work.

   $(document).ready(function() {
        $('.myClass').magnificPopup({
            type: 'image',
            callbacks: {
                elementParse: function(item) {
                    item.src = item.el.attr('src');
                }
            }
        });
    });


问:
Textmate: Remove a list of email addresses from a larger list
This feels like something that ought to be very simple, but i've been unable to find any way to accomplish it.

i have a list of over 10,000 email addresses in a text file. i have another, shorter list of 100+ addresses i need to remove from the original list. The problem is, there is an unknown number of addresses between each one to be removed.

i want to know: Is there a way to remove this list of addresses from the main list without doing a find/replace for each of the 100+ addresses individually?

答:
use grep:

```<code>grep -Fxvf smallfile mainfile
</code>```

it will print lines that, there are only in mainfile and not in smallfile.

Body:
use grep:

grep -Fxvf smallfile mainfile

it will print lines that, there are only in mainfile and not in smallfile.