问:
NSURL from PHAsset
I'm converting our app over to use the Photos Framework of iOS8, the ALAsset framework is clearly a second class citizen under iOS8.

I'm having a problem is that our architecture really wants an NSURL that represents the location of the media on "disk." We use this to upload the media to our servers for further processing.

This was easy with ALAsset:

```<code>    ALAssetRepresentation *rep = [asset defaultRepresentation];
    self.originalVideo = rep.url;
</code>```

But I'm just not seeing this ability in PHAsset. I guess I can call:

```<code>    imageManager.requestImageDataForAsset
</code>```

and then write it out to a temp spot in the file system but that seems awfully heavyweight and wasteful, not to mention potentially slow.

Is there a way to get this or am I going to have refactor more of my app to only use NSURLs for iOS7 and some other method for iOS8?

答:
Here's a handy PHAsset category:</p>

```<code>@implementation PHAsset (Utils)

- (NSURL *)fileURL {
    __block NSURL *url = nil;

    switch (self.mediaType) {
        case PHAssetMediaTypeImage: {
            PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
            options.synchronous = YES;
            [PHImageManager.defaultManager requestImageDataForAsset:self
                                                            options:options
                                                      resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
                                                          url = info[@"PHImageFileURLKey"];
                                                      }];
            break;
        }
        case PHAssetMediaTypeVideo: {
            dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
            [PHImageManager.defaultManager requestAVAssetForVideo:self
                                                          options:nil
                                                    resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
                                                        if ([asset isKindOfClass:AVURLAsset.class]) {
                                                            url = [(AVURLAsset *)asset URL];
                                                        }
                                                        dispatch_semaphore_signal(semaphore);
                                                    }];
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            break;
        }
        default:
            break;
    }
    return url;
}

@end
</code>```

Title: NSURL from PHAsset

Body:
I'm converting our app over to use the Photos Framework of iOS8, the ALAsset framework is clearly a second class citizen under iOS8.

I'm having a problem is that our architecture really wants an NSURL that represents the location of the media on "disk." We use this to upload the media to our servers for further processing.

This was easy with ALAsset:

    ALAssetRepresentation *rep = [asset defaultRepresentation];
    self.originalVideo = rep.url;

But I'm just not seeing this ability in PHAsset. I guess I can call:

    imageManager.requestImageDataForAsset

and then write it out to a temp spot in the file system but that seems awfully heavyweight and wasteful, not to mention potentially slow.

Is there a way to get this or am I going to have refactor more of my app to only use NSURLs for iOS7 and some other method for iOS8?

Body:
Here's a handy PHAsset category:

@implementation PHAsset (Utils)

- (NSURL *)fileURL {
    __block NSURL *url = nil;

    switch (self.mediaType) {
        case PHAssetMediaTypeImage: {
            PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
            options.synchronous = YES;
            [PHImageManager.defaultManager requestImageDataForAsset:self
                                                            options:options
                                                      resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
                                                          url = info[@"PHImageFileURLKey"];
                                                      }];
            break;
        }
        case PHAssetMediaTypeVideo: {
            dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
            [PHImageManager.defaultManager requestAVAssetForVideo:self
                                                          options:nil
                                                    resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
                                                        if ([asset isKindOfClass:AVURLAsset.class]) {
                                                            url = [(AVURLAsset *)asset URL];
                                                        }
                                                        dispatch_semaphore_signal(semaphore);
                                                    }];
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            break;
        }
        default:
            break;
    }
    return url;
}

@end


来源: stackexchange

问:
Code golf: combining multiple sorted lists into a single sorted list
Implement an algorithm to merge an arbitrary number of sorted lists into one sorted list. The aim is to create the smallest working programme, in whatever language you like.

For example:

```<code>input:  ((1, 4, 7), (2, 5, 8), (3, 6, 9))
output: (1, 2, 3, 4, 5, 6, 7, 8, 9)

input:  ((1, 10), (), (2, 5, 6, 7))
output: (1, 2, 5, 6, 7, 10)
</code>```

Note: solutions which concatenate the input lists then use a language-provided sort function are not in-keeping with the spirit of golf, and will not be accepted:

```<code>sorted(sum(lists,[])) # cheating: out of bounds!
</code>```

Apart from anything else, your algorithm should be (but doesn't have to be) a lot faster!

Clearly state the language, any foibles and the character count. Only include meaningful characters in the count, but feel free to add whitespace to the code for artistic / readability purposes.

To keep things tidy, suggest improvement in comments or by editing answers where appropriate, rather than creating a new answer for each "revision".

EDIT: if I was submitting this question again, I would expand on the "no language provided sort" rule to be "don't concatenate all the lists then sort the result". Existing entries which do concatenate-then-sort are actually very interesting and compact, so I won't retro-actively introduce a rule they break, but feel free to work to the more restrictive spec in new submissions.

Inspired by Combining two sorted lists in Python

答:
(all other solutions are O(N) (for the input provided))

If we let N be the number of elements in the output and k the number of input lists, then you can't do faster than O(N log k) -- suppose that each list was only a single element, and you'd have faster-than-O(N log N) comparison-based sorting.

Those I've looked at look more like they're O(N*k).

You can fairly easily get down to O(N log k) time: just put the lists in a heap.  This is one of the ways to do I/O-efficient sorting (you can generalize quicksort and heaps/heapsort as well).

[no code, just commentary]

OwnerDisplayName: jamesbrady

ContentLicense: CC BY-SA 2.5

Body:
Implement an algorithm to merge an arbitrary number of sorted lists into one sorted list. The aim is to create the smallest working programme, in whatever language you like.

For example:

input:  ((1, 4, 7), (2, 5, 8), (3, 6, 9))
output: (1, 2, 3, 4, 5, 6, 7, 8, 9)

input:  ((1, 10), (), (2, 5, 6, 7))
output: (1, 2, 5, 6, 7, 10)

Note: solutions which concatenate the input lists then use a language-provided sort function are not in-keeping with the spirit of golf, and will not be accepted:

sorted(sum(lists,[])) # cheating: out of bounds!

Apart from anything else, your algorithm should be (but doesn't have to be) a lot faster!

Clearly state the language, any foibles and the character count. Only include meaningful characters in the count, but feel free to add whitespace to the code for artistic / readability purposes.

To keep things tidy, suggest improvement in comments or by editing answers where appropriate, rather than creating a new answer for each "revision".

EDIT: if I was submitting this question again, I would expand on the "no language provided sort" rule to be "don't concatenate all the lists then sort the result". Existing entries which do concatenate-then-sort are actually very interesting and compact, so I won't retro-actively introduce a rule they break, but feel free to work to the more restrictive spec in new submissions.

Inspired by Combining two sorted lists in Python

LastEditorDisplayName: Alabaster Codify

OwnerDisplayName: Jonas Kölker


问:
How to extract words from sample corpus that comes with NLTK?
NLTK comes with some samples of corpus at:
http://nltk.googlecode.com/svn/trunk/nltk_data/index.xml

I want to have only text without encodings. I do not know how to extract such content. What I want to extract are

1) nps_chat: filename is like 10-19-20s_706posts.xml after unzip.
Such file is XML format like:

```<code><Posts>
<Post class="Statement" user="10-19-20sUser7">now im left with this gay name<terminals>

                <t pos="RB" word="now"/>
                <t pos="PRP" word="im"/>
                <t pos="VBD" word="left"/>
                <t pos="IN" word="with"/>
                <t pos="DT" word="this"/>
                <t pos="JJ" word="gay"/>
                <t pos="NN" word="name"/>
            </terminals>

        </Post>
            ...
            ...
</code>```

I only want that actual post:

```<code>now im left with this gay name
</code>```

How can do in NLTK or (whatever) to save the bare posts after stripping encodings in local disk?

2) switchboard transcript. This type of file (filename is discourse after unzip) contains the following formats. What I want is to strip preceding markers:

```<code>o A.1 utt1: Okay, /
qy A.1 utt2: have you ever served as a juror? /
ng B.2 utt1: Never. /
sd^e B.2 utt2: I've never been served on the jury, never been called up in a jury, although some of my friends have been jurors. /
b A.3 utt1: Uh-huh. /
sd A.3 utt2: I never have either. /
% B.4 utt1: You haven't, {F huh. } /
...
...
</code>```

I want to have only:

```<code>Okay, /
have you ever served as a juror? /
Never. /
I've never been served on the jury, never been called up in a jury, although some of my friends have been jurors. /
Uh-huh. /
I never have either. /
You haven't, {F huh. } /
...
...
</code>```

Thank you very much in advance.

答:
First, you need to make a corpus reader for the corpus. There are some corpus readers that you can use in nltk.corpus, such as:

```<code>AlpinoCorpusReader
BNCCorpusReader
BracketParseCorpusReader
CMUDictCorpusReader
CategorizedCorpusReader
CategorizedPlaintextCorpusReader
CategorizedTaggedCorpusReader
ChunkedCorpusReader
ConllChunkCorpusReader
ConllCorpusReader
CorpusReader
DependencyCorpusReader
EuroparlCorpusReader
IEERCorpusReader
IPIPANCorpusReader
IndianCorpusReader
MacMorphoCorpusReader
NPSChatCorpusReader
NombankCorpusReader
PPAttachmentCorpusReader
Pl196xCorpusReader
PlaintextCorpusReader
PortugueseCategorizedPlaintextCorpusReader
PropbankCorpusReader
RTECorpusReader
SensevalCorpusReader
SinicaTreebankCorpusReader
StringCategoryCorpusReader
SwadeshCorpusReader
SwitchboardCorpusReader
SyntaxCorpusReader
TaggedCorpusReader
TimitCorpusReader
ToolboxCorpusReader
VerbnetCorpusReader
WordListCorpusReader
WordNetCorpusReader
WordNetICCorpusReader
XMLCorpusReader
YCOECorpusReader
</code>```

Once you've made a corpus reader out of your corpus like so:

```<code>c = nltk.corpus.whateverCorpusReaderYouChoose(directoryWithCorpus, regexForFileTypes)
</code>```

you can get the words out of the corpus by using the following code:

```<code>paragraphs = [para for para in c.paras()]
for para in paragraphs:
    words = [word for sentence in para for word in sentence]
</code>```

This should get you a list of all the words in all the paragraphs of your corpus.

Hope this helps

Body:
NLTK comes with some samples of corpus at:
http://nltk.googlecode.com/svn/trunk/nltk_data/index.xml

I want to have only text without encodings. I do not know how to extract such content. What I want to extract are

1) nps_chat: filename is like 10-19-20s_706posts.xml after unzip.
Such file is XML format like:

<Posts>
<Post class="Statement" user="10-19-20sUser7">now im left with this gay name<terminals>

                <t pos="RB" word="now"/>
                <t pos="PRP" word="im"/>
                <t pos="VBD" word="left"/>
                <t pos="IN" word="with"/>
                <t pos="DT" word="this"/>
                <t pos="JJ" word="gay"/>
                <t pos="NN" word="name"/>
            </terminals>

        </Post>
            ...
            ...

I only want that actual post:

now im left with this gay name

How can do in NLTK or (whatever) to save the bare posts after stripping encodings in local disk?

2) switchboard transcript. This type of file (filename is discourse after unzip) contains the following formats. What I want is to strip preceding markers:

