问:
Calculating the amount of time left until completion
I am wondering how to calculate the amount of time it would take to example:

Complete a brute force word list.

I know how to use the time function and measure in time,
but the problem is i need to find out how long it would take in the program itself...

Here is the code i made this yesterday

```<code>import itertools, math
import os
Alphabet = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890") # Add or remove whatevs you think will be in the password you're cracking (example, [symbols])
counter = 1
CharLength = 1
range_num = int(raw_input("Enter range: "))
stopper = range_num + 1
filename = "bruteforce_%r.txt" % (range_num)
f = open(filename, 'a')
#n_1 = len(Alphabet)
#n_2 = n_1 - 1 # <-- total useless peice of garbage that could of been great in vurtual life
#n_3 = '0' * n_2
#n = '1' + n_3
x = range_num
y = len(Alphabet)
amount = math.pow(y, x)
total_items = math.pow(y, x)
for CharLength in range(range_num, stopper):
    passwords = (itertools.product(Alphabet, repeat = CharLength))

    for i in passwords:
        counter += 1
        percentage = (counter / total_items) * 100
        amount -= 1
        i = str(i)
        i = i.replace("[", "")
        i = i.replace("]", "")
        i = i.replace("'", "")
        i = i.replace(" ", "")
        i = i.replace(",", "")
        i = i.replace("(", "")
        i = i.replace(")", "")
        f.write(i)
        f.write('\n')
        print "Password: %r\tPercentage: %r/100\tAmount left: %r" % (i, int(percentage), amount)
        if i == '0'* range_num:
            print "*Done"
            f.close()
            exit(0)
        else:
            pass
</code>```

This is my timer function i managed to make

```<code>#import winsound # Comment this out if your using linux
import os
import time
from sys import exit

print "This is the timer\nHit CTRL-C to stop the timer\nOtherwise just let         it rip untill the time's up"
hours = int(raw_input('Enter the hours.\n>>> '))
os.system('clear') # Linux
#os.system('cls')   # Windows

minutes = int(raw_input('Enter the minutes.\n>>> '))
os.system('clear') # linux
#os.system('cls')   # Windows

seconds = int(raw_input('Enter the seconds.\n>>> '))
os.system('clear') # Linux
#os.system('cls')   # Windows

stop_time = '%r:%r:%r' % (hours, minutes, seconds)

t_hours = 00
t_minutes = 00
t_seconds = 00

while t_seconds <= 60:
    try:
        os.system('clear') # Linux
        #os.system('cls') # Windows
        current_time = '%r:%r:%r' % (t_hours, t_minutes, t_seconds)
        print current_time
        time.sleep(1)
        t_seconds+=1

        if current_time == stop_time:
            print "// Done"
            #winsound.Beep(500,1000)
            #winsound.Beep(400,1000)
            break

        elif t_seconds == 60:
            t_minutes+=1
            t_seconds=0

        elif t_minutes == 60:
            t_hours+=1
            t_minutes = 00

    except KeyboardInterrupt:
        print "Stopped at: %r:%r:%r" % (t_hours, t_minutes, t_seconds)
        raw_input("Hit enter to continue\nHit CTRL-C to end")
        try:
            pass

        except KeyboardInterrupt:
            exit(0)
</code>```

Now i just cant figure out how to make this again but to calculate how long it will take rather than how long it is taking...

答:
You cannot predict the time a script is going to take.
Firstly because two machines wouldn't run the script in the same time, and secondly, because the execution time on one machine can vary from on take to another.

What you can do, however, is compute the percentage of execution.
You need to figure out, for example, how many iterations your main loop will do, and calculate at each iteration the ratio current iteration count / total number of iterations.

Here is a minimalist example of what you can do:

```<code>n = 10000
for i in range(n):
    print("Processing file {} ({}%)".format(i, 100*i//n))
    process_file(i)
</code>```

You can take it further and add the time as an additional info:

```<code>n = 10000
t0 = time.time()
for i in range(n):
    t1 = time.time()
    print("Processing file {} ({}%)".format(i, 100*i//n), end="")
    process_file(i)
    t2 = time.time()
    print(" {}s (total: {}s)".format(t2-t1, t2-t0))
</code>```

The output will look like this:

```<code>...
Processing file 2597 (25%) 0.2s (total: 519.4s)
Processing file 2598 (25%) 0.3s (total: 519.7s)
Processing file 2599 (25%) 0.1s (total: 519.8s)
Processing file 2600 (25%)
</code>```

Body:
I am wondering how to calculate the amount of time it would take to example:

Complete a brute force word list.

I know how to use the time function and measure in time,
but the problem is i need to find out how long it would take in the program itself...

Here is the code i made this yesterday

import itertools, math
import os
Alphabet = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890") # Add or remove whatevs you think will be in the password you're cracking (example, [symbols])
counter = 1
CharLength = 1
range_num = int(raw_input("Enter range: "))
stopper = range_num + 1
filename = "bruteforce_%r.txt" % (range_num)
f = open(filename, 'a')
#n_1 = len(Alphabet)
#n_2 = n_1 - 1 # <-- total useless peice of garbage that could of been great in vurtual life
#n_3 = '0' * n_2
#n = '1' + n_3
x = range_num
y = len(Alphabet)
amount = math.pow(y, x)
total_items = math.pow(y, x)
for CharLength in range(range_num, stopper):
    passwords = (itertools.product(Alphabet, repeat = CharLength))

    for i in passwords:
        counter += 1
        percentage = (counter / total_items) * 100
        amount -= 1
        i = str(i)
        i = i.replace("[", "")
        i = i.replace("]", "")
        i = i.replace("'", "")
        i = i.replace(" ", "")
        i = i.replace(",", "")
        i = i.replace("(", "")
        i = i.replace(")", "")
        f.write(i)
        f.write('\n')
        print "Password: %r\tPercentage: %r/100\tAmount left: %r" % (i, int(percentage), amount)
        if i == '0'* range_num:
            print "*Done"
            f.close()
            exit(0)
        else:
            pass

This is my timer function i managed to make

#import winsound # Comment this out if your using linux
import os
import time
from sys import exit

print "This is the timer\nHit CTRL-C to stop the timer\nOtherwise just let         it rip untill the time's up"
hours = int(raw_input('Enter the hours.\n>>> '))
os.system('clear') # Linux
#os.system('cls')   # Windows

minutes = int(raw_input('Enter the minutes.\n>>> '))
os.system('clear') # linux
#os.system('cls')   # Windows

seconds = int(raw_input('Enter the seconds.\n>>> '))
os.system('clear') # Linux
#os.system('cls')   # Windows

stop_time = '%r:%r:%r' % (hours, minutes, seconds)

t_hours = 00
t_minutes = 00
t_seconds = 00

while t_seconds <= 60:
    try:
        os.system('clear') # Linux
        #os.system('cls') # Windows
        current_time = '%r:%r:%r' % (t_hours, t_minutes, t_seconds)
        print current_time
        time.sleep(1)
        t_seconds+=1

        if current_time == stop_time:
            print "// Done"
            #winsound.Beep(500,1000)
            #winsound.Beep(400,1000)
            break

        elif t_seconds == 60:
            t_minutes+=1
            t_seconds=0

        elif t_minutes == 60:
            t_hours+=1
            t_minutes = 00

    except KeyboardInterrupt:
        print "Stopped at: %r:%r:%r" % (t_hours, t_minutes, t_seconds)
        raw_input("Hit enter to continue\nHit CTRL-C to end")
        try:
            pass

        except KeyboardInterrupt:
            exit(0)

Now i just cant figure out how to make this again but to calculate how long it will take rather than how long it is taking...

Body:
You cannot predict the time a script is going to take.
Firstly because two machines wouldn't run the script in the same time, and secondly, because the execution time on one machine can vary from on take to another.

What you can do, however, is compute the percentage of execution.
You need to figure out, for example, how many iterations your main loop will do, and calculate at each iteration the ratio current iteration count / total number of iterations.

Here is a minimalist example of what you can do:

