问:
Find two rectangles with minimum areas that cover all points
You're given a n points, unsorted in an array. You're supposed to find two rectangles that cover all points and they should not overlap. Edges of rectangles should be parallel to x or y ordinate.

The program should return the minimum area covered by all these dots. Area of first rectangle + area of second rectangle.

I tried to solve this problem. I sorted points by X ordinate and the first one is the leftmost one of the first rectangle. When we go through the points we find the highest and lowest one. I was thinking that when the difference between two points by x is the biggest, that means that the first point is rightmost one of the first rectangle, and the second point is the leftmost one of the second rectangle.

It should work when the points are given as in first example, however, if the example is the second one it doesn't work. As it would return something like this and that's wrong:

This should be correct:

Then i was thinking doing sorting twice, just, the second time do it by Y ordinate and then compare two total areas. Areas when points are sorted by x and when points are sorted by y and the smaller area is the correct answer.

答:
The two rectangles cannot overlap, so one must be either completely to the right or on top of the other. Your idea to sort the points by x-value and find the biggest gap is good, but you should do that for both directions, as you suggested. That would find the correct rectangles in your example.

The biggest gap isn't necessarily the ideal splitting point, however. Depending on the extent of the bounding boxes in the perpendicular direction, the split may be somewhere else. Consider a rectangular area with four quadrants, where two diagonally opposite quadrants are populated with points:

Here, the ideal split isn't where the largest gap is.

You can find the ideal location by considering all possible splits between points with adjacent x- and y-coordinates.

Sort the points by x-coordinate.

Scan the sorted array in ascending order. Keep track of the minimum rectangle to the left of the current point by storing the minimum and maximum y-coordinates. Store these running top and bottom borders for each point.

Now do the same in descending order, where you keep running top and bottom borders for the right rectangle.

Finally, loop through the points again and calculate the areas of the left and right minimal rectangles for a split between two adjacent nodes. Keep track of the minimum area sum.

Then do the same for minimum top and bottom rectangles. The last two steps can be combined, which will save arrays for the minimum bounds for the right rectangle.

This should be O(n · log n) in time: Sorting is O(n · log n) and the individual passes are O(n). You need O(n) additional memory for the running bounding boxes for thze first rectangle.


来源: stackexchange

问:
How to use a Boolean variable in an if statement to change text (C#)
So i am trying to create a simple text adventure in unity and i have written a script the changes the state of the text depending on key presses. To try and add a bit of complexity i have attempted to add a system where when in one state it is displayed that an item is picked up and the variable for that item has been set to true which is stated at the top of the script. Then, when the user next enters a different state it is checked to see if the variable is true or false in which if the variable is true different text will be displayed to if it where false. My issue is that every time i enter the state withe the IF statements the variable is automatically set to false no matter what. An answer would be more than appreciated :).

Engine:

```<code>using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class TextController : MonoBehaviour {

public Text text;
private enum states {cell, floor, CellDoor, mirror, bed, rock, shard};
private states myState;
bool rock;
bool shard;

    // Use this for initialization
    void Start () {
        rock = false;
        shard = false;
        myState = states.cell;
    }

    // Update is called once per frame
    void Update () {
        print (myState);
        if (myState == states.cell){
            state_cell ();
        }else if (myState == states.floor){
            state_floor ();
        }else if (myState == states.CellDoor){
            state_CellDoor ();
        }else if (myState == states.mirror){
           state_mirror ();
        }else if (myState == states.bed){
            state_bed ();
        }else if (myState == states.rock){
            state_rock ();
        }else if (myState == states.shard){
            state_shard ();
        }
    }
</code>```

Variable change:

```<code>void state_rock (){
        rock = true;
        text.text = "You conjure what strength you have and eagerly pry at a slightly loose looking part of the concrete " +
                    "with your blistered hands. Finally a piece breaks free, you drop it into one of your pockets.\n\n" +
                    "You have obtained a rock! \n\n" +
                    "Press R to return to the cell.";
    if (Input.GetKeyDown(KeyCode.R)){
        myState = states.cell;
    }
    print(rock);
</code>```

Statements that don't work:

```<code>void state_mirror (){
    print (rock);
    if (rock = true);{
        text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
                    "wielding a shard could prove useful. You remember the hefty chunk of concrete in your pocket. \n\n" +
                    "Press T if you would like to throw the rock at the mirror or R if you would like to return to the cell";
    }
    if (rock = false);{
        text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
                    "wielding a shard could prove useful. You are unable to think of any way of shattering the mirror " +
                    "as it is rigidly screwed into the wall, perhaps a blunt object would do the trick?. \n\n" +
                    "Press R to return to the cell.";
    }
    if (Input.GetKeyDown(KeyCode.R)){
        myState = states.cell;
    }
    if (Input.GetKeyDown(KeyCode.T)){
        myState = states.shard;
    }

}
</code>```

Console saying item is obtained, 'true'

Console saying that the item has not been obtained for some reason, 'false'

答:
There are some obvious problems with these statements.

```<code>if (rock = true);{
        text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
                    "wielding a shard could prove useful. You remember the hefty chunk of concrete in your pocket. \n\n" +
                    "Press T if you would like to throw the rock at the mirror or R if you would like to return to the cell";
    }
    if (rock = false);{
        text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
                    "wielding a shard could prove useful. You are unable to think of any way of shattering the mirror " +
                    "as it is rigidly screwed into the wall, perhaps a blunt object would do the trick?. \n\n" +
                    "Press R to return to the cell.";
    }
</code>```

You don't put a semicolon at the end of an if, and the = sign by itself, asigns the value on the right to the variable on the left before it is evaluated. So change the single = to a ==.

Your code becomes,

```<code>if (rock == true){
        text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
                    "wielding a shard could prove useful. You remember the hefty chunk of concrete in your pocket. \n\n" +
                    "Press T if you would like to throw the rock at the mirror or R if you would like to return to the cell";
    }
    if (rock == false){
        text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
                    "wielding a shard could prove useful. You are unable to think of any way of shattering the mirror " +
                    "as it is rigidly screwed into the wall, perhaps a blunt object would do the trick?. \n\n" +
                    "Press R to return to the cell.";
    }
</code>```

Though a better way to write this would be,

```<code>if (rock) // is the same as if rock == true
{
        text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
                    "wielding a shard could prove useful. You remember the hefty chunk of concrete in your pocket. \n\n" +
                    "Press T if you would like to throw the rock at the mirror or R if you would like to return to the cell";
}
else // is the same as if rock == false (in this case)
{
        text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
                    "wielding a shard could prove useful. You are unable to think of any way of shattering the mirror " +
                    "as it is rigidly screwed into the wall, perhaps a blunt object would do the trick?. \n\n" +
                    "Press R to return to the cell.";
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So i am trying to create a simple text adventure in unity and i have written a script the changes the state of the text depending on key presses. To try and add a bit of complexity i have attempted to add a system where when in one state it is displayed that an item is picked up and the variable for that item has been set to true which is stated at the top of the script. Then, when the user next enters a different state it is checked to see if the variable is true or false in which if the variable is true different text will be displayed to if it where false. My issue is that every time i enter the state withe the IF statements the variable is automatically set to false no matter what. An answer would be more than appreciated :).

Engine:

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class TextController : MonoBehaviour {

public Text text;
private enum states {cell, floor, CellDoor, mirror, bed, rock, shard};
private states myState;
bool rock;
bool shard;

    // Use this for initialization
    void Start () {
        rock = false;
        shard = false;
        myState = states.cell;
    }

    // Update is called once per frame
    void Update () {
        print (myState);
        if (myState == states.cell){
            state_cell ();
        }else if (myState == states.floor){
            state_floor ();
        }else if (myState == states.CellDoor){
            state_CellDoor ();
        }else if (myState == states.mirror){
           state_mirror ();
        }else if (myState == states.bed){
            state_bed ();
        }else if (myState == states.rock){
            state_rock ();
        }else if (myState == states.shard){
            state_shard ();
        }
    }

Variable change:

void state_rock (){
        rock = true;
        text.text = "You conjure what strength you have and eagerly pry at a slightly loose looking part of the concrete " +
                    "with your blistered hands. Finally a piece breaks free, you drop it into one of your pockets.\n\n" +
                    "You have obtained a rock! \n\n" +
                    "Press R to return to the cell.";
    if (Input.GetKeyDown(KeyCode.R)){
        myState = states.cell;
    }
    print(rock);

Statements that don't work:

void state_mirror (){
    print (rock);
    if (rock = true);{
        text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
                    "wielding a shard could prove useful. You remember the hefty chunk of concrete in your pocket. \n\n" +
                    "Press T if you would like to throw the rock at the mirror or R if you would like to return to the cell";
    }
    if (rock = false);{
        text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
                    "wielding a shard could prove useful. You are unable to think of any way of shattering the mirror " +
                    "as it is rigidly screwed into the wall, perhaps a blunt object would do the trick?. \n\n" +
                    "Press R to return to the cell.";
    }
    if (Input.GetKeyDown(KeyCode.R)){
        myState = states.cell;
    }
    if (Input.GetKeyDown(KeyCode.T)){
        myState = states.shard;
    }

}

Console saying item is obtained, 'true'

Console saying that the item has not been obtained for some reason, 'false'

Body:
There are some obvious problems with these statements.

if (rock = true);{
        text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
                    "wielding a shard could prove useful. You remember the hefty chunk of concrete in your pocket. \n\n" +
                    "Press T if you would like to throw the rock at the mirror or R if you would like to return to the cell";
    }
    if (rock = false);{
        text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
                    "wielding a shard could prove useful. You are unable to think of any way of shattering the mirror " +
                    "as it is rigidly screwed into the wall, perhaps a blunt object would do the trick?. \n\n" +
                    "Press R to return to the cell.";
    }

You don't put a semicolon at the end of an if, and the = sign by itself, asigns the value on the right to the variable on the left before it is evaluated. So change the single = to a ==.

Your code becomes,

if (rock == true){
        text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
                    "wielding a shard could prove useful. You remember the hefty chunk of concrete in your pocket. \n\n" +
                    "Press T if you would like to throw the rock at the mirror or R if you would like to return to the cell";
    }
    if (rock == false){
        text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
                    "wielding a shard could prove useful. You are unable to think of any way of shattering the mirror " +
                    "as it is rigidly screwed into the wall, perhaps a blunt object would do the trick?. \n\n" +
                    "Press R to return to the cell.";
    }

Though a better way to write this would be,

if (rock) // is the same as if rock == true
{
        text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
                    "wielding a shard could prove useful. You remember the hefty chunk of concrete in your pocket. \n\n" +
                    "Press T if you would like to throw the rock at the mirror or R if you would like to return to the cell";
}
else // is the same as if rock == false (in this case)
{
        text.text = "A rather old fashioned mirror, strangely clean and drilled into the wall. Shattering the mirror and " +
                    "wielding a shard could prove useful. You are unable to think of any way of shattering the mirror " +
                    "as it is rigidly screwed into the wall, perhaps a blunt object would do the trick?. \n\n" +
                    "Press R to return to the cell.";
}


问:
Laravel between dates
I want to check the validity of promo code by comparing date in eloquent but dont know why its not working

```<code>$promoCode = self::where('code', $code)
        ->where('start_date', '>=', Carbon::now()->toDateString())
        ->where('end_date', '<=', Carbon::now()->toDateString())
        ->first();