o A.1 utt1: Okay, /
qy A.1 utt2: have you ever served as a juror? /
ng B.2 utt1: Never. /
sd^e B.2 utt2: I've never been served on the jury, never been called up in a jury, although some of my friends have been jurors. /
b A.3 utt1: Uh-huh. /
sd A.3 utt2: I never have either. /
% B.4 utt1: You haven't, {F huh. } /
...
...

I want to have only:

Okay, /
have you ever served as a juror? /
Never. /
I've never been served on the jury, never been called up in a jury, although some of my friends have been jurors. /
Uh-huh. /
I never have either. /
You haven't, {F huh. } /
...
...

Thank you very much in advance.

Body:
First, you need to make a corpus reader for the corpus. There are some corpus readers that you can use in nltk.corpus, such as:

AlpinoCorpusReader
BNCCorpusReader
BracketParseCorpusReader
CMUDictCorpusReader
CategorizedCorpusReader
CategorizedPlaintextCorpusReader
CategorizedTaggedCorpusReader
ChunkedCorpusReader
ConllChunkCorpusReader
ConllCorpusReader
CorpusReader
DependencyCorpusReader
EuroparlCorpusReader
IEERCorpusReader
IPIPANCorpusReader
IndianCorpusReader
MacMorphoCorpusReader
NPSChatCorpusReader
NombankCorpusReader
PPAttachmentCorpusReader
Pl196xCorpusReader
PlaintextCorpusReader
PortugueseCategorizedPlaintextCorpusReader
PropbankCorpusReader
RTECorpusReader
SensevalCorpusReader
SinicaTreebankCorpusReader
StringCategoryCorpusReader
SwadeshCorpusReader
SwitchboardCorpusReader
SyntaxCorpusReader
TaggedCorpusReader
TimitCorpusReader
ToolboxCorpusReader
VerbnetCorpusReader
WordListCorpusReader
WordNetCorpusReader
WordNetICCorpusReader
XMLCorpusReader
YCOECorpusReader

Once you've made a corpus reader out of your corpus like so:

c = nltk.corpus.whateverCorpusReaderYouChoose(directoryWithCorpus, regexForFileTypes)

you can get the words out of the corpus by using the following code:

paragraphs = [para for para in c.paras()]
for para in paragraphs:
    words = [word for sentence in para for word in sentence]

This should get you a list of all the words in all the paragraphs of your corpus.

Hope this helps


问:
Not sure how to do a while loop in this situation
I am writing a program to take the input for a sequence

```<code>import java.util.Scanner;
</code>```

public class FibonacciCode {

```<code>public static void main(String[] args) {

    System.out.println("Enter a number");

    int count, number0 = 0, number1 = 1, loop = 0;

    Scanner userInput = new Scanner(System.in);
    count = userInput.nextInt();

    while(loop > count)
    {
        System.out.print(number0 + ", ");

        int sum = number0 + number1;
        number0 = number1;
        number1 = sum;
        loop++;
    }
}
</code>```

}

答:
A while loop does whatever is in the block as long as the condition is true, in your case, you are simply repeating order = b.nextInt() until something other than 'y' is given as input

```<code>while (continuePlay= b.nextLine().equalsIgnoreCase ("y")) {
        order = b.nextInt(); // This is inside the block
    }
</code>```

you should use a do while loop instead, like so:

```<code>do{
    System.out.println("Welcome to Hess Burgers");
    System.out.println("1- Cheeseburger.............$7");
    System.out.println("2- Barbeque Burger..........$8");
    System.out.println("3- Southwestern Burger......$9");
    System.out.println("4- Bacon Cheeseburger.......$10");
    System.out.println("5- Double Stack Burger......$11");
    System.out.println("                               ");
    System.out.print("Please enter your order selection:");

    Scanner a = new Scanner(System.in);
    int order = a.nextInt();

    int total = 0;
    boolean continuePlay = true;

    if (order == 1 ) {

    } else if (order == 2) {

    } else if (order == 3) {

    } else if (order == 4) {

    } else if (order == 5) {
    }
    Scanner b = new Scanner(System.in);

    System.out.println("Would you like to order more? Press 'y' to continue or 'n' to finish order.");
    } while (continuePlay= b.nextLine().equalsIgnoreCase ("y"));
</code>```

Also I'd recommend reading some basic programming books or tutorials instead of going directly to Stack Overflow.

ContentLicense: CC BY-SA 3.0

Body:
I am writing a program to take the input for a sequence

import java.util.Scanner;

public class FibonacciCode {

public static void main(String[] args) {

    System.out.println("Enter a number");

    int count, number0 = 0, number1 = 1, loop = 0;

    Scanner userInput = new Scanner(System.in);
    count = userInput.nextInt();

    while(loop > count)
    {
        System.out.print(number0 + ", ");

        int sum = number0 + number1;
        number0 = number1;
        number1 = sum;
        loop++;
    }
}

}

Body:
A while loop does whatever is in the block as long as the condition is true, in your case, you are simply repeating order = b.nextInt() until something other than 'y' is given as input

while (continuePlay= b.nextLine().equalsIgnoreCase ("y")) {
        order = b.nextInt(); // This is inside the block
    }

you should use a do while loop instead, like so:

do{
    System.out.println("Welcome to Hess Burgers");
    System.out.println("1- Cheeseburger.............$7");
    System.out.println("2- Barbeque Burger..........$8");
    System.out.println("3- Southwestern Burger......$9");
    System.out.println("4- Bacon Cheeseburger.......$10");
    System.out.println("5- Double Stack Burger......$11");
    System.out.println("                               ");
    System.out.print("Please enter your order selection:");

    Scanner a = new Scanner(System.in);
    int order = a.nextInt();

    int total = 0;
    boolean continuePlay = true;

    if (order == 1 ) {

    } else if (order == 2) {

    } else if (order == 3) {

    } else if (order == 4) {

    } else if (order == 5) {
    }
    Scanner b = new Scanner(System.in);

    System.out.println("Would you like to order more? Press 'y' to continue or 'n' to finish order.");
    } while (continuePlay= b.nextLine().equalsIgnoreCase ("y"));

Also I'd recommend reading some basic programming books or tutorials instead of going directly to Stack Overflow.


答:
This should be a usable implementation:

```<code>public class Menu {

    public static void main(String[] args) {
        Scanner a = new Scanner(System.in);
        boolean orderCompleted = false;
        while(!orderCompleted) {
            printMenu();
            String orderString = a.nextLine();
            int order = Integer.parseInt(orderString);
            int total = 0;
            if(order == 1) {
            } else if(order == 2) {
            } else if(order == 3) {
            } else if(order == 4) {
            } else if(order == 5) {
            }
            System.out.println("Would you like to order more? Press 'y' to continue or 'n' to finish order.");
            orderString = a.nextLine();
            if(orderString.equals("n")){
                orderCompleted = true;
            }
        }
    }

    private static void printMenu() {
        System.out.println("Welcome to Hess Burgers");
        System.out.println("1- Cheeseburger.............$7");
        System.out.println("2- Barbeque Burger..........$8");
        System.out.println("3- Southwestern Burger......$9");
        System.out.println("4- Bacon Cheeseburger.......$10");
        System.out.println("5- Double Stack Burger......$11");
        System.out.println("");
        System.out.print("Please enter your order selection:");
    }
}
</code>```

I pulled the menu printing to a separate method, and re-used scanner a as well as re-using the orderString. The while loop checks a completedOrder boolean flag, so that it can be used to do completion tasks prior to exiting the order loop if need be.

Title: Not sure how to do a while loop in this situation

Body:
This should be a usable implementation:

public class Menu {

    public static void main(String[] args) {
        Scanner a = new Scanner(System.in);
        boolean orderCompleted = false;
        while(!orderCompleted) {
            printMenu();
            String orderString = a.nextLine();
            int order = Integer.parseInt(orderString);
            int total = 0;
            if(order == 1) {
            } else if(order == 2) {
            } else if(order == 3) {
            } else if(order == 4) {
            } else if(order == 5) {
            }
            System.out.println("Would you like to order more? Press 'y' to continue or 'n' to finish order.");
            orderString = a.nextLine();
            if(orderString.equals("n")){
                orderCompleted = true;
            }
        }
    }

    private static void printMenu() {
        System.out.println("Welcome to Hess Burgers");
        System.out.println("1- Cheeseburger.............$7");
        System.out.println("2- Barbeque Burger..........$8");
        System.out.println("3- Southwestern Burger......$9");
        System.out.println("4- Bacon Cheeseburger.......$10");
        System.out.println("5- Double Stack Burger......$11");
        System.out.println("");
        System.out.print("Please enter your order selection:");
    }
}

I pulled the menu printing to a separate method, and re-used scanner a as well as re-using the orderString. The while loop checks a completedOrder boolean flag, so that it can be used to do completion tasks prior to exiting the order loop if need be.


问:
Getting null while trying to get an object propriety inside localStorage
I have this code:

```<code>let cart = [];
let item1 = {
        name: "CD - Animal",
        price: "12",
        qntd: "0"
    };

let item2 = {
    name: "CD - Cannibal",
    price: "10",
    qntd: "0"
};

$("button").click(function() {
    event.preventDefault();
    var li = $(this).parent();
    var quantity = $(li).find('input[type=number]').val();
    eval($(this).val()).qntd = quantity;
    cart.push(eval($(this).val()));
    console.log(item1.qntd);
    localStorage.setItem(cart, JSON.stringify(cart));
    console.log(cart[0].name);
    console.log(JSON.parse((localStorage.getItem(cart[0].name))));
});
</code>```

But cart[0].name does not return the object's name, instead, returns null.

cart[0] returns the object correctly, 0:{name: "CD - Animal", price: "12", qntd: "3"}, but when I try to get cart[0].name, it returns null instead of "CD - Animal".

HTML:

```<code><div class="card-content animal">
    <form style = "display: flex; justify-content: space-between; flex-wrap: wrap;">
        <input type = "number" class = "qntd" placeholder="Quantidade" style = "width: 100%; margin-top: -20px;" maxlength="10">
        <button class="btn waves-effect waves-light" type="submit" name="action" value = "item1">Add
            <i class="material-icons right">attach_money</i>
        </button>
    </form>
</div>
</code>```

答:
Use index on the parsed localStorage item.

Try JSON.parse((localStorage.getItem(cart)))[0].name instead of

JSON.parse((localStorage.getItem(cart[0].name)));

Body:
I have this code:

let cart = [];
let item1 = {
        name: "CD - Animal",
        price: "12",
        qntd: "0"
    };

let item2 = {
    name: "CD - Cannibal",
    price: "10",
    qntd: "0"
};

$("button").click(function() {
    event.preventDefault();
    var li = $(this).parent();
    var quantity = $(li).find('input[type=number]').val();
    eval($(this).val()).qntd = quantity;
    cart.push(eval($(this).val()));
    console.log(item1.qntd);
    localStorage.setItem(cart, JSON.stringify(cart));
    console.log(cart[0].name);
    console.log(JSON.parse((localStorage.getItem(cart[0].name))));
});

But cart[0].name does not return the object's name, instead, returns null.

cart[0] returns the object correctly, 0:{name: "CD - Animal", price: "12", qntd: "3"}, but when I try to get cart[0].name, it returns null instead of "CD - Animal".

