问:
How to represent a graph in c++
I would like to write prims and dijkstra algoritms that create a MST. But I do not know what is the best way to represent graph in c++.

I could represent an edge by pair of two ints for example vector 0 to 1 would be pair(0,1);

```<code>typedef pair<int, int> Edge;
</code>```

And then the prims function would take Vector of pairs that consist of an edge and its weight.

```<code>void prims(vector<pair<Edge, int>>);
</code>```

I think that this way is not the best one, could anyone tell me what way would be the best to represent a graph?

答:
The two main ways to represent graphs learned in theoretical computer-science are adjacency matrix and adjacency lists.

Adjacency Matrix is as shown in the photo below is an n*n matrix and a[i][j] represents the edge between node i and node j so if it's a weighted graph it can be an integer instead of a boolean value for unweighted graphs.

adjacency matrix (photo source: google)

On the other hand, adjacency lists is a set of linked-lists (n-set to be exact), the i-th set has exactly the nodes i is connected to.
in this case you will need some additional way to save edge distance for example you can build your own class Edge as following

```<code>class Edge
{
     int destination, length;
     Edge* next = 0;
}
</code>```

and use it for your linked-list. How ever I am used to std::vector<std::pair<int, int>> a[N] to define a list of pairs and a[i][j].first would be the j-th neighbor of nod i and a[i][j].second the length of the edge between them.
For undirected graph your can add i to j neighbors as well.
So it's also a flexible way to represent graphs.

adjacency lists (image source: google photos)

So now let's talk complexity, I will try to keep it as simple as possible:

We habe n lists, each has the #(edges going out of node i)
so the total number is sum of this numbers which is the total number of edges E.
That means place complexity is O(E) which is at most 5 * n in a sparse-graph in comparison to O(N^2) in adjacency matrix. (We need a linear factor of E to represent it).
Now let's consider visiting all neighbors of a nod x:
in adjacency matrix we will go through the whole x-th line and if it's not 0 there's an edge there which is O(N).
In adjacency lists it's again exactly the number of neighbors of x which  can though reach O(N).
But if we are visiting all neighbors of all Nodes (which is the case in Dijkstra when updating dis array), you will need to visit n elements n times in adjacency lists which is also O(N^2) time complexity while in adjacency lists it's exactly the sum of the number of neighbors - again E. which means we need also O(E) to visit all neighbors of all edges.
And sind all edges are given usually in the input O(E) would pass as calculation time, but O(N^2) would be a high complexity for constraints of N <= 10^6 for example.
At the end I will leave you with my usual implementation of diffreent variants of graphs using adjacency lists (vector as a list):

```<code>#include<iostream>
#include<vector>
int main(){
    const int N = 5;
    int n, e;
    std::vector<std::pair<int, int>> graph[N], inverse[N];
    std::vector<int> unweighted[N], undirectedUnweighted[N];
    std::cin >> n >> e;
    for(int i = 0; i < e; i++)
    {
        int x, y, z;//z is length of edge
        std::cin >> x >> y >> z;
        //substitute 1 from x, y if they starts from 1
        graph[x].push_back(std::make_pair(y, z));
        inverse[y].push_back(std::make_pair(x, z));
        unweighted[x].push_back(y);
        undirectedUnweighted[x].push_back(y);
        undirectedUnweighted[y].push_back(x);
    }
    return 0;
}
</code>```

Title: How to represent a graph in c++

Body:
I would like to write prims and dijkstra algoritms that create a MST. But I do not know what is the best way to represent graph in c++.

I could represent an edge by pair of two ints for example vector 0 to 1 would be pair(0,1);

typedef pair<int, int> Edge;

And then the prims function would take Vector of pairs that consist of an edge and its weight.

void prims(vector<pair<Edge, int>>);

I think that this way is not the best one, could anyone tell me what way would be the best to represent a graph?

Body:
The two main ways to represent graphs learned in theoretical computer-science are adjacency matrix and adjacency lists.

Adjacency Matrix is as shown in the photo below is an n*n matrix and a[i][j] represents the edge between node i and node j so if it's a weighted graph it can be an integer instead of a boolean value for unweighted graphs.

adjacency matrix (photo source: google)

On the other hand, adjacency lists is a set of linked-lists (n-set to be exact), the i-th set has exactly the nodes i is connected to.
in this case you will need some additional way to save edge distance for example you can build your own class Edge as following

class Edge
{
     int destination, length;
     Edge* next = 0;
}

and use it for your linked-list. How ever I am used to std::vector<std::pair<int, int>> a[N] to define a list of pairs and a[i][j].first would be the j-th neighbor of nod i and a[i][j].second the length of the edge between them.
For undirected graph your can add i to j neighbors as well.
So it's also a flexible way to represent graphs.

adjacency lists (image source: google photos)

So now let's talk complexity, I will try to keep it as simple as possible:

We habe n lists, each has the #(edges going out of node i)
so the total number is sum of this numbers which is the total number of edges E.
That means place complexity is O(E) which is at most 5 * n in a sparse-graph in comparison to O(N^2) in adjacency matrix. (We need a linear factor of E to represent it).
Now let's consider visiting all neighbors of a nod x:
in adjacency matrix we will go through the whole x-th line and if it's not 0 there's an edge there which is O(N).
In adjacency lists it's again exactly the number of neighbors of x which  can though reach O(N).
But if we are visiting all neighbors of all Nodes (which is the case in Dijkstra when updating dis array), you will need to visit n elements n times in adjacency lists which is also O(N^2) time complexity while in adjacency lists it's exactly the sum of the number of neighbors - again E. which means we need also O(E) to visit all neighbors of all edges.
And sind all edges are given usually in the input O(E) would pass as calculation time, but O(N^2) would be a high complexity for constraints of N <= 10^6 for example.
At the end I will leave you with my usual implementation of diffreent variants of graphs using adjacency lists (vector as a list):

#include<iostream>
#include<vector>
int main(){
    const int N = 5;
    int n, e;
    std::vector<std::pair<int, int>> graph[N], inverse[N];
    std::vector<int> unweighted[N], undirectedUnweighted[N];
    std::cin >> n >> e;
    for(int i = 0; i < e; i++)
    {
        int x, y, z;//z is length of edge
        std::cin >> x >> y >> z;
        //substitute 1 from x, y if they starts from 1
        graph[x].push_back(std::make_pair(y, z));
        inverse[y].push_back(std::make_pair(x, z));
        unweighted[x].push_back(y);
        undirectedUnweighted[x].push_back(y);
        undirectedUnweighted[y].push_back(x);
    }
    return 0;
}


来源: stackexchange

问:
How to create a file upload button in Racket?
So I'm writing a small Racket application that will parse a (very poorly formatted) .txt file and output a .csv that can be worked with in Excel.  The first thing I want to do is open up a small window with a button that opens a file dialog so the user can select the file to be converted (just like any program that launches an open file selection dialog).  I've looked around online and can't find anything on this.  This is going to be a native application, so the stuff I have found on POSTing to webservers isn't relevant.  How can you do this in Racket?</p>

答: It's not clear what are you need. If you want know how to work with files see File ports section, but if you need to know how to create and use GUI objects see Windowing. Build GUI applications based on GTK (wich used in racket implemenation) it's not trivial task for a newbe user. It's not my business, but I think if you take some RAD (such as Lazarus for object pascal, MS Visual Studio for C#), you can doing your task faster and easier than write GUI as text without some experience.</p>

ContentLicense: CC BY-SA 3.0


问:
React.js ES6 avoid binding 'this' to every method
Recently, I've started tinkering with React.js and I love it. I started out in the regular ES5, so as to get the hang of things, the docs are all written in ES5...

But now I wanted to try ES6, because it's shiny and new, and it does seem to simplify some things. What bothers me a lot is that for every method I had added into my component classes I now have to bind 'this' to, otherwise it doesn't work. So my constructor ends up looking like this:

```<code>constructor(props) {
  super(props);
  this.state = { ...some initial state... }

  this.someHandler = this.someHandler.bind(this);
  this.someHandler = this.someHandler.bind(this);
  this.someHandler = this.someHandler.bind(this);
  this.someHandler = this.someHandler.bind(this);
  this.someHandler = this.someHandler.bind(this);
  this.someHandler = this.someHandler.bind(this);
  this.someHandler = this.someHandler.bind(this);
}
</code>```

If I were to add even more methods to my class, this would become an even bigger, uglier mess.

My question is, is there some way to get around this, or at least make it easier, shorter and less ugly? One of the main reasons I wanted to try React with ES6 was to make my code more concise, but this is doing the opposite. Any suggestions or input would be appreciated.

答:
I created a method to organize all the "binds". </p>

```<code>class MyClass {
  constructor() {

    this.bindMethods([
      'updateLocationFields',
      'render',
      'loadCities',
    ]);
  }

  bindMethods(methods) {
    methods.forEach((item) => {
      this[item] = this[item].bind(this);
    });
  }

  ...
}
</code>```

Body:
Recently, I've started tinkering with React.js and I love it. I started out in the regular ES5, so as to get the hang of things, the docs are all written in ES5...

But now I wanted to try ES6, because it's shiny and new, and it does seem to simplify some things. What bothers me a lot is that for every method I had added into my component classes I now have to bind 'this' to, otherwise it doesn't work. So my constructor ends up looking like this:

constructor(props) {
  super(props);
  this.state = { ...some initial state... }

  this.someHandler = this.someHandler.bind(this);
  this.someHandler = this.someHandler.bind(this);
  this.someHandler = this.someHandler.bind(this);
  this.someHandler = this.someHandler.bind(this);
  this.someHandler = this.someHandler.bind(this);
  this.someHandler = this.someHandler.bind(this);
  this.someHandler = this.someHandler.bind(this);
}

