问:
How to create RowEncoder to map Tuple to Row?
I have a spark dataset where I have grouped and reduced my data according to my need. I need to get rid of the tuple and only retain Tuple2::_2.
I am trying to map the dataset as follows:

```<code>sparkSession.read()
            .parquet("s3://stuff/*")
            .groupByKey((MapFunction<Row, Long>) value -> {
                long stamp = value.getAs("timeStamp");
                return stamp / 600000;
            }, Encoders.LONG())
            .reduceGroups((ReduceFunction<Row>) (v1, v2) -> {
                int fare1 = v1.getAs("totalFare");
                int fare2 = v2.getAs("totalFare");
                return fare1 < fare2 ? v1 : v2;
            })
            .map((MapFunction<Tuple2<Long, Row>, Row>) Tuple2::_2, RowEncoder.apply(null))
</code>```

Can't figure out how to supply the schema to RowEncoder::apply.
I am reading a parquet file with this schema.

答:
So I ended up doing it this way. Basically read 1 element to get the required "ExpressionEncoder". I need the full "row" in the final output so could not go ahead with @Jacek's approach.</p>

```<code>System.out.println("Starting");
System.out.println(Arrays.toString(args));
Row sampleRow = sparkSession.read().parquet(readFrom).head();
ExpressionEncoder<Row> rowEncoder = RowEncoder.apply(sampleRow.schema());

//read all elements, process and write back the result
sparkSession.read()
            .parquet(readFrom)
            .groupByKey((MapFunction<Row, Long>) value -> {
                long stamp = value.getAs("timeStamp");
                return stamp / 600000;
            }, Encoders.LONG())
            .reduceGroups((ReduceFunction<Row>) (v1, v2) -> {
                int fare1 = v1.getAs("totalFare");
                int fare2 = v2.getAs("totalFare");
                return fare1 < fare2 ? v1 : v2;
            })
            .map((MapFunction<Tuple2<Long, Row>, Row>) Tuple2::_2, rowEncoder)
            .write()
            .parquet(writeTo);
System.out.println("Done !!!!");
</code>```

Title: How to create RowEncoder to map Tuple<A,Row> to Row?

Body:
I have a spark dataset where I have grouped and reduced my data according to my need. I need to get rid of the tuple and only retain Tuple2::_2.
I am trying to map the dataset as follows:

sparkSession.read()
            .parquet("s3://stuff/*")
            .groupByKey((MapFunction<Row, Long>) value -> {
                long stamp = value.getAs("timeStamp");
                return stamp / 600000;
            }, Encoders.LONG())
            .reduceGroups((ReduceFunction<Row>) (v1, v2) -> {
                int fare1 = v1.getAs("totalFare");
                int fare2 = v2.getAs("totalFare");
                return fare1 < fare2 ? v1 : v2;
            })
            .map((MapFunction<Tuple2<Long, Row>, Row>) Tuple2::_2, RowEncoder.apply(null))

Can't figure out how to supply the schema to RowEncoder::apply.
I am reading a parquet file with this schema.

Body:
So I ended up doing it this way. Basically read 1 element to get the required "ExpressionEncoder". I need the full "row" in the final output so could not go ahead with @Jacek's approach.

System.out.println("Starting");
System.out.println(Arrays.toString(args));
Row sampleRow = sparkSession.read().parquet(readFrom).head();
ExpressionEncoder<Row> rowEncoder = RowEncoder.apply(sampleRow.schema());

//read all elements, process and write back the result
sparkSession.read()
            .parquet(readFrom)
            .groupByKey((MapFunction<Row, Long>) value -> {
                long stamp = value.getAs("timeStamp");
                return stamp / 600000;
            }, Encoders.LONG())
            .reduceGroups((ReduceFunction<Row>) (v1, v2) -> {
                int fare1 = v1.getAs("totalFare");
                int fare2 = v2.getAs("totalFare");
                return fare1 < fare2 ? v1 : v2;
            })
            .map((MapFunction<Tuple2<Long, Row>, Row>) Tuple2::_2, rowEncoder)
            .write()
            .parquet(writeTo);
System.out.println("Done !!!!");


来源: stackexchange

问:
How to change the color of bottom navigation bar tap animation?
As you can see in this gif: https://gyazo.com/fc2f8e8ae9fbdae1b06d88336e76bc05

When an icon is tapped, an animation is played which is a green color. By default this color is gray. How can I change it to a different color?

答:
For ripples you can specify colorControlHighlight for API 21 or higher.

Add this line to your res/values-v21/styles.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppTheme" parent="...">
        ...
        <item name="colorControlHighlight">[desired color]</item>
        ...
    </style>
</resources>
</code>```

Replace [desired color] with your color, or a color resource, such as #009688 or @color/color_control_highlight. That'll default all ripple animations to the desired color.

ContentLicense: CC BY-SA 3.0

Body:
For ripples you can specify colorControlHighlight for API 21 or higher.

Add this line to your res/values-v21/styles.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppTheme" parent="...">
        ...
        <item name="colorControlHighlight">[desired color]</item>
        ...
    </style>
</resources>

Replace [desired color] with your color, or a color resource, such as #009688 or @color/color_control_highlight. That'll default all ripple animations to the desired color.


问:
how to get contact information to tableviewcell from all contacts?
i am trying to reproduce native phone app favorites tab in my app , i am succeed displaying all contacts
my code

```<code>-(IBAction)addFavorite {
    ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
    picker.peoplePickerDelegate = self;
    [self presentModalViewController:picker animated:YES];
    [picker release];
}
</code>```

how can i get full contact information of a contact into tableview cell, like in real app

and how can i get red color delete buttons to edit them ?

thanks in advance

regards

答:
For this you must use database(coredata or sqlite) and store contacts in the database .

when you want to display fetch all records and make 26 section for a-z alphabet then according to first alphabet categories them.

for delete button,

```<code>yourTable.editing=YES;
</code>```

this gives red - marks on left in table cell and on tapping these you get red delete button.
and you can write your deletion code in

```<code>- (void) tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
 forRowAtIndexPath:(NSIndexPath *)indexPath
</code>```

above method.

use this information with your logics

ContentLicense: CC BY-SA 2.5

Body:
i am trying to reproduce native phone app favorites tab in my app , i am succeed displaying all contacts
my code

-(IBAction)addFavorite {
    ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
    picker.peoplePickerDelegate = self;
    [self presentModalViewController:picker animated:YES];
    [picker release];
}

how can i get full contact information of a contact into tableview cell, like in real app

and how can i get red color delete buttons to edit them ?

thanks in advance

regards

Body:
For this you must use database(coredata or sqlite) and store contacts in the database .

when you want to display fetch all records and make 26 section for a-z alphabet then according to first alphabet categories them.

for delete button,

yourTable.editing=YES;

this gives red - marks on left in table cell and on tapping these you get red delete button.
and you can write your deletion code in

- (void) tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
 forRowAtIndexPath:(NSIndexPath *)indexPath

above method.

use this information with your logics


问:
Getting a list of authors with the numbers or counts of their respective posts in django
I'm trying to get author's list from my post model which has a field (author_name) related to the author model with a (ForeignKey).Using Post.objects.all() gets the list alright, but if I have a John Doe (Author) with 3 posts, I get John Doe listed three times with the respective post title. What I want is to list John once with numbers (count) of his posts so far. Thanks.

答:
Use an aggregation on a query on Author.

```<code>from django.db.models import Count
authors_with_counts = Author.objects.all().annotate(Count('post'))
</code>```

Now each author has a post__count attribute containing the number of posts for which they are the author.

Body:
Use an aggregation on a query on Author.

from django.db.models import Count
authors_with_counts = Author.objects.all().annotate(Count('post'))

Now each author has a post__count attribute containing the number of posts for which they are the author.


问:
How to compare two hash sets in java?
How can I compare two hash sets in java ? My first hash sets looks like below.

```<code>static Set<String> nounPhrases = new HashSet<>();
</code>```

Above hash set contains elements like this.

List of Noun Parse : [java, jsp, book]

2nd hash set

```<code>static Set<String> nounPhrases2 = new HashSet<>();
</code>```

List of Noun Parse : [web, php, java,book]

Note - I need to check if there are equal nouns in both sets. and if they have similar nouns then I need to do another task

答:
By the use of Java apache.commons.collections package we can implement </p>

```<code>package com.StackoverFlow;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.collections.CollectionUtils;
public class MainClass {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Set hs_1 = new HashSet();
        hs_1.add("A");
        hs_1.add("B");
        hs_1.add("C");
        hs_1.add("D");

        Set hs_2 = new HashSet();
        hs_2.add("A");
        hs_2.add("B");
        hs_2.add("C");
        hs_2.add("D");

        Collection result = CollectionUtils.subtract(hs_1, hs_2);
        System.out.println(result);
        if(result.isEmpty()){
            System.out.println("perform Task-->>Value maches  ");

        }else{
            System.out.println("perform Task-->>Value not maches  ");
        }

    }

}
</code>```

Title: How to compare two hash sets in java?

Body:
How can I compare two hash sets in java ? My first hash sets looks like below.

static Set<String> nounPhrases = new HashSet<>();

Above hash set contains elements like this.

List of Noun Parse : [java, jsp, book]

2nd hash set

static Set<String> nounPhrases2 = new HashSet<>();

List of Noun Parse : [web, php, java,book]

Note - I need to check if there are equal nouns in both sets. and if they have similar nouns then I need to do another task

Body:
By the use of Java apache.commons.collections package we can implement

package com.StackoverFlow;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.collections.CollectionUtils;
public class MainClass {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Set hs_1 = new HashSet();
        hs_1.add("A");
        hs_1.add("B");
        hs_1.add("C");
        hs_1.add("D");

        Set hs_2 = new HashSet();
        hs_2.add("A");
        hs_2.add("B");
        hs_2.add("C");
        hs_2.add("D");

        Collection result = CollectionUtils.subtract(hs_1, hs_2);
        System.out.println(result);
        if(result.isEmpty()){
            System.out.println("perform Task-->>Value maches  ");

        }else{
            System.out.println("perform Task-->>Value not maches  ");
        }

    }

}


问:
Firebase: What's the correct way to update values?
If my database structure is like this:

and I have this:

```<code>    ref = Database.database().reference().child(passUserID)

    ref?.child("wins").updateChildValues("wins": numerator)
</code>```

where numerator = (games played beforehand) + (games played after logging in), for the second statement it is giving me an error in the expression that I don't know how to fix.

Also if I try to do this instead:

```<code>ref?.child("wins").setValue(numerator)
</code>```

it messes up my data bad and gives a bad instruction error.

答:
The updateChildValues method takes a Dictionary. So you just need to call the method with a dictionary containing the key-value pairs you want to update, i.e.

```<code>ref = Database.database().reference().child(passUserID)