</code>```

If i comment out 2nd and 3rd line then it works fine. MySQL column type is date. I also tried whereDate method and thats not working too

答: It looks like you inverted the signs. You are looking for something that is older than start_date and younger than end_date.

Title: Laravel between dates

Body:
I want to check the validity of promo code by comparing date in eloquent but dont know why its not working

$promoCode = self::where('code', $code)
        ->where('start_date', '>=', Carbon::now()->toDateString())
        ->where('end_date', '<=', Carbon::now()->toDateString())
        ->first();

If i comment out 2nd and 3rd line then it works fine. MySQL column type is date. I also tried whereDate method and thats not working too


问:
Filename match and export
I have several files in a folder. I have to match the filenames using a regex pattern. In the regex pattern I have a word which would be a variable. I want all the files matched with the pattern to be moved to a separate directory with an alternate filename replacing the string with which I had made the match.

Eg,

I have many files with filenames having the word foo in the directory like,

```<code>gadgeagfooafsa
fsafsaffooarwf
fasfsfoofsafff
</code>```

I have to list these files and copy it to another directory replacing the word foo from it. I have specified the new pattern to be "kuh", Like the above files should be copied to the new folder as

```<code>gadgeagkuhafsa
fsafsafkuharwf
fasfskuhfsafff
</code>```

Finally, can I pipe different commands together to execute these in one line? :)

I had tried this command, but it didn't work, somehow the copy is failing.

```<code>ls | grep ".*foo[} ].*" | xargs cp -t work/
</code>```

答:
If all the files are in same folder

with bash

```<code>for i in *foo* ;do mv "$i" /tmp/"${i/foo/kuh}";done
</code>```

Title: Filename match and export

Body:
I have several files in a folder. I have to match the filenames using a regex pattern. In the regex pattern I have a word which would be a variable. I want all the files matched with the pattern to be moved to a separate directory with an alternate filename replacing the string with which I had made the match.

Eg,

I have many files with filenames having the word foo in the directory like,

gadgeagfooafsa
fsafsaffooarwf
fasfsfoofsafff

I have to list these files and copy it to another directory replacing the word foo from it. I have specified the new pattern to be "kuh", Like the above files should be copied to the new folder as

gadgeagkuhafsa
fsafsafkuharwf
fasfskuhfsafff

Finally, can I pipe different commands together to execute these in one line? :)

I had tried this command, but it didn't work, somehow the copy is failing.

ls | grep ".*foo[} ].*" | xargs cp -t work/

Body:
If all the files are in same folder

with bash

for i in *foo* ;do mv "$i" /tmp/"${i/foo/kuh}";done


问:
How to make apidoc.json parameters required?
Super simple but I can't find the docs on how to mark a parameter as required when I markup my document to generate an api-doc (using the package @: http://apidocjs.com)

```<code>// My APIDOC markup in my PHP doc

 * @apiParam {String} [type] comma delimited list of any or all of: contests, deals, coupons
</code>```

... which generates the following html:

I want the optional as shown  to become required. What is the markup for that?

答:
Found it. Turns out you just remove the [] brackets around the variable</p>

```<code> * @apiParam {String} required_variable comma delimited list of any or all of: contests, deals, coupons
</code>```

Body:
Super simple but I can't find the docs on how to mark a parameter as required when I markup my document to generate an api-doc (using the package @: http://apidocjs.com)

// My APIDOC markup in my PHP doc

 * @apiParam {String} [type] comma delimited list of any or all of: contests, deals, coupons

... which generates the following html:

I want the optional as shown  to become required. What is the markup for that?

Body:
Found it. Turns out you just remove the [] brackets around the variable

 * @apiParam {String} required_variable comma delimited list of any or all of: contests, deals, coupons


问:
Need help, need to count the number of negative values inside a linked list, C++
So I am working through an assignment on an online course and I need some help programming a way to count the number of negative values inside a linked list in C++.

Here is the code I have right now along with one of my attempted awnsers:

```<code>#include <iostream>
#include <cstdlib>
using namespace std;

class IntNode {
public:
   IntNode(int dataInit = 0, IntNode* nextLoc = nullptr);
   void InsertAfter(IntNode* nodePtr);
   IntNode* GetNext();
   int GetDataVal();
private:
   int dataVal;
   IntNode* nextNodePtr;
};

// Constructor
IntNode::IntNode(int dataInit, IntNode* nextLoc) {
   this->dataVal = dataInit;
   this->nextNodePtr = nextLoc;

   return;
}

/* Insert node after this node.
 * Before: this -- next
 * After:  this -- node -- next
 */
void IntNode::InsertAfter(IntNode* nodeLoc) {
   IntNode* tmpNext = nullptr;

   tmpNext = this->nextNodePtr;    // Remember next
   this->nextNodePtr = nodeLoc;    // this -- node -- ?
   nodeLoc->nextNodePtr = tmpNext; // this -- node -- next

   return;
}

// Grab location pointed by nextNodePtr
IntNode* IntNode::GetNext() {
   return this->nextNodePtr;
}

int IntNode::GetDataVal() {
   return this->dataVal;
}