If I were to add even more methods to my class, this would become an even bigger, uglier mess.

My question is, is there some way to get around this, or at least make it easier, shorter and less ugly? One of the main reasons I wanted to try React with ES6 was to make my code more concise, but this is doing the opposite. Any suggestions or input would be appreciated.

Body:
I created a method to organize all the "binds".

class MyClass {
  constructor() {

    this.bindMethods([
      'updateLocationFields',
      'render',
      'loadCities',
    ]);
  }

  bindMethods(methods) {
    methods.forEach((item) => {
      this[item] = this[item].bind(this);
    });
  }

  ...
}


问:
How do I keep @HostListeners from overriding each other when extending classes?
I'm building a class to extend all my components that listens to resize events like this

```<code>@HostListener( 'window:resize', ['$event'] ).....//function
</code>```

In other components I listen to the same event, which causes one to override the other when the class is extended so only one triggers when the window size changes. I discovered this was the problem because I have one big class I un-comment to tinker with everything in one place.  When I added this to the class

```<code>@HostListener( 'window:resize', ['$event'] ) reSize( event ){ this.calcScreen(); }
@HostListener( 'window:resize', ['$event'] ) reScale( event ){ this.checkScrn(); }
</code>```

I got an error pointing at there being duplicates, which explains why they overridde one another when extended.  I gave the functions different names to see if that would help and I think the second one is the one that took dominance.  However with just one @HostListener with this on the end

```<code>reSize( event ){ this.calcScreen(); this.checkScrn(); }
</code>```

they both run as desired.

How can I work around this problem?  Here's my classes so far.

AppComponent

```<code>export class AppComponent extends GridFactory implements OnInit {
    MainFrame: SiteFrame;

    @HostListener( 'window:resize', ['$event'] ) onResize( event ){ this.calcScreen(); }

    constructor( @Self() public appSpecs: ElementRef ){
        super( appSpecs );
    }

    ngOnInit(){ this.calcScreen(); }

    calcScreen(){ this.MainFrame = uiMonitor(); }
}
</code>```

GridFactory

```<code>export class GridFactory implements AfterViewInit {
    ScreenCore   : ScrnCore  = new ScrnCore();
    GridSettings : GridSpecs = new GridSpecs();

    @HostListener( 'window:resize', ['$event'] ) onResize( event ){ this.checkScrn(); }

    constructor( @Self() public appSpecs: ElementRef ){}

    ngAfterViewInit(){ this.checkScrn(); }

    checkScrn(){
        this.ScreenCore.Width   = this.appSpecs.nativeElement.offsetWidth;
        this.ScreenCore.Height  = this.appSpecs.nativeElement.offsetHeight;

        this.activteGrid( this.ScreenCore );
    }

    activteGrid( data: ScrnCore ){ this.GridSettings = gridManager( data.Width ); }
}
</code>```

AppComponent (both combined as one class)

```<code>export class AppComponent implements OnInit, AfterViewInit{
    MainFrame    : SiteFrame = new SiteFrame();
    ScreenCore   : ScrnCore  = new ScrnCore();
    GridSettings : GridSpecs = new GridSpecs();

    @HostListener('window:resize', ['$event'])
    reSize(event){ this.calcScreen(); this.checkScrn(); }

    constructor( @Self() public appSpecs: ElementRef ){}

    ngOnInit(){ this.calcScreen(); }

    ngAfterViewInit(){ this.checkScrn(); }

    calcScreen(){ this.MainFrame = uiMonitor(); }

    checkScrn(){
        this.ScreenCore.Width   = this.appSpecs.nativeElement.offsetWidth;
        this.ScreenCore.Height  = this.appSpecs.nativeElement.offsetHeight;

        this.activteGrid( this.ScreenCore );
    }

    activteGrid( data: ScrnCore ){ this.GridSettings = gridManager( data.Width ); }
}
</code>```

答:
Turns out all I had to do was leave it like this in the AppComponent

```<code>@HostListener('window:resize', ['$event'])
reSize(event){ this.calcScreen(); this.checkScrn(); }
</code>```

even though I don't have it defined on the AppComponent it still registers because I'm extending the GridFactory to it, which I instinctively assumed wouldn't work...... but it does :)

Body:
I'm building a class to extend all my components that listens to resize events like this

@HostListener( 'window:resize', ['$event'] ).....//function

In other components I listen to the same event, which causes one to override the other when the class is extended so only one triggers when the window size changes. I discovered this was the problem because I have one big class I un-comment to tinker with everything in one place.  When I added this to the class

@HostListener( 'window:resize', ['$event'] ) reSize( event ){ this.calcScreen(); }
@HostListener( 'window:resize', ['$event'] ) reScale( event ){ this.checkScrn(); }

I got an error pointing at there being duplicates, which explains why they overridde one another when extended.  I gave the functions different names to see if that would help and I think the second one is the one that took dominance.  However with just one @HostListener with this on the end

reSize( event ){ this.calcScreen(); this.checkScrn(); }

they both run as desired.

How can I work around this problem?  Here's my classes so far.

AppComponent

export class AppComponent extends GridFactory implements OnInit {
    MainFrame: SiteFrame;

    @HostListener( 'window:resize', ['$event'] ) onResize( event ){ this.calcScreen(); }

    constructor( @Self() public appSpecs: ElementRef ){
        super( appSpecs );
    }

    ngOnInit(){ this.calcScreen(); }

    calcScreen(){ this.MainFrame = uiMonitor(); }
}

GridFactory

export class GridFactory implements AfterViewInit {
    ScreenCore   : ScrnCore  = new ScrnCore();
    GridSettings : GridSpecs = new GridSpecs();

    @HostListener( 'window:resize', ['$event'] ) onResize( event ){ this.checkScrn(); }

    constructor( @Self() public appSpecs: ElementRef ){}

    ngAfterViewInit(){ this.checkScrn(); }

    checkScrn(){
        this.ScreenCore.Width   = this.appSpecs.nativeElement.offsetWidth;
        this.ScreenCore.Height  = this.appSpecs.nativeElement.offsetHeight;

        this.activteGrid( this.ScreenCore );
    }

    activteGrid( data: ScrnCore ){ this.GridSettings = gridManager( data.Width ); }
}

AppComponent (both combined as one class)

export class AppComponent implements OnInit, AfterViewInit{
    MainFrame    : SiteFrame = new SiteFrame();
    ScreenCore   : ScrnCore  = new ScrnCore();
    GridSettings : GridSpecs = new GridSpecs();

    @HostListener('window:resize', ['$event'])
    reSize(event){ this.calcScreen(); this.checkScrn(); }

    constructor( @Self() public appSpecs: ElementRef ){}

    ngOnInit(){ this.calcScreen(); }

    ngAfterViewInit(){ this.checkScrn(); }

    calcScreen(){ this.MainFrame = uiMonitor(); }

    checkScrn(){
        this.ScreenCore.Width   = this.appSpecs.nativeElement.offsetWidth;
        this.ScreenCore.Height  = this.appSpecs.nativeElement.offsetHeight;

        this.activteGrid( this.ScreenCore );
    }

    activteGrid( data: ScrnCore ){ this.GridSettings = gridManager( data.Width ); }
}

Body:
Turns out all I had to do was leave it like this in the AppComponent

@HostListener('window:resize', ['$event'])
reSize(event){ this.calcScreen(); this.checkScrn(); }

even though I don't have it defined on the AppComponent it still registers because I'm extending the GridFactory to it, which I instinctively assumed wouldn't work...... but it does :)


问:
JavaScript - I don't understand how this collision detection function works
I'm enrolling in this course and they have this function from their code example and I don't understand how this particular one works.

```<code>function circRectsOverlap(x0, y0, w0, h0, cx, cy, r) {
   var testX=cx;
   var testY=cy;
   if (testX < x0) testX=x0;
   if (testX > (x0+w0)) testX=(x0+w0);
   if (testY < y0) testY=y0;
   if (testY > (y0+h0)) testY=(y0+h0);
   return (((cx-testX)*(cx-testX)+(cy-testY)*(cy-testY))< r*r);
}
</code>```

The first four arguments are the x and y position, width and height of the rectangle, while the last three are the x and y position, and the radius of the circle in the canvas.

If the rectangle and circle touch, the function returns true, hence there is a collision.

答: It appears that testX and testY become the coordinates of the nearest point to the center of the circle enclosed by the rectangle.  The four if tests 'clamp' these values to the edges of the rectangle should the center of the circle be outside of it in either dimension.  It might help to consider the case where the circle is centered inside the rectangle - all the ifs are false and testX and testY are the coordinates of the circle's center.  The test in the return statement uses the Pythagorean Theorem to determine if the test point is within the radius of the circle. </p>

Body:
I'm enrolling in this course and they have this function from their code example and I don't understand how this particular one works.

function circRectsOverlap(x0, y0, w0, h0, cx, cy, r) {
   var testX=cx;
   var testY=cy;
   if (testX < x0) testX=x0;
   if (testX > (x0+w0)) testX=(x0+w0);
   if (testY < y0) testY=y0;
   if (testY > (y0+h0)) testY=(y0+h0);
   return (((cx-testX)*(cx-testX)+(cy-testY)*(cy-testY))< r*r);
}

The first four arguments are the x and y position, width and height of the rectangle, while the last three are the x and y position, and the radius of the circle in the canvas.

If the rectangle and circle touch, the function returns true, hence there is a collision.


问:
Kivy update matplotlib graph with kivy.clock
I have a matplotlib graph in my kivy app which I want to update every second with streaming data. So far what I have behaves a little weird. It does update but only when I resize my window a little