n = 10000
for i in range(n):
    print("Processing file {} ({}%)".format(i, 100*i//n))
    process_file(i)

You can take it further and add the time as an additional info:

n = 10000
t0 = time.time()
for i in range(n):
    t1 = time.time()
    print("Processing file {} ({}%)".format(i, 100*i//n), end="")
    process_file(i)
    t2 = time.time()
    print(" {}s (total: {}s)".format(t2-t1, t2-t0))

The output will look like this:

...
Processing file 2597 (25%) 0.2s (total: 519.4s)
Processing file 2598 (25%) 0.3s (total: 519.7s)
Processing file 2599 (25%) 0.1s (total: 519.8s)
Processing file 2600 (25%)


来源: stackexchange

问:
javascript if a html element text equal with 0, addClass to an element
I have an element that contains the discount of a product

0
        %

```

I want, if the element with id="mydiscouttext" equal to 0, addClass "hide".

I am looking for a solution with javascript.

Any idea?

答:
changes to:

```<code><div class="discount_discountAmount">
    <div id="mydiscouttext" class="discouttext">
        <span class="value_percent">0</span>
        <span class="price_percent">%</span>
    </div>
</div>
</code>```

and:

```<code>$(document).ready(function(){
    var discouttext = $('#mydiscouttext span:first-child').html();
    if(discouttext === '0')
        $('.discount_discountAmount').hide();
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an element that contains the discount of a product

0
        %

I want, if the element with id="mydiscouttext" equal to 0, addClass "hide".

I am looking for a solution with javascript.

Any idea?

Body:
changes to:

<div class="discount_discountAmount">
    <div id="mydiscouttext" class="discouttext">
        <span class="value_percent">0</span>
        <span class="price_percent">%</span>
    </div>
</div>

and:

$(document).ready(function(){
    var discouttext = $('#mydiscouttext span:first-child').html();
    if(discouttext === '0')
        $('.discount_discountAmount').hide();
});


问:
Replace shell environment variables in a string with actual values
I am reading a property file in Java.

```<code>Properties myProp = new Properties();
InputStream in = new FileInputStream(pathOfPropertyFile);
myProp.load(in);
in.close();
</code>```

The values in the property file have references to Linux shell variables.
For example, an entry in the property file might look like:

```<code>DATA_PATH=/data/${PROJECT}/${YEAR}${MONTH}${DAY}
</code>```

I have to execute a shell script from java and so I have ProcessBuilder instance and also the environment variables (envMap as given below):

```<code>List<String> command = new ArrayList<String>();
command.add(actualCommand);
command.add(param1);
command.add(param2);
ProcessBuilder processBuilder = new ProcessBuilder(command);
Map<String, String> envMap = processBuilder.environment();
</code>```

The envMap has the environment variables I require  along with over one hundred (> 100) other environment variables which I do not require.

I want to replace the ${USER},${PROJECT},etc., from the property-value string "/home/${USER}/${PROJECT}/data" with actual values from the shell.

I would consider iterating the Map as the last option(as the Map has between 100 and 200 elements to iterate) as it is not an efficient approach.

Please advise some approach that will fetch the environment variable enclosed by braces from the string, so that I can directly use the get() of the Map and replace. Or, any better approaches are most welcome.

Note:  The reference offered ( Replace String values with value in Hash Map  that made my question to look duplicate) is not the best fit in my case.

答:
I am not sure if it works, but I hope someone can edit to make it work, or at least you get the logic and make it work on your own:

```<code>command = command.replaceAll("\\$\\{(.*?)\\}", envMap.get("$1"));
</code>```

Here, I am assuming that command is a String (not a List) and that all environment variables exist in your Map (otherwise you should check for null and handle this case as you wish).

A bit of an explanation:

this regex is looking for the pattern "${something}" and replaces it with envMap.get("something"). In this example, we use parentheses to mark "something" as a group, which can then be retracted as "$1" (since we have only one group, i.e., only one set of parentheses).
The question mark '?' is the non-greedy operator here meaning to stop at the smallest possible regex match (otherwise it would find a singe match for the first "${" until the last "}".

Body:
I am reading a property file in Java.

Properties myProp = new Properties();
InputStream in = new FileInputStream(pathOfPropertyFile);
myProp.load(in);
in.close();

The values in the property file have references to Linux shell variables.
For example, an entry in the property file might look like:

DATA_PATH=/data/${PROJECT}/${YEAR}${MONTH}${DAY}

I have to execute a shell script from java and so I have ProcessBuilder instance and also the environment variables (envMap as given below):

List<String> command = new ArrayList<String>();
command.add(actualCommand);
command.add(param1);
command.add(param2);
ProcessBuilder processBuilder = new ProcessBuilder(command);
Map<String, String> envMap = processBuilder.environment();

The envMap has the environment variables I require  along with over one hundred (> 100) other environment variables which I do not require.

I want to replace the ${USER},${PROJECT},etc., from the property-value string "/home/${USER}/${PROJECT}/data" with actual values from the shell.

I would consider iterating the Map as the last option(as the Map has between 100 and 200 elements to iterate) as it is not an efficient approach.

Please advise some approach that will fetch the environment variable enclosed by braces from the string, so that I can directly use the get() of the Map and replace. Or, any better approaches are most welcome.

Note:  The reference offered ( Replace String values with value in Hash Map  that made my question to look duplicate) is not the best fit in my case.

Body:
I am not sure if it works, but I hope someone can edit to make it work, or at least you get the logic and make it work on your own:

command = command.replaceAll("\\$\\{(.*?)\\}", envMap.get("$1"));

Here, I am assuming that command is a String (not a List) and that all environment variables exist in your Map (otherwise you should check for null and handle this case as you wish).

A bit of an explanation:

this regex is looking for the pattern "${something}" and replaces it with envMap.get("something"). In this example, we use parentheses to mark "something" as a group, which can then be retracted as "$1" (since we have only one group, i.e., only one set of parentheses).
The question mark '?' is the non-greedy operator here meaning to stop at the smallest possible regex match (otherwise it would find a singe match for the first "${" until the last "}".


问:
On creating VCard not getting contact image and notes in iOS
Fetching contact list using CNContactStore and converting complete contact list to VCard, all are coming fine except i am not getting contact image and notes.  </p>

```<code>   NSMutableArray *contactsArray=[[NSMutableArray alloc] init];
   CNContactStore *store = [[CNContactStore alloc] init];
   [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
    if (!granted) {
        dispatch_async(dispatch_get_main_queue(), ^{
        });
        return;
    }
    NSMutableArray *contacts = [NSMutableArray array];
    NSError *fetchError;

    CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:@[[CNContactVCardSerialization descriptorForRequiredKeys], [CNContactFormatter descriptorForRequiredKeysForStyle:CNContactFormatterStyleFullName]]];

    BOOL success = [store enumerateContactsWithFetchRequest:request error:&fetchError usingBlock:^(CNContact *contact, BOOL *stop) {
        [contacts addObject:contact];
    }];
    if (!success) {
        NSLog(@"error = %@", fetchError);
    }

    for (CNContact *contact in contacts) {
        CNContact *contact1 = contact.mutableCopy;
        [contactsArray addObject:contact1];
    }

    NSData *vcardString =[CNContactVCardSerialization dataWithContacts:contactsArray error:&error];

    vcardStr = [[NSString alloc] initWithData:vcardString encoding:NSUTF8StringEncoding];
    NSLog(@"vcardStr = %@",vcardStr);
  }];
</code>```

答:
Contact Profile images from CNContact</p>

```<code> if (granted == YES) {
 NSArray *keys = @[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey];
 NSString *containerId = store.defaultContainerIdentifier;
 NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
 NSError *error;
 NSArray *Contacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
 if (error)
 {
    //error
 }
else
{
for (CNContact *contact in Contacts)
{
UIImage *contactProfileImage;
if (contact.imageDataAvailable)
{
  UIImage * image = [UIImage imageWithData:contact.imageData];
  contactProfileImage = image;
}
else
{
  contactProfileImage = [UIImage imageNamed:@"icon.png"];
}
}
</code>```

Body:
Fetching contact list using CNContactStore and converting complete contact list to VCard, all are coming fine except i am not getting contact image and notes.

   NSMutableArray *contactsArray=[[NSMutableArray alloc] init];
   CNContactStore *store = [[CNContactStore alloc] init];
   [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
    if (!granted) {
        dispatch_async(dispatch_get_main_queue(), ^{
        });
        return;
    }
    NSMutableArray *contacts = [NSMutableArray array];
    NSError *fetchError;

    CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:@[[CNContactVCardSerialization descriptorForRequiredKeys], [CNContactFormatter descriptorForRequiredKeysForStyle:CNContactFormatterStyleFullName]]];

    BOOL success = [store enumerateContactsWithFetchRequest:request error:&fetchError usingBlock:^(CNContact *contact, BOOL *stop) {
        [contacts addObject:contact];
    }];
    if (!success) {
        NSLog(@"error = %@", fetchError);
    }

    for (CNContact *contact in contacts) {
        CNContact *contact1 = contact.mutableCopy;
        [contactsArray addObject:contact1];
    }

    NSData *vcardString =[CNContactVCardSerialization dataWithContacts:contactsArray error:&error];

    vcardStr = [[NSString alloc] initWithData:vcardString encoding:NSUTF8StringEncoding];
    NSLog(@"vcardStr = %@",vcardStr);
  }];

Body:
Contact Profile images from CNContact

 if (granted == YES) {
 NSArray *keys = @[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey];
 NSString *containerId = store.defaultContainerIdentifier;
 NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
 NSError *error;
 NSArray *Contacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
 if (error)
 {
    //error
 }
else
{
for (CNContact *contact in Contacts)
{
UIImage *contactProfileImage;
if (contact.imageDataAvailable)
{
  UIImage * image = [UIImage imageWithData:contact.imageData];
  contactProfileImage = image;
}
else
{
  contactProfileImage = [UIImage imageNamed:@"icon.png"];
}
}


问:
How to make wordpress website https secure?
Actually I applied ssl certification to my wordpress website but Its working only on the homepage. Except for Homepage every other page's url starts with http only. I want https applied to all pages. Can anyone help me.</p>

答:
Just follow attached image and change.

You can do this by adding the following code in your .htaccess file:

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.yoursite.com/$1 [R,L]
</IfModule>
</code>```

Body:
Just follow attached image and change.

You can do this by adding the following code in your .htaccess file:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.yoursite.com/$1 [R,L]
</IfModule>


问:
How to get current function into a variable?
How can I get a variable that contains the currently executing function in Python? I don't want the function's name. I know I can use inspect.stack to get the current function name. I want the actual callable object. Can this be done without using inspect.stack to retrieve the function's name and then evaling the name to get the callable object?

Edit: I have a reason to do this, but it's not even a remotely good one. I'm using plac to parse command-line arguments. You use it by doing plac.call(main), which generates an ArgumentParser object from the function signature of "main". Inside "main", if there is a problem with the arguments, I want to exit with an error message that includes the help text from the ArgumentParser object, which means that I need to directly access this object by calling plac.parser_from(main).print_help(). It would be nice to be able to say instead: plac.parser_from(get_current_function()).print_help(), so that I am not relying on the function being named "main". Right now, my implementation of "get_current_function" would be:

```<code>import inspect
def get_current_function():
    return eval(inspect.stack()[1][3])
</code>```

But this implementation relies on the function having a name, which I suppose is not too onerous. I'm never going to do plac.call(lambda ...).

In the long run, it might be more useful to ask the author of plac to implement a print_help method to print the help text of the function that was most-recently called using plac, or something similar.

答:
I recently spent a lot of time trying to do something like this and ended up walking away from it. There's a lot of corner cases.

If you just want the lowest level of the call stack, you can just reference the name that is used in the def statement. This will be bound to the function that you want through lexical closure.

For example:

```<code>def recursive(*args, **kwargs):
    me = recursive
</code>```

me will now refer to the function in question regardless of the scope that the function is called from so long as it is not redefined in the scope where the definition occurs. Is there some reason why this won't work?

To get a function that is executing higher up the call stack, I couldn't think of anything that can be reliably done.

ContentLicense: CC BY-SA 4.0

Body:
How can I get a variable that contains the currently executing function in Python? I don't want the function's name. I know I can use inspect.stack to get the current function name. I want the actual callable object. Can this be done without using inspect.stack to retrieve the function's name and then evaling the name to get the callable object?

Edit: I have a reason to do this, but it's not even a remotely good one. I'm using plac to parse command-line arguments. You use it by doing plac.call(main), which generates an ArgumentParser object from the function signature of "main". Inside "main", if there is a problem with the arguments, I want to exit with an error message that includes the help text from the ArgumentParser object, which means that I need to directly access this object by calling plac.parser_from(main).print_help(). It would be nice to be able to say instead: plac.parser_from(get_current_function()).print_help(), so that I am not relying on the function being named "main". Right now, my implementation of "get_current_function" would be:

import inspect
def get_current_function():
    return eval(inspect.stack()[1][3])

But this implementation relies on the function having a name, which I suppose is not too onerous. I'm never going to do plac.call(lambda ...).

In the long run, it might be more useful to ask the author of plac to implement a print_help method to print the help text of the function that was most-recently called using plac, or something similar.

Body:
I recently spent a lot of time trying to do something like this and ended up walking away from it. There's a lot of corner cases.

If you just want the lowest level of the call stack, you can just reference the name that is used in the def statement. This will be bound to the function that you want through lexical closure.

For example:

def recursive(*args, **kwargs):
    me = recursive

me will now refer to the function in question regardless of the scope that the function is called from so long as it is not redefined in the scope where the definition occurs. Is there some reason why this won't work?

To get a function that is executing higher up the call stack, I couldn't think of anything that can be reliably done.

ContentLicense: CC BY-SA 2.5


问:
Get Average of column using group by
I am trying to get the average of property from table based on its group,

```<code>from avgtbl1 in table1
group avgtbl1 by new
{
    avgtbl1 .Prop1,
    avgtbl1 .Prop2,
    avgtbl1 .Prop3,
    avgtbl1 .Prop4
} into tempavgtbl1
select new
{
    Prop1= tempavgtbl1 .Key.Prop1,
    Prop2= tempavgtbl1 .Key.Prop2,
    Prop3= tempavgtbl1 .Key.Prop3,
    Prop4= tempavgtbl1 .Key.Prop4,
    prop5= tempavgtbl1 .Average(a =>  a.Prop4)
};
</code>```

After executing the query it's gives same value of prop4 rather than a average of group for prop4 which is based on prop1,prop2,prop3. I am not getting where i went wrong.

```<code> |Prop1 | prop2 |prop3| prop4|
 |1     | abc   |123  |    20|
 |1     | abc   |123  |    24|
 |2     | abc   |123  |    20|
 |2     | abc   |123  |    24|
 |3     | pqr   |  123|    27|
 |3     | pqr   |  123|    29|

 Expected Result

 |Prop1 | prop2 |prop3| prop4|prop5|
 |1     | abc   |123  |    20| 22  |
 |1     | abc   |123  |    24| 22  |
 |2     | abc   |123  |    21| 22.5|
 |2     | abc   |123  |    24| 22.5|
 |3     | pqr   |  123|    27| 28  |
 |3     | pqr   |  123|    29| 28  |
</code>```

Current result:

```<code> |Prop1 | prop2 |prop3| prop4|prop5|
 |1     | abc   |123  |    20|   20|
 |1     | abc   |123  |    24|   24|
 |2     | abc   |123  |    21|   21|
 |2     | abc   |123  |    24|   24|
 |3     | pqr   |  123|    27|   27|
 |3     | pqr   |  123|    29|   29|
</code>```

答:
The problem is that you are grouping on Prop4.  To do what you want you'll have to calculate the average then join back to the original table to get the un-averaged values.  Also you can just group Prop4 by the other columns so that you don't have to specify the column in the Average.

```<code>from a1 in table1
group a1.Prop4 by new
{
    a1.Prop1,
    a1.Prop2,
    a1.Prop3
} into grp
join a2 in table1
on grp.Key equals new {a2.Prop1, a2.Prop2, a2.Prop3};
select new
{
    a2.Prop1, // or grp.Key.Prop1,
    a2.Prop2, // or grp.Key.Prop2,
    a2.Prop3, // or grp.Key.Prop3,
    a2.Prop4,
    Prop5 = grp.Average()
}
</code>```

Alternatively this can also be done with a subquery.

```<code>from a1 in table1
select new
{
    a1.Prop1,
    a1.Prop2,
    a1.Prop3,
    a1.Prop4,
    Prop5 = (from a2 in table1
             where a2.Prop1 = a1.Prop1
                   && a2.Prop2 = a1.Prop2
                   && a2.Prop3 = a1.Prop3
             select a2.Prop4).Average()
}
</code>```

Title: Get Average of column using group by

Body:
I am trying to get the average of property from table based on its group,

from avgtbl1 in table1
group avgtbl1 by new
{
    avgtbl1 .Prop1,
    avgtbl1 .Prop2,
    avgtbl1 .Prop3,
    avgtbl1 .Prop4
} into tempavgtbl1
select new
{
    Prop1= tempavgtbl1 .Key.Prop1,
    Prop2= tempavgtbl1 .Key.Prop2,
    Prop3= tempavgtbl1 .Key.Prop3,
    Prop4= tempavgtbl1 .Key.Prop4,
    prop5= tempavgtbl1 .Average(a =>  a.Prop4)
};

After executing the query it's gives same value of prop4 rather than a average of group for prop4 which is based on prop1,prop2,prop3. I am not getting where i went wrong.

 |Prop1 | prop2 |prop3| prop4|
 |1     | abc   |123  |    20|
 |1     | abc   |123  |    24|
 |2     | abc   |123  |    20|
 |2     | abc   |123  |    24|
 |3     | pqr   |  123|    27|
 |3     | pqr   |  123|    29|

 Expected Result

 |Prop1 | prop2 |prop3| prop4|prop5|
 |1     | abc   |123  |    20| 22  |
 |1     | abc   |123  |    24| 22  |
 |2     | abc   |123  |    21| 22.5|
 |2     | abc   |123  |    24| 22.5|
 |3     | pqr   |  123|    27| 28  |
 |3     | pqr   |  123|    29| 28  |

Current result:

 |Prop1 | prop2 |prop3| prop4|prop5|
 |1     | abc   |123  |    20|   20|
 |1     | abc   |123  |    24|   24|
 |2     | abc   |123  |    21|   21|
 |2     | abc   |123  |    24|   24|
 |3     | pqr   |  123|    27|   27|
 |3     | pqr   |  123|    29|   29|

Body:
The problem is that you are grouping on Prop4.  To do what you want you'll have to calculate the average then join back to the original table to get the un-averaged values.  Also you can just group Prop4 by the other columns so that you don't have to specify the column in the Average.

from a1 in table1
group a1.Prop4 by new
{
    a1.Prop1,
    a1.Prop2,
    a1.Prop3
} into grp
join a2 in table1
on grp.Key equals new {a2.Prop1, a2.Prop2, a2.Prop3};
select new
{
    a2.Prop1, // or grp.Key.Prop1,
    a2.Prop2, // or grp.Key.Prop2,
    a2.Prop3, // or grp.Key.Prop3,
    a2.Prop4,
    Prop5 = grp.Average()
}

Alternatively this can also be done with a subquery.

from a1 in table1
select new
{
    a1.Prop1,
    a1.Prop2,
    a1.Prop3,
    a1.Prop4,
    Prop5 = (from a2 in table1
             where a2.Prop1 = a1.Prop1
                   && a2.Prop2 = a1.Prop2
                   && a2.Prop3 = a1.Prop3
             select a2.Prop4).Average()
}


问:
How to sync Firebase Database with Google Sheets?
I am working in an Ionic 3 project with ts to integrate Firebase into my app.
The below code I used to integrate firebase with Ionic project

```<code>constructor(angFire: AngularFireDatabase){
}
 books: FirebaseListObservable<any>;
</code>```

To send the data from my app to firebase, I used push method and to update entries I used update($key). Now I have all the data's in Firebase backend.

Now, how can I sync the firebase Database with Google Sheets so that each and every entry added to firebase backend has to get updated into sheets. I used a third party ZAPIER for this integration, but it would be nice if I get to learn on how to do this sync on my own.

Upon surfing, there are many tutorials to get the data's from the google sheets into Firebase. But I didn't come across any tutorials for vice versa.

I followed the below tutorial but it doesn't point to spreadsheets.
https://sites.google.com/site/scriptsexamples/new-connectors-to-google-services/firebase

Any help would be greatly appreciated!

答:
I looked into importing Firebase right into Google Scripts either through the JavaScript SDK or or the REST API. Both have requirements/steps that Google Scripts cannot satisfy or that are extremely difficult to satisfy.

There is no foreseeable method of downloading the JavaScript SDK inside a Google Script because almost every method requires a DOM, which you don't have with a Google Sheet.

The REST API requires GoogleCredentials which, at a short glance, appear very difficult to get inside Google Scripts as well

So, the other option is to interact with Firebase in a true server side environment. This would be a lot of code, but here are the steps that I would take:

1) Setup a Pyrebase project so you can interact with your Firebase project via Python.

```<code>import pyrebase

config = {
    "apiKey": "apiKey",
    "authDomain": "projectId.firebaseapp.com",
    "databaseURL": "https://databaseName.firebaseio.com",
    "storageBucket": "projectId.appspot.com",
    "serviceAccount": "path/to/serviceAccountCredentials.json"
}
firebase = pyrebase.initialize_app(config)

...

db = firebase.database()
all_users = db.child("users").get()
</code>```

2) Setup a Google Scripts/Sheets project as a class that can interact with your Google Sheet

```<code>from __future__ import print_function
import httplib2
import os

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/sheets.googleapis.com-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Sheets API Python Quickstart'

class GoogleSheets:

    ...
    # The rest of the functions from that link can go here
    ...

    def write(self, sheet, sheet_name, row, col):
        """
            Write data to specified google sheet
        """

        if sheet == None or sheet == "":
            print("Sheet not specified.")
            return

        day = time.strftime("%m/%d/%Y")
        clock = time.strftime("%H:%M:%S")
        datetime = day + " - " + clock
        values = [[datetime]]

        spreadsheetId = sheet
        rangeName = sheet_name + "!" + str(row) + ":" + str(col)
        body = {
            'values': values
        }

        credentials = self.get_credentials()
        http = credentials.authorize(httplib2.Http())
        discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                'version=v4')
        service = discovery.build('sheets', 'v4', http=http,
                          discoveryServiceUrl=discoveryUrl)
        result = service.spreadsheets().values().update(
            spreadsheetId=spreadsheetId, range=rangeName,
            valueInputOption="RAW", body=body).execute()
</code>```

3) Call the Google Sheets somewhere inside your Pyrebase project

```<code>from GoogleSheets import GoogleSheets

...

g = GoogleSheets()
g.write(<project-id>, <sheet-name>, <row>, <col>)

...
</code>```

4) Set up a cron job to run the python script every so often

```<code># every 2 minutes
*/2 * * * * /root/my_projects/file_example.py
</code>```

You will need some basic server (Heroku, Digital Ocean) to run this.

This is not extensive because there is a lot of code to be written, but you could get the basics done. Makes we want to make a package now.

Body:
I am working in an Ionic 3 project with ts to integrate Firebase into my app.
The below code I used to integrate firebase with Ionic project

constructor(angFire: AngularFireDatabase){
}
 books: FirebaseListObservable<any>;

To send the data from my app to firebase, I used push method and to update entries I used update($key). Now I have all the data's in Firebase backend.

Now, how can I sync the firebase Database with Google Sheets so that each and every entry added to firebase backend has to get updated into sheets. I used a third party ZAPIER for this integration, but it would be nice if I get to learn on how to do this sync on my own.

Upon surfing, there are many tutorials to get the data's from the google sheets into Firebase. But I didn't come across any tutorials for vice versa.

I followed the below tutorial but it doesn't point to spreadsheets.
https://sites.google.com/site/scriptsexamples/new-connectors-to-google-services/firebase

Any help would be greatly appreciated!

Body:
I looked into importing Firebase right into Google Scripts either through the JavaScript SDK or or the REST API. Both have requirements/steps that Google Scripts cannot satisfy or that are extremely difficult to satisfy.

There is no foreseeable method of downloading the JavaScript SDK inside a Google Script because almost every method requires a DOM, which you don't have with a Google Sheet.

The REST API requires GoogleCredentials which, at a short glance, appear very difficult to get inside Google Scripts as well

So, the other option is to interact with Firebase in a true server side environment. This would be a lot of code, but here are the steps that I would take:

1) Setup a Pyrebase project so you can interact with your Firebase project via Python.

import pyrebase

config = {
    "apiKey": "apiKey",
    "authDomain": "projectId.firebaseapp.com",
    "databaseURL": "https://databaseName.firebaseio.com",
    "storageBucket": "projectId.appspot.com",
    "serviceAccount": "path/to/serviceAccountCredentials.json"
}
firebase = pyrebase.initialize_app(config)

...

db = firebase.database()
all_users = db.child("users").get()

2) Setup a Google Scripts/Sheets project as a class that can interact with your Google Sheet

from __future__ import print_function
import httplib2
import os

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/sheets.googleapis.com-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Sheets API Python Quickstart'

class GoogleSheets:

    ...
    # The rest of the functions from that link can go here
    ...

    def write(self, sheet, sheet_name, row, col):
        """
            Write data to specified google sheet
        """

        if sheet == None or sheet == "":
            print("Sheet not specified.")
            return

        day = time.strftime("%m/%d/%Y")
        clock = time.strftime("%H:%M:%S")
        datetime = day + " - " + clock
        values = [[datetime]]

        spreadsheetId = sheet
        rangeName = sheet_name + "!" + str(row) + ":" + str(col)
        body = {
            'values': values
        }

        credentials = self.get_credentials()
        http = credentials.authorize(httplib2.Http())
        discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                'version=v4')
        service = discovery.build('sheets', 'v4', http=http,
                          discoveryServiceUrl=discoveryUrl)
        result = service.spreadsheets().values().update(
            spreadsheetId=spreadsheetId, range=rangeName,
            valueInputOption="RAW", body=body).execute()

3) Call the Google Sheets somewhere inside your Pyrebase project

from GoogleSheets import GoogleSheets

...

g = GoogleSheets()
g.write(<project-id>, <sheet-name>, <row>, <col>)

...

4) Set up a cron job to run the python script every so often

# every 2 minutes
*/2 * * * * /root/my_projects/file_example.py

You will need some basic server (Heroku, Digital Ocean) to run this.

This is not extensive because there is a lot of code to be written, but you could get the basics done. Makes we want to make a package now.


问:
Passing ID Of Dynamic Javascript HTML
I'm trying to pass the element itself, or id. How can I make this work?

```<code>onclick="addYes(this)"
</code>```

```<code>for (var i = 0; i < data.length; i++) {
  tempTable+= '<tr>'+
    '<td  class="cust-data-row"style="height:40px;width:40%;">'+
    data[i].service+
    '</td>'+
    '</td>'+
    '<td  class="cust-data-row-yes" style="height:40px;width:10%;  id="rec_btn_yes_' +i+'"  onclick="addYes(this)" >'+
    'Yes'+
    '</td>'+
    '</tr>';
}

function addYes(button){
  //shows nothing:
  alert(button.id);
  //not working:
  document.getElementById(button.id).addClass("clicked_yes");
  //unrecognized method:
  button.addClass("clicked_yes");
}
</code>```

答:
Please have a look. It May help you.

$(document).ready(function(e){
for (var i = 0; i < 5; i++) {
    var $tr = '
'+
    ''+
    i +
    '	'+
    '	'+
    ''+
    'Yes_'+ i +
    '	'+
    '
';
    $("#t_body").append($tr);
}
});

function addYes(button){
  //shows nothing:
  console.log(button);
  alert(button.id);

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
            <tbody id="t_body">

            </tbody>
</table></code>```

Title: Passing ID Of Dynamic Javascript HTML

Body:
I'm trying to pass the element itself, or id. How can I make this work?

onclick="addYes(this)"

for (var i = 0; i < data.length; i++) {
  tempTable+= '
'+
    ''+
    data[i].service+
    '	'+
    '	'+
    ''+
    'Yes'+
    '	'+
    '
';
}

function addYes(button){
  //shows nothing:
  alert(button.id);
  //not working:
  document.getElementById(button.id).addClass("clicked_yes");
  //unrecognized method:
  button.addClass("clicked_yes");
}

Body:
Please have a look. It May help you.

$(document).ready(function(e){
for (var i = 0; i < 5; i++) {
    var $tr = '<tr>'+
    '<td  class="cust-data-row"style="height:40px;width:40%;">'+
    i +
    '</td>'+
    '</td>'+
    '<td  class="cust-data-row-yes" style="height:40px;width:10%;" id="rec_btn_yes_' +i+'" onclick="addYes(this);" >'+
    'Yes_'+ i +
    '</td>'+
    '</tr>';
    $("#t_body").append($tr);
}
});

function addYes(button){
  //shows nothing:
  console.log(button);
  alert(button.id);

}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
            <tbody id="t_body">

            </tbody>
</table>


问:
understanding jQuery $.getScript()
I use getScript to load dynamically my plugin:

```<code>$.getScript('js/code.photoswipe.jquery-3.0.4.min.js', function () {
   //do magic
});
</code>```

How do I disable caching busting?
At the moment it generates numbers at the end: js/code.photoswipe.jquery-3.0.4.min.js?_=1326992601415
I saw this, but not sure how to use it in my case:

```<code>$.getScript = function (url, callback, cache) {
   $.ajax({
      type: "GET",
      url: url,
      success: callback,
      dataType: "script",
      cache: cache
   });
};
</code>```

If I call $.getScript multiple times adding the same js file, does it do request each time to get that file? If so, is there a way to check if we already imported that script, so we could avoid calling getScript again for the same file?

答:
1 .
jQuery 1.12.0 and later supports the options object signature:

```<code>$.getScript({
    url: "foo.js",
    cache: true
})
</code>```

2 . Assuming you set cache:true the file will be loaded from the browser cache (unless browser cache is disabled or expired, for example when devtools is open)

Title: understanding jQuery $.getScript()

Body:
I use getScript to load dynamically my plugin:

$.getScript('js/code.photoswipe.jquery-3.0.4.min.js', function () {
   //do magic
});

How do I disable caching busting?
At the moment it generates numbers at the end: js/code.photoswipe.jquery-3.0.4.min.js?_=1326992601415
I saw this, but not sure how to use it in my case:

$.getScript = function (url, callback, cache) {
   $.ajax({
      type: "GET",
      url: url,
      success: callback,
      dataType: "script",
      cache: cache
   });
};

If I call $.getScript multiple times adding the same js file, does it do request each time to get that file? If so, is there a way to check if we already imported that script, so we could avoid calling getScript again for the same file?

Body:
1 .
jQuery 1.12.0 and later supports the options object signature:

$.getScript({
    url: "foo.js",
    cache: true
})

2 . Assuming you set cache:true the file will be loaded from the browser cache (unless browser cache is disabled or expired, for example when devtools is open)


问:
SignInManager.ExternalLoginSignInAsync fails to log in user
In the context of ASP.NET Identity in ASP.NET Core and OAuth, I have the following snippet in a login callback:

```<code>var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
    return RedirectToAction(nameof(Login));
}

var result = await _signInManager.ExternalLoginSignInAsync(
    info.LoginProvider,
    info.ProviderKey,
    isPersistent: true);

if (result.Succeeded)
{
    // ...
</code>```

For some reason that I'm unable to determine, result always comes back with status Failed, even though I do log into the external provider correctly (evidently, since a refresh of the external page suddenly shows me as logged on).

The only information I have except that the login attempt failed, is that it is not because any of IsLockedOut, RequiresTwoFactor or IsNotAllowed, since those flags are also false on the result object.

How do I obtain more information about what went wrong?

Update:

Following suggestions by @Dmitry, I've enabled quite aggressive logging, but I still fail to find anything valuable. The only thing I get in my logs between the successful fetch of info and the subsequent failed login attempt, is the following from my db context:

2017-07-04T22:45:14.2847287+02:00 0HL633KNRMVO7 [INF] Executed DbCommand (1ms) [Parameters=[@__get_Item_0='?' (Size = 450), @__get_Item_1='?' (Size = 450)], CommandType='Text', CommandTimeout='30']
  SELECT TOP(1) [e].[LoginProvider], [e].[ProviderKey], [e].[ProviderDisplayName], [e].[UserId]
  FROM [AspNetUserLogins] AS [e]
  WHERE ([e].[LoginProvider] = @__get_Item_0) AND ([e].[ProviderKey] = @__get_Item_1) (6438bdd5)

Executing that in MSSQL Management Studio I get an empty result set, which I suspect might be a problem, but I have no idea why, or how to fix it. Any help is much appreciated.

答: You are missing a call to UserManager.AddLoginAsync (https://msdn.microsoft.com/en-us/library/dn497534(v=vs.108).aspx), which will populate the AspNetUserLogins table.

Body:
In the context of ASP.NET Identity in ASP.NET Core and OAuth, I have the following snippet in a login callback:

var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
    return RedirectToAction(nameof(Login));
}

var result = await _signInManager.ExternalLoginSignInAsync(
    info.LoginProvider,
    info.ProviderKey,
    isPersistent: true);

if (result.Succeeded)
{
    // ...

For some reason that I'm unable to determine, result always comes back with status Failed, even though I do log into the external provider correctly (evidently, since a refresh of the external page suddenly shows me as logged on).

The only information I have except that the login attempt failed, is that it is not because any of IsLockedOut, RequiresTwoFactor or IsNotAllowed, since those flags are also false on the result object.

How do I obtain more information about what went wrong?

Update:

Following suggestions by @Dmitry, I've enabled quite aggressive logging, but I still fail to find anything valuable. The only thing I get in my logs between the successful fetch of info and the subsequent failed login attempt, is the following from my db context:

2017-07-04T22:45:14.2847287+02:00 0HL633KNRMVO7 [INF] Executed DbCommand (1ms) [Parameters=[@__get_Item_0='?' (Size = 450), @__get_Item_1='?' (Size = 450)], CommandType='Text', CommandTimeout='30']
  SELECT TOP(1) [e].[LoginProvider], [e].[ProviderKey], [e].[ProviderDisplayName], [e].[UserId]
  FROM [AspNetUserLogins] AS [e]
  WHERE ([e].[LoginProvider] = @__get_Item_0) AND ([e].[ProviderKey] = @__get_Item_1) (6438bdd5)

Executing that in MSSQL Management Studio I get an empty result set, which I suspect might be a problem, but I have no idea why, or how to fix it. Any help is much appreciated.


问:
How to get GA Tracking IDs from GTM code
Is there with javascript a way to retrieve the Google Analytics "Web Property ID" for a given GTM code?

I am including the snippet for GTM in the HEAD of my pages, and the Google Tag Assistant extension sees the tags properly, including the "Web Property Id" (UA-XXXXX-XX).
I am using ReactGA module to send GA Events, and I need the "Web Property Id" to initialise it.

If I copy it to initialize the module like this;

```<code>ReactGA.initialize('UA-XXXXX-XX');
</code>```

it is working properly, but I would prefer to retrieve it dynamically: i already map the GTM codes, i don't see any reason to do the same for the Web Property IDs if I can retrieve them from GTM codes.

答:
I would assume this is not possible. The reason being that the property ID would most likely be stored in the GTM container as a constant variable. Client side (i.e. via JavaScript), you would have no way of knowing the name (or unique ID) of this GTM variable. There is a JavaScript function available:

google_tag_manager['GTM-XXXXXX'].macro(i)

This macro function accepts a single integer as a parameter. This integer represents the "id" of the GTM variable. As I said above, you have no way of knowing what the ID of the (constant) variable that stores your GA property ID is, so this function is of no use to you.

Body:
Is there with javascript a way to retrieve the Google Analytics "Web Property ID" for a given GTM code?

I am including the snippet for GTM in the HEAD of my pages, and the Google Tag Assistant extension sees the tags properly, including the "Web Property Id" (UA-XXXXX-XX).
I am using ReactGA module to send GA Events, and I need the "Web Property Id" to initialise it.

If I copy it to initialize the module like this;

ReactGA.initialize('UA-XXXXX-XX');

it is working properly, but I would prefer to retrieve it dynamically: i already map the GTM codes, i don't see any reason to do the same for the Web Property IDs if I can retrieve them from GTM codes.


问:
How to check for nil value? App crashes even though nil values are accounted for. Swift
I am creating a simple guessing game on Xcode where the user has to correctly guess the number (between 0 and 5). I thought that I had checked for a nil value for my textFieldIntto ensure the app does not crash if no value is submitted. Unfortunately this does not seem to be the case and I am not sure where my fault lies.

If I do not enter a value and press the button, I receive the following error message:

fatal error: unexpectedly found nil while unwrapping an Optional value

I have had this issue before and managed to solve it by correctly checking the right optional for nil. Though now it seems to still have 'unexpectedly found nil' even though a nil value has been accounted for.

```<code>@IBOutlet var textField: UITextField!

@IBOutlet var label: UILabel!

@IBAction func buttonTapped(_ sender: Any) {
    let textFieldInt: UInt32 = UInt32(textField.text!)!
    let number = arc4random_uniform(6)

    if textFieldInt != nil {
        if textFieldInt != number {
            label.text = "Wrong! It was \(number)"
        }
        else if textFieldInt == number {
            label.text = "You're right!"
        }

    else {
        label.text = "Please enter a number!"
    }
}
}
</code>```

答:
Use if let or guard let to test your values. For example

```<code>if let textFieldInt = UInt32(textField.text!)  {
    //textField.text! can be converted to UInt32
    if textFieldInt != number {
        label.text = "Wrong! It was \(number)"
    }
    else if textFieldInt == number {
        label.text = "You're right!"
    }
}else {
    //textField.text! can NOT be converted to UInt32
    label.text = "Please enter a number!"
}
</code>```

Or

```<code>guard let textFieldInt = UInt32(textField.text!) else {
    //textField.text! can NOT be converted to UInt32
    label.text = "Please enter a number!"
    return
}
//textField.text! can be converted to UInt32
if textFieldInt != number {
    label.text = "Wrong! It was \(number)"
}
else if textFieldInt == number {
    label.text = "You're right!"
}
</code>```

Body:
I am creating a simple guessing game on Xcode where the user has to correctly guess the number (between 0 and 5). I thought that I had checked for a nil value for my textFieldIntto ensure the app does not crash if no value is submitted. Unfortunately this does not seem to be the case and I am not sure where my fault lies.

If I do not enter a value and press the button, I receive the following error message:

fatal error: unexpectedly found nil while unwrapping an Optional value

I have had this issue before and managed to solve it by correctly checking the right optional for nil. Though now it seems to still have 'unexpectedly found nil' even though a nil value has been accounted for.

@IBOutlet var textField: UITextField!

@IBOutlet var label: UILabel!

@IBAction func buttonTapped(_ sender: Any) {
    let textFieldInt: UInt32 = UInt32(textField.text!)!
    let number = arc4random_uniform(6)

    if textFieldInt != nil {
        if textFieldInt != number {
            label.text = "Wrong! It was \(number)"
        }
        else if textFieldInt == number {
            label.text = "You're right!"
        }

    else {
        label.text = "Please enter a number!"
    }
}
}

Body:
Use if let or guard let to test your values. For example

if let textFieldInt = UInt32(textField.text!)  {
    //textField.text! can be converted to UInt32
    if textFieldInt != number {
        label.text = "Wrong! It was \(number)"
    }
    else if textFieldInt == number {
        label.text = "You're right!"
    }
}else {
    //textField.text! can NOT be converted to UInt32
    label.text = "Please enter a number!"
}

Or

guard let textFieldInt = UInt32(textField.text!) else {
    //textField.text! can NOT be converted to UInt32
    label.text = "Please enter a number!"
    return
}
//textField.text! can be converted to UInt32
if textFieldInt != number {
    label.text = "Wrong! It was \(number)"
}
else if textFieldInt == number {
    label.text = "You're right!"
}


问:
T-SQL Consider timestamp ordering to determine group
I have an interesting grouping case for which I really can't figure the best way to proceed with.  I'm dealing with a lot of data so I'm trying to find the most effective way to perform my query.

Here's an example of data I could have

```<code>|Line      |Trip          |Speed        |Timestamp
====================================================
|100       |1             |50 kmh       |2017-06-12 22:34:50
|100       |1             |55 kmh       |2017-06-12 22:36:44
|100       |1             |56 kmh       |2017-06-12 22:37:12
|200       |5             |12 kmh       |2017-06-12 22:40:11
|200       |5             |18 kmh       |2017-06-12 22:43:13
|100       |1             |23 kmh       |2017-06-12 22:49:11
|100       |1             |45 kmh       |2017-06-12 22:53:49
</code>```

I would like to be able to define a grouping number sequentially based on the Line & Trip ordered by the timestamp.  So basically at the end I would expect something such as:

```<code>|Line      |Trip          |Speed        |Timestamp            |GroupNumber
===========================================================================
|100       |1             |50 kmh       |2017-06-12 22:34:50  |  1
|100       |1             |55 kmh       |2017-06-12 22:36:44  |  1
|100       |1             |56 kmh       |2017-06-12 22:37:12  |  1
|200       |5             |12 kmh       |2017-06-12 22:40:11  |  2
|200       |5             |18 kmh       |2017-06-12 22:43:13  |  2
|100       |1             |23 kmh       |2017-06-12 22:49:11  |  3
|100       |1             |45 kmh       |2017-06-12 22:53:49  |  3
</code>```

I can't find any way using DENSE_RANK or ROW_NUMBER because the last group of 100/1 is merged again with the first records but should not because there is another group (200/5) between both occurence.

Any help would be appreciated.
Thank you.

Body:
I have an interesting grouping case for which I really can't figure the best way to proceed with.  I'm dealing with a lot of data so I'm trying to find the most effective way to perform my query.

Here's an example of data I could have

|Line      |Trip          |Speed        |Timestamp
====================================================
|100       |1             |50 kmh       |2017-06-12 22:34:50
|100       |1             |55 kmh       |2017-06-12 22:36:44
|100       |1             |56 kmh       |2017-06-12 22:37:12
|200       |5             |12 kmh       |2017-06-12 22:40:11
|200       |5             |18 kmh       |2017-06-12 22:43:13
|100       |1             |23 kmh       |2017-06-12 22:49:11
|100       |1             |45 kmh       |2017-06-12 22:53:49

I would like to be able to define a grouping number sequentially based on the Line & Trip ordered by the timestamp.  So basically at the end I would expect something such as:

|Line      |Trip          |Speed        |Timestamp            |GroupNumber
===========================================================================
|100       |1             |50 kmh       |2017-06-12 22:34:50  |  1
|100       |1             |55 kmh       |2017-06-12 22:36:44  |  1
|100       |1             |56 kmh       |2017-06-12 22:37:12  |  1
|200       |5             |12 kmh       |2017-06-12 22:40:11  |  2
|200       |5             |18 kmh       |2017-06-12 22:43:13  |  2
|100       |1             |23 kmh       |2017-06-12 22:49:11  |  3
|100       |1             |45 kmh       |2017-06-12 22:53:49  |  3

I can't find any way using DENSE_RANK or ROW_NUMBER because the last group of 100/1 is merged again with the first records but should not because there is another group (200/5) between both occurence.

Any help would be appreciated.
Thank you.

Body:
This is known as a Gaps and Islands problem.

To identify your islands, you need to use two ranking functions, the first to find the position of a row within the set, and the second to find the position of the row within its subset (Line, Trip), So you would end up with:

SELECT  Line,
        Trip,
        Speed,
        Timestamp,
        R1 = ROW_NUMBER() OVER(ORDER BY Timestamp),
        R2 = ROW_NUMBER() OVER(PARTITION BY Line, Trip ORDER BY Timestamp)
FROM    dbo.YourTable;

|Line      |Trip          |Speed        |Timestamp              R1      R2
==========================================================================
|100       |1             |50 kmh       |2017-06-12 22:34:50    1       1
|100       |1             |55 kmh       |2017-06-12 22:36:44    2       2
|100       |1             |56 kmh       |2017-06-12 22:37:12    3       3
|200       |5             |12 kmh       |2017-06-12 22:40:11    4       1   <-- starts new sequence for new group
|200       |5             |18 kmh       |2017-06-12 22:43:13    5       2
|100       |1             |23 kmh       |2017-06-12 22:49:11    6       4   <-- follows on from where it left off
|100       |1             |45 kmh       |2017-06-12 22:53:49    7       5

Now, if you deduct one from the other you get a unique identifier for each island

|Line      |Trip          |Speed        |Timestamp              R1      R2  (R1 - R2)
=======================================================================================
|100       |1             |50 kmh       |2017-06-12 22:34:50    1       1       0
|100       |1             |55 kmh       |2017-06-12 22:36:44    2       2       0
|100       |1             |56 kmh       |2017-06-12 22:37:12    3       3       0
|200       |5             |12 kmh       |2017-06-12 22:40:11    4       1       3
|200       |5             |18 kmh       |2017-06-12 22:43:13    5       2       3
|100       |1             |23 kmh       |2017-06-12 22:49:11    6       4       2
|100       |1             |45 kmh       |2017-06-12 22:53:49    7       5       2

Finally, you can use this unique identifier to get a starting time for each group:

SELECT  Line,
        Trip,
        Speed,
        Timestamp,
        GroupStart = MIN(Timestamp) OVER(PARTITION BY Line, Trip, IslandID)
FROM    (   SELECT  Line,
                    Trip,
                    Speed,
                    Timestamp,
                    IslandID = ROW_NUMBER() OVER(ORDER BY Timestamp) -
                                ROW_NUMBER() OVER(PARTITION BY Line, Trip
                                                    ORDER BY Timestamp)
            FROM    dbo.YourTable
        ) AS t;

Then finally, you can apply DENSE_RANK() to the group start time to get an integer ranking. So with your sample data you would get:

-- SAMPLE DATA
DECLARE @T TABLE (Line INT, Trip INT, Speed VARCHAR(6), Timestamp DATETIME);
INSERT @T (Line, Trip, Speed, Timestamp)
VALUES
    (100, 1, '50 kmh', '2017-06-12 22:34:50'),
    (100, 1, '55 kmh', '2017-06-12 22:36:44'),
    (100, 1, '56 kmh', '2017-06-12 22:37:12'),
    (200, 5, '12 kmh', '2017-06-12 22:40:11'),
    (200, 5, '18 kmh', '2017-06-12 22:43:13'),
    (100, 1, '23 kmh', '2017-06-12 22:49:11'),
    (100, 1, '45 kmh', '2017-06-12 22:53:49');

WITH GroupedData AS
(   SELECT  Line,
            Trip,
            Speed,
            Timestamp,
            GroupStart = MIN(Timestamp) OVER(PARTITION BY Line, Trip, IslandID),
            IslandID
    FROM    (   SELECT  Line,
                        Trip,
                        Speed,
                        Timestamp,
                        IslandID = ROW_NUMBER() OVER(ORDER BY Timestamp) -
                                    ROW_NUMBER() OVER(PARTITION BY Line, Trip
                                                        ORDER BY Timestamp)
                FROM    @T
            ) AS t
)
SELECT  Line,
        Trip,
        Speed,
        Timestamp,
        GroupNumber = DENSE_RANK() OVER(ORDER BY GroupStart, IslandID)
FROM    GroupedData
ORDER BY Timestamp;

OUTPUT

Line    Trip    Speed   Timestamp                   GroupNumber
--------------------------------------------------------------
100     1       50 kmh  2017-06-12 22:34:50.000     1
100     1       55 kmh  2017-06-12 22:36:44.000     1
100     1       56 kmh  2017-06-12 22:37:12.000     1
200     5       12 kmh  2017-06-12 22:40:11.000     2
200     5       18 kmh  2017-06-12 22:43:13.000     2
100     1       23 kmh  2017-06-12 22:49:11.000     3
100     1       45 kmh  2017-06-12 22:53:49.000     3


问:
Import CSV file with tab delimited using PHPExcel lib
I'm trying to import CSV file using PHPExcel lib. My CSV file has \t or tab as delimiter.

So when I'm trying to printout the result in my screen, every comma seen as new cell, just like this

But actually I need to export data in one line for each row and separated by quotation-sign (") for each tab delimiter, just like this one

This is my code in Controller for reading and write the data:

```<code>$worksheet = $objPHPExcelDetail->getActiveSheet();
        foreach ($worksheet->getRowIterator() as $row) {
                echo '```';
                echo 'Row number: ' . $row->getRowIndex() . "\r\n";

                $cellIterator = $row->getCellIterator();
                $cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set

                foreach ($cellIterator as $cell) {
                    if (!is_null($cell)) {
                        echo 'Cell: ' . $cell->getCoordinate() . ' - ' . $cell->getValue() . "\r\n";
                    }
                }
        }
```

How can I read CSV file with \t separator, and set into one line for each row?

答:
It's the code for loading the file that you need to think about.

Look at the methods available to the CSV Reader in the PHPExcel Documentation.... you'll find that there is a setDelimiter() method that allows you to say to use a tab rather than a ,.

```<code>$objReader = PHPExcel_IOFactory::createReader('CSV')
    ->setDelimiter("\t");
$objPHPExcel = $objReader->load($myFileName);
</code>```

Body:
I'm trying to import CSV file using PHPExcel lib. My CSV file has \t or tab as delimiter.

So when I'm trying to printout the result in my screen, every comma seen as new cell, just like this

But actually I need to export data in one line for each row and separated by quotation-sign (") for each tab delimiter, just like this one

This is my code in Controller for reading and write the data:

$worksheet = $objPHPExcelDetail->getActiveSheet();
        foreach ($worksheet->getRowIterator() as $row) {
                echo '
';
                echo 'Row number: ' . $row->getRowIndex() . "\r\n";

                $cellIterator = $row->getCellIterator();
                $cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set

                foreach ($cellIterator as $cell) {
                    if (!is_null($cell)) {
                        echo 'Cell: ' . $cell->getCoordinate() . ' - ' . $cell->getValue() . "\r\n";
                    }
                }
        }

How can I read CSV file with \t separator, and set into one line for each row?

Body:
It's the code for loading the file that you need to think about.

Look at the methods available to the CSV Reader in the PHPExcel Documentation.... you'll find that there is a setDelimiter() method that allows you to say to use a tab rather than a ,.

$objReader = PHPExcel_IOFactory::createReader('CSV')
    ->setDelimiter("\t");
$objPHPExcel = $objReader->load($myFileName);


问:
Use Process.Start with parameters AND spaces in path
I've seen similar examples, but can't find something exactly like my problem.

I need to run a command like this from C#:

```<code>C:\FOLDER\folder with spaces\OTHER_FOLDER\executable.exe p1=hardCodedv1 p2=v2
</code>```

I'm setting v2 at runtime, so I need to be able to modify the string in C# before calling Process.Start.  Does anyone know how to handle this, since I have spaces between my parameters?

答:
After looking at the other solutions provided I ran into the issue where all my various arguments were bundled into one argument.

i.e. "-setting0=arg0 --subsetting0=arg1"

So I would propose the following:

```<code>        ProcessStartInfo psi = new ProcessStartInfo();
        psi.FileName = "\"" + Prefs.CaptureLocation.FullName + "\"";
        psi.Arguments = String.Format("-setting0={0} --subsetting0={1}", "\"" + arg0 + "\"", "\"" + arg1+ "\"");
        Process.Start(psi);
</code>```

With the quotes around each argument, instead of around the entire set of arguments. And as pointed out by Red_Shadow this can all be done with the single line

```<code>        Process.Start("\"" + filename + "\"", arguments here)
</code>```

Body:
I've seen similar examples, but can't find something exactly like my problem.

I need to run a command like this from C#:

C:\FOLDER\folder with spaces\OTHER_FOLDER\executable.exe p1=hardCodedv1 p2=v2

I'm setting v2 at runtime, so I need to be able to modify the string in C# before calling Process.Start.  Does anyone know how to handle this, since I have spaces between my parameters?

Body:
After looking at the other solutions provided I ran into the issue where all my various arguments were bundled into one argument.

i.e. "-setting0=arg0 --subsetting0=arg1"

So I would propose the following:

        ProcessStartInfo psi = new ProcessStartInfo();
        psi.FileName = "\"" + Prefs.CaptureLocation.FullName + "\"";
        psi.Arguments = String.Format("-setting0={0} --subsetting0={1}", "\"" + arg0 + "\"", "\"" + arg1+ "\"");
        Process.Start(psi);

With the quotes around each argument, instead of around the entire set of arguments. And as pointed out by Red_Shadow this can all be done with the single line

        Process.Start("\"" + filename + "\"", arguments here)


问:
google apps script HTMLService button click opens new blank tab
Fairly new to HTML Service in apps script, have written a very basic UI.

The problem is that when the button is clicked (no onclick handler set) it opens up a new blank tab (I'm using Chrome).

Code below reproduces the behaviour, I have jquery / jquery UI references which are used in the broader project so left them in here.

How do I stop this blank tab opening on button click?  Not shown here but it also happens when entered hit in a text box.

code.js:

```<code>    function NewProposal() {
  var html = HtmlService.createTemplateFromFile('Index');

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  ss.show(html.evaluate().setHeight(530).setWidth(1100).setSandboxMode(HtmlService.SandboxMode.IFRAME));
}
</code>```

Index.html:

```<code><!DOCTYPE html>

<base target="_top">

    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/cupertino/jquery-ui.css">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>

    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.4.1/jsgrid.min.js"></script>

<form>
        <table>
            <tr>
                <td>
                    <button id="Create">Create</button>
                </td>
            </tr>
       </table>
</form>
</code>```

答:
Add onsubmit="return(false)" inside your form openning tag:

```<code><form onsubmit="return(false)">
  ...
</form>
</code>```

Body:
Fairly new to HTML Service in apps script, have written a very basic UI.

The problem is that when the button is clicked (no onclick handler set) it opens up a new blank tab (I'm using Chrome).

Code below reproduces the behaviour, I have jquery / jquery UI references which are used in the broader project so left them in here.

How do I stop this blank tab opening on button click?  Not shown here but it also happens when entered hit in a text box.

code.js:

    function NewProposal() {
  var html = HtmlService.createTemplateFromFile('Index');

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  ss.show(html.evaluate().setHeight(530).setWidth(1100).setSandboxMode(HtmlService.SandboxMode.IFRAME));
}

Index.html:

<!DOCTYPE html>

<base target="_top">

    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/cupertino/jquery-ui.css">

<form>

                    <button id="Create">Create</button>

</form>

Body:
Add onsubmit="return(false)" inside your form openning tag:

<form onsubmit="return(false)">
  ...
</form>


问:
How to convert an IOrderedEnumerable<char> to string in c#?
I need to sort a string alphabetically. The most common solution I have found is to use linq:

```<code>var sortedString = unsortedString.OrderBy(c => c);
</code>```

The problem I have with this solution is that the result is not a string. The result is an IOrderedEnumerable< char > which needs to be converted. This does not work:

```<code>var sortedString = unsortedString.OrderBy(c => c).ToString();
</code>```

答:
String is a sequence of characters. So

```<code>unsortedString.OrderBy(c => c)
</code>```

returns sequence of ordered characters as well. I.e. IEnumerable<char>. You should create a new instance of string from these ordered characters:

```<code>var sortedString = new String(unsortedString.OrderBy(c => c).ToArray());
</code>```

When you use ToString() on sequence of characters, you just get a type name of the sequence.

Body:
I need to sort a string alphabetically. The most common solution I have found is to use linq:

var sortedString = unsortedString.OrderBy(c => c);

The problem I have with this solution is that the result is not a string. The result is an IOrderedEnumerable< char > which needs to be converted. This does not work:

var sortedString = unsortedString.OrderBy(c => c).ToString();

Body:
String is a sequence of characters. So

unsortedString.OrderBy(c => c)

returns sequence of ordered characters as well. I.e. IEnumerable<char>. You should create a new instance of string from these ordered characters:

var sortedString = new String(unsortedString.OrderBy(c => c).ToArray());

When you use ToString() on sequence of characters, you just get a type name of the sequence.


问:
How Run A Stored Procedure (with Parameters - Has A return Value) From Code Behind?
How can I use a stored procedure (with parameters - has a return value of type int) from code behind?

My stored procedure looks like this :

```<code>ALTER Procedure [dbo].[sp_Noskheh_SumOfTotalPay]
    @Co_ID int
AS
-----------------
Declare @Sum bigint
-----------------
BEGIN
    SELECT
       @Sum = SUM(TotalPay)
    FROM Noskheh
    WHERE
       (Co_ID = @Co_ID)

    RETURN @Sum
END
</code>```

I want to use @Sum in code behind ...

Would you please show me a way for doing that ?

Thanks in advance

best regards

答:
You need to set up a SqlConnection and a SqlCommand. If you have your code with the RETURN @Sum statement in the end, you need to do this (define a parameter of type RETURN_VALUE):

```<code>using(SqlConnection _conn = new SqlConnection(-your-connection-string-here))
using(SqlCommand _cmd = new SqlCommand("dbo.sp_Noskheh_SumOfTotalPay", _conn))
{
   _cmd.CommandType = CommandType.StoredProcedure;

   _cmd.Parameters.Add(new SqlParameter("@CO_ID", SqlDbType.Int));
   _cmd.Parameters["@CO_ID"].Value = 5; // whatever value you want

   _cmd.Parameters.Add(new SqlParameter("@RETURN_VALUE", SqlDbType.BigInt));
   _cmd.Parameters["@RETURN_VALUE"].Direction = ParameterDirection.ReturnValue;

   _conn.Open();
   _cmd.ExecuteNonQuery();

   Int64 result = Int64.Parse(_cmd.Parameters["@RETURN_VALUE"].Value);

   _conn.Close();
}
</code>```

It would be a lot easier if you would replace that RETURN statement with a simple SELECT:

```<code>SELECT @Sum
</code>```

In that case, you can use the simplified version I had before - using .ExecuteScalar() to retrieve the single value of the single row being returned from the stored proc:

```<code>using(SqlConnection _conn = new SqlConnection(-your-connection-string-here))
using(SqlCommand _cmd = new SqlCommand("dbo.sp_Noskheh_SumOfTotalPay", _conn))
{
   _cmd.CommandType = CommandType.StoredProcedure;

   _cmd.Parameters.Add(new SqlParameter("@CO_ID", SqlDbType.Int));
   _cmd.Parameters["@CO_ID"].Value = 5; // whatever value you want

   _conn.Open();
   object result = _cmd.ExecuteScalar();
   _conn.Close();

   Int64 sum = Int64.Parse(result);
}
</code>```

That should call your stored proc, read the single value you're returning, and converting it into an int variable called sum.

Body:
How can I use a stored procedure (with parameters - has a return value of type int) from code behind?

My stored procedure looks like this :

ALTER Procedure [dbo].[sp_Noskheh_SumOfTotalPay]
    @Co_ID int
AS
-----------------
Declare @Sum bigint
-----------------
BEGIN
    SELECT
       @Sum = SUM(TotalPay)
    FROM Noskheh
    WHERE
       (Co_ID = @Co_ID)

    RETURN @Sum
END

I want to use @Sum in code behind ...

Would you please show me a way for doing that ?

Thanks in advance

best regards

Body:
You need to set up a SqlConnection and a SqlCommand. If you have your code with the RETURN @Sum statement in the end, you need to do this (define a parameter of type RETURN_VALUE):

using(SqlConnection _conn = new SqlConnection(-your-connection-string-here))
using(SqlCommand _cmd = new SqlCommand("dbo.sp_Noskheh_SumOfTotalPay", _conn))
{
   _cmd.CommandType = CommandType.StoredProcedure;

   _cmd.Parameters.Add(new SqlParameter("@CO_ID", SqlDbType.Int));
   _cmd.Parameters["@CO_ID"].Value = 5; // whatever value you want

   _cmd.Parameters.Add(new SqlParameter("@RETURN_VALUE", SqlDbType.BigInt));
   _cmd.Parameters["@RETURN_VALUE"].Direction = ParameterDirection.ReturnValue;

   _conn.Open();
   _cmd.ExecuteNonQuery();

   Int64 result = Int64.Parse(_cmd.Parameters["@RETURN_VALUE"].Value);

   _conn.Close();
}

It would be a lot easier if you would replace that RETURN statement with a simple SELECT:

SELECT @Sum

In that case, you can use the simplified version I had before - using .ExecuteScalar() to retrieve the single value of the single row being returned from the stored proc:

using(SqlConnection _conn = new SqlConnection(-your-connection-string-here))
using(SqlCommand _cmd = new SqlCommand("dbo.sp_Noskheh_SumOfTotalPay", _conn))
{
   _cmd.CommandType = CommandType.StoredProcedure;

   _cmd.Parameters.Add(new SqlParameter("@CO_ID", SqlDbType.Int));
   _cmd.Parameters["@CO_ID"].Value = 5; // whatever value you want

   _conn.Open();
   object result = _cmd.ExecuteScalar();
   _conn.Close();

   Int64 sum = Int64.Parse(result);
}

That should call your stored proc, read the single value you're returning, and converting it into an int variable called sum.


问:
How can I create the necessary out-directories for targets with make?
Say, in a Makefile, I have the following targets:

```<code>EXES=dir1/subdir1/abc dir1/subdir1/def dir1/subdir2/ghi dir1/subdir2/jkl dir2/subdir3/mno dir2/subdir3/pqr
</code>```

Each item in $(EXES) represents a binary to be created. I want to make sure that the necessary directories (in the example: dir1/subdir1, dir1/subdir2, dir2/subdir3) are created if they are not existent.

How would I achieve this with gnu-make?

答:
Use order-only prerequisites:

```<code>target: prerequisites | order-only-prerequisites

order-only-prerequisites:
    recipe
</code>```

Their recipe is executed only if they do not exist yet. Example:

```<code>$(BUILDDIR)/foo.o: src/foo.c | $(BUILDDIR)
    $(CC) $(CFLAGS) -o $@ $<

$(BUILDDIR):
    mkdir -p $@
</code>```

And if you want to extract the list of directories to create from the definition of your EXES variable:

```<code>$(EXES): | $(dir $(EXES))

$(dir $(EXES)):
    mkdir -p $@
</code>```

Or, to instantiate exactly one rule per target:

```<code>define DIR_rule
$(1): | $$(dir $(1))
endef
$(foreach e,$(EXES),$(eval $(call DIR_rule,$(e))))

$(dir $(EXES)):
    mkdir -p $@
</code>```

Body:
Say, in a Makefile, I have the following targets:

EXES=dir1/subdir1/abc dir1/subdir1/def dir1/subdir2/ghi dir1/subdir2/jkl dir2/subdir3/mno dir2/subdir3/pqr

Each item in $(EXES) represents a binary to be created. I want to make sure that the necessary directories (in the example: dir1/subdir1, dir1/subdir2, dir2/subdir3) are created if they are not existent.

How would I achieve this with gnu-make?

Body:
Use order-only prerequisites:

target: prerequisites | order-only-prerequisites

order-only-prerequisites:
    recipe

Their recipe is executed only if they do not exist yet. Example:

$(BUILDDIR)/foo.o: src/foo.c | $(BUILDDIR)
    $(CC) $(CFLAGS) -o $@ $<

$(BUILDDIR):
    mkdir -p $@

And if you want to extract the list of directories to create from the definition of your EXES variable:

$(EXES): | $(dir $(EXES))

$(dir $(EXES)):
    mkdir -p $@

Or, to instantiate exactly one rule per target:

define DIR_rule
$(1): | $$(dir $(1))
endef
$(foreach e,$(EXES),$(eval $(call DIR_rule,$(e))))

$(dir $(EXES)):
    mkdir -p $@


问:
Can't reach metadata in viewmodel in my view
I would like to use metadata in my view but my model(ToDoTable) is packed in viewmodel(ModelsViewList) and I don't know how to reach the model.The @foreach (var property in ViewData.ModelMetadata.Properties) doesn't work :(.

Model:

```<code>public partial class ToDoTable
        {
            [HiddenInput(DisplayValue = false)]
            public int ID { get; set; }

            [Required(ErrorMessage = "Please write name of event.")]
            public string EventName { get; set; }

            [MaxLength(50, ErrorMessage = "Description must be shorter than 50 characters ")]
            [Required(ErrorMessage = "Proszę podać opis.")]
            public string Description { get; set; }

            [Display(Name = "Tu wpisz format daty")]
            [DataType(DataType.Date, ErrorMessage = "Date mast be in format described")]
            public string Data { get; set; }
        }
</code>```

Controller:

```<code> using System.Web.Mvc;
        using ToDoLibrary.Abstract;
        using ToDoUI.ModelsViews;

        namespace ToDoUI.Controllers
        {
            public class HomeController : Controller
            {
                IToDoRepository repository;
               public HomeController(IToDoRepository rep)
               {
                    repository = rep;
               }
                public ViewResult List()
                {
                    ToDoLibrary.ToDoTable model = new ToDoLibrary.ToDoTable();
                    ModelsViewList modelView = new ModelsViewList()
                    {
                        FromRepository = repository.FromRepository,
                        ModelDB = model
                    };
                   return View(modelView);
                }

           }`
       }
</code>```

View:

```<code>@model ToDoUI.ModelsViews.ModelsViewList
    @{
        ViewBag.Title = "List";
    }
    <div class="row">
        <div class="col-lg-6 main tile1 col-lg-push-6">
            pierwsza kolumna

            @using (Html.BeginForm("Edit", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {
                <div class="panel-body">

                    @foreach (var property in ViewData.ModelMetadata.Properties)
                    {
                        switch (property.PropertyName)
                        {
                            case "ID":

                                break;
                            default:
                                <div class="form-group">
                                    <label>@(property.DisplayName ?? property.PropertyName)</label>
                                    @if (property.PropertyName == "Description")
                                {
                                        @Html.TextArea(property.PropertyName, null, new { @class = "form-control", rows = 5 })
                                    }
                                    else
                                    {
                                        @Html.TextBox(property.PropertyName, null, new { @class = "form-control" })
                                    }
                                    @Html.ValidationMessage(property.PropertyName)
                                </div>
                                break;
                        }
                    }
                </div>
                <div class="panel-footer">
                    <input type="submit" value="Zapisz" class="btn btn-primary" />
                    @Html.ActionLink("Anuluj i wróć do listy", "Index", null, new
               {
                   @class = "btn btn-default"
               })
                </div>
            }
         </div>
    </div>
</code>```

答:
Your property name should be more like ModelDB.ID as your metadata is related to ToDoUI.ModelsViews.ModelsViewList which contains a property ModelDB, which is your ToDoTable object you are referencing.

Otherwise :

```<code>var metaData = ModelMetadataProviders.
     Current.GetMetadataForType(null, Model.ModelDB.GetType());
</code>```

This will give you the metadata of your TodoTable you can then go through your properties. Anyway I am not sure it will help you to do something decent... As it doesn't look like it will :)

Body:
I would like to use metadata in my view but my model(ToDoTable) is packed in viewmodel(ModelsViewList) and I don't know how to reach the model.The @foreach (var property in ViewData.ModelMetadata.Properties) doesn't work :(.

Model:

public partial class ToDoTable
        {
            [HiddenInput(DisplayValue = false)]
            public int ID { get; set; }

            [Required(ErrorMessage = "Please write name of event.")]
            public string EventName { get; set; }

            [MaxLength(50, ErrorMessage = "Description must be shorter than 50 characters ")]
            [Required(ErrorMessage = "Proszę podać opis.")]
            public string Description { get; set; }

            [Display(Name = "Tu wpisz format daty")]
            [DataType(DataType.Date, ErrorMessage = "Date mast be in format described")]
            public string Data { get; set; }
        }

Controller:

 using System.Web.Mvc;
        using ToDoLibrary.Abstract;
        using ToDoUI.ModelsViews;

        namespace ToDoUI.Controllers
        {
            public class HomeController : Controller
            {
                IToDoRepository repository;
               public HomeController(IToDoRepository rep)
               {
                    repository = rep;
               }
                public ViewResult List()
                {
                    ToDoLibrary.ToDoTable model = new ToDoLibrary.ToDoTable();
                    ModelsViewList modelView = new ModelsViewList()
                    {
                        FromRepository = repository.FromRepository,
                        ModelDB = model
                    };
                   return View(modelView);
                }

           }`
       }

View:

@model ToDoUI.ModelsViews.ModelsViewList
    @{
        ViewBag.Title = "List";
    }

            pierwsza kolumna

            @using (Html.BeginForm("Edit", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {

                    @foreach (var property in ViewData.ModelMetadata.Properties)
                    {
                        switch (property.PropertyName)
                        {
                            case "ID":

                                break;
                            default:

                                    @(property.DisplayName ?? property.PropertyName)
                                    @if (property.PropertyName == "Description")
                                {
                                        @Html.TextArea(property.PropertyName, null, new { @class = "form-control", rows = 5 })
                                    }
                                    else
                                    {
                                        @Html.TextBox(property.PropertyName, null, new { @class = "form-control" })
                                    }
                                    @Html.ValidationMessage(property.PropertyName)

                                break;
                        }
                    }

                    <input type="submit" value="Zapisz" class="btn btn-primary" />
                    @Html.ActionLink("Anuluj i wróć do listy", "Index", null, new
               {
                   @class = "btn btn-default"
               })

            }

Body:
Your property name should be more like ModelDB.ID as your metadata is related to ToDoUI.ModelsViews.ModelsViewList which contains a property ModelDB, which is your ToDoTable object you are referencing.

Otherwise :

var metaData = ModelMetadataProviders.
     Current.GetMetadataForType(null, Model.ModelDB.GetType());

This will give you the metadata of your TodoTable you can then go through your properties. Anyway I am not sure it will help you to do something decent... As it doesn't look like it will :)


问:
WPF Application should start on the Left or Right side on any PC/Laptop
I want to open my c# application on any PC at the left corner of the screen always (Left or right side of the screen). For this what should I do? I did in this way;

```<code><Window x:Class="BPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:BPF"
       Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <TextBlock Text="{Binding Source={x:Static SystemParameters.FullPrimaryScreenHeight}}" />
        <TextBlock Text="{Binding Source={x:Static SystemParameters.FullPrimaryScreenWidth}}" />
        <TextBlock Text="{Binding Source={x:Static SystemParameters.PrimaryScreenHeight}}" />
        <TextBlock Text="{Binding Source={x:Static SystemParameters.PrimaryScreenWidth}}" />
    </StackPanel>
</Window>
</code>```

I can set the Height and Width parameters but the PCs screens are different. I want that on any PC the application should open with full height (Equal to the PC/Laptop screen) with width of 400.
I want to make application start on the right side of the laptop/PC screen (On each laptop/PC), Application's right side should be attached with the right side of the laptop screen.

答:
If I understand your requirements correctly you could set the Height property to SystemParameters.PrimaryScreenHeight and the Left property to 0:

```<code><Window x:Class="BPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:BPF"
       Title="MainWindow" Left="0" Height="{x:Static SystemParameters.PrimaryScreenHeight}" Width="400">
    <StackPanel>

    </StackPanel>
</Window>
</code>```

Body:
I want to open my c# application on any PC at the left corner of the screen always (Left or right side of the screen). For this what should I do? I did in this way;

<Window x:Class="BPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:BPF"
       Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <TextBlock Text="{Binding Source={x:Static SystemParameters.FullPrimaryScreenHeight}}" />
        <TextBlock Text="{Binding Source={x:Static SystemParameters.FullPrimaryScreenWidth}}" />
        <TextBlock Text="{Binding Source={x:Static SystemParameters.PrimaryScreenHeight}}" />
        <TextBlock Text="{Binding Source={x:Static SystemParameters.PrimaryScreenWidth}}" />
    </StackPanel>
</Window>

I can set the Height and Width parameters but the PCs screens are different. I want that on any PC the application should open with full height (Equal to the PC/Laptop screen) with width of 400.
I want to make application start on the right side of the laptop/PC screen (On each laptop/PC), Application's right side should be attached with the right side of the laptop screen.

Body:
If I understand your requirements correctly you could set the Height property to SystemParameters.PrimaryScreenHeight and the Left property to 0:

<Window x:Class="BPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:BPF"
       Title="MainWindow" Left="0" Height="{x:Static SystemParameters.PrimaryScreenHeight}" Width="400">
    <StackPanel>

    </StackPanel>
</Window>


问:
How to display attached properties in Property Browser of blend for silverlight?
I created couple of custom controls and their childresn correctly shows the attached properties in Property Browser for WPF, but in silverlight none of the attached properties appear in Property Brower.

How to add design time support for attached properties in silverlight?

答:
Henrik's definitely works for WPF in VS2015/Blend.  Just for reference, I'm adding some of the info from the linked article because so many times links to blogs die after a number of years.

AttachedPropertyBrowsableWhenAttributePresentAttribute

This attribute allows you to specify that your attached property show
  up in the Property Browser when the selected item has a given
  attribute applied to it.  If the attribute has a default value, that
  value also has to be different from the default value.

In the example above that passes in “MyCustomAttribute” as the
  attribute to look for, when CustomLabel below is selected in the
  designer, the Property Browser will show the ShowWhenCustomAttribute
  attached property however it will not when
  CustomLabelNoCustomAttribute is selected:

```<code>[MyCustomAttribute]
public class CustomLabel : Label
{
}

public class CustomLabelNoCustomAttribute : Label
{
}
</code>```

AttachedPropertyBrowsableForChildrenAttribute

This attribute indicates that the attached property should be available for the children of the given control.  There are two main flavors for this attribute.  One that includes descendants and one that does not. As you might expect including descendants refers to including all children or simply the direct children of the control.

```<code>[AttachedPropertyBrowsableForChildrenAttribute(IncludeDescendants=true)]
public static int GetShowForChildrenDeep(UIElement element)
{
    return (int)element.GetValue(ShowForChildrenDeepProperty);
}
</code>```

AttachedPropertyBrowsableForType

This attribute allows you to specify that your attached property show up when a given type or types derived from that type are selected in the designer.  The following sample would make your attached property show up when any Grid, derived Grid, Button or derived Button is selected.

```<code>[AttachedPropertyBrowsableForType(typeof(Grid))]
[AttachedPropertyBrowsableForType(typeof(Button))]
public static int GetShowForTypes(UIElement element)
{
    return (int)element.GetValue(ShowForTypesProperty);
}
</code>```

And here are the MSDN doc links:

https://msdn.microsoft.com/en-us/library/system.windows.attachedpropertybrowsableforchildrenattribute(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.windows.attachedpropertybrowsablefortypeattribute(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.windows.attachedpropertybrowsablewhenattributepresentattribute(v=vs.110).aspx

Body:
Henrik's definitely works for WPF in VS2015/Blend.  Just for reference, I'm adding some of the info from the linked article because so many times links to blogs die after a number of years.

AttachedPropertyBrowsableWhenAttributePresentAttribute

This attribute allows you to specify that your attached property show
  up in the Property Browser when the selected item has a given
  attribute applied to it.  If the attribute has a default value, that
  value also has to be different from the default value.

In the example above that passes in “MyCustomAttribute” as the
  attribute to look for, when CustomLabel below is selected in the
  designer, the Property Browser will show the ShowWhenCustomAttribute
  attached property however it will not when
  CustomLabelNoCustomAttribute is selected:

[MyCustomAttribute]
public class CustomLabel : Label
{
}

public class CustomLabelNoCustomAttribute : Label
{
}

AttachedPropertyBrowsableForChildrenAttribute

This attribute indicates that the attached property should be available for the children of the given control.  There are two main flavors for this attribute.  One that includes descendants and one that does not. As you might expect including descendants refers to including all children or simply the direct children of the control.

[AttachedPropertyBrowsableForChildrenAttribute(IncludeDescendants=true)]
public static int GetShowForChildrenDeep(UIElement element)
{
    return (int)element.GetValue(ShowForChildrenDeepProperty);
}

AttachedPropertyBrowsableForType

This attribute allows you to specify that your attached property show up when a given type or types derived from that type are selected in the designer.  The following sample would make your attached property show up when any Grid, derived Grid, Button or derived Button is selected.

[AttachedPropertyBrowsableForType(typeof(Grid))]
[AttachedPropertyBrowsableForType(typeof(Button))]
public static int GetShowForTypes(UIElement element)
{
    return (int)element.GetValue(ShowForTypesProperty);
}

And here are the MSDN doc links:

https://msdn.microsoft.com/en-us/library/system.windows.attachedpropertybrowsableforchildrenattribute(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.windows.attachedpropertybrowsablefortypeattribute(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.windows.attachedpropertybrowsablewhenattributepresentattribute(v=vs.110).aspx


问:
How to convert java project to Maven project or similar
I am currently creating an application for compiling multiple java projects in one go for programming assignments. As there are many different ways to submit java projects(e.g. as eclipse project, as netbeans project, as jar file) is there a plugin of something similar that you can easily import or use in a project that will convert a java project to a maven project so they can all be compiled in the same way rather then having to create functionality to allow the program to compile all different types of java projects?

If not to maven projects, is there another way to accomplish what i am trying to do?

答: If you are using Eclipse or Spring Tool Suite, right click on the project -> configure -> convert to maven project should convert your project to a maven project. You can check whether the project contains a pom.xml file. If yes then it is successfully converted.</p>