ref?.updateChildValues(["wins": numerator])
</code>```

For more on how to read/write data to firebase realtime database, refer to: https://firebase.google.com/docs/database/ios/read-and-write

Body:
If my database structure is like this:

and I have this:

    ref = Database.database().reference().child(passUserID)

    ref?.child("wins").updateChildValues("wins": numerator)

where numerator = (games played beforehand) + (games played after logging in), for the second statement it is giving me an error in the expression that I don't know how to fix.

Also if I try to do this instead:

ref?.child("wins").setValue(numerator)

it messes up my data bad and gives a bad instruction error.

Body:
The updateChildValues method takes a Dictionary. So you just need to call the method with a dictionary containing the key-value pairs you want to update, i.e.

ref = Database.database().reference().child(passUserID)

ref?.updateChildValues(["wins": numerator])

For more on how to read/write data to firebase realtime database, refer to: https://firebase.google.com/docs/database/ios/read-and-write


问:
How do I get a url parameter as nitial data into django's form wizard?
I have in my urls.py the following line:

```<code>url(r'^voter/(?P<voter_id>{id})/$'.format(id = UUID_PATTERN), views.VoterWizard.as_view(views.FORMS), name='voter_index'),
</code>```

In here I have a voter_id

Then in my views.py I have this class:

```<code>class VoterWizard(SessionWizardView):
    #initial_dict = {}

    def get_form_initial(self, step):
        initial = {}
        print(self, step)
        return self.initial_dict.get(step, initial)

    def get_template_names(self):
        return [TEMPLATES[self.steps.current]]

    def done(self, form_list, **kwargs):
        # do_something_with_the_form_data(form_list)
        return HttpResponseRedirect('voting_success.html')
</code>```

In general it works but I have no clue how I can populate some initial data to the form?

How can I read my voter_id from the url, perform a query and pass the result to the form?
I know I need to polulate the initial_dict or initial in the get_form_initial.

But how???

Many thanks!

答:
I finally found the solution to add the following function:</p>

```<code>    def get_context_data(self, form, **kwargs):
        context = super(VotingWizard, self).get_context_data(form, **kwargs)
        context.update({'voting': Voting.objects.get(uuid=self.kwargs['voting_id'])})
        return context
</code>```

Body:
I have in my urls.py the following line:

url(r'^voter/(?P<voter_id>{id})/$'.format(id = UUID_PATTERN), views.VoterWizard.as_view(views.FORMS), name='voter_index'),

In here I have a voter_id

Then in my views.py I have this class:

class VoterWizard(SessionWizardView):
    #initial_dict = {}

    def get_form_initial(self, step):
        initial = {}
        print(self, step)
        return self.initial_dict.get(step, initial)

    def get_template_names(self):
        return [TEMPLATES[self.steps.current]]

    def done(self, form_list, **kwargs):
        # do_something_with_the_form_data(form_list)
        return HttpResponseRedirect('voting_success.html')

In general it works but I have no clue how I can populate some initial data to the form?

How can I read my voter_id from the url, perform a query and pass the result to the form?
I know I need to polulate the initial_dict or initial in the get_form_initial.

But how???

Many thanks!

Body:
I finally found the solution to add the following function:

    def get_context_data(self, form, **kwargs):
        context = super(VotingWizard, self).get_context_data(form, **kwargs)
        context.update({'voting': Voting.objects.get(uuid=self.kwargs['voting_id'])})
        return context


问:
How can I specify the priority of a match pattern in a Regex?
I'm writing a function-parsing engine which uses regular expressions to separate the individual terms (defined as a constant or a variable followed (optionally) by an operator). It's working great, except when I have grouped terms within other grouped terms. Here's the code I'm using:

```<code>//This matches an opening delimiter
Regex openers = new Regex("[\\[\\{\\(]");

//This matches a closing delimiter
Regex closers = new Regex("[\\]\\}\\)]");

//This matches the name of a variable (\w+) or a constant numeric value (\d+(\.\d+)?)
Regex VariableOrConstant = new Regex("((\\d+(\\.\\d+)?)|\\w+)" + FunctionTerm.opRegex + "?");

//This matches the binary operators +, *, -, or /
Regex ops = new Regex("[\\*\\+\\-/]");

//This compound Regex finds a single variable or constant term (including a proceeding operator,
//if any) OR a group containing multiple terms (and their proceeding operators, if any)
//and a proceeding operator, if any.
//Matches that match this second pattern need to be added to the function as sub-functions,
//not as individual terms, to ensure the correct evalutation order with parentheses.
Regex splitter = new Regex(
openers +
"(" + VariableOrConstant + ")+" + closers + ops + "?" +
"|" +
"(" + VariableOrConstant + ")" + ops + "?");
</code>```

When "splitter" is matched against the string "4/(2*X*[2+1])", the matches' values are "4/", "2*", "X*", "2+", and "1", completely ignoring all of the delimiting parentheses and braces. I believe this is because the second half of the "splitter" Regex (the part after the "|") is being matched and overriding the other part of the pattern. This is bad- I want grouped expressions to take precedence over single terms. Does anyone know how I can do this? I looked into using positive/negative lookaheads and lookbehinds, but I'm honestly not sure how to use those, or what they're even for, for that matter, and I can't find any relevant examples... Thanks in advance.

答:
You didn't show us how you're applying the regex, so here's a demo I whipped up:

```<code>private static void ParseIt(string subject)
{
  Console.WriteLine("subject : {0}\n", subject);

  Regex openers = new Regex(@"[[{(]");
  Regex closers = new Regex(@"[]})]");
  Regex ops = new Regex(@"[*+/-]");
  Regex VariableOrConstant = new Regex(@"((\d+(\.\d+)?)|\w+)" + ops + "?");

  Regex splitter = new Regex(
    openers + @"(?<FIRST>" + VariableOrConstant + @")+" + closers + ops + @"?" +
    @"|" +
    @"(?<SECOND>" + VariableOrConstant + @")" + ops + @"?",
    RegexOptions.ExplicitCapture
  );

  foreach (Match m in splitter.Matches(subject))
  {
    foreach (string s in splitter.GetGroupNames())
    {
      Console.WriteLine("group {0,-8}: {1}", s, m.Groups[s]);
    }
    Console.WriteLine();
  }
}
</code>```

output:

```<code>subject : 4/(2*X*[2+1])

group 0       : 4/
group FIRST   :
group SECOND  : 4/

group 0       : 2*
group FIRST   :
group SECOND  : 2*

group 0       : X*
group FIRST   :
group SECOND  : X*

group 0       : [2+1]
group FIRST   : 1
group SECOND  :
</code>```

As you can see, the term [2+1] is matched by the first part of the regex, as you intended.  It can't do anything with the (, though, because the next bracketing character after that is another "opener" ([), and it's looking for a "closer".

You could use .NET's "balanced matching" feature to allow for grouped terms enclosed in other groups, but it's not worth the effort.  Regexes are not designed for parsing--in fact, parsing and regex matching are fundamentally different kinds of operation.  And this is a good example of the difference: a regex actively seeks out matches, skipping over anything it can't use (like the open-parenthesis in your example), but a parser has to examine every character (even if it's just to decide to ignore it).

About the demo: I tried to make the minimum functional changes necessary to get your code to work (which is why I didn't correct the error of putting the + outside the capturing group), but I also made several surface changes, and those represent active recommendations. To wit:

Always use verbatim string literals (@"...") when creating regexes in C# (I think the reason is obvious).

If you're using capturing groups, use named groups whenever possible, but don't use named groups and numbered groups in the same regex.  Named groups save you the hassle of keeping track of what's captured where, and the ExplicitCapture option saves you having to clutter up the regex with (?:...) wherever you need a non-capturing group.

Finally, that whole scheme of building a large regex from a bunch of smaller regexes has very limited usefulness IMO.  It's very difficult to keep track of the interactions between the parts, like which part's inside which group.  Another advantage of C#'s verbatim strings is that they're multiline, so you can take advantage of free-spacing mode (a.k.a. /x or COMMENTS mode):

```<code>  Regex r = new Regex(@"
    (?<GROUPED>
      [[{(]                  # opening bracket
      (                      # group containing:
        ((\d+(\.\d+)?)|\w+)     # number or variable
        [*+/-]?                 # and proceeding operator
      )+                     # ...one or more times
      []})]                  # closing bracket
      [*+/-]?                # and proceeding operator
    )
    |
    (?<UNGROUPED>
      ((\d+(\.\d+)?)|\w+)    # number or variable
      [*+/-]?                # and proceeding operator
    )
    ",
    RegexOptions.ExplicitCapture | RegexOptions.IgnorePatternWhitespace
  );