```<code>fig, ax = plt.subplots()
width = 0.65
ax.set_title('Scores by group and gender')
bar_canvas = fig.canvas

class Test(BoxLayout):
    catA = NumericProperty(0)
    catB = NumericProperty(0)
    catC = NumericProperty(0)

    #plot the bar graph
    def plot(self, dt):
        catA_rects = ax.bar(5, self.catA, width, color='g')
        catB_rects = ax.bar(6, self.catB, width, color='#808080')
        catC_rects = ax.bar(7, self.catC, width, color='r')
        ax.legend((catA_rects[0], catB_rects[0], catC_rects[0]), ('Category A', 'Category B', 'Category C'))

    #update the graph
    def update(self):
        Clock.schedule_interval(self.plot,1)

    def classify_sample(self, test_sample):
        result_prob = classifier.predict_proba(test_sample)[0]
        result = classifier.predict(test_sample)[0]

        if result_prob.max() > 0.55:
            if result == 1:
                self.catA += 1

            else:
                self.catC += 1

        else:
            self.catB += 1

class ClassificationApp(App):
    def build(self):
        res = Test()
        res.bar_tab.add_widget(bar_canvas)
        res.update()
        return res

if __name__ == '__main__':
    ClassificationApp().run()
</code>```

In 'kv' file I call classify_sample to display the results inside a RecycleView Viewclass

```<code>Label:
    text: app.root.classify_sample(data)
</code>```

I'm updating the plot function with Clock.schedule_interval(self.plot,1) which is working when I'm printing the output on the screen but the plot isn't getting updated when the value of catA, catB or catC changes
It only updates when I resize my app window a little

Also is there another way to add graphs other than matplotlib? Matplotlib wont work when I package this for android right?

答: I was making rather a silly error. After updating the graph in plot function I wasn't actually calling the bar_canvas.draw() method

Body:
I have a matplotlib graph in my kivy app which I want to update every second with streaming data. So far what I have behaves a little weird. It does update but only when I resize my window a little

fig, ax = plt.subplots()
width = 0.65
ax.set_title('Scores by group and gender')
bar_canvas = fig.canvas

class Test(BoxLayout):
    catA = NumericProperty(0)
    catB = NumericProperty(0)
    catC = NumericProperty(0)

    #plot the bar graph
    def plot(self, dt):
        catA_rects = ax.bar(5, self.catA, width, color='g')
        catB_rects = ax.bar(6, self.catB, width, color='#808080')
        catC_rects = ax.bar(7, self.catC, width, color='r')
        ax.legend((catA_rects[0], catB_rects[0], catC_rects[0]), ('Category A', 'Category B', 'Category C'))

    #update the graph
    def update(self):
        Clock.schedule_interval(self.plot,1)

    def classify_sample(self, test_sample):
        result_prob = classifier.predict_proba(test_sample)[0]
        result = classifier.predict(test_sample)[0]

        if result_prob.max() > 0.55:
            if result == 1:
                self.catA += 1

            else:
                self.catC += 1

        else:
            self.catB += 1

class ClassificationApp(App):
    def build(self):
        res = Test()
        res.bar_tab.add_widget(bar_canvas)
        res.update()
        return res

if __name__ == '__main__':
    ClassificationApp().run()

In 'kv' file I call classify_sample to display the results inside a RecycleView Viewclass

Label:
    text: app.root.classify_sample(data)

I'm updating the plot function with Clock.schedule_interval(self.plot,1) which is working when I'm printing the output on the screen but the plot isn't getting updated when the value of catA, catB or catC changes
It only updates when I resize my app window a little

Also is there another way to add graphs other than matplotlib? Matplotlib wont work when I package this for android right?


问:
SQL Server - Combining OUTER and INNER joins
I have 3 tables and I have to inner join Table A with Table B but a left outer between Table A and Table C.

Can I combine outer and inner join in the same query? I can nest queries and attain the desired result but I am unable to do both the joins in the same query. It appears that in other SQL languages, the order of joining is important. Is this the case in SQL Server as well?

Ok, here's the scenario.

Consider 3 tables. Table A, Table F, Table D.

