问:
Is there a way to stop a tkinter class object from opening until the button is opened
I have a little problem with my code. I am writing multiples classes with different GUI interfaces as a project. However, every time I import those classes the GUI window automatically opens the window and I want the window to open only when a button is clicked.

```<code>from FinalProject import addFlight
from FinalProject import reserveFlight

class ex:
    def __init__(self,win):
        self.win = win
        ...
        ...

def mainButtons(self):
    look = Button(self.win, text="Add New Flight",command=lambda: self.reserveMenu(1))
    look.place(relx="0.2", rely="0.3")

    res = Button(self.win, text="Book A Flight",command=lambda: self.reserveMenu(2))
    res.place(relx="0.4", rely="0.3")
      ...
      ...

def reserveMenu(self, options):
    if options == 1:
        self.flight = Toplevel(self.win)
        self.flMenu = addFlight.AddFlights(self.flight)
        self.flMenu.addingFlight()
        # call(["python","addFlight.py"])
    if options == 2:
        pass
        # self.flight = Toplevel(self.win)
        # self.flMenu = reserveFlight.ReserveFlights(self.flight)
        # self.flMenu.reserve()
        # call(["python","reserveFlight.py"])
       ...
       ...
</code>```

The "reserveMenu" function works fine but is there way to suppress those import statements or at least prevent the windows from opening until the button is clicked.

I know there are other methods of opening my python code but this HAS to be done using CLASSES. Trust me I have found way easier methods of doing this. FYI, there is more code but I only copied the more important parts.

答:
Instead of using a method you could define your reserve option windows as classes, ReserveAdd, ReserveBook, that inherit from tkinter.Toplevel. And all a button would do is to call them. Here's an example:

```<code>import tkinter as tk

root = tk.Tk()

class ReserveAdd(tk.Toplevel):
    def __init__(self, master):
        super().__init__(master)
        self.master = master
        tk.Label(self, text="This is ReserveAdd window.").pack()

class ReserveBook(tk.Toplevel):
    def __init__(self, master):
        super().__init__(master)
        self.master = master
        tk.Label(self, text="This is ReserveBook window.").pack()

def res_one():
    ReserveAdd(root)

def res_two():
    ReserveBook(root)

tk.Button(root, text="Reserve Option 1", command=res_one).pack()
tk.Button(root, text="Reserve Option 2", command=res_two).pack()

root.mainloop()
</code>```

In the above example Reserve Option 1 calls an instance of ReserveAdd class whereas Reserve Option 2 calls an instance of a ReserveBook class.

I'd define a single method for buttons but that's not exactly the scope here.

Body:
I have a little problem with my code. I am writing multiples classes with different GUI interfaces as a project. However, every time I import those classes the GUI window automatically opens the window and I want the window to open only when a button is clicked.

from FinalProject import addFlight
from FinalProject import reserveFlight

class ex:
    def __init__(self,win):
        self.win = win
        ...
        ...

def mainButtons(self):
    look = Button(self.win, text="Add New Flight",command=lambda: self.reserveMenu(1))
    look.place(relx="0.2", rely="0.3")

    res = Button(self.win, text="Book A Flight",command=lambda: self.reserveMenu(2))
    res.place(relx="0.4", rely="0.3")
      ...
      ...

def reserveMenu(self, options):
    if options == 1:
        self.flight = Toplevel(self.win)
        self.flMenu = addFlight.AddFlights(self.flight)
        self.flMenu.addingFlight()
        # call(["python","addFlight.py"])
    if options == 2:
        pass
        # self.flight = Toplevel(self.win)
        # self.flMenu = reserveFlight.ReserveFlights(self.flight)
        # self.flMenu.reserve()
        # call(["python","reserveFlight.py"])
       ...
       ...

The "reserveMenu" function works fine but is there way to suppress those import statements or at least prevent the windows from opening until the button is clicked.

I know there are other methods of opening my python code but this HAS to be done using CLASSES. Trust me I have found way easier methods of doing this. FYI, there is more code but I only copied the more important parts.

Body:
Instead of using a method you could define your reserve option windows as classes, ReserveAdd, ReserveBook, that inherit from tkinter.Toplevel. And all a button would do is to call them. Here's an example:

import tkinter as tk

root = tk.Tk()

class ReserveAdd(tk.Toplevel):
    def __init__(self, master):
        super().__init__(master)
        self.master = master
        tk.Label(self, text="This is ReserveAdd window.").pack()

class ReserveBook(tk.Toplevel):
    def __init__(self, master):
        super().__init__(master)
        self.master = master
        tk.Label(self, text="This is ReserveBook window.").pack()

def res_one():
    ReserveAdd(root)

def res_two():
    ReserveBook(root)

tk.Button(root, text="Reserve Option 1", command=res_one).pack()
tk.Button(root, text="Reserve Option 2", command=res_two).pack()

root.mainloop()

In the above example Reserve Option 1 calls an instance of ReserveAdd class whereas Reserve Option 2 calls an instance of a ReserveBook class.

I'd define a single method for buttons but that's not exactly the scope here.


来源: stackexchange

问:
Adding Some Extra calculation during the time of Sum on mongodb $sum function
My Mongo-Db dataset is this:

```<code>{
    "_id" : ObjectId("5a267533754884223467604a"),
    "user_id" : "5a20ee1acdacc7086ce7742c",
    "tv_count" : 1,
    "ac_count" : 0,
    "fridge_count" : 0,
    "blower_count" : 0,
    "chair_count" : 0,
    "sofa_count" : 0,
    "D2H_count" : 2,
    "lastmodified" : ISODate("2017-12-05T10:30:30.559Z"),
    "__v" : 0
}
</code>```

So I know i want to do some modification during the time of Sum.
My Sum Code is this:

```<code>Accessories.aggregate([
                {$match: { "lastmodified":{$gt: newTime}}},
                {
                    $project: {
                        total: {
                            $add: [ "$tv_count", "$ac_count", "$fridge_count", "$blower_count", "$chair_count", "$sofa_count", "$D2H_count"]
                        }
                    }
                }
            ]);
</code>```

So it will return the result

```<code>[ { _id: 5a267533754884223467604a, total: 3 } ]
</code>```

Now I want to do some extra calculation. Example is

```<code>Earlier Result will be 1+0+0+0+0+0+2 = 3

My desire result will be like (1*2)+0+0+0+0+0+(2*4) = 10
</code>```

Any Help will be appreciated.

答:
You can simply include additional nested calculations inside your existing projection like so:

```<code>$project: {
    total: {
        $add: [ { $multiply: [ "$tv_count", 2 ] }, "$ac_count", "$fridge_count", "$blower_count", "$chair_count", "$sofa_count", { $multiply: [ "$D2H_count", 4 ] }]
    }
}
</code>```

You should not use the $addFields or any other additional stage for this type of thing, really, since adding stages will slow down the aggregation pipeline and adding fields in particular will inflate the interim result documents between the stages so again slow down your query.

ContentLicense: CC BY-SA 3.0

Body:
My Mongo-Db dataset is this:

{
    "_id" : ObjectId("5a267533754884223467604a"),
    "user_id" : "5a20ee1acdacc7086ce7742c",
    "tv_count" : 1,
    "ac_count" : 0,
    "fridge_count" : 0,
    "blower_count" : 0,
    "chair_count" : 0,
    "sofa_count" : 0,
    "D2H_count" : 2,
    "lastmodified" : ISODate("2017-12-05T10:30:30.559Z"),
    "__v" : 0
}

So I know i want to do some modification during the time of Sum.
My Sum Code is this:

Accessories.aggregate([
                {$match: { "lastmodified":{$gt: newTime}}},
                {
                    $project: {
                        total: {
                            $add: [ "$tv_count", "$ac_count", "$fridge_count", "$blower_count", "$chair_count", "$sofa_count", "$D2H_count"]
                        }
                    }
                }
            ]);

So it will return the result

[ { _id: 5a267533754884223467604a, total: 3 } ]

Now I want to do some extra calculation. Example is

Earlier Result will be 1+0+0+0+0+0+2 = 3

My desire result will be like (1*2)+0+0+0+0+0+(2*4) = 10

Any Help will be appreciated.

Body:
You can simply include additional nested calculations inside your existing projection like so:

$project: {
    total: {
        $add: [ { $multiply: [ "$tv_count", 2 ] }, "$ac_count", "$fridge_count", "$blower_count", "$chair_count", "$sofa_count", { $multiply: [ "$D2H_count", 4 ] }]
    }
}

You should not use the $addFields or any other additional stage for this type of thing, really, since adding stages will slow down the aggregation pipeline and adding fields in particular will inflate the interim result documents between the stages so again slow down your query.


问:
make a DLL work on MacOS
I have a Jar application that I use on Windows, it uses some DLL files to send and receive messages from them, so i'm trying to find a way to make it work on MacOS, I tried to run the jar first to see what will happen:

```<code>java -cp myApp.jar
</code>```

It worked until the time that the app requires one of the DLLs, so I got this:

```<code>/Users/XXX/Java/bin/myDLL.dll: unknown file type, first eight bytes: 0x4D 0x5A 0x90 0x00 0x03 0x00 0x00 0x00
</code>```

I found some tips to use Wine, but I don't have any idea how to convert those DLLs so the app can use them on MacOS.

Note: The Jar app has many files like DLLs, GIFs, and INI files that are needed to work.

答: Java itself is cross-platform, but native code such as your DLL is not.  Under no circumstances can you expect to load a Windows DLL directly into your OS X JVM and run anything within.  You could, however, run your code on OS X in a Windows JVM via a Windows emulation layer such as Crossover Mac or Parallels Desktop.  Note that these are both commercial products, however, as are most others in this category, and also that OS emulation imposes a performance cost.

Title: make a DLL work on MacOS

Body:
I have a Jar application that I use on Windows, it uses some DLL files to send and receive messages from them, so i'm trying to find a way to make it work on MacOS, I tried to run the jar first to see what will happen:

java -cp myApp.jar

It worked until the time that the app requires one of the DLLs, so I got this:

/Users/XXX/Java/bin/myDLL.dll: unknown file type, first eight bytes: 0x4D 0x5A 0x90 0x00 0x03 0x00 0x00 0x00

I found some tips to use Wine, but I don't have any idea how to convert those DLLs so the app can use them on MacOS.

Note: The Jar app has many files like DLLs, GIFs, and INI files that are needed to work.


问:
Make Seekbar thumb easier to grab
So I have a SeekBar but the little circle thumb thing is kind of hard to grab. Is there a way to make the hitbox larger? I don't necessarily care if the graphic itself looks any different -- I just want it to be grabbable.</p>

