问:
Searching list of words in scrabble with blank tile using Python
I have a scrabble challenge and have the following list of letters:

```<code>letters = ['t', 'u', 'v', 'w', 'x', 'y', 'z']
</code>```

And following list of words:

```<code>word = ['apple', 'whisky', 'yutz', 'xray', 'tux', 'zebra']
</code>```

Here is the code I'm using to find the words which can be made for a given list of letters:

```<code>def valid_word(word, letters):
    available_letters = letters[:]

    candidate = True

    for letter in word:
        if letter not in available_letters:
            candidate = False
        else:
            available_letters.remove(letter)
    if candidate == True:
        return candidate
</code>```

It gives me output that two words 'yutz' and 'tux' can be made for the current list of letters.

My challenge is what if we replace one of the letter in the list of letters with blank denoted as '_' in the list. For example 't' is replaced by '_' below:

```<code>letters = ['_', 'u', 'v', 'w', 'x', 'y', 'z']
</code>```

How can code still be able to find the same words 'yutz' and 'tux' but replace the missing letter? The expected output is 'yu_z' and '_ux'.

UPDATE:

Here is the code which I tried which does not completely work but kind of give direction to where I am going:

```<code>rack_list = []
    for letter in letters:
        if letter in string.ascii_lowercase:
            rack_list.append(letter)
        else:
            blank_count = user_input.count("_")

    def valid_word(word, rack):
    available_letters = rack_list[:]
    missed_counter = 0

    for letter in word:
        if letter in available_letters:
            available_letters.remove(letter)
        else:
            missed_counter += 1
    if missed_counter <= blank_count:
        for i in word:
            if i in available_letters:
                word += i
            else:
                word += "_"
        return word
</code>```

答:
There is probably a more efficient solution but this one would work:

```<code>letters = ['_', 'u', 'v', 'w', 'x', 'y', 'z']

words = ['apple', 'whisky', 'yutz', 'xray', 'tux', 'zebra']

def valid_word(words, letters):
    not_valid = []
    valid = []
    wild = 0

    for letter in letters:
        if letter == '_':
            wild += 1

    for word in words:
        missing = 0
        for letter in word:
            if letter not in letters:
                missing += 1
                if missing > wild:
                    not_valid.append(word)
                    break
        if word not in not_valid:
            s = ''
            for letter in word:
                if letter in letters:
                    s += letter
                else:
                    s += '_'
            valid.append(s)

    return valid

print(valid_word(words, letters))

#output
['yu_z', '_ux']
</code>```

So you create a not valid list, a valid list and a wild variable that counts the number of underscores in your letters list.

Then loop through your words. If the number of letters missing from the word is greater than the number of underscores counted by wild, add the word to your not valid list. Otherwise add it letter by letter your valid list, replacing any missing letters with an underscore.

Body:
I have a scrabble challenge and have the following list of letters:

letters = ['t', 'u', 'v', 'w', 'x', 'y', 'z']

And following list of words:

word = ['apple', 'whisky', 'yutz', 'xray', 'tux', 'zebra']

Here is the code I'm using to find the words which can be made for a given list of letters:

def valid_word(word, letters):
    available_letters = letters[:]

    candidate = True

    for letter in word:
        if letter not in available_letters:
            candidate = False
        else:
            available_letters.remove(letter)
    if candidate == True:
        return candidate

It gives me output that two words 'yutz' and 'tux' can be made for the current list of letters.

My challenge is what if we replace one of the letter in the list of letters with blank denoted as '_' in the list. For example 't' is replaced by '_' below:

letters = ['_', 'u', 'v', 'w', 'x', 'y', 'z']

How can code still be able to find the same words 'yutz' and 'tux' but replace the missing letter? The expected output is 'yu_z' and '_ux'.

UPDATE:

Here is the code which I tried which does not completely work but kind of give direction to where I am going:

rack_list = []
    for letter in letters:
        if letter in string.ascii_lowercase:
            rack_list.append(letter)
        else:
            blank_count = user_input.count("_")

    def valid_word(word, rack):
    available_letters = rack_list[:]
    missed_counter = 0

    for letter in word:
        if letter in available_letters:
            available_letters.remove(letter)
        else:
            missed_counter += 1
    if missed_counter <= blank_count:
        for i in word:
            if i in available_letters:
                word += i
            else:
                word += "_"
        return word

Body:
There is probably a more efficient solution but this one would work:

letters = ['_', 'u', 'v', 'w', 'x', 'y', 'z']

words = ['apple', 'whisky', 'yutz', 'xray', 'tux', 'zebra']

def valid_word(words, letters):
    not_valid = []
    valid = []
    wild = 0

    for letter in letters:
        if letter == '_':
            wild += 1

    for word in words:
        missing = 0
        for letter in word:
            if letter not in letters:
                missing += 1
                if missing > wild:
                    not_valid.append(word)
                    break
        if word not in not_valid:
            s = ''
            for letter in word:
                if letter in letters:
                    s += letter
                else:
                    s += '_'
            valid.append(s)

    return valid

print(valid_word(words, letters))

#output
['yu_z', '_ux']

So you create a not valid list, a valid list and a wild variable that counts the number of underscores in your letters list.

Then loop through your words. If the number of letters missing from the word is greater than the number of underscores counted by wild, add the word to your not valid list. Otherwise add it letter by letter your valid list, replacing any missing letters with an underscore.


来源: stackexchange

问:
Adding one day at a time from a starting date
Can someone show me a few lines of code on how to add one day to datetime?

Like if you had some initial date:

```<code>start_date = datetime.date(1847, 3, 30)
</code>```

and simply wanted to change it to (1847, 3, 31)

and then (1847, 4, 1)

and so on.

I'm new to Python and just trying to wrap my head around this import.

答:
```<code>startdate + datetime.timedelta(days=1)
</code>```

will give you the answer

ContentLicense: CC BY-SA 3.0

Body:
Can someone show me a few lines of code on how to add one day to datetime?

Like if you had some initial date:

start_date = datetime.date(1847, 3, 30)

and simply wanted to change it to (1847, 3, 31)

and then (1847, 4, 1)

and so on.

I'm new to Python and just trying to wrap my head around this import.

Body:
startdate + datetime.timedelta(days=1)

will give you the answer


问:
Scope of global array javascript
I am trying to load data from a csv and store it in an array of objects.  I know global variables are frowned upon but I can't think of a better way to store the data and access it from multiple functions.

Here is my code:

```<code>var mydata = new Array;
$(document).ready( function () {
    $.get('./datafile.csv', function(data) {
        var head = data.split("\n");
        for(var i = 1; i < head.length; i++){
            line = head[i].split(",");
            var obj = {
                index:i,
                img:line[0],
                caption:line[1],
                desc:line[2]
            };
            mydata.push(obj);
        }
        console.log(mydata); //1
    });
    console.log(mydata); //2
    //I then want to select various elements on my page and set some attributes to
    //an object in my data, but I can't since everything is undefined
});
</code>```

At the first spot it logs my data correctly, but at second spot it logs an empty array.  I read this article on global variables in JavaScript so I'm not sure what is going wrong.