</code>```

This is not intended as a solution to your problem; as I said, that's not a job for regexes.  This is just a demonstration of some useful regex techniques.

Body:
I'm writing a function-parsing engine which uses regular expressions to separate the individual terms (defined as a constant or a variable followed (optionally) by an operator). It's working great, except when I have grouped terms within other grouped terms. Here's the code I'm using:

//This matches an opening delimiter
Regex openers = new Regex("[\\[\\{\\(]");

//This matches a closing delimiter
Regex closers = new Regex("[\\]\\}\\)]");

//This matches the name of a variable (\w+) or a constant numeric value (\d+(\.\d+)?)
Regex VariableOrConstant = new Regex("((\\d+(\\.\\d+)?)|\\w+)" + FunctionTerm.opRegex + "?");

//This matches the binary operators +, *, -, or /
Regex ops = new Regex("[\\*\\+\\-/]");

//This compound Regex finds a single variable or constant term (including a proceeding operator,
//if any) OR a group containing multiple terms (and their proceeding operators, if any)
//and a proceeding operator, if any.
//Matches that match this second pattern need to be added to the function as sub-functions,
//not as individual terms, to ensure the correct evalutation order with parentheses.
Regex splitter = new Regex(
openers +
"(" + VariableOrConstant + ")+" + closers + ops + "?" +
"|" +
"(" + VariableOrConstant + ")" + ops + "?");

When "splitter" is matched against the string "4/(2*X*[2+1])", the matches' values are "4/", "2*", "X*", "2+", and "1", completely ignoring all of the delimiting parentheses and braces. I believe this is because the second half of the "splitter" Regex (the part after the "|") is being matched and overriding the other part of the pattern. This is bad- I want grouped expressions to take precedence over single terms. Does anyone know how I can do this? I looked into using positive/negative lookaheads and lookbehinds, but I'm honestly not sure how to use those, or what they're even for, for that matter, and I can't find any relevant examples... Thanks in advance.

Body:
You didn't show us how you're applying the regex, so here's a demo I whipped up:

private static void ParseIt(string subject)
{
  Console.WriteLine("subject : {0}\n", subject);

  Regex openers = new Regex(@"[[{(]");
  Regex closers = new Regex(@"[]})]");
  Regex ops = new Regex(@"[*+/-]");
  Regex VariableOrConstant = new Regex(@"((\d+(\.\d+)?)|\w+)" + ops + "?");

  Regex splitter = new Regex(
    openers + @"(?<FIRST>" + VariableOrConstant + @")+" + closers + ops + @"?" +
    @"|" +
    @"(?<SECOND>" + VariableOrConstant + @")" + ops + @"?",
    RegexOptions.ExplicitCapture
  );

  foreach (Match m in splitter.Matches(subject))
  {
    foreach (string s in splitter.GetGroupNames())
    {
      Console.WriteLine("group {0,-8}: {1}", s, m.Groups[s]);
    }
    Console.WriteLine();
  }
}

output:

subject : 4/(2*X*[2+1])

group 0       : 4/
group FIRST   :
group SECOND  : 4/

group 0       : 2*
group FIRST   :
group SECOND  : 2*

group 0       : X*
group FIRST   :
group SECOND  : X*

group 0       : [2+1]
group FIRST   : 1
group SECOND  :

As you can see, the term [2+1] is matched by the first part of the regex, as you intended.  It can't do anything with the (, though, because the next bracketing character after that is another "opener" ([), and it's looking for a "closer".

You could use .NET's "balanced matching" feature to allow for grouped terms enclosed in other groups, but it's not worth the effort.  Regexes are not designed for parsing--in fact, parsing and regex matching are fundamentally different kinds of operation.  And this is a good example of the difference: a regex actively seeks out matches, skipping over anything it can't use (like the open-parenthesis in your example), but a parser has to examine every character (even if it's just to decide to ignore it).

About the demo: I tried to make the minimum functional changes necessary to get your code to work (which is why I didn't correct the error of putting the + outside the capturing group), but I also made several surface changes, and those represent active recommendations. To wit:

Always use verbatim string literals (@"...") when creating regexes in C# (I think the reason is obvious).

If you're using capturing groups, use named groups whenever possible, but don't use named groups and numbered groups in the same regex.  Named groups save you the hassle of keeping track of what's captured where, and the ExplicitCapture option saves you having to clutter up the regex with (?:...) wherever you need a non-capturing group.

Finally, that whole scheme of building a large regex from a bunch of smaller regexes has very limited usefulness IMO.  It's very difficult to keep track of the interactions between the parts, like which part's inside which group.  Another advantage of C#'s verbatim strings is that they're multiline, so you can take advantage of free-spacing mode (a.k.a. /x or COMMENTS mode):

  Regex r = new Regex(@"
    (?<GROUPED>
      [[{(]                  # opening bracket
      (                      # group containing:
        ((\d+(\.\d+)?)|\w+)     # number or variable
        [*+/-]?                 # and proceeding operator
      )+                     # ...one or more times
      []})]                  # closing bracket
      [*+/-]?                # and proceeding operator
    )
    |
    (?<UNGROUPED>
      ((\d+(\.\d+)?)|\w+)    # number or variable
      [*+/-]?                # and proceeding operator
    )
    ",
    RegexOptions.ExplicitCapture | RegexOptions.IgnorePatternWhitespace
  );

This is not intended as a solution to your problem; as I said, that's not a job for regexes.  This is just a demonstration of some useful regex techniques.


问:
Media instagram endpoint not working - Invalid media id
I'm trying to use https://www.instagram.com/developer/endpoints/media/, but for every media id that I use I get always the same result :

```<code>{
    "meta": {
        "error_type": "APINotFoundError",
        "code": 400,
        "error_message": "invalid media id"
    }
}
</code>```

I'm getting the media id from another api service, for example:

https://api.instagram.com/oembed?url=http://instagr.am/p/fA9uwTtkSN/.

So in the response we can see ``"media_id":"558717847597368461_9538472"`, then I use that id in media endpoint and i get "invalid media id".

I was wondering if the api is having some problems or maybe I missing something.

答: You are maybe getting that error because the user that posted the media is a private user. That was my case.

Body:
I'm trying to use https://www.instagram.com/developer/endpoints/media/, but for every media id that I use I get always the same result :

{
    "meta": {
        "error_type": "APINotFoundError",
        "code": 400,
        "error_message": "invalid media id"
    }
}

I'm getting the media id from another api service, for example:

https://api.instagram.com/oembed?url=http://instagr.am/p/fA9uwTtkSN/.

So in the response we can see ``"media_id":"558717847597368461_9538472"`, then I use that id in media endpoint and i get "invalid media id".

I was wondering if the api is having some problems or maybe I missing something.


问:
Laravel select field cannot be null
I'm trying to store a form into my database but this is the error i get:

```<code>Integrity constraint violation: 1048 Column 'rent_product' cannot be null
</code>```

Why is this?

I'm trying to do this in an array because i have an option to show more select fields (to add more products to rent).

This is the HTML:

```<code><div class="col-lg-10">
 <label for="sel1">Selecteer product:</label>
   <select class="form-control" id="sel1" style="height: 40px;">
     @foreach ($pr as $prr)
      <option name="product_name[]" value="{{$prr->product_name}}">{{$prr->product_name}}</option>
     @endforeach
   </select>
</div>
</code>```

Function:

```<code>public function create_order($id) {

    $customer = Customer::find($id);

    $customer->rent_product = Request::get('product_name');
    $customer->rent_product_count = Request::get('product_count');
    $customer->update();

}
</code>```

Thanks in advance.

答:
I think You should use name attribute in the select tag. code below

```<code><div class="col-lg-10">
 <label for="sel1">Selecteer product:</label>
   <select name="product_name" class="form-control" id="sel1" style="height: 40px;">
     @foreach ($pr as $prr)
      <option value="{{$prr->product_name}}">{{$prr->product_name}}</option>
     @endforeach
   </select>
</div>
</code>```

and then

```<code>$customer = Customer::find($id);
$customer->rent_product = Request::get('product_name');
$customer->rent_product_count = Request::get('product_count');
$customer->save();
</code>```

Title: Laravel select field cannot be null

Body:
I'm trying to store a form into my database but this is the error i get:

Integrity constraint violation: 1048 Column 'rent_product' cannot be null

Why is this?

I'm trying to do this in an array because i have an option to show more select fields (to add more products to rent).

This is the HTML:

 Selecteer product:
   <select class="form-control" id="sel1" style="height: 40px;">
     @foreach ($pr as $prr)
      <option name="product_name[]" value="{{$prr->product_name}}">{{$prr->product_name}}</option>
     @endforeach
   </select>

Function:

public function create_order($id) {

    $customer = Customer::find($id);

    $customer->rent_product = Request::get('product_name');
    $customer->rent_product_count = Request::get('product_count');
    $customer->update();

}

Thanks in advance.

Body:
I think You should use name attribute in the select tag. code below

<div class="col-lg-10">
 <label for="sel1">Selecteer product:</label>
   <select name="product_name" class="form-control" id="sel1" style="height: 40px;">
     @foreach ($pr as $prr)
      <option value="{{$prr->product_name}}">{{$prr->product_name}}</option>
     @endforeach
   </select>
</div>

and then

$customer = Customer::find($id);
$customer->rent_product = Request::get('product_name');
$customer->rent_product_count = Request::get('product_count');
$customer->save();


问:
How to implement an API key on PHP software?
I am distributing a PHP created plugin like a Wordpress plugin but I want to implement an API key for it and users would need to enter an API key to unlock it for it to work.

How can that be done?  And yes I already know it could be easily bypassed since PHP is not compiled but atleast it will deter some people with no PHP knowledge.

Thanks..

答:
I don't think you understand what an API key is.

An API key is a key that allows you or a script to access and interact with an API or an online service.

What you seem to be describing is some sort of license key, that would prevent a user from operating your script without perhaps payment or registration.

While an API key often does require payment or registration, the two are really not the same thing.

API keys are typically put into place to track the use, and prevent abuse of online services and data.

It appears that in your case you are simply trying to restrict access to your script.

Unless your script has a fundamental dependency on a remote data source, this method will not work because any user with any distant knowledge of PHP will just remove the code that performs the validation.

With PHP, the same applies to a license key. User's will find a way to circumvent it, unless they need it for the script to perform.

The validation must be performed remotely, and there must be some incentive to leave it in-tact (access to remote data being the obvious one).


问:
Calculating maximum length of AES encrypted message
I'm using this function to encrypt data using openssl AES 256 CBC:

```<code>int encryptAES(unsigned char *plaintext, int plaintext_len, unsigned char *key,
  unsigned char *iv, unsigned char *ciphertext)
{
  EVP_CIPHER_CTX *ctx;

  int len;

  int ciphertext_len;

  /* Create and initialise the context */
  if(!(ctx = EVP_CIPHER_CTX_new())) return handleErrors();

  /* Initialise the encryption operation. IMPORTANT - ensure you use a key
   * and IV size appropriate for your cipher
   * In this example we are using 256 bit AES (i.e. a 256 bit key). The
   * IV size for *most* modes is the same as the block size. For AES this
   * is 128 bits */
  if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
    return handleErrors();

  /* Provide the message to be encrypted, and obtain the encrypted output.
   * EVP_EncryptUpdate can be called multiple times if necessary
   */

  if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
    return handleErrors();
  ciphertext_len = len;

  /* Finalise the encryption. Further ciphertext bytes may be written at
   * this stage.
   */

  if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) return handleErrors();
  ciphertext_len += len;

  /* Clean up */
  EVP_CIPHER_CTX_free(ctx);

  return ciphertext_len;
}
</code>```

I want to provide to this function a fixed sized buffer ciphertext, How can I calculate the maximum possible length of the encrypted message (ciphertext)

Thanks.

答:
Assuming PKCS#7 padding, which is the default for OpenSSL ECB and CBC mode, the encrypted length will be:

```<code>plaintext_len + block_size - (plaintext_len % block_size)
</code>```

where

```<code>block_size = 16
</code>```

for AES. The end result is always a multiple of block_size.

Body:
I'm using this function to encrypt data using openssl AES 256 CBC:

int encryptAES(unsigned char *plaintext, int plaintext_len, unsigned char *key,
  unsigned char *iv, unsigned char *ciphertext)
{
  EVP_CIPHER_CTX *ctx;

  int len;

  int ciphertext_len;

  /* Create and initialise the context */
  if(!(ctx = EVP_CIPHER_CTX_new())) return handleErrors();

  /* Initialise the encryption operation. IMPORTANT - ensure you use a key
   * and IV size appropriate for your cipher
   * In this example we are using 256 bit AES (i.e. a 256 bit key). The
   * IV size for *most* modes is the same as the block size. For AES this
   * is 128 bits */
  if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
    return handleErrors();

  /* Provide the message to be encrypted, and obtain the encrypted output.
   * EVP_EncryptUpdate can be called multiple times if necessary
   */

  if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
    return handleErrors();
  ciphertext_len = len;

  /* Finalise the encryption. Further ciphertext bytes may be written at
   * this stage.
   */

  if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) return handleErrors();
  ciphertext_len += len;

  /* Clean up */
  EVP_CIPHER_CTX_free(ctx);

  return ciphertext_len;
}

I want to provide to this function a fixed sized buffer ciphertext, How can I calculate the maximum possible length of the encrypted message (ciphertext)

Thanks.

Body:
Assuming PKCS#7 padding, which is the default for OpenSSL ECB and CBC mode, the encrypted length will be:

plaintext_len + block_size - (plaintext_len % block_size)

where

block_size = 16

for AES. The end result is always a multiple of block_size.


问:
How to call Stored Procedure with Eloquent (Laravel)?
There is no standard procedure mentioned in documentation that how to call a stored procedure in MYSQL in laravel with Eloquent syntax.

I mean is there any way to call stored procedure in mysql with help of eloquent syntax like

```<code>$result = StoredProcedures::my_custom_procedure(param1, param2);
return view('welcome')->with('result',$result);
</code>```

Is there any way to call and fetch results from stored procedures with pure eloquent syntax(purely eloquent way).

Thanks. Small examples are highly encouraged .

答:
As everyone has mentioned, you can't call a stored procedure in Laravel with Eloquent syntax. You can transfer the result of your query to a collection which will give you all of the collection functionality.</p>

```<code>$queryResult = DB::select('call my_custom_procedure(?, ?)', [1,2]);