答:
You want an inset drawable resource. This answer to the question "Offset shape within a ShapeDrawable" https://stackoverflow.com/a/3674134/3175580 happens to be the same thing, you're asking. Like the other answer, you'll still need to copy the target drawable if it's private.

The advantage (or disadvantage) is that this shows you exactly how much you're increasing the size by, instead of the total size. Plus, I think it saves memory because using a Transparent shape will create a transparent bitmap of that size (?).

Title: Make Seekbar thumb easier to grab


问:
How does instructions like I/O work in user mode?
I am curious because I am reading this OS book which mentions

"User programs always run in user mode, which permits only a subset of the instructions [...]. Generally, all instructions involving I/O and memory protection are disallowed in user mode.
To obtain services from the OS, a user program must make a system call, which traps into the kernel and invokes the OS."

If I/O is not allowed generally in user mode, but let's say I have a program in C++ or Java which asks for input, or let's say something else like a search bar in any program. Whenever I select the search bar (meaning I will write something) then a TRAP instruction is called to invoke the OS (since the OS runs in kernel) to be able to have access to I/O, that is, the keyboard? I am not sure if I follow correctly or what am I getting wrong.

The I/O is not allowed in user mode, but you use Input for applications in the OS, or even with the OS itself there are keyboard commands. If you can use keyboard commands that means the OS is ready for I/O at any time. Then the original statement about I/O instructions being disallowed in user mode.

I am sorry for my ignorance but I am just a little bit confused with these terms and difference between user and kernel. I know the OS runs in kernel mode, and the applications run in the OS, so in the end the applications do have access to I/O.

答:
It is important to understand what "user-mode" and "kernel-mode" mean. A process is mapped to memory regions which are user-priviliged, depending on the memory layout.
 Kernel-mode is basically routines that are in supervisor priviliged memory regions, which are invoked by your program to do the desired work (I/O).


问:
React router ignoring slash in URL
React router renders both Foo and FooBar for the route /foo/bar

```<code>ReactDOM.render(
(<BrowserRouter>
        <div>
                <Route path="/foo/bar" component={FooBar}/>
                <Route path="/foo" component={Foo}/>
        </div>
</BrowserRouter>)
, document.getElementById("root"));
</code>```

Why on earth would it run both routes? I think this is insane.

How would I use nested routes (without :/params in case I want to do more than one nested route? Such as /foo/bar/baz/whatever?).

Would an answer to this question even make sense without mentioning which version I'm on?

答:
With React Router V4, you can use the Switch component to ensure only the first matched route is rendered:

```<code>import { Switch, Route } from 'react-router-dom'

...

<Switch>
  <Route path="/foo/bar" component={FooBar}/>
  <Route path="/foo" component={Foo}/>
</Switch>
</code>```

You could also use the exact prop to ensure the /foo route is only matched when the url is /foo and not /foo/bar:

```<code><Route path="/foo" exact component={Foo}/>
<Route path="/foo/bar" component={FooBar}/>
</code>```

Title: React router ignoring slash in URL

Body:
React router renders both Foo and FooBar for the route /foo/bar

ReactDOM.render(
(<BrowserRouter>

                <Route path="/foo/bar" component={FooBar}/>
                <Route path="/foo" component={Foo}/>

</BrowserRouter>)
, document.getElementById("root"));

Why on earth would it run both routes? I think this is insane.

How would I use nested routes (without :/params in case I want to do more than one nested route? Such as /foo/bar/baz/whatever?).

Would an answer to this question even make sense without mentioning which version I'm on?

Body:
With React Router V4, you can use the Switch component to ensure only the first matched route is rendered:

import { Switch, Route } from 'react-router-dom'

...

<Switch>
  <Route path="/foo/bar" component={FooBar}/>
  <Route path="/foo" component={Foo}/>
</Switch>

You could also use the exact prop to ensure the /foo route is only matched when the url is /foo and not /foo/bar:

<Route path="/foo" exact component={Foo}/>
<Route path="/foo/bar" component={FooBar}/>


问:
C++ Classes, Default Constructors
To keep it simple and to the point, I have a class

```<code>class square
{
public:
    square(int s); // parameterized constructor with default parameter = 0
    square();

private:
    int side; // holds the side of the square (whole number)
};

square::square() {

    side = 0;
}

square::square(int s){

    side = 0; // parameterized constructor with default parameter = 0
}
</code>```

and in the main I have the following:

```<code>int main()
{
    square sq1;// declare 4 objects of type square named sq1, sq2, sq3, and sq4 initializing the third one to 10
    square sq2;
    square sq3(10);
    square sq4;
}
</code>```

The problem is that if I comment out square(); in the class, the square sq1, sq2 and sq4 won't work.
I need to initialize square(int s) as a default constructor set to 0 and only use that for all four square sq's. How would I go about fixing that?

答:
Remove the default constructor (square(); ) completely and modify your parametrized constructor definition as shown below.

```<code>square::square(int s = 0) {

    side = s; // parameterized constructor with default parameter = 0
}
</code>```

Title: C++ Classes, Default Constructors

Body:
To keep it simple and to the point, I have a class

class square
{
public:
    square(int s); // parameterized constructor with default parameter = 0
    square();

private:
    int side; // holds the side of the square (whole number)
};

square::square() {

    side = 0;
}

square::square(int s){

    side = 0; // parameterized constructor with default parameter = 0
}

and in the main I have the following:

int main()
{
    square sq1;// declare 4 objects of type square named sq1, sq2, sq3, and sq4 initializing the third one to 10
    square sq2;
    square sq3(10);
    square sq4;
}

The problem is that if I comment out square(); in the class, the square sq1, sq2 and sq4 won't work.
I need to initialize square(int s) as a default constructor set to 0 and only use that for all four square sq's. How would I go about fixing that?

Body:
Remove the default constructor (square(); ) completely and modify your parametrized constructor definition as shown below.

square::square(int s = 0) {

    side = s; // parameterized constructor with default parameter = 0
}


问:
vba date comparison
I have an access table where dates are stored in the format "25102010". How can I compare this to today's date? Thanks.</p>

答:
This will give you todays date formatted as you have above</p>

```<code>Format(Date, "ddmmyyyy")
</code>```

ContentLicense: CC BY-SA 2.5

Title: vba date comparison

Body:
This will give you todays date formatted as you have above

Format(Date, "ddmmyyyy")


问:
Changing the child element's CSS when the parent is hovered
First of all, I'm assuming this is too complex for CSS3, but if there's a solution in there somewhere, I'd love to go with that instead.

The HTML is pretty straightforward.

```<code><div class="parent">
    <div class="child">
        Text Block 1
    </div>
</div>

<div class="parent">
    <div class="child">
        Text Block 2
    </div>
</div>
</code>```

The child div is set to display:none; by default, but then changes to display:block; when the mouse is hovered over the parent div. The problem is that this markup appears in several places on my site, and I only want the child to be displayed if the mouse is over it's parent, and not if the mouse is over any of the other parents (they all have the same class name and no IDs).

I've tried using $(this) and .children() to no avail.

```<code>$('.parent').hover(function(){
            $(this).children('.child').css("display","block");
        }, function() {
            $(this).children('.child').css("display","none");
        });
</code>```

答:
Not sure if there's terrible reasons to do this or not, but it seems to work with me on the latest version of Chrome/Firefox without any visible performance problems with quite a lot of elements on the page.

```<code>*:not(:hover)>.parent-hover-show{
    display:none;
}
</code>```

But this way, all you need is to apply parent-hover-show to an element and the rest is taken care of, and you can keep whatever default display type you want without it always being "block" or making multiple classes for each type.

Body:
First of all, I'm assuming this is too complex for CSS3, but if there's a solution in there somewhere, I'd love to go with that instead.

The HTML is pretty straightforward.

        Text Block 1

        Text Block 2

The child div is set to display:none; by default, but then changes to display:block; when the mouse is hovered over the parent div. The problem is that this markup appears in several places on my site, and I only want the child to be displayed if the mouse is over it's parent, and not if the mouse is over any of the other parents (they all have the same class name and no IDs).

I've tried using $(this) and .children() to no avail.

$('.parent').hover(function(){
            $(this).children('.child').css("display","block");
        }, function() {
            $(this).children('.child').css("display","none");
        });

Body:
Not sure if there's terrible reasons to do this or not, but it seems to work with me on the latest version of Chrome/Firefox without any visible performance problems with quite a lot of elements on the page.

*:not(:hover)>.parent-hover-show{
    display:none;
}

But this way, all you need is to apply parent-hover-show to an element and the rest is taken care of, and you can keep whatever default display type you want without it always being "block" or making multiple classes for each type.