I will need the recordset to contain all rows in D irrespective of whether it exists in F (after it's inner joined with A). So, a outer join comes to mind. What I would need is:

First do a inner join between A and F to get a set (this may be a null set)

Then do a outer join with the recordset in (1) with D

答:
You can use both inner and outer joins in the same query, but their order is important. See this question:

Inner join & outer join; is the order of tables in from important?

OwnerDisplayName: Bob Smith

OwnerDisplayName: gkrogers

ContentLicense: CC BY-SA 2.5


问:
project tango usage in an oem product
We are trying to use Project Tango in our prototype/future product. We are open to use either Asus or Lenovo.

Does anyone know what the licensing is? Or is it now in the hands of Asus/Lenovo?

答: you would need to contact google as tango is their product and lenovo/asus license it from google. FYI, the future of tango is somewhat up in the air currently as google has said little about the program and have seriously reduced the updates to the handsets and code. you would be better off if you tried ARCore by google which seems to be the way forward with AR as far a google is concerned.</p>

Title: project tango usage in an oem product


问:
How to aggregate-initialize this struct?
I'm having a struct that I would like to initialize like this:

```<code>checkPoints someCheckpoints = {
    {
        mPosition(10, 18),
        mPosition(15, 20),
    },
    {
        mPosition(45, 80),
        mPosition(95, 105),
    }
};
</code>```

Basically a vector of position vectors initialization using aggregators.

This is working without problems:

```<code>std::vector<PosVec> someCheckpoints = {
    {
        mPosition(10, 18),
        mPosition(15, 20),
    },
    {
        mPosition(45, 80),
        mPosition(95, 105),
    }
};
</code>```

However I need to use struct in order to add some additional functionality.

My code:

```<code>struct mPosition {
    mPosition(int32_t x, int32_t y) : x(x), y(y) {}

    int32_t x;
    int32_t y;
};

typedef std::vector<mPosition> PosVec;

struct checkPoints {
    explicit checkPoints(std::vector<PosVec>& checkPoints) {
        checkPointsVec = checkPoints;
    };

    const PosVec& getRandom() const {
        return checkPointsVec[getRandomInt(0, checkPointsVec.size())];
    }

    std::vector<PosVec> checkPointsVec;
};

checkPoints someCheckpoints = { // no matching constructor
    {
        mPosition(10, 18),
        mPosition(15, 20),
    },
    {
        mPosition(45, 80),
        mPosition(95, 105),
    }
};
</code>```

This is producing no matching constructor error. I would like it to use a proper vector-like aggregation constructor. Should my struct extend vector class
instead or would I be able to do this declaring my own constructor (which one)?

How can I solve this?

答:
The constructor needs a std::vector<PosVec> as input parameter, like this:

```<code>     checkPoints someCheckpoints{
        std::vector<PosVec>{
        {
            mPosition{10, 18},
            mPosition{15, 20},
        },
        {
            mPosition{45, 80},
            mPosition{95, 105},
        }
        }
    };
</code>```

Body:
I'm having a struct that I would like to initialize like this:

checkPoints someCheckpoints = {
    {
        mPosition(10, 18),
        mPosition(15, 20),
    },
    {
        mPosition(45, 80),
        mPosition(95, 105),
    }
};

Basically a vector of position vectors initialization using aggregators.

This is working without problems:

std::vector<PosVec> someCheckpoints = {
    {
        mPosition(10, 18),
        mPosition(15, 20),
    },
    {
        mPosition(45, 80),
        mPosition(95, 105),
    }
};

However I need to use struct in order to add some additional functionality.

My code:

struct mPosition {
    mPosition(int32_t x, int32_t y) : x(x), y(y) {}

    int32_t x;
    int32_t y;
};

typedef std::vector<mPosition> PosVec;

struct checkPoints {
    explicit checkPoints(std::vector<PosVec>& checkPoints) {
        checkPointsVec = checkPoints;
    };

    const PosVec& getRandom() const {
        return checkPointsVec[getRandomInt(0, checkPointsVec.size())];
    }

    std::vector<PosVec> checkPointsVec;
};

checkPoints someCheckpoints = { // no matching constructor
    {
        mPosition(10, 18),
        mPosition(15, 20),
    },
    {
        mPosition(45, 80),
        mPosition(95, 105),
    }
};

This is producing no matching constructor error. I would like it to use a proper vector-like aggregation constructor. Should my struct extend vector class
instead or would I be able to do this declaring my own constructor (which one)?

How can I solve this?

Body:
The constructor needs a std::vector<PosVec> as input parameter, like this:

     checkPoints someCheckpoints{
        std::vector<PosVec>{
        {
            mPosition{10, 18},
            mPosition{15, 20},
        },
        {
            mPosition{45, 80},
            mPosition{95, 105},
        }
        }
    };


问:
Installing Qt5 and PyQt5 for Python 2.7
I am new to Stack Overflow and Python.

I am developing for Visual Effects, which means that I am (and will continue) using Python 2.7. I'm a bit lost and looking for clear instructions on how to install pyqt5. I know this seems pretty elementary, so I appreciate everyone's patience.

There is a lot of information on this subject like, you need QT5 or Scintilla? A lot of the instructions are fragmented and don't have all of the information. I was wondering if someone could point me in the right direction with clear and concise instructions.

For example:

Install Python 2.7

Install x

...

...

...

I'm willing to figure it out myself, but I feel the information I have has a lot of holes and could use some help/direction.

Thanks in advance.

答:
Maybe this link can help. It is for installing PyQt5 on Python 3, but I think it will be the same process for Python 2.

Update:
Since you didn't say any specific OS, I will assume you're using Windows. For Windows, there is already Python distribution which is ready to use such as WinPython. This is what I've done on my machine:

Download appropriate WinPython version for your machine,

Download appropriate PyQt5 wheels version for your machine,

Install WinPython,

Extract the downloaded PyQt5 wheels,

Copy pyqt5-tools folder found inside where you extracted PyQt5 wheels

Paste it to Where_You_Installed_WinPython\Lib\site-packages.

You can start designing your GUI with double-clicking Qt Designer.exe. After you finished designing your GUI, you can convert the GUI file (with *.ui extension) to *.py with pyuic5 -x yourgui.ui -o yourgui.py command.

python and pyuic5 command on your command prompt can only be executed in your WinPython installation folder. inside your WinPython installation folder.

Title: Installing Qt5 and PyQt5 for Python 2.7


问:
VC++ Visual Studio added .hpp files in subdirectory but get "Error: cannot open source file ..."
This is driving me nuts - I've added a number of .hpp files in subdirectories in the root of an existing VC++ projects source directory.

Visual Studio complains "Error: cannot open source file ..." but if I right click on the  and select open document, VS can display it.

I've tried:

"Rescan solution" which appears to do nothing.

Adding existing item (both on it's own and with a "filter" - which appears to be a directory?)

Closing the project and VStudio in the vain hope it would eventually discover the directories/files I'd added

VStudio complains it cannot find these files when it is capable of opening them?  My question is simply this:  "How can I add a directory containing source files to a VC++ project such that the linker/complier can see them?

(disclaimer; i've never used Visual Studio before or many Microsoft products, so am finding this all very alien)

答: first you need to include any header file you'd like to use into your cpp files by #include "path/file.hpp". in your case your probably didn't specify path, e.g. "subdir/file.hpp"


问:
MySQL - Make an existing field unique without deleting empty entries
```<code>ALTER IGNORE TABLE mytbl ADD UNIQUE (columnName);
</code>```

This will make a filed a unique index but the command deletes all rows with an empty value, is there any way I can avoid that happening. The field may have NULL values if that helps.

答: Set the "empty" (?) values to NULL and don't use IGNORE.  The purpose of ALTER IGNORE is to remove duplicate values.  Multiple NULL are not duplicates of each other, since the expression NULL = NULL is not true (and is also not false).

Body:
ALTER IGNORE TABLE mytbl ADD UNIQUE (columnName);

This will make a filed a unique index but the command deletes all rows with an empty value, is there any way I can avoid that happening. The field may have NULL values if that helps.


问:
Return function(event, userData) both in callback?
Using a callback I'm getting the position of a child object and adding it to an array. I would also like to add a key to that id so I can search the array for it later. Then I can link the key of the originally created object, with a key in the position array.

I can't seem to get the callback for both to work. Is there a way you can pass function(event, callback) both back ?

Bonus points if you know why this.props.onLayout sends e in the callback, while this.props.onLayout() doesn't. I don't!

```<code>const dataArray = [{key: 0,id: 'A',},{key: 1,id: 'B',},{key: 2,id: 'Z',}]

// Root Component
export default class App extends Component {
    render(){
        return (
            <View>
            {this.getSomeText()}
            </
    getSomeText() {
        return dataArray.map( d =>
            <SomeText key={d.key} id={d.id} onLayout={(e) => this.onLayout(e)} />
        )
    }
    onLayout (e, id ) {
        // add these items to array
        // e.nativeEvent.Layout{Width,Height,x,y,id}
        // I can add the e data but the id data never comes through.
    }
}

// Child Component
class SomeText extends Component {
    render() {
        return (
            <Text
                onLayout={this.props.onLayout}
                // onLayout as above this returns the event e but
                // 2. this.props.onLayout() // doesn't return e at all ??
                // 3. () => this.props.onLayout // doesn't work either, why?
                // 4. (e, this.props.key)  => this.props.onLayout(this.props.key)
                // 4 doesnt work either
                >Some text</Text>
        )
    }
}
</code>```

答:
You can use:

```<code><SomeText key={d.key} id={d.id} onLayout={(e) => this.onLayout(e, d.id)} />
</code>```

However, you can also get the id from the event:

```<code>onLayout (e) {
  const id = e.target.id;
}
</code>```

See some additions to your comments below:

```<code><Text
    onLayout={this.props.onLayout}
    // onLayout as above this returns the event e but
    // 2. this.props.onLayout() // Calls the function during every render instead of assigning it.
    // 3. () => this.props.onLayout // Assigns the anonymous function, but when the event occurs and the anonymous function is called, you aren't calling your onLayout function.
    // 4. (e, this.props.key)  => this.props.onLayout(this.props.key)
    // this.props.key isn't being passed in by the event handler. Also, you are not passing the event to onLayout. Should be (e) => this.props.onLayout(e, this.props.key)
    >Some text</Text>
</code>```

Body:
Using a callback I'm getting the position of a child object and adding it to an array. I would also like to add a key to that id so I can search the array for it later. Then I can link the key of the originally created object, with a key in the position array.

I can't seem to get the callback for both to work. Is there a way you can pass function(event, callback) both back ?

Bonus points if you know why this.props.onLayout sends e in the callback, while this.props.onLayout() doesn't. I don't!

const dataArray = [{key: 0,id: 'A',},{key: 1,id: 'B',},{key: 2,id: 'Z',}]

// Root Component
export default class App extends Component {
    render(){
        return (
            <View>
            {this.getSomeText()}
            </
    getSomeText() {
        return dataArray.map( d =>
            <SomeText key={d.key} id={d.id} onLayout={(e) => this.onLayout(e)} />
        )
    }
    onLayout (e, id ) {
        // add these items to array
        // e.nativeEvent.Layout{Width,Height,x,y,id}
        // I can add the e data but the id data never comes through.
    }
}

// Child Component
class SomeText extends Component {
    render() {
        return (
            <Text
                onLayout={this.props.onLayout}
                // onLayout as above this returns the event e but
                // 2. this.props.onLayout() // doesn't return e at all ??
                // 3. () => this.props.onLayout // doesn't work either, why?
                // 4. (e, this.props.key)  => this.props.onLayout(this.props.key)
                // 4 doesnt work either
                >Some text</Text>
        )
    }
}

Body:
You can use:

<SomeText key={d.key} id={d.id} onLayout={(e) => this.onLayout(e, d.id)} />

However, you can also get the id from the event:

onLayout (e) {
  const id = e.target.id;
}

See some additions to your comments below:

<Text
    onLayout={this.props.onLayout}
    // onLayout as above this returns the event e but
    // 2. this.props.onLayout() // Calls the function during every render instead of assigning it.
    // 3. () => this.props.onLayout // Assigns the anonymous function, but when the event occurs and the anonymous function is called, you aren't calling your onLayout function.
    // 4. (e, this.props.key)  => this.props.onLayout(this.props.key)
    // this.props.key isn't being passed in by the event handler. Also, you are not passing the event to onLayout. Should be (e) => this.props.onLayout(e, this.props.key)
    >Some text</Text>


问:
Tabula-py is not splitting columns right
I've just discovered the joy of tabula-py (and tabula-java of course) to extract tables from pdf. I am now programming a script for my job that reads some data from the pdf table, cleans it a little bit and the export that into excel. The pdf I am using has the same format every day, and the table is always in a certain area. To detect the area, I am using tabula.exe: I select the table, visualize the preview (which looks good), and then export the script, in order to see the -a parameter that is used by tabula.exe. I then use this in my command in Python, that is:

```<code>df = tabula.read_pdf(os.fsdecode(directory)+filename, encoding = 'ISO-8859-1',
stream=True, area = "81.106,302.475,384.697,552.491", pages = 2, pandas_options={'header':None})
</code>```

I am using the encoding parameter because the standard utf-8 returns an error, and the stream method, because it's the one that shows a nice extracted table in tabula.exe. However, the dataframe has a problem, because the first 2 columns (which are displayed correctly as 2 different columns in the preview of tabula.exe) are actually one single column, so that names and values get mixed together.

Do you have any idea of why the same area yields 2 different results in tabula-py and tabula.exe? Thank you very much!

答:
Figured it out on GitHub: tabula-py has the "guess" option set on True by default. So to correct the discrepancy, you can just add guess=False, and the output will be the same!</p>

```<code>    df = tabula.read_pdf(os.fsdecode(directory)+filename, encoding = 'ISO-8859-1',
         stream=True, area = "81.106,302.475,384.697,552.491", pages = 2, guess = False,  pandas_options={'header':None})
</code>```

Body:
I've just discovered the joy of tabula-py (and tabula-java of course) to extract tables from pdf. I am now programming a script for my job that reads some data from the pdf table, cleans it a little bit and the export that into excel. The pdf I am using has the same format every day, and the table is always in a certain area. To detect the area, I am using tabula.exe: I select the table, visualize the preview (which looks good), and then export the script, in order to see the -a parameter that is used by tabula.exe. I then use this in my command in Python, that is:

df = tabula.read_pdf(os.fsdecode(directory)+filename, encoding = 'ISO-8859-1',
stream=True, area = "81.106,302.475,384.697,552.491", pages = 2, pandas_options={'header':None})

I am using the encoding parameter because the standard utf-8 returns an error, and the stream method, because it's the one that shows a nice extracted table in tabula.exe. However, the dataframe has a problem, because the first 2 columns (which are displayed correctly as 2 different columns in the preview of tabula.exe) are actually one single column, so that names and values get mixed together.

Do you have any idea of why the same area yields 2 different results in tabula-py and tabula.exe? Thank you very much!

Body:
Figured it out on GitHub: tabula-py has the "guess" option set on True by default. So to correct the discrepancy, you can just add guess=False, and the output will be the same!

    df = tabula.read_pdf(os.fsdecode(directory)+filename, encoding = 'ISO-8859-1',
         stream=True, area = "81.106,302.475,384.697,552.491", pages = 2, guess = False,  pandas_options={'header':None})


问:
Get sum of array and callback a function inside another function
I am trying to solve a problem where I have to get the sum of an array using the .reduce() method inside a function and instead of returning the sum, I need to invoke the callback and pass the sum there.

I am pretty sure I am using the .reduce() correctly but I keep getting 'undefined' and, for the life of me, I cannot figure out how to get invoke a function inside a function.

Any help/explanations would be greatly appreciated!

Question: Sum up all of the integers in the numbers array.
Instead of returning the sum invoke cb and pass in the sum there.

My code:

```<code>function sumArray(numbers, cb) {
  //code here

  numbers.reduce(function(sum, currentValue) {
    return sum + currentValue;
  }, 0);

  cb([1, 2, 3, 4, 5], result);

}

function addTwo(num) {
  const result =  num + 2;
}
</code>```

答:
This is, I assume, your homework so I don't want to give too much away but here are a couple pointers.

numbers.reduce(function(sum, currentValue) { is calculating the sum but then not storing it. You want something like var reduced = things.reduce(...).

Also cb is probably expecting to be passed just 1 argument, the sum, where as you are currently passing an array as the first argument and result (which you haven't declared yet) as the second argument.

Body:
I am trying to solve a problem where I have to get the sum of an array using the .reduce() method inside a function and instead of returning the sum, I need to invoke the callback and pass the sum there.

I am pretty sure I am using the .reduce() correctly but I keep getting 'undefined' and, for the life of me, I cannot figure out how to get invoke a function inside a function.

Any help/explanations would be greatly appreciated!

Question: Sum up all of the integers in the numbers array.
Instead of returning the sum invoke cb and pass in the sum there.

My code:

function sumArray(numbers, cb) {
  //code here

  numbers.reduce(function(sum, currentValue) {
    return sum + currentValue;
  }, 0);

  cb([1, 2, 3, 4, 5], result);

}

function addTwo(num) {
  const result =  num + 2;
}


问:
shared_from_this() returns std::shared_ptr<const X>, not std::shared_ptr<X>
OK, this one has me stumped. Clearly I've missed something, so I hope someone can tell me what it is.

I'm developing a C++17 library. I've written a custom tree data structure composed of Node objects and a custom iterator, Node::iterator, for traversing the tree. The iterator looks like this:

```<code>template <typename T>
class NodeIterator {
public:
    using value_type = T;
    using difference_type = std::ptrdiff_t;
    using pointer = std::shared_ptr<T>;
    using reference = T&;
    using iterator_category = std::forward_iterator_tag;

    NodeIterator() = default;
    NodeIterator(pointer n);

    // Etc.
}
</code>```

And later...

```<code>template class NodeIterator<Node>;
template class NodeIterator<const Node>;
</code>```

When I add the standard iterator methods (begin(), end(), and the const equivalents) to a parent class Tree, I can control the initial value for the iterator. So I can say

```<code>Node::iterator Tree::begin() const {
    return Node::iterator(_root);
}
</code>```

where _root is a std::shared_ptr<Node>. This works great.

However, not content to leave well enough alone, I want these iterator methods on the node itself. That way I can traverse a subtree from any node, eliminate the Tree class altogether, and just pass around Node objects.

I declare Node as

```<code>class Node : public std::enable_shared_from_this<Node> {
public:
    using iterator = NodeIterator<Node>;
    using const_iterator = NodeIterator<const Node>;

    iterator begin() const;
    iterator end() const;
    const_iterator cbegin() const;
    const_iterator cend() const;

    // Etc.
}
</code>```

and define the iterator methods as

```<code>Node::iterator Node::begin() const {
    return Node::iterator(this->shared_from_this());
}

Node::iterator Node::end() const {
    return Node::iterator(nullptr);
}

Node::const_iterator Node::cbegin() const {
    return Node::const_iterator(this->shared_from_this());
}

Node::const_iterator Node::cend() const {
    return Node::const_iterator(nullptr);
}
</code>```

The compiler then loudly complains about the return statement:

```<code>src/node.cc:79:9: error: no matching conversion for functional-style cast from
      'shared_ptr<const Node>' to 'Node::iterator' (aka 'NodeIterator<Node>')
        return Node::iterator(this->shared_from_this());
               ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</code>```

and later...

```<code>include/example.h:344:2: note: candidate constructor not viable: no known
      conversion from 'shared_ptr<const Node>' to 'shared_ptr<Node>' for
      1st argument
        NodeIterator(pointer n);
        ^
</code>```

In another method, Node::appendChild(), I automatically set the parent node (std::shared_ptr<Node>) to this->shared_from_this(), and it works fine.

If I comment out Node::begin() and Node::end() and only use cbegin() and cend() in my loop, it also works fine.

What gives?

答: shared_from_this has const and non-const overloads. See cppreference. Within your const begin, this is pointer to const and calls the const overload which returns a shared_ptr to const.

Body:
OK, this one has me stumped. Clearly I've missed something, so I hope someone can tell me what it is.

I'm developing a C++17 library. I've written a custom tree data structure composed of Node objects and a custom iterator, Node::iterator, for traversing the tree. The iterator looks like this:

template <typename T>
class NodeIterator {
public:
    using value_type = T;
    using difference_type = std::ptrdiff_t;
    using pointer = std::shared_ptr<T>;
    using reference = T&;
    using iterator_category = std::forward_iterator_tag;

    NodeIterator() = default;
    NodeIterator(pointer n);

    // Etc.
}

And later...

template class NodeIterator<Node>;
template class NodeIterator<const Node>;

When I add the standard iterator methods (begin(), end(), and the const equivalents) to a parent class Tree, I can control the initial value for the iterator. So I can say

Node::iterator Tree::begin() const {
    return Node::iterator(_root);
}

where _root is a std::shared_ptr<Node>. This works great.

However, not content to leave well enough alone, I want these iterator methods on the node itself. That way I can traverse a subtree from any node, eliminate the Tree class altogether, and just pass around Node objects.

I declare Node as

class Node : public std::enable_shared_from_this<Node> {
public:
    using iterator = NodeIterator<Node>;
    using const_iterator = NodeIterator<const Node>;

    iterator begin() const;
    iterator end() const;
    const_iterator cbegin() const;
    const_iterator cend() const;

    // Etc.
}

and define the iterator methods as

Node::iterator Node::begin() const {
    return Node::iterator(this->shared_from_this());
}

Node::iterator Node::end() const {
    return Node::iterator(nullptr);
}

Node::const_iterator Node::cbegin() const {
    return Node::const_iterator(this->shared_from_this());
}

Node::const_iterator Node::cend() const {
    return Node::const_iterator(nullptr);
}

The compiler then loudly complains about the return statement:

src/node.cc:79:9: error: no matching conversion for functional-style cast from
      'shared_ptr<const Node>' to 'Node::iterator' (aka 'NodeIterator<Node>')
        return Node::iterator(this->shared_from_this());
               ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

and later...

include/example.h:344:2: note: candidate constructor not viable: no known
      conversion from 'shared_ptr<const Node>' to 'shared_ptr<Node>' for
      1st argument
        NodeIterator(pointer n);
        ^

In another method, Node::appendChild(), I automatically set the parent node (std::shared_ptr<Node>) to this->shared_from_this(), and it works fine.

If I comment out Node::begin() and Node::end() and only use cbegin() and cend() in my loop, it also works fine.

What gives?


问:
How to display a form inside another form like Visual Studio
How does Visual Studio and other similar programs display a form in their IDE?

Is it possible to achieve the same or a similar effect using C# or VB.NET?

Please see the picture below to get what I mean.

答:
If you are talking about hosting a Winforms editor in your code, it is entirely possible and is actually built in to the .NET framework!

The Essence is the IDesignerHost interface.  The whole system is complicated, but can be done (I have done it in production code for runtime layout configuration editing).  There is a sample of code from Microsoft here.

I'm sure if you search fir 'IDesignerHost' you'll find enough reference material to figure it out.


问:
Can't move a view to the center of the screen (programmatically, not with layout properties) - Android
This might look like a very common problem but I can't seem to move a view to the center of the screen.

I have 3 views:

a background image (center crop)

a black/white grid to visualize the center of the screen, for debugging purpose. Also center crop

a square that I want to move to the center, top left corner of the square at the center of the screen.

I first get the screen size in pixels, divide width and height by 2 to get the coordinates of the center. Then move my square view by center.x and center.y
I expect the square to be moves precisely to the center of the screen.

I also scale the square view so its size is always the same relative to the background image.

I want to solve this programmatically (not just centering with layout properties) because it is only a first step, I intend to be able to place the square anywhere I want on the screen. I try to place in the center here because it seems like the easiest thing to do.

The code

```<code>public class FullScreenActivity extends AppCompatActivity {

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            getWindow().getDecorView().setSystemUiVisibility(
                  View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
            );
        }
    }

}
</code>```

The class whit the logic

```<code>public class AnimalPopupActivity extends FullScreenActivity {

    private final String TAG = "AnimalPopup";

    ImageView backgroundView;
    ImageView square;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_animal_popup);

        backgroundView = (ImageView)findViewById(R.id.background);

        square = (ImageView) findViewById(R.id.square);

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int screenWidthInPixels = metrics.widthPixels;
        int screenHeightInPixels = metrics.heightPixels;
        Log.i(TAG, "screen width pixels: "+screenWidthInPixels);
        Log.i(TAG, "screen height pixels: "+screenHeightInPixels);

        Point center = new Point(screenWidthInPixels/2, screenHeightInPixels/2);
        Log.i(TAG, "center: "+center);

        double ratioH = (double)screenWidthInPixels/100d;
        Log.i(TAG, "ratioH: "+ratioH);
        double ratioV = (double)screenHeightInPixels/100d;
        Log.i(TAG, "ratioV: "+ratioV);

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams((int)(10*ratioH), (int)(10*ratioV));
        layoutParams.leftMargin = center.x;
        layoutParams.topMargin = center.y;
        square.setLayoutParams(layoutParams);
    }
}
</code>```

Layout

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.bentaye.app.games.AnimalPopupActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/background"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            app:srcCompat="@drawable/animal_popup_background" />

        <ImageView
            android:id="@+id/grid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:scaleType="centerCrop"
            app:srcCompat="@drawable/animal_popup_grid" />

        <ImageView
            android:id="@+id/square"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:srcCompat="@drawable/square" />

    </RelativeLayout>

</android.support.constraint.ConstraintLayout>
</code>```

Here is what I get on a Nexus 5 (1080*1920:420dpi)

With the following logs:

screen width pixels: 1080

screen height pixels: 1794

center: Point(540, 897)

ratioH: 10.8

ratioV: 17.94

Here is what I get on a Nexus 10 (2560*1600:xhdpi)

With the following logs:

screen width pixels: 1600

screen height pixels: 2464

center: Point(800, 1232)

ratioH: 16.0

ratioV: 24.64

The 2 are off by a few pixels, I am not an Android specialist and clearly I am doing something wrong but can't understand what.

Any help welcome. Cheers!

EDIT: I think that it is due the calculation taking the status bar into account. It also explains why the discrepancy is bigger on the Nexus5, as the status bar is bigger relatively to the screen height. And also why the discrepancy only affects the vertical alignment.
I'll come back and post the code once I sort it out.

答:
Assuming the square you want centered is inside the RelativeLayout, add layout_gravity=center

For example:

```<code><ImageView
    android:id="@+id/square"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity=center"
    app:srcCompat="@drawable/square"/>
</code>```

Body:
This might look like a very common problem but I can't seem to move a view to the center of the screen.

I have 3 views:

a background image (center crop)

a black/white grid to visualize the center of the screen, for debugging purpose. Also center crop

a square that I want to move to the center, top left corner of the square at the center of the screen.

I first get the screen size in pixels, divide width and height by 2 to get the coordinates of the center. Then move my square view by center.x and center.y
I expect the square to be moves precisely to the center of the screen.

I also scale the square view so its size is always the same relative to the background image.

I want to solve this programmatically (not just centering with layout properties) because it is only a first step, I intend to be able to place the square anywhere I want on the screen. I try to place in the center here because it seems like the easiest thing to do.

The code

public class FullScreenActivity extends AppCompatActivity {

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            getWindow().getDecorView().setSystemUiVisibility(
                  View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
            );
        }
    }

}

The class whit the logic

public class AnimalPopupActivity extends FullScreenActivity {

    private final String TAG = "AnimalPopup";

    ImageView backgroundView;
    ImageView square;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_animal_popup);

        backgroundView = (ImageView)findViewById(R.id.background);

        square = (ImageView) findViewById(R.id.square);

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int screenWidthInPixels = metrics.widthPixels;
        int screenHeightInPixels = metrics.heightPixels;
        Log.i(TAG, "screen width pixels: "+screenWidthInPixels);
        Log.i(TAG, "screen height pixels: "+screenHeightInPixels);

        Point center = new Point(screenWidthInPixels/2, screenHeightInPixels/2);
        Log.i(TAG, "center: "+center);

        double ratioH = (double)screenWidthInPixels/100d;
        Log.i(TAG, "ratioH: "+ratioH);
        double ratioV = (double)screenHeightInPixels/100d;
        Log.i(TAG, "ratioV: "+ratioV);

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams((int)(10*ratioH), (int)(10*ratioV));
        layoutParams.leftMargin = center.x;
        layoutParams.topMargin = center.y;
        square.setLayoutParams(layoutParams);
    }
}

Layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.bentaye.app.games.AnimalPopupActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/background"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            app:srcCompat="@drawable/animal_popup_background" />

        <ImageView
            android:id="@+id/grid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:scaleType="centerCrop"
            app:srcCompat="@drawable/animal_popup_grid" />

        <ImageView
            android:id="@+id/square"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:srcCompat="@drawable/square" />

    </RelativeLayout>

</android.support.constraint.ConstraintLayout>

Here is what I get on a Nexus 5 (1080*1920:420dpi)

With the following logs:

screen width pixels: 1080

screen height pixels: 1794

center: Point(540, 897)

ratioH: 10.8

ratioV: 17.94

Here is what I get on a Nexus 10 (2560*1600:xhdpi)

With the following logs:

screen width pixels: 1600

screen height pixels: 2464

center: Point(800, 1232)

ratioH: 16.0

ratioV: 24.64

The 2 are off by a few pixels, I am not an Android specialist and clearly I am doing something wrong but can't understand what.

Any help welcome. Cheers!

EDIT: I think that it is due the calculation taking the status bar into account. It also explains why the discrepancy is bigger on the Nexus5, as the status bar is bigger relatively to the screen height. And also why the discrepancy only affects the vertical alignment.
I'll come back and post the code once I sort it out.

Body:
Assuming the square you want centered is inside the RelativeLayout, add layout_gravity=center

For example:

<ImageView
    android:id="@+id/square"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity=center"
    app:srcCompat="@drawable/square"/>


答:
Here are the problems

1. Your reduce() function needs to return its output to your result variable. You did not return the output to the result variable and you did not define the result variable.

2. If the addTwo() function is the callback function, then you are supposed to pass in a single variable. But since you did not indicate the destination of the cd call back, I guess you did not include it in the code sample. Do this;

```<code>function sumArray(numbers, cb) {

 var result=numbers.reduce(function(sum, currentValue) {
    return sum + currentValue;
 }, 0);

 cb([1, 2, 3, 4, 5], result);

}

function addTwo(num) {
 const result =  num + 2;
}
</code>```

Title: Get sum of array and callback a function inside another function

Body:
Here are the problems

1. Your reduce() function needs to return its output to your result variable. You did not return the output to the result variable and you did not define the result variable.

2. If the addTwo() function is the callback function, then you are supposed to pass in a single variable. But since you did not indicate the destination of the cd call back, I guess you did not include it in the code sample. Do this;

function sumArray(numbers, cb) {

 var result=numbers.reduce(function(sum, currentValue) {
    return sum + currentValue;
 }, 0);

 cb([1, 2, 3, 4, 5], result);

}

function addTwo(num) {
 const result =  num + 2;
}


问:
How to let user end program and shift list
Im trying to make an encryption program </p>

```<code>def intro():
    msg = input("Enter the message you wish to encrypt: ")
    return msg

def shift(msg):
    alpha = ['a', 'b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    rotate = int(input("The level of the encryption?: "))
    text = ""
    for ch in msg:
        if ch == " " or ch == ".":
            pass
        elif msg == "$":
            print("nah")
        else:
            index = alpha.index(ch)
            newindex = index + rotate
            new= alpha[newindex]
            text += new
    return text

def start():
    msg = intro()
    text = shift(msg)
    print("Your encryptions is: " + text)

start()
</code>```

<p>I can't figure out a way to loop the list without getting an index out of range error. For example, if you put "z" it will shift to an  "a". I also need for my program to loop till user inputs to end it.  I just started coding in python a few months ago so any help will be appreciated!beginner </p>

答:
use the modulus operator to wrap the index around when it's outside the list length:

```<code>newindex = (index + rotate) % len(alpha)
</code>```

To repeat, use a while True: loop, and use break to end it.

```<code>def start():
    while True:
        msg = intro()
        if msg == '':
            break
        text = shift(msg)
        print("Your encryptions is: " + text)
</code>```

This will end when the user inputs an empty line.

Body:
Im trying to make an encryption program

def intro():
    msg = input("Enter the message you wish to encrypt: ")
    return msg

def shift(msg):
    alpha = ['a', 'b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    rotate = int(input("The level of the encryption?: "))
    text = ""
    for ch in msg:
        if ch == " " or ch == ".":
            pass
        elif msg == "$":
            print("nah")
        else:
            index = alpha.index(ch)
            newindex = index + rotate
            new= alpha[newindex]
            text += new
    return text

def start():
    msg = intro()
    text = shift(msg)
    print("Your encryptions is: " + text)

start()

I can't figure out a way to loop the list without getting an index out of range error. For example, if you put "z" it will shift to an  "a". I also need for my program to loop till user inputs to end it.  I just started coding in python a few months ago so any help will be appreciated!beginner

Body:
use the modulus operator to wrap the index around when it's outside the list length:

newindex = (index + rotate) % len(alpha)

To repeat, use a while True: loop, and use break to end it.

def start():
    while True:
        msg = intro()
        if msg == '':
            break
        text = shift(msg)
        print("Your encryptions is: " + text)

This will end when the user inputs an empty line.


问:
dplyr filter() with SQL-like %wildcard%
Suppose I have the following data:

```<code>foo <- data.frame(Company = c("company1", "foo", "test", "food"), Metric = rnorm(4, 10))

> foo
   Company    Metric
1 company1 10.539970
2      foo  9.487823
3     test  9.663994
4     food  9.499327
</code>```

Why does the following code return 0 results (instead of the second and fourth rows)?

```<code>library(dplyr)
library(data.table)

foo %>% dplyr::filter(Company %like% "%foo%")
</code>```

I'm trying to use the SQL-equivalent wildcard filter on a particular input string to dplyr::filter, using the %like% operator from the data.table package.

What am I doing wrong?

答:
You can use with library(stringr)

```<code>library(dplyr)
library(stringr)
foo <- data.frame(Company = c("company1", "foo", "test", "food"), Metric = rnorm(4, 10))

foo %>% filter(str_detect(Company,"foo"))
</code>```

as well as any other Regular expression

```<code>foo %>% filter(str_detect(Company,"^f"))
</code>```

ContentLicense: CC BY-SA 4.0

Title: dplyr filter() with SQL-like %wildcard%

Body:
Suppose I have the following data:

foo <- data.frame(Company = c("company1", "foo", "test", "food"), Metric = rnorm(4, 10))

> foo
   Company    Metric
1 company1 10.539970
2      foo  9.487823
3     test  9.663994
4     food  9.499327

Why does the following code return 0 results (instead of the second and fourth rows)?

library(dplyr)
library(data.table)

foo %>% dplyr::filter(Company %like% "%foo%")

I'm trying to use the SQL-equivalent wildcard filter on a particular input string to dplyr::filter, using the %like% operator from the data.table package.

What am I doing wrong?

Body:
You can use with library(stringr)

library(dplyr)
library(stringr)
foo <- data.frame(Company = c("company1", "foo", "test", "food"), Metric = rnorm(4, 10))

foo %>% filter(str_detect(Company,"foo"))

as well as any other Regular expression

foo %>% filter(str_detect(Company,"^f"))


问:
How to print parts of an 2d array
Im not asking for the answer per say im asking necessarily what would i need to change in order to print out sections of a 2d array for example if the array has 5 rows and 5 columns how would i print out the last 3 rows and last three columns.</p>

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

public class multiplication {
    static int a,b;
    public static void main(String[] args){
    Scanner input = new Scanner(System.in);
    a =input.nextInt();
    b = input.nextInt();

 int[][] matrix = new int[a][b];

matrix = timesTable(a,b);

for (int row = 0; row < matrix.length; row++) {
    for (int column = 0; column < matrix[row].length; column++) {
        System.out.print(" "+matrix[row][column] + "\t|");
        }
      System.out.println();
      }

}

public static int[][] timesTable(int r, int c)
{
    int [][] yes = new int[c][c];
    for ( r = 0; r < yes.length ; r++)
    {
        for (c = 0; c < yes[r].length; c++)
        {

                 yes[r][c] = (r+1)*(c+1);

        }
             }

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

答:
```<code>if((row = 0 && col > 1) ||( row > 1 && col != 1)) {
    //print
}
</code>```

This logic should work for your example. But I don't understand what you're trying to do.
Can you try explain a bit more what you want to do ?

Edit: you might wanna check this. Oracle documentation bottom of the page with arraycopy and arraymanipulation

Title: How to print parts of an 2d array

Body:
Im not asking for the answer per say im asking necessarily what would i need to change in order to print out sections of a 2d array for example if the array has 5 rows and 5 columns how would i print out the last 3 rows and last three columns.

   import java.util.Scanner;

public class multiplication {
    static int a,b;
    public static void main(String[] args){
    Scanner input = new Scanner(System.in);
    a =input.nextInt();
    b = input.nextInt();

 int[][] matrix = new int[a][b];

matrix = timesTable(a,b);

for (int row = 0; row < matrix.length; row++) {
    for (int column = 0; column < matrix[row].length; column++) {
        System.out.print(" "+matrix[row][column] + "\t|");
        }
      System.out.println();
      }

}

public static int[][] timesTable(int r, int c)
{
    int [][] yes = new int[c][c];
    for ( r = 0; r < yes.length ; r++)
    {
        for (c = 0; c < yes[r].length; c++)
        {

                 yes[r][c] = (r+1)*(c+1);

        }
             }

    return yes;
}
}

Body:
if((row = 0 && col > 1) ||( row > 1 && col != 1)) {
    //print
}

This logic should work for your example. But I don't understand what you're trying to do.
Can you try explain a bit more what you want to do ?

Edit: you might wanna check this. Oracle documentation bottom of the page with arraycopy and arraymanipulation


问:
Unable to cast page as page class
I'm attempting to access data on a parent page from a user control. I understand this is not the best way to go about it and I do not want to get into that debate. This is HOW I have to go about it due to constraints beyond my control and pay grade.

I should be able to do this:

```<code>myWebBase myPage = (myWebBase) Parent.Page;
int x = myPage.getX();
</code>```

But the class name myWebBase is not recognized. Anyone have any ideas why?

答:
I wonder if its related to this kind of issue:

Any reference to profilecommon causes error Value cannot be null. Parameter name: type  ?

Title: Unable to cast page as page class

Body:
I'm attempting to access data on a parent page from a user control. I understand this is not the best way to go about it and I do not want to get into that debate. This is HOW I have to go about it due to constraints beyond my control and pay grade.

I should be able to do this:

myWebBase myPage = (myWebBase) Parent.Page;
int x = myPage.getX();

But the class name myWebBase is not recognized. Anyone have any ideas why?


答:
Since your code is running fine, I can tell you about some techniques you can work on to get the functionality you want.

To get an array that loops around, you can use a mod system. For example 8 mod 3 = 2 and it would be coded remainder = 8 % 3. If you had a mod size 26, i.e. the alphabet, you could take the remainder of the total number and use it as an index in your alphabet list. This would cycle around when the total number is greater than 26 and begin again at a.

To get the program to end on user input, you can use a variety of methods such as keyboard interrupts, recognizing certain commands such as ctrl-c or whole words. Here is a start from a previous stackoverflow question. How to kill a while loop with a keystroke?

Title: How to let user end program and shift list


问:
Writing Files in HDFS- Using TextIO API vs Java - BufferedWriter(new FileWriter())
We have a requirement that we need to create files for each and every Employee ID. We used the groupbyKey feature and able to create the data structure.
< ID, Iterable < Employee Objects > > where we converted Iterable < Employee > to List.
Then we created a folder and a file for the Employee ID.
So in < EmployeeID, List < Employee > > object, for each and every row we loop and using BufferedWriter we write data into the file. IS it good enough or we need to use TextIO framework to do the same thing. The question is whether we will get drastic performance improvements using TextIO when compared to BufferedWriter to write data in files each and every row.

Thanks

答:
It is surprisingly difficult to write files in a way that produces well-defined results and no data loss or duplication in case of failures. You can get a glimpse of this complexity by looking at the implementation of the WriteFiles transform, used by TextIO under the hood. So TextIO handles this complexity for you, and I strongly recommend using it, if you can - rather than using hand-crafted code. You probably want the write().to(DynamicDestinations) version.

If you're doing something that TextIO definitely can not do, I still recommend looking at the implementation of WriteFiles to get an understanding of what else needs to be done to make sure your code is resilient against failures.


问:
Launch Image names of iPhoneX?
A question about iPhoneX.  I want put  Launch Image of iPhoneX( 1125px × 2436px) in common folder. Not in LaunchImage source.   What's the  Launch Image names of iPhoneX? just like 'Default-iOS8-736h@3x', I can not found the name in  https://developer.apple.com/ios/human-interface-guidelines/icons-and-images/launch-screen/ .</p>

答:
You can add static launch image for iPhone X, only add:
Default-375w-812h@3x.png</p>

Title: Launch Image names of iPhoneX?


问:
How to "perfectly" override a dict?
How can I make as "perfect" a subclass of dict as possible? The end goal is to have a simple dict in which the keys are lowercase.

It would seem that there should be some tiny set of primitives I can override to make this work, but according to all my research and attempts it seem like this isn't the case:

If I override __getitem__/__setitem__, then get/set don't work.    How can I make them work?  Surely I don't need to implement them individually?

Am I preventing pickling from working, and do I need to implement __setstate__ etc?

Do I need repr, update and __init__?

Should I just use mutablemapping (it seems one shouldn't use UserDict
or DictMixin)?  If so, how? The docs aren't exactly enlightening.

Here is my first go at it, get() doesn't work and no doubt there are many other minor problems:

```<code>class arbitrary_dict(dict):
    """A dictionary that applies an arbitrary key-altering function
       before accessing the keys."""

    def __keytransform__(self, key):
        return key

    # Overridden methods. List from
    # https://stackoverflow.com/questions/2390827/how-to-properly-subclass-dict

    def __init__(self, *args, **kwargs):
        self.update(*args, **kwargs)

    # Note: I'm using dict directly, since super(dict, self) doesn't work.
    # I'm not sure why, perhaps dict is not a new-style class.

    def __getitem__(self, key):
        return dict.__getitem__(self, self.__keytransform__(key))

    def __setitem__(self, key, value):
        return dict.__setitem__(self, self.__keytransform__(key), value)

    def __delitem__(self, key):
        return dict.__delitem__(self, self.__keytransform__(key))

    def __contains__(self, key):
        return dict.__contains__(self, self.__keytransform__(key))

class lcdict(arbitrary_dict):
    def __keytransform__(self, key):
        return str(key).lower()
</code>```

答:
After trying out both of the top two suggestions, I've settled on a shady-looking middle route for Python 2.7.  Maybe 3 is saner, but for me:

```<code>class MyDict(MutableMapping):
   # ... the few __methods__ that mutablemapping requires
   # and then this monstrosity
   @property
   def __class__(self):
       return dict
</code>```

which I really hate, but seems to fit my needs, which are:

can override **my_dict

if you inherit from dict, this bypasses your code.  try it out.

this makes #2 unacceptable for me at all times, as this is quite common in python code

masquerades as isinstance(my_dict, dict)

rules out MutableMapping alone, so #1 is not enough

I heartily recommend #1 if you don't need this, it's simple and predictable

fully controllable behavior

so I cannot inherit from dict

If you need to tell yourself apart from others, personally I use something like this (though I'd recommend better names):

```<code>def __am_i_me(self):
  return True

@classmethod
def __is_it_me(cls, other):
  try:
    return other.__am_i_me()
  except Exception:
    return False
</code>```

As long as you only need to recognize yourself internally, this way it's harder to accidentally call __am_i_me due to python's name-munging (this is renamed to _MyDict__am_i_me from anything calling outside this class).  Slightly more private than _methods, both in practice and culturally.

So far I have no complaints, aside from the seriously-shady-looking __class__ override.  I'd be thrilled to hear of any problems that others encounter with this though, I don't fully understand the consequences.  But so far I've had no problems whatsoever, and this allowed me to migrate a lot of middling-quality code in lots of locations without needing any changes.

As evidence: https://repl.it/repls/TraumaticToughCockatoo

Basically: copy the current #2 option, add print 'method_name' lines to every method, and then try this and watch the output:

```<code>d = LowerDict()  # prints "init", or whatever your print statement said
print '------'
splatted = dict(**d)  # note that there are no prints here
</code>```

You'll see similar behavior for other scenarios.  Say your fake-dict is a wrapper around some other datatype, so there's no reasonable way to store the data in the backing-dict; **your_dict will be empty, regardless of what every other method does.

This works correctly for MutableMapping, but as soon as you inherit from dict it becomes uncontrollable.

Edit: as an update, this has been running without a single issue for almost two years now, on several hundred thousand (eh, might be a couple million) lines of complicated, legacy-ridden python.  So I'm pretty happy with it :)

Edit 2: apparently I mis-copied this or something long ago.  @classmethod __class__ does not work for isinstance checks - @property __class__ does: https://repl.it/repls/UnitedScientificSequence

Title: How to "perfectly" override a dict?

Body:
How can I make as "perfect" a subclass of dict as possible? The end goal is to have a simple dict in which the keys are lowercase.

It would seem that there should be some tiny set of primitives I can override to make this work, but according to all my research and attempts it seem like this isn't the case:

If I override __getitem__/__setitem__, then get/set don't work.    How can I make them work?  Surely I don't need to implement them individually?

Am I preventing pickling from working, and do I need to implement __setstate__ etc?

Do I need repr, update and __init__?

Should I just use mutablemapping (it seems one shouldn't use UserDict
or DictMixin)?  If so, how? The docs aren't exactly enlightening.

Here is my first go at it, get() doesn't work and no doubt there are many other minor problems:

class arbitrary_dict(dict):
    """A dictionary that applies an arbitrary key-altering function
       before accessing the keys."""

    def __keytransform__(self, key):
        return key

    # Overridden methods. List from
    # https://stackoverflow.com/questions/2390827/how-to-properly-subclass-dict

    def __init__(self, *args, **kwargs):
        self.update(*args, **kwargs)

    # Note: I'm using dict directly, since super(dict, self) doesn't work.
    # I'm not sure why, perhaps dict is not a new-style class.

    def __getitem__(self, key):
        return dict.__getitem__(self, self.__keytransform__(key))

    def __setitem__(self, key, value):
        return dict.__setitem__(self, self.__keytransform__(key), value)

    def __delitem__(self, key):
        return dict.__delitem__(self, self.__keytransform__(key))

    def __contains__(self, key):
        return dict.__contains__(self, self.__keytransform__(key))

class lcdict(arbitrary_dict):
    def __keytransform__(self, key):
        return str(key).lower()

Body:
After trying out both of the top two suggestions, I've settled on a shady-looking middle route for Python 2.7.  Maybe 3 is saner, but for me:

class MyDict(MutableMapping):
   # ... the few __methods__ that mutablemapping requires
   # and then this monstrosity
   @property
   def __class__(self):
       return dict

which I really hate, but seems to fit my needs, which are:

can override **my_dict

if you inherit from dict, this bypasses your code.  try it out.

this makes #2 unacceptable for me at all times, as this is quite common in python code

masquerades as isinstance(my_dict, dict)

rules out MutableMapping alone, so #1 is not enough

I heartily recommend #1 if you don't need this, it's simple and predictable

fully controllable behavior

so I cannot inherit from dict

If you need to tell yourself apart from others, personally I use something like this (though I'd recommend better names):

def __am_i_me(self):
  return True

@classmethod
def __is_it_me(cls, other):
  try:
    return other.__am_i_me()
  except Exception:
    return False

As long as you only need to recognize yourself internally, this way it's harder to accidentally call __am_i_me due to python's name-munging (this is renamed to _MyDict__am_i_me from anything calling outside this class).  Slightly more private than _methods, both in practice and culturally.

So far I have no complaints, aside from the seriously-shady-looking __class__ override.  I'd be thrilled to hear of any problems that others encounter with this though, I don't fully understand the consequences.  But so far I've had no problems whatsoever, and this allowed me to migrate a lot of middling-quality code in lots of locations without needing any changes.

As evidence: https://repl.it/repls/TraumaticToughCockatoo

Basically: copy the current #2 option, add print 'method_name' lines to every method, and then try this and watch the output:

d = LowerDict()  # prints "init", or whatever your print statement said
print '------'
splatted = dict(**d)  # note that there are no prints here

You'll see similar behavior for other scenarios.  Say your fake-dict is a wrapper around some other datatype, so there's no reasonable way to store the data in the backing-dict; **your_dict will be empty, regardless of what every other method does.

This works correctly for MutableMapping, but as soon as you inherit from dict it becomes uncontrollable.

Edit: as an update, this has been running without a single issue for almost two years now, on several hundred thousand (eh, might be a couple million) lines of complicated, legacy-ridden python.  So I'm pretty happy with it :)

Edit 2: apparently I mis-copied this or something long ago.  @classmethod __class__ does not work for isinstance checks - @property __class__ does: https://repl.it/repls/UnitedScientificSequence


问:
Open a Form under a DataGridView Cell
I try to open a form just below a DataGridView header cell. I have this (and it is not working):

```<code>private void button1_Click(object sender, EventArgs e)
{
    Form aForm = new Form();

    aForm.Text = @"Test";
    aForm.Top = this.Top + dataGridView1.Top - dataGridView1.GetCellDisplayRectangle(0, 0, false).Height;
    aForm.Left =  this.Left + dataGridView1.GetCellDisplayRectangle(0, 0, false).Left;
    aForm.Width = 25;
    aForm.Height = 100;
    aForm.ShowDialog();
}
</code>```

I don't see how to get the right top and left based on the DataGridView cell.

答:
Should you consider to use a Form, you have to calculate its Location using Screen coordinates:

```<code>Form form = new Form();
form.StartPosition = FormStartPosition.Manual;
form.FormBorderStyle = FormBorderStyle.FixedSingle;
form.Size = new Size(dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex].Width, 100);

Point c = dataGridView1.PointToScreen(dataGridView1.GetCellDisplayRectangle(
                                      dataGridView1.CurrentCell.ColumnIndex,
                                      dataGridView1.CurrentCell.RowIndex, false).Location);
form.Location = new Point(c.X, c.Y);
form.BringToFront();
form.Show(this);
</code>```

If you find youself in trouble using a Form, you might consider using a Panel instead:

```<code>Point c = dataGridView1.PointToScreen(dataGridView1.GetCellDisplayRectangle(
                        dataGridView1.CurrentCell.ColumnIndex,
                        dataGridView1.CurrentCell.RowIndex, false).Location);
Point r = this.PointToClient(c);
panel1.Location = new Point(r.X, r.Y);
panel1.BringToFront();
</code>```

Take also a look at How do I to get the current cell position x and y in a DataGridView?

and Position new form directly under Datagridview selected row of parent

Title: Open a Form under a DataGridView Cell

Body:
I try to open a form just below a DataGridView header cell. I have this (and it is not working):

private void button1_Click(object sender, EventArgs e)
{
    Form aForm = new Form();

    aForm.Text = @"Test";
    aForm.Top = this.Top + dataGridView1.Top - dataGridView1.GetCellDisplayRectangle(0, 0, false).Height;
    aForm.Left =  this.Left + dataGridView1.GetCellDisplayRectangle(0, 0, false).Left;
    aForm.Width = 25;
    aForm.Height = 100;
    aForm.ShowDialog();
}

I don't see how to get the right top and left based on the DataGridView cell.

Body:
Should you consider to use a Form, you have to calculate its Location using Screen coordinates:

Form form = new Form();
form.StartPosition = FormStartPosition.Manual;
form.FormBorderStyle = FormBorderStyle.FixedSingle;
form.Size = new Size(dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex].Width, 100);

Point c = dataGridView1.PointToScreen(dataGridView1.GetCellDisplayRectangle(
                                      dataGridView1.CurrentCell.ColumnIndex,
                                      dataGridView1.CurrentCell.RowIndex, false).Location);
form.Location = new Point(c.X, c.Y);
form.BringToFront();
form.Show(this);

If you find youself in trouble using a Form, you might consider using a Panel instead:

Point c = dataGridView1.PointToScreen(dataGridView1.GetCellDisplayRectangle(
                        dataGridView1.CurrentCell.ColumnIndex,
                        dataGridView1.CurrentCell.RowIndex, false).Location);
Point r = this.PointToClient(c);
panel1.Location = new Point(r.X, r.Y);
panel1.BringToFront();

Take also a look at How do I to get the current cell position x and y in a DataGridView?

and Position new form directly under Datagridview selected row of parent