HTML:

    <form style = "display: flex; justify-content: space-between; flex-wrap: wrap;">
        <input type = "number" class = "qntd" placeholder="Quantidade" style = "width: 100%; margin-top: -20px;" maxlength="10">
        <button class="btn waves-effect waves-light" type="submit" name="action" value = "item1">Add
            attach_money
        </button>
    </form>


问:
Java DAO for all class
I'm new to Java and I must make some DAO for my app. However, I don't want to make a DAO for each class (with interface) et override methods.
Is it possible to make a DAO extended by all the others, with methods working with all kind of Class ?
For example, a DAO that could handle class MyClass and class Foo with a single mehtod getList().
Thank you !</p>

答:
And if you mean you want to make a generic repository (DAO), again not that good idea, because Spring has already made it in a quite good way (it calls JpaRepository, e.g. interface MyRepository extends JpaRepository<User, Long> { }):
Source: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.multiple-modules

But if you want, you can make such a mechanism too, based on something like this (but it will be a cumbersome work to make it work like it does in Spring, for instance; because they are a team of experts who worked day and night to realize such a tremendous project):

```<code>public abstract class Repo<T, K> {
    public abstract T read(K id);
    public abstract List<T> findAll();
}
</code>```

or

```<code>public interface Repo<T, K> {
    T read(K id);
    List<T> findAll();
}
</code>```

Title: Java DAO for all class

Body:
And if you mean you want to make a generic repository (DAO), again not that good idea, because Spring has already made it in a quite good way (it calls JpaRepository, e.g. interface MyRepository extends JpaRepository<User, Long> { }):
Source: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.multiple-modules

But if you want, you can make such a mechanism too, based on something like this (but it will be a cumbersome work to make it work like it does in Spring, for instance; because they are a team of experts who worked day and night to realize such a tremendous project):

public abstract class Repo<T, K> {
    public abstract T read(K id);
    public abstract List<T> findAll();
}

or

public interface Repo<T, K> {
    T read(K id);
    List<T> findAll();
}


问:
Placing an image inside irregular shaped div
I have sets of skewed divs that I would like a separate image in each. Is this possible? If I try to place an image inside, the image is also skewed and looks distorted. How can I fix this? Essentially I would like an image in the black colored spaced. Please and thank you for all your help in advance!!!

.wrap {
  position: relative;
  width: 95vw;
  height: 20vw;
  margin-right: auto;
  margin-left: auto;
  background: white;
  overflow: hidden;
}
.button-skewed .button {
  width: 98%;
  height: 100%;
  background: black;
  display: inline-block;
  text-align: center;
  box-shadow: inset 0 0 0 1vw #008080, inset 0 0 0 1.1vw #fff;
}
.button-skewed .button:hover ~ span {
  background: #007a7a !important;
}
.button-skewed .button:hover ~ span:before {
  background: #007a7a !important;
}
.button-skewed .button:hover {
  background: #007a7a;
  box-shadow: inset 0 0 0 1vw #007a7a, inset 0 0 0 1.1vw #fff;
}
.button-skewed .button.left {
  margin-left: -1.7vw;
  position: absolute;
  left: 0%;
  transform: skewX(-20deg) translate(-50%, -50%);
  top: 50%;
}

.button-skewed .button.right {
  margin-right: 1.7vw;
  width: 200%;
  position: absolute;
  transform: skewX(-20deg) translate(100%, -50%);
  top: 50%;
  right: 50%;
}
.button-skewed .button .titleleft {
  position: absolute;
  top: 50%;
  left: 71%;
  transform: skewX(20deg) translate(-50%, -50%);
  display: inline-block;
  font-family: montserrat;
  color: white;
  font-size: 2.6vw;
  text-shadow: 2px 2px 5px #000;
}

.button-skewed .button .titleright {
  position: absolute;
  top: 50%;
  left: 12%;
  transform: skewX(20deg) translate(-50%, -50%);
  display: inline-block;
  font-family: montserrat;
  color: white;
  font-size: 2.6vw;
  text-shadow: 2px 2px 5px #000;
}

.button-skewed img {
   position: relative;
  background-size: cover;
}