int main() {
   IntNode* headObj = nullptr; // Create intNode objects
   IntNode* currObj = nullptr;
   IntNode* lastObj = nullptr;
   int i = 0;
   int negativeCntr = 0;

   headObj = new IntNode(-1);        // Front of nodes list
   lastObj = headObj;

   for (i = 0; i < 10; ++i) {        // Append 10 rand nums
      currObj = new IntNode((rand() % 21) - 10);
      lastObj->InsertAfter(currObj); // Append curr
      lastObj = currObj;             // Curr is the new last item
   }

   currObj = headObj;                // Print the list
   while (currObj != nullptr) {
      cout << currObj->GetDataVal() << ", ";
      currObj = currObj->GetNext();
   }
   cout << endl;

   currObj = headObj;                // Count number of negative numbers
   while (currObj != nullptr) {

      /* Your solution goes here  */
    if (currObj > 0)
    {
        negativeCntr++;
    }

      currObj = currObj->GetNext();
   }
   cout << "Number of negatives: " << negativeCntr << endl;

   return 0;
}
</code>```

I am not sure what syntaxes to use in this case, I prowled around the book for some solutions but could not find anything.

答:
This seems like the easiest way to do it.</p>

```<code>if(currObj->GetDataVal() < 0) negativeCntr++;
</code>```

Body:
So I am working through an assignment on an online course and I need some help programming a way to count the number of negative values inside a linked list in C++.

Here is the code I have right now along with one of my attempted awnsers:

#include <iostream>
#include <cstdlib>
using namespace std;

class IntNode {
public:
   IntNode(int dataInit = 0, IntNode* nextLoc = nullptr);
   void InsertAfter(IntNode* nodePtr);
   IntNode* GetNext();
   int GetDataVal();
private:
   int dataVal;
   IntNode* nextNodePtr;
};

// Constructor
IntNode::IntNode(int dataInit, IntNode* nextLoc) {
   this->dataVal = dataInit;
   this->nextNodePtr = nextLoc;

   return;
}

/* Insert node after this node.
 * Before: this -- next
 * After:  this -- node -- next
 */
void IntNode::InsertAfter(IntNode* nodeLoc) {
   IntNode* tmpNext = nullptr;

   tmpNext = this->nextNodePtr;    // Remember next
   this->nextNodePtr = nodeLoc;    // this -- node -- ?
   nodeLoc->nextNodePtr = tmpNext; // this -- node -- next

   return;
}

// Grab location pointed by nextNodePtr
IntNode* IntNode::GetNext() {
   return this->nextNodePtr;
}

int IntNode::GetDataVal() {
   return this->dataVal;
}

int main() {
   IntNode* headObj = nullptr; // Create intNode objects
   IntNode* currObj = nullptr;
   IntNode* lastObj = nullptr;
   int i = 0;
   int negativeCntr = 0;

   headObj = new IntNode(-1);        // Front of nodes list
   lastObj = headObj;

   for (i = 0; i < 10; ++i) {        // Append 10 rand nums
      currObj = new IntNode((rand() % 21) - 10);
      lastObj->InsertAfter(currObj); // Append curr
      lastObj = currObj;             // Curr is the new last item
   }

   currObj = headObj;                // Print the list
   while (currObj != nullptr) {
      cout << currObj->GetDataVal() << ", ";
      currObj = currObj->GetNext();
   }
   cout << endl;

   currObj = headObj;                // Count number of negative numbers
   while (currObj != nullptr) {

      /* Your solution goes here  */
    if (currObj > 0)
    {
        negativeCntr++;
    }

      currObj = currObj->GetNext();
   }
   cout << "Number of negatives: " << negativeCntr << endl;

   return 0;
}

I am not sure what syntaxes to use in this case, I prowled around the book for some solutions but could not find anything.

Body:
This seems like the easiest way to do it.

if(currObj->GetDataVal() < 0) negativeCntr++;


问:
Apache Flink: how to consume dynamic type in transformation (map, reduce, join, etc) functions
I create a custom csv reader that generates a dynamic return type specified with env.readCsvFile(location).pojoType(dynClass, arr);, where dynClass is created with ByteBuddy and arr is an array of column names. I then try to map my pojo to a tuple with:

```<code>public class PojoToTupleRichMapFunction extends RichMapFunction<I, O> implements ResultTypeQueryable {

    Class tupleClass = null;
    Class pojoClass = null;
    Config.Schema schema = null;
    transient List<Field> fields = null;

    PojoToTupleRichMapFunction(DynDataSet dynSet) {
        this.schema = dynSet.dataDef.schema;
        // Create a map from pojo to tuple
        this.tupleClass = O.getTupleClass(schema.columns.size());
        this.pojoClass = dynSet.recType;

    }

    @Override
    public void open(Configuration parameters) {
        fields = new ArrayList<>(schema.columns.size());
        for (int i = 0; i < schema.columns.size(); i++) {
            try {
                fields.add(pojoClass.getField(schema.columns.get(i).name));
            } catch (NoSuchFieldException | SecurityException ex) {
                Logger.getLogger(PojoToTupleRichMapFunction.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    @Override
    public TupleTypeInfo getProducedType() {
        // build list of types
        List<BasicTypeInfo<?>> types = new ArrayList<>(schema.columns.size());
        for (int i = 0; i < schema.columns.size(); i++) {
            BasicTypeInfo bt = null;
            String typeName = schema.columns.get(i).type.getName();
            switch (typeName) {
                case "java.lang.Integer":
                    bt = BasicTypeInfo.INT_TYPE_INFO;
                    break;
                case "java.lang.String":
                    bt = BasicTypeInfo.STRING_TYPE_INFO;
                    break;
                case "java.lang.Long":
                    bt = BasicTypeInfo.LONG_TYPE_INFO;
                    break;
                case "java.lang.Short":
                    bt = BasicTypeInfo.SHORT_TYPE_INFO;
                    break;
                default:
                    Logger.getLogger(Config.class.getName()).log(Level.SEVERE, "Unknown type: {0}", typeName);

            }
            types.add(bt);
        }
        return new TupleTypeInfo(tupleClass, types.toArray(new BasicTypeInfo[0]));
    }

    @Override
    public O map(I pojo) throws Exception {
        O ret;
        ret = (O) tupleClass.newInstance();
        for (int i = 0; i < schema.columns.size(); i++) {
            ret.setField(fields.get(i).get(pojo), i);
        }
        return ret;
    }
}
</code>```

The challenge I am running into is this runtime error fragment:
org.apache.flink.api.common.functions.InvalidTypesException: Input mismatch: POJO type 'com.me.dynamic.FlinkPojo$ByteBuddy$zQ9VllB1' expected but was 'com.me.dynamic.I'.

The function declaration specifies base types. The actual input type is a dynamic subclass. The output type is provided by getProducedType.

How do I craft the MapFunction to handle the dynamic input type?

答:
To provide at least one solution (perhaps not the best), I changed the class definition to:

```<code>public class PojoToTupleRichMapFunction<I extends FlinkPojo, O extends Tuple> extends RichMapFunction<I, O> implements ResultTypeQueryable {
}
</code>```

I then used ByteBuddy to reclassify a the compiled class containing generic parameters.

```<code>static private DataSet<?> mapPojoToTuple(DataSet ds, DynDataSet dynSet) {
    Class<?> clazz = new ByteBuddy()
        .subclass(TypeDescription.Generic.Builder.parameterizedType(PojoToTupleRichMapFunction.class, dynSet.recType, Tuple.class).build())
        .make()
        .load(PojoToTupleRichMapFunction.class.getClassLoader())
        .getLoaded();
    Constructor<?> ctr = clazz.getConstructors()[0];
    RichMapFunction fcn = null;
    try {
        fcn = (RichMapFunction) ctr.newInstance(dynSet);
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
        Logger.getLogger(dyn_demo.class.getName()).log(Level.SEVERE, null, ex);
    }
    return ds.map(fcn);
}
</code>```

This seems to satisfy Flink.

Body:
I create a custom csv reader that generates a dynamic return type specified with env.readCsvFile(location).pojoType(dynClass, arr);, where dynClass is created with ByteBuddy and arr is an array of column names. I then try to map my pojo to a tuple with:

public class PojoToTupleRichMapFunction extends RichMapFunction implements ResultTypeQueryable {

    Class tupleClass = null;
    Class pojoClass = null;
    Config.Schema schema = null;
    transient List<Field> fields = null;

    PojoToTupleRichMapFunction(DynDataSet dynSet) {
        this.schema = dynSet.dataDef.schema;
        // Create a map from pojo to tuple
        this.tupleClass = O.getTupleClass(schema.columns.size());
        this.pojoClass = dynSet.recType;

    }

    @Override
    public void open(Configuration parameters) {
        fields = new ArrayList<>(schema.columns.size());
        for (int i = 0; i < schema.columns.size(); i++) {
            try {
                fields.add(pojoClass.getField(schema.columns.get(i).name));
            } catch (NoSuchFieldException | SecurityException ex) {
                Logger.getLogger(PojoToTupleRichMapFunction.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    @Override
    public TupleTypeInfo getProducedType() {
        // build list of types
        List<BasicTypeInfo<?>> types = new ArrayList<>(schema.columns.size());
        for (int i = 0; i < schema.columns.size(); i++) {
            BasicTypeInfo bt = null;
            String typeName = schema.columns.get(i).type.getName();
            switch (typeName) {
                case "java.lang.Integer":
                    bt = BasicTypeInfo.INT_TYPE_INFO;
                    break;
                case "java.lang.String":
                    bt = BasicTypeInfo.STRING_TYPE_INFO;
                    break;
                case "java.lang.Long":
                    bt = BasicTypeInfo.LONG_TYPE_INFO;
                    break;
                case "java.lang.Short":
                    bt = BasicTypeInfo.SHORT_TYPE_INFO;
                    break;
                default:
                    Logger.getLogger(Config.class.getName()).log(Level.SEVERE, "Unknown type: {0}", typeName);

            }
            types.add(bt);
        }
        return new TupleTypeInfo(tupleClass, types.toArray(new BasicTypeInfo[0]));
    }

    @Override
    public O map(I pojo) throws Exception {
        O ret;
        ret = (O) tupleClass.newInstance();
        for (int i = 0; i < schema.columns.size(); i++) {
            ret.setField(fields.get(i).get(pojo), i);
        }
        return ret;
    }
}

The challenge I am running into is this runtime error fragment:
org.apache.flink.api.common.functions.InvalidTypesException: Input mismatch: POJO type 'com.me.dynamic.FlinkPojo$ByteBuddy$zQ9VllB1' expected but was 'com.me.dynamic.I'.

The function declaration specifies base types. The actual input type is a dynamic subclass. The output type is provided by getProducedType.

How do I craft the MapFunction to handle the dynamic input type?

Body:
To provide at least one solution (perhaps not the best), I changed the class definition to:

public class PojoToTupleRichMapFunction<I extends FlinkPojo, O extends Tuple> extends RichMapFunction<I, O> implements ResultTypeQueryable {
}

I then used ByteBuddy to reclassify a the compiled class containing generic parameters.

static private DataSet<?> mapPojoToTuple(DataSet ds, DynDataSet dynSet) {
    Class<?> clazz = new ByteBuddy()
        .subclass(TypeDescription.Generic.Builder.parameterizedType(PojoToTupleRichMapFunction.class, dynSet.recType, Tuple.class).build())
        .make()
        .load(PojoToTupleRichMapFunction.class.getClassLoader())
        .getLoaded();
    Constructor<?> ctr = clazz.getConstructors()[0];
    RichMapFunction fcn = null;
    try {
        fcn = (RichMapFunction) ctr.newInstance(dynSet);
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
        Logger.getLogger(dyn_demo.class.getName()).log(Level.SEVERE, null, ex);
    }
    return ds.map(fcn);
}

This seems to satisfy Flink.


问:
How to detect scroll events in mat-sidenav-container
I can't figure out how to detect when the mat-sidenav-container scrolls in angular material 2.

I would like to call a method on my component when a user scrolls. However when using the sidenav-container the scroll event is no longer fired on the window.

Instead an extra <mat-sidenav-content cdkscrollable></mat-sidenav-content> element is added and this is where the scroll bars are. How can I detect when scrolling occurs on this component if I can't directly access it to put an (scroll)="myMethod()" event listener on it.

Any ideas?

答:
You should use Material2 example "Sidenav with a FAB".

Please wrap scrollable content with div:

```<code><mat-sidenav-container class="example-sidenav-fab-container">
  <mat-sidenav #sidenav mode="side" opened="true">
   ...
  </mat-sidenav>
  <div class="example-scrolling-content" (scroll)="handleScroll($event)">
    ... content ...
  </div>
</mat-sidenav-container>
</code>```

and this should be your css:

```<code>.example-scrolling-content {
  overflow: auto;
  height: 100%;
}
</code>```

Body:
You should use Material2 example "Sidenav with a FAB".

Please wrap scrollable content with div:

<mat-sidenav-container class="example-sidenav-fab-container">
  <mat-sidenav #sidenav mode="side" opened="true">
   ...
  </mat-sidenav>
  <div class="example-scrolling-content" (scroll)="handleScroll($event)">
    ... content ...
  </div>
</mat-sidenav-container>

and this should be your css:

.example-scrolling-content {
  overflow: auto;
  height: 100%;
}


问:
Passing a generator to a process in Python
My code at large takes a Python dictionary, that contains database column names and their content, binarizes the columns (struct.pack, array.array, str.encode) and sends them using socket.sendall.

To improve speed, I wrote the binarization part in a generator function, that yields the binary chunks. A generator is sent to a thread, which generates the chunks and puts them in a queue, which the main thread collects and sends away.

However, I still don't get the speed improvement I expected.
I figured I'd try using an auxiliary process instead of an aux. thread. The problem is - I can't pass a generator to a process - "not pickleable".

I would be grateful for any suggestions / feedback / insights as to how to go about this type of mechanics.

EDIT: When profiling the code with snakeviz (cProfile with graphics), I saw that socket.recv takes 3/4 of the time, and time.sleep (Waiting for chunks in the main thread) another 1/4. That 1/4 is what I thought I could mitigate with another therad/process, as I read that both blocking socket operations and time.sleep are supposed to release the GIL.

答:
I don't see how you would expect to have any performance improvement by doing this in another process. The function of producing a binary representation (serialization) of your dictionary is completely CPU bound -- and, relatively speaking, should be very fast -- while the function of sending it to another system is I/O bound, and will almost certainly be slower and the ultimate bottleneck.

In fact, I wouldn't be surprised if delivering these binary chunks you've created through a queue from one thread to another takes more time than simply running the serializer directly in the socket-sending thread when you factor in thread context-switching and queue insertion/extraction/synchronization overhead (and the effects of the GIL if you're using CPython). And the queue sending/synchronization overhead is unlikely to change for the better if you move the serialization to a separate process.

If you want to do the sending concurrently with other activity -- you're concerned with tying up your main thread for a long time -- then you should probably just delegate the entire task (serialization plus sending) to another thread or process.

Another thing to understand is that when you first begin to send on a socket, the kernel will copy the initial data into internal buffers and immediately return control to you -- the kernel then breaks the data up into packets and sends on the wire as the protocol permits asynchronously. So, the sends will not (at first) appear to be I/O bound. But if you have many megabytes of data to send, eventually the kernel buffer space allowed to your socket will fill and then your thread will be blocked until enough packets have been sent and acknowledged by the peer to free up some of that space.

In other words, in a single-threaded implementation, if G means generate a chunk of data and S is a socket.sendall call, your total time spent in each phase will look something like this:

```<code>G|S|G|S|G|S|G|S|G|S-------|G|S------|G|S-----|G|S------ ...
</code>```

At first, the sends will seem near-instantaneous, but after a while, will start to take longer to complete. And if you aren't generating enough data to experience this effect, then it's even less likely you have any need to push the serialization to a separate thread.

Body:
I don't see how you would expect to have any performance improvement by doing this in another process. The function of producing a binary representation (serialization) of your dictionary is completely CPU bound -- and, relatively speaking, should be very fast -- while the function of sending it to another system is I/O bound, and will almost certainly be slower and the ultimate bottleneck.

In fact, I wouldn't be surprised if delivering these binary chunks you've created through a queue from one thread to another takes more time than simply running the serializer directly in the socket-sending thread when you factor in thread context-switching and queue insertion/extraction/synchronization overhead (and the effects of the GIL if you're using CPython). And the queue sending/synchronization overhead is unlikely to change for the better if you move the serialization to a separate process.

If you want to do the sending concurrently with other activity -- you're concerned with tying up your main thread for a long time -- then you should probably just delegate the entire task (serialization plus sending) to another thread or process.

Another thing to understand is that when you first begin to send on a socket, the kernel will copy the initial data into internal buffers and immediately return control to you -- the kernel then breaks the data up into packets and sends on the wire as the protocol permits asynchronously. So, the sends will not (at first) appear to be I/O bound. But if you have many megabytes of data to send, eventually the kernel buffer space allowed to your socket will fill and then your thread will be blocked until enough packets have been sent and acknowledged by the peer to free up some of that space.

In other words, in a single-threaded implementation, if G means generate a chunk of data and S is a socket.sendall call, your total time spent in each phase will look something like this:

G|S|G|S|G|S|G|S|G|S-------|G|S------|G|S-----|G|S------ ...

At first, the sends will seem near-instantaneous, but after a while, will start to take longer to complete. And if you aren't generating enough data to experience this effect, then it's even less likely you have any need to push the serialization to a separate thread.


问:
Ifelse in R with multiple categorical conditions
I have a data set, dt.train2 with  1500 different observations and 130 variables. One of them is languages and it can be english, french, arabic...

I want to create a ifelse string that gives attributes 1 for english, 2 for french, 3 for spanish and 0 for anything else. I have no idea how to do it.

```<code>dt.train2[, language_string := ifelse(language == "english",
                                      1,
                                      ifelse(language == "french",
                                             2,
                                             ifelse(language == "spanish",3)]
</code>```

I'm using this to run linear model about sales.

答:
check this: </p>

```<code> t <- 'es'
 tt <- (if (t == 'en') 1 else if (t == 'fr') {2} else if (t == 'es') 3 else 0)
 tt
 [1] 0
</code>```

<p>you can then apply it to like a dataframe: </p>

```<code>df <- data.frame(l=c('en', 'fr', 'es', 'sthelse'))
df$lnum <- sapply(df$l, function(t){(if (t == 'en') 1 else if (t == 'fr') {2} else if (t == 'es') 3 else 0)})
df
        l lnum
1      en    1
2      fr    2
3      es    3
4 sthelse    0
</code>```

Body:
I have a data set, dt.train2 with  1500 different observations and 130 variables. One of them is languages and it can be english, french, arabic...

I want to create a ifelse string that gives attributes 1 for english, 2 for french, 3 for spanish and 0 for anything else. I have no idea how to do it.

dt.train2[, language_string := ifelse(language == "english",
                                      1,
                                      ifelse(language == "french",
                                             2,
                                             ifelse(language == "spanish",3)]

I'm using this to run linear model about sales.

Body:
check this:

 t <- 'es'
 tt <- (if (t == 'en') 1 else if (t == 'fr') {2} else if (t == 'es') 3 else 0)
 tt
 [1] 0

you can then apply it to like a dataframe:

df <- data.frame(l=c('en', 'fr', 'es', 'sthelse'))
df$lnum <- sapply(df$l, function(t){(if (t == 'en') 1 else if (t == 'fr') {2} else if (t == 'es') 3 else 0)})
df
        l lnum
1      en    1
2      fr    2
3      es    3
4 sthelse    0


问:
How do I save the viewport bitmap of an imageview? - Android
I only want to save the bitmap of the image being displayed/cropped in the ImageView.

When I call this, it returns the entire bitmap:

```<code>Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
</code>```

答:
Use this to get the bitmap from ImageView</p>

```<code>imageView.buildDrawingCache();
Bitmap bmap = imageView.getDrawingCache();
</code>```

Body:
I only want to save the bitmap of the image being displayed/cropped in the ImageView.

When I call this, it returns the entire bitmap:

Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();

Body:
Use this to get the bitmap from ImageView

imageView.buildDrawingCache();
Bitmap bmap = imageView.getDrawingCache();


问:
how to make an attribute unique in xml schema?
i wanna make an attribute of an element to be unique like primary key. how to make it?</p>

答:
Note:
This is not working if you have different namespaces. Then you need the full XPath expression:

This could be like:

```<code><xs:unique name="unique-isbn">
      <xs:selector xpath="theOtherNamespace:book"/>
      <xs:field xpath="@isbn"/>
</xs:unique>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Note:
This is not working if you have different namespaces. Then you need the full XPath expression:

This could be like:

<xs:unique name="unique-isbn">
      <xs:selector xpath="theOtherNamespace:book"/>
      <xs:field xpath="@isbn"/>
</xs:unique>


问:
Program Displays the number of Mersenne wrong
hi guys the problem that im having with this code is that the number of mersenne primes is supposed to be 4 but it outputs 8. i know this because the number of Mersenne primes between 1 and 1000 are 3, 7, 31, and 127 but it also outputs 15, 63, 255, and 511. which i dont know why. is there also a way to output the counts of Primes per 100 numbers? thanks

```<code> public static void main(String[] args) {
    System.out.println("Prime numbers between 1 and 1000 are\n");
    String message = "";
    String message2 = "";
    // loop numbers from 1 to 1,000, printing only the primes
            int counter2 = 0;
            int counter = 0;
            for( int number s= 2; number <= 1000; number ++){
               if(isPrime(number)) {
                  counter++;
                  if(counter % 10 == 0) {
                    System.out.println(number);
                  }
                  else
                    System.out.print(number + " ");
                 }
               }
         for(int number2 = 2; number2 <= 1000; number2 ++){
           if(isMersenne(number2)){
                 counter2++;
                 System.out.print(number2 + "*");
              }
            }
            System.out.print( "\n\n The number of primes between 1 and 1000 are " + counter);
            System.out.print( "\n The number of Mersennes is " + counter2);
 }

public static boolean isPrime( int number ){
            // initialize the boolean variable prime to true
            boolean isPrime = true;
            for(int divisor = 2; divisor <= number /2; divisor++) {
             if(number % divisor == 0) {
              isPrime = false;
             }
           }
            return isPrime;
         }

public static boolean isMersenne(int number){
                // declare and initialize variable powTwo to 2
                int powTwo = 2;
                boolean mersenne = false;
                    while(powTwo <= number){
                          powTwo *= 2;
                       if(powTwo - number == 1)
                       // if the prime is one less than a power of 2, return true
                       mersenne =  true;
                    }
        return mersenne;
            } // end method isMersenne
       }
</code>```

this is the output of my program

```<code> Prime numbers between 1 and 1000 are

 2 3 5 7 11 13 17 19 23 29
 31 37 41 43 47 53 59 61 67 71
 73 79 83 89 97 101 103 107 109 113
 127 131 137 139 149 151 157 163 167 173
 179 181 191 193 197 199 211 223 227 229
 233 239 241 251 257 263 269 271 277 281
 283 293 307 311 313 317 331 337 347 349
 353 359 367 373 379 383 389 397 401 409
 419 421 431 433 439 443 449 457 461 463
 467 479 487 491 499 503 509 521 523 541
 547 557 563 569 571 577 587 593 599 601
 607 613 617 619 631 641 643 647 653 659
 661 673 677 683 691 701 709 719 727 733
 739 743 751 757 761 769 773 787 797 809
 811 821 823 827 829 839 853 857 859 863
 877 881 883 887 907 911 919 929 937 941
 947 953 967 971 977 983 991 997 3*7*15*31*63*127*255*511*

 The number of primes between 1 and 1000 are 168
 The number of Mersennes is 8
</code>```

答:
Your problem is that isMersenne is just checking whether the number is one less than a power of two.  It's not also checking that it's a prime.

You need to change your isMersenne method so that it calls isPrime after checking whether the number is one less than a power of two.  If isPrime returns false, then isMersenne should also return false.

Body:
hi guys the problem that im having with this code is that the number of mersenne primes is supposed to be 4 but it outputs 8. i know this because the number of Mersenne primes between 1 and 1000 are 3, 7, 31, and 127 but it also outputs 15, 63, 255, and 511. which i dont know why. is there also a way to output the counts of Primes per 100 numbers? thanks

 public static void main(String[] args) {
    System.out.println("Prime numbers between 1 and 1000 are\n");
    String message = "";
    String message2 = "";
    // loop numbers from 1 to 1,000, printing only the primes
            int counter2 = 0;
            int counter = 0;
            for( int number s= 2; number <= 1000; number ++){
               if(isPrime(number)) {
                  counter++;
                  if(counter % 10 == 0) {
                    System.out.println(number);
                  }
                  else
                    System.out.print(number + " ");
                 }
               }
         for(int number2 = 2; number2 <= 1000; number2 ++){
           if(isMersenne(number2)){
                 counter2++;
                 System.out.print(number2 + "*");
              }
            }
            System.out.print( "\n\n The number of primes between 1 and 1000 are " + counter);
            System.out.print( "\n The number of Mersennes is " + counter2);
 }

public static boolean isPrime( int number ){
            // initialize the boolean variable prime to true
            boolean isPrime = true;
            for(int divisor = 2; divisor <= number /2; divisor++) {
             if(number % divisor == 0) {
              isPrime = false;
             }
           }
            return isPrime;
         }

public static boolean isMersenne(int number){
                // declare and initialize variable powTwo to 2
                int powTwo = 2;
                boolean mersenne = false;
                    while(powTwo <= number){
                          powTwo *= 2;
                       if(powTwo - number == 1)
                       // if the prime is one less than a power of 2, return true
                       mersenne =  true;
                    }
        return mersenne;
            } // end method isMersenne
       }

this is the output of my program

 Prime numbers between 1 and 1000 are

 2 3 5 7 11 13 17 19 23 29
 31 37 41 43 47 53 59 61 67 71
 73 79 83 89 97 101 103 107 109 113
 127 131 137 139 149 151 157 163 167 173
 179 181 191 193 197 199 211 223 227 229
 233 239 241 251 257 263 269 271 277 281
 283 293 307 311 313 317 331 337 347 349
 353 359 367 373 379 383 389 397 401 409
 419 421 431 433 439 443 449 457 461 463
 467 479 487 491 499 503 509 521 523 541
 547 557 563 569 571 577 587 593 599 601
 607 613 617 619 631 641 643 647 653 659
 661 673 677 683 691 701 709 719 727 733
 739 743 751 757 761 769 773 787 797 809
 811 821 823 827 829 839 853 857 859 863
 877 881 883 887 907 911 919 929 937 941
 947 953 967 971 977 983 991 997 3*7*15*31*63*127*255*511*

 The number of primes between 1 and 1000 are 168
 The number of Mersennes is 8


问:
Sort dict within dict by Month
I have the following dictionary:

```<code>myList= {'Green Cars': {'April': 11455.0, 'March': 12210, 'February': 2559, 'August': 1439, 'July': 4921, 'January': 340, 'December': 340, 'November': 340, 'October': 306, 'September': 6},
'Yellow cars': {'April': 192914, 'March': 20187, 'February': 20994, 'January': 230625, 'December': 208422, 'November': 17914, 'October': 170835, 'September': 185357, 'July': 226697, 'May': 1852, 'August': 22096},
'Red Cars': {'April': 159, 'March': 1400, 'February': 2620, 'January': 237, 'August': 2959, 'July': 6943},...
</code>```

How do I sort each primary key ("Green Cars", "Yellow Cars", "Red Cars", etc. by month?

I've seen how to sort a dictionary by an internal dictionary where the secondary key is the same, but not when it changes.

In the end, I'm sorting these all to get a chart by month, for different cars via matplotlib.

ie.

答:
You have two issues: Sorting the nested dictionary of dicts and maintaining the sorted result in a dict. In Python, dicts are unordered.

To sort the dict of dicts that you used as an example:

```<code>import calendar
months=list(calendar.month_name)       # use a dict if you have lots of data...
myDictODicts= {'Green Cars': {'April': 11455.0, 'March': 12210, 'February': 2559, 'August': 1439, 'July': 4921, 'January': 340, 'December': 340, 'November': 340, 'October': 306, 'September': 6},
'Yellow cars': {'April': 192914, 'March': 20187, 'February': 20994, 'January': 230625, 'December': 208422, 'November': 17914, 'October': 170835, 'September': 185357, 'July': 226697, 'May': 1852, 'August': 22096},
'Red Cars': {'April': 159, 'March': 1400, 'February': 2620, 'January': 237, 'August': 2959, 'July': 6943}}

for k in myDictODicts:
    print(k, sorted(myDictODicts[k].items(), key=lambda t: months.index(t[0])))
</code>```

Prints:

```<code>Green Cars [('January', 340), ('February', 2559), ('March', 12210), ('April', 11455.0), ('July', 4921), ('August', 1439), ('September', 6), ('October', 306), ('November', 340), ('December', 340)]
Yellow cars [('January', 230625), ('February', 20994), ('March', 20187), ('April', 192914), ('May', 1852), ('July', 226697), ('August', 22096), ('September', 185357), ('October', 170835), ('November', 17914), ('December', 208422)]
Red Cars [('January', 237), ('February', 2620), ('March', 1400), ('April', 159), ('July', 6943), ('August', 2959)]
</code>```

You can either use the list of tuples or recreate a dict directly using those.
With Python 3.6, you can turn that sorted list of tuples back into a dict that will maintain its insertion order. You can also use an OrderedDict that will appear to the rest of your code as a dict would.

Example:

```<code>from collections import OrderedDict
nd={}
for k in myDictODicts:
    nd[k]=OrderedDict(sorted(myDictODicts[k].items(), key=lambda t: months.index(t[0])))

>>> nd
{'Green Cars': OrderedDict([('January', 340), ('February', 2559), ('March', 12210), ('April', 11455.0), ('July', 4921), ('August', 1439), ('September', 6), ('October', 306), ('November', 340), ('December', 340)]), 'Yellow cars': OrderedDict([('January', 230625), ('February', 20994), ('March', 20187), ('April', 192914), ('May', 1852), ('July', 226697), ('August', 22096), ('September', 185357), ('October', 170835), ('November', 17914), ('December', 208422)]), 'Red Cars': OrderedDict([('January', 237), ('February', 2620), ('March', 1400), ('April', 159), ('July', 6943), ('August', 2959)])}
</code>```

Title: Sort dict within dict by Month

Body:
I have the following dictionary:

myList= {'Green Cars': {'April': 11455.0, 'March': 12210, 'February': 2559, 'August': 1439, 'July': 4921, 'January': 340, 'December': 340, 'November': 340, 'October': 306, 'September': 6},
'Yellow cars': {'April': 192914, 'March': 20187, 'February': 20994, 'January': 230625, 'December': 208422, 'November': 17914, 'October': 170835, 'September': 185357, 'July': 226697, 'May': 1852, 'August': 22096},
'Red Cars': {'April': 159, 'March': 1400, 'February': 2620, 'January': 237, 'August': 2959, 'July': 6943},...

How do I sort each primary key ("Green Cars", "Yellow Cars", "Red Cars", etc. by month?

I've seen how to sort a dictionary by an internal dictionary where the secondary key is the same, but not when it changes.

In the end, I'm sorting these all to get a chart by month, for different cars via matplotlib.

ie.

Body:
You have two issues: Sorting the nested dictionary of dicts and maintaining the sorted result in a dict. In Python, dicts are unordered.

To sort the dict of dicts that you used as an example:

import calendar
months=list(calendar.month_name)       # use a dict if you have lots of data...
myDictODicts= {'Green Cars': {'April': 11455.0, 'March': 12210, 'February': 2559, 'August': 1439, 'July': 4921, 'January': 340, 'December': 340, 'November': 340, 'October': 306, 'September': 6},
'Yellow cars': {'April': 192914, 'March': 20187, 'February': 20994, 'January': 230625, 'December': 208422, 'November': 17914, 'October': 170835, 'September': 185357, 'July': 226697, 'May': 1852, 'August': 22096},
'Red Cars': {'April': 159, 'March': 1400, 'February': 2620, 'January': 237, 'August': 2959, 'July': 6943}}

for k in myDictODicts:
    print(k, sorted(myDictODicts[k].items(), key=lambda t: months.index(t[0])))

Prints:

Green Cars [('January', 340), ('February', 2559), ('March', 12210), ('April', 11455.0), ('July', 4921), ('August', 1439), ('September', 6), ('October', 306), ('November', 340), ('December', 340)]
Yellow cars [('January', 230625), ('February', 20994), ('March', 20187), ('April', 192914), ('May', 1852), ('July', 226697), ('August', 22096), ('September', 185357), ('October', 170835), ('November', 17914), ('December', 208422)]
Red Cars [('January', 237), ('February', 2620), ('March', 1400), ('April', 159), ('July', 6943), ('August', 2959)]

You can either use the list of tuples or recreate a dict directly using those.
With Python 3.6, you can turn that sorted list of tuples back into a dict that will maintain its insertion order. You can also use an OrderedDict that will appear to the rest of your code as a dict would.

Example:

from collections import OrderedDict
nd={}
for k in myDictODicts:
    nd[k]=OrderedDict(sorted(myDictODicts[k].items(), key=lambda t: months.index(t[0])))

>>> nd
{'Green Cars': OrderedDict([('January', 340), ('February', 2559), ('March', 12210), ('April', 11455.0), ('July', 4921), ('August', 1439), ('September', 6), ('October', 306), ('November', 340), ('December', 340)]), 'Yellow cars': OrderedDict([('January', 230625), ('February', 20994), ('March', 20187), ('April', 192914), ('May', 1852), ('July', 226697), ('August', 22096), ('September', 185357), ('October', 170835), ('November', 17914), ('December', 208422)]), 'Red Cars': OrderedDict([('January', 237), ('February', 2620), ('March', 1400), ('April', 159), ('July', 6943), ('August', 2959)])}


问:
Undesired backslashes when reading a html with rvest
I am trying to read a website using rvest, my code as follows:

```<code>pg <- read_html("https://www.gob.mx/presidencia/archivo/prensa?utf8=%E2%9C%93&idiom=es&style=list&order=DESC&filter_id=&filter_origin=archive&tags=&year=&category=Discursos+del+Presidente&year=&category=Discursos+del+Presidente")
</code>```

However, when I read "pg" I get double backslashes between html-classes, like in the following snippet:

```<code><a class='\\"small-link\\"' href="%5C%22/presidencia/es/prensa/epn-palabras-134612?idiom=es%5C%22" target='\\"_blank\\"'>
</code>```

This does not occur when I read other websites:

```<code>pg2 <- read_html("http://www.imdb.com/title/tt0245712/")
#output: <head>\n<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">\n
</code>```

Any idea why this might happen? I really want to get rid of it, since it hinders me from retrieving data with html_nodes():

```<code>pg  %>%
  html_nodes(".small-link")
#output: {xml_nodeset (0)}
</code>```

Update!

This error seems to happen only when using rvest with Mexican IPs :/

Following a suggestion below, I tried using regex to clean my object ("pg").

So when looking at pg div classes have these double backslashes like this:

```<code>pg
#Result: <div class='\\"col-md-12' small-bottom-buffer>
</code>```

If I clean pg trying to delete one backslash it seems to work and I only have one left:

```<code>pg2 <- gsub("\\\\", "", pg)
pg2
#Result: <div class='\"col-md-12' small-bottom-buffer>
</code>```

However, if I try to delete both backslashes, I get three back instead!:

```<code>pg3 <- gsub("\\\\\\\\", "", pg)
pg3
#<div class='\\\"col-md-12' small-bottom-buffer>
</code>```

I don't understand this behaviour

答:
I'm not familiar enough with rvest to provide an rvest solution, but you can use readLines and grep to find the data you're looking for. You can then use REGEX to clean it up

```<code>pg3 <- readLines("https://www.gob.mx/presidencia/archivo/prensa?utf8=%E2%9C%93&idiom=es&style=list&order=DESC&filter_id=&filter_origin=archive&tags=&year=&category=Discursos+del+Presidente&year=&category=Discursos+del+Presidente")

grep('<a class=\"small-link\"', pg3, value = TRUE)
grep('<a class="small-link"', pg3, value = TRUE)
grep('<a class=\\"small-link\\"', pg3, value = TRUE)
</code>```

All three work. The reason you are seeing \" is because \ is an escape character, and " is a special character since it's used to input character data into R. For example:

```<code>> print("test"test")
Error: unexpected symbol in "print("test"test"
> print('test"test')
[1] "test\"test"
> print("test\"test")
[1] "test\"test"
</code>```

Body:
I am trying to read a website using rvest, my code as follows:

pg <- read_html("https://www.gob.mx/presidencia/archivo/prensa?utf8=%E2%9C%93&idiom=es&style=list&order=DESC&filter_id=&filter_origin=archive&tags=&year=&category=Discursos+del+Presidente&year=&category=Discursos+del+Presidente")

However, when I read "pg" I get double backslashes between html-classes, like in the following snippet:

This does not occur when I read other websites:

pg2 <- read_html("http://www.imdb.com/title/tt0245712/")
#output: \n<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">\n

Any idea why this might happen? I really want to get rid of it, since it hinders me from retrieving data with html_nodes():

pg  %>%
  html_nodes(".small-link")
#output: {xml_nodeset (0)}

Update!

This error seems to happen only when using rvest with Mexican IPs :/

Following a suggestion below, I tried using regex to clean my object ("pg").

So when looking at pg div classes have these double backslashes like this:

pg
#Result:

If I clean pg trying to delete one backslash it seems to work and I only have one left:

pg2 <- gsub("\\\\", "", pg)
pg2
#Result:

However, if I try to delete both backslashes, I get three back instead!:

pg3 <- gsub("\\\\\\\\", "", pg)
pg3
#

I don't understand this behaviour

Body:
I'm not familiar enough with rvest to provide an rvest solution, but you can use readLines and grep to find the data you're looking for. You can then use REGEX to clean it up

pg3 <- readLines("https://www.gob.mx/presidencia/archivo/prensa?utf8=%E2%9C%93&idiom=es&style=list&order=DESC&filter_id=&filter_origin=archive&tags=&year=&category=Discursos+del+Presidente&year=&category=Discursos+del+Presidente")

grep('<a class=\"small-link\"', pg3, value = TRUE)
grep('<a class="small-link"', pg3, value = TRUE)
grep('<a class=\\"small-link\\"', pg3, value = TRUE)

All three work. The reason you are seeing \" is because \ is an escape character, and " is a special character since it's used to input character data into R. For example:

> print("test"test")
Error: unexpected symbol in "print("test"test"
> print('test"test')
[1] "test\"test"
> print("test\"test")
[1] "test\"test"


问:
Design a selection program using C

Brief Description

I am currently writing a program that allows users to select via arrow keys, when done selecting, hit 'enter', it then proceeds to the next question etc.

I have done the selection process using the code below :

```<code>int first_selection(int i){
    while (ch != 0xD)
        {
        ch = _getch ();
        if (ch == 0 || ch == 224)
            {
                switch (_getch ())
                    {
                        case 75:
                        system("cls");
                        left_option();
                        i=1;
                        break;

                        case 77:
                        system("cls");
                        right_option();
                        i=0;
                        break;

                    }
            }
        }
 return i;
}
</code>```

but this only works for one selection, when I write the second question below the first one, it will skip the second question like this :

```<code>first_selection();
printf("%d",i);
second_selection();
printf("%d",j);
</code>```

I've tried nested while loop but using this will only allow me to press right or left arrow key once, then it will automatically skip to the second question due to getch.

I was wondering if someone can tell me how to design such selection program...

Desired Results

After three selections, it will then output strings according to the user's selection.

Ex:

Input

User selects left option in the first question

User selects right option in second question

User selects right option in third question

Ouput

Left

Right

Right

Full Code

```<code>void firstR_option(void);
void firstR_option(void);
void secondL_option(void);
void secondR_option(void);

int ch,i,j;
int main(int argc, char const *argv[])
{
firstL_selection();
first_selection();
second_selection();
printf("%d%d",i,j);

return 0;
}

void firstL_option(void){
    printf("LEFT\n");
}

void firstR_option(void){
printf("RIGHT\n");
}

void secondL_option(void){
printf("LEFT\n");
}

void secondR_bread(void){
printf("RIGHT\n");
}

int first_selection(int i){
    while (ch != 0xD)
        {
        ch = _getch ();
        if (ch == 0 || ch == 224)
            {
             switch (_getch ())
                    {
                        case 75:
                        system("cls");
                        firstL_option();
                        i=1;
                        break;

                        case 77:
                        system("cls");
                        firstR_option();
                        i=0;
                        break;

                    }
            }
        }
return i;
}

int second_selection(int j){
    while (ch != 0xD)
        {
        ch = _getch ();
        if (ch == 0 || ch == 224)
            {
                switch (_getch ())
                    {
                        case 75:
                        system("cls");
                        secondL_option();
                        j=1;
                        break;

                        case 77:
                        system("cls");
                        secondR_option();
                        j=0;
                        break;

                    }
            }
        }
 return j;
}
</code>```

答:
I did not debug your code but I believe the reason why it skips the second question is that there is still something left in stdin and you need to somehow discard that.

Something like this will do the trick:

```<code>while((c = getchar()) != '\n' && c != EOF);
</code>```

The other important thing is arrow keys are special characters and the way you get those values depend on the OS and compiler you have. I am also using macOS Sierra (with gcc) and I had to figure out what characters I get when I press an arrow key with simple getchar() followed by printf() functions.

So for the left arrow key for example, I get: ESC, [, and 'C'.

Then I set-up my function based on that little experiment I did.

Lastly, you can use an array for the answers. This way it is easier to use loops.

Here is the full code (I left some of the error-checking to you):

```<code>#include <stdio.h>

#define UP    65  // A
#define DOWN  66  // B
#define LEFT  68  // C
#define RIGHT 67  // D

int getUserInput()
{
  int c = getchar();
  int retVal = 0;

  if (c == 27)  // ESC
  {
    c = getchar();
    if (c == 91) // [
    {
      c = getchar();
      if (c == UP || c == DOWN || c == LEFT || c == RIGHT)
      {
        retVal = c;
      }
    }
  }
  // Discard what is left in stdin
  while((c = getchar()) != '\n' && c != EOF);
  return retVal;
}

void printSelection(int selection)
{
  switch (selection)
  {
    case 65:
      printf("You pressed the UP KEY\n");
      break;
    case 66:
      printf("You pressed the DOWN KEY\n");
      break;
    case 67:
      printf("You pressed the RIGHT KEY\n");
      break;
    case 68:
      printf("You pressed the LEFT KEY\n");
      break;
    default:
      printf("Invalid input!\n");
      break;
  }
}

int main ()
{
  const int numOfQuestions = 3;
  int ansArr[numOfQuestions];
  int cnt = 0;

  for (cnt = 0; cnt < numOfQuestions; cnt++)
  {
    printf("Please press an arrow key: \n");
    ansArr[cnt] = getUserInput();
  }

  for (cnt = 0; cnt < numOfQuestions; cnt++)
  {
    printSelection(ansArr[cnt]);
  }
  return 0;
}
</code>```

Here is the console output:

```<code>Please press an arrow key:
^[[D
Please press an arrow key:
^[[A
Please press an arrow key:
^[[C
You pressed the LEFT KEY
You pressed the UP KEY
You pressed the RIGHT KEY
</code>```

Update

What you can do is wait for DLE (Data Link Escape) character. This way you can allow the user to enter multiple inputs. Then you can simply save the last input.

Here is the updated function:

```<code>int getUserInput()
{
  int c = getchar();
  int retVal = 0;

  while (c != 10) // DLE
  {
    if (c == 27)  // ESC
    {
      c = getchar();
      if (c == 91) // [
      {
        c = getchar();
        if (c == UP || c == DOWN || c == LEFT || c == RIGHT)
        {
          retVal = c;  // This is the last valid (arrow key) input
          c = getchar();
        }
      }
    }
  }
  return retVal;
}
</code>```

Here is the sample output:

```<code>Please press an arrow key:
^[[C
Please press an arrow key:
^[[D^[[B^[[A^[[C
Please press an arrow key:
^[[B^[[B^[[A^[[C^[[D^[[C
You pressed the RIGHT KEY
You pressed the RIGHT KEY
You pressed the RIGHT KEY
</code>```

You need to check for some invalid inputs and do some error-handling but that's the idea.

Hope this helps,

Baris

Title: Design a selection program using C

Body:
Brief Description

I am currently writing a program that allows users to select via arrow keys, when done selecting, hit 'enter', it then proceeds to the next question etc.

I have done the selection process using the code below :

int first_selection(int i){
    while (ch != 0xD)
        {
        ch = _getch ();
        if (ch == 0 || ch == 224)
            {
                switch (_getch ())
                    {
                        case 75:
                        system("cls");
                        left_option();
                        i=1;
                        break;

                        case 77:
                        system("cls");
                        right_option();
                        i=0;
                        break;

                    }
            }
        }
 return i;
}

but this only works for one selection, when I write the second question below the first one, it will skip the second question like this :

first_selection();
printf("%d",i);
second_selection();
printf("%d",j);

I've tried nested while loop but using this will only allow me to press right or left arrow key once, then it will automatically skip to the second question due to getch.

I was wondering if someone can tell me how to design such selection program...

Desired Results

After three selections, it will then output strings according to the user's selection.

Ex:

Input

User selects left option in the first question

User selects right option in second question

User selects right option in third question

Ouput

Left

Right

Right

Full Code

void firstR_option(void);
void firstR_option(void);
void secondL_option(void);
void secondR_option(void);

int ch,i,j;
int main(int argc, char const *argv[])
{
firstL_selection();
first_selection();
second_selection();
printf("%d%d",i,j);

return 0;
}

void firstL_option(void){
    printf("LEFT\n");
}

void firstR_option(void){
printf("RIGHT\n");
}

void secondL_option(void){
printf("LEFT\n");
}

void secondR_bread(void){
printf("RIGHT\n");
}

int first_selection(int i){
    while (ch != 0xD)
        {
        ch = _getch ();
        if (ch == 0 || ch == 224)
            {
             switch (_getch ())
                    {
                        case 75:
                        system("cls");
                        firstL_option();
                        i=1;
                        break;

                        case 77:
                        system("cls");
                        firstR_option();
                        i=0;
                        break;

                    }
            }
        }
return i;
}

int second_selection(int j){
    while (ch != 0xD)
        {
        ch = _getch ();
        if (ch == 0 || ch == 224)
            {
                switch (_getch ())
                    {
                        case 75:
                        system("cls");
                        secondL_option();
                        j=1;
                        break;

                        case 77:
                        system("cls");
                        secondR_option();
                        j=0;
                        break;

                    }
            }
        }
 return j;
}

Body:
I did not debug your code but I believe the reason why it skips the second question is that there is still something left in stdin and you need to somehow discard that.

Something like this will do the trick:

while((c = getchar()) != '\n' && c != EOF);

The other important thing is arrow keys are special characters and the way you get those values depend on the OS and compiler you have. I am also using macOS Sierra (with gcc) and I had to figure out what characters I get when I press an arrow key with simple getchar() followed by printf() functions.

So for the left arrow key for example, I get: ESC, [, and 'C'.

Then I set-up my function based on that little experiment I did.

Lastly, you can use an array for the answers. This way it is easier to use loops.

Here is the full code (I left some of the error-checking to you):

#include <stdio.h>

#define UP    65  // A
#define DOWN  66  // B
#define LEFT  68  // C
#define RIGHT 67  // D

int getUserInput()
{
  int c = getchar();
  int retVal = 0;

  if (c == 27)  // ESC
  {
    c = getchar();
    if (c == 91) // [
    {
      c = getchar();
      if (c == UP || c == DOWN || c == LEFT || c == RIGHT)
      {
        retVal = c;
      }
    }
  }
  // Discard what is left in stdin
  while((c = getchar()) != '\n' && c != EOF);
  return retVal;
}

void printSelection(int selection)
{
  switch (selection)
  {
    case 65:
      printf("You pressed the UP KEY\n");
      break;
    case 66:
      printf("You pressed the DOWN KEY\n");
      break;
    case 67:
      printf("You pressed the RIGHT KEY\n");
      break;
    case 68:
      printf("You pressed the LEFT KEY\n");
      break;
    default:
      printf("Invalid input!\n");
      break;
  }
}

int main ()
{
  const int numOfQuestions = 3;
  int ansArr[numOfQuestions];
  int cnt = 0;

  for (cnt = 0; cnt < numOfQuestions; cnt++)
  {
    printf("Please press an arrow key: \n");
    ansArr[cnt] = getUserInput();
  }

  for (cnt = 0; cnt < numOfQuestions; cnt++)
  {
    printSelection(ansArr[cnt]);
  }
  return 0;
}

Here is the console output:

Please press an arrow key:
^[[D
Please press an arrow key:
^[[A
Please press an arrow key:
^[[C
You pressed the LEFT KEY
You pressed the UP KEY
You pressed the RIGHT KEY

Update

What you can do is wait for DLE (Data Link Escape) character. This way you can allow the user to enter multiple inputs. Then you can simply save the last input.

Here is the updated function:

int getUserInput()
{
  int c = getchar();
  int retVal = 0;

  while (c != 10) // DLE
  {
    if (c == 27)  // ESC
    {
      c = getchar();
      if (c == 91) // [
      {
        c = getchar();
        if (c == UP || c == DOWN || c == LEFT || c == RIGHT)
        {
          retVal = c;  // This is the last valid (arrow key) input
          c = getchar();
        }
      }
    }
  }
  return retVal;
}

Here is the sample output:

Please press an arrow key:
^[[C
Please press an arrow key:
^[[D^[[B^[[A^[[C
Please press an arrow key:
^[[B^[[B^[[A^[[C^[[D^[[C
You pressed the RIGHT KEY
You pressed the RIGHT KEY
You pressed the RIGHT KEY

You need to check for some invalid inputs and do some error-handling but that's the idea.

Hope this helps,

Baris


问:
GWT Special Features compared to other Frameworks
I am on searching special features of GWT which are present only in GWT and not in other web framework. I am a student and I am not well acquainted to the many web frameworks on the market, so if u can help me increasing my list of special GWT features, it would be a great help. Some which i know are:

```<code> 1. GWT allows using java to program
web. (only, it also allows merging
javascript through JSNI of course)

2. The developer does not have to be a guru in browser incompatibilities
to develop web sites which works on
a variety of browsers because
incompatibilities are handled by GWT
through differed bindind

3. GWT allows easy integration of popular Java Tools such as ,
hibernate through gilead

4. GWT enables server implementation not only in java but also other
languages such as php

5. GWT enables code splitting which improves application interactivity
by allowing javaScript file to
download only when required

6. In essence GWT is toolkit, it does not force a way to program,
other layers can be placed on top of
it to program such as placing MVP or
MVC framework on top of GWT and then
develop app

7. GWT MVP is great because first it allows collaborative working, faster
testing with JUnit and the event bus
allows many updates in client side
application by placing event on the
event bus

8. GWT compiled java files to obfuscated mode which is first small
and make the application safer
because bots fails on the javascript
generated during the obfuscated mode
</code>```

In case in the 8 points, i've mention something which not special to GWT, then let me know.

答:
There are other, more important/wider accepted GUI-Frameworks that are based on Java.
There are for example Struts and JSF. That's why some of your points don't fit only for GWT, but for all GUI java frameworks in general, e.g. bullet point 1, 2 & 3.

But to add another one:
I think GWT is an easy way to code an AJAX-application, because it hides the AJAX stuff quite well. Wouldn't you agree?

Furthermore, GWT is a proprietary framework (which is somehow a unique property). JSF is standardized and Struts is lead by Apache.

Body:
I am on searching special features of GWT which are present only in GWT and not in other web framework. I am a student and I am not well acquainted to the many web frameworks on the market, so if u can help me increasing my list of special GWT features, it would be a great help. Some which i know are:

 1. GWT allows using java to program
web. (only, it also allows merging
javascript through JSNI of course)

2. The developer does not have to be a guru in browser incompatibilities
to develop web sites which works on
a variety of browsers because
incompatibilities are handled by GWT
through differed bindind

3. GWT allows easy integration of popular Java Tools such as ,
hibernate through gilead

4. GWT enables server implementation not only in java but also other
languages such as php

5. GWT enables code splitting which improves application interactivity
by allowing javaScript file to
download only when required

6. In essence GWT is toolkit, it does not force a way to program,
other layers can be placed on top of
it to program such as placing MVP or
MVC framework on top of GWT and then
develop app

7. GWT MVP is great because first it allows collaborative working, faster
testing with JUnit and the event bus
allows many updates in client side
application by placing event on the
event bus

8. GWT compiled java files to obfuscated mode which is first small
and make the application safer
because bots fails on the javascript
generated during the obfuscated mode

In case in the 8 points, i've mention something which not special to GWT, then let me know.


问:
how do i pass arrays in java
I am trying to compare to arrays defined in the main method and need to pass them to the compareAnswers method how do I do this?

here is my code:

```<code>/**********************************************
 *
 * Daniel Wilson
 *
 * CIS129
 *
 * November 15 2017
 *
 * Compaires test answers against correct answers
 *
 * ********************************************/

import java.io.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;

public class CIS129_DanielWilson_PC6 {

public static void main(String args[]) {

  final int SIZE = 20;
  String[] givenAnswers = new String[SIZE];
  String[] correctAnswers =      { "B", "D", "A", "A", "C", "A", "B", "A", "C", "D", "B",  "C", "D", "A", "D", "C    ", "C", "B", "D", "A"};
  String answers = compareAnswers();

  InputStreamReader input = new InputStreamReader(System.in);
  BufferedReader reader = new BufferedReader(input);

  try{
    System.out.println(Arrays.toString(correctAnswers));
    for (int i = 0; i<SIZE; i++) {
    System.out.println("please enter your answer for question " + (i+1));
      givenAnswers[i] = reader.readLine();
    }
  }catch (IOException e){
            System.out.println("Error reading from user");
      }
}
public static String compareAnswers(){

List<String> tempList = new ArrayList<String>();
for(int i = 0; i < correctAnswers.length; i++)
{
    boolean foundString = false;
    for(int j = 0; j < givenAnswers.length; j++)
    {
        if(givenAnswers[j].equals(correctAnswers[i]))
        {
            foundString = true;
            break;
        }
    }
    if(!foundString)
        tempList.add(givenAnswers[i]);
}
String ammountRight[] = tempList.toArray(new String[0]);
for(int i = 0; i < ammountRight.length; i++)
{
    System.out.println(ammountRight[i]);
  }
 }
}
</code>```

I understand I need to pass by reference but my professor didn't cover that in much detail. any help is appreciated.

答:
Like this</p>

```<code>public static String compareAnswers(ArrayList<String> firstArray, ArrayList<String> secondArray)
</code>```

Title: how do i pass arrays in java

Body:
I am trying to compare to arrays defined in the main method and need to pass them to the compareAnswers method how do I do this?

here is my code:

/**********************************************
 *
 * Daniel Wilson
 *
 * CIS129
 *
 * November 15 2017
 *
 * Compaires test answers against correct answers
 *
 * ********************************************/

import java.io.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;

public class CIS129_DanielWilson_PC6 {

public static void main(String args[]) {

  final int SIZE = 20;
  String[] givenAnswers = new String[SIZE];
  String[] correctAnswers =      { "B", "D", "A", "A", "C", "A", "B", "A", "C", "D", "B",  "C", "D", "A", "D", "C    ", "C", "B", "D", "A"};
  String answers = compareAnswers();

  InputStreamReader input = new InputStreamReader(System.in);
  BufferedReader reader = new BufferedReader(input);

  try{
    System.out.println(Arrays.toString(correctAnswers));
    for (int i = 0; i<SIZE; i++) {
    System.out.println("please enter your answer for question " + (i+1));
      givenAnswers[i] = reader.readLine();
    }
  }catch (IOException e){
            System.out.println("Error reading from user");
      }
}
public static String compareAnswers(){

List<String> tempList = new ArrayList<String>();
for(int i = 0; i < correctAnswers.length; i++)
{
    boolean foundString = false;
    for(int j = 0; j < givenAnswers.length; j++)
    {
        if(givenAnswers[j].equals(correctAnswers[i]))
        {
            foundString = true;
            break;
        }
    }
    if(!foundString)
        tempList.add(givenAnswers[i]);
}
String ammountRight[] = tempList.toArray(new String[0]);
for(int i = 0; i < ammountRight.length; i++)
{
    System.out.println(ammountRight[i]);
  }
 }
}

I understand I need to pass by reference but my professor didn't cover that in much detail. any help is appreciated.

Body:
Like this

public static String compareAnswers(ArrayList<String> firstArray, ArrayList<String> secondArray)


问:
Simple nginx/Angular project force HTTPS
I have a really simple Docker container running an Angular app in nginx v1.13 that I want to enforce HTTPS on.

I've tried setting rewrite rules but I either only get it working on the root domain (ie: http://myapp.com -> https://myapp.com), but not on pages (ie: http://myapp.com/login stays http)

I've tried different combos of $localhost, $host, $server_name, and $request_uri but I usually end up with a 'too many redirects' error.

My domain has an SSL certificate that is working with other apps hosted in IIS, so I'm pretty sure it's just my nginx config.

Here is the config file (unchanged from the image):

```</p>

<p>server {
    listen       80;
    server_name  localhost;</p>

```#charset koi8-r;
#access_log  /var/log/nginx/host.access.log  main;

location / {
    root   /usr/share/nginx/html;
    index  index.html index.htm;
    try_files $uri $uri/ /index.html;
}

location /(assets)/  {
    gzip_static on;
    gzip_types text/plain text/xml text/css
    text/comma-separated-values
    text/javascript application/x-javascript
    application/atom+xml;

    expires off;
}
#error_page  404              /404.html;

# redirect server error pages to the static page /50x.html
#
error_page   500 502 503 504  /50x.html;
location = /50x.html {
    root   /usr/share/nginx/html;
}

# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
#    proxy_pass   http://127.0.0.1;
#}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
#    root           html;
#    fastcgi_pass   127.0.0.1:9000;
#    fastcgi_index  index.php;
#    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
#    include        fastcgi_params;
#}

# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
#    deny  all;
#}
```

<p>}</p>

<p>```

UPDATE:

Thanks for the help, but it turned out to be an Azure configuration problem. I had to set the Custom Domains options to allow SSL Redirect.

When running the container locally, the suggestion from @MatTheWhale seemed to have an impact on my service, although I can't 100% confirm it since localhost is never a true replica of a domain

答:
For HTTPS forcing, I usually add something like this in my conf:

```<code>server {
    listen 80;
    server_name myapp.com;
    return 301 https://$host$request_uri;
}
</code>```

Then make another server block for where the HTTP requests will get redirected to, and move all the actual configurations there:

```<code>server {
    listen 443;
    server_name myapp.com;

    # Move all your location blocks here
}
</code>```

Body:
I have a really simple Docker container running an Angular app in nginx v1.13 that I want to enforce HTTPS on.

I've tried setting rewrite rules but I either only get it working on the root domain (ie: http://myapp.com -> https://myapp.com), but not on pages (ie: http://myapp.com/login stays http)

I've tried different combos of $localhost, $host, $server_name, and $request_uri but I usually end up with a 'too many redirects' error.

My domain has an SSL certificate that is working with other apps hosted in IIS, so I'm pretty sure it's just my nginx config.

Here is the config file (unchanged from the image):

```</p>

<p>server {
    listen       80;
    server_name  localhost;</p>

<pre><code>#charset koi8-r;
#access_log  /var/log/nginx/host.access.log  main;

location / {
    root   /usr/share/nginx/html;
    index  index.html index.htm;
    try_files $uri $uri/ /index.html;
}

location /(assets)/  {
    gzip_static on;
    gzip_types text/plain text/xml text/css
    text/comma-separated-values
    text/javascript application/x-javascript
    application/atom+xml;

    expires off;
}
#error_page  404              /404.html;

# redirect server error pages to the static page /50x.html
#
error_page   500 502 503 504  /50x.html;
location = /50x.html {
    root   /usr/share/nginx/html;
}

# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
#    proxy_pass   http://127.0.0.1;
#}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
#    root           html;
#    fastcgi_pass   127.0.0.1:9000;
#    fastcgi_index  index.php;
#    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
#    include        fastcgi_params;
#}

# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
#    deny  all;
#}
</code></pre>

<p>}</p>

<p>```

UPDATE:

Thanks for the help, but it turned out to be an Azure configuration problem. I had to set the Custom Domains options to allow SSL Redirect.

When running the container locally, the suggestion from @MatTheWhale seemed to have an impact on my service, although I can't 100% confirm it since localhost is never a true replica of a domain

Body:
For HTTPS forcing, I usually add something like this in my conf:

server {
    listen 80;
    server_name myapp.com;
    return 301 https://$host$request_uri;
}

Then make another server block for where the HTTP requests will get redirected to, and move all the actual configurations there:

server {
    listen 443;
    server_name myapp.com;

    # Move all your location blocks here
}


问:
Create Pandas Dataframe from List of Dictionaries with missing values for some keys
everyone.

Below is the code I'm using to parse a text file:

```<code>import pandas as pd

tags = ['129','30','32','851','9730','9882']
rows = []

file = open('D:\\python\\redi_fix\\redi_august.txt','r')
content = file.readlines()
for line in content:
    for message in line.split('\t'):
        try:
            row_dict = {}
            tag,val = message.split('=')
            if tag in tags:
                row_dict[tag]=val
                rows.append(row_dict)
        except:
            pass
</code>```

Creating a pandas dataframe from rows yields the following result:

```<code>129     30      32      851     9730    9882
r170557 NaN     NaN     NaN     NaN     NaN
NaN     ARCA    NaN     NaN     NaN     NaN
NaN     NaN     100     NaN     NaN     NaN
r170557 NaN     NaN     NaN     NaN     NaN
NaN     ARCA    NaN     NaN     NaN     NaN
NaN     NaN     300     NaN     NaN     NaN
</code>```

Looks like every value for a key is on a different row.
The result I'm struggling to achieve is all values to be on the same row - see below for example:

```<code>129     30      32      851     9730    9882
r170557 ARCA    100     NaN     NaN     NaN
r170557 ARCA    300     NaN     NaN     NaN
</code>```

答:
If you want to "collapse" your NaNs, you can perform a groupby + agg on first/last:

```<code>df.groupby(df['129'].notnull().cumsum(), as_index=False).agg('first')

       129    30     32  851  9730  9882
0  r170557  ARCA  100.0  NaN   NaN   NaN
1  r170557  ARCA  300.0  NaN   NaN   NaN
</code>```

ContentLicense: CC BY-SA 4.0

Body:
everyone.

Below is the code I'm using to parse a text file:

import pandas as pd

tags = ['129','30','32','851','9730','9882']
rows = []

file = open('D:\\python\\redi_fix\\redi_august.txt','r')
content = file.readlines()
for line in content:
    for message in line.split('\t'):
        try:
            row_dict = {}
            tag,val = message.split('=')
            if tag in tags:
                row_dict[tag]=val
                rows.append(row_dict)
        except:
            pass

Creating a pandas dataframe from rows yields the following result:

129     30      32      851     9730    9882
r170557 NaN     NaN     NaN     NaN     NaN
NaN     ARCA    NaN     NaN     NaN     NaN
NaN     NaN     100     NaN     NaN     NaN
r170557 NaN     NaN     NaN     NaN     NaN
NaN     ARCA    NaN     NaN     NaN     NaN
NaN     NaN     300     NaN     NaN     NaN

Looks like every value for a key is on a different row.
The result I'm struggling to achieve is all values to be on the same row - see below for example:

129     30      32      851     9730    9882
r170557 ARCA    100     NaN     NaN     NaN
r170557 ARCA    300     NaN     NaN     NaN

Body:
If you want to "collapse" your NaNs, you can perform a groupby + agg on first/last:

df.groupby(df['129'].notnull().cumsum(), as_index=False).agg('first')

       129    30     32  851  9730  9882
0  r170557  ARCA  100.0  NaN   NaN   NaN
1  r170557  ARCA  300.0  NaN   NaN   NaN


答:
Using your result dataframe, we need sorted and dropna

```<code>result.apply(lambda x : sorted(x,key=pd.isnull)).dropna(thresh=1)
Out[1171]:
       129    30     32  851  9730  9882
0  r170557  ARCA  100.0  NaN   NaN   NaN
1  r170557  ARCA  300.0  NaN   NaN   NaN
</code>```

Title: Create Pandas Dataframe from List of Dictionaries with missing values for some keys

Body:
Using your result dataframe, we need sorted and dropna

result.apply(lambda x : sorted(x,key=pd.isnull)).dropna(thresh=1)
Out[1171]:
       129    30     32  851  9730  9882
0  r170557  ARCA  100.0  NaN   NaN   NaN
1  r170557  ARCA  300.0  NaN   NaN   NaN


问:
Processing Checkbox Group into String
I have a form which contains a series of checkboxes, in a group. Here is the HTML -

```<code><input type="checkbox" name="p_contents[]" value="Value 1" />
<input type="checkbox" name="p_contents[]" value="Value 2" />
<input type="checkbox" name="p_contents[]" value="Value 3" />
<input type="checkbox" name="p_contents[]" value="Value 4" />
<input type="checkbox" name="p_contents[]" value="Value 5" />
</code>```

And I wish to process this with javascript -

```<code>var contents;
for(var i=0; i < document.forms['addForm'].elements['p_contents[]'].length; i++){
    if(i != (document.forms['addForm'].elements['p_contents[]'].length - 1)){
        if(document.forms['addForm'].elements['p_contents[]'].checked){
            contents += encodeURIComponent(document.forms['addForm'].elements['p_contents[]'][i].value) + ",";
        }
    }else{
        if(document.forms['addForm'].elements['p_contents[]'][i].checked){
            contents += encodeURIComponent(document.forms['addForm'].elements['p_contents[]'][i].value);
        }
    }
}
</code>```

I'm sure the problem is with the enumeration:

```<code>document.forms['addForm'].elements['p_contents[]'][i].checked
</code>```

Is this the correct way to process a grouped checkbox form?

答:
You have several checkboxes with the same name. You can't easily access them by name. Add a unique id to each and use document.getElementById(). Note that form.elements[] is indexed by integer, not name, and scans through every element on a form.

Also, if you assign a long repeating expression to a short-named var and then use that short name, it significantly improves readability of your code.

Title: Processing Checkbox Group into String

Body:
I have a form which contains a series of checkboxes, in a group. Here is the HTML -

<input type="checkbox" name="p_contents[]" value="Value 1" />
<input type="checkbox" name="p_contents[]" value="Value 2" />
<input type="checkbox" name="p_contents[]" value="Value 3" />
<input type="checkbox" name="p_contents[]" value="Value 4" />
<input type="checkbox" name="p_contents[]" value="Value 5" />

And I wish to process this with javascript -

var contents;
for(var i=0; i < document.forms['addForm'].elements['p_contents[]'].length; i++){
    if(i != (document.forms['addForm'].elements['p_contents[]'].length - 1)){
        if(document.forms['addForm'].elements['p_contents[]'].checked){
            contents += encodeURIComponent(document.forms['addForm'].elements['p_contents[]'][i].value) + ",";
        }
    }else{
        if(document.forms['addForm'].elements['p_contents[]'][i].checked){
            contents += encodeURIComponent(document.forms['addForm'].elements['p_contents[]'][i].value);
        }
    }
}

I'm sure the problem is with the enumeration:

document.forms['addForm'].elements['p_contents[]'][i].checked

Is this the correct way to process a grouped checkbox form?


问:
VBA Select Multiple Tabs in Spreadsheet using code
I have a spreadsheet with 3 tabs. I need the following code to select the first two tabs. I almost have it but the Sheets(Array(c)).Select portion returns an error. Essentially i need the last section to return as Sheets(Array("Sheet1", "Sheet2")).Select

```<code>Sub HideUnhide2()
Dim a As String
Dim b As Double
Dim c As String
Application.Calculation = xlManual
        For I = 1 To 100
            If Range("d5") <> "Entity:" Then Exit For
            'Start
            c = c & ", " & Chr(34) & ActiveSheet.Name & Chr(34)

            'End
            b = b + 1

            ActiveSheet.Next.Select
        Next I
    '   End If
           c = Right(c, Len(c) - 2)
           MsgBox c
           Sheets(Array(c)).Select

Application.Calculation = xlAutomatic
MsgBox "Total tabs updated = " & b

End Sub
</code>```

Any help is appreciated.

答:
The Worksheet.Select Method lets you specify if want to add to or replace the current selection:

```<code>Dim ws as Worksheet, replaceSelection As Boolean
replaceSelection = True

For Each ws In ThisWorkbook.Worksheets
    If ws.Range("d5") = "Entity:" Then
       ws.Select Replace:=replaceSelection
       replaceSelection = False
    End If
Next
</code>```

To select starting from the current Sheet:

```<code>Dim ws as Worksheet, replaceSelection As Boolean
replaceSelection = True

While Not ws Is Nothing
    If ws.Range("d5") = "Entity:" Then
       ws.Select Replace:=replaceSelection
       replaceSelection = False
    End If
    Set ws = ws.Next
Wend
</code>```

Body:
I have a spreadsheet with 3 tabs. I need the following code to select the first two tabs. I almost have it but the Sheets(Array(c)).Select portion returns an error. Essentially i need the last section to return as Sheets(Array("Sheet1", "Sheet2")).Select

Sub HideUnhide2()
Dim a As String
Dim b As Double
Dim c As String
Application.Calculation = xlManual
        For I = 1 To 100
            If Range("d5") <> "Entity:" Then Exit For
            'Start
            c = c & ", " & Chr(34) & ActiveSheet.Name & Chr(34)

            'End
            b = b + 1

            ActiveSheet.Next.Select
        Next I
    '   End If
           c = Right(c, Len(c) - 2)
           MsgBox c
           Sheets(Array(c)).Select

Application.Calculation = xlAutomatic
MsgBox "Total tabs updated = " & b

End Sub

Any help is appreciated.

Body:
The Worksheet.Select Method lets you specify if want to add to or replace the current selection:

Dim ws as Worksheet, replaceSelection As Boolean
replaceSelection = True

For Each ws In ThisWorkbook.Worksheets
    If ws.Range("d5") = "Entity:" Then
       ws.Select Replace:=replaceSelection
       replaceSelection = False
    End If
Next

To select starting from the current Sheet:

Dim ws as Worksheet, replaceSelection As Boolean
replaceSelection = True

While Not ws Is Nothing
    If ws.Range("d5") = "Entity:" Then
       ws.Select Replace:=replaceSelection
       replaceSelection = False
    End If
    Set ws = ws.Next
Wend