答:
The second part (//2) runs too soon. When $.get executes, it just starts the HTTP request to get the CSV, but doesn't wait for it to finish - that's why you need to pass that function(data) in. After the request finishes, the callback function gets called, and it's there that you should continue your initialization.

So, your code should look something like that below. (if you need to use the data elsewhere, you can keep on using the global, but it's not needed just for this)

```<code>$(document).ready( function () {
    $.get('./datafile.csv', function(data) {
        var mydata = [];
        var head = data.split("\n");
        // ...

        console.log(mydata); //1
        continueSetup(mydata); // 2
    });
});

function continueSetup(mydata) {
    // do what you need
}
</code>```

Title: Scope of global array javascript

Body:
I am trying to load data from a csv and store it in an array of objects.  I know global variables are frowned upon but I can't think of a better way to store the data and access it from multiple functions.

Here is my code:

var mydata = new Array;
$(document).ready( function () {
    $.get('./datafile.csv', function(data) {
        var head = data.split("\n");
        for(var i = 1; i < head.length; i++){
            line = head[i].split(",");
            var obj = {
                index:i,
                img:line[0],
                caption:line[1],
                desc:line[2]
            };
            mydata.push(obj);
        }
        console.log(mydata); //1
    });
    console.log(mydata); //2
    //I then want to select various elements on my page and set some attributes to
    //an object in my data, but I can't since everything is undefined
});

At the first spot it logs my data correctly, but at second spot it logs an empty array.  I read this article on global variables in JavaScript so I'm not sure what is going wrong.

Body:
The second part (//2) runs too soon. When $.get executes, it just starts the HTTP request to get the CSV, but doesn't wait for it to finish - that's why you need to pass that function(data) in. After the request finishes, the callback function gets called, and it's there that you should continue your initialization.

So, your code should look something like that below. (if you need to use the data elsewhere, you can keep on using the global, but it's not needed just for this)

$(document).ready( function () {
    $.get('./datafile.csv', function(data) {
        var mydata = [];
        var head = data.split("\n");
        // ...

        console.log(mydata); //1
        continueSetup(mydata); // 2
    });
});

function continueSetup(mydata) {
    // do what you need
}


问:
How do I build a Play project with Hudson?
I have a project that's using the Play framework, and the corporate standard is that all projects should be built by Hudson. However, I cannot find out how to do this, as Hudson does not follow any Java standards, and requires the framework installed at the computer it runs on. I have tried to build the project with Maven (if I had managed this, adding it to Hudson should be quite simple), but I have failed to make it work. I tried the Play Maven module, but Maven claims it does not find the external repo that is listed (http://nexus.infin-it.fr/content/groups/public). This might be because I am behind a firewall. I also tried the recipe listed here, but the local maven build fails because it is unable to find org.playframework:play:1.1:jar.

Has anyone done this and can provide a howto?

答: In theory, you could put the full Play zip on your build or in in your repository, and then use Hudson to kick off an Ant script to download Play to the Hudson agent, unzip it, and then run commands on it.  It's a little clunky, but it should work.</p>

ContentLicense: CC BY-SA 2.5


问:
Weird issue during migration from Swift 2 to Swift 3: Initializer has different argument names from those required by protocol
I'm trying to migrate this (https://github.com/emilwojtaszek/leveldb-swift) project from Swift 2 to Swift 3. I've cleared all 100+ errors during migration except this following one:

```<code>Initializer 'init(bytes:count:)' has different argument names from those required by protocol 'KeyType' ('init(bytes:length:)')
</code>```

I was struggling to figure out the reason for it past couple of hours and getting no clue of what the problem is, any thoughts?

P.S.

Here is the link to project with current state of migration:

https://drive.google.com/file/d/1pR6-NrJFYGOwYyLLg_SbYNCQ9lyF6Ljc/view?usp=sharing

Here is an screenshot of the problem:

答:
In Swift 2 we used to have NSData with the initializer init(bytes:length:). Since Apple has done a lot of renaming in Swift 3, NSData is called Data and the initializer is called init(bytes:count:) now.

So everything you need to do is to update your KeyType protocol:

```<code>public protocol KeyType {
    init(bytes: UnsafeRawPointer, count: Int) // change "length" to "count"
    func withSlice(_ f: (Slice) -> ())
    func asData() -> Data
}
</code>```

Body:
I'm trying to migrate this (https://github.com/emilwojtaszek/leveldb-swift) project from Swift 2 to Swift 3. I've cleared all 100+ errors during migration except this following one:

Initializer 'init(bytes:count:)' has different argument names from those required by protocol 'KeyType' ('init(bytes:length:)')

I was struggling to figure out the reason for it past couple of hours and getting no clue of what the problem is, any thoughts?

P.S.

Here is the link to project with current state of migration:

https://drive.google.com/file/d/1pR6-NrJFYGOwYyLLg_SbYNCQ9lyF6Ljc/view?usp=sharing

Here is an screenshot of the problem:

Body:
In Swift 2 we used to have NSData with the initializer init(bytes:length:). Since Apple has done a lot of renaming in Swift 3, NSData is called Data and the initializer is called init(bytes:count:) now.

So everything you need to do is to update your KeyType protocol:

public protocol KeyType {
    init(bytes: UnsafeRawPointer, count: Int) // change "length" to "count"
    func withSlice(_ f: (Slice) -> ())
    func asData() -> Data
}


问:
Creating a list/array in excel using VBA to get a list of unique names in a column
I'm trying to create a list of unique names in a column but I've never understood how to use ReDim correctly, could someone help finish this off for me and explain how it's done or better suggest an alternative better/faster way.

```<code>Sub test()
    LastRow = Range("C65536").End(xlUp).Row
    For Each Cell In Range("C4:C" & LastRow)
        OldVar = NewVar
        NewVar = Cell
        If OldVar <> NewVar Then
            `x =...
        End If
    Next Cell
End Sub
</code>```

My Data is in the format of:

```<code>Stack
Stack
Stack
Stack
Stack
Overflow
Overflow
Overflow
Overflow
Overflow
Overflow
Overflow
Overflow
.com
.com
.com
</code>```

So essentially once it has the name once it will never popup again later on down in the list.

At the end the array should consist of:

```
    Stack
    Overflow
    .com
```

答:
I realize this is an old question, but I use a much simpler way. Typically I just grab the list that I need, either by query or copying an existing list or whatever, then remove the duplicates. We will assume for this answer that your list is already in column C, row 4, as per the original question. This method works for whatever size list you have and you can select header yes or no.</p>

```<code>Dim rng as range
Range("C4").Select
Set rng = Range(Selection, Selection.End(xlDown))
rng.RemoveDuplicates Columns:=1, Header:=xlYes
</code>```

Body:
I'm trying to create a list of unique names in a column but I've never understood how to use ReDim correctly, could someone help finish this off for me and explain how it's done or better suggest an alternative better/faster way.

Sub test()
    LastRow = Range("C65536").End(xlUp).Row
    For Each Cell In Range("C4:C" & LastRow)
        OldVar = NewVar
        NewVar = Cell
        If OldVar <> NewVar Then
            `x =...
        End If
    Next Cell
End Sub

My Data is in the format of:

Stack
Stack
Stack
Stack
Stack
Overflow
Overflow
Overflow
Overflow
Overflow
Overflow
Overflow
Overflow
.com
.com
.com

So essentially once it has the name once it will never popup again later on down in the list.

At the end the array should consist of:

    Stack
    Overflow
    .com

Body:
I realize this is an old question, but I use a much simpler way. Typically I just grab the list that I need, either by query or copying an existing list or whatever, then remove the duplicates. We will assume for this answer that your list is already in column C, row 4, as per the original question. This method works for whatever size list you have and you can select header yes or no.

Dim rng as range
Range("C4").Select
Set rng = Range(Selection, Selection.End(xlDown))
rng.RemoveDuplicates Columns:=1, Header:=xlYes


答:
I think you might be getting confused about the order of what is happening in your code. First of all, there is nothing wrong with using a global variable like this, especially if you are accessing it multiple times throughout your page (using events and such). Secondly, the reason you are seeing an empty array at your "second" spot in code is because that spot (#2) is actually getting executed before your get function has received the data and before #1.

get is an asynchronous function, which means that it waits to receive a response, and then executes the code inside (including #1). However, #2 gets executed immediately, while your array is still empty.

Title: Scope of global array javascript


问:
SQLite Import CSV File - Expected 3 columns, found 1948
I'm trying to import a CSV file (a Pokemon CSV file found at https://github.com/veekun/pokedex/blob/master/pokedex/data/csv/pokemon_species_names.csv ) into SQLite3. I've created a table using the following line:

sqlite> create table pokemon_species_names (pid integer, lang integer, pokemonName text, genus text);

Which works fine, of course, but when I try to import the above CSV file, I get the following error:

sqlite> .separator "," (EDIT: forgot to add this initially, but I did run this also)

sqlite> .import ./pokemon_species_names.csv pokemon_species_names

Error: ./pokemon_species_names.csv line 1: expected 4 columns of data but found 1948

Why would it be finding 1948 columns of data when there are only 4?

答: For anyone looking at this (5 years later), in TextWrangler on Mac, you select "Save As" Unicode(UTF-8) and Unix(LF).  Then .import will work like a charm.  </p>


问:
es6 arrow function not recognizing this operator after transpiling to javascript
I am working on a node app that is transpiled from typescript es6 to javascript es6.  I am using inversify to inject class dependencies into the appropriate classes.  When I try to access the member variables using the this operator I am getting the following error: "TypeError: Cannot read property 'organizationMemberRepository' of undefined".  I noticed I began to receive this error after moving to the arrow function and removing the "that = this" logic and I am running node in a docker container.  Here is the transpiled javascript file:

```<code>"use strict";
let OrganizationMemberService = class OrganizationMemberService {
    constructor(organizationRepository, organizationMemberRepository, authorizationService) {
        this.authenticateUser = (userName, password) => {
            return new Promise(function (resolve, reject) {
                console.log('about to check if user exists.....');
                this.organizationMemberRepository.findMemberByUserName(userName)
                    .then(function (organizationMember) {
                        if (organizationMember) {
                            organizationMember.comparePassword(password)
                                .then(function (same) {
                                    if (same) {
                                        let returnedObj = JSON.parse(JSON.stringify(organizationMember));
                                        resolve(returnedObj);
                                    }
                                    else {
                                        reject(new genericerror_1.GenericError("You username/password combination is incorrect."));
                                    }
                                })
                                .catch(function (err) {
                                    reject(err);
                                });
                        }
                        else {
                            reject(new genericerror_1.GenericError("You username/password combination is incorrect."));
                        }
                    });
            });
        };

        this.organizationRepository = organizationRepository;
        this.organizationMemberRepository = organizationMemberRepository;
        this.authorizationService = authorizationService;
    }
};
OrganizationMemberService = __decorate([
    inversify_1.injectable(),
    __param(0, inversify_1.inject(types_1.TYPES.IOrganizationRepository)), __param(1, inversify_1.inject(types_1.TYPES.IOrganizationMemberRepository)), __param(2, inversify_1.inject(types_1.TYPES.IAuthorizationService)),
    __metadata("design:paramtypes", [Object, Object, Object])
], OrganizationMemberService);
exports.OrganizationMemberService = OrganizationMemberService;
</code>```

I thought that es6 arrow operator was suppose to solve the issue of not being able to properly access the this operator issue?

答:
You need to change all .then(function () { syntax, to .then(()=> {
After that this is working as it should, see my changes below

```<code>let OrganizationMemberService = class OrganizationMemberService {
    constructor(organizationRepository, organizationMemberRepository, authorizationService) {
        this.authenticateUser = (userName, password) => {
            return new Promise( (resolve, reject) => {
                console.log('about to check if user exists.....');
                this.organizationMemberRepository.findMemberByUserName(userName)
                    .then( (organizationMember) => {
                        if (organizationMember) {
                            organizationMember.comparePassword(password)
                                .then( (same) => {
                                    if (same) {
                                        let returnedObj = JSON.parse(JSON.stringify(organizationMember));
                                        resolve(returnedObj);
                                    }
                                    else {
                                        reject(new genericerror_1.GenericError("You username/password combination is incorrect."));
                                    }
                                })
                                .catch((err) => {
                                    reject(err);
                                });
                        }
                        else {
                            reject(new genericerror_1.GenericError("You username/password combination is incorrect."));
                        }
                    });
            });
        };

        this.organizationRepository = organizationRepository;
        this.organizationMemberRepository = organizationMemberRepository;
        this.authorizationService = authorizationService;
    }
};
</code>```

Body:
I am working on a node app that is transpiled from typescript es6 to javascript es6.  I am using inversify to inject class dependencies into the appropriate classes.  When I try to access the member variables using the this operator I am getting the following error: "TypeError: Cannot read property 'organizationMemberRepository' of undefined".  I noticed I began to receive this error after moving to the arrow function and removing the "that = this" logic and I am running node in a docker container.  Here is the transpiled javascript file:

"use strict";
let OrganizationMemberService = class OrganizationMemberService {
    constructor(organizationRepository, organizationMemberRepository, authorizationService) {
        this.authenticateUser = (userName, password) => {
            return new Promise(function (resolve, reject) {
                console.log('about to check if user exists.....');
                this.organizationMemberRepository.findMemberByUserName(userName)
                    .then(function (organizationMember) {
                        if (organizationMember) {
                            organizationMember.comparePassword(password)
                                .then(function (same) {
                                    if (same) {
                                        let returnedObj = JSON.parse(JSON.stringify(organizationMember));
                                        resolve(returnedObj);
                                    }
                                    else {
                                        reject(new genericerror_1.GenericError("You username/password combination is incorrect."));
                                    }
                                })
                                .catch(function (err) {
                                    reject(err);
                                });
                        }
                        else {
                            reject(new genericerror_1.GenericError("You username/password combination is incorrect."));
                        }
                    });
            });
        };

        this.organizationRepository = organizationRepository;
        this.organizationMemberRepository = organizationMemberRepository;
        this.authorizationService = authorizationService;
    }
};
OrganizationMemberService = __decorate([
    inversify_1.injectable(),
    __param(0, inversify_1.inject(types_1.TYPES.IOrganizationRepository)), __param(1, inversify_1.inject(types_1.TYPES.IOrganizationMemberRepository)), __param(2, inversify_1.inject(types_1.TYPES.IAuthorizationService)),
    __metadata("design:paramtypes", [Object, Object, Object])
], OrganizationMemberService);
exports.OrganizationMemberService = OrganizationMemberService;

I thought that es6 arrow operator was suppose to solve the issue of not being able to properly access the this operator issue?

Body:
You need to change all .then(function () { syntax, to .then(()=> {
After that this is working as it should, see my changes below

let OrganizationMemberService = class OrganizationMemberService {
    constructor(organizationRepository, organizationMemberRepository, authorizationService) {
        this.authenticateUser = (userName, password) => {
            return new Promise( (resolve, reject) => {
                console.log('about to check if user exists.....');
                this.organizationMemberRepository.findMemberByUserName(userName)
                    .then( (organizationMember) => {
                        if (organizationMember) {
                            organizationMember.comparePassword(password)
                                .then( (same) => {
                                    if (same) {
                                        let returnedObj = JSON.parse(JSON.stringify(organizationMember));
                                        resolve(returnedObj);
                                    }
                                    else {
                                        reject(new genericerror_1.GenericError("You username/password combination is incorrect."));
                                    }
                                })
                                .catch((err) => {
                                    reject(err);
                                });
                        }
                        else {
                            reject(new genericerror_1.GenericError("You username/password combination is incorrect."));
                        }
                    });
            });
        };

        this.organizationRepository = organizationRepository;
        this.organizationMemberRepository = organizationMemberRepository;
        this.authorizationService = authorizationService;
    }
};


问:
Spring Kafka is Acknowledgement.acknowledge thread safe?
I am implementing an kafka based application where I would like to manually acknowledge incoming messages. Architecture forces me to do it in a separate thread.

The question is: is it possible and safe to execute Acknowledgement.acknowledge() in a different thread than consumer?

答:
Yes it is, as long as you use MANUAL and not MANUAL_IMMEDIATE, but I don't think you'll get what you expect.

Kafka doesn't track each message, just offsets within the partition.

Let's say message 1 arrives and you hand off to another thread. Then message 2 arrives and it is handed off to yet another thread.

When the offset for message 2 is ack'd, you are effectively acking both messages.


问:
PHP regexp for a valid regexp pattern
Is there a regexp to check if a string is a valid php regexp ?

In the back office of my application, the administrator define the data type and he can define a pattern as a regexp. For example /^[A-Z][a-zA-Z]+[a-z]$/ and in the front office, i use this pattern for validate user entries.
In my code i use the PHP preg_match function

```<code>preg_match($pattern, $user_entries);
</code>```

the first argument must be a valid PHP regexp, how can i be sure that $pattern is a valid regexp since it a user entrie in my back office.

Any idea ?

答:
Technically, any expression can be a valid regular expression...

So, the validity of a regular expression will depend on the rules you want to respect.

I would:

Identify the rules your regex must do

Use a preg_match of your own, or some combination of substr to validate the pattern

Title: PHP regexp for a valid regexp pattern

Body:
Is there a regexp to check if a string is a valid php regexp ?

In the back office of my application, the administrator define the data type and he can define a pattern as a regexp. For example /^[A-Z][a-zA-Z]+[a-z]$/ and in the front office, i use this pattern for validate user entries.
In my code i use the PHP preg_match function

preg_match($pattern, $user_entries);

the first argument must be a valid PHP regexp, how can i be sure that $pattern is a valid regexp since it a user entrie in my back office.

Any idea ?


问:
How to display confirm pop-up on top of custom window in Extjs?
I have a simple grid and when I click on a record a custom window shows up, then if I click on Open-Pop-Up button I want the confirm pop-up to show up right on top of the custom window. I'm using

```<code>customePanel.showAt(event.pageX, event.pageY);
</code>```

to show the custom window on top of the record that was clicked on based on the X and Y axis, and I'm trying to use the same functionality to show the confirm pop-up but I'm not having any luck.

Here's a working code:  FIDDLE

```<code> handler: function () {
         var x = Ext.MessageBox.confirm(
         'Confirm', 'Are you sure you want to see patient\'s chart?', callbackFunction);
            function callbackFunction(btn) {
              var self = this;
              if(btn === 'yes') {
               Ext.Msg.alert ('Redirecting', 'You will be redirected soon...');
               } else {
                self.close();
        }
    };
 }
</code>```

Any ideas on what I'm missing or need to do? Thank you in advance!

答:
Use this:</p>

```<code>Ext.MessageBox.confirm('Confirm', 'Foo', callbackFunction);
Ext.MessageBox.alignTo(customePanel, 'c-c');
</code>```

Body:
I have a simple grid and when I click on a record a custom window shows up, then if I click on Open-Pop-Up button I want the confirm pop-up to show up right on top of the custom window. I'm using

customePanel.showAt(event.pageX, event.pageY);

to show the custom window on top of the record that was clicked on based on the X and Y axis, and I'm trying to use the same functionality to show the confirm pop-up but I'm not having any luck.

Here's a working code:  FIDDLE

 handler: function () {
         var x = Ext.MessageBox.confirm(
         'Confirm', 'Are you sure you want to see patient\'s chart?', callbackFunction);
            function callbackFunction(btn) {
              var self = this;
              if(btn === 'yes') {
               Ext.Msg.alert ('Redirecting', 'You will be redirected soon...');
               } else {
                self.close();
        }
    };
 }

Any ideas on what I'm missing or need to do? Thank you in advance!

Body:
Use this:

Ext.MessageBox.confirm('Confirm', 'Foo', callbackFunction);
Ext.MessageBox.alignTo(customePanel, 'c-c');


问:
C++ how to access value of inherited and overridden attribute of base class?

I try to do something like this:

```<code>class A{
public:
    A(){number = 1;}
    int number;
};
class B : public A{
public:
    B(){number = 2;}
};

class Base {
public:
    Base() {myAttribute = new A();}
    int returnAttrNumber(){return myAttribute->number;}
    A *myAttribute;
};

class Inherited : public Base{
public:
    Inherited(){myAttribute = new B();}
    B *myAttribute;
};

int main()
{
    Inherited *i = new Inherited();
    std::cout << i->returnAttrNumber(); // outputs 1, because it gets the A not the B. I want it to output 2, to get the B object in returnAttrNumber()
}
</code>```

So, class Base holds an object A. Inherited holds an A-derived object B. And I try to call a method on the base class, but I want it to cast down in the hirarchy of the corresponding Object as far as possible (without static_cast or dynamic_cast) and then take the B object, not A and do stuff (returning it's number in in this case)

Is there a way to do that downcasting from a base class in C++ without big difficulties?
Thanks for answers!

答:
This is very bad design. The quick answer is you can access variable from the base class via the fully qualified identifier. Take the following example:

```<code>#include <iostream>

class A
{
public:
    A()
    : var(1) {}

protected:
    int var;
};

class B : public A
{
public:
    B()
    : var(2) {}

    int getBVar() const
    {
        return var;
    }

    int getAVar() const
    {
        return A::var;
    }

private:
    int var;
};

int main()
{
    B b;
    std::cout << "A: " << b.getAVar() << std::endl;
    std::cout << "B: " << b.getBVar() << std::endl;
}
</code>```

Which outputs the following:

```<code>A: 1
B: 2
</code>```

About the down casting bit... Base and Inherited have different variables. You can not safely case one to the other.

Body:
I try to do something like this:

class A{
public:
    A(){number = 1;}
    int number;
};
class B : public A{
public:
    B(){number = 2;}
};

class Base {
public:
    Base() {myAttribute = new A();}
    int returnAttrNumber(){return myAttribute->number;}
    A *myAttribute;
};

class Inherited : public Base{
public:
    Inherited(){myAttribute = new B();}
    B *myAttribute;
};

int main()
{
    Inherited *i = new Inherited();
    std::cout <returnAttrNumber(); // outputs 1, because it gets the A not the B. I want it to output 2, to get the B object in returnAttrNumber()
}

So, class Base holds an object A. Inherited holds an A-derived object B. And I try to call a method on the base class, but I want it to cast down in the hirarchy of the corresponding Object as far as possible (without static_cast or dynamic_cast) and then take the B object, not A and do stuff (returning it's number in in this case)

Is there a way to do that downcasting from a base class in C++ without big difficulties?
Thanks for answers!

Body:
This is very bad design. The quick answer is you can access variable from the base class via the fully qualified identifier. Take the following example:

#include <iostream>

class A
{
public:
    A()
    : var(1) {}

protected:
    int var;
};

class B : public A
{
public:
    B()
    : var(2) {}

    int getBVar() const
    {
        return var;
    }

    int getAVar() const
    {
        return A::var;
    }

private:
    int var;
};

int main()
{
    B b;
    std::cout << "A: " << b.getAVar() << std::endl;
    std::cout << "B: " << b.getBVar() << std::endl;
}

Which outputs the following:

A: 1
B: 2

About the down casting bit... Base and Inherited have different variables. You can not safely case one to the other.


问:
How to get recyceview height after settings adapter?
I need to get my recycle view height , I wrote this code but it doesn't work :

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

and also this one

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

but both of them returns invalid height .

how can I get the exact height of recyceview?

答:
I had the same problem a while ago. I got round it by setting a global layout listener, in my fragments onViewCreated method,  to pass through the height of the recycler to the adapter (and then to the view it was required in) when the layout was complete. Recycler views are difficult to get the height of because they are not included in the layout until the adapter is set.

```<code>view?.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
        override fun onGlobalLayout() {
            val height = main_recyclerview?.measuredHeight ?: 0
            if (height > 0) {
                view.viewTreeObserver?.removeOnGlobalLayoutListener(this)
                mainAdapter.setRecyclerHeight(height)
            }
        }
    })
</code>```

This is my code in kotlin, but it should give you some idea of what to do in Java

The remove layout listener is important as otherwise you can catch yourself in a loop of changing a layout property that causes a reset layout, that then calls your listener, which resets the property, etc, etc

Body:
I need to get my recycle view height , I wrote this code but it doesn't work :

recyecle.getHeight()

and also this one

getLayoutParams().height

but both of them returns invalid height .

how can I get the exact height of recyceview?

Body:
I had the same problem a while ago. I got round it by setting a global layout listener, in my fragments onViewCreated method,  to pass through the height of the recycler to the adapter (and then to the view it was required in) when the layout was complete. Recycler views are difficult to get the height of because they are not included in the layout until the adapter is set.

view?.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
        override fun onGlobalLayout() {
            val height = main_recyclerview?.measuredHeight ?: 0
            if (height > 0) {
                view.viewTreeObserver?.removeOnGlobalLayoutListener(this)
                mainAdapter.setRecyclerHeight(height)
            }
        }
    })

This is my code in kotlin, but it should give you some idea of what to do in Java

The remove layout listener is important as otherwise you can catch yourself in a loop of changing a layout property that causes a reset layout, that then calls your listener, which resets the property, etc, etc


问:
Failed Prop Type Error in Fine Uploader
I'm trying to get Fine Uploader React to work but keep running into issues.

I'm getting the following errors:

Here's the URL: http://fineuploader.azurewebsites.net/

Here's what I've done so far:

Downloaded the source on to my computer from https://github.com/FineUploader/react-fine-uploader

I then npm installed react-fine-uploader and fine-uploader as per instructions

I ran webpack to transpile and bundle the code

Added an entry point and index.html

Finally, I simply published the app to a new Azure app/website

Any idea what's causing the issue?

P.S. My goal is to use Fine Uploader to upload files to Azure Blob Storage. At this point, I'm simply trying to get Fine Uploader going. I do realize that I'll have to enter a few pieces of information about my blog storage endpoint, etc. but I don't think this error is related to any of that.

答:
A Gallery (and every higher level component of that library) needs an "uploader" props as explained in the section https://github.com/FineUploader/react-fine-uploader#high-level-components

An uploader is one of the 3 classes avaiable in the fine-uploader-wrappers package https://github.com/FineUploader/fine-uploader-wrappers#wrapper-classes
those are for upload to

Aws s3

Azure

or your enpoint

The uploader class need all the configuration endpoint, credentials, custom configuration, etc... (you can find a comprehensive list here in the api section https://docs.fineuploader.com/branch/master/api/options.html)

An example for s3 direct upload would be something like:

```<code>const uploader = new FineUploaderS3({
    options: {
        request: {
            endpoint: "http://fineuploadertest.s3.amazonaws.com",
            accessKey: "AKIAIXVR6TANOGNBGANQ"
        },
        signature: {
            endpoint: "/vendor/fineuploader/php-s3-server/endpoint.php"
        }
    }
})
</code>```

and use that uploader in a gallery

```<code> <Gallery uploader={ uploader } />
</code>```

There are many usefull option for customization: callbacks, onEventHandler, etc you can find them all in the docs of fineuploader

Edit: if im not mistaken react-transition-group is necessary even if it's not listed anywhere in the docs...

Title: Failed Prop Type Error in Fine Uploader

Body:
A Gallery (and every higher level component of that library) needs an "uploader" props as explained in the section https://github.com/FineUploader/react-fine-uploader#high-level-components

An uploader is one of the 3 classes avaiable in the fine-uploader-wrappers package https://github.com/FineUploader/fine-uploader-wrappers#wrapper-classes
those are for upload to

Aws s3

Azure

or your enpoint

The uploader class need all the configuration endpoint, credentials, custom configuration, etc... (you can find a comprehensive list here in the api section https://docs.fineuploader.com/branch/master/api/options.html)

An example for s3 direct upload would be something like:

const uploader = new FineUploaderS3({
    options: {
        request: {
            endpoint: "http://fineuploadertest.s3.amazonaws.com",
            accessKey: "AKIAIXVR6TANOGNBGANQ"
        },
        signature: {
            endpoint: "/vendor/fineuploader/php-s3-server/endpoint.php"
        }
    }
})

and use that uploader in a gallery

 <Gallery uploader={ uploader } />

There are many usefull option for customization: callbacks, onEventHandler, etc you can find them all in the docs of fineuploader

Edit: if im not mistaken react-transition-group is necessary even if it's not listed anywhere in the docs...


问:
div run through loop and perform disable and enable button with same classes
My loop runs 3 times.

Inside the loop div is run and its 3 time run.

When in box 1 div I checked checkbox and if it is checked a button is enabled, otherwise the button is disabled.

That works but its run on loop so its 3 time save div with same classes.

If I check first div like box 1 checkbox then only enable button of box 1 div other div not affected.

If I check box 3 checkbox then only disable this button not other.

How is this possible?

My code

$(document).ready(function (){

   $('body').on('click' , '.currentcheck' , function() {
      $(this).toggleClass("checked");

      if ($(".currentcheck.checked").length>0) {
        $('.btn_disable').prop('disabled', false);
      } else {
        $('.btn_disable').prop('disabled', true);
      }
    });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
    <title>Test Your Self</title>
    <meta name="viewport" content="width=device-width initial-state=1"/>
</head>
<body>
 <form>
   <div class="box">
  <div class="element_checkbox">
      <p>box 1</p>
   <input type="checkbox" name="chec1" class="currentcheck">
   <input type="checkbox" name="chec1" class="currentcheck">
   <input type="checkbox" name="chec1" class="currentcheck">
   <input type="checkbox" name="chec1" class="currentcheck">
            <button class="btn_disable" disabled>next</button>
  </div>
  <div class="element_checkbox">
      <p>box 2</p>
   <input type="checkbox" name="chec1" class="currentcheck">
   <input type="checkbox" name="chec1" class="currentcheck">
   <input type="checkbox" name="chec1" class="currentcheck">
   <input type="checkbox" name="chec1" class="currentcheck">
   <button class="btn_disable" disabled>next</button>
  </div>
  <div class="element_checkbox">
      <p>box 3</p>
   <input type="checkbox" name="chec1" class="currentcheck">
   <input type="checkbox" name="chec1" class="currentcheck">
   <input type="checkbox" name="chec1" class="currentcheck">
   <input type="checkbox" name="chec1" class="currentcheck">
   <button class="btn_disable" disabled>next</button>
  </div>
   </div>
 </form>

</body>
</html></code>```

答:
$(document).ready(function() {

  $('body').on('click', '.currentcheck', function() {
    var $this = $(this);
    //get the parent that encapsulates the checkboxes related to the one that was clicked
    var $parent = $this.closest('.element_checkbox');

    $this.toggleClass("checked");

    //only look at the checkboxes in the parent
    //only change the btn in the parent
    if ($parent.find(".currentcheck.checked").length > 0) {
      $parent.find('.btn_disable').prop('disabled', false);
    } else {
      $parent.find('.btn_disable').prop('disabled', true);
    }
  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <title>Test Your Self</title>
  <meta name="viewport" content="width=device-width initial-state=1" />
</head>

<body>
  <form>
    <div class="box">
      <div class="element_checkbox">
        <p>box 1</p>
        <input type="checkbox" name="chec1" class="currentcheck">
        <input type="checkbox" name="chec1" class="currentcheck">
        <input type="checkbox" name="chec1" class="currentcheck">
        <input type="checkbox" name="chec1" class="currentcheck">
        <button class="btn_disable" disabled>next</button>
      </div>
      <div class="element_checkbox">
        <p>box 2</p>
        <input type="checkbox" name="chec1" class="currentcheck">
        <input type="checkbox" name="chec1" class="currentcheck">
        <input type="checkbox" name="chec1" class="currentcheck">
        <input type="checkbox" name="chec1" class="currentcheck">
        <button class="btn_disable" disabled>next</button>
      </div>
      <div class="element_checkbox">
        <p>box 3</p>
        <input type="checkbox" name="chec1" class="currentcheck">
        <input type="checkbox" name="chec1" class="currentcheck">
        <input type="checkbox" name="chec1" class="currentcheck">
        <input type="checkbox" name="chec1" class="currentcheck">
        <button class="btn_disable" disabled>next</button>
      </div>
    </div>
  </form>

</body>

</html></code>```

Body:
My loop runs 3 times.

Inside the loop div is run and its 3 time run.

When in box 1 div I checked checkbox and if it is checked a button is enabled, otherwise the button is disabled.

That works but its run on loop so its 3 time save div with same classes.

If I check first div like box 1 checkbox then only enable button of box 1 div other div not affected.

If I check box 3 checkbox then only disable this button not other.

How is this possible?

My code

$(document).ready(function (){

   $('body').on('click' , '.currentcheck' , function() {
      $(this).toggleClass("checked");

      if ($(".currentcheck.checked").length>0) {
        $('.btn_disable').prop('disabled', false);
      } else {
        $('.btn_disable').prop('disabled', true);
      }
    });

});

<!DOCTYPE html>

    <title>Test Your Self</title>
    <meta name="viewport" content="width=device-width initial-state=1"/>

 <form>

box 1

   <input type="checkbox" name="chec1" class="currentcheck">
   <input type="checkbox" name="chec1" class="currentcheck">
   <input type="checkbox" name="chec1" class="currentcheck">
   <input type="checkbox" name="chec1" class="currentcheck">
            <button class="btn_disable" disabled>next</button>

box 2

   <input type="checkbox" name="chec1" class="currentcheck">
   <input type="checkbox" name="chec1" class="currentcheck">
   <input type="checkbox" name="chec1" class="currentcheck">
   <input type="checkbox" name="chec1" class="currentcheck">
   <button class="btn_disable" disabled>next</button>

box 3

   <input type="checkbox" name="chec1" class="currentcheck">
   <input type="checkbox" name="chec1" class="currentcheck">
   <input type="checkbox" name="chec1" class="currentcheck">
   <input type="checkbox" name="chec1" class="currentcheck">
   <button class="btn_disable" disabled>next</button>

 </form>

Body:
$(document).ready(function() {

  $('body').on('click', '.currentcheck', function() {
    var $this = $(this);
    //get the parent that encapsulates the checkboxes related to the one that was clicked
    var $parent = $this.closest('.element_checkbox');

    $this.toggleClass("checked");

    //only look at the checkboxes in the parent
    //only change the btn in the parent
    if ($parent.find(".currentcheck.checked").length > 0) {
      $parent.find('.btn_disable').prop('disabled', false);
    } else {
      $parent.find('.btn_disable').prop('disabled', true);
    }
  });

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>

<head>
  <title>Test Your Self</title>
  <meta name="viewport" content="width=device-width initial-state=1" />
</head>

<body>
  <form>
    <div class="box">
      <div class="element_checkbox">
        <p>box 1</p>
        <input type="checkbox" name="chec1" class="currentcheck">
        <input type="checkbox" name="chec1" class="currentcheck">
        <input type="checkbox" name="chec1" class="currentcheck">
        <input type="checkbox" name="chec1" class="currentcheck">
        <button class="btn_disable" disabled>next</button>
      </div>
      <div class="element_checkbox">
        <p>box 2</p>
        <input type="checkbox" name="chec1" class="currentcheck">
        <input type="checkbox" name="chec1" class="currentcheck">
        <input type="checkbox" name="chec1" class="currentcheck">
        <input type="checkbox" name="chec1" class="currentcheck">
        <button class="btn_disable" disabled>next</button>
      </div>
      <div class="element_checkbox">
        <p>box 3</p>
        <input type="checkbox" name="chec1" class="currentcheck">
        <input type="checkbox" name="chec1" class="currentcheck">
        <input type="checkbox" name="chec1" class="currentcheck">
        <input type="checkbox" name="chec1" class="currentcheck">
        <button class="btn_disable" disabled>next</button>
      </div>
    </div>
  </form>

</body>

</html>


问:
Mapping drive to SharePoint 2010
Maybe someone can help me with this one. I am able to map a SharePoint folder to a drive just fine , however if I log off then log back in , there is a red X on the drive , if i double click it and put my credentials then it fine again.

My question is , How do I avoid that ?  how can I make it so that when I login, the drive is ready to go and I dont have to click on it and type my password?

答:
Open IE

Tools -> Internet Options -> Security

The its either "Trusted" or "Local Intranet" depending on your settings

Sites -> Advanced (or Add) -> Add

then add file://*.yourdomainname.com, or http://*.yourdomainname.com

Title: Mapping drive to SharePoint 2010


问:
SQL: Count items by day (where day must be converted)
Thank you in advance for reading my question. I have data like this:

```<code>| Date_Time               | City | Vehicle_ID |
'2017-01-01 00:00:00.000'   'A'       1159
'2017-01-01 13:12:00.000'   'A'       1159
'2017-01-02 01:00:34.000'   'B'       1323
'2017-01-02 02:00:25.000'   'A'       1159
</code>```

I would like to calculate a new column 'Day_Number' which represents the interval of days from min(Date_Time) + 1, and then count the unique(Vehicle_IDs) by 'City' and by 'Day_Number'.

Example:

```<code>| City | Day | count_unique_vehicles |
  'A'     1             2
  'A'     2             1
  'B'     2             1
</code>```

I have written some terrible sql like

```<code> select date_time, city, count(distinct Vehicle_ID) as unique_vehicle
 from X
 where date_time >= '2017-12-01 00:00:00.000'
 group by DATEADD(DAY, DATEDIFF(DAY,'2017-12-01', date_time), date_time), Division
</code>```

which doesn't work. What should my query look like?

答:
You can actually do this with window functions:

```<code>select t.city,
       datediff(day, min(min(t.date_time)) over (), cast(t.date_time as date)) as days,
       count(distinct t.vehicle_id) as num_uniques
from t
group by t.city, cast(t.date_time as date)
order by t.city, days;
</code>```

Note:  This will return 0 for the value on the minimum day.  That makes sense to me.  However, you can just add 1 if you want 1 instead.

Body:
Thank you in advance for reading my question. I have data like this:

| Date_Time               | City | Vehicle_ID |
'2017-01-01 00:00:00.000'   'A'       1159
'2017-01-01 13:12:00.000'   'A'       1159
'2017-01-02 01:00:34.000'   'B'       1323
'2017-01-02 02:00:25.000'   'A'       1159

I would like to calculate a new column 'Day_Number' which represents the interval of days from min(Date_Time) + 1, and then count the unique(Vehicle_IDs) by 'City' and by 'Day_Number'.

Example:

| City | Day | count_unique_vehicles |
  'A'     1             2
  'A'     2             1
  'B'     2             1

I have written some terrible sql like

 select date_time, city, count(distinct Vehicle_ID) as unique_vehicle
 from X
 where date_time >= '2017-12-01 00:00:00.000'
 group by DATEADD(DAY, DATEDIFF(DAY,'2017-12-01', date_time), date_time), Division

which doesn't work. What should my query look like?

Body:
You can actually do this with window functions:

select t.city,
       datediff(day, min(min(t.date_time)) over (), cast(t.date_time as date)) as days,
       count(distinct t.vehicle_id) as num_uniques
from t
group by t.city, cast(t.date_time as date)
order by t.city, days;

Note:  This will return 0 for the value on the minimum day.  That makes sense to me.  However, you can just add 1 if you want 1 instead.


问:
How to find the first node of the tree in a dict?
i have a big problem , in a function for start to work i need to find the first node in a tree , here an example :

```<code>              "hi"
            /     \
           /       \
          "ok"     "no"
          /
         /
       "lol"
</code>```

the problem is that i dont know how to take it from a dict , because the input is like this :

```<code>{ "ok":["lol"] , "no":[] , "hi": ["ok","no"] , "lol" : [] }
</code>```

so in this case "hi" is the first because nobody has "hi" in dict.values() the problem is how to say that and most important the dict has 50'000 nodes so if i check one by one it goes in overtime .

i wrote this :

```<code>    d = { "ok":["lol"] , "no":[] , "hi": ["ok","no"] , "lol" : [] }
    x = d.values()
    x = str(x)
    for y in d.keys():
        if not y in x :
            first_node = y
            break
</code>```

but the problem is that can be a word like "hello" and a "key" like "hell" so "hell" is in "hellow" but is not "hellow" :(

答:
Here's a way to do it using set.difference.

```<code>from itertools import chain

d = { "ok":["lol"] , "no":[] , "hi": ["ok","no"] , "lol" : [] }
roots = set(d).difference(chain.from_iterable(d.values()))
</code>```

gives us

```<code>{'hi'}
</code>```

Body:
i have a big problem , in a function for start to work i need to find the first node in a tree , here an example :

              "hi"
            /     \
           /       \
          "ok"     "no"
          /
         /
       "lol"

the problem is that i dont know how to take it from a dict , because the input is like this :

{ "ok":["lol"] , "no":[] , "hi": ["ok","no"] , "lol" : [] }

so in this case "hi" is the first because nobody has "hi" in dict.values() the problem is how to say that and most important the dict has 50'000 nodes so if i check one by one it goes in overtime .

i wrote this :

    d = { "ok":["lol"] , "no":[] , "hi": ["ok","no"] , "lol" : [] }
    x = d.values()
    x = str(x)
    for y in d.keys():
        if not y in x :
            first_node = y
            break

but the problem is that can be a word like "hello" and a "key" like "hell" so "hell" is in "hellow" but is not "hellow" :(

Body:
Here's a way to do it using set.difference.

from itertools import chain

d = { "ok":["lol"] , "no":[] , "hi": ["ok","no"] , "lol" : [] }
roots = set(d).difference(chain.from_iterable(d.values()))

gives us

{'hi'}


问:
Android: Am I using the BroadcastReceiver wrong?
I would like to describe how the communication in my app works in the hopes that someone can tell me if it's good/bad/just okay design.

My app is single Activity multiple Fragments.  The Activity has several generic functions such as show/hide a Progressbar animation on the screen or showing a Snackbar.  This is functionality that should only be implemented in one place.

My Fragments send broadcasts whenever they need functionality that is not in the Fragment.  For example, if the Fragment wanted to show a Snackbar message,  I would send a broadcast like this:

```<code>localBroadcastManager.sendBroadcast(new SnackBarIntent("Show this text"));
</code>```

The Activity receives this broadcast, and shows the Snackbar message. Of course, this is a one way message. My Fragment doesn't know if the broadcast was received.  But all in all, it works.  I can send broadcasts from anywhere, a Service, an Adapter, etc. I can also send Broadcasts between Fragments if I wanted.

I understand there are alternatives to this.  There is an EventBus. Or I could pass a reference of the Activity into the Fragment, Adapter, etc.  To me this sounds like a terrible idea that could prevent proper garbage collection.

Then there is RxJava where I guess my fragment subscribes to an Observable that I get from the Activity.

But the question remains, is it bad to use BroadcastReceiver in this way?  And if so, why?

答:
Is it wrong?  No, they were meant for things like this.  I'd make sure I was using a local broadcast and not a global one, for efficiency.  Some of the alternatives may provide a nicer API or more features, but they all do more or less the same thing.

I would say that unless the part of the code that broadcasts is really buried that you're better off with interfaces and method calls than broadcasts.  The problem with any kind of event broadcast is that it decouples the sender and receiver.  That can have advantages when you'd otherwise need to pass objects through multiple levels or to places that shouldn't know about that part of the system.  But it has drawbacks in maintenance, especially if multiple places can put similar messages on the same bus.

Body:
I would like to describe how the communication in my app works in the hopes that someone can tell me if it's good/bad/just okay design.

My app is single Activity multiple Fragments.  The Activity has several generic functions such as show/hide a Progressbar animation on the screen or showing a Snackbar.  This is functionality that should only be implemented in one place.

My Fragments send broadcasts whenever they need functionality that is not in the Fragment.  For example, if the Fragment wanted to show a Snackbar message,  I would send a broadcast like this:

localBroadcastManager.sendBroadcast(new SnackBarIntent("Show this text"));

The Activity receives this broadcast, and shows the Snackbar message. Of course, this is a one way message. My Fragment doesn't know if the broadcast was received.  But all in all, it works.  I can send broadcasts from anywhere, a Service, an Adapter, etc. I can also send Broadcasts between Fragments if I wanted.

I understand there are alternatives to this.  There is an EventBus. Or I could pass a reference of the Activity into the Fragment, Adapter, etc.  To me this sounds like a terrible idea that could prevent proper garbage collection.

Then there is RxJava where I guess my fragment subscribes to an Observable that I get from the Activity.

But the question remains, is it bad to use BroadcastReceiver in this way?  And if so, why?


问:
Difference between rows of different variables, avoiding macro method
I am trying to find the average time between two processes. Each record is a repair process with an part ID, a start date, and an end date. For a given ID, only one repair process can occur at a time. See sample data below:

```<code>ID  START_DATE  END_DATE
123  1/2/2006   2/3/2006
124  1/3/2006   4/2/2006
123  3/5/2006   3/7/2006
123  6/2/2006   6/4/2006
123  6/8/2006   6/9/2006
124  6/2/2006   6/4/2006
124  6/5/2006   6/9/2006
124  6/10/2006   6/12/2006
</code>```

The information I need is the difference between the END_DATE and START_DATE for a given ID. For example, for ID 123, the time between its first process and the second process is 3/5/2006 - 2/3/2006. If the list were longer, I would then take the all those differences and take the average of them.

The output would be something like this:

```<code>ID  AverageTime
123   4.3
124   2.3
</code>```

My approach is to create a macro based on the following steps:

Create list of unique IDs.

For each ID in list, create table
of just that ID.

Calculate the difference between START_DATE and
END_DATE for that ID using the LAG function.

Average the
difference and append to list of unique IDs.

I think this would work, but may take a long time because there are 400k rows. Is there a way to do this without a macro? How might this process be optimized as the server I am running this on is very slow?

答:
You can do it in a data step and a PROC MEANS.
Use LAG() to find the previous value. You cannot use DIF() here because you're looking at different variables.</p>

```<code>data middle_step;
set have;
by id;

lag_end = lag(end_date);
duration = start_date-lag_end;

if first.id then duration=.;

run;

proc means data=middle_step mean;
class id;
var duration;
run;
</code>```

Body:
I am trying to find the average time between two processes. Each record is a repair process with an part ID, a start date, and an end date. For a given ID, only one repair process can occur at a time. See sample data below:

ID  START_DATE  END_DATE
123  1/2/2006   2/3/2006
124  1/3/2006   4/2/2006
123  3/5/2006   3/7/2006
123  6/2/2006   6/4/2006
123  6/8/2006   6/9/2006
124  6/2/2006   6/4/2006
124  6/5/2006   6/9/2006
124  6/10/2006   6/12/2006

The information I need is the difference between the END_DATE and START_DATE for a given ID. For example, for ID 123, the time between its first process and the second process is 3/5/2006 - 2/3/2006. If the list were longer, I would then take the all those differences and take the average of them.

The output would be something like this:

ID  AverageTime
123   4.3
124   2.3

My approach is to create a macro based on the following steps:

Create list of unique IDs.

For each ID in list, create table
of just that ID.

Calculate the difference between START_DATE and
END_DATE for that ID using the LAG function.

Average the
difference and append to list of unique IDs.

I think this would work, but may take a long time because there are 400k rows. Is there a way to do this without a macro? How might this process be optimized as the server I am running this on is very slow?

Body:
You can do it in a data step and a PROC MEANS.
Use LAG() to find the previous value. You cannot use DIF() here because you're looking at different variables.

data middle_step;
set have;
by id;

lag_end = lag(end_date);
duration = start_date-lag_end;

if first.id then duration=.;

run;

proc means data=middle_step mean;
class id;
var duration;
run;


问:
Try-Catch to loop back to while loop Java
I have a project to create a program that picks a number (1-10), then has the user guess. If they are too high it tells them so and same goes for if they guessed too low. Now to mistake-proof it, I have to add try and catch blocks. If you look at the code you will see that I have but when triggered the code processes the catch then finishes. How do I get it to loop back?</p>

```<code>    import java.util.*;
    import java.lang.*;

    class GuessDR {

        public static void main(String[] args){

            System.out.println("Welcome to my number guessing game!");

            int maxnum = 10;
            Scanner input = new Scanner(System.in);
            Random rand = new Random();
            int number = rand.nextInt(maxnum);
            int tries = 0;
            int guess;
            boolean win = false;

             try{

               while (win == false){

                   System.out.println("Guess a number between 1 and "+
                   maxnum +": ");
                   guess = input.nextInt();
                   tries++;
                   if (guess == number){
                       win = true;
                   }

                   else if(guess < number){
                       System.out.println("Number is to low, tray again");

                   }

                   else if(guess > number){
                       System.out.println("Number is to high, try again");

                   }

               }
            }

            catch (InputMismatchException e) {

                System.out.println("Enter numerical guess");

            }
     System.out.println("You win!");
     System.out.println("It took you "+ tries + " tries.");

    }
 }
</code>```

答:
Move try-catch into the while loop and handle the scanner to prevenet infinite loop. Check it out: https://stackoverflow.com/a/3572233/5964489</p>

```<code>while (win == false)
        {

            System.out.println("Guess a number between 1 and "
                    + maxnum + ": ");
            try
            {
                guess = input.nextInt();
                tries++;
                if (guess == number)
                {
                    win = true;
                } else if (guess < number)
                {
                    System.out.println("Number is to low, tray again");

                } else if (guess > number)
                {
                    System.out.println("Number is to high, try again");

                }

            } catch (InputMismatchException e)
            {
                System.out.println("Enter numerical guess");
                input.next();
            }
        }
</code>```

Body:
I have a project to create a program that picks a number (1-10), then has the user guess. If they are too high it tells them so and same goes for if they guessed too low. Now to mistake-proof it, I have to add try and catch blocks. If you look at the code you will see that I have but when triggered the code processes the catch then finishes. How do I get it to loop back?

    import java.util.*;
    import java.lang.*;

    class GuessDR {

        public static void main(String[] args){

            System.out.println("Welcome to my number guessing game!");

            int maxnum = 10;
            Scanner input = new Scanner(System.in);
            Random rand = new Random();
            int number = rand.nextInt(maxnum);
            int tries = 0;
            int guess;
            boolean win = false;

             try{

               while (win == false){

                   System.out.println("Guess a number between 1 and "+
                   maxnum +": ");
                   guess = input.nextInt();
                   tries++;
                   if (guess == number){
                       win = true;
                   }

                   else if(guess < number){
                       System.out.println("Number is to low, tray again");

                   }

                   else if(guess > number){
                       System.out.println("Number is to high, try again");

                   }

               }
            }

            catch (InputMismatchException e) {

                System.out.println("Enter numerical guess");

            }
     System.out.println("You win!");
     System.out.println("It took you "+ tries + " tries.");

    }
 }

Body:
Move try-catch into the while loop and handle the scanner to prevenet infinite loop. Check it out: https://stackoverflow.com/a/3572233/5964489

while (win == false)
        {

            System.out.println("Guess a number between 1 and "
                    + maxnum + ": ");
            try
            {
                guess = input.nextInt();
                tries++;
                if (guess == number)
                {
                    win = true;
                } else if (guess < number)
                {
                    System.out.println("Number is to low, tray again");

                } else if (guess > number)
                {
                    System.out.println("Number is to high, try again");

                }

            } catch (InputMismatchException e)
            {
                System.out.println("Enter numerical guess");
                input.next();
            }
        }


问:
Creating an efficient datatype for looking up conversion factors by initial and resulting units C#
I'm trying to create a windows form application that will convert units of measurements from one to the other.  My form features navigation buttons that I figured would make it user friendly.

When the user selects a category from the main menu it fills the category of measurement combobox and sets default unit of measurements into two other combo boxes.

These comboboxes allow the user to select which unit of measurement they want.  When they choose a category such as distance, it fills the initial and resulting unit of measurement comboboxes.

I therefore have already created a few string[] that contains each unit of measurement.

```<code>string[] distanceUnits = { "Inches", "Feet", "Centimeters", "Meters", "Kilometers", "Miles" };
string[] massUnits = { "Grams", "Kilograms", "Pounds", "Ounces" };
</code>```

I also created a couple different decimal[] arrays filled with conversion factors that I have been looking up and editing for precision purposes since I will be doing unit testing. I'd like to easily be able to change the conversion factor or add new ones into the arrays.

For example,

```<code>decimal[] massConversionFactors =
{
    .001m,               // [0] Grams to KiloGrams
    .00220462m,          // [1] Grams to Pounds
    .035274m,            // [2] Grams to Ounces
    1000,                // [3] KiloGrams to Grams
    2.20462m,            // [4] KiloGrams to Pounds
    35.274m,             // [5] KiloGrams to Ounces
    453.592m,            // [6] Pounds to Grams
    .453592m,            // [7] Pounds to Kilograms
    16                   // [8] Pounds to Ounces
};
</code>```

and

```<code>decimal[] distanceConversionFactors =
{
    .083333m,             // [0] Inches to Feet
    2.54m,                // [1] Inches to Centimeters
    .0254m,               // [2] Inches to Meters
    .0000254m,            // [3] Inches to Kilometers
    .0000157828282828m,   // [4] Inches to Miles
    12,                   // [5] Feet to Inches
    30.48m,               // [6] Feet to Centimetes
    .3048m,               // [7] Feet to Meters
    .0003048m,            // [8] Feet to Kilometers
    .000189394m,          // [9] Feet to Miles
    .3937009133858m,      // [10] Centimeters to Inches
    .03280840944882m,     // [11] Centimeters to Feet
    .01m,                 // [12] Centimeters to Meters
    .00001m,              // [13] Centimeters to Kilometers
    .0000062137m,         // [14] Centimeters to Miles
    39.3701m,             // [15] Meters to Inches
    3.28084m,             // [16] Meters to Feet
    100,                  // [17] Meters to Centimeters
    .001m,                // [18] Meters to Kilometers
    .000621371m,          // [19] Meters to Miles
    39370.1m,             // [20] Kilometers to Inches
    3280.84m,             // [21] Kilometers to Feet
    100000,               // [22] Kilometers to Centimeters
    1000,                 // [23] Kilometers to Meters
    .621371m,             // [24] Kilometers to Miles
    63360,                // [25] Miles to Inches
    5280,                 // [26] Miles to Feet
    160934,               // [27] Miles to Centimeters
    1609.34m,             // [28] Miles to Meters
    1.60934m              // [29] Miles to Kilometers
};
</code>```

That way when the submission button is pressed I can do a calculation such as:

```<code>private void ConvertSubmissionButton_Click(object sender, EventArgs e)
{
    //User's input value
    decimal input = decimal.Parse(UserInputTextBox.Text);
    string initialUnits = InitialUnitsComboBox.SelectedItem.ToString();
    string resultingUnits = ResultingUnitsComboBox.SelectedItem.ToString();

    //conversion of user input to result accepting initial and resulting
    decimal result =  input * ObjectWithTooManyMethods(initalUnits, resultingUnits);

    ResultingValueLabel.Text = (initialUnits);
    ResultingValueLabel.Show();
}
</code>```

This works fine for now, but as I add more methods to the object I wonder if there is a way to consolidate the already created arrays.

The problem I'm having is that I am forced to hardcode every permutation of conversion in the

```<code>ObjectWithTooManyMethods(string, string);
</code>```

What I'd really like to do is create a recursive loop that will go through the distanceUnits[] massUnits[] and other unit of measurement category arrays, and creates every possible permutation based on the category's appropriate conversionFactor arrays.
This way I can add on units of measurements and their conversion factors without coding an entire new method in the future.

Is this possible?

This ideal loop would create a single datatype that contains this information and be able to retrieve the decimal value for the conversion factor for initial, and resulting units when the user clicks a submission button.

Such as:

```<code>DesiredDatatype<string,string,decimal> conversionFactors = new DesiredDatatype<string,string,decimal>()
{
    {initialUnits, resultingUnits, conversionFactor}
};

    private void ConvertSubmissionButton_Click(object sender, EventArgs e)
    {
        //User's input value
        decimal input = decimal.Parse(UserInputTextBox.Text);
        string initialUnits = InitialUnitsComboBox.SelectedItem.ToString();
        string resultingUnits = ResultingUnitsComboBox.SelectedItem.ToString();

        decimal result =  input * conversionFactors.get(initialUnits, resultingUnits);

        ResultingValueLabel.Text = (result);
        ResultingValueLabel.Show();
    }
</code>```

Maybe I'm approaching this the wrong way, and/or have been coding too long today.. I have looked up information about tuples and dictionarys and they seem like they would ideal for this scenario but I have failed in creating a working datatype from looping through the information in these existing arrays.

Any advice is greatly appreciated. Thanks a lot!

答:
When working in C# I like to use objects (when in Rome, right?).

Here's my "quick and dirty" take on solving the problem with objects. As @zzxyz mentioned, for each unit group we define a standard unit and calculate everything relative to that.

The huge advantage to this approach is that we define each unit once rather than making a big cross-reference table for all the possible combinations. And adding a new unit is easy - just define it.

Also, there's no need to hardcode a function for each call... just set the parameters of the Convert method call:

weight.Convert(400, "kg", "g");

As far as the objects go, I thought about giving Units both name and abbreviation properties, but for the sake of speed I kept only Name. But when populating it I used abbreviations.

The Output:

To run it:

var app = new App_Conversion();
app.Run();

```<code>using System;
using System.Collections.Generic;
using System.Linq;

namespace StackOverflow
{
    public class App_Conversion
    {
        public void Run()
        {
            var weight = getWeightUnitGroup();

            var w = weight.Convert("g", "kg");
            Console.WriteLine(w.ToString());

            var x = weight.Convert(400, "kg", "g");
            Console.WriteLine(x.ToString());

            var y = weight.Convert(12, "lb", "g");
            Console.WriteLine(y.ToString());

            var z = weight.Convert(7, "g", "lb");
            Console.WriteLine(z.ToString());
        }

        private UnitGroup getWeightUnitGroup()
        // we could also get the data from wherever and deserialize into these classes
        {
            //base unit for the weight Unit Group
            var gram = new Unit("g", 1);

            var weight = new UnitGroup("Weight", UnitGroup.eType.Mass, gram);

            weight.AddUnit(new Unit("kg", 1000m));
            weight.AddUnit(new Unit("mg", 0.001m));
            weight.AddUnit(new Unit("oz", 28.35m));
            weight.AddUnit(new Unit("lb", 453.59m));

            return weight;
        }
    }

    public class UnitGroup
    {
        public enum eType
        {
            Mass = 1,
            Distance = 2
        }

        public eType Type { get; private set; }

        public string Name { get; private set; }

        public Unit BaseUnit { get; private set; }

        public List<Unit> Units { get; private set; } = new List<Unit>();

        public UnitGroup(string name, eType type, Unit baseUnit)
        {
            Name = name;
            Type = type;
            BaseUnit = baseUnit;
            AddUnit(baseUnit);
        }

        public void AddUnit(Unit unit)
        {
            Units.Add(unit);
            unit.AddToGroup(this);
        }

        public ConversionResult Convert(string fromName, string toName)
        {
            return Convert(1, fromName, toName);
        }

        public ConversionResult Convert(decimal qty, string fromName, string toName)
        {
            var from = Units.Where(u => u.Name.Equals(fromName)).First();

            var to = Units.Where(u => u.Name.Equals(toName)).First();

            var result = Decimal.Round(qty * (from.Quantity * to.ConvertToFactor),5);

            var formattedResult = $"{qty} {fromName} = {result} {toName}";

            return new ConversionResult(result, formattedResult);
        }
    }

    public class Unit
    {
        public UnitGroup Group { get; private set; }

        public string Name { get; private set; }

        public decimal Quantity { get; private set; }

        public decimal ConvertToFactor
        {
            get
            {
                return Group.BaseUnit.Quantity / Quantity;
            }
        }

        public Unit(string name, decimal qty)
        {
            Name = name;
            Quantity = qty;
        }

        public void AddToGroup(UnitGroup group)
        {
            Group = group;
        }
    }

    public class ConversionResult
    {
        private string formattedResult;

        public decimal Result { get; private set; }

        public ConversionResult(decimal result, string formattedResult)
        {
            Result = result;
            this.formattedResult = formattedResult;
        }

        public override string ToString()
        {
            return formattedResult;
        }
    }
}
</code>```

Body:
I'm trying to create a windows form application that will convert units of measurements from one to the other.  My form features navigation buttons that I figured would make it user friendly.

When the user selects a category from the main menu it fills the category of measurement combobox and sets default unit of measurements into two other combo boxes.

These comboboxes allow the user to select which unit of measurement they want.  When they choose a category such as distance, it fills the initial and resulting unit of measurement comboboxes.

I therefore have already created a few string[] that contains each unit of measurement.

string[] distanceUnits = { "Inches", "Feet", "Centimeters", "Meters", "Kilometers", "Miles" };
string[] massUnits = { "Grams", "Kilograms", "Pounds", "Ounces" };

I also created a couple different decimal[] arrays filled with conversion factors that I have been looking up and editing for precision purposes since I will be doing unit testing. I'd like to easily be able to change the conversion factor or add new ones into the arrays.

For example,

decimal[] massConversionFactors =
{
    .001m,               // [0] Grams to KiloGrams
    .00220462m,          // [1] Grams to Pounds
    .035274m,            // [2] Grams to Ounces
    1000,                // [3] KiloGrams to Grams
    2.20462m,            // [4] KiloGrams to Pounds
    35.274m,             // [5] KiloGrams to Ounces
    453.592m,            // [6] Pounds to Grams
    .453592m,            // [7] Pounds to Kilograms
    16                   // [8] Pounds to Ounces
};

and

decimal[] distanceConversionFactors =
{
    .083333m,             // [0] Inches to Feet
    2.54m,                // [1] Inches to Centimeters
    .0254m,               // [2] Inches to Meters
    .0000254m,            // [3] Inches to Kilometers
    .0000157828282828m,   // [4] Inches to Miles
    12,                   // [5] Feet to Inches
    30.48m,               // [6] Feet to Centimetes
    .3048m,               // [7] Feet to Meters
    .0003048m,            // [8] Feet to Kilometers
    .000189394m,          // [9] Feet to Miles
    .3937009133858m,      // [10] Centimeters to Inches
    .03280840944882m,     // [11] Centimeters to Feet
    .01m,                 // [12] Centimeters to Meters
    .00001m,              // [13] Centimeters to Kilometers
    .0000062137m,         // [14] Centimeters to Miles
    39.3701m,             // [15] Meters to Inches
    3.28084m,             // [16] Meters to Feet
    100,                  // [17] Meters to Centimeters
    .001m,                // [18] Meters to Kilometers
    .000621371m,          // [19] Meters to Miles
    39370.1m,             // [20] Kilometers to Inches
    3280.84m,             // [21] Kilometers to Feet
    100000,               // [22] Kilometers to Centimeters
    1000,                 // [23] Kilometers to Meters
    .621371m,             // [24] Kilometers to Miles
    63360,                // [25] Miles to Inches
    5280,                 // [26] Miles to Feet
    160934,               // [27] Miles to Centimeters
    1609.34m,             // [28] Miles to Meters
    1.60934m              // [29] Miles to Kilometers
};

That way when the submission button is pressed I can do a calculation such as:

private void ConvertSubmissionButton_Click(object sender, EventArgs e)
{
    //User's input value
    decimal input = decimal.Parse(UserInputTextBox.Text);
    string initialUnits = InitialUnitsComboBox.SelectedItem.ToString();
    string resultingUnits = ResultingUnitsComboBox.SelectedItem.ToString();

    //conversion of user input to result accepting initial and resulting
    decimal result =  input * ObjectWithTooManyMethods(initalUnits, resultingUnits);

    ResultingValueLabel.Text = (initialUnits);
    ResultingValueLabel.Show();
}

This works fine for now, but as I add more methods to the object I wonder if there is a way to consolidate the already created arrays.

The problem I'm having is that I am forced to hardcode every permutation of conversion in the

ObjectWithTooManyMethods(string, string);

What I'd really like to do is create a recursive loop that will go through the distanceUnits[] massUnits[] and other unit of measurement category arrays, and creates every possible permutation based on the category's appropriate conversionFactor arrays.
This way I can add on units of measurements and their conversion factors without coding an entire new method in the future.

Is this possible?

This ideal loop would create a single datatype that contains this information and be able to retrieve the decimal value for the conversion factor for initial, and resulting units when the user clicks a submission button.

Such as:

DesiredDatatype<string,string,decimal> conversionFactors = new DesiredDatatype<string,string,decimal>()
{
    {initialUnits, resultingUnits, conversionFactor}
};

    private void ConvertSubmissionButton_Click(object sender, EventArgs e)
    {
        //User's input value
        decimal input = decimal.Parse(UserInputTextBox.Text);
        string initialUnits = InitialUnitsComboBox.SelectedItem.ToString();
        string resultingUnits = ResultingUnitsComboBox.SelectedItem.ToString();

        decimal result =  input * conversionFactors.get(initialUnits, resultingUnits);

        ResultingValueLabel.Text = (result);
        ResultingValueLabel.Show();
    }

Maybe I'm approaching this the wrong way, and/or have been coding too long today.. I have looked up information about tuples and dictionarys and they seem like they would ideal for this scenario but I have failed in creating a working datatype from looping through the information in these existing arrays.

Any advice is greatly appreciated. Thanks a lot!

Body:
When working in C# I like to use objects (when in Rome, right?).

Here's my "quick and dirty" take on solving the problem with objects. As @zzxyz mentioned, for each unit group we define a standard unit and calculate everything relative to that.

The huge advantage to this approach is that we define each unit once rather than making a big cross-reference table for all the possible combinations. And adding a new unit is easy - just define it.

Also, there's no need to hardcode a function for each call... just set the parameters of the Convert method call:

weight.Convert(400, "kg", "g");

As far as the objects go, I thought about giving Units both name and abbreviation properties, but for the sake of speed I kept only Name. But when populating it I used abbreviations.

The Output:

To run it:

var app = new App_Conversion();
app.Run();

using System;
using System.Collections.Generic;
using System.Linq;

namespace StackOverflow
{
    public class App_Conversion
    {
        public void Run()
        {
            var weight = getWeightUnitGroup();

            var w = weight.Convert("g", "kg");
            Console.WriteLine(w.ToString());

            var x = weight.Convert(400, "kg", "g");
            Console.WriteLine(x.ToString());

            var y = weight.Convert(12, "lb", "g");
            Console.WriteLine(y.ToString());

            var z = weight.Convert(7, "g", "lb");
            Console.WriteLine(z.ToString());
        }

        private UnitGroup getWeightUnitGroup()
        // we could also get the data from wherever and deserialize into these classes
        {
            //base unit for the weight Unit Group
            var gram = new Unit("g", 1);

            var weight = new UnitGroup("Weight", UnitGroup.eType.Mass, gram);

            weight.AddUnit(new Unit("kg", 1000m));
            weight.AddUnit(new Unit("mg", 0.001m));
            weight.AddUnit(new Unit("oz", 28.35m));
            weight.AddUnit(new Unit("lb", 453.59m));

            return weight;
        }
    }

    public class UnitGroup
    {
        public enum eType
        {
            Mass = 1,
            Distance = 2
        }

        public eType Type { get; private set; }

        public string Name { get; private set; }

        public Unit BaseUnit { get; private set; }

        public List<Unit> Units { get; private set; } = new List<Unit>();

        public UnitGroup(string name, eType type, Unit baseUnit)
        {
            Name = name;
            Type = type;
            BaseUnit = baseUnit;
            AddUnit(baseUnit);
        }

        public void AddUnit(Unit unit)
        {
            Units.Add(unit);
            unit.AddToGroup(this);
        }

        public ConversionResult Convert(string fromName, string toName)
        {
            return Convert(1, fromName, toName);
        }

        public ConversionResult Convert(decimal qty, string fromName, string toName)
        {
            var from = Units.Where(u => u.Name.Equals(fromName)).First();

            var to = Units.Where(u => u.Name.Equals(toName)).First();

            var result = Decimal.Round(qty * (from.Quantity * to.ConvertToFactor),5);

            var formattedResult = $"{qty} {fromName} = {result} {toName}";

            return new ConversionResult(result, formattedResult);
        }
    }

    public class Unit
    {
        public UnitGroup Group { get; private set; }

        public string Name { get; private set; }

        public decimal Quantity { get; private set; }

        public decimal ConvertToFactor
        {
            get
            {
                return Group.BaseUnit.Quantity / Quantity;
            }
        }

        public Unit(string name, decimal qty)
        {
            Name = name;
            Quantity = qty;
        }

        public void AddToGroup(UnitGroup group)
        {
            Group = group;
        }
    }

    public class ConversionResult
    {
        private string formattedResult;

        public decimal Result { get; private set; }

        public ConversionResult(decimal result, string formattedResult)
        {
            Result = result;
            this.formattedResult = formattedResult;
        }

        public override string ToString()
        {
            return formattedResult;
        }
    }
}


问:
Odoo 10 - Disable default "My opportunities" filter in CRM
When user checks sales flow (opportunities) in Odoo 10 CRM module, the "My opportunities" filter is enabled by default.

Is it possible to configure behaviour so user has no such filter and he/she sees all opportunities?

Thanks

答: And here an answer without using debug mode and changing odoo default actions: Just create a filter for yourself, for example "group by stage and group by salesman" and save it as default filter.</p>


问:
Convert MySQL to a new system?
I have an old MySQL table structure that I want to upgrade to a new one, I'll explain the structures below.

Its for a permission system, and the table represents what rank id's get what permission id's

Table [Old]:

permission_id the id of the permission given

rank the rank id that gets the permission

Now, for the old table system, it uses an extra call to permissions table to find the name of the permission linked with permission_id, in my new system I just store permission rights by permission's name not the permissions id.

Table [New]:

permission_name the name of the permission given

allowed_ranks a string of rank ids, seperated by ,

How would I convert all the records to 1 simple record for all permissions, but convert the rank column to the new allowed_ranks with a seperator of ,?

答:
Do not convert to the new system if you have any choice.
You can avoid "an extra call to permissions" by just joining the tables.

```<code>SELECT *
FROM old_table AS t
INNER JOIN permissions AS p ON t.permission_id = p.permission_id
WHERE t.rank = ?
;
</code>```

If you need to display the information in the new table format, just use this query:

```<code>SELECT p.permission_name, GROUP_CONCAT(t.rank) AS allowed_ranks
FROM old_table AS t
INNER JOIN permissions AS p ON t.permission_id = p.permission_id
GROUP BY p.permission_name
;
</code>```

Note: you could use the second query to populate the new table, but it is pretty much guaranteed you will quickly regret moving to it; at least, once you have to find all permissions associated with a specific rank.

Title: Convert MySQL to a new system?

Body:
Do not convert to the new system if you have any choice.
You can avoid "an extra call to permissions" by just joining the tables.

SELECT *
FROM old_table AS t
INNER JOIN permissions AS p ON t.permission_id = p.permission_id
WHERE t.rank = ?
;

If you need to display the information in the new table format, just use this query:

SELECT p.permission_name, GROUP_CONCAT(t.rank) AS allowed_ranks
FROM old_table AS t
INNER JOIN permissions AS p ON t.permission_id = p.permission_id
GROUP BY p.permission_name
;

Note: you could use the second query to populate the new table, but it is pretty much guaranteed you will quickly regret moving to it; at least, once you have to find all permissions associated with a specific rank.


问:
ifelse() and conditionally pasting column names across a data frame
I've got a data frame (df) with nine categorical variables, the first one being called student and then the names of eight school subjects.

I'd like to create a new variable called overall, summing up what subjects the student studied (dfgoal).

The problem's that what I've got doesn't work. Also I'm not sure how to best skip the first column (student). Use a list of the variables I do want to use (the eight subjects)?

Any help would be much appreciated.

starting point (df):

```<code>     df <-
  data.frame(
    student = c(1, 2, 3, 4, 5),
    maths = c("y", "n", "n", "n", "n"),
    English = c("n", "y", "n", "n", "n"),
    geography = c("y", "n", "n", "n", "n"),
    history = c("n", "n", "n", "n", "n"),
    art = c("n", "n", "n", "n", "n"),
    Spanish = c("n", "n", "n", "n", "n"),
    physics = c("n", "n", "n", "n", "y"),
    chemistry = c("n", "n", "n", "n", "y"),
    stringsAsFactors = TRUE
  )
</code>```

desired outcome (dfgoal):

```<code> dfgoal <-
data.frame(
student = c(1, 2, 3, 4, 5),
maths = c("y", "n", "n", "n", "n"),
English = c("n", "y", "n", "n", "n"),
geography = c("y", "n", "n", "n", "n"),
history = c("n", "n", "n", "n", "n"),
art = c("n", "n", "n", "n", "n"),
Spanish = c("n", "n", "n", "n", "n"),
physics = c("n", "n", "n", "n", "y"),
chemistry = c("n", "n", "n", "n", "y"),
overall = c("maths, geography,", "English", "n", "n", "physics,chemistry,"),
stringsAsFactors = TRUE )
</code>```

current code:

```<code>sapply(df, function(x)
  df$overall <- ifelse(df$x == y, paste0(names(df$x), ","), "n"))
</code>```

答:
TL;DR

```<code>> overall <- apply(df, 1, function(r) paste0(names(r)[r == 'y'], collapse = ', '))
> dfgoal <- cbind(df, overall)
</code>```

Let's try to derive it:

pick the first line to play with:

```<code>r <- df[2,]
r
  student maths English geography history art Spanish physics chemistry
    1     y       n         y      n      n     n         n     n
</code>```

now let's first produce a list of boolean where TRUE will be assigned to the position where a y appears, and FALSE otherwise, this is trivial:

```<code>> r == 'y'
  student maths English geography history   art Spanish physics chemistry
   FALSE  TRUE   FALSE      TRUE   FALSE FALSE   FALSE   FALSE     FALSE
</code>```

Now you should get the point: we will use the last as a subset argument to get the desired elements from the names(r) vector, which contains the actual names for each of the positions:

```<code>> names(r)[r == 'y']
[1] "maths"     "geography"
</code>```

Now we just need to concat all these, and iterate over the entire dataframe:

```<code>> overall <- apply(df, 1, function(r) paste0(names(r)[r == 'y'], collapse = ', '))
> dfgoal <- cbind(df, overall)
</code>```

Body:
I've got a data frame (df) with nine categorical variables, the first one being called student and then the names of eight school subjects.

I'd like to create a new variable called overall, summing up what subjects the student studied (dfgoal).

The problem's that what I've got doesn't work. Also I'm not sure how to best skip the first column (student). Use a list of the variables I do want to use (the eight subjects)?

Any help would be much appreciated.

starting point (df):

     df <-
  data.frame(
    student = c(1, 2, 3, 4, 5),
    maths = c("y", "n", "n", "n", "n"),
    English = c("n", "y", "n", "n", "n"),
    geography = c("y", "n", "n", "n", "n"),
    history = c("n", "n", "n", "n", "n"),
    art = c("n", "n", "n", "n", "n"),
    Spanish = c("n", "n", "n", "n", "n"),
    physics = c("n", "n", "n", "n", "y"),
    chemistry = c("n", "n", "n", "n", "y"),
    stringsAsFactors = TRUE
  )

desired outcome (dfgoal):

 dfgoal <-
data.frame(
student = c(1, 2, 3, 4, 5),
maths = c("y", "n", "n", "n", "n"),
English = c("n", "y", "n", "n", "n"),
geography = c("y", "n", "n", "n", "n"),
history = c("n", "n", "n", "n", "n"),
art = c("n", "n", "n", "n", "n"),
Spanish = c("n", "n", "n", "n", "n"),
physics = c("n", "n", "n", "n", "y"),
chemistry = c("n", "n", "n", "n", "y"),
overall = c("maths, geography,", "English", "n", "n", "physics,chemistry,"),
stringsAsFactors = TRUE )

current code:

sapply(df, function(x)
  df$overall <- ifelse(df$x == y, paste0(names(df$x), ","), "n"))

Body:
TL;DR

> overall <- apply(df, 1, function(r) paste0(names(r)[r == 'y'], collapse = ', '))
> dfgoal <- cbind(df, overall)

Let's try to derive it:

pick the first line to play with:

r <- df[2,]
r
  student maths English geography history art Spanish physics chemistry
    1     y       n         y      n      n     n         n     n

now let's first produce a list of boolean where TRUE will be assigned to the position where a y appears, and FALSE otherwise, this is trivial:

> r == 'y'
  student maths English geography history   art Spanish physics chemistry
   FALSE  TRUE   FALSE      TRUE   FALSE FALSE   FALSE   FALSE     FALSE

Now you should get the point: we will use the last as a subset argument to get the desired elements from the names(r) vector, which contains the actual names for each of the positions:

> names(r)[r == 'y']
[1] "maths"     "geography"

Now we just need to concat all these, and iterate over the entire dataframe:

> overall <- apply(df, 1, function(r) paste0(names(r)[r == 'y'], collapse = ', '))
> dfgoal <- cbind(df, overall)