$result = collect($queryResult);

return view('welcome')->with('result',$result);
</code>```

Body:
There is no standard procedure mentioned in documentation that how to call a stored procedure in MYSQL in laravel with Eloquent syntax.

I mean is there any way to call stored procedure in mysql with help of eloquent syntax like

$result = StoredProcedures::my_custom_procedure(param1, param2);
return view('welcome')->with('result',$result);

Is there any way to call and fetch results from stored procedures with pure eloquent syntax(purely eloquent way).

Thanks. Small examples are highly encouraged .

Body:
As everyone has mentioned, you can't call a stored procedure in Laravel with Eloquent syntax. You can transfer the result of your query to a collection which will give you all of the collection functionality.

$queryResult = DB::select('call my_custom_procedure(?, ?)', [1,2]);

$result = collect($queryResult);

return view('welcome')->with('result',$result);


问:
Colour-categorised density scatterplots
I need to admit that I am pretty new to R and programming in general.

I am looking to create a density scatterplot. I have around 350 data points and only 27 unique x,y values. I would like it take the shape of what smoothScatter does with the only difference being that I would like the data points to take the colour which would reflect the absolute density (like, 1-5 green; 2-10, blue; 11-20, red; etc.), not how intense the colour is. Essentially, sharp and coloured points is what I am after

This is what it looks like before colouring:

Can you please help me figure out how to do this?

答:
Are you after something like this?

```<code>set.seed(357)
xy <- data.frame(x = runif(37), y = runif(37))
xy <- round(xy, 1)
rp <- sample(1:30, size = nrow(xy), replace = TRUE)
xy <- xy[rp, ]
xy$colors <- cut(rp, 3)

library(ggplot2)

ggplot(xy, aes(x = x, y = y, color = colors)) +
  theme_bw() +
  geom_point()
</code>```

```<code>ggplot(xy, aes(x = x, y = y, color = colors)) +
  theme_bw() +
  geom_point()+
  geom_density_2d(h = 0.25)
</code>```

Title: Colour-categorised density scatterplots

Body:
Are you after something like this?

set.seed(357)
xy <- data.frame(x = runif(37), y = runif(37))
xy <- round(xy, 1)
rp <- sample(1:30, size = nrow(xy), replace = TRUE)
xy <- xy[rp, ]
xy$colors <- cut(rp, 3)

library(ggplot2)

ggplot(xy, aes(x = x, y = y, color = colors)) +
  theme_bw() +
  geom_point()

ggplot(xy, aes(x = x, y = y, color = colors)) +
  theme_bw() +
  geom_point()+
  geom_density_2d(h = 0.25)


问:
Using variables in the values-form in multiple-value-bind
I am trying to implement a function read-from-whole-string in lisp, where it uses the inbuilt function read-from-string.

About read-from-string

read-from-string is used to read an object from a string which can be specified using the keywords :start,:end etc. It returns two values, the object and the position of the next element, which wasn't read. I plan to use this value.

The plan

The plan is to use the second value returned from the read-from-string function, again on itself to insert the value of the keyword :start. But the problem comes with the function multiple-value-bind. We can't:

Initialize a variable in multiple-value-bind.

Use a variable just defined into the values-form.

To be specific, I want to:

```<code>(multiple-value-bind (x (y 0))
         (read-from-string str :Start y)
         y)
</code>```

Any other clean method is appreciated.

答:
Other method for implementing the function read-from-whole-string , which might not be too clean is:

```<code>(defun read-from-whole-string (str)
  (loop
    collect (multiple-value-bind (x y)
                (read-from-string str)
              (setf str (delete-if #'atom str :start 0 :end (if (= (length str) y)
                                                                y
                                                               (1- y))))
              x)
    until (zerop (length str))
        ))
</code>```

Body:
I am trying to implement a function read-from-whole-string in lisp, where it uses the inbuilt function read-from-string.

About read-from-string

read-from-string is used to read an object from a string which can be specified using the keywords :start,:end etc. It returns two values, the object and the position of the next element, which wasn't read. I plan to use this value.

The plan

The plan is to use the second value returned from the read-from-string function, again on itself to insert the value of the keyword :start. But the problem comes with the function multiple-value-bind. We can't:

Initialize a variable in multiple-value-bind.

Use a variable just defined into the values-form.

To be specific, I want to:

(multiple-value-bind (x (y 0))
         (read-from-string str :Start y)
         y)

Any other clean method is appreciated.

Body:
Other method for implementing the function read-from-whole-string , which might not be too clean is:

(defun read-from-whole-string (str)
  (loop
    collect (multiple-value-bind (x y)
                (read-from-string str)
              (setf str (delete-if #'atom str :start 0 :end (if (= (length str) y)
                                                                y
                                                               (1- y))))
              x)
    until (zerop (length str))
        ))


问:
Undefined local variable or method `git_source' for Gemfile
Cloned a rails application from github, works on the original dev's machine using the same version of rails (5.0.1).

Any rails command run from the app directory fails with:

```<code>Undefined local variable or method `git_source' for Gemfile
</code>```

Relevant Gemfile section:

```<code>git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end
</code>```

答:
I got the same problem.
$ gem update bundler
didn't help.
I installed one of missing gem via console, then used RubyMine Gem Manager to install rest of them (or sudo bundle install). It worked for me. </p>

Body:
Cloned a rails application from github, works on the original dev's machine using the same version of rails (5.0.1).

Any rails command run from the app directory fails with:

Undefined local variable or method `git_source' for Gemfile

Relevant Gemfile section:

git_source(:github) do |repo_name|
  repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/")
  "https://github.com/#{repo_name}.git"
end


问:
How should I handle importing third-party libraries within my setup.py script?
I'm developing a Python application and in the process of branching off a release. I've got a PyPI server set up on a company server and I've copied a source distribution of my package onto it.

I checked that the package was being hosted on the server and then tried installing it on my local development machine. I ended up with this output:

$ pip3 install --trusted-host 172.16.1.92 -i http://172.16.1.92:5001/simple/ <my-package>
Collecting <my-package>
  Downloading http://172.16.1.92:5001/packages/<my-package>-0.2.0.zip
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\<me>\AppData\Local\Temp\pip-build-ubb3jkpr\<my-package>\setup.py", line 9, in <module>
        import appdirs
    ModuleNotFoundError: No module named 'appdirs'

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\<me>\AppData\Local\Temp\pip-build-ubb3jkpr\<my-package>\
```

<p>The reason is that I'm trying to import a third-party library <code>appdirs</code> in my <code>setup.py</code>, which is necessary for me to compute the <code>data_files</code> argument to <code>setup()</code>:</p>

<pre class="lang-py prettyprint-override"><code>try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

import os
from collections import defaultdict

import appdirs
from <my-package>.version import __version__ as <my-package>_version

APP_NAME = '<my-app>'
APP_AUTHOR = '<company>'
SYSTEM_COMPONENT_PLUGIN_DIR = os.path.join(appdirs.user_data_dir(APP_NAME, APP_AUTHOR), 'components')

# ...

setup(
    # ...
    data_files=component_files,
)
</code>```

However, I don't have appdirs installed on my local dev machine and I don't expect the end users to have it either.

Is it acceptable to rely on third-party libraries like this in setup.py, and if so what is the recommended approach to using them? Is there a way I can ensure appdirs gets installed before it's imported in setup.py, or should I just document that appdirs is a required package to install my package?

答: You can mention install_requires with the dependencies list. Please check the python packaging guide here. Also you can provide a requirements.txt file so that it can be run at once using "pip install -r"</p>

Body:
I'm developing a Python application and in the process of branching off a release. I've got a PyPI server set up on a company server and I've copied a source distribution of my package onto it.

I checked that the package was being hosted on the server and then tried installing it on my local development machine. I ended up with this output:

$ pip3 install --trusted-host 172.16.1.92 -i http://172.16.1.92:5001/simple/ <my-package>
Collecting <my-package>
  Downloading http://172.16.1.92:5001/packages/<my-package>-0.2.0.zip
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\<me>\AppData\Local\Temp\pip-build-ubb3jkpr\<my-package>\setup.py", line 9, in <module>
        import appdirs
    ModuleNotFoundError: No module named 'appdirs'

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\<me>\AppData\Local\Temp\pip-build-ubb3jkpr\<my-package>\

The reason is that I'm trying to import a third-party library appdirs in my setup.py, which is necessary for me to compute the data_files argument to setup():

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

import os
from collections import defaultdict

import appdirs
from <my-package>.version import __version__ as <my-package>_version

APP_NAME = '<my-app>'
APP_AUTHOR = '<company>'
SYSTEM_COMPONENT_PLUGIN_DIR = os.path.join(appdirs.user_data_dir(APP_NAME, APP_AUTHOR), 'components')

# ...

setup(
    # ...
    data_files=component_files,
)