问:
Media query min-width not considering devices below a certain width
Why is some devices NOT listening to my media query when the device width is smaller than "375" which is my smallest breakpoint. I use @media (min-width: 375px) { // Rules here }... I get that it "requires" that the device has to be at least "375px" wide, but I can't figure out what's wrong here. It works when I change the 375-breakpoint to 0px... But is that even a correct approach?

In my "media.scss" file, I've it all set up like this:

```<code>@media (min-width: 375px) {}
@media (min-width: 768px) {}
@media (min-width: 992px) {}
@media (min-width: 1280px) {}
</code>```

Everything works fine, but when testing on a device that is smaller than 375 pixels, it doesn't consider the rules. I hope you get what I mean. I've looked how bootstrap has their media queries, and I can't really tell if there is any difference.

答: Create a media query with max-width: 374px and insert your css into it.</p>

Body:
Why is some devices NOT listening to my media query when the device width is smaller than "375" which is my smallest breakpoint. I use @media (min-width: 375px) { // Rules here }... I get that it "requires" that the device has to be at least "375px" wide, but I can't figure out what's wrong here. It works when I change the 375-breakpoint to 0px... But is that even a correct approach?

In my "media.scss" file, I've it all set up like this:

@media (min-width: 375px) {}
@media (min-width: 768px) {}
@media (min-width: 992px) {}
@media (min-width: 1280px) {}

Everything works fine, but when testing on a device that is smaller than 375 pixels, it doesn't consider the rules. I hope you get what I mean. I've looked how bootstrap has their media queries, and I can't really tell if there is any difference.


问:
Convert Unixtime to Datetime SQL (Oracle)
I have a datetime field(P_DT) and I would like to return all results where P_DT is greater then an input unix timestamp.

Does Oracle have any built in functions that can help?

In my searchs I find resuts for DateTime to Unix but no Unix to DateTime...

答:
I used this in the end...</p>

```<code>date=unixtimestamp number

to_date(\'1970-01-01\',\'YYYY-MM-DD\') + numtodsinterval('.$_GET["date"].',\'SECOND\')
</code>```

Body:
I used this in the end...

date=unixtimestamp number

to_date(\'1970-01-01\',\'YYYY-MM-DD\') + numtodsinterval('.$_GET["date"].',\'SECOND\')


问:
Google Script: setOption chartArea doesn't work in Google Spreadsheet embedded chartbuilder
I want to build a chart in my Google spreadsheet.  The chart responds to all options except the chartArea.  I want my labels to show on the left side of the V-Axis.  Now these are hidden behind the chartArea. (photo)

This chart has the labels hidden behind the chartArea

```<code>    var chartBuilder = SS.newChart();
chartBuilder.addRange(range)
.setPosition(10, 2, 0, 0)
   .setChartType(Charts.ChartType.BAR)
     .setOption('height', BVhoogte)
   .setOption('width', 720)
   .setOption('isStacked', true)
   .setOption('legend', { position: "bottom" })
.setOption( 'hAxis', {textStyle:{color:"white"}, gridlines:{color:"white"}})
   .setOption('height', 150)
   .setOption('width',720)
   .setOption('colors', ["#6d6f75","#000000", "#dcdee2"])
   .asBarChart().setOption('chartArea',{ left:200, width: 500}) ;
    SS.insertChart(chartBuilder.build());
</code>```

I've tried

```<code>         .asBarChart().setOption('chartArea.left', 100)
</code>```

but this doesn't work either.

答:
How about the following modification?

From :

```<code>.asBarChart().setOption('chartArea.left', 100)
</code>```

To :

```<code>.asBarChart().setOption('chartArea', {left:'20%', top:'10%', width:"60%", height:"60%"})
</code>```

About each parameter, please adjust for your design. If this was not useful for you, I'm sorry.

Body:
I want to build a chart in my Google spreadsheet.  The chart responds to all options except the chartArea.  I want my labels to show on the left side of the V-Axis.  Now these are hidden behind the chartArea. (photo)

This chart has the labels hidden behind the chartArea

    var chartBuilder = SS.newChart();
chartBuilder.addRange(range)
.setPosition(10, 2, 0, 0)
   .setChartType(Charts.ChartType.BAR)
     .setOption('height', BVhoogte)
   .setOption('width', 720)
   .setOption('isStacked', true)
   .setOption('legend', { position: "bottom" })
.setOption( 'hAxis', {textStyle:{color:"white"}, gridlines:{color:"white"}})
   .setOption('height', 150)
   .setOption('width',720)
   .setOption('colors', ["#6d6f75","#000000", "#dcdee2"])
   .asBarChart().setOption('chartArea',{ left:200, width: 500}) ;
    SS.insertChart(chartBuilder.build());

I've tried

         .asBarChart().setOption('chartArea.left', 100)

but this doesn't work either.

Body:
How about the following modification?

From :

.asBarChart().setOption('chartArea.left', 100)

To :

.asBarChart().setOption('chartArea', {left:'20%', top:'10%', width:"60%", height:"60%"})

About each parameter, please adjust for your design. If this was not useful for you, I'm sorry.


问:
Dynamically growing a python array when assigning to it
I want to populate an array in python so that I can use id numbers to index into the array. Not all indexes will exist in the array and items will not necessarily be added to the array in order. The largest possible index is not known (or at least I'd prefer not to hard code it). Is there a way to dynamically grow the array when assigning?
I.e I want something like

```<code>arr = []
for x in xs
    arr[x.index] = x
</code>```

but this gives "IndexError: list assignment index out of range". I tried using list.insert() but that does not work if the items are not inserted in order, as it changes the index of items already in the array.

Is there a good way to do this in python, or do I have to settle for initializing the array "big enough"?

答:
Python arrays can grow dynamically, but simply assigning to an index does not extend the array.

Arrays have the extend method for adding a bunch of items at once from a collection. For example:

```<code>>>> a = [1, 2, 3]
>>> a.extend([None, None])
>>> a
[1, 2, 3, None, None]
</code>```

You can emulate auto-extending array assignment like this:

```<code>def arr_assign(arr, key, val):
    try:
        arr[key] = val
        return
    except IndexError:
        # Do not extend the array for negative indices
        # That is ridiculously counterintuitive
        assert key >= 0
        arr.extend(((key + 1) - len(arr)) * [None])
        arr[key] = val
        return
</code>```

For example:

```<code>>>> a = []
>>> arr_assign(a, 4, 5)
>>> a
[None, None, None, None, 5]
</code>```

As an addendum, languages that do have the auto-extend behavior by default (e.g. Perl, Ruby, PHP, JavaScript, Lua) tend to be less strict than Python and will return a magical null value if you access a slot in an array that doesn't exist. This means that they can allow auto-extending when assigning to a non-existent index without changing the behavior of the array at any other index.

E.g. In Ruby a[2] doesn't change despite the fact that a has changed underneath it.

```<code>irb(main):006:0> a = []
=> []
irb(main):007:0> a[2]
=> nil
irb(main):008:0> a[4] = 7
=> 7
irb(main):009:0> a
=> [nil, nil, nil, nil, 7]
irb(main):010:0> a[2]
=> nil
</code>```

Body:
I want to populate an array in python so that I can use id numbers to index into the array. Not all indexes will exist in the array and items will not necessarily be added to the array in order. The largest possible index is not known (or at least I'd prefer not to hard code it). Is there a way to dynamically grow the array when assigning?
I.e I want something like

arr = []
for x in xs
    arr[x.index] = x

but this gives "IndexError: list assignment index out of range". I tried using list.insert() but that does not work if the items are not inserted in order, as it changes the index of items already in the array.

Is there a good way to do this in python, or do I have to settle for initializing the array "big enough"?

Body:
Python arrays can grow dynamically, but simply assigning to an index does not extend the array.

Arrays have the extend method for adding a bunch of items at once from a collection. For example:

>>> a = [1, 2, 3]
>>> a.extend([None, None])
>>> a
[1, 2, 3, None, None]

You can emulate auto-extending array assignment like this:

def arr_assign(arr, key, val):
    try:
        arr[key] = val
        return
    except IndexError:
        # Do not extend the array for negative indices
        # That is ridiculously counterintuitive
        assert key >= 0
        arr.extend(((key + 1) - len(arr)) * [None])
        arr[key] = val
        return

For example:

>>> a = []
>>> arr_assign(a, 4, 5)
>>> a
[None, None, None, None, 5]

As an addendum, languages that do have the auto-extend behavior by default (e.g. Perl, Ruby, PHP, JavaScript, Lua) tend to be less strict than Python and will return a magical null value if you access a slot in an array that doesn't exist. This means that they can allow auto-extending when assigning to a non-existent index without changing the behavior of the array at any other index.

E.g. In Ruby a[2] doesn't change despite the fact that a has changed underneath it.

irb(main):006:0> a = []
=> []
irb(main):007:0> a[2]
=> nil
irb(main):008:0> a[4] = 7
=> 7
irb(main):009:0> a
=> [nil, nil, nil, nil, 7]
irb(main):010:0> a[2]
=> nil


问:
How do I programmatically scroll a winforms datagridview control?
I'm implementing some drag drop features in one my controls inheriting from a datagridview. Basically I'm dragging a row from somewhere in the DGV and dropping it somewhere else, reordering the rows. I've run into a problem though. If the DGV is too large such that there's a scrollbar, how can I have the DGV scroll up or down while the user is in the middle of a dragdrop?

I know how to get the current mouse position and also get the position of the dgv rectangle and such. So, I can easily find out if i'm in the top or bottom half of the rectangle... I just need a way to programmatically scroll the dgv. I'd prefer if I don't have to keep changing the selected cell to do this.

Any suggestions?

Thanks

Isaac

答:
You may do that using WinAPI by sending message to the control telling it to scroll up or down.

Here is the code, I hope it helps:

```<code>private const int WM_SCROLL = 276; // Horizontal scroll
private const int WM_VSCROLL = 277; // Vertical scroll
private const int SB_LINEUP = 0; // Scrolls one line up
private const int SB_LINELEFT = 0;// Scrolls one cell left
private const int SB_LINEDOWN = 1; // Scrolls one line down
private const int SB_LINERIGHT = 1;// Scrolls one cell right
private const int SB_PAGEUP = 2; // Scrolls one page up
private const int SB_PAGELEFT = 2;// Scrolls one page left
private const int SB_PAGEDOWN = 3; // Scrolls one page down
private const int SB_PAGERIGTH = 3; // Scrolls one page right
private const int SB_PAGETOP = 6; // Scrolls to the upper left
private const int SB_LEFT = 6; // Scrolls to the left
private const int SB_PAGEBOTTOM = 7; // Scrolls to the upper right
private const int SB_RIGHT = 7; // Scrolls to the right
private const int SB_ENDSCROLL = 8; // Ends scroll

[DllImport("user32.dll",CharSet=CharSet.Auto)]
private static extern int SendMessage(IntPtr hWnd, int wMsg,IntPtr wParam, IntPtr lParam);
</code>```

Now assuming you have a textbox control on your form. You can move it with:

```<code>SendMessage(textBox1.Handle,WM_VSCROLL,(IntPtr)SB_PAGEUP,IntPtr.Zero); //ScrollUp
SendMessage(textBox1.Handle,WM_VSCROLL,(IntPtr)SB_PAGEDOWN,IntPtr.Zero); //ScrollDown
</code>```

If that classic general solution doesn't work for you. You may want to look at FirstDisplayedScrollingRowIndex Property and change it regarding your mouse position during dragging.

Body:
You may do that using WinAPI by sending message to the control telling it to scroll up or down.

Here is the code, I hope it helps:

private const int WM_SCROLL = 276; // Horizontal scroll
private const int WM_VSCROLL = 277; // Vertical scroll
private const int SB_LINEUP = 0; // Scrolls one line up
private const int SB_LINELEFT = 0;// Scrolls one cell left
private const int SB_LINEDOWN = 1; // Scrolls one line down
private const int SB_LINERIGHT = 1;// Scrolls one cell right
private const int SB_PAGEUP = 2; // Scrolls one page up
private const int SB_PAGELEFT = 2;// Scrolls one page left
private const int SB_PAGEDOWN = 3; // Scrolls one page down
private const int SB_PAGERIGTH = 3; // Scrolls one page right
private const int SB_PAGETOP = 6; // Scrolls to the upper left
private const int SB_LEFT = 6; // Scrolls to the left
private const int SB_PAGEBOTTOM = 7; // Scrolls to the upper right
private const int SB_RIGHT = 7; // Scrolls to the right
private const int SB_ENDSCROLL = 8; // Ends scroll

[DllImport("user32.dll",CharSet=CharSet.Auto)]
private static extern int SendMessage(IntPtr hWnd, int wMsg,IntPtr wParam, IntPtr lParam);

Now assuming you have a textbox control on your form. You can move it with:

SendMessage(textBox1.Handle,WM_VSCROLL,(IntPtr)SB_PAGEUP,IntPtr.Zero); //ScrollUp
SendMessage(textBox1.Handle,WM_VSCROLL,(IntPtr)SB_PAGEDOWN,IntPtr.Zero); //ScrollDown

If that classic general solution doesn't work for you. You may want to look at FirstDisplayedScrollingRowIndex Property and change it regarding your mouse position during dragging.


问:
Automated testing for DialogFlow
I have developed a bot using DialogFlow/API.ai.

I am trying to include automated testing to test the conversation that I have developed before moving the code to deployment. Are there any frameworks that Dialogflow/API.ai support which can be used for automated testing?

答:
Dialogflow does not currently support any testing frameworks.

You could use Dialogflow's v1 query API or v2 detectIntent API to query your agent with responses and retrive answers in sequence to test conversational flows:

Dialogflow v1 Query API Docs

Dialogflow v2 detectIntent API Docs

Title: Automated testing for DialogFlow


问:
Create a new column by picking non-null values from 3 different columns in Tableau
I have outer-joined 3 data sources - Sales, Cost, Price details to make sure I don't miss any rows from either of data sources. A sample of my case looks as below:

As per above image, after outer joining I find Cost and Price info for Brand E but there is no sale of Brand E as a reason Brand column from Sales data appears null against Brand 'E' at both Cost and Price details.

I want to create a new column called 'Brand_New' where all Brand from A to D as in Sales should get populated also Brand 'E' from Cost details and Brand 'E' from Price details should also get populated under 'Brand_New'.

I wrote a logic in Tableau as: IF ([Brand] = 'null') THEN [Brand (cost)] ELSE [Brand (price)] END

But this did not help, could anyone please help me with a logic for this. Please let me know for any further details.

答:
So, you need a non-null value from [Brand], [Brand(cost)] and [Brand(price)].
You could use something like this for the definition of [Brand_new] calculation:</p>

```<code>IFNULL([Brand],IFNULL([Brand(cost)],[Brand(price)]))
</code>```

Body:
So, you need a non-null value from [Brand], [Brand(cost)] and [Brand(price)].
You could use something like this for the definition of [Brand_new] calculation:

IFNULL([Brand],IFNULL([Brand(cost)],[Brand(price)]))


问:
Testing throttle with jasmine clock
Is there currently a way to test lodash _.throttle using jasmine.clock? I found answers from 2015 where people are saying it's not possible, here is an example of what I found: https://github.com/jasmine/jasmine/issues/361

My code looks something like this:

```<code>let methodTested =  _.throttle(() => callMethod, {trailing: true, leading: false }); // this method is imported

beforeEach(function() {
  methodTested();
  jasmine.clock().tick(100);
});

it('callMethod to be called', function() {
  expect(callMethod).toHaveBeenCalled();
});
</code>```

I am using jasmine 2.2 and lodash 3.10

答:
This works for me

Lodash:

'use strict';

const _ = require('lodash');

describe('foo:', () => {
  let now;

  beforeEach(() => {
    jasmine.clock().install();
    jasmine.clock().mockDate();

    // const nowTime = Date.UTC(2017, 0, 1); // 1483228800 * 1000, now
    // jasmine.clock().mockDate(new Date(nowTime));
  });

  afterEach(() => {
    jasmine.clock().uninstall();
  });

  it('bar', () => {
    const callMethod = jasmine.createSpy();
    const throttled = _.throttle(() => callMethod(), 100);

    const t = setInterval(() => {
       throttled()
    }, 50);

    jasmine.clock().tick(400);

    expect(callMethod).toHaveBeenCalledTimes(4);

    clearInterval(t);
  });

});```

Title: Testing throttle with jasmine clock

Body:
Is there currently a way to test lodash _.throttle using jasmine.clock? I found answers from 2015 where people are saying it's not possible, here is an example of what I found: https://github.com/jasmine/jasmine/issues/361

My code looks something like this:

let methodTested =  _.throttle(() => callMethod, {trailing: true, leading: false }); // this method is imported

beforeEach(function() {
  methodTested();
  jasmine.clock().tick(100);
});

it('callMethod to be called', function() {
  expect(callMethod).toHaveBeenCalled();
});

I am using jasmine 2.2 and lodash 3.10


问:
Xaamrin Forms BoxView Width Too Long when using to Underline
I am using a BoxView to accomplish underlining in my app.  I have a couple of labels that are very short - Text such as Yes or No etc.  Here is the XAML for one of the labels with the BoxView for underlining:

```<code><StackLayout Orientation="Vertical" Grid.Row="5" Grid.Column="1" Margin="0,4,0,4" HorizontalOptions="Start" BackgroundColor="Purple" MinimumWidthRequest="1">
    <Label x:Name="txtUseMetric" TextColor="Blue" FontSize="Small" Text="{Binding UseMetricText}" BackgroundColor="Yellow">
    <Label.GestureRecognizers>
        <TapGestureRecognizer Tapped="Value_Tapped" CommandParameter="usemetric" />
    </Label.GestureRecognizers>
    </Label>
    <BoxView BackgroundColor="Green" HeightRequest="1" MinimumWidthRequest="1" />
</StackLayout>
</code>```

My problem is that the width of the BoxView is always extending past my text  I have tried overriding the MinWidthRequest in my App.Xaml file as seen below:

```<code><Style TargetType="BoxView">
    <Setter Property="MinimumWidthRequest" Value="3" />
</Style>
</code>```

But this has not effect.  I have included  screen shots for you to see.

FYI - The yellow is the width of the Label.  You don't see any purple (the background color of the StackLayout) because the StackLayout and Label are the same width.  The second screen shot shows what the screen looks like if I remove the BoxView - i.e. the Label and StackLayout are sized correctly.

Any suggestions on how to fix this?

Screen shot with BoxView Too Long making label and StackLayout too long

Screen shot with BoxView removed and Label and Stack Layout sizing correctly

答:
Please note the default HorizontalOptions and that Label derives from View:

Default value is LayoutOptions.Fill unless otherwise documented.

Add HorizontalOptions="Start" on the "Use Metric" Label:

```<code><Label x:Name="txtUseMetric" TextColor="Blue" FontSize="Small"
       Text="{Binding UseMetricText}" BackgroundColor="Yellow"
       HorizontalOptions="Start">
<BoxView BackgroundColor="Green" HeightRequest="1"
         WidthRequest="{Binding Path=Width, Source={x:Reference txtUseMetric}"
         HorizontalOptions="Start"/>
</code>```

Body:
I am using a BoxView to accomplish underlining in my app.  I have a couple of labels that are very short - Text such as Yes or No etc.  Here is the XAML for one of the labels with the BoxView for underlining:

<StackLayout Orientation="Vertical" Grid.Row="5" Grid.Column="1" Margin="0,4,0,4" HorizontalOptions="Start" BackgroundColor="Purple" MinimumWidthRequest="1">

        <TapGestureRecognizer Tapped="Value_Tapped" CommandParameter="usemetric" />

    <BoxView BackgroundColor="Green" HeightRequest="1" MinimumWidthRequest="1" />
</StackLayout>

My problem is that the width of the BoxView is always extending past my text  I have tried overriding the MinWidthRequest in my App.Xaml file as seen below:

But this has not effect.  I have included  screen shots for you to see.

FYI - The yellow is the width of the Label.  You don't see any purple (the background color of the StackLayout) because the StackLayout and Label are the same width.  The second screen shot shows what the screen looks like if I remove the BoxView - i.e. the Label and StackLayout are sized correctly.

Any suggestions on how to fix this?

Screen shot with BoxView Too Long making label and StackLayout too long

Screen shot with BoxView removed and Label and Stack Layout sizing correctly

Body:
Please note the default HorizontalOptions and that Label derives from View:

Default value is LayoutOptions.Fill unless otherwise documented.

Add HorizontalOptions="Start" on the "Use Metric" Label:

<Label x:Name="txtUseMetric" TextColor="Blue" FontSize="Small"
       Text="{Binding UseMetricText}" BackgroundColor="Yellow"
       HorizontalOptions="Start">
<BoxView BackgroundColor="Green" HeightRequest="1"
         WidthRequest="{Binding Path=Width, Source={x:Reference txtUseMetric}"
         HorizontalOptions="Start"/>


问:
Not able to use kotlin library
I am trying to use this library for my app but as it is made in kotlin I am facing the problem . I downloaded the module of this library and imported this module in the project but in the initial state i am gettin kotlin plugin not found so i changed the gradel as this

```<code>apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"

    defaultConfig {
        minSdkVersion 17
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'),   'proguard-rules.pro'
        }
    }
    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }
    resourcePrefix "yal_ms_"
}
buidscript {
    ext.kotlin_version = '1.0.1-2'

    repositories {
        jcenter()
        mavenCentral()
    }

    dependencies {
        classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.0.1-2'
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile "com.android.support:appcompat-v7:26.1.0"
    compile "com.android.support:recyclerview-v7:26.1.0"
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
repositories {
    mavenCentral()
    jcenter()
}
</code>```

I am trying to use the kotlin library for the first time and I dont know any thing much about kotlin any advice how to use this library will be helpful .

答:
Try Importing this library by gradle

Add  maven { url "https://jitpack.io" } to the repositories of project gradle. So it will be like this

build.gradle(Project)

```<code>buildscript {
    ext.kotlin_version = '1.1.60'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

and add compile 'com.github.yalantis:multi-selection:v0.1' to dependencies in build.gradle(app)

This may create Manifest Merge Conflicts error while building project to remove that add  tools:replace="android:label" under <application> tag in Manifest

Title: Not able to use kotlin library

Body:
I am trying to use this library for my app but as it is made in kotlin I am facing the problem . I downloaded the module of this library and imported this module in the project but in the initial state i am gettin kotlin plugin not found so i changed the gradel as this

apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.2"

    defaultConfig {
        minSdkVersion 17
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'),   'proguard-rules.pro'
        }
    }
    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }
    resourcePrefix "yal_ms_"
}
buidscript {
    ext.kotlin_version = '1.0.1-2'

    repositories {
        jcenter()
        mavenCentral()
    }

    dependencies {
        classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.0.1-2'
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile "com.android.support:appcompat-v7:26.1.0"
    compile "com.android.support:recyclerview-v7:26.1.0"
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
repositories {
    mavenCentral()
    jcenter()
}

I am trying to use the kotlin library for the first time and I dont know any thing much about kotlin any advice how to use this library will be helpful .

Body:
Try Importing this library by gradle

Add  maven { url "https://jitpack.io" } to the repositories of project gradle. So it will be like this

build.gradle(Project)

buildscript {
    ext.kotlin_version = '1.1.60'
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io" }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

and add compile 'com.github.yalantis:multi-selection:v0.1' to dependencies in build.gradle(app)

This may create Manifest Merge Conflicts error while building project to remove that add  tools:replace="android:label" under <application> tag in Manifest


问:
Spell check for python input
I have a code which takes a user's input which is supposed to be a first and last name. My code then takes that input and searches a csv for projects and hours that the input name is associated to. The problem I'm running into is if I misspell or don't capitalize the first letter of each name the code will not work. Is there a function or a way out there where if the user inputs the first 3 letters right or something similar the code will automatically assume the correct spelling and change the input accordingly? I'm a very novice coder so any help would be great.

Here's my code for reference:

```<code>import csv

# I've used full name to avoid duplicate first names in report
full_name = input('Enter your full name: ')

with open('Report1.csv') as csvfile:
    hour_summation = {}
    read_csv = csv.reader(csvfile, delimiter=',')
    for row in read_csv:
            if ' '.join((row[0], row[1])) == full_name.strip():
                hour_summation[row[2]] = hour_summation.get(row[2], 0) + int(float(row[3]))
print('This is {} full hours report:'.format(full_name))
for k, v in hour_summation.items():
    print(k + ': ' + str(v) + ' hours')
</code>```

答:
You can use str.lower on both the user input and the value from the csv to ignore case.

You can use str.startswith to match the user input against the beginning of a value from the csv. You could also use in to detemrine if the user input is in a value from the csv.

Title: Spell check for python input

Body:
I have a code which takes a user's input which is supposed to be a first and last name. My code then takes that input and searches a csv for projects and hours that the input name is associated to. The problem I'm running into is if I misspell or don't capitalize the first letter of each name the code will not work. Is there a function or a way out there where if the user inputs the first 3 letters right or something similar the code will automatically assume the correct spelling and change the input accordingly? I'm a very novice coder so any help would be great.

Here's my code for reference:

import csv

# I've used full name to avoid duplicate first names in report
full_name = input('Enter your full name: ')

with open('Report1.csv') as csvfile:
    hour_summation = {}
    read_csv = csv.reader(csvfile, delimiter=',')
    for row in read_csv:
            if ' '.join((row[0], row[1])) == full_name.strip():
                hour_summation[row[2]] = hour_summation.get(row[2], 0) + int(float(row[3]))
print('This is {} full hours report:'.format(full_name))
for k, v in hour_summation.items():
    print(k + ': ' + str(v) + ' hours')


问:
Neo4j Enterprise embedded database
I'm going to try Neo4j Enterprise embedded database. Right now I can't find any tutorials that explain how to configure and use Neo4j Enterprise embedded database togher with Maven and Spring.

In order to use embedded Neo4j Enterprise should I download Neo4j zip archive and start it or Maven dependency should be enough ? I don't understand collaboration between Java configuration and for example downloaded distributions.

Could you please tell me the proper way how to use Neo4j Enterprise embedded database together with my application ?

答:
If you really need to embed Neo4j into an application, you most likely just need the core and kernel apis which is under the org.neo4j:neo4j dependency not the enterprise dependencies (org.neo4j:neo4j-enterprise).

Your maven config would have the following dependency:

```<code><dependency>
  <groupId>org.neo4j</groupId>
  <artifactId>neo4j</artifactId>
  <version>NEO4J VERSION HERE</version>
</dependency>
</code>```

Your question makes me think that you may really want to just run Neo4j as a server and connect to it via REST or any of it's BOLT drivers.  You don't download and start the embedded version - you do that with the server.  Can you clarify exactly what you want to do?

Title: Neo4j Enterprise embedded database

Body:
If you really need to embed Neo4j into an application, you most likely just need the core and kernel apis which is under the org.neo4j:neo4j dependency not the enterprise dependencies (org.neo4j:neo4j-enterprise).

Your maven config would have the following dependency:

<dependency>
  <groupId>org.neo4j</groupId>
  <artifactId>neo4j</artifactId>
  <version>NEO4J VERSION HERE</version>
</dependency>

Your question makes me think that you may really want to just run Neo4j as a server and connect to it via REST or any of it's BOLT drivers.  You don't download and start the embedded version - you do that with the server.  Can you clarify exactly what you want to do?


问:
Tail recursion: comparing two cases
Why is this tail recursion:

```<code>  def navigate(myList : List[Int]) : (Int, List[Int]) = {
    def navigate(step: Int, offset: Int, myList: List[Int]): (Int, scala.List[Int]) = {
      if //some test and exit condition, then a definition of jump
      else navigate(step + 1, offset + jump, myList)
    }
    navigate(0, 0, myList)
  }
</code>```

while this is not:

```<code>def navigate(myList : List[Int]) : (Int, List[Int]) = {
  navigate(0, 0, myList)
}

def navigate(step: Int, offset: Int, myList: List[Int]): (Int, scala.List[Int]) = {
  if //some test and exit condition, then a definition of jump
  else navigate(step + 1, offset + jump, myList)
}
</code>```

If myList is very long, the first case does not give any problem, when the second one causes a StackOverflowError.

Also, is there any way to say the compiler that the latter should be compiled so that the recursion does not increase the stack?

答:
In order for a method to be eligible for tail-recursion optimization, it must:

be tail-recursive (duh!)

not use return

be final

Both of your examples conform to #1 and #2, but only the first example conforms to #3 (local methods are implicitly final).

The reason why a method is not tail-recursive if it is not final is that "tail-recursive" means "tail-calls itself", but if the method is virtual, then you cannot know whether it tail-calls itself or an overridden version of itself. Figuring out at compile time whether a method has been overridden requires Class Hierarchy Analysis, which is known to be equivalent to solving the Halting Problem … IOW is impossible.

Also, is there any way to say the compiler that the latter should be compiled so that the recursion does not increase the stack?

No. There is no way to turn tail-recursion optimization on or off. Methods that are tail-recursive (according to the Scala Language Specification's definition of "tail-recursive", of course) are always optimized. Any implementation of Scala that does not do this is in violation of the Scala Language Specification.

There is, however, the scala.annotation.tailrec annotation, which guarantees that the compiler will generate an error if a method that is annotated with this annotation does not comply with the SLS's definition of tail-recursion.

Title: Tail recursion: comparing two cases

Body:
Why is this tail recursion:

  def navigate(myList : List[Int]) : (Int, List[Int]) = {
    def navigate(step: Int, offset: Int, myList: List[Int]): (Int, scala.List[Int]) = {
      if //some test and exit condition, then a definition of jump
      else navigate(step + 1, offset + jump, myList)
    }
    navigate(0, 0, myList)
  }

while this is not:

def navigate(myList : List[Int]) : (Int, List[Int]) = {
  navigate(0, 0, myList)
}

def navigate(step: Int, offset: Int, myList: List[Int]): (Int, scala.List[Int]) = {
  if //some test and exit condition, then a definition of jump
  else navigate(step + 1, offset + jump, myList)
}

If myList is very long, the first case does not give any problem, when the second one causes a StackOverflowError.

Also, is there any way to say the compiler that the latter should be compiled so that the recursion does not increase the stack?


问:
Storing multiple matches during iteration in java
I'm trying to figure the following problem out in the scenario.

My method takes an ArrayList of user input, I also have a HashMap<String(keyword), ArrayList<String>(collection of responses)> in a separate class.

What I need is to match the user input against the HashMap's keywords and store the respective ArrayLists (returned from the HashMap key) for further manipulation.

The problem is that after one match I am not sure how to continue, as I'm going through user input with for-each loop. After the first match, I need to continue looking for a second, third and so on.

For each HashMap key match, I need to store the appropriate ArrayList - so I think it should look like this:

```<code>ArrayList<String> match1 = hashMap.get(wordFromInput);
ArrayList<String> match2 = hashMap.get(wordFromInput2);
</code>```

To me, this seems like it should have an easy/obvious solution, but I haven't been able to find it yet. Any suggestions?

答:
You can accomplish the task at hand by creating a stream of the HashMap's entrySet then
 filter, map and collect the result into a list.

```<code>List<ArrayList<String>> resultSet = hashMap.entrySet()
                        .stream()
                        .filter(e -> inputArrayList.contains(e.getKey()))
                        .map(Entry::getValue)
                        .collect(Collectors.toCollection(ArrayList::new));
</code>```

using the imperative approach:

```<code>List<ArrayList<String>> resultSet = new ArrayList<>();
for (Map.Entry<String, ArrayList<String>> entry : hashMap.entrySet())
{
      if(inputArrayList.contains(entry.getKey())){
           resultSet.add(entry.getValue());
      }
}
</code>```

Body:
I'm trying to figure the following problem out in the scenario.

My method takes an ArrayList of user input, I also have a HashMap<String(keyword), ArrayList<String>(collection of responses)> in a separate class.

What I need is to match the user input against the HashMap's keywords and store the respective ArrayLists (returned from the HashMap key) for further manipulation.

The problem is that after one match I am not sure how to continue, as I'm going through user input with for-each loop. After the first match, I need to continue looking for a second, third and so on.

For each HashMap key match, I need to store the appropriate ArrayList - so I think it should look like this:

ArrayList<String> match1 = hashMap.get(wordFromInput);
ArrayList<String> match2 = hashMap.get(wordFromInput2);

To me, this seems like it should have an easy/obvious solution, but I haven't been able to find it yet. Any suggestions?

Body:
You can accomplish the task at hand by creating a stream of the HashMap's entrySet then
 filter, map and collect the result into a list.

List<ArrayList<String>> resultSet = hashMap.entrySet()
                        .stream()
                        .filter(e -> inputArrayList.contains(e.getKey()))
                        .map(Entry::getValue)
                        .collect(Collectors.toCollection(ArrayList::new));

using the imperative approach:

List<ArrayList<String>> resultSet = new ArrayList<>();
for (Map.Entry<String, ArrayList<String>> entry : hashMap.entrySet())
{
      if(inputArrayList.contains(entry.getKey())){
           resultSet.add(entry.getValue());
      }
}


问:
How can I compare two files in a batch file?
How can I compare two files in a batch file, and perform an action based on whether or not they match? I've tried something like:

```<code>if file1.txt NEQ file2.txt goto label
</code>```

but it compares the actual string "file1.txt" rather than the file. I've read about the COMP command, but it doesn't seem to work if I put it in an if statement. Does anybody know how to do this? Sorry, but I rarely use batch files and have little experience in them.

Thanks in advance.

答:
I use the below example to build reports based on file differences:</p>

```<code>set %Batch_Work_Space_Dir%=folder for your batch file and temp resource files
set file_1=name of file
set file_2=name of file

fc %file_1% %file_1%t > %Batch_Work_Space_Dir%\Are_They_Different.txt

powershell -command "(Get-Content %Batch_Work_Space_Dir%\Are_They_Different.txt) | select -skip 1 | Set-Content %Batch_Work_Space_Dir%\Are_They_Different.txt"
set /p Diff_Found=<%Batch_Work_Space_Dir%\Are_They_Different.txt
if %Diff_Found:~0,17%" == "FC: no difference" (
  execute commands
 )
</code>```

Body:
How can I compare two files in a batch file, and perform an action based on whether or not they match? I've tried something like:

if file1.txt NEQ file2.txt goto label

but it compares the actual string "file1.txt" rather than the file. I've read about the COMP command, but it doesn't seem to work if I put it in an if statement. Does anybody know how to do this? Sorry, but I rarely use batch files and have little experience in them.

Thanks in advance.

Body:
I use the below example to build reports based on file differences:

set %Batch_Work_Space_Dir%=folder for your batch file and temp resource files
set file_1=name of file
set file_2=name of file

fc %file_1% %file_1%t > %Batch_Work_Space_Dir%\Are_They_Different.txt

powershell -command "(Get-Content %Batch_Work_Space_Dir%\Are_They_Different.txt) | select -skip 1 | Set-Content %Batch_Work_Space_Dir%\Are_They_Different.txt"
set /p Diff_Found=<%Batch_Work_Space_Dir%\Are_They_Different.txt
if %Diff_Found:~0,17%" == "FC: no difference" (
  execute commands
 )


问:
Content not refreshing in Google assistant, but works fine in Dialog Flow
I have been searching so long for this, and couldn't find a solution.

So, I have developed a pretty basic dialog flow project and deployed it onto firebase using inline editor.
Now the 1st deployment works perfectly fine with the simulator.
However, I changed some content to include suggestion chips and modify the responses as well; this gets reflected fine in dialog flow. And I can see the changes I have made.

But when I update the Draft and try to test it again in simulator/google assistant device, it doesn't load the newer changes. I am not sure if what I am doing is correct or not.
Please help :(

Just now found this - https://discuss.api.ai/t/actions-on-google-integration-agent-updates-do-not-always-publish-correctly/7483

It seems many users are facing this issue.. :/

答: Dialogflow had a bug causing this issue which should now be fixed.</p>


问:
How can I scroll my panel using my mousewheel?
I have a panel on my form with AutoScroll set to true so a scrollbar appears automatically.

How can I make it so a user can use his mouse wheel to scroll the panel? Thanks SO.

答:
Below code works for me.....</p>

```<code>    Public Form
{
InitializeComponent();
this.MouseWheel += new MouseEventHandler(Panel1_MouseWheel);
}

 private void Panel1_MouseWheel(object sender, MouseEventArgs e)
        {
         panel1.Focus();
         }
</code>```

Body:
Below code works for me.....

    Public Form
{
InitializeComponent();
this.MouseWheel += new MouseEventHandler(Panel1_MouseWheel);
}

 private void Panel1_MouseWheel(object sender, MouseEventArgs e)
        {
         panel1.Focus();
         }


问:
'WSGIRequest' object has no attribute method
I know this question has been asked many times, but I haven't found any solution that solved my problem. Basically, I have a method inside a class view in Django, and that method calls another method, which raises an AttributeError: 'WSGIRequest' object has no attribute 'send_email'.

This is the code:

```<code>class PartyListView(ListView):
    # ...
    # ...

    def approve_party(self, party_id):
        returnObj = {}

        # get the party by id
        party = party_repo.get_party_by_id(party_id)
        if party is None:
            returnObj['message'] = "The requested party doesn't exist."
            jsonObj = json.dumps(returnObj)
            return HttpResponse(jsonObj, status=404, content_type="application/json")

        # change the status to Approved
        party.party_status = Core.PartyStatus.Approved
        party.save()

        # email the party team on the approval
        self.send_email(True, party)

        # return a json success response
        returnObj['message'] = "The party has been approved."
        jsonObj = json.dumps(returnObj)
        return HttpResponse(jsonObj, status=200, content_type="application/json")

    def send_email(self, isApprovalEmail, party):
        username = self.request.user.username
        from_email = username + "@example.com"
        recipient_list = [party.host.student_email]
        cc = ['admin@example.com']

        if isApprovalEmail:
            subject = "APPROVED Party Registration for {}".format(party.party_time)
            body = "approval email"

            email = EmailMessage(subject, body, from_email, recipient_list, cc=cc)
            email.send()
        else:
            subject = "REJECTED Party Registration for {}".format(party.party_time)
            body = "rejection email"

            email = EmailMessage(subject, body, from_email, recipient_list, cc=cc)
            email.send()

    # ...
    # ...
</code>```

I have tried the following things:

Rearrange the order of the method send_email: Above approve_party, below, at the top, at the bottom.

Rewrite the whole file in another editor without copying anything.

Use PyCharm's convert indents to spaces option to make sure indentation is good.

Write other dummy functions in the class and try to call them from approve_party - none of them works.

Here's the full traceback:

```<code>Internal Server Error: /admin/parties/approve/151
Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = get_response(request)
  File "C:\Program Files\Python36\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Program Files\Python36\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:/Programming/Party-Reg\admin_dashboard\views.py", line 93, in approve_party
    self.send_email(True, party)
AttributeError: 'WSGIRequest' object has no attribute 'send_email'
[05/Dec/2017 18:07:19] "GET /admin/parties/approve/151 HTTP/1.1" 500 17786
</code>```

And approve_party is registered in urls.py as follows:

```<code>urlpatterns = [
    # ...,
    url(r'^parties/approve/([0-9]*$)', views.PartyListView.approve_party, name="Approve Party"),
    # ...
]
</code>```

答:
You are using class based views incorrectly. Class based views should be registered with the as_view method.

```<code>url(r'^parties/approve/([0-9]*$)', views.PartyListView.as_view(), name="Approve Party"),
</code>```

However, in this case, it looks as it would be simpler to make approve_party and send_email regular functions instead of methods of your view.

```<code>def approve_party(request, party_id):
    returnObj = {}
    ...
    send_email(request, True, party)

    return HttpResponse(jsonObj, status=200, content_type="application/json")

def send_email(request, isApprovalEmail, party):
    username = request.user.username
</code>```

Then change your URL pattern to:

```<code>url(r'^parties/approve/([0-9]+$)', views.approve_party, name="approve-party"),
</code>```

I suggest using [0-9]+ instead of [0-9]* to make sure that the URL includes at least one digit, and I would avoid using spaces in URL pattern names.

Body:
I know this question has been asked many times, but I haven't found any solution that solved my problem. Basically, I have a method inside a class view in Django, and that method calls another method, which raises an AttributeError: 'WSGIRequest' object has no attribute 'send_email'.

This is the code:

class PartyListView(ListView):
    # ...
    # ...

    def approve_party(self, party_id):
        returnObj = {}

        # get the party by id
        party = party_repo.get_party_by_id(party_id)
        if party is None:
            returnObj['message'] = "The requested party doesn't exist."
            jsonObj = json.dumps(returnObj)
            return HttpResponse(jsonObj, status=404, content_type="application/json")

        # change the status to Approved
        party.party_status = Core.PartyStatus.Approved
        party.save()

        # email the party team on the approval
        self.send_email(True, party)

        # return a json success response
        returnObj['message'] = "The party has been approved."
        jsonObj = json.dumps(returnObj)
        return HttpResponse(jsonObj, status=200, content_type="application/json")

    def send_email(self, isApprovalEmail, party):
        username = self.request.user.username
        from_email = username + "@example.com"
        recipient_list = [party.host.student_email]
        cc = ['admin@example.com']

        if isApprovalEmail:
            subject = "APPROVED Party Registration for {}".format(party.party_time)
            body = "approval email"

            email = EmailMessage(subject, body, from_email, recipient_list, cc=cc)
            email.send()
        else:
            subject = "REJECTED Party Registration for {}".format(party.party_time)
            body = "rejection email"

            email = EmailMessage(subject, body, from_email, recipient_list, cc=cc)
            email.send()

    # ...
    # ...

I have tried the following things:

Rearrange the order of the method send_email: Above approve_party, below, at the top, at the bottom.

Rewrite the whole file in another editor without copying anything.

Use PyCharm's convert indents to spaces option to make sure indentation is good.

Write other dummy functions in the class and try to call them from approve_party - none of them works.

Here's the full traceback:

Internal Server Error: /admin/parties/approve/151
Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = get_response(request)
  File "C:\Program Files\Python36\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Program Files\Python36\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:/Programming/Party-Reg\admin_dashboard\views.py", line 93, in approve_party
    self.send_email(True, party)
AttributeError: 'WSGIRequest' object has no attribute 'send_email'
[05/Dec/2017 18:07:19] "GET /admin/parties/approve/151 HTTP/1.1" 500 17786

And approve_party is registered in urls.py as follows:

urlpatterns = [
    # ...,
    url(r'^parties/approve/([0-9]*$)', views.PartyListView.approve_party, name="Approve Party"),
    # ...
]

Body:
You are using class based views incorrectly. Class based views should be registered with the as_view method.

url(r'^parties/approve/([0-9]*$)', views.PartyListView.as_view(), name="Approve Party"),

However, in this case, it looks as it would be simpler to make approve_party and send_email regular functions instead of methods of your view.

def approve_party(request, party_id):
    returnObj = {}
    ...
    send_email(request, True, party)

    return HttpResponse(jsonObj, status=200, content_type="application/json")

def send_email(request, isApprovalEmail, party):
    username = request.user.username

Then change your URL pattern to:

url(r'^parties/approve/([0-9]+$)', views.approve_party, name="approve-party"),

I suggest using [0-9]+ instead of [0-9]* to make sure that the URL includes at least one digit, and I would avoid using spaces in URL pattern names.


问:
Inheritance security rules violated by type: 'MySql.Data.Entity.MySqlEFConfiguration'
I've created an asp.net web application which should connect to a mysql database.

I´m using entity framework 6 with an ado.net entity data model. I´ve also followed the following tutorial: https://dev.mysql.com/doc/connectors/en/connector-net-entityframework60.html#connector-net-ef6-config

However calling: DbConfiguration.SetConfiguration(new MySqlEFConfiguration());

causes my application to crash. It probably has nothing to do with this specific method, because creating a DBContext also crashes the app.

Any ideas what's causing this error?

.NET Framework: 4.6.1

MySql.Data.Entity.EF6: 6.10.4

Web.config:

```<code><configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
      <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>
    <providers>
      <provider invariantName="MySql.Data.MySqlClient"
                type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6"/>
      <provider invariantName="System.Data.SqlClient"
                type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
    </providers>
  </entityFramework>

<connectionStrings><add name="DatabaseEntities" connectionString="metadata=res://*/Database.Model.csdl|res://*/Database.Model.ssdl|res://*/Database.Model.msl;provider=MySql.Data.MySqlClient;provider connection string=""" providerName="System.Data.EntityClient" /></connectionStrings><system.data>
    <DbProviderFactories>
      <remove invariant="MySql.Data.MySqlClient" />
      <add description=".Net Framework Data Provider for MySQL" invariant="MySql.Data.MySqlClient" name="MySQL Data Provider" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.10.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
    </DbProviderFactories>
  </system.data>
</code>```

Complete error:

Inheritance security rules violated by type:
  'MySql.Data.Entity.MySqlEFConfiguration'. Derived types must either
  match the security accessibility of the base type or be less
  accessible.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace
  for more information about the error and where it originated in the
  code.

Exception Details: System.TypeLoadException: Inheritance security rules violated by type:
  'MySql.Data.Entity.MySqlEFConfiguration'. Derived types must either
  match the security accessibility of the base type or be less
  accessible.

答: Downgrade MySql.Data.Entity from version 6.10.x to 6.9.10 can solve the problem. It solved mine</p>

Body:
I've created an asp.net web application which should connect to a mysql database.

I´m using entity framework 6 with an ado.net entity data model. I´ve also followed the following tutorial: https://dev.mysql.com/doc/connectors/en/connector-net-entityframework60.html#connector-net-ef6-config

However calling: DbConfiguration.SetConfiguration(new MySqlEFConfiguration());

causes my application to crash. It probably has nothing to do with this specific method, because creating a DBContext also crashes the app.

Any ideas what's causing this error?

.NET Framework: 4.6.1

MySql.Data.Entity.EF6: 6.10.4

Web.config:

<configSections>

  </configSections>
      <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>
    <providers>
      <provider invariantName="MySql.Data.MySqlClient"
                type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6"/>
      <provider invariantName="System.Data.SqlClient"
                type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
    </providers>
  </entityFramework>

<connectionStrings><add name="DatabaseEntities" connectionString="metadata=res://*/Database.Model.csdl|res://*/Database.Model.ssdl|res://*/Database.Model.msl;provider=MySql.Data.MySqlClient;provider connection string=""" providerName="System.Data.EntityClient" /></connectionStrings><system.data>
    <DbProviderFactories>
      <remove invariant="MySql.Data.MySqlClient" />
      <add description=".Net Framework Data Provider for MySQL" invariant="MySql.Data.MySqlClient" name="MySQL Data Provider" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.10.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
    </DbProviderFactories>
  </system.data>

Complete error:

Inheritance security rules violated by type:
  'MySql.Data.Entity.MySqlEFConfiguration'. Derived types must either
  match the security accessibility of the base type or be less
  accessible.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace
  for more information about the error and where it originated in the
  code.

Exception Details: System.TypeLoadException: Inheritance security rules violated by type:
  'MySql.Data.Entity.MySqlEFConfiguration'. Derived types must either
  match the security accessibility of the base type or be less
  accessible.


问:
Making a html kanban scrollable
I am trying to create a kanban board, the code there seems great, but when a column(e.g ToDO) has a large number of items I use the browser scroll bar to scroll down, I would like to have a scroll bar visible for each swim lane, and be able to scroll a single swim lane so that I don't have to do the entire page.

I have tried adding overflow-y:scroll to the .section

```<code>    .section > h1 {
        margin: 0;
        border-bottom: 1px solid #999;
        padding: 0;
        font-size: 12pt;
        text-align: center;
        overflow-y:scroll;

    }
</code>```

But this shows a scroll bar but I cannot scroll a single swim lane on its own.
I'm completely new to HTML/CSS.

答:
add the overflow-y:scroll; to the section class (.section), not only to the h1s in the class.

```<code>  .section {
        display: table-cell;
        margin: 0;
        border: 1px solid #666;
        padding: 5px;
        width: 300px;
        overflow-y:scroll;
    }
</code>```

what you did only makes the headlines scrollable if to big, not the entire thing. Maybe you should look at an explenation to the ">" in css

Title: Making a html kanban scrollable

Body:
I am trying to create a kanban board, the code there seems great, but when a column(e.g ToDO) has a large number of items I use the browser scroll bar to scroll down, I would like to have a scroll bar visible for each swim lane, and be able to scroll a single swim lane so that I don't have to do the entire page.

I have tried adding overflow-y:scroll to the .section

    .section > h1 {
        margin: 0;
        border-bottom: 1px solid #999;
        padding: 0;
        font-size: 12pt;
        text-align: center;
        overflow-y:scroll;

    }

But this shows a scroll bar but I cannot scroll a single swim lane on its own.
I'm completely new to HTML/CSS.

Body:
add the overflow-y:scroll; to the section class (.section), not only to the h1s in the class.

  .section {
        display: table-cell;
        margin: 0;
        border: 1px solid #666;
        padding: 5px;
        width: 300px;
        overflow-y:scroll;
    }

what you did only makes the headlines scrollable if to big, not the entire thing. Maybe you should look at an explenation to the ">" in css


问:
C++ Classes, Default Constructors
To keep it simple and to the point, I have a class

```<code>class square
{
public:
    square(int s); // parameterized constructor with default parameter = 0
    square();

private:
    int side; // holds the side of the square (whole number)
};

square::square() {

    side = 0;
}

square::square(int s){

    side = 0; // parameterized constructor with default parameter = 0
}
</code>```

and in the main I have the following:

```<code>int main()
{
    square sq1;// declare 4 objects of type square named sq1, sq2, sq3, and sq4 initializing the third one to 10
    square sq2;
    square sq3(10);
    square sq4;
}
</code>```

The problem is that if I comment out square(); in the class, the square sq1, sq2 and sq4 won't work.
I need to initialize square(int s) as a default constructor set to 0 and only use that for all four square sq's. How would I go about fixing that?

答:
In any case you have to define a default constructor. From the C++ (2017) Standard (15.1 Constructors)

4 A default constructor for a class X is a constructor of class X
  for which each parameter that is not a function parameter pack has a
  default argument (including the case of a constructor with no
  parameters). If there is no user-declared constructor for class X, a
  non-explicit constructor having no parameters is implicitly declared
  as defaulted (11.4). An implicitly-declared default constructor is an
  inline public member of its class.

So to make the constructor with parameter a default constructor just supply a default argument in the declaration of the constructor. For example

```<code>class square
{
public:
    square(int s = 0 ); // parameterized constructor with default parameter = 0

private:
    int side; // holds the side of the square (whole number)
};
</code>```

The constructor itself can be defined like

```<code>square::square( int s ) : side( s )
{
}
</code>```

Also you can declare the constructor with the function specifier explicit to prevent implicit conversion from the type int to the type square.

```<code>class square
{
public:
    explicit square(int s = 0 ); // parameterized constructor with default parameter = 0

private:
    int side; // holds the side of the square (whole number)
};
</code>```

Title: C++ Classes, Default Constructors

Body:
To keep it simple and to the point, I have a class

class square
{
public:
    square(int s); // parameterized constructor with default parameter = 0
    square();

private:
    int side; // holds the side of the square (whole number)
};

square::square() {

    side = 0;
}

square::square(int s){

    side = 0; // parameterized constructor with default parameter = 0
}

and in the main I have the following:

int main()
{
    square sq1;// declare 4 objects of type square named sq1, sq2, sq3, and sq4 initializing the third one to 10
    square sq2;
    square sq3(10);
    square sq4;
}

The problem is that if I comment out square(); in the class, the square sq1, sq2 and sq4 won't work.
I need to initialize square(int s) as a default constructor set to 0 and only use that for all four square sq's. How would I go about fixing that?

Body:
In any case you have to define a default constructor. From the C++ (2017) Standard (15.1 Constructors)

4 A default constructor for a class X is a constructor of class X
  for which each parameter that is not a function parameter pack has a
  default argument (including the case of a constructor with no
  parameters). If there is no user-declared constructor for class X, a
  non-explicit constructor having no parameters is implicitly declared
  as defaulted (11.4). An implicitly-declared default constructor is an
  inline public member of its class.

So to make the constructor with parameter a default constructor just supply a default argument in the declaration of the constructor. For example

class square
{
public:
    square(int s = 0 ); // parameterized constructor with default parameter = 0

private:
    int side; // holds the side of the square (whole number)
};

The constructor itself can be defined like

square::square( int s ) : side( s )
{
}

Also you can declare the constructor with the function specifier explicit to prevent implicit conversion from the type int to the type square.

class square
{
public:
    explicit square(int s = 0 ); // parameterized constructor with default parameter = 0

private:
    int side; // holds the side of the square (whole number)
};


问:
Bootstrap body auto padding remove after open modal
After open bootstrap modal a auto padding-right : 19px adding in body tag. I want to remove this auto padding. I have tried bellow code for modal and remove body auto padding.

```<code><div class="media" data-toggle="modal" data-target="#kolpochitro">
             --------
</div>
</code>```

Then I have written

```<code><div class="modal fade" id="kolpochitro" role="dialog">
    <div class="modal-dialog modal-sm" >

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
              -------
        </div>
        <div class="modal-body">
              ------
        </div>
      </div>

    </div>
  </div>
</code>```

After open modal my body tag looking at firebug

```<code><body class="cbp-spmenu-push modal-open" style="padding-right: 19px;">
</code>```

for remove this style I am trying bellow code

```<code>$('document').ready(function(){
            $('.media').click(function(){
                $("body").removeAttr("style");
            })
})
</code>```

But it's not working.

答:
I had the same problem. Removing the inline style with Javascript as in the accepted answer will remove the padding but not until the modal is completely shown so it still results in kind of an erratic behavior. In the end I removed the padding with CSS, which will make sure there page content doesn't move and there is no padding at all times.

```<code>body.modal-open {
  padding-right: 0 !important;
}
</code>```

Hope this will help anyone with the same question.

Body:
After open bootstrap modal a auto padding-right : 19px adding in body tag. I want to remove this auto padding. I have tried bellow code for modal and remove body auto padding.

             --------

Then I have written

              -------

              ------

After open modal my body tag looking at firebug

for remove this style I am trying bellow code

$('document').ready(function(){
            $('.media').click(function(){
                $("body").removeAttr("style");
            })
})

But it's not working.

Body:
I had the same problem. Removing the inline style with Javascript as in the accepted answer will remove the padding but not until the modal is completely shown so it still results in kind of an erratic behavior. In the end I removed the padding with CSS, which will make sure there page content doesn't move and there is no padding at all times.

body.modal-open {
  padding-right: 0 !important;
}

Hope this will help anyone with the same question.


问:
Proto Compilation Error - No such file or directory
I am trying to compile Protoc library but It just keeps giving me the error of No Such Directory even though it is there

I am following Google's Photobuf compilation steps
I have added Protoc to PATH environment variable as well.

But it simply won't see the object_detection/protos directory

```<code>protoc object_detection/protos/*.proto --python_out=.
</code>```

The directory and the files are clearly there

答: I was running into the same problem using the latest protoc version for windows: 3.5.0.   On a whim I tried using the slightly older version (3.4.0) and got it to work using the exact same instructions.</p>

Body:
I am trying to compile Protoc library but It just keeps giving me the error of No Such Directory even though it is there

I am following Google's Photobuf compilation steps
I have added Protoc to PATH environment variable as well.

But it simply won't see the object_detection/protos directory

protoc object_detection/protos/*.proto --python_out=.

The directory and the files are clearly there


问:
File serving using ngRoute in Angular with NodeJS server
I am trying to run AngularJS, using Angular Router, with a NodeJS server. I do not plan on serving the various views in Node, but instead I want to use the angular router. This first page is served correctly with no errors but when I try to click on another link, the browser displays the following
error code. Below is the relevant code from the server script, the routing script, and where the link in the HTML is.

HTML Link

```<code><li><a href="./add">Add Workout</a></li>
</code>```

Server.js

```<code>app.get('/', function(req, res) {
   res.sendFile(path.join(__dirname + '/public/app/views/home.html'));
});

app.use(express.static('public'));
</code>```

App.js

```<code>var app = angular.module("fitness2Uapp", ["ngRoute"]);
app.config(function($routeProvider) {
    $routeProvider
      .when("/", {
          templateUrl : "./app/views/home.html"
      })
      .when("/browse", {
          templateUrl : "./app/views/browse.html"
      })
      .when("/add", {
          templateUrl : "./add.html"
      })
      .when("/workout", {
          templateUrl : "./app/views/workout.html"
      });
  });
</code>```

答:
Try putting in a "catch all" route that just redirects back to the main page.  This will in turn allow the angular routing mechanism to kick in.  Right now the problem is that it's trying to find an endpoint path of '/add' on the node server, but nothing is found.  This should be the very last route established on your server.

I personally use AngularJS and had to do this, and everything works great.  Not sure if this will also perform the same way as Angular2+

```<code>// Catch all if all other routes fail to match.
app.get('*', (req, res) => {
  res.sendFile(path.resolve(`${__dirname}/path/to/home.html`));
});
</code>```

Body:
I am trying to run AngularJS, using Angular Router, with a NodeJS server. I do not plan on serving the various views in Node, but instead I want to use the angular router. This first page is served correctly with no errors but when I try to click on another link, the browser displays the following
error code. Below is the relevant code from the server script, the routing script, and where the link in the HTML is.

HTML Link

Add Workout

Server.js

app.get('/', function(req, res) {
   res.sendFile(path.join(__dirname + '/public/app/views/home.html'));
});

app.use(express.static('public'));

App.js

var app = angular.module("fitness2Uapp", ["ngRoute"]);
app.config(function($routeProvider) {
    $routeProvider
      .when("/", {
          templateUrl : "./app/views/home.html"
      })
      .when("/browse", {
          templateUrl : "./app/views/browse.html"
      })
      .when("/add", {
          templateUrl : "./add.html"
      })
      .when("/workout", {
          templateUrl : "./app/views/workout.html"
      });
  });

Body:
Try putting in a "catch all" route that just redirects back to the main page.  This will in turn allow the angular routing mechanism to kick in.  Right now the problem is that it's trying to find an endpoint path of '/add' on the node server, but nothing is found.  This should be the very last route established on your server.

I personally use AngularJS and had to do this, and everything works great.  Not sure if this will also perform the same way as Angular2+

// Catch all if all other routes fail to match.
app.get('*', (req, res) => {
  res.sendFile(path.resolve(`${__dirname}/path/to/home.html`));
});


问:
What's the easiest way to create an Excel table with C#?
I have some tabular data that I'd like to turn into an Excel table.

Software available:

.NET 4 (C#)

Excel 2010 (using the Excel API is OK)

I prefer not to use any 3rd party libraries

Information about the data:

A couple million rows

5 columns, all strings (very simple and regular table structure)

In my script I'm currently using a nested List data structure but I can change that

Performance of the script is not critical

Searching online gives many results, and I'm confused whether I should use OleDb, ADO RecordSets, or something else. Some of these technologies seem like overkill for my scenario, and some seem like they might be obsolete.

What is the very simplest way to do this?

Edit: this is a one-time script I intend to run from my attended desktop.

答:
i implemented "export to Excel" with the ms-access-ole-db-driver that can also read and write excel files the follwoing way:

preparation (done once)

create an excel file that contains all (header, Formatting, formulas, diagrams) with an empty data area as a template to be filled

give the data area (including the headers) a name (ie "MyData")

Implementing export

copy template file to destination folder

open an oledb-database connection to the destination file

use sql to insert data

Example

```<code>Excel table with Named area "MyData"
Name, FamilyName, Birthday

open System.Data.OleDb.OleDbConnection
execute sql "Insert into MyData(Name, FamilyName, Birthday) values(...)"
</code>```

I used this connection string

```<code>private const string FORMAT_EXCEL_CONNECT =
        // @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 8.0;HDR={1}""";
        @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0;HDR={1}""";

    private static string GetExcelConnectionString(string excelFilePath, bool header)
    {
        return string.Format(FORMAT_EXCEL_CONNECT,
            excelFilePath,
            (header) ? "Yes" : "No"
            );
    }
</code>```

Body:
i implemented "export to Excel" with the ms-access-ole-db-driver that can also read and write excel files the follwoing way:

preparation (done once)

create an excel file that contains all (header, Formatting, formulas, diagrams) with an empty data area as a template to be filled

give the data area (including the headers) a name (ie "MyData")

Implementing export

copy template file to destination folder

open an oledb-database connection to the destination file

use sql to insert data

Example

Excel table with Named area "MyData"
Name, FamilyName, Birthday

open System.Data.OleDb.OleDbConnection
execute sql "Insert into MyData(Name, FamilyName, Birthday) values(...)"

I used this connection string

private const string FORMAT_EXCEL_CONNECT =
        // @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 8.0;HDR={1}""";
        @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0;HDR={1}""";

    private static string GetExcelConnectionString(string excelFilePath, bool header)
    {
        return string.Format(FORMAT_EXCEL_CONNECT,
            excelFilePath,
            (header) ? "Yes" : "No"
            );
    }


问:
glm in python vs R
I have some dataset: titanic

Doing this in R

glm(Survived ~ Sex, titanic, family = "binomial")

I get

```<code>(Intercept)     SexMale
1.124321   -2.477825
</code>```

R takes survived as positive outcome.

But when I'm doing the same in Python

sm.formula.glm("Survived ~ Sex", family=sm.families.Binomial(), data=titanic).fit()

I get negative results: i.e. Python takes not survived as positive outcome.

How can I adjust Python's glm function behavior so it will return the same result as R does?

答:
You just need to set your reference group to either male or female (depending on what you're interested in):

With a small test dataset in R, the code and model summary looks like this:

```<code>df <- data.frame(c(0,0,1,1,0), c("Male", "Female", "Female", "Male", "Male"))
colnames(df) <- c("Survived", "Sex")

model <- glm(Survived ~ Sex, data=df, family="binomial")
summary(model)
</code>```

Output:

```<code>Coefficients:
              Estimate Std. Error z value Pr(>|z|)
(Intercept) -3.084e-16  1.414e+00   0.000    1.000
SexMale     -6.931e-01  1.871e+00  -0.371    0.711
</code>```

To get something similar in Python/statsmodels:

```<code>import pandas as pd
import statsmodels.api as sm

df = pd.DataFrame({"Survived": [0,0,1,1,0],
                   "Sex": ["Male", "Female", "Female", "Male", "Male"]})

model = sm.formula.glm("Survived ~ C(Sex, Treatment(reference='Female'))",
                       family=sm.families.Binomial(), data=df).fit()
print(model.summary())
</code>```

Which will give:

```<code>                                                    coef    std err          z      P>|z|      [0.025      0.975]
-----------------------------------------------------------------------------------------------------------------
Intercept                                      5.551e-16      1.414   3.93e-16      1.000      -2.772       2.772
C(Sex, Treatment(reference='Female'))[T.Male]    -0.6931      1.871     -0.371      0.711      -4.360       2.974
</code>```

Notice the use of Treatment() to set the reference group. I've set it to Female in this case to match the R output, but with your dataset it might make more sense to use Male. Either way, its just an issue of being explicit about which group is used as reference.

Title: glm in python vs R

Body:
I have some dataset: titanic

Doing this in R

glm(Survived ~ Sex, titanic, family = "binomial")

I get

(Intercept)     SexMale
1.124321   -2.477825

R takes survived as positive outcome.

But when I'm doing the same in Python

sm.formula.glm("Survived ~ Sex", family=sm.families.Binomial(), data=titanic).fit()

I get negative results: i.e. Python takes not survived as positive outcome.

How can I adjust Python's glm function behavior so it will return the same result as R does?

Body:
You just need to set your reference group to either male or female (depending on what you're interested in):

With a small test dataset in R, the code and model summary looks like this:

df <- data.frame(c(0,0,1,1,0), c("Male", "Female", "Female", "Male", "Male"))
colnames(df) <- c("Survived", "Sex")

model <- glm(Survived ~ Sex, data=df, family="binomial")
summary(model)

Output:

Coefficients:
              Estimate Std. Error z value Pr(>|z|)
(Intercept) -3.084e-16  1.414e+00   0.000    1.000
SexMale     -6.931e-01  1.871e+00  -0.371    0.711

To get something similar in Python/statsmodels:

import pandas as pd
import statsmodels.api as sm

df = pd.DataFrame({"Survived": [0,0,1,1,0],
                   "Sex": ["Male", "Female", "Female", "Male", "Male"]})

model = sm.formula.glm("Survived ~ C(Sex, Treatment(reference='Female'))",
                       family=sm.families.Binomial(), data=df).fit()
print(model.summary())

Which will give:

                                                    coef    std err          z      P>|z|      [0.025      0.975]
-----------------------------------------------------------------------------------------------------------------
Intercept                                      5.551e-16      1.414   3.93e-16      1.000      -2.772       2.772
C(Sex, Treatment(reference='Female'))[T.Male]    -0.6931      1.871     -0.371      0.711      -4.360       2.974

Notice the use of Treatment() to set the reference group. I've set it to Female in this case to match the R output, but with your dataset it might make more sense to use Male. Either way, its just an issue of being explicit about which group is used as reference.