.mask-outer-left {
  position: absolute;
  left: 0;
  top: 0;
  height: calc(100% - 2vw);
  margin-top: 1vw;
  margin-bottom: 1vw;
}
.mask-outer-left:before {
  content: '';
  background: white;
  position: absolute;
  height: 200%;
  width: 100%;
  top: 50%;
  left: 49%;
  transform: translate(-50%, -50%);
}
.mask-outer-right {
  position: absolute;
  right: 0;
  top: 0;
  height: calc(100% - 2vw);
  margin-top: 1vw;
  margin-bottom: 1vw;
}
.mask-outer-right:before {
  content: '';
  background: white;
  position: absolute;
  height: 200%;
  width: 100%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrap">
  <div class="button-skewed"><span class="titleleft">title here</span><span class="mask mask-outer-left"></span><span class="titleright">title here</span><span class="mask mask-outer-right"></span></div>
</div>
<br>
<div class="wrap">
  <div class="button-skewed"><span class="titleleft">title here</span><span class="mask mask-outer-left"></span><span class="titleright">title here</span><span class="mask mask-outer-right"></span></div>
</div></code>```

答:
You may simply add a second css class which skews in the opposite direction. Perhaps someone has a more elegant solution:

```<code>.button-skewed .button img {
  transform: skewX(20deg)
}
</code>```

.wrap {
  position: relative;
  width: 95vw;
  height: 20vw;
  margin-right: auto;
  margin-left: auto;
  background: white;
  overflow: hidden;
}
.button-skewed .button {
  width: 98%;
  height: 100%;
  background: black;
  display: inline-block;
  text-align: center;
  box-shadow: inset 0 0 0 1vw #008080, inset 0 0 0 1.1vw #fff;
}
.button-skewed .button:hover ~ span {
  background: #007a7a !important;
}
.button-skewed .button:hover ~ span:before {
  background: #007a7a !important;
}
.button-skewed .button:hover {
  background: #007a7a;
  box-shadow: inset 0 0 0 1vw #007a7a, inset 0 0 0 1.1vw #fff;
}
.button-skewed .button.left {
  margin-left: -1.7vw;
  position: absolute;
  left: 0%;
  transform: skewX(-20deg) translate(-50%, -50%);
  top: 50%;
}

.button-skewed .button.right {
  margin-right: 1.7vw;
  width: 200%;
  position: absolute;
  transform: skewX(-20deg) translate(100%, -50%);
  top: 50%;
  right: 50%;
}
.button-skewed .button .titleleft {
  position: absolute;
  top: 50%;
  left: 71%;
  transform: skewX(20deg) translate(-50%, -50%);
  display: inline-block;
  font-family: montserrat;
  color: white;
  font-size: 2.6vw;
  text-shadow: 2px 2px 5px #000;
}

.button-skewed .button .titleright {
  position: absolute;
  top: 50%;
  left: 12%;
  transform: skewX(20deg) translate(-50%, -50%);
  display: inline-block;
  font-family: montserrat;
  color: white;
  font-size: 2.6vw;
  text-shadow: 2px 2px 5px #000;
}

.button-skewed img {
   position: relative;
  background-size: cover;
}

.mask-outer-left {
  position: absolute;
  left: 0;
  top: 0;
  height: calc(100% - 2vw);
  margin-top: 1vw;
  margin-bottom: 1vw;
}
.mask-outer-left:before {
  content: '';
  background: white;
  position: absolute;
  height: 200%;
  width: 100%;
  top: 50%;
  left: 49%;
  transform: translate(-50%, -50%);
}
.mask-outer-right {
  position: absolute;
  right: 0;
  top: 0;
  height: calc(100% - 2vw);
  margin-top: 1vw;
  margin-bottom: 1vw;
}
.mask-outer-right:before {
  content: '';
  background: white;
  position: absolute;
  height: 200%;
  width: 100%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.button-skewed .button img {
  transform: skewX(20deg)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrap">
  <div class="button-skewed"><img src="https://fxfactory.com/downloads/docs/noiseindustries/fxfactorypro/Thumbnails/Stripes.jpg"/><span class="titleleft">title here</span><span class="mask mask-outer-left"></span><span class="titleright">title here</span><span class="mask mask-outer-right"></span></div>
</div>
<br>
<div class="wrap">
  <div class="button-skewed"><span class="titleleft">title here</span><span class="mask mask-outer-left"></span><span class="titleright">title here</span><span class="mask mask-outer-right"></span></div>
</div></code>```

Body:
I have sets of skewed divs that I would like a separate image in each. Is this possible? If I try to place an image inside, the image is also skewed and looks distorted. How can I fix this? Essentially I would like an image in the black colored spaced. Please and thank you for all your help in advance!!!

.wrap {
  position: relative;
  width: 95vw;
  height: 20vw;
  margin-right: auto;
  margin-left: auto;
  background: white;
  overflow: hidden;
}
.button-skewed .button {
  width: 98%;
  height: 100%;
  background: black;
  display: inline-block;
  text-align: center;
  box-shadow: inset 0 0 0 1vw #008080, inset 0 0 0 1.1vw #fff;
}
.button-skewed .button:hover ~ span {
  background: #007a7a !important;
}
.button-skewed .button:hover ~ span:before {
  background: #007a7a !important;
}
.button-skewed .button:hover {
  background: #007a7a;
  box-shadow: inset 0 0 0 1vw #007a7a, inset 0 0 0 1.1vw #fff;
}
.button-skewed .button.left {
  margin-left: -1.7vw;
  position: absolute;
  left: 0%;
  transform: skewX(-20deg) translate(-50%, -50%);
  top: 50%;
}

.button-skewed .button.right {
  margin-right: 1.7vw;
  width: 200%;
  position: absolute;
  transform: skewX(-20deg) translate(100%, -50%);
  top: 50%;
  right: 50%;
}
.button-skewed .button .titleleft {
  position: absolute;
  top: 50%;
  left: 71%;
  transform: skewX(20deg) translate(-50%, -50%);
  display: inline-block;
  font-family: montserrat;
  color: white;
  font-size: 2.6vw;
  text-shadow: 2px 2px 5px #000;
}

.button-skewed .button .titleright {
  position: absolute;
  top: 50%;
  left: 12%;
  transform: skewX(20deg) translate(-50%, -50%);
  display: inline-block;
  font-family: montserrat;
  color: white;
  font-size: 2.6vw;
  text-shadow: 2px 2px 5px #000;
}

.button-skewed img {
   position: relative;
  background-size: cover;
}

.mask-outer-left {
  position: absolute;
  left: 0;
  top: 0;
  height: calc(100% - 2vw);
  margin-top: 1vw;
  margin-bottom: 1vw;
}
.mask-outer-left:before {
  content: '';
  background: white;
  position: absolute;
  height: 200%;
  width: 100%;
  top: 50%;
  left: 49%;
  transform: translate(-50%, -50%);
}
.mask-outer-right {
  position: absolute;
  right: 0;
  top: 0;
  height: calc(100% - 2vw);
  margin-top: 1vw;
  margin-bottom: 1vw;
}
.mask-outer-right:before {
  content: '';
  background: white;
  position: absolute;
  height: 200%;
  width: 100%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

title heretitle here

title heretitle here

Body:
You may simply add a second css class which skews in the opposite direction. Perhaps someone has a more elegant solution:

.button-skewed .button img {
  transform: skewX(20deg)
}

.wrap {
  position: relative;
  width: 95vw;
  height: 20vw;
  margin-right: auto;
  margin-left: auto;
  background: white;
  overflow: hidden;
}
.button-skewed .button {
  width: 98%;
  height: 100%;
  background: black;
  display: inline-block;
  text-align: center;
  box-shadow: inset 0 0 0 1vw #008080, inset 0 0 0 1.1vw #fff;
}
.button-skewed .button:hover ~ span {
  background: #007a7a !important;
}
.button-skewed .button:hover ~ span:before {
  background: #007a7a !important;
}
.button-skewed .button:hover {
  background: #007a7a;
  box-shadow: inset 0 0 0 1vw #007a7a, inset 0 0 0 1.1vw #fff;
}
.button-skewed .button.left {
  margin-left: -1.7vw;
  position: absolute;
  left: 0%;
  transform: skewX(-20deg) translate(-50%, -50%);
  top: 50%;
}

.button-skewed .button.right {
  margin-right: 1.7vw;
  width: 200%;
  position: absolute;
  transform: skewX(-20deg) translate(100%, -50%);
  top: 50%;
  right: 50%;
}
.button-skewed .button .titleleft {
  position: absolute;
  top: 50%;
  left: 71%;
  transform: skewX(20deg) translate(-50%, -50%);
  display: inline-block;
  font-family: montserrat;
  color: white;
  font-size: 2.6vw;
  text-shadow: 2px 2px 5px #000;
}

.button-skewed .button .titleright {
  position: absolute;
  top: 50%;
  left: 12%;
  transform: skewX(20deg) translate(-50%, -50%);
  display: inline-block;
  font-family: montserrat;
  color: white;
  font-size: 2.6vw;
  text-shadow: 2px 2px 5px #000;
}

.button-skewed img {
   position: relative;
  background-size: cover;
}

.mask-outer-left {
  position: absolute;
  left: 0;
  top: 0;
  height: calc(100% - 2vw);
  margin-top: 1vw;
  margin-bottom: 1vw;
}
.mask-outer-left:before {
  content: '';
  background: white;
  position: absolute;
  height: 200%;
  width: 100%;
  top: 50%;
  left: 49%;
  transform: translate(-50%, -50%);
}
.mask-outer-right {
  position: absolute;
  right: 0;
  top: 0;
  height: calc(100% - 2vw);
  margin-top: 1vw;
  margin-bottom: 1vw;
}
.mask-outer-right:before {
  content: '';
  background: white;
  position: absolute;
  height: 200%;
  width: 100%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.button-skewed .button img {
  transform: skewX(20deg)
}

<div class="wrap">
  <div class="button-skewed"><a class="button left" href="#"><img src="https://fxfactory.com/downloads/docs/noiseindustries/fxfactorypro/Thumbnails/Stripes.jpg"/><span class="titleleft">title here</span></a><span class="mask mask-outer-left"></span><a class="button right" href="#"><span class="titleright">title here</span></a><span class="mask mask-outer-right"></span></div>
</div>
<br>
<div class="wrap">
  <div class="button-skewed"><a class="button left" href="#"><span class="titleleft">title here</span></a><span class="mask mask-outer-left"></span><a class="button right" href="#"><span class="titleright">title here</span></a><span class="mask mask-outer-right"></span></div>
</div>


问:
Pandas If/then else with multiple conditions
This is such a simple thing yet I'm spending hours trying to figure out, when I could easily do this in SQL or Tableau.

So imagine I have an ID column and a Item1 and Item2 column. In SQL, I'd write:

```<code>CASE
WHEN Item1 IS NULL AND Item2 IS NULL
THEN '0'
WHEN Item1 IS NOT NULL AND ITEM2 IS NOT NULL
THEN '2'
WHEN Item1 IS NULL AND Item2 is NOT NULL
THEN '1'
WHEN Item1 IS NOT NULL AND Item2 IS NULL
THEN '1'
END
</code>```

Any ideas how I can replicate this in pandas?  To clarify, this has to be a NEW column with values either being 0, 1 or 2.

答:
Save new data in a existing column name 'item3':

```<code>for index, row in df.iterrows():

    if row['item1'] is None and row['item2'] is None:
        df.set_value(index, 'item3', 0)
    elif row['item1'] is None and row['item2'] is not None:
        df.set_value(index, 'item3', 1)
    elif row['item1'] is not None and row['item2'] is None :
        df.set_value(index, 'item3', 2)
    elif row['item1'] is not None and row['item2'] is not None:
        df.set_value(index, 'item3', 1)
</code>```

More compact:

```<code>for index, row in df.iterrows():

if row['item1'] is None and row['item2'] is None:
    df.set_value(index, 'item3', 0)
elif row['item2'] is not None:
    df.set_value(index, 'item3', 1)
else:
    df.set_value(index, 'item3', 2)
</code>```

Body:
This is such a simple thing yet I'm spending hours trying to figure out, when I could easily do this in SQL or Tableau.

So imagine I have an ID column and a Item1 and Item2 column. In SQL, I'd write:

CASE
WHEN Item1 IS NULL AND Item2 IS NULL
THEN '0'
WHEN Item1 IS NOT NULL AND ITEM2 IS NOT NULL
THEN '2'
WHEN Item1 IS NULL AND Item2 is NOT NULL
THEN '1'
WHEN Item1 IS NOT NULL AND Item2 IS NULL
THEN '1'
END

Any ideas how I can replicate this in pandas?  To clarify, this has to be a NEW column with values either being 0, 1 or 2.

Body:
Save new data in a existing column name 'item3':

for index, row in df.iterrows():

    if row['item1'] is None and row['item2'] is None:
        df.set_value(index, 'item3', 0)
    elif row['item1'] is None and row['item2'] is not None:
        df.set_value(index, 'item3', 1)
    elif row['item1'] is not None and row['item2'] is None :
        df.set_value(index, 'item3', 2)
    elif row['item1'] is not None and row['item2'] is not None:
        df.set_value(index, 'item3', 1)

More compact:

for index, row in df.iterrows():

if row['item1'] is None and row['item2'] is None:
    df.set_value(index, 'item3', 0)
elif row['item2'] is not None:
    df.set_value(index, 'item3', 1)
else:
    df.set_value(index, 'item3', 2)


问:
Filter rows based on ID over multiple data frames with for loop
How can I filter 180 .csv files from my global directory based on a matching ID in another df named 'Camera' in R? When I tried to incorporate my one by one file filtering code (see step 3b) into a for-loop (see step 3a) I get the error:

Error in paste("i")$SegmentID : $ operator is invalid for atomic vectors.

I'm quite new to for loop functions, so I really appreciate your help! All the 180 files have a unique name, are different in length, but have the same column structure & names. They look like:

```<code> df 'File1'             df 'Camera'
 ID  Speed  Location      ID  Time
 1   30    4              1   10
 2   35    5              3   11
 3   40    6              5   12
 4   30    7
 5   35    8

 Filtered df 'File1'
 ID  Speed  Location
 1   30    4
 3   40    6
 5   35    8
</code>```

These are some samples of my code:

```<code>#STEP 1: read files
filenames <- list.files(path="06-06-2017_0900-1200uur",
                        pattern="*.csv")

# STEP 2: import files
for(i in filenames){
  filepath <- file.path("06-06-2017_0900-1200uur",paste(i))
  assign(i, read.csv2(filepath, header = TRUE, skip = "1"))
}

# STEP 3a: delete rows that do not match ID in df 'Cameras'
for(i in filesnames){
    paste("i") <- paste("i")[paste("i")$ID %in% Cameras$ID,]
}

#STEP 3b: filtering one by one
    File1  <- File1[File1$ID   %in% Camera$ID,]
</code>```

答:
If I understand the question, the output should be a data frame from file1 where the ID for all rows matches one of the rows in the Camera file.

This is easily accomplished with the sqldf() package and structured query language.

```<code>rawFile1 <- "ID  Speed  Location
1   30    4
2   35    5
3   40    6
4   30    7
5   35    8
"

rawCamera <- "      ID  Time
1   10
3   11
5   12
"
file1 <- read.table(textConnection(rawFile1),header=TRUE)
Camera <- read.table(textConnection(rawCamera),header=TRUE)

library(sqldf)
sqlStmt <- "select * from file1 where ID in(select ID from Camera)"
sqldf(sqlStmt,drv="SQLite")
</code>```

...and the output:

```<code>  ID Speed Location
1  1    30        4
2  3    40        6
3  5    35        8
>
</code>```

To extend this logic to a number of csv files, first we obtain the list of files from the subdirectory where they are stored using the list.files() function. For example, if the files were in a data subdirectory of the R working directory, one might use the following function call.

```<code>theFiles <- list.files("./data/",".csv",full.names=TRUE)
</code>```

We can read these files with read.table() to create a list() of data frames.

```<code>theData <- lapply(theFiles,function(x) {
                      read.table(x,header=TRUE)})
</code>```

To combine the files into a single data frame, we execute do.call().

```<code>combinedData <- do.call(rbind,theData)
</code>```

Now we can read the camera data and use sqldf to keep only the IDs matching the camera data.

```<code>Camera <- read.table(...,header=TRUE)
library(sqldf)
sqlStmt <- "select * from combinedData where ID in(select ID from Camera)"
sqldf(sqlStmt,drv="SQLite")
</code>```

Body:
How can I filter 180 .csv files from my global directory based on a matching ID in another df named 'Camera' in R? When I tried to incorporate my one by one file filtering code (see step 3b) into a for-loop (see step 3a) I get the error:

Error in paste("i")$SegmentID : $ operator is invalid for atomic vectors.

I'm quite new to for loop functions, so I really appreciate your help! All the 180 files have a unique name, are different in length, but have the same column structure & names. They look like:

 df 'File1'             df 'Camera'
 ID  Speed  Location      ID  Time
 1   30    4              1   10
 2   35    5              3   11
 3   40    6              5   12
 4   30    7
 5   35    8

 Filtered df 'File1'
 ID  Speed  Location
 1   30    4
 3   40    6
 5   35    8

These are some samples of my code:

#STEP 1: read files
filenames <- list.files(path="06-06-2017_0900-1200uur",
                        pattern="*.csv")

# STEP 2: import files
for(i in filenames){
  filepath <- file.path("06-06-2017_0900-1200uur",paste(i))
  assign(i, read.csv2(filepath, header = TRUE, skip = "1"))
}

# STEP 3a: delete rows that do not match ID in df 'Cameras'
for(i in filesnames){
    paste("i") <- paste("i")[paste("i")$ID %in% Cameras$ID,]
}

#STEP 3b: filtering one by one
    File1  <- File1[File1$ID   %in% Camera$ID,]

Body:
If I understand the question, the output should be a data frame from file1 where the ID for all rows matches one of the rows in the Camera file.

This is easily accomplished with the sqldf() package and structured query language.

rawFile1 <- "ID  Speed  Location
1   30    4
2   35    5
3   40    6
4   30    7
5   35    8
"

rawCamera <- "      ID  Time
1   10
3   11
5   12
"
file1 <- read.table(textConnection(rawFile1),header=TRUE)
Camera <- read.table(textConnection(rawCamera),header=TRUE)

library(sqldf)
sqlStmt <- "select * from file1 where ID in(select ID from Camera)"
sqldf(sqlStmt,drv="SQLite")

...and the output:

  ID Speed Location
1  1    30        4
2  3    40        6
3  5    35        8
>

To extend this logic to a number of csv files, first we obtain the list of files from the subdirectory where they are stored using the list.files() function. For example, if the files were in a data subdirectory of the R working directory, one might use the following function call.

theFiles <- list.files("./data/",".csv",full.names=TRUE)

We can read these files with read.table() to create a list() of data frames.

theData <- lapply(theFiles,function(x) {
                      read.table(x,header=TRUE)})

To combine the files into a single data frame, we execute do.call().

combinedData <- do.call(rbind,theData)

Now we can read the camera data and use sqldf to keep only the IDs matching the camera data.

Camera <- read.table(...,header=TRUE)
library(sqldf)
sqlStmt <- "select * from combinedData where ID in(select ID from Camera)"
sqldf(sqlStmt,drv="SQLite")


问:
What's the problem in my code? c# winforms
I have two forms Login and Main form. Initially, the Login form will be displayed and when the user is authenticated, the Main form will be displayed and the Login form will be closed.

It's kinda working, but I have to click the btnLogin (a Button in the Login form) twice to close the Login form and show the Main form.

Here's my code.

Program.cs (Login form)

```<code>namespace Login
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Login fLogin = new Login();
            if (fLogin.ShowDialog() == DialogResult.OK)
            {
                Application.Run(new Main());
            }
        }
    }
}
</code>```

Login form

```<code>namespace Login
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }

        private void Login_Load(object sender, EventArgs e)
        {

        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            // initially btnLogin has a DialogResult property set to None
            Authenticate();
        }

        private void Authenticate()
        {
            SqlCeConnection conn = new SqlCeConnection(@"Data source=d:/BIMS.sdf");
            conn.Open();
            SqlCeCommand cmd = new SqlCeCommand(Properties.Resources.CheckIfUserExists, conn);
            cmd.Parameters.Add("username", txtUsername.Text.Trim());
            cmd.Parameters.Add("password", txtPassword.Text.Trim());

            SqlCeDataReader dr = cmd.ExecuteReader();
            bool hasRow = dr.Read();
            if (hasRow)
            {
                btnLogin.DialogResult = DialogResult.OK;
            }
        }
    }
}
</code>```

Where do you think I'm doing it wrong?
Thanks....

答:
It is a problem with your Authenticate() most likely. Can you remove that code and simply have

```<code>private void Authenticate()
{
   btnLogin.DialogResult = DialogResult.OK;
}
</code>```

This will tell you if if the problem is with the authentication code or with the gui.

If it's with your authen code it is possible that you need do a little more to access the database(check and see if you are connected, etc...)

Body:
I have two forms Login and Main form. Initially, the Login form will be displayed and when the user is authenticated, the Main form will be displayed and the Login form will be closed.

It's kinda working, but I have to click the btnLogin (a Button in the Login form) twice to close the Login form and show the Main form.

Here's my code.

Program.cs (Login form)

namespace Login
{
    static class Program
    {
        ///
        /// The main entry point for the application.
        ///
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Login fLogin = new Login();
            if (fLogin.ShowDialog() == DialogResult.OK)
            {
                Application.Run(new Main());
            }
        }
    }
}

Login form

namespace Login
{
    public partial class Login : Form
    {
        public Login()
        {
            InitializeComponent();
        }

        private void Login_Load(object sender, EventArgs e)
        {

        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            // initially btnLogin has a DialogResult property set to None
            Authenticate();
        }

        private void Authenticate()
        {
            SqlCeConnection conn = new SqlCeConnection(@"Data source=d:/BIMS.sdf");
            conn.Open();
            SqlCeCommand cmd = new SqlCeCommand(Properties.Resources.CheckIfUserExists, conn);
            cmd.Parameters.Add("username", txtUsername.Text.Trim());
            cmd.Parameters.Add("password", txtPassword.Text.Trim());

            SqlCeDataReader dr = cmd.ExecuteReader();
            bool hasRow = dr.Read();
            if (hasRow)
            {
                btnLogin.DialogResult = DialogResult.OK;
            }
        }
    }
}

Where do you think I'm doing it wrong?
Thanks....

Body:
It is a problem with your Authenticate() most likely. Can you remove that code and simply have

private void Authenticate()
{
   btnLogin.DialogResult = DialogResult.OK;
}

This will tell you if if the problem is with the authentication code or with the gui.

If it's with your authen code it is possible that you need do a little more to access the database(check and see if you are connected, etc...)


问:
how to read attributes for given DN in ldap3 (how to search with ldap3 if no filter)
If I already have an LDAP DN, how do I get the attributes for that DN with ldap3.Connection.search()? There is no other search criteria, I already have the DN...

I tried searching for dn attribute, but it returned no objects found. I also tried forcing search_filter to '', '()' or None and they all returned malformed filter string.

I also couldn't find a way to do this with the abstract Reader...

In ldapsearch you don't need to specify a search filter if you are doing a baseDN lookup...

```<code>import ldap3

ldap_conn = ldap3.Connection('ldapserver', raise_exceptions=True,
    auto_bind=True, user='me', password='mypassword')

my_dn = "attrib1=blahblah, ou=org1, dc=dc1, dc=dcroot"

ldap_conn.search(
    search_base=my_dn,
    search_filter= '(????)', # required
    search_scope=ldap3.BASE,
    attributes='*'
)

print(ldap_conn.response)
</code>```

答:
I just realized that objectClass will always be present, so setting it to wildcard should shim search_filter to return the 1 entry associated with base DN:

```<code>ldap_conn.search(
    search_base=my_dn,
    search_filter= '(objectClass=*)', # required
    search_scope=ldap3.BASE,
    attributes='*'
)
</code>```

However it seems silly there is no special case for LOOKUP operation against the connection given a DN in ldap3.

EDIT: @cannatag mentioned this was a limitation of the protocol, so I decided to check the RFC: (RFC 4511). Apparently, ldapsearch and Active Directory emulate an x.500-style LIST or READ by setting an objectClass presence filter :

Note that an X.500 "list"-like operation can be emulated by the
client requesting a singleLevel Search operation with a filter
checking for the presence of the 'objectClass' attribute, and that an
X.500 "read"-like operation can be emulated by a baseObject Search
operation with the same filter.  A server that provides a gateway to
X.500 is not required to use the Read or List operations, although it
may choose to do so, and if it does, it must provide the same
semantics as the X.500 Search operation.

ContentLicense: CC BY-SA 4.0

Body:
If I already have an LDAP DN, how do I get the attributes for that DN with ldap3.Connection.search()? There is no other search criteria, I already have the DN...

I tried searching for dn attribute, but it returned no objects found. I also tried forcing search_filter to '', '()' or None and they all returned malformed filter string.

I also couldn't find a way to do this with the abstract Reader...

In ldapsearch you don't need to specify a search filter if you are doing a baseDN lookup...

import ldap3

ldap_conn = ldap3.Connection('ldapserver', raise_exceptions=True,
    auto_bind=True, user='me', password='mypassword')

my_dn = "attrib1=blahblah, ou=org1, dc=dc1, dc=dcroot"

ldap_conn.search(
    search_base=my_dn,
    search_filter= '(????)', # required
    search_scope=ldap3.BASE,
    attributes='*'
)

print(ldap_conn.response)

Body:
I just realized that objectClass will always be present, so setting it to wildcard should shim search_filter to return the 1 entry associated with base DN:

ldap_conn.search(
    search_base=my_dn,
    search_filter= '(objectClass=*)', # required
    search_scope=ldap3.BASE,
    attributes='*'
)

However it seems silly there is no special case for LOOKUP operation against the connection given a DN in ldap3.

EDIT: @cannatag mentioned this was a limitation of the protocol, so I decided to check the RFC: (RFC 4511). Apparently, ldapsearch and Active Directory emulate an x.500-style LIST or READ by setting an objectClass presence filter :

Note that an X.500 "list"-like operation can be emulated by the
client requesting a singleLevel Search operation with a filter
checking for the presence of the 'objectClass' attribute, and that an
X.500 "read"-like operation can be emulated by a baseObject Search
operation with the same filter.  A server that provides a gateway to
X.500 is not required to use the Read or List operations, although it
may choose to do so, and if it does, it must provide the same
semantics as the X.500 Search operation.


问:
Angular 2 create element on click
I would like to ask how to implement this logic in Angular 2:
I have posts like this:

```<code><div class="postDetail clearfix">
  <div class="title float-left"><a href="#">Lorem ipsum dolor sit</a></div>
  <div class="createdAt float-right">before 10 hours</div>
  <br>
  <div class="desc float-left">Lorem ipsum dolor sit amet, <b>consectetur</b> adipisicing.</div>
  <div class="createdAt float-right">Preview >></div>
  <br>
</div>
</code>```

When I click "Preview >>" I would like to display after last br tag this code:

```<code><div class="loading">
    <mat-spinner [diameter]="40" [strokeWidth]="5"></mat-spinner>
</div>
</code>```

When async server call will finish and I'll have data in redux, I want to display following code instead of loading before:

```<code><div class="preview" style="display: none;">
    <img src="...">
    <span class="name">Name Surname</span>
    <p>Lorem ipsum dolor ...</p>
    <div class="foot">
      <b>Responses:</b> 221 | <a href="#">Show all</a>
    </div>
</div>
</code>```

I have no idea what logic should I use.

How should it work?
1. Server call onInit loads title and metadata
2. After clicking Preview button, will be shown loading spinner and made server call for data about specific post (there is so many data to load on init call)
3. When server call successfull, replace loading with actual data provided above

答:
You could use *ngIf on your different template and display the wanted template depending on your component state.

Example:

EDIT: Example with *ngFor

Template

```<code><div *ngFor="let user of users">
  <div class="postDetail clearfix" *ngIf=" ! user.loading && ! user.loaded">
    <div class="title float-left"><a href="#">Lorem ipsum dolor sit</a></div>
    <div class="createdAt float-right">before 10 hours</div>
    <br>
    <div class="desc float-left">Lorem ipsum dolor sit amet, <b>consectetur</b> adipisicing.</div>
    <div class="createdAt float-right" (click)="loadPreviewData(user)">Preview >></div>
    <br>
  </div>

  <div class="loading" *ngIf="user.loading">
    <mat-spinner [diameter]="40" [strokeWidth]="5"></mat-spinner>
  </div>

  <div class="preview" style="display: none;" *ngIf="user.loaded">
    <img src="...">
    <span class="name">Name Surname</span>
    <p>Lorem ipsum dolor ...</p>
    <div class="foot">
      <b>Responses:</b> 221 | <a href="#">Show all</a>
    </div>
  </div>
</div>
</code>```

Component

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  public users: Array<any>;

  constructor() {};

  ngOnInit() {
  // Get your initial value
     this.users.forEach(user => {
      user.loaded = false;
      user.loading = false;
   })
  }
  loadPreviewData(user) {
    user.loading = true;
    this.loadRemoteData().subscribe(data => {
      user.loading = false;
      user.loaded = true;
      user.data = data;
      // Display new data
    })
  }

  loadRemoteData() {
    // Method requesting data
  }
};
</code>```

Title: Angular 2 create element on click

Body:
I would like to ask how to implement this logic in Angular 2:
I have posts like this:

Lorem ipsum dolor sit

before 10 hours

Lorem ipsum dolor sit amet, consectetur adipisicing.

Preview >>

When I click "Preview >>" I would like to display after last br tag this code:

    <mat-spinner [diameter]="40" [strokeWidth]="5"></mat-spinner>

When async server call will finish and I'll have data in redux, I want to display following code instead of loading before:

    Name Surname

Lorem ipsum dolor ...

      Responses: 221 | Show all

I have no idea what logic should I use.

How should it work?
1. Server call onInit loads title and metadata
2. After clicking Preview button, will be shown loading spinner and made server call for data about specific post (there is so many data to load on init call)
3. When server call successfull, replace loading with actual data provided above

Body:
You could use *ngIf on your different template and display the wanted template depending on your component state.

Example:

EDIT: Example with *ngFor

Template

<div *ngFor="let user of users">
  <div class="postDetail clearfix" *ngIf=" ! user.loading && ! user.loaded">
    <div class="title float-left"><a href="#">Lorem ipsum dolor sit</a></div>
    <div class="createdAt float-right">before 10 hours</div>
    <br>
    <div class="desc float-left">Lorem ipsum dolor sit amet, <b>consectetur</b> adipisicing.</div>
    <div class="createdAt float-right" (click)="loadPreviewData(user)">Preview >></div>
    <br>
  </div>

  <div class="loading" *ngIf="user.loading">
    <mat-spinner [diameter]="40" [strokeWidth]="5"></mat-spinner>
  </div>

  <div class="preview" style="display: none;" *ngIf="user.loaded">
    <img src="...">
    <span class="name">Name Surname</span>
    <p>Lorem ipsum dolor ...</p>
    <div class="foot">
      <b>Responses:</b> 221 | <a href="#">Show all</a>
    </div>
  </div>
</div>

Component

import { Component } from '@angular/core';

@Component({
  selector: 'app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  public users: Array<any>;

  constructor() {};

  ngOnInit() {
  // Get your initial value
     this.users.forEach(user => {
      user.loaded = false;
      user.loading = false;
   })
  }
  loadPreviewData(user) {
    user.loading = true;
    this.loadRemoteData().subscribe(data => {
      user.loading = false;
      user.loaded = true;
      user.data = data;
      // Display new data
    })
  }

  loadRemoteData() {
    // Method requesting data
  }
};


问:
How to combine Arbitrary and IO monads?
I am trying to write a program which writes to a file a list of data generated by an Arbitrary instance, and I am having trouble combining the Arbitrary and IO monads.

A simplified version of what I am trying to do is shown below.

```<code>main = do
  let n = 10
  list <- vector n
  writeFile "output.txt" (unlines $ show <$> list)
</code>```

This leads to a type error since writeFile's IO monad does not match vector's Gen monad.

```<code>TestCases.hs:31:3: error:
    • Couldn't match type ‘IO’ with ‘Test.QuickCheck.Gen.Gen’
      Expected type: Test.QuickCheck.Gen.Gen ()
        Actual type: IO ()
    • In a stmt of a 'do' block:
        writeFile "output.txt" (unlines $ show <$> list)
      In the expression:
        do { let n = 10;
             list <- vector n;
             writeFile "output.txt" (unlines $ show <$> list) }
      In an equation for ‘main’:
          main
            = do { let n = ...;
                   list <- vector n;
                   writeFile "output.txt" (unlines $ show <$> list) }
</code>```

I have tried using liftIO to resolve this type mismatch, but it appears that this does not work due to Gen lacking a MonadIO instance.

```<code>main = do
  let n = 10
  list <- vector n :: Gen [Integer]
  liftIO $ writeFile "output.txt" (unlines $ show <$> list)
</code>```

gives the error

```<code>TestCases.hs:32:3: error:
    • No instance for (MonadIO Gen) arising from a use of ‘liftIO’
    • In a stmt of a 'do' block:
        liftIO $ writeFile "output.txt" (unlines $ show <$> list)
      In the expression:
        do { let n = 10;
             list <- vector n :: Gen [Integer];
             liftIO $ writeFile "output.txt" (unlines $ show <$> list) }
      In an equation for ‘main’:
          main
            = do { let n = ...;
                   list <- vector n :: Gen [Integer];
                   liftIO $ writeFile "output.txt" (unlines $ show <$> list) }
</code>```

How can I print an Arbitrary-generated list to a file?

答:
As Test.QuickCheck.Gen tells you, you can use GenT from QuickCheck-GenT. GenT m is a MonadIO instance whenever m is.

```<code>main = join . generate . runGenT $ do
  let n = 10
  list <- liftGen $ vector n
  liftIO $ writeFile "output.txt" (unlines $ show <$> list)
</code>```

seems likely to work.

Title: How to combine Arbitrary and IO monads?

Body:
I am trying to write a program which writes to a file a list of data generated by an Arbitrary instance, and I am having trouble combining the Arbitrary and IO monads.

A simplified version of what I am trying to do is shown below.

main = do
  let n = 10
  list <- vector n
  writeFile "output.txt" (unlines $ show <$> list)

This leads to a type error since writeFile's IO monad does not match vector's Gen monad.

TestCases.hs:31:3: error:
    • Couldn't match type ‘IO’ with ‘Test.QuickCheck.Gen.Gen’
      Expected type: Test.QuickCheck.Gen.Gen ()
        Actual type: IO ()
    • In a stmt of a 'do' block:
        writeFile "output.txt" (unlines $ show <$> list)
      In the expression:
        do { let n = 10;
             list <- vector n;
             writeFile "output.txt" (unlines $ show <$> list) }
      In an equation for ‘main’:
          main
            = do { let n = ...;
                   list <- vector n;
                   writeFile "output.txt" (unlines $ show <$> list) }

I have tried using liftIO to resolve this type mismatch, but it appears that this does not work due to Gen lacking a MonadIO instance.

main = do
  let n = 10
  list <- vector n :: Gen [Integer]
  liftIO $ writeFile "output.txt" (unlines $ show <$> list)

gives the error

TestCases.hs:32:3: error:
    • No instance for (MonadIO Gen) arising from a use of ‘liftIO’
    • In a stmt of a 'do' block:
        liftIO $ writeFile "output.txt" (unlines $ show <$> list)
      In the expression:
        do { let n = 10;
             list <- vector n :: Gen [Integer];
             liftIO $ writeFile "output.txt" (unlines $ show <$> list) }
      In an equation for ‘main’:
          main
            = do { let n = ...;
                   list <- vector n :: Gen [Integer];
                   liftIO $ writeFile "output.txt" (unlines $ show <$> list) }

How can I print an Arbitrary-generated list to a file?

Body:
As Test.QuickCheck.Gen tells you, you can use GenT from QuickCheck-GenT. GenT m is a MonadIO instance whenever m is.

main = join . generate . runGenT $ do
  let n = 10
  list <- liftGen $ vector n
  liftIO $ writeFile "output.txt" (unlines $ show <$> list)

seems likely to work.


问:
Gollum-wiki error from start
After succesful installation I do

sudo gollum  --port 80 and get error

```<code> Gollum::InvalidGitRepositoryError at /
       Gollum::InvalidGitRepositoryError
         file: git_layer_grit.rb location: rescue in initialize line: 280
        BACKTRACE
        (expand)
        JUMP TO: GET POST COOKIES ENV
         /usr/lib/ruby/1.9.1/webrick/httpserver.rb in service
  si.service(req, res)
         /usr/lib/ruby/1.9.1/webrick/httpserver.rb in run
      server.service(req, res)
        /usr/lib/ruby/1.9.1/webrick/server.rb in block in start_thread
      block ? block.call(sock) : run(sock)
</code>```

答:
You need to specify the git repo as an argument to gollum, like this:

gollum --port 80 /home/gollum/wiki

See gollum --help.

Title: Gollum-wiki error from start

Body:
After succesful installation I do

sudo gollum  --port 80 and get error

 Gollum::InvalidGitRepositoryError at /
       Gollum::InvalidGitRepositoryError
         file: git_layer_grit.rb location: rescue in initialize line: 280
        BACKTRACE
        (expand)
        JUMP TO: GET POST COOKIES ENV
         /usr/lib/ruby/1.9.1/webrick/httpserver.rb in service
  si.service(req, res)
         /usr/lib/ruby/1.9.1/webrick/httpserver.rb in run
      server.service(req, res)
        /usr/lib/ruby/1.9.1/webrick/server.rb in block in start_thread
      block ? block.call(sock) : run(sock)


问:
Python: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
My pandas dataframe:

```<code>dframe = pd.DataFrame({"A":list("abcde"), "B":list("aabbc"), "C":[1,2,3,4,5]},  index=[10,11,12,13,14])

    A   B   C
10  a   a   1
11  b   a   2
12  c   b   3
13  d   b   4
14  e   c   5
</code>```

My desired output:

```<code>    A   B   C   a   b   c
10  a   a   1   1   None    None
11  b   a   2   2   None    None
12  c   b   3   None    3   None
13  d   b   4   None    4   None
14  e   c   5   None    None    5
</code>```

Idea is to create new column based on values in 'B' column, copy respective values in 'C' column and paste them in newly created columns.
Here is my code:

```<code>lis = sorted(list(dframe.B.unique()))

#creating empty columns
for items in lis:
   dframe[items] = None

 #here copy and pasting
    for items in range(0, len(dframe)):
        slot = dframe.B.iloc[items]
        dframe[slot][items] = dframe.C.iloc[items]
</code>```

I ended up with this error:

```<code>SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  app.launch_new_instance()
</code>```

This code worked well in Python 2.7 but not in 3.x. Where I'm going wrong?

答:
Chained assignment will now by default warn if the user is assigning to a copy.

This can be changed with the option mode.chained_assignment, allowed options are raise/warn/None. See the docs.

In [5]: dfc = DataFrame({'A':['aaa','bbb','ccc'],'B':[1,2,3]})

In [6]: pd.set_option('chained_assignment','warn')

The following warning / exception will show if this is attempted.

In [7]: dfc.loc[0]['A'] = 1111

Traceback (most recent call last)
   ...
SettingWithCopyWarning:
   A value is trying to be set on a copy of a slice from a DataFrame.
   Try using .loc[row_index,col_indexer] = value instead
Here is the correct method of assignment.

In [8]: dfc.loc[0,'A'] = 11

In [9]: dfc

```<code> A  B
</code>```

0    11  1

1   bbb  2

2   ccc  3

Body:
My pandas dataframe:

dframe = pd.DataFrame({"A":list("abcde"), "B":list("aabbc"), "C":[1,2,3,4,5]},  index=[10,11,12,13,14])

    A   B   C
10  a   a   1
11  b   a   2
12  c   b   3
13  d   b   4
14  e   c   5

My desired output:

    A   B   C   a   b   c
10  a   a   1   1   None    None
11  b   a   2   2   None    None
12  c   b   3   None    3   None
13  d   b   4   None    4   None
14  e   c   5   None    None    5

Idea is to create new column based on values in 'B' column, copy respective values in 'C' column and paste them in newly created columns.
Here is my code:

lis = sorted(list(dframe.B.unique()))

#creating empty columns
for items in lis:
   dframe[items] = None

 #here copy and pasting
    for items in range(0, len(dframe)):
        slot = dframe.B.iloc[items]
        dframe[slot][items] = dframe.C.iloc[items]

I ended up with this error:

SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  app.launch_new_instance()

This code worked well in Python 2.7 but not in 3.x. Where I'm going wrong?

Body:
Chained assignment will now by default warn if the user is assigning to a copy.

This can be changed with the option mode.chained_assignment, allowed options are raise/warn/None. See the docs.

In [5]: dfc = DataFrame({'A':['aaa','bbb','ccc'],'B':[1,2,3]})

In [6]: pd.set_option('chained_assignment','warn')

The following warning / exception will show if this is attempted.

In [7]: dfc.loc[0]['A'] = 1111

Traceback (most recent call last)
   ...
SettingWithCopyWarning:
   A value is trying to be set on a copy of a slice from a DataFrame.
   Try using .loc[row_index,col_indexer] = value instead
Here is the correct method of assignment.

In [8]: dfc.loc[0,'A'] = 11

In [9]: dfc

 A  B

0    11  1

1   bbb  2

2   ccc  3


问:
How can I call an async method in Main?
```<code>public class test
{
    public async Task Go()
    {
        await PrintAnswerToLife();
        Console.WriteLine("done");
    }

    public async Task PrintAnswerToLife()
    {
        int answer = await GetAnswerToLife();
        Console.WriteLine(answer);
    }

    public async Task<int> GetAnswerToLife()
    {
        await Task.Delay(5000);
        int answer = 21 * 2;
        return answer;
    }
}
</code>```

if I want to call Go in main() method, how can I do that?
I am trying out c# new features, I know i can hook the async method to a event and by triggering that event, async method can be called.

But what if I want to call it directly in main method? How can i do that?

I did something like

```<code>class Program
{
    static void Main(string[] args)
    {
        test t = new test();
        t.Go().GetAwaiter().OnCompleted(() =>
        {
            Console.WriteLine("finished");
        });
        Console.ReadKey();
    }

}
</code>```

But seems it's a dead lock and nothing is printed on the screen.

答:
```<code>class Program
{
    static void Main(string[] args)
    {
       test t = new test();
       Task.Run(async () => await t.Go());
    }
}
</code>```

Title: How can I call an async method in Main?

Body:
public class test
{
    public async Task Go()
    {
        await PrintAnswerToLife();
        Console.WriteLine("done");
    }

    public async Task PrintAnswerToLife()
    {
        int answer = await GetAnswerToLife();
        Console.WriteLine(answer);
    }

    public async Task<int> GetAnswerToLife()
    {
        await Task.Delay(5000);
        int answer = 21 * 2;
        return answer;
    }
}

if I want to call Go in main() method, how can I do that?
I am trying out c# new features, I know i can hook the async method to a event and by triggering that event, async method can be called.

But what if I want to call it directly in main method? How can i do that?

I did something like

class Program
{
    static void Main(string[] args)
    {
        test t = new test();
        t.Go().GetAwaiter().OnCompleted(() =>
        {
            Console.WriteLine("finished");
        });
        Console.ReadKey();
    }

}

But seems it's a dead lock and nothing is printed on the screen.


问:
ExtJS: Limiting the number of rows on a GridPanel
I have a grid panel that loads data through a XML store. I cannot control how many items the XML will return, but I want to limit the grid to showing x number of rows.

Sorry if this is basic, I couldnt find it via google

Cheers

答:
Do you not want to show the rows beyond x for performance / too much data to visualize reason or do you want to really hide the records beyond x from the users?

If former, you can just setup pagination (it's pretty straight forward)

More info here -
http://dev.sencha.com/deploy/dev/examples/grid/paging.html

If later, you can use bensiu's suggestion. (using getRange())


问:
Angular 2 (4/5) check if user authenticated, best practices
I am new to Angular and implementing authentication for users.

Most of suggestions on the web propose to save session/username in local storage and when user is back to the app, check local storage in order to display proper navigation (in my navbar I have different nav buttons for private and public views).

However, I found this solution having some drawbacks. For example, if session on server expired, or local storage was manually added, then when app will be initialising, it will show wrong buttons in navbar.

After that I came to solution - to use service before showing navbar buttons, to send request to server to verify if user from local storage with his session is currently active. And only after that I will display nav buttons.

Here comes a question: is it the most efficient way to proof check if user from local storage is logged in and session is active?

There is another way, which I was thinking, but didn't find solution.
Since my angular webapp and nodejs server are located in two different places, is it possible for the webapp to check authentication status (make a request from webapp server to my nodejs server) when index.html is requested and respond with pre-rendered navbar and user status (logged in or not)?

Thanks.

P.S. I am using PassportJS and Express on server side.

答:
The best practise is to use AuthGuard and implement CanActivate to check whether user can view a particular part of the application. Also an authentication service is used normally to let the user login to system and gain an access token.

This access token is then used as Authorisation-Header on each request to server (this is where they will be in sync).

You will need to check for JWT/or any other type token on load which contains user information plus session time out.

If the token is invalid you simply redirect the user to login, otherwise it will allow user to go where they wanted to.

A practical example can be found here.


问:
Install .Net Framework 3.5 on Windows 10 using Microsoft Instructions
I am trying to install .Net Framework 3.5 on Windows 10 using the Microsoft's instructions.

I downloaded dotnetfx35.exe

And when it runs I get this error:

So I click on the Tell me how to solve this problem link and I get this instruction:

Could someone please make those instructions a bit more clear?

An iso of what?

How do i mount an iso?

Where am I going to see "Alternate source file path"?

Do I run gpupdate /force from a cmd prompt?

Do I need that cmd prompt to be started as administrator?

This is a windows 10 machine and I only have remote access to it.  I can not be physically by the computer.

This question is different than the other questions because:

I included a screenshots of the errors I am getting.

I am asking how to install using Microsoft's instructions, not just any instructions.

I have a specific error number that I encountered.

答:
The offline installer doesn't work for Windows 8 and up. You need to enable the Windows feature. Hit the Windows key and type "Turn Windows features on or off". Check off the .NET Framework 3.5. This will download the necessary bits and install the framework on your machine. Take a look at the Install the .NET Framework 3.5 on Windows 10, Windows 8.1, and Windows 8 for more details.

If you continue to get the above error, you are missing the side-by-side (SxS) install files. To fix this, you need to create an ISO of the Windows 10 installation media. To do this, read Create installation media for Windows.

Once there, you mount that ISO in Windows 10 by either double clicking it or right clicking on it and selection Mount.

Next, you will need enable the group policy setting that allows you to point your the alternate sources for SxS install files to the ISO you just mounted. You will need to read the article .NET Framework 3.5 installation error: 0x800F0906, 0x800F081F, 0x800F0907 and follow the directions for Windows 8 (the group policy object is the same for Windows 8, 8.1 and 10).

Now you should be able to turn the Windows feature on without an issue. There are few reasons that cause this issue, but the most common is an issue trying download the files from Windows Update. If you are in an environment that runs WSUS, the administrator my not have approved .NET Framework 3.5 which preventing the download.


答:
import java.util.Scanner;
public class FibonacciCode {

```<code>public static void main(String[] args) {

    System.out.println("Enter a number");

    int count, number0 = 0, number1 = 1, loop = 0;

    Scanner userInput = new Scanner(System.in);
    count = userInput.nextInt();

    while(loop > count)
    {
        System.out.print(number0 + ", ");

        int sum = number0 + number1;
        number0 = number1;
        number1 = sum;
        loop++;
    }
}
</code>```

}

Body:
I am writing a program to take the input for a sequence

import java.util.Scanner;

public class FibonacciCode {

public static void main(String[] args) {

    System.out.println("Enter a number");

    int count, number0 = 0, number1 = 1, loop = 0;

    Scanner userInput = new Scanner(System.in);
    count = userInput.nextInt();

    while(loop > count)
    {
        System.out.print(number0 + ", ");

        int sum = number0 + number1;
        number0 = number1;
        number1 = sum;
        loop++;
    }
}

}


答:
Looks like Microsoft is suggesting you use an ISO of the Windows installation disk to install .NET from it. Which you obviously won't be doing remotely, it probably wouldn't help anyway.

A quick search on Google about it revealed this page:

https://winaero.com/blog/offline-install-of-net-framework-3-5-in-windows-10-using-dism/

Title: Install .Net Framework 3.5 on Windows 10 using Microsoft Instructions

Body:
I am trying to install .Net Framework 3.5 on Windows 10 using the Microsoft's instructions.

I downloaded dotnetfx35.exe

And when it runs I get this error:

So I click on the Tell me how to solve this problem link and I get this instruction:

Could someone please make those instructions a bit more clear?

An iso of what?

How do i mount an iso?

Where am I going to see "Alternate source file path"?

Do I run gpupdate /force from a cmd prompt?

Do I need that cmd prompt to be started as administrator?

This is a windows 10 machine and I only have remote access to it.  I can not be physically by the computer.

This question is different than the other questions because:

I included a screenshots of the errors I am getting.

I am asking how to install using Microsoft's instructions, not just any instructions.

I have a specific error number that I encountered.


问:
Getting current userid and password in windows
I am logged into windows 10 where I am trying to run a connection to oracle db as:

```<code>import cx_Oracle
import pandas as pd
qry = 'select * from Table11 where rownum < 20'
conn = cx_Oracle.connect('uid', 'pwd', 'myDBOracle')
testData = pd.read_sql(qry, conn)
</code>```

The username and password for the database myDBOracle is same as my windows authentication. However, windows authentication changes every month. So, I was wondering whether there was a way to recover the current authentication password for windows so that I don't have to worry about my query breaking every month after password change; since the windows authentication change flows to database also.

I am currently doing:

```<code>import os
conn = cx_Oracle.connect(os.getlogin(), 'pwd', 'myDBOracle')
</code>```

答:
If your DB user account was created with IDENTIFIED EXTERNALLY (see external authentication), then connect with:

```<code>import cx_Oracle

conn = cx_Oracle.connect(dsn = "the_tns_entry_name")
</code>```

See cx_Oracle with Windows authentication

Body:
I am logged into windows 10 where I am trying to run a connection to oracle db as:

import cx_Oracle
import pandas as pd
qry = 'select * from Table11 where rownum < 20'
conn = cx_Oracle.connect('uid', 'pwd', 'myDBOracle')
testData = pd.read_sql(qry, conn)

The username and password for the database myDBOracle is same as my windows authentication. However, windows authentication changes every month. So, I was wondering whether there was a way to recover the current authentication password for windows so that I don't have to worry about my query breaking every month after password change; since the windows authentication change flows to database also.

I am currently doing:

import os
conn = cx_Oracle.connect(os.getlogin(), 'pwd', 'myDBOracle')

Body:
If your DB user account was created with IDENTIFIED EXTERNALLY (see external authentication), then connect with:

import cx_Oracle

conn = cx_Oracle.connect(dsn = "the_tns_entry_name")

See cx_Oracle with Windows authentication


问:
How to learn professional JavaScript in two days?
I really need to learn professional javascript in two days because I am gonna have to hit the
ground running (real world project). I have little which can be approximated to no knowledge of JavaScript or website development. Any help would be appreciated greatly.</p>

答: Don't cram for a programming language, especially learning it professionally, unless you have previous programing experience.


问:
awscli not added to path after installation
I installed the aws cli according to the offical Amazon directions.

```<code>sudo pip install awscli
</code>```

However, aws is nowhere to be found in my path. The installation seems to have been successful. There are a number of files located at /Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/awscli, however there are no executables named aws. My python version is 3.3.4, my pip version is 1.5.4, and running this command on OS X 10.9. What could be wrong?

Thanks!

答:
Edit the paths file directly if you have admin rights.

Definitely go with the top answer if you don't have admin rights, but if you do then I would highly recommend directly editing the paths files, located at /etc/paths.

Use your favorite editor and simply paste the desired path on a new line:

Sample paths file:

```<code>/usr/local/bin
/usr/bin
/bin
/usr/sbin
/sbin
/Users/username/Library/Python/3.6/bin #new path added here at bottom of file
</code>```

Paste at the top or bottom or in whatever order you would like the locations searched for binaries (in the event there are binaries with duplicate names).

Using the paths file saves you the hassle of remembering the concatenation syntax or the potential trouble if you write an faulty export statement.

Body:
I installed the aws cli according to the offical Amazon directions.

sudo pip install awscli

However, aws is nowhere to be found in my path. The installation seems to have been successful. There are a number of files located at /Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/awscli, however there are no executables named aws. My python version is 3.3.4, my pip version is 1.5.4, and running this command on OS X 10.9. What could be wrong?

Thanks!

Body:
Edit the paths file directly if you have admin rights.

Definitely go with the top answer if you don't have admin rights, but if you do then I would highly recommend directly editing the paths files, located at /etc/paths.

Use your favorite editor and simply paste the desired path on a new line:

Sample paths file:

/usr/local/bin
/usr/bin
/bin
/usr/sbin
/sbin
/Users/username/Library/Python/3.6/bin #new path added here at bottom of file

Paste at the top or bottom or in whatever order you would like the locations searched for binaries (in the event there are binaries with duplicate names).

Using the paths file saves you the hassle of remembering the concatenation syntax or the potential trouble if you write an faulty export statement.


问:
How to code a conditional program in Excel VBA
I would like to run a program if a value of a certain cell change.

For example, if the value of cell E9 changes then run the following program:

```<code>Sub macrorepeatsolveNRTL()

Dim count As Long
count = 3
Do While count <= 203
    SolverOk SetCell:=Sheets("ParametersNRTL").Cells(count, 27),
    MaxMinVal:=3, ValueOf:=1, ByChange:=Sheets("ParametersNRTL").Cells(count, 12)
SolverSolve UserFinish:=True
count = count + 1
Loop
End Sub
</code>```

答:
IMPORTANT: Place in your worksheet module, not a standard module. You can accomplish this task easily by right-clicking the worksheet tab in the spreadsheet, then click "View Code".

```<code>Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim myTarget As Range
    Set myTarget = Range("E9")

    If Not Intersect(Target, myTarget) Is Nothing Then
        macrorepeatsolveNRTL
    End If

End Sub
</code>```

Body:
I would like to run a program if a value of a certain cell change.

For example, if the value of cell E9 changes then run the following program:

Sub macrorepeatsolveNRTL()

Dim count As Long
count = 3
Do While count <= 203
    SolverOk SetCell:=Sheets("ParametersNRTL").Cells(count, 27),
    MaxMinVal:=3, ValueOf:=1, ByChange:=Sheets("ParametersNRTL").Cells(count, 12)
SolverSolve UserFinish:=True
count = count + 1
Loop
End Sub

Body:
IMPORTANT: Place in your worksheet module, not a standard module. You can accomplish this task easily by right-clicking the worksheet tab in the spreadsheet, then click "View Code".

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim myTarget As Range
    Set myTarget = Range("E9")

    If Not Intersect(Target, myTarget) Is Nothing Then
        macrorepeatsolveNRTL
    End If

End Sub


问:
Need some javascript show image and play song at same time
I am trying to figure out how to display an image inside of a div that corresponds to the song that is playing in the playlist. Right now I only have the image showing IF the person has actually CLICKED a song, but I would like it to show the image when the code shifts from one song to the next automatically. I do not know how to do that as I am very new to jquery here are the relevant snippets.

This is just a snippet of the playlist:

```<code><li>
  <a href="audio/02.mp3"onclick="changeImg('audio/2.jpg');" >
    Above All - Michael W. Smith
  </a>
</li>
</code>```

and this is these are the scripts used(which by the way, I am sure can be condensed in a very big way - but I have not attempted this as of yet!

```<code><script>
$(document).ready(function () {
  init();
  function init(){
    var current = 0;
    var audio = $('#audio');
    var playlist = $('#playlist');
    var tracks = playlist.find('li a');
    var len = tracks.length - 1;
    var imghol = document.getElementById("imageHolder");
    audio[0].volume = .10;
    audio[0].play();
    playlist.on('click','a', function(e){
      e.preventDefault();
      link = $(this);
      current = link.parent().index();
      run(link, audio[0]);
    });
    audio[0].addEventListener('ended',function(e){
      current++;
      if(current == len){
        current = 0;
        link = playlist.find('a')[0];
      }else{
        link = playlist.find('a')[current];
      }
      run($(link),audio[0]);
    });
  }
  function run(link, player){
    player.src = link.attr('href');
    par = link.parent();
    par.addClass('active').siblings().removeClass('active');
    player.load();
    player.play();
  }
});
</script>

<script type="text/javascript">
  function changeImg(image){
  var imghol = document.getElementById("imageHolder");
  imghol.src = image;
}
</script>
</code>```

So far everything works GREAT, but as I said - I would LIKE to have the image that corresponds to the song automatically switch to another image when the song auto plays a different song.

The image showing method was taken from this site where someone else asked how to show an image when clicking on a list item, and I adapted the answer to fit what I needed it to show - but cannot figure out to get it to auto show!

Thanks :)

答:
The code below is fully untested. See the edit below.

I re-ordered things in there.

Please change your markup from

to this:

Adjust your filenames to match!

audio/02.mp3 should match audio/02.jpg

Just the file extention needs to be different.

Then, consider this:

```<code><script>
$(document).ready(function () {
  var current = 0;
  var audio = $('#audio');
  var playlist = $('#playlist');
  var tracks = playlist.find('li a');
  var len = tracks.length - 1;
  var imghol = $("#imageHolder");

  function init(){
    audio[0].volume = .10;
    //audio[0].play();
  }
  init();

  // Your click handler
  playlist.on('click','a', function(e){
    e.preventDefault();
    link = $(this);
    current = link.parent().index();
    run(link, audio[0]);
  });

  // Audio end event handler
  audio.on('ended',function(e){
    current++;
    if(current == len){
      current = 0;
      link = playlist.find('a')[0];
    }else{
      link = playlist.find('a')[current];
    }
    run($(link),audio[0]);
  });

  // Run function
  function run(link, player){
    player.src = link.attr('href');
    par = link.parent();
    par.addClass('active').siblings().removeClass('active');
    player.load();
    player.play();

    // The image change is here
    href = link.attr("href");
    href = href.replace(".mp3",".jpg");   // changes .mp3 for .jpg ADJUST your file naming
    //imghol.src = href;
    imghol.attr("src",href);
  }

}); // ready
</script>
</code>```

EDIT

I tryed your code from the PasteBin.

There is just 4 errors to be fixed. The first was from my suggested code.

In the run() function, imghol.src = href; should be imghol.attr("src",href); since imghol is a jQuery object.

The other errors are yours.

href = href.replace("audio/02.mp3","audio/02.jpg"); This line is intended to catch the file name from the href but with a changed extension (from .mp3 to .jpg). My suggestion was correct. It has to be href = href.replace(".mp3",".jpg");

Change  to . This function does not exist anymore.

Remove audio[0].play(); from the init() function. You don't want to play anything yet... There is no file to play!

Now some advises:

Don't use jQuery slim! For the code you actually have, it's ok. But as soon as you will try to add an animation (like a fadeIn()) to the images... It won't work. The href="https://stackoverflow.com/questions/35424053/what-are-the-differences-between-normal-and-slim-package-of-jquery">slim version is the same as the full version MINUS the animations, Ajax and more usefull stuff. That is only good were performance is important. But without all that jQuery has to offer... Better just use plain JavaScript! If you experiment jQuery, use the full library.

And use the href="https://webmasters.stackexchange.com/questions/8525/how-do-i-open-the-javascript-console-in-different-browsers">console. All hints to debug your script were there for you to see.

Body:
I am trying to figure out how to display an image inside of a div that corresponds to the song that is playing in the playlist. Right now I only have the image showing IF the person has actually CLICKED a song, but I would like it to show the image when the code shifts from one song to the next automatically. I do not know how to do that as I am very new to jquery here are the relevant snippets.

This is just a snippet of the playlist:

    Above All - Michael W. Smith

and this is these are the scripts used(which by the way, I am sure can be condensed in a very big way - but I have not attempted this as of yet!

So far everything works GREAT, but as I said - I would LIKE to have the image that corresponds to the song automatically switch to another image when the song auto plays a different song.

The image showing method was taken from this site where someone else asked how to show an image when clicking on a list item, and I adapted the answer to fit what I needed it to show - but cannot figure out to get it to auto show!

Thanks :)

Body:
The code below is fully untested. See the edit below.

I re-ordered things in there.

Please change your markup from <a href="audio/02.mp3"onclick="changeImg('audio/2.jpg');" >

to this: <a href="audio/02.mp3">

Adjust your filenames to match!

audio/02.mp3 should match audio/02.jpg

Just the file extention needs to be different.

Then, consider this:

<script>
$(document).ready(function () {
  var current = 0;
  var audio = $('#audio');
  var playlist = $('#playlist');
  var tracks = playlist.find('li a');
  var len = tracks.length - 1;
  var imghol = $("#imageHolder");

  function init(){
    audio[0].volume = .10;
    //audio[0].play();
  }
  init();

  // Your click handler
  playlist.on('click','a', function(e){
    e.preventDefault();
    link = $(this);
    current = link.parent().index();
    run(link, audio[0]);
  });

  // Audio end event handler
  audio.on('ended',function(e){
    current++;
    if(current == len){
      current = 0;
      link = playlist.find('a')[0];
    }else{
      link = playlist.find('a')[current];
    }
    run($(link),audio[0]);
  });

  // Run function
  function run(link, player){
    player.src = link.attr('href');
    par = link.parent();
    par.addClass('active').siblings().removeClass('active');
    player.load();
    player.play();

    // The image change is here
    href = link.attr("href");
    href = href.replace(".mp3",".jpg");   // changes .mp3 for .jpg ADJUST your file naming
    //imghol.src = href;
    imghol.attr("src",href);
  }

}); // ready
</script>

EDIT

I tryed your code from the PasteBin.

There is just 4 errors to be fixed. The first was from my suggested code.

In the run() function, imghol.src = href; should be imghol.attr("src",href); since imghol is a jQuery object.

The other errors are yours.

href = href.replace("audio/02.mp3","audio/02.jpg"); This line is intended to catch the file name from the href but with a changed extension (from .mp3 to .jpg). My suggestion was correct. It has to be href = href.replace(".mp3",".jpg");

Change <body onload="PlayerLoaded()"> to <body>. This function does not exist anymore.

Remove audio[0].play(); from the init() function. You don't want to play anything yet... There is no file to play!

Now some advises:

Don't use jQuery slim! For the code you actually have, it's ok. But as soon as you will try to add an animation (like a fadeIn()) to the images... It won't work. The slim version is the same as the full version MINUS the animations, Ajax and more usefull stuff. That is only good were performance is important. But without all that jQuery has to offer... Better just use plain JavaScript! If you experiment jQuery, use the full library.

And use the console. All hints to debug your script were there for you to see.