However, I don't have appdirs installed on my local dev machine and I don't expect the end users to have it either.

Is it acceptable to rely on third-party libraries like this in setup.py, and if so what is the recommended approach to using them? Is there a way I can ensure appdirs gets installed before it's imported in setup.py, or should I just document that appdirs is a required package to install my package?


问:
Django - Name Error when views call model's object
I'm making a simple python3 django server for a mobile application.
But in views.py, I got errors while testing.

This is one of functions.

```<code>from django.shortcuts import render
from django.http import HttpResponse
from django.http import JsonResponse
from bns_info.models import Character, Dungeon, Tactics, Team
import json
import hashlib
import time

def login(request):
    if request.method == 'POST':
        data = request.body.decode("utf-8")
        receivedData = json.loads(data)

        receivedName = receivedData['characterName']
        character = Character.objects.get(name=receivedName)
        team = Team.objects.filter(teamNum=character['teamNum'])
        teamDungeonType = Dungeon.objects.filter(dType=team['dType'])

        retValue = {character['teamNum']:teamDungeonType['dType']}
        return JsonResponse(retValue, safe=False)

    else:
        return HttpResponse('Request is not POST method.')
</code>```

and  this is my model design.

```<code>class Character(models.Model):
    name = models.TextField(blank=True, null=True)
    teamNum = models.IntegerField(db_column='teamNum', blank=True, null=True)  # Field name made lowercase.
    id = models.IntegerField(blank=True, primary_key=True)

    class Meta:
        db_table = 'Character'
</code>```

And I got few errors, this is the message.

Internal Server Error: /login/
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/Dalek_Sec/BnS_Info/Server/appServer/bns_info/views.py", line 18, in login
    character = Character.objects.filter(name=receivedName)
NameError: name 'Character' is not defined
[04/Jun/2017 21:11:54] "POST /login/ HTTP/1.1" 500 60733

I thought It's enough that I defined 'Character' in models but django says Character is not defined. What's the problem???

答:
Edit your view like this,</p>

```<code>def login(request):
    if request.method == 'POST':
        data = request.body.decode("utf-8")
        receivedData = json.loads(data)
        receivedName = receivedData['characterName']
        character = Character.objects.get(name=receivedName)
        team = Team.objects.get(teamNum=character.teamNum)
        teamDungeonType = Dungeon.objects.get(dType=team.dType)
        retValue = {character.teamNum : teamDungeonType.dType}
        return JsonResponse(retValue, safe=False)
    else:
        return HttpResponse('Request is not POST method.')
</code>```

Body:
I'm making a simple python3 django server for a mobile application.
But in views.py, I got errors while testing.

This is one of functions.

from django.shortcuts import render
from django.http import HttpResponse
from django.http import JsonResponse
from bns_info.models import Character, Dungeon, Tactics, Team
import json
import hashlib
import time

def login(request):
    if request.method == 'POST':
        data = request.body.decode("utf-8")
        receivedData = json.loads(data)

        receivedName = receivedData['characterName']
        character = Character.objects.get(name=receivedName)
        team = Team.objects.filter(teamNum=character['teamNum'])
        teamDungeonType = Dungeon.objects.filter(dType=team['dType'])

        retValue = {character['teamNum']:teamDungeonType['dType']}
        return JsonResponse(retValue, safe=False)

    else:
        return HttpResponse('Request is not POST method.')

and  this is my model design.

class Character(models.Model):
    name = models.TextField(blank=True, null=True)
    teamNum = models.IntegerField(db_column='teamNum', blank=True, null=True)  # Field name made lowercase.
    id = models.IntegerField(blank=True, primary_key=True)

    class Meta:
        db_table = 'Character'

And I got few errors, this is the message.

Internal Server Error: /login/
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/Dalek_Sec/BnS_Info/Server/appServer/bns_info/views.py", line 18, in login
    character = Character.objects.filter(name=receivedName)
NameError: name 'Character' is not defined
[04/Jun/2017 21:11:54] "POST /login/ HTTP/1.1" 500 60733

I thought It's enough that I defined 'Character' in models but django says Character is not defined. What's the problem???

Body:
Edit your view like this,

def login(request):
    if request.method == 'POST':
        data = request.body.decode("utf-8")
        receivedData = json.loads(data)
        receivedName = receivedData['characterName']
        character = Character.objects.get(name=receivedName)
        team = Team.objects.get(teamNum=character.teamNum)
        teamDungeonType = Dungeon.objects.get(dType=team.dType)
        retValue = {character.teamNum : teamDungeonType.dType}
        return JsonResponse(retValue, safe=False)
    else:
        return HttpResponse('Request is not POST method.')


问:
Only print when run as script?
Is there a better way to only print when run as a script, when __name__ == '__main__' ?

I have some scripts that I also import and use parts of.

Something like the below will work but is ugly, and would have to be defined in each script separately:

```<code>def printif(s):
    if globals()['__name__'] == '__main__':
        print (s)
    return
</code>```

I looked briefly at some of python's logging libraries but would prefer a two lighter solution...

edit:

I ended up doing something like this:

```<code># mylog.py
import sys
import logging

log = logging.getLogger()

#default logging level
log.setLevel(logging.WARNING)

log.addHandler(logging.StreamHandler(sys.stdout))
</code>```

And from the script:

```<code>import log from mylog

...
log.info(...)
log.warning(...)
...

if __name__ == '__main__':
    #override when script is run..
    log.setLevel(logger.INFO)
</code>```

This scheme has minimal code duplication, per script log levels, and a project-wide default level...which is exactly what I wanted.

答:
Using a logging library is really not that heavyweight:

```<code>import logging

log = logging.getLogger('myscript')

def dostuff(...):
    ....
    log.info('message!')
    ...

if __name__ == '__main__':
    import sys
    log.setLevel(logging.INFO)
    log.addHandler(logging.StreamHandler(sys.stdout))
    ...
</code>```

One wart is the "WARNING: no handlers found for myscript" message  that logging prints by default if you import this module (rather than run it as a script), and call your function without setting up logging.  It'll be gone in Python 3.2.  For Python 2.7, you can shut it off by adding

```<code>log.addHandler(logging.NullHandler())
</code>```

at the top, and for older versions you'd have to define a NullHandler class like this:

```<code>class NullHandler(logging.Handler):
    def emit(self, record):
        pass
</code>```

Looking back at all this, I say: go with Gerrat's suggestion.  I'll leave mine here, for completeness.

Title: Only print when run as script?

Body:
Is there a better way to only print when run as a script, when __name__ == '__main__' ?

I have some scripts that I also import and use parts of.

Something like the below will work but is ugly, and would have to be defined in each script separately:

def printif(s):
    if globals()['__name__'] == '__main__':
        print (s)
    return

I looked briefly at some of python's logging libraries but would prefer a two lighter solution...

edit:

I ended up doing something like this:

# mylog.py
import sys
import logging

log = logging.getLogger()

#default logging level
log.setLevel(logging.WARNING)

log.addHandler(logging.StreamHandler(sys.stdout))

And from the script:

import log from mylog

...
log.info(...)
log.warning(...)
...

if __name__ == '__main__':
    #override when script is run..
    log.setLevel(logger.INFO)

This scheme has minimal code duplication, per script log levels, and a project-wide default level...which is exactly what I wanted.

Body:
Using a logging library is really not that heavyweight:

import logging

log = logging.getLogger('myscript')

def dostuff(...):
    ....
    log.info('message!')
    ...

if __name__ == '__main__':
    import sys
    log.setLevel(logging.INFO)
    log.addHandler(logging.StreamHandler(sys.stdout))
    ...

One wart is the "WARNING: no handlers found for myscript" message  that logging prints by default if you import this module (rather than run it as a script), and call your function without setting up logging.  It'll be gone in Python 3.2.  For Python 2.7, you can shut it off by adding

log.addHandler(logging.NullHandler())

at the top, and for older versions you'd have to define a NullHandler class like this:

class NullHandler(logging.Handler):
    def emit(self, record):
        pass

Looking back at all this, I say: go with Gerrat's suggestion.  I'll leave mine here, for completeness.


问:
Android Studio: I can not run/debug my project after cloning it from my repository
My HD died two days ago, luckily my android app is versioned on Bitbucket. So I got an SSD, reinstalled Windows 10 and the latest Android Studio. With Android Studio installed, I've cloned the project of my app through the 'Checkout project from Version Control' option in the welcome window of Android Studio. The project seems to have been cloned correctly, bringing all my source codes.

However, Android Studio was not able to create a Run / Debug configuration automatically. So, I tried to create a configuration by my own by clicking Edit Configurations> Add New Configuration (green cross) and choosing the option Android App. When choosing this option, the error 'Error: Module not specified' is showing below in the window, like Shows the image I attached.

This is the first time I have to clone my Android project from my repository and unfortunately I am not sure how to handle it. Can anybody help me?

答:
Looks like you are missing the settings.gradle file. Create a new one in the project root folder with the following content:

```<code>include ':app'
include ':BaseGameUtils'
include ':squarecamera'
include ':volley'
</code>```

I just guessed your modules, fix them in case they are not correct.

Body:
Looks like you are missing the settings.gradle file. Create a new one in the project root folder with the following content:

include ':app'
include ':BaseGameUtils'
include ':squarecamera'
include ':volley'

I just guessed your modules, fix them in case they are not correct.


问:
pprint with custom float formats
I have a nested dictionary structure with tuple keys. Here's what an entry looks like when I pretty-print the dictionary using pprint:

```<code>...
 ('A', 'B'): {'C': 0.14285714285714285,
              'D': 0.14285714285714285,
              'E': 0.14285714285714285,
              'F': 0.14285714285714285,
              'G': 0.14285714285714285,
              'H': 0.14285714285714285,
              'I': 0.14285714285714285},
...
</code>```

It's pretty nifty, but I'd like to customize it further by cutting down some extra digits from the floats. I was thinking that it'd be possible to achieve by subclassing pprint.PrettyPrint but I don't know how that would be done.

Thanks.

答:
As you said, you can achieve this by subclassing PrettyPrinter and overwriting the format method. Note that the output is not only the formatted string, but also some flags.

Once you're at it, you could also generalize this and pass a dictionary with the desired formats for different types into the constructor:

```<code>class FormatPrinter(pprint.PrettyPrinter):

    def __init__(self, formats):
        super(FormatPrinter, self).__init__()
        self.formats = formats

    def format(self, obj, ctx, maxlvl, lvl):
        if type(obj) in self.formats:
            return self.formats[type(obj)] % obj, 1, 0
        return pprint.PrettyPrinter.format(self, obj, ctx, maxlvl, lvl)
</code>```

Example:

```<code>>>> d = {('A', 'B'): {'C': 0.14285714285714285,
...                   'D': 0.14285714285714285,
...                   'E': 0.14285714285714285},
...       'C': 255}
...
>>> FormatPrinter({float: "%.2f", int: "%06X"}).pprint(d)
{'C': 0000FF,
 ('A', 'B'): {'C': 0.14,
              'D': 0.14,
              'E': 0.14}}
</code>```

Title: pprint with custom float formats

Body:
I have a nested dictionary structure with tuple keys. Here's what an entry looks like when I pretty-print the dictionary using pprint:

...
 ('A', 'B'): {'C': 0.14285714285714285,
              'D': 0.14285714285714285,
              'E': 0.14285714285714285,
              'F': 0.14285714285714285,
              'G': 0.14285714285714285,
              'H': 0.14285714285714285,
              'I': 0.14285714285714285},
...

It's pretty nifty, but I'd like to customize it further by cutting down some extra digits from the floats. I was thinking that it'd be possible to achieve by subclassing pprint.PrettyPrint but I don't know how that would be done.

Thanks.

Body:
As you said, you can achieve this by subclassing PrettyPrinter and overwriting the format method. Note that the output is not only the formatted string, but also some flags.

Once you're at it, you could also generalize this and pass a dictionary with the desired formats for different types into the constructor:

class FormatPrinter(pprint.PrettyPrinter):

    def __init__(self, formats):
        super(FormatPrinter, self).__init__()
        self.formats = formats

    def format(self, obj, ctx, maxlvl, lvl):
        if type(obj) in self.formats:
            return self.formats[type(obj)] % obj, 1, 0
        return pprint.PrettyPrinter.format(self, obj, ctx, maxlvl, lvl)

Example:

>>> d = {('A', 'B'): {'C': 0.14285714285714285,
...                   'D': 0.14285714285714285,
...                   'E': 0.14285714285714285},
...       'C': 255}
...
>>> FormatPrinter({float: "%.2f", int: "%06X"}).pprint(d)
{'C': 0000FF,
 ('A', 'B'): {'C': 0.14,
              'D': 0.14,
              'E': 0.14}}


问:
How call out queries through axios in Vue Js
I'm trying to call a query search with url something like this:

http://localhost/Stellar/public/api/companies?column=name&direction=desc&page=1

In Vue Js 2.0 in trying to call something like this:

```<code>axios.get('$(this.source)?column=$(this.query.column)&direction=$(this.query.direction)$page=$(this.query.page)')
</code>```

It is appearing something like this

```<code>http://localhost/Stellar/public/$(this.source)?column=$(this.query.column)&direction=$(this.query.direction)$page=$(this.query.page)
</code>```

It is not converting the data. Help me out in this.

Thanks.

答:
There is a more elegant way with the Axios Request Config:</p>

```<code>const url = "mysite.com";
const config = {
   params: {
       column: 42,
       direction: 'up'
    }
}
return axios.get(url, config)
   .then((response) => {
        ...
</code>```

Body:
I'm trying to call a query search with url something like this:

http://localhost/Stellar/public/api/companies?column=name&direction=desc&page=1

In Vue Js 2.0 in trying to call something like this:

axios.get('$(this.source)?column=$(this.query.column)&direction=$(this.query.direction)$page=$(this.query.page)')

It is appearing something like this

http://localhost/Stellar/public/$(this.source)?column=$(this.query.column)&direction=$(this.query.direction)$page=$(this.query.page)

It is not converting the data. Help me out in this.

Thanks.

Body:
There is a more elegant way with the Axios Request Config:

const url = "mysite.com";
const config = {
   params: {
       column: 42,
       direction: 'up'
    }
}
return axios.get(url, config)
   .then((response) => {
        ...


问:
Count no. of tokens after tokenization, stop words removal and stemming
I have the following function:

```<code>def preprocessText (data):
    stemmer = nltk.stem.porter.PorterStemmer()
    preprocessed = []
    for each in data:
        tokens = nltk.word_tokenize(each.lower().translate(string.punctuation))
        filtered = [word for word in tokens if word not in nltk.corpus.stopwords.words('english')]
        preprocessed.append([stemmer.stem(item) for item in filtered])
    print(Counter(tokens).most_common(10))
    return (np.array(preprocessed))
</code>```

which should remove punctuation, tokenize, remove stop words and stem using the Porter Stemmer. However, it doesn't work correctly. For example, when I run this code:

```<code>s = ["The cow and of.", "and of dog the."]
print (Counter(preprocessText(s)))
</code>```

it produces this output:

```<code>[('and', 1), ('.', 1), ('dog', 1), ('the', 1), ('of', 1)]
</code>```

which doesn't remove punctuation or stopwords.

答:
Your translate was not working to removing punctuation. Here is some working code.  I made a few changes, the most significant of which is:

Code:

```<code>xlate = {ord(x): y for x, y in
         zip(string.punctuation, ' ' * len(string.punctuation))}
tokens = nltk.word_tokenize(each.lower().translate(xlate))
</code>```

Test Code:

```<code>from collections import Counter
import nltk
import string

stopwords = set(nltk.corpus.stopwords.words('english'))
try:
    # python 2
    xlate = string.maketrans(
        string.punctuation, ' ' * len(string.punctuation))
except AttributeError:
    xlate = {ord(x): y for x, y in
             zip(string.punctuation, ' ' * len(string.punctuation))}

def preprocessText(data):
    stemmer = nltk.stem.porter.PorterStemmer()
    preprocessed = []
    for each in data:
        tokens = nltk.word_tokenize(each.lower().translate(xlate))
        filtered = [word for word in tokens if word not in stopwords]
        preprocessed.append([stemmer.stem(item) for item in filtered])
    return np.array(preprocessed)

s = ["The cow and of.", "and of dog the."]
print(Counter(sum([list(x) for x in preprocessText(s)], [])))
</code>```

Results:

```<code>Counter({'dog': 1, 'cow': 1})
</code>```

Body:
I have the following function:

def preprocessText (data):
    stemmer = nltk.stem.porter.PorterStemmer()
    preprocessed = []
    for each in data:
        tokens = nltk.word_tokenize(each.lower().translate(string.punctuation))
        filtered = [word for word in tokens if word not in nltk.corpus.stopwords.words('english')]
        preprocessed.append([stemmer.stem(item) for item in filtered])
    print(Counter(tokens).most_common(10))
    return (np.array(preprocessed))

which should remove punctuation, tokenize, remove stop words and stem using the Porter Stemmer. However, it doesn't work correctly. For example, when I run this code:

s = ["The cow and of.", "and of dog the."]
print (Counter(preprocessText(s)))

it produces this output:

[('and', 1), ('.', 1), ('dog', 1), ('the', 1), ('of', 1)]

which doesn't remove punctuation or stopwords.

Body:
Your translate was not working to removing punctuation. Here is some working code.  I made a few changes, the most significant of which is:

Code:

xlate = {ord(x): y for x, y in
         zip(string.punctuation, ' ' * len(string.punctuation))}
tokens = nltk.word_tokenize(each.lower().translate(xlate))

Test Code:

from collections import Counter
import nltk
import string

stopwords = set(nltk.corpus.stopwords.words('english'))
try:
    # python 2
    xlate = string.maketrans(
        string.punctuation, ' ' * len(string.punctuation))
except AttributeError:
    xlate = {ord(x): y for x, y in
             zip(string.punctuation, ' ' * len(string.punctuation))}

def preprocessText(data):
    stemmer = nltk.stem.porter.PorterStemmer()
    preprocessed = []
    for each in data:
        tokens = nltk.word_tokenize(each.lower().translate(xlate))
        filtered = [word for word in tokens if word not in stopwords]
        preprocessed.append([stemmer.stem(item) for item in filtered])
    return np.array(preprocessed)

s = ["The cow and of.", "and of dog the."]
print(Counter(sum([list(x) for x in preprocessText(s)], [])))

Results:

Counter({'dog': 1, 'cow': 1})


问:
Racket's Big Bang framework - making a game go faster using tick rate?
So in the Big Bang framework you can specify a tick rate:

(on-tick tick-handler tick-rate)

This tick-rate value is evaluated only once I believe (there is a similar question on here where this is stated as so).

If that's the case, how would one go about writing a game (such as Tetris) where you want the shape to drop down at a quicker rate as time goes by?  I've got the shape-drop occurring on the tick-handler at present.  If the tick-rate changed, the drop would occur more frequently.  As it is, I can't figure out how to make this happen without that feature.  Any clues?

答:
Set the tickrate to the fastest rate you need. Make a tick counter.
In you tick-handler have something like:

```<code> (define rate 4)
 (cond
   [(= (remainder tick-counter rate) 0)   do-the-same-as-before]
   [else                                  do-nothing-but-increment-counter])
</code>```

When rate is 4, you will only activate your tick handler for every fourth tick.
If you change rate to, say 2, you the speed is twice as fast. And when rate is 1, you will get the fastest speed.

Body:
Set the tickrate to the fastest rate you need. Make a tick counter.
In you tick-handler have something like:

 (define rate 4)
 (cond
   [(= (remainder tick-counter rate) 0)   do-the-same-as-before]
   [else                                  do-nothing-but-increment-counter])

When rate is 4, you will only activate your tick handler for every fourth tick.
If you change rate to, say 2, you the speed is twice as fast. And when rate is 1, you will get the fastest speed.


问:
How to exclude the VCS root in the template in particular sub projects?
I have a VCS root added to the template and the template is in the main project.

My project hierarchy looks something like this:

```<code>MAIN-PROJ --> SUB-PROJ1 --> SUB-SUB-PROJ1.......PROJN
          --> SUB-PROJ2 --> SUB2-SUB_PROJ1.......PROJN
</code>```

MAIN-PROJ contains my configuration template and I have added a VCS root to it. I don't want to use the VCS root in SUB-PROJ2 and it's sub projects.

How to achieve that?

答:
You cannot override VCS Root in TeamCity. That is possible just for properties.
You can exclude VCS Root from the template and instead add it just for those builds that really need it.
That will be also logically correct since having VCS Root in the template makes little sense if not all implementations of this template use it.

You won't have duplication since you reuse the same VCS Root in all builds that need it.

Body:
I have a VCS root added to the template and the template is in the main project.

My project hierarchy looks something like this:

MAIN-PROJ --> SUB-PROJ1 --> SUB-SUB-PROJ1.......PROJN
          --> SUB-PROJ2 --> SUB2-SUB_PROJ1.......PROJN

MAIN-PROJ contains my configuration template and I have added a VCS root to it. I don't want to use the VCS root in SUB-PROJ2 and it's sub projects.

How to achieve that?


问:
How to change the color of bottom navigation bar tap animation?
As you can see in this gif: https://gyazo.com/fc2f8e8ae9fbdae1b06d88336e76bc05

When an icon is tapped, an animation is played which is a green color. By default this color is gray. How can I change it to a different color?

答:
You can do it with your event. Like when you click the event then change source or transparent color of bottom bar actions.

Changing drawable can be a good option.


问:
Sorting MySQL results in PHP...?
I have a page on my site that lists a bunch of products, each with a user rating. I use one query to pull some data points for each product ("details query"), and a second query that returns the average user rating for each product ("ratings query").

I want to append the user rating for each product onto the "details query" result set, then sort by rating in descending order. I've read a bunch of entries on Stack Overflow, php.net etc. and I think I need to use usort() with a custom function, but every time I pass my MySQL result to usort() I get a php error saying the object I'm passing to usort() isn't an array. For example, I've tried:

```<code>$data = mysql_fetch_array($details_query);
usort($data,"compare");
</code>```

Doing the above will throw an error saying $data isn't an array. What am I doing wrong?

Also, if anyone has any other suggestions on how to get this done I'd really appreciate. I'm having a really tough time with this for some reason...

Thanks!

答:
I would have done this in the SQL Query.

```<code>SELECT foo,bar,baz
FROM MyTable
ORDER BY bar DESC
</code>```

You can put in your sorting field with PHP after "ORDER BY" and add ASC or DESC depending what way you want to sort.

```<code>$SQL = "SELECT foo,bar,baz FROM MyTable ORDER BY ".$SortField." DESC";
</code>```

Let the SQL server do as much as possible for you :D

Title: Sorting MySQL results in PHP...?

Body:
I have a page on my site that lists a bunch of products, each with a user rating. I use one query to pull some data points for each product ("details query"), and a second query that returns the average user rating for each product ("ratings query").

I want to append the user rating for each product onto the "details query" result set, then sort by rating in descending order. I've read a bunch of entries on Stack Overflow, php.net etc. and I think I need to use usort() with a custom function, but every time I pass my MySQL result to usort() I get a php error saying the object I'm passing to usort() isn't an array. For example, I've tried:

$data = mysql_fetch_array($details_query);
usort($data,"compare");

Doing the above will throw an error saying $data isn't an array. What am I doing wrong?

Also, if anyone has any other suggestions on how to get this done I'd really appreciate. I'm having a really tough time with this for some reason...

Thanks!

Body:
I would have done this in the SQL Query.

SELECT foo,bar,baz
FROM MyTable
ORDER BY bar DESC

You can put in your sorting field with PHP after "ORDER BY" and add ASC or DESC depending what way you want to sort.

$SQL = "SELECT foo,bar,baz FROM MyTable ORDER BY ".$SortField." DESC";

Let the SQL server do as much as possible for you :D


问:
Website is not responsive
I'm at the moment building a simple website with a header, a vertical nav and a content box and I'm failing in some minor thing. After building the html structure

```<code><html>
    <head>
        <title>Website</title>
        <link href="style.css" type="text/css" rel="stylesheet">
    </head>
    <body>
        <div class="container">
            <div class="header"></div>
            <div class="nav_content_container">
                <div class="nav"></div>
                <div class="content"></div>
                <div class="floatkiller"></div>
            </div>
        </div>
    </body>
</html>
</code>```

and giving it some css

```<code>body {
    height: 100%;
    width: 100%;
    margin: 0px;
    padding: 0px;
    background-color: lightgray;
}

.container {
    height: 100%;
    width: 77%;
    margin: 0px auto;
    background-color: white;
    border: 3px solid black;
}

.header {
    height: 20%;
    width: 100%;
    background-color: yellowgreen;
    border-bottom: 3px solid black;
}

.nav_content_container {
    height: 80%;
    width: 100%;
    background-color: azure;
}

.nav {
    height: 100%;
    width: 20%;
    float: left;
    background-color: palevioletred;
    border-right: 3px solid black;
}

.content {
    height: 100%;
    width: 80%;
    float: left;
    background-color: cornflowerblue;
}

.floatkiller {
    float: none;
    clear: both;
}
</code>```

my website is failing in beeing responsiv or to be accurate, my site get's a height more than 100% and my content box drops out of the nav_content_container. If I'm not giving any borders, everything is alright, but after applying the borders my website is broken. Why is the border making everything broken?

答: Because you are giving border in px. Change them to %. It will get fixed.

Title: Website is not responsive

Body:
I'm at the moment building a simple website with a header, a vertical nav and a content box and I'm failing in some minor thing. After building the html structure

        <title>Website</title>
        <link href="style.css" type="text/css" rel="stylesheet">

and giving it some css

body {
    height: 100%;
    width: 100%;
    margin: 0px;
    padding: 0px;
    background-color: lightgray;
}

.container {
    height: 100%;
    width: 77%;
    margin: 0px auto;
    background-color: white;
    border: 3px solid black;
}

.header {
    height: 20%;
    width: 100%;
    background-color: yellowgreen;
    border-bottom: 3px solid black;
}

.nav_content_container {
    height: 80%;
    width: 100%;
    background-color: azure;
}

.nav {
    height: 100%;
    width: 20%;
    float: left;
    background-color: palevioletred;
    border-right: 3px solid black;
}

.content {
    height: 100%;
    width: 80%;
    float: left;
    background-color: cornflowerblue;
}

.floatkiller {
    float: none;
    clear: both;
}

my website is failing in beeing responsiv or to be accurate, my site get's a height more than 100% and my content box drops out of the nav_content_container. If I'm not giving any borders, everything is alright, but after applying the borders my website is broken. Why is the border making everything broken?


问:
Div after div does not work as intended
I have div that needs to show after div, but it is showing before

Here is how it looks like

Screenshot

Here is the code

```<code><div style="width:100%;height:500px;border-style:solid;border-color:#1d69b4;margin-top:25px; white-space:nowrap;">
<div style="float:left; width:70%;height:100%;margin-left: 80px;">
    <div style="width:50%;height:30%;float:left;margin-top:20px;">
        <form>
            <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;border-width: 1px;" />
            <input class="form-control" type="text" id="from" name="from" placeholder="From" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;border-width: 1px;" />
        </form>
    </div>
    <div style="width:50%;height:30%;float:right;margin-top:20px;">
        <form>
            <input type="text" class="form-control" id="birth" name="birth" placeholder="Date of birth" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;border-width: 1px;" />
            <input class="form-control" type="text" id="to" name="to" placeholder="To" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;border-width: 1px;" />
        </form>
     </div>
    <div>sdkfhsdfgdsjfgjdf</div>
  </div>
</code>```

But it must be after div, not before.

Where is trouble?

答:
You missed a closing div and the second div has a float left. This takes it out of the normal document flow. Add float:left to the other div, and it looks good.

      <form>
        <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;border-width: 1px;" />
        <input class="form-control" type="text" id="from" name="from" placeholder="From" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;border-width: 1px;" />
      </form>

      <form>
        <input type="text" class="form-control" id="birth" name="birth" placeholder="Date of birth" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;border-width: 1px;" />
        <input class="form-control" type="text" id="to" name="to" placeholder="To" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;border-width: 1px;" />
      </form>

sdkfhsdfgdsjfgjdf

```

Title: Div after div does not work as intended

Body:
I have div that needs to show after div, but it is showing before

Here is how it looks like

Screenshot

Here is the code

        <form>
            <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;border-width: 1px;" />
            <input class="form-control" type="text" id="from" name="from" placeholder="From" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;border-width: 1px;" />
        </form>

        <form>
            <input type="text" class="form-control" id="birth" name="birth" placeholder="Date of birth" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;border-width: 1px;" />
            <input class="form-control" type="text" id="to" name="to" placeholder="To" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;border-width: 1px;" />
        </form>

sdkfhsdfgdsjfgjdf

But it must be after div, not before.

Where is trouble?

Body:
You missed a closing div and the second div has a float left. This takes it out of the normal document flow. Add float:left to the other div, and it looks good.

<div style="width:100%;height:500px;border-style:solid;border-color:#1d69b4;margin-top:25px; white-space:nowrap;">
  <div style="float:left; width:70%;height:100%;margin-left: 80px;">
    <div style="width:50%;height:30%;float:left;margin-top:20px;">
      <form>
        <input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;border-width: 1px;" />
        <input class="form-control" type="text" id="from" name="from" placeholder="From" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;border-width: 1px;" />
      </form>
    </div>
    <div style="width:50%;height:30%;float:right;margin-top:20px;">
      <form>
        <input type="text" class="form-control" id="birth" name="birth" placeholder="Date of birth" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;border-width: 1px;" />
        <input class="form-control" type="text" id="to" name="to" placeholder="To" style="padding: 12px 20px;margin: 8px 0;box-sizing: border-box; border-radius:50px;border-width: 1px;" />
      </form>
    </div>
    <div style="float:left;">sdkfhsdfgdsjfgjdf</div>
  </div>
</div>


问:
Change status bar color with react-navigation
I use a DrawerNavigator from react-navigation in my app. Without any customization, the Android status bar is blue, and not black.

I tried to do

StatusBar.setBackgroundColor('#000000');
```

but it only works for a few seconds, and then it goes back to blue. It seems that something I am using set the status bar color to blue. However, I tried to remove all dependencies and only keep react-navigation, and it still happens and the docs of react-navigation do not say anything about that.

How can I set the status bar color to black with react-navigation ?

答:
I don't think there is any conflict between react-navigation and the StatusBar, but I think you should use the <StatusBar> component rather than the imperative API. There's a high chance this is due to a re-render of your app and it just switch back to the default, with a component declare, you ensure it won't happen.

<StatusBar backgroundColor='blue' barStyle='light-content' />
```

You can even have multiple ones per route, to change it depending on the path. If you want to change it depending on the user and using redux, declare it in a connected component and pass the backgroundColor.

Body:
I use a DrawerNavigator from react-navigation in my app. Without any customization, the Android status bar is blue, and not black.

I tried to do

StatusBar.setBackgroundColor('#000000');

but it only works for a few seconds, and then it goes back to blue. It seems that something I am using set the status bar color to blue. However, I tried to remove all dependencies and only keep react-navigation, and it still happens and the docs of react-navigation do not say anything about that.

How can I set the status bar color to black with react-navigation ?

Body:
I don't think there is any conflict between react-navigation and the StatusBar, but I think you should use the <StatusBar> component rather than the imperative API. There's a high chance this is due to a re-render of your app and it just switch back to the default, with a component declare, you ensure it won't happen.

<StatusBar backgroundColor='blue' barStyle='light-content' />

You can even have multiple ones per route, to change it depending on the path. If you want to change it depending on the user and using redux, declare it in a connected component and pass the backgroundColor.


问:
.Net Console Application in System tray
Is there a way I can put a console application in the system tray when minimizing ?</p>

答:
```<code>using System.Windows.Forms;
using System.Drawing;

static NotifyIcon notifyIcon = new NotifyIcon();
static bool Visible = true;
static void Main(string[] args)
{
    notifyIcon.DoubleClick += (s, e) =>
    {
        Visible = !Visible;
        SetConsoleWindowVisibility(Visible);
    };
    notifyIcon.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
    notifyIcon.Visible = true;
    notifyIcon.Text = Application.ProductName;

    var contextMenu = new ContextMenuStrip();
    contextMenu.Items.Add("Exit", null, (s, e) => { Application.Exit(); });
    notifyIcon.ContextMenuStrip = contextMenu;

    Console.WriteLine("Running!");

    // Standard message loop to catch click-events on notify icon
    // Code after this method will be running only after Application.Exit()
    Application.Run();

    notifyIcon.Visible = false;
}

[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
public static void SetConsoleWindowVisibility(bool visible)
{
    IntPtr hWnd = FindWindow(null, Console.Title);
    if (hWnd != IntPtr.Zero)
    {
        if (visible) ShowWindow(hWnd, 1); //1 = SW_SHOWNORMAL
        else ShowWindow(hWnd, 0); //0 = SW_HIDE
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: .Net Console Application in System tray


问:
How do I throttle bandwidth-speed for internal ip-addresses using tc command and cbq-only filter?
I want to limit bandwidth-speed of internal ip-addresses (like 10.8.0.1) and had been trying to use the following rules:

```<code>tc qdisc add dev tun1 root handle 1: cbq avpkt 1000 bandwidth 3000mbit
tc class add dev tun1 parent 1: classid 1:1 cbq rate 1mbit allot 1500 prio 1 bounded isolated
tc qdisc add dev tun1 parent 1: sfq perturb 10
tc filter add dev tun1 parent 1: protocol ip prio 16 u32 match ip src {IP_HERE} flowid 1:1
</code>```

These rules work perfect with 'non-internal' ip-addresses but don't work with internals.
I am unable to use htb filter because my VPS is based on OpenVZ and the kernel doesn't support it.

Thanks.

答:
I solved the issue which is quite easy.

Just had to change source to destination. So, the last command will be like this:

```<code>tc filter add dev tun1 parent 1: protocol ip prio 16 u32 match ip dst {IP_HERE} flowid 1:1
</code>```

Body:
I want to limit bandwidth-speed of internal ip-addresses (like 10.8.0.1) and had been trying to use the following rules:

tc qdisc add dev tun1 root handle 1: cbq avpkt 1000 bandwidth 3000mbit
tc class add dev tun1 parent 1: classid 1:1 cbq rate 1mbit allot 1500 prio 1 bounded isolated
tc qdisc add dev tun1 parent 1: sfq perturb 10
tc filter add dev tun1 parent 1: protocol ip prio 16 u32 match ip src {IP_HERE} flowid 1:1

These rules work perfect with 'non-internal' ip-addresses but don't work with internals.
I am unable to use htb filter because my VPS is based on OpenVZ and the kernel doesn't support it.

Thanks.

Body:
I solved the issue which is quite easy.

Just had to change source to destination. So, the last command will be like this:

tc filter add dev tun1 parent 1: protocol ip prio 16 u32 match ip dst {IP_HERE} flowid 1:1


问:
Using protractor with ng-upgrade
I am working on migrating my AngularJS (1.6) app to Angular (4) and now have a hybrid application, bootstrapped with NgUpgrade.

However, this seems to have completely broken my Protractor tests.

Failed: Timed out waiting for asynchronous Angular tasks to finish after 11 seconds. This may be because the current page is not an Angular application. Please see the FAQ for more details: https://github.com/angular/protractor/blob/master/docs/timeouts.md#waiting-for-angular

While waiting for element with locator - Locator: By(css selector, .toggle-summary-button)

Hybrid app changes

The application seems to run fine, and both AngularJS and Angular components are working as expected. The changes I made in the bootstrapping process are:

1 Removed ng-app from html tag:

2 Added an AppModules (@NgModule) etc.

3 Used NgUpgrade to bootstrap the app:

```<code>import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { UpgradeModule } from '@angular/upgrade/static';
import { AppModule } from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule).then(platformRef => {
  const upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule;
  upgrade.bootstrap(document.body, ['myapp'], {strictDi: true});
});
</code>```

Protractor tests

Based on the error above, the problem seems to be related to whatever Protractor does when it is waiting for Angular. I have a beforeEach block which loads the login page, fills in the details and logs in. Weirdly it is still opening the page and entering text into the username field, but then it fails to go any further.

I can't understand why this is any different and no amount of changing things around seems to help, so any guidance would be most welcome!

I have tried, with no success:

adding "rootElement: 'body'" to my protractor config file

adding "ng12Hybrid: true" to my protractor config file - I get a message saying that it should no longer be needed as it auto detects.

increasing the allScriptsTimeout setting from 11000 to 60000 and it still times out.

turning off the waitForAngularEnabled setting. This solves the problem with the login fields, but then none of my http mocks work and the tests fail.

答:
What is funny is I asked the exact same question (+github) 15 months ago about angular 1 to angular 2:

Protractor + Hybrid Angular 1+2 Application = Fail

Without any solution I rolled back to angular 1. Today we decided to try again to move up from angular 1 to 4 like you, and landed on your question because we still have the exact same problem...

Well, not so funny actually... I can't understand why a so important feature is put apart like that. AngularJs was supposed to be actively maintained because of the breaking change to Angular 2+! It's a little disappointing (sorry for those expecting an real answer, I will post if updates)...

Edit: I went to React

Title: Using protractor with ng-upgrade

Body:
I am working on migrating my AngularJS (1.6) app to Angular (4) and now have a hybrid application, bootstrapped with NgUpgrade.

However, this seems to have completely broken my Protractor tests.

Failed: Timed out waiting for asynchronous Angular tasks to finish after 11 seconds. This may be because the current page is not an Angular application. Please see the FAQ for more details: https://github.com/angular/protractor/blob/master/docs/timeouts.md#waiting-for-angular

While waiting for element with locator - Locator: By(css selector, .toggle-summary-button)

Hybrid app changes

The application seems to run fine, and both AngularJS and Angular components are working as expected. The changes I made in the bootstrapping process are:

1 Removed ng-app from html tag:

2 Added an AppModules (@NgModule) etc.

3 Used NgUpgrade to bootstrap the app:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { UpgradeModule } from '@angular/upgrade/static';
import { AppModule } from './app.module';

platformBrowserDynamic().bootstrapModule(AppModule).then(platformRef => {
  const upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule;
  upgrade.bootstrap(document.body, ['myapp'], {strictDi: true});
});

Protractor tests

Based on the error above, the problem seems to be related to whatever Protractor does when it is waiting for Angular. I have a beforeEach block which loads the login page, fills in the details and logs in. Weirdly it is still opening the page and entering text into the username field, but then it fails to go any further.

I can't understand why this is any different and no amount of changing things around seems to help, so any guidance would be most welcome!

I have tried, with no success:

adding "rootElement: 'body'" to my protractor config file

adding "ng12Hybrid: true" to my protractor config file - I get a message saying that it should no longer be needed as it auto detects.

increasing the allScriptsTimeout setting from 11000 to 60000 and it still times out.

turning off the waitForAngularEnabled setting. This solves the problem with the login fields, but then none of my http mocks work and the tests fail.


问:
Double Value error in C
I am having a bit problem with this simple code.

I have tried different type castings, but I have not got any issue in here. If anybody tell me the reason that why its always printing 0.0000000 or something like that, I will be regretful and thanks in advance.

```<code>#include<stdio.h>
main()
{
    double num1,num5;
    printf ("Hello user\n");
    printf ("Let the thickness of black and white brick are same and the value
             is 2m\nAnd the gap between them is 1m\n");
    printf ("\nEnter the length of the road:\n");
    scanf ("%lf",&num1);
    num5 = ((2/5)*num1);
    printf ("%lf",num5);
    return 0;
}
</code>```

答: In integer math, 2/5 is 0 (remainder two). In C, how you use a result does not affect how that result is computed (the rules are complex enough already). So the fact that you multiply the result by a double doesn't change the way 2/5 (the quotient of two integers) is computed.

Title: Double Value error in C

Body:
I am having a bit problem with this simple code.

I have tried different type castings, but I have not got any issue in here. If anybody tell me the reason that why its always printing 0.0000000 or something like that, I will be regretful and thanks in advance.

#include<stdio.h>
main()
{
    double num1,num5;
    printf ("Hello user\n");
    printf ("Let the thickness of black and white brick are same and the value
             is 2m\nAnd the gap between them is 1m\n");
    printf ("\nEnter the length of the road:\n");
    scanf ("%lf",&num1);
    num5 = ((2/5)*num1);
    printf ("%lf",num5);
    return 0;
}


问:
Colour-categorised density scatterplots
I need to admit that I am pretty new to R and programming in general.

I am looking to create a density scatterplot. I have around 350 data points and only 27 unique x,y values. I would like it take the shape of what smoothScatter does with the only difference being that I would like the data points to take the colour which would reflect the absolute density (like, 1-5 green; 2-10, blue; 11-20, red; etc.), not how intense the colour is. Essentially, sharp and coloured points is what I am after

This is what it looks like before colouring:

Can you please help me figure out how to do this?

答:
Here's another way using the standard plot function and mtcars where the color reflects the model of the car.

```<code>attach(mtcars)
cars <- mtcars
cars$model <- as.factor(rownames(cars))
plot(cars$mpg, cars$wt, col = cars$model, pch = 16)
</code>```

Title: Colour-categorised density scatterplots

Body:
Here's another way using the standard plot function and mtcars where the color reflects the model of the car.

attach(mtcars)
cars <- mtcars
cars$model <- as.factor(rownames(cars))
plot(cars$mpg, cars$wt, col = cars$model, pch = 16)


答:
(2/5) performs an integer calculation, result 0. I suggest one of these approaches

```<code>num5 = 0.4 * num1;

num5 = 2 * num1 / 5;
</code>```

The second is potentially more accurate (since 0.4 cannot be exactly represented in double) when num1 is already a multiple of 5. In the first case, an error is already there.

Title: Double Value error in C

Body:
(2/5) performs an integer calculation, result 0. I suggest one of these approaches

num5 = 0.4 * num1;

num5 = 2 * num1 / 5;

The second is potentially more accurate (since 0.4 cannot be exactly represented in double) when num1 is already a multiple of 5. In the first case, an error is already there.