问:
SQL - AVG and Group by
I have the following table:

```<code>Date      |   Product   |   Price
06-12-17  |    1.1      |   10
06-12-17  |    1.2      |   20
06-12-17  |    1.3      |   30
06-12-17  |    1.4      |   40
05-12-17  |    1.1      |   20
05-12-17  |    1.2      |   20
05-12-17  |    1.3      |   40
05-12-17  |    1.4      |   40
</code>```

I am having hard time finding a query in SQL Server that can give me this result:

```<code>Date      |   Product |   Price
06-12-17  |    1      |   25
05-12-17  |    1      |   30
</code>```

I want the average price for each product everyday

Product starting from 1.1 to 24.4

答:
If you just need left part of product, cast to int and then aggregate using resultant value and date.

```<code>select date,
       cast(product as int) as product,
       avg(price) as Price
from table1
group by date, cast(product as int)
</code>```

Result:

```<code>date        product Price
--------------------------
05-12-17    1       30
06-12-17    1       25
</code>```

DEMO

Update:

If product is of varchar datatype, use cast twice.

```<code>select date,
       cast(cast(product as dec(3,1)) as int) as product,
       avg(price) as Price
from table1
group by date, cast(cast(product as dec(3,1)) as int)
</code>```

Varchar() Datatype DEMO

Title: SQL - AVG and Group by

Body:
I have the following table:

Date      |   Product   |   Price
06-12-17  |    1.1      |   10
06-12-17  |    1.2      |   20
06-12-17  |    1.3      |   30
06-12-17  |    1.4      |   40
05-12-17  |    1.1      |   20
05-12-17  |    1.2      |   20
05-12-17  |    1.3      |   40
05-12-17  |    1.4      |   40

I am having hard time finding a query in SQL Server that can give me this result:

Date      |   Product |   Price
06-12-17  |    1      |   25
05-12-17  |    1      |   30

I want the average price for each product everyday

Product starting from 1.1 to 24.4

Body:
If you just need left part of product, cast to int and then aggregate using resultant value and date.

select date,
       cast(product as int) as product,
       avg(price) as Price
from table1
group by date, cast(product as int)

Result:

date        product Price
--------------------------
05-12-17    1       30
06-12-17    1       25

DEMO

Update:

If product is of varchar datatype, use cast twice.

select date,
       cast(cast(product as dec(3,1)) as int) as product,
       avg(price) as Price
from table1
group by date, cast(cast(product as dec(3,1)) as int)

Varchar() Datatype DEMO


来源: stackexchange

问:
jquery : show/hide div, timing
I have a pretty standard problem here.

I have an error div that,

when a button is pressed is populated with an error message,
the div is then faded in, after (500*n)ms (where n = number of letters) the div is faded out.

my issue occurs when the user presses the button again before the div has faded out.

while the div is still visible the divs contents are updated with the new error message,

after the initial (500*n)ms the div is faded out, then immediately gets faded back in and is visible for another (500*n)ms.

What I want is.

user clicks button

div contents are updated

div is faded in

user clicks button again

div immediately fades out

content is updated

div is faded in.

How can I achieve this?

My current code is below

```<code>function login_error(message){
        $('form').effect('shake', { times: 1 }, 50);
        $('#error').html(message).fadeIn('fast').delay(500*message.length).fadeOut('fast');
}
</code>```

答:
simething like this?

```<code> $(function() {
    var counter = 0;
    var timeOut;
    $('button').click(function() {
        showdiv('clicked ' + counter++);
    });

    function showdiv(str) {
        clearTimeout(timeOut);
        $('div').fadeOut(function() {
            $(this).html(str).fadeIn(function() {
                timeOut = setTimeout(function() {
                    $('div').fadeOut();
                }, 100 * str.length);
            });
        })
    }
});
</code>```

demo:
http://www.jsfiddle.net/N88gv/

ContentLicense: CC BY-SA 2.5

Title: jquery : show/hide div, timing

Body:
I have a pretty standard problem here.

I have an error div that,

when a button is pressed is populated with an error message,
the div is then faded in, after (500*n)ms (where n = number of letters) the div is faded out.

my issue occurs when the user presses the button again before the div has faded out.

while the div is still visible the divs contents are updated with the new error message,

after the initial (500*n)ms the div is faded out, then immediately gets faded back in and is visible for another (500*n)ms.

What I want is.

user clicks button

div contents are updated

div is faded in

user clicks button again

div immediately fades out

content is updated

div is faded in.

How can I achieve this?

My current code is below

function login_error(message){
        $('form').effect('shake', { times: 1 }, 50);
        $('#error').html(message).fadeIn('fast').delay(500*message.length).fadeOut('fast');
}

Body:
simething like this?

 $(function() {
    var counter = 0;
    var timeOut;
    $('button').click(function() {
        showdiv('clicked ' + counter++);
    });

    function showdiv(str) {
        clearTimeout(timeOut);
        $('div').fadeOut(function() {
            $(this).html(str).fadeIn(function() {
                timeOut = setTimeout(function() {
                    $('div').fadeOut();
                }, 100 * str.length);
            });
        })
    }
});

demo:
http://www.jsfiddle.net/N88gv/


问:
Create reference to object in unique_ptr with typecast

I find I still do an embarrassingly large number of things in c style, so I am now trying to embrace the new millennium by reducing my usage of raw pointers. I have a vector of unique_ptr<BaseClass>, that each points to an object of a derived class. I am trying to get a nice way to refer to one of the objects of the derived class. At the moment, I do this by using the .get() function and casting this to the derived class.

However, as I understand it, .get() is mostly there to interface with legacy code that insists on raw pointers, and its use should be avoided. Having another pointer to an object within a unique_ptr doesn't seem like great style if it can be avoided. Is there a way to get a reference to the derived class object, without using get? Or some other convenient way of handling the object?

Here is a simplified code example:

#include <iostream>
#include <vector>

class Fruit {
public:
    double size = 0;
    virtual ~Fruit() = default;
};

class Apple : public Fruit {
public:
    bool hasLeaf = false;
};

void doAppleStuff(std::vector<std::unique_ptr<Fruit> > &apples) {

    // assume we know that element [0] exists and it is definitely of type Apple
    auto apple = static_cast<Apple *> (apples[0].get());  // is there a better option?

    if (apple->hasLeaf) {
        std::cout << "We can leaf now" << std::endl;
    } else {
        std::cout << "We are pitiably leafless" << std::endl;
    }
}

int main() {
    std::vector<std::unique_ptr<Fruit> > fruitVec;
    auto apple = new Apple;
    apple->hasLeaf = true;
    std::unique_ptr<Fruit> applePt(apple);
    fruitVec.push_back(std::move(applePt));
    doAppleStuff(fruitVec);
    return 0;
}
```

<p>(I think that it's probably possible to shorten the main function with <code>make_unique</code> from c++14).</p>

<p>Would it be good coding style to do something like this?</p>

<pre class="lang-cpp prettyprint-override"><code>auto &apple = *static_cast<Apple *> (apples[0].get());
</code>```

The answer at "Downcasting" unique_ptr<Base> to unique_ptr<Derived> outlines a method to "cast" the unique_ptr by releasing it and recreating a new unique_ptr to the derived class, but that doesn't seem applicable here, as I don't really want to mess with the vector of unique pointers (unless I am missing something).

答:
If you know that the pointer is non-nullptr, a simpler cast is:

```<code>auto& apple = static_cast<Apple&>(*apples[0]);
</code>```

This syntax works with all smart-pointers that support T& operator*() const (e.g. std::unique_ptr, std::shared_ptr, boost::intrusive_ptr).

In cases with multiple inheritance casting from-base-reference-to-derived-reference is faster than casting from-base-pointer-to-derived-pointer because the latter must always check for nullptr before adding or subtracting an offset to the pointer (so that nullptr turns into nullptr after the cast), whereas references cannot be nullptr and therefore no run-time check is necessary.

ContentLicense: CC BY-SA 3.0

Body:
I find I still do an embarrassingly large number of things in c style, so I am now trying to embrace the new millennium by reducing my usage of raw pointers. I have a vector of unique_ptr<BaseClass>, that each points to an object of a derived class. I am trying to get a nice way to refer to one of the objects of the derived class. At the moment, I do this by using the .get() function and casting this to the derived class.

However, as I understand it, .get() is mostly there to interface with legacy code that insists on raw pointers, and its use should be avoided. Having another pointer to an object within a unique_ptr doesn't seem like great style if it can be avoided. Is there a way to get a reference to the derived class object, without using get? Or some other convenient way of handling the object?

Here is a simplified code example:

#include <iostream>
#include <vector>

class Fruit {
public:
    double size = 0;
    virtual ~Fruit() = default;
};

class Apple : public Fruit {
public:
    bool hasLeaf = false;
};

void doAppleStuff(std::vector<std::unique_ptr<Fruit> > &apples) {

    // assume we know that element [0] exists and it is definitely of type Apple
    auto apple = static_cast<Apple *> (apples[0].get());  // is there a better option?

    if (apple->hasLeaf) {
        std::cout << "We can leaf now" << std::endl;
    } else {
        std::cout << "We are pitiably leafless" << std::endl;
    }
}

int main() {
    std::vector<std::unique_ptr<Fruit> > fruitVec;
    auto apple = new Apple;
    apple->hasLeaf = true;
    std::unique_ptr<Fruit> applePt(apple);
    fruitVec.push_back(std::move(applePt));
    doAppleStuff(fruitVec);
    return 0;
}

(I think that it's probably possible to shorten the main function with make_unique from c++14).

Would it be good coding style to do something like this?

auto &apple = *static_cast<Apple *> (apples[0].get());

The answer at "Downcasting" unique_ptr<Base> to unique_ptr<Derived> outlines a method to "cast" the unique_ptr by releasing it and recreating a new unique_ptr to the derived class, but that doesn't seem applicable here, as I don't really want to mess with the vector of unique pointers (unless I am missing something).

Body:
If you know that the pointer is non-nullptr, a simpler cast is:

auto& apple = static_cast<Apple&>(*apples[0]);

This syntax works with all smart-pointers that support T& operator*() const (e.g. std::unique_ptr, std::shared_ptr, boost::intrusive_ptr).

In cases with multiple inheritance casting from-base-reference-to-derived-reference is faster than casting from-base-pointer-to-derived-pointer because the latter must always check for nullptr before adding or subtracting an offset to the pointer (so that nullptr turns into nullptr after the cast), whereas references cannot be nullptr and therefore no run-time check is necessary.


问:
How to create and export XML Reports in Odoo?
As default we can export our reports in Odoo as PDF or HTML. Also it seems possible to export to XLS, ODT etc. with help of some addons. But what I need is the XML format. Is it possible somehow in Odoo?

When I checked the Odoo implementation, I thought that maybe it was possible with a controller type report and some python code for controller to export as XML. So what are your insights about that?

答:
There is a module that let you create a xml report: report_xml. You only need to add a dependency to your module and declare the report as a normal one like this:

<report
    id="example_xml_report"
    name="module_name.template_custom_id"
    string="Example XML Report"
    report_type="qweb-xml"
    menu="False"
    model="account.invoice" />
```

<p>Then you can add the xml report with qweb. This is much more convenient that build it with the <code>lxml</code> library directly:</p>

<pre class="lang-xml prettyprint-override"><code><template id="template_custom_id">
    <t t-call="report_xml.utf8_header">
        <FIRSTHEADER>
            <OPERATION t-esc="operation" />
            <OPERATIONTYPE t-esc="operation_type" />
            <VERSION t-raw="0">1.0</VERSION>    <!-- literal value -->

            <ELEMENT t-foreach="docs" t-as="o">
                <COMPANYNAME t-esc="o.company_id.name" />

                <!-- [...] -->
</code>```

You can add a python class to process some custom data for the report as the rest of reports:

class AccountInvoiceXmlReport(models.AbstractModel):
    _name = "report.module_name.template_custom_id"

    @api.multi
    def render_html(self, data=None):
        """ If ``context`` contains a dict called ``docargs``, it will be used as
            the Qweb context. The special key ``docs`` will be added to ``docargs``
            automatically if missing.
        """

        # some operations

        docargs = self.env.context.get("docargs", dict())
        if "docs" not in docargs:
            docargs["docs"] = (account_invoice_obj)

        docargs.update({
            'operation': self.env.context.get('operation', False),
            'operation_type': self.env.context.get('operation_type', False)       # TODO >> verify the invoices have the same type
        })

        result = (
            self.env["report"].render(            # generate xml report
                self._name[len("report."):],
                docargs
            ).strip()
        )
        return result
```

As you can check in the README.rst the requirements:

Install the lxml library.

Install the repository reporting-engine

For further instructions about creating reports go here

Body:
There is a module that let you create a xml report: report_xml. You only need to add a dependency to your module and declare the report as a normal one like this:

<report
    id="example_xml_report"
    name="module_name.template_custom_id"
    string="Example XML Report"
    report_type="qweb-xml"
    menu="False"
    model="account.invoice" />

Then you can add the xml report with qweb. This is much more convenient that build it with the lxml library directly:

<template id="template_custom_id">
    <t t-call="report_xml.utf8_header">
        <FIRSTHEADER>
            <OPERATION t-esc="operation" />
            <OPERATIONTYPE t-esc="operation_type" />
            <VERSION t-raw="0">1.0</VERSION>    <!-- literal value -->

            <ELEMENT t-foreach="docs" t-as="o">
                <COMPANYNAME t-esc="o.company_id.name" />

                <!-- [...] -->

You can add a python class to process some custom data for the report as the rest of reports:

class AccountInvoiceXmlReport(models.AbstractModel):
    _name = "report.module_name.template_custom_id"

    @api.multi
    def render_html(self, data=None):
        """ If ``context`` contains a dict called ``docargs``, it will be used as
            the Qweb context. The special key ``docs`` will be added to ``docargs``
            automatically if missing.
        """

        # some operations

        docargs = self.env.context.get("docargs", dict())
        if "docs" not in docargs:
            docargs["docs"] = (account_invoice_obj)

        docargs.update({
            'operation': self.env.context.get('operation', False),
            'operation_type': self.env.context.get('operation_type', False)       # TODO >> verify the invoices have the same type
        })

        result = (
            self.env["report"].render(            # generate xml report
                self._name[len("report."):],
                docargs
            ).strip()
        )
        return result

As you can check in the README.rst the requirements:

Install the lxml library.

Install the repository reporting-engine

For further instructions about creating reports go here


问:
Hyperlink combined with pseudo code
In the code below, how can I have the same font color for the hyperlinks as for the other text? It now seems to morph with the color as defined in the pseudo code.

ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

a, a:link, a:visited, a:active {
  text-decoration: none;
  color: #484693;
}

nav {
  color: #484693;
  font-weight: bold;
  width: calc(100% - 5vw);
  display: flex;
  align-items: center;
}

nav>ul {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: space-around;
}

nav>ul>li {
  margin-right: 2em;
}

nav>ul>li.header-button {
  position: relative;
  padding: 1em;
}

nav>ul>li.header-button::before {
  content: '';
  width: 100%;
  height: 70%;
  background: rgba(255, 25, 255, 0.4);
  border: thin solid rgba(255, 25, 255, 0.4);
  border-radius: 20px;
  position: absolute;
  top: 50%;
  left: 0;
  transform: translateY(-50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <div class="header-logo">
    <img src="http://via.placeholder.com/50x50" alt="" />
  </div>
  <ul>
    <li>Option1</li>
    <li>Option2</li>
    <li class="header-button">Option3</li>
    <li class="header-button">Option4</li>
  </ul>
</nav></code>```

答:
The issue you are having is the pseudo element you are using to create the background is coming on top of the anchor tag, since you have given absolute position to the pseudo element. You can overcome that by assigning position relative to the anchor tag and assign a z-index to it.

WORKING DEMO:

ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

a, a:link, a:visited, a:active {
  text-decoration: none;
  color: #484693;
}

nav {
  color: #484693;
  font-weight: bold;
  width: calc(100% - 5vw);
  display: flex;
  align-items: center;
}

nav>ul {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: space-around;
}

nav>ul>li {
  margin-right: 2em;
}

nav>ul>li.header-button {
  position: relative;
  padding: 1em;
}

nav>ul>li.header-button::before {
  content: '';
  width: 100%;
  height: 70%;
  background: rgba(255, 25, 255, 0.4);
  border: thin solid rgba(255, 25, 255, 0.4);
  border-radius: 20px;
  position: absolute;
  top: 50%;
  left: 0;
  transform: translateY(-50%);
}

nav>ul>li a {
   position: relative;
   z-index: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <div class="header-logo">
    <img src="http://via.placeholder.com/50x50" alt="" />
  </div>
  <ul>
    <li>Option1</li>
    <li>Option2</li>
    <li class="header-button">Option3</li>
    <li class="header-button">Option4</li>
  </ul>
</nav></code>```

Title: Hyperlink combined with pseudo code

Body:
In the code below, how can I have the same font color for the hyperlinks as for the other text? It now seems to morph with the color as defined in the pseudo code.

ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

a, a:link, a:visited, a:active {
  text-decoration: none;
  color: #484693;
}

nav {
  color: #484693;
  font-weight: bold;
  width: calc(100% - 5vw);
  display: flex;
  align-items: center;
}

nav>ul {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: space-around;
}

nav>ul>li {
  margin-right: 2em;
}

nav>ul>li.header-button {
  position: relative;
  padding: 1em;
}

nav>ul>li.header-button::before {
  content: '';
  width: 100%;
  height: 70%;
  background: rgba(255, 25, 255, 0.4);
  border: thin solid rgba(255, 25, 255, 0.4);
  border-radius: 20px;
  position: absolute;
  top: 50%;
  left: 0;
  transform: translateY(-50%);
}

Option1

Option2

Option3

Option4

Body:
The issue you are having is the pseudo element you are using to create the background is coming on top of the anchor tag, since you have given absolute position to the pseudo element. You can overcome that by assigning position relative to the anchor tag and assign a z-index to it.

WORKING DEMO:

ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

a, a:link, a:visited, a:active {
  text-decoration: none;
  color: #484693;
}

nav {
  color: #484693;
  font-weight: bold;
  width: calc(100% - 5vw);
  display: flex;
  align-items: center;
}

nav>ul {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: space-around;
}

nav>ul>li {
  margin-right: 2em;
}

nav>ul>li.header-button {
  position: relative;
  padding: 1em;
}

nav>ul>li.header-button::before {
  content: '';
  width: 100%;
  height: 70%;
  background: rgba(255, 25, 255, 0.4);
  border: thin solid rgba(255, 25, 255, 0.4);
  border-radius: 20px;
  position: absolute;
  top: 50%;
  left: 0;
  transform: translateY(-50%);
}

nav>ul>li a {
   position: relative;
   z-index: 1;
}

<nav>
  <div class="header-logo">
    <a href="#"><img src="http://via.placeholder.com/50x50" alt="" /></a>
  </div>
  <ul>
    <li>Option1</li>
    <li>Option2</li>
    <li class="header-button"><a href="#">Option3</a></li>
    <li class="header-button"><a href="#">Option4</a></li>
  </ul>
</nav>


问:
How can I fill icon color after onclick function using jquery in react js
Here is my code.Let me advice ,I want to change icon color after onclick function .

```<code><div class="timeline-footer">
  <a
    id="changeicon"
    onClick={(event) => this.handleCount(post.id, event)}
    class="m-r-25"
  ><i class="fa fa-heart-o"></i> {post.rating} Like</a>
</div>
</code>```

This is my rating count function

```<code>handleCount(id, event) {
  event.classList.toggle("icon-heart");

  fetch(this.state.url + '/rating/' + id, {
    method: 'POST',
    header: {
      'Accept': 'applicatoin/json',
      'Content-Type': 'application/json'
    }
  })
  .then((response) => {
    window.location.reload();
  })
}
</code>```

答:
Do you want to change color after each click?
You can do it more 'react-way' without using jquery through state changing:

```<code>changeColor = (color) => this.setState({iconColor: color});

getIconStyle = () => ({
    color: this.state.iconColor
});

handleCount = (id, event) => {
    event.classList.toggle("icon-heart");

    this.changeColor("red"); // or anyway you want

    fetch(this.state.url + '/rating/' + id, {
        method: 'POST',
        header: {
            'Accept': 'applicatoin/json',
            'Content-Type': 'application/json'
        }
    })
    .then((response) => {
        window.location.reload();
    })
}
</code>```

Inside render:

```<code><div className="timeline-footer">
     <a
         id="changeicon"
         onClick={(event) => this.handleCount(post.id, event)}
         style={this.getIconStyle()}
         className="m-r-25"
     >
          <i className="fa fa-heart-o"></i> {post.rating} Like
     </a>
</div>
</code>```

Or change class instead of style if it suits your case

Body:
Here is my code.Let me advice ,I want to change icon color after onclick function .

   this.handleCount(post.id, event)}
    class="m-r-25"
  > {post.rating} Like

This is my rating count function

handleCount(id, event) {
  event.classList.toggle("icon-heart");

  fetch(this.state.url + '/rating/' + id, {
    method: 'POST',
    header: {
      'Accept': 'applicatoin/json',
      'Content-Type': 'application/json'
    }
  })
  .then((response) => {
    window.location.reload();
  })
}

Body:
Do you want to change color after each click?
You can do it more 'react-way' without using jquery through state changing:

changeColor = (color) => this.setState({iconColor: color});

getIconStyle = () => ({
    color: this.state.iconColor
});

handleCount = (id, event) => {
    event.classList.toggle("icon-heart");

    this.changeColor("red"); // or anyway you want

    fetch(this.state.url + '/rating/' + id, {
        method: 'POST',
        header: {
            'Accept': 'applicatoin/json',
            'Content-Type': 'application/json'
        }
    })
    .then((response) => {
        window.location.reload();
    })
}

Inside render:

<div className="timeline-footer">
     <a
         id="changeicon"
         onClick={(event) => this.handleCount(post.id, event)}
         style={this.getIconStyle()}
         className="m-r-25"
     >
          <i className="fa fa-heart-o"></i> {post.rating} Like
     </a>
</div>

Or change class instead of style if it suits your case


问:
kivy(v1.8) Clock.unschedule() -> AttributeError: no attribute "is_done"
Overflow community,

I am struggeling right now with the following problem:
I want to have various callback-events running (having their own amount of arguments passed additionally, so using something like "partial" comes into play as well) in parallel and I want to have buttons to cancel them individually. I tried this for one event to begin with in various ways. Using lambda notation, global variables or adressing the "Clock._events['']. Also, I enhanced an example that I found on the net which makes use of a new class to even pass further variables to the callback-function. One code-snipped, that produces the same error that I get for all my approaches is the following:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.clock import Clock
from kivy.lang import Builder

class CallbackHelper:
    def __init__(self, *args):
        self.app = args[0][0]
        self.instance = args[0][1]
        print 'writing from init'
        print self.app
        print self.instance

    def __call__(self, *args):
        MyWidget.my_callback(self.app, self.instance)
        print Clock._events

Builder.load_string("""
#:import Clock kivy.clock.Clock

<MyWidget>:
    Button:
        text: "Print events"
        on_press: print(Clock._events)
    Button:
        text: "Add event"
        on_press: root.start_callback(self)
    Button:
        text: "Unschedule event"
        on_press: root.start_unschedule(self)
""")

class MyWidget(BoxLayout):
    callback_var = []
    def my_callback(self, *args):
        print("my_callback")

    def start_callback(self, instance):
        self.callback_var = Clock.schedule_interval(CallbackHelper([self, instance]), 1)

    def start_unschedule(self,instance):
        Clock.unschedule(self.callback_var)

class MyApp(App):
    def build(self):
        return MyWidget()

if __name__ == '__main__':
    MyApp().run()
```

<p>The error produced is: </p>

<pre class="lang-bsh prettyprint-override"><code>my_callback
{'default': [<ClockEvent callback=<__main__.CallbackHelper instance at 0x000000000642D248>>], '_purge_by_timeout': [<ClockEvent callback=<function _purge_by_timeout at 0x0000000004B18668>>]}
[INFO              ] [Base        ] Leaving application in progress...
 Traceback (most recent call last):
   File "[...]/test/functionScheduleCheck.py", line 53, in <module>
     MyApp().run()
   File "[...]\Anaconda2\lib\site-packages\kivy\app.py", line 792, in run
     runTouchApp()
   File "[...]\Anaconda2\lib\site-packages\kivy\base.py", line 481, in runTouchApp
     EventLoop.window.mainloop()
   File "[...]\Anaconda2\lib\site-packages\kivy\core\window\window_pygame.py", line 381, in mainloop
     self._mainloop()
   File "[...]\Anaconda2\lib\site-packages\kivy\core\window\window_pygame.py", line 287, in _mainloop
     EventLoop.idle()
   File "[...]\Anaconda2\lib\site-packages\kivy\base.py", line 324, in idle
     self.dispatch_input()
   File "[...]\Anaconda2\lib\site-packages\kivy\base.py", line 309, in dispatch_input
     post_dispatch_input(*pop(0))
   File "[...]\Anaconda2\lib\site-packages\kivy\base.py", line 220, in post_dispatch_input
     listener.dispatch('on_motion', etype, me)
   File "_event.pyx", line 316, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:4537)
   File "[...]\Anaconda2\lib\site-packages\kivy\core\window\__init__.py", line 645, in on_motion
     self.dispatch('on_touch_down', me)
   File "_event.pyx", line 316, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:4537)
   File "[...]\Anaconda2\lib\site-packages\kivy\core\window\__init__.py", line 657, in on_touch_down
     if w.dispatch('on_touch_down', touch):
   File "_event.pyx", line 316, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:4537)
   File "[...]\Anaconda2\lib\site-packages\kivy\uix\widget.py", line 284, in on_touch_down
     if child.dispatch('on_touch_down', touch):
   File "_event.pyx", line 316, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:4537)
   File "[...]\Anaconda2\lib\site-packages\kivy\uix\behaviors.py", line 93, in on_touch_down
     self.dispatch('on_press')
   File "_event.pyx", line 312, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:4491)
   File "[...]\Anaconda2\lib\site-packages\kivy\lang.py", line 1299, in custom_callback
     exec(__kvlang__.co_value, idmap)
   File "<string>", line 14, in <module>
   File "[...]/test/functionScheduleCheck.py", line 46, in start_unschedule
     Clock.unschedule(self.callback_var)
   File "[...]\Anaconda2\lib\site-packages\kivy\clock.py", line 505, in unschedule
     if callback.is_done:
 AttributeError: 'ClockEvent' object has no attribute 'is_done'
</code>```

E.g. storing the event as a global variable EVENT and then calling EVENT.cancel() does nothing btw.

Any ideas?

I really appreciate your help,
Tanoshimi

答:
I tried the following:

upgrading to kivy 1.10 in a new virtualenv (from 1.8)

migrating the code

fixing: Clock._events['my_event_name'] to Clock.get_events()[my_event_list_nbr]

now works like a charm. One guess is: callback routines just weren't functionally implemented at kivy v1.8 with respect to cancel() and unschedule routines. Thank you kivy time for having this fixes with a newer installment of the environment.

Body:
Overflow community,

I am struggeling right now with the following problem:
I want to have various callback-events running (having their own amount of arguments passed additionally, so using something like "partial" comes into play as well) in parallel and I want to have buttons to cancel them individually. I tried this for one event to begin with in various ways. Using lambda notation, global variables or adressing the "Clock._events['']. Also, I enhanced an example that I found on the net which makes use of a new class to even pass further variables to the callback-function. One code-snipped, that produces the same error that I get for all my approaches is the following:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.clock import Clock
from kivy.lang import Builder

class CallbackHelper:
    def __init__(self, *args):
        self.app = args[0][0]
        self.instance = args[0][1]
        print 'writing from init'
        print self.app
        print self.instance

    def __call__(self, *args):
        MyWidget.my_callback(self.app, self.instance)
        print Clock._events

Builder.load_string("""
#:import Clock kivy.clock.Clock

<MyWidget>:
    Button:
        text: "Print events"
        on_press: print(Clock._events)
    Button:
        text: "Add event"
        on_press: root.start_callback(self)
    Button:
        text: "Unschedule event"
        on_press: root.start_unschedule(self)
""")

class MyWidget(BoxLayout):
    callback_var = []
    def my_callback(self, *args):
        print("my_callback")

    def start_callback(self, instance):
        self.callback_var = Clock.schedule_interval(CallbackHelper([self, instance]), 1)

    def start_unschedule(self,instance):
        Clock.unschedule(self.callback_var)

class MyApp(App):
    def build(self):
        return MyWidget()

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

The error produced is:

my_callback
{'default': [<ClockEvent callback=<__main__.CallbackHelper instance at 0x000000000642D248>>], '_purge_by_timeout': [<ClockEvent callback=<function _purge_by_timeout at 0x0000000004B18668>>]}
[INFO              ] [Base        ] Leaving application in progress...
 Traceback (most recent call last):
   File "[...]/test/functionScheduleCheck.py", line 53, in <module>
     MyApp().run()
   File "[...]\Anaconda2\lib\site-packages\kivy\app.py", line 792, in run
     runTouchApp()
   File "[...]\Anaconda2\lib\site-packages\kivy\base.py", line 481, in runTouchApp
     EventLoop.window.mainloop()
   File "[...]\Anaconda2\lib\site-packages\kivy\core\window\window_pygame.py", line 381, in mainloop
     self._mainloop()
   File "[...]\Anaconda2\lib\site-packages\kivy\core\window\window_pygame.py", line 287, in _mainloop
     EventLoop.idle()
   File "[...]\Anaconda2\lib\site-packages\kivy\base.py", line 324, in idle
     self.dispatch_input()
   File "[...]\Anaconda2\lib\site-packages\kivy\base.py", line 309, in dispatch_input
     post_dispatch_input(*pop(0))
   File "[...]\Anaconda2\lib\site-packages\kivy\base.py", line 220, in post_dispatch_input
     listener.dispatch('on_motion', etype, me)
   File "_event.pyx", line 316, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:4537)
   File "[...]\Anaconda2\lib\site-packages\kivy\core\window\__init__.py", line 645, in on_motion
     self.dispatch('on_touch_down', me)
   File "_event.pyx", line 316, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:4537)
   File "[...]\Anaconda2\lib\site-packages\kivy\core\window\__init__.py", line 657, in on_touch_down
     if w.dispatch('on_touch_down', touch):
   File "_event.pyx", line 316, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:4537)
   File "[...]\Anaconda2\lib\site-packages\kivy\uix\widget.py", line 284, in on_touch_down
     if child.dispatch('on_touch_down', touch):
   File "_event.pyx", line 316, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:4537)
   File "[...]\Anaconda2\lib\site-packages\kivy\uix\behaviors.py", line 93, in on_touch_down
     self.dispatch('on_press')
   File "_event.pyx", line 312, in kivy._event.EventDispatcher.dispatch (kivy\_event.c:4491)
   File "[...]\Anaconda2\lib\site-packages\kivy\lang.py", line 1299, in custom_callback
     exec(__kvlang__.co_value, idmap)
   File "<string>", line 14, in <module>
   File "[...]/test/functionScheduleCheck.py", line 46, in start_unschedule
     Clock.unschedule(self.callback_var)
   File "[...]\Anaconda2\lib\site-packages\kivy\clock.py", line 505, in unschedule
     if callback.is_done:
 AttributeError: 'ClockEvent' object has no attribute 'is_done'

E.g. storing the event as a global variable EVENT and then calling EVENT.cancel() does nothing btw.

Any ideas?

I really appreciate your help,
Tanoshimi


问:
Install ruby gem in rescue block when 'LoadError' occurs
I am trying to install a ruby gem from a ruby script when it can't load the required gem from local system. Here is my code.

```<code>begin
  require '<gem name here>'
rescue LoadError
  puts `gem install <gem name here>`
  require '<gem name here>'
end
</code>```

The code above installs the gem in the rescue block. But when it requires the gem, it shows this error:

```<code>.rvm/rubies/ruby-2.4.2/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb
:55:in require': cannot load such file -- <gem name here> (LoadError)
</code>```

How can this be solved? I want the gem to be loaded within the rescue block if not already present in the system.

答:
After rigorous searching, I found an answer. If we use Gem.clear_paths after installing the gem, it will now available to the script. Total updated code is :

```<code>begin
require '<gem name here>'
rescue LoadError
  puts `gem install <gem name here>`
  Gem.clear_paths
  require '<gem name here>'
end
</code>```

Body:
I am trying to install a ruby gem from a ruby script when it can't load the required gem from local system. Here is my code.

begin
  require '<gem name here>'
rescue LoadError
  puts `gem install <gem name here>`
  require '<gem name here>'
end

The code above installs the gem in the rescue block. But when it requires the gem, it shows this error:

.rvm/rubies/ruby-2.4.2/lib/ruby/site_ruby/2.4.0/rubygems/core_ext/kernel_require.rb
:55:in require': cannot load such file -- <gem name here> (LoadError)

How can this be solved? I want the gem to be loaded within the rescue block if not already present in the system.

Body:
After rigorous searching, I found an answer. If we use Gem.clear_paths after installing the gem, it will now available to the script. Total updated code is :

begin
require '<gem name here>'
rescue LoadError
  puts `gem install <gem name here>`
  Gem.clear_paths
  require '<gem name here>'
end


问:
jboss eap 6.4 in maven access failed
I had deploy maven project built in war package to Jboss EAP 6.4 and successfully, WAR package deployed. I had created services and run with spring-boot in local eclipse and I can ran in browser but I have a problem when access that URL based on war package in Jboss eap. I success ran jboss service but cannot run the URL. for example, I have service with method GET with url: localhost:8080/letter-printing-eap-generator/testing cannot run in jboss but ran in local eclipse before deploy. how to fix this problem? any configuration xml in maven project? I just add jboss plugin. thanks. my code:

my pom.xml:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.prudential.letter.printing</groupId>
    <artifactId>letter-printing-eap-generator</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <packaging>war</packaging>

    <name>LetterPrintingEapGenerator</name>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>1.2.2.RELEASE</spring-cloud.version>
        <swagger.version>2.6.1</swagger.version>
        <jboss.home>${env.JBOSS_HOME}</jboss.home>
        <config.server>http://10.170.49.103/configserver</config.server>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
        </dependency>

        <!-- Spring Boot -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
            <version>${spring-cloud.version}</version>
        </dependency>

        <!-- Swagger -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger.version}</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-data-rest</artifactId>
            <version>${swagger.version}</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.5</version>
        </dependency>

    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <!-- JBOSS maven plugin to simulate deployment to JBOSS -->
            <plugin>
                <groupId>org.jboss.as.plugins</groupId>
                <artifactId>jboss-as-maven-plugin</artifactId>
                <version>7.9.Final</version>
                <configuration>
                    <jbossHome>${jboss.home}</jbossHome>
                    <serverArgs>
                        <serverArg>-Dspring.profiles.active=${run.profiles}</serverArg>
                        <serverArg>-Dspring.cloud.config.uri=${config.server}</serverArg>
                    </serverArgs>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

SpringBootRestApiApp.java

```<code>@SpringBootApplication(scanBasePackages={"com.prudential.letter.printing"})
@Import({SpringDataRestConfiguration.class})
public class SpringBootRestApiApp {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootRestApiApp.class, args);
    }
}
</code>```

my controller:

```<code>@RestController
@RequestMapping(value="/")
public class TestingController {

    @GetMapping("testing")
    public String getTestingMethod(){
        return "Hello Testing";
    }

    @GetMapping("data")
    public Map<String, Object> getData(){
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("status", "200");
        map.put("message", "ini messagenya");
        map.put("content", "mantap");

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

this is my project structure:

application.yml :

```<code>server:
  port: 8080
  contextPath: /letter-printing-eap-generator
</code>```

答:
In the absence of any specific configuration, JBoss EAP will provide access to your web application at a context with a name that matches the WAR file name.

Therefore, your application should be accessible at:

```<code>http://localhost:8080/letter-printing-eap-generator-0.0.1-SNAPSHOT/testing
</code>```

A common way of changing this for development purposes is to include a finalName element in the pom.xml file:

```<code>    <build>
        <finalName>${project.artifactId}</finalName>
        ...
    </build>
</code>```

This will generate a WAR file named letter-printing-eap-generator.war and the original URL that you tried should work.

Alternatively, you could add a jboss-web.xml file to your deployment (in the WEB-INF directory) that contains a context-root element:

```<code><jboss-web>
     <context-root>letter-printing-eap-generator</context-root>
</jboss-web>
</code>```

You could also do this using the JBoss CLI or the web console to perform deployment as well.

Title: jboss eap 6.4 in maven access failed

Body:
I had deploy maven project built in war package to Jboss EAP 6.4 and successfully, WAR package deployed. I had created services and run with spring-boot in local eclipse and I can ran in browser but I have a problem when access that URL based on war package in Jboss eap. I success ran jboss service but cannot run the URL. for example, I have service with method GET with url: localhost:8080/letter-printing-eap-generator/testing cannot run in jboss but ran in local eclipse before deploy. how to fix this problem? any configuration xml in maven project? I just add jboss plugin. thanks. my code:

my pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.prudential.letter.printing</groupId>
    <artifactId>letter-printing-eap-generator</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <packaging>war</packaging>

    <name>LetterPrintingEapGenerator</name>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>1.2.2.RELEASE</spring-cloud.version>
        <swagger.version>2.6.1</swagger.version>
        <jboss.home>${env.JBOSS_HOME}</jboss.home>
        <config.server>http://10.170.49.103/configserver</config.server>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
            <version>${spring-cloud.version}</version>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger.version}</version>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-data-rest</artifactId>
            <version>${swagger.version}</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.5</version>
        </dependency>

    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>org.jboss.as.plugins</groupId>
                <artifactId>jboss-as-maven-plugin</artifactId>
                <version>7.9.Final</version>
                <configuration>
                    <jbossHome>${jboss.home}</jbossHome>
                    <serverArgs>
                        <serverArg>-Dspring.profiles.active=${run.profiles}</serverArg>
                        <serverArg>-Dspring.cloud.config.uri=${config.server}</serverArg>
                    </serverArgs>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

SpringBootRestApiApp.java

@SpringBootApplication(scanBasePackages={"com.prudential.letter.printing"})
@Import({SpringDataRestConfiguration.class})
public class SpringBootRestApiApp {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootRestApiApp.class, args);
    }
}

my controller:

@RestController
@RequestMapping(value="/")
public class TestingController {

    @GetMapping("testing")
    public String getTestingMethod(){
        return "Hello Testing";
    }

    @GetMapping("data")
    public Map<String, Object> getData(){
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("status", "200");
        map.put("message", "ini messagenya");
        map.put("content", "mantap");

        return map;
    }
}

this is my project structure:

application.yml :

server:
  port: 8080
  contextPath: /letter-printing-eap-generator

Body:
In the absence of any specific configuration, JBoss EAP will provide access to your web application at a context with a name that matches the WAR file name.

Therefore, your application should be accessible at:

http://localhost:8080/letter-printing-eap-generator-0.0.1-SNAPSHOT/testing

A common way of changing this for development purposes is to include a finalName element in the pom.xml file:

    <build>
        <finalName>${project.artifactId}</finalName>
        ...
    </build>

This will generate a WAR file named letter-printing-eap-generator.war and the original URL that you tried should work.

Alternatively, you could add a jboss-web.xml file to your deployment (in the WEB-INF directory) that contains a context-root element:

<jboss-web>
     <context-root>letter-printing-eap-generator</context-root>
</jboss-web>

You could also do this using the JBoss CLI or the web console to perform deployment as well.


问:
PhP shell_exec python code - how to avoid repetitive initiation of python objects

In "webpage1.php":

```<code>shell_exec("\usr\local\bin\python3.5 code1.py")
</code>```

In "code1.py":

```<code>import bigClass
obj1 = bigClass() # costs >1 minute to initiate
obj1.dosomething()
</code>```

The problem is that everytime webpage1 is called by a visitor to the website, a bigClass object is initiated from fresh, costing a lot of time.

Is there a way that I have this obj1 initiated beforehand, and the shell_exec simple gets a handle to it and calls its method?

答: Pickle is not a solution, because the object is not a global one. Pickle cannot handle local objects. I just have to purchase a more expensive server with more memory I suppose for the big NLP class to initialise quickly!</p>

Body:
In "webpage1.php":

shell_exec("\usr\local\bin\python3.5 code1.py")

In "code1.py":

import bigClass
obj1 = bigClass() # costs >1 minute to initiate
obj1.dosomething()

The problem is that everytime webpage1 is called by a visitor to the website, a bigClass object is initiated from fresh, costing a lot of time.

Is there a way that I have this obj1 initiated beforehand, and the shell_exec simple gets a handle to it and calls its method?


问:
PHP Uncaught Error: Call to a member function query() on null,
I'm studying php and trying to integrate it with oop on my own,can anyone explain idea of this error ?

As I guess it can't find a query and but I can't get why,because in $query everything is correct, p.s global $mysqli is for test purposes only,I know using it carelessly is bad.

```<code>    <?php

class Index{
    public function connect(){
    $mysqli=new mysqli();
    $mysqli->connect('localhost',"root","");
    $conn=$mysqli->select_db("webartisan");

    if($mysqli->errno){
    echo "Unable to connect to the database: ".$mysqli->error;
    exit();
    }
 }
public function select_data($table,$id){
    $query="SELECT * FROM {$table} WHERE id=$id  ";
    }
    public function insert_data(){
        global $conn;
        $username=$_POST['username'];
        $password=$_POST['password'];
        $query="INSERT INTO artisan(username,password) VALUES('$username','$password')";

        $result=$conn->query($query);

        if($result->num_rows){
            return true;
        }
    }
    public function register(){
        if(isset($_POST['submit'])){
            self::insert_data();
        }
    }
}
$index=new Index();
$index->register();
?>

<form method="POST" action="index.php">
    <input type="text" name="username"><br><br>
    <input type="password" name="password"><br><br>
    <input type="submit" name="submit">

</form>
</code>```

Error:

Fatal error: Uncaught Error: Call to a member function query() on null
  in C:\xampp\htdocs\webartisan\index.php:23 Stack trace: #0
  C:\xampp\htdocs\webartisan\index.php(31): Index->insert_data() #1
  C:\xampp\htdocs\webartisan\index.php(36): Index->register() #2 {main}
  thrown in C:\xampp\htdocs\webartisan\index.php on line 23

答:
$conn variable is not accessible as global variable because you declare $conn as local variable inside connect() method.

To address this problem, you need to declare as class field and then you can access $conn as $this->conn inside any methods of class Index. This way you do not need global $conn.

For example:

```<code><?php
class Index{
    private $conn;

    public function connect() {
        ...
        $this->conn = $mysqli->select_db("webartisan");
        ...
    }

    public function insert_data() {
        ...
        $result = $this->conn->query($query);
        ...
    }
}
</code>```

Update:

select_db() returns boolean value, not connection object. Following line will cause Call to a member function query() on boolean error as you said in comment.

```<code>$this->conn = $mysqli->select_db("webartisan");
</code>```

You should read mysqli documentation.

Body:
I'm studying php and trying to integrate it with oop on my own,can anyone explain idea of this error ?

As I guess it can't find a query and but I can't get why,because in $query everything is correct, p.s global $mysqli is for test purposes only,I know using it carelessly is bad.

    <?php

class Index{
    public function connect(){
    $mysqli=new mysqli();
    $mysqli->connect('localhost',"root","");
    $conn=$mysqli->select_db("webartisan");

    if($mysqli->errno){
    echo "Unable to connect to the database: ".$mysqli->error;
    exit();
    }
 }
public function select_data($table,$id){
    $query="SELECT * FROM {$table} WHERE id=$id  ";
    }
    public function insert_data(){
        global $conn;
        $username=$_POST['username'];
        $password=$_POST['password'];
        $query="INSERT INTO artisan(username,password) VALUES('$username','$password')";

        $result=$conn->query($query);

        if($result->num_rows){
            return true;
        }
    }
    public function register(){
        if(isset($_POST['submit'])){
            self::insert_data();
        }
    }
}
$index=new Index();
$index->register();
?>

<form method="POST" action="index.php">
    <input type="text" name="username">

    <input type="password" name="password">

    <input type="submit" name="submit">

</form>

Error:

Fatal error: Uncaught Error: Call to a member function query() on null
  in C:\xampp\htdocs\webartisan\index.php:23 Stack trace: #0
  C:\xampp\htdocs\webartisan\index.php(31): Index->insert_data() #1
  C:\xampp\htdocs\webartisan\index.php(36): Index->register() #2 {main}
  thrown in C:\xampp\htdocs\webartisan\index.php on line 23

Body:
$conn variable is not accessible as global variable because you declare $conn as local variable inside connect() method.

To address this problem, you need to declare as class field and then you can access $conn as $this->conn inside any methods of class Index. This way you do not need global $conn.

For example:

<?php
class Index{
    private $conn;

    public function connect() {
        ...
        $this->conn = $mysqli->select_db("webartisan");
        ...
    }

    public function insert_data() {
        ...
        $result = $this->conn->query($query);
        ...
    }
}

Update:

select_db() returns boolean value, not connection object. Following line will cause Call to a member function query() on boolean error as you said in comment.

$this->conn = $mysqli->select_db("webartisan");

You should read mysqli documentation.


问:
How to use Matches() and Pattern correctley
I'm doing a assignment for school and need to build a Student class. The constructor will receive a String,"Student name". I need to verify that the given String from the user includes only letters from a-z, A-Z, and numbers 0-9.

From looking online this is what I found

```<code>boolean ans = true;
String str = ("Maor Rocky");
Pattern pattern = Pattern.compile("[A-Za-z0-9]\\w+");
Matcher matcher = pattern.matcher(str);
System.out.println(matcher.group());

if (!str.matches("[a-zA-Z0-9//s+]"))
    ans = false;

System.out.println(ans);
</code>```

I know it's missing something but I didn't grasp the idea of pattern and matcher yet.

答:
thanks every one, this is the code i wrote and it works:</p>

```<code>boolean ans = true;
    if (!name.matches("^[a-zA-Z0-9 ]+$")) {
        ans = false;
</code>```

Body:
I'm doing a assignment for school and need to build a Student class. The constructor will receive a String,"Student name". I need to verify that the given String from the user includes only letters from a-z, A-Z, and numbers 0-9.

From looking online this is what I found

boolean ans = true;
String str = ("Maor Rocky");
Pattern pattern = Pattern.compile("[A-Za-z0-9]\\w+");
Matcher matcher = pattern.matcher(str);
System.out.println(matcher.group());

if (!str.matches("[a-zA-Z0-9//s+]"))
    ans = false;

System.out.println(ans);

I know it's missing something but I didn't grasp the idea of pattern and matcher yet.

Body:
thanks every one, this is the code i wrote and it works:

boolean ans = true;
    if (!name.matches("^[a-zA-Z0-9 ]+$")) {
        ans = false;


问:
RegEx Parser written in Prolog
I've been banging my head against the wall on this homework problem for a few hours now.  We have to parse a regular expression with Prolog. For the most part, the predicates I have work, but there's a few regular expression and string combos which cause them to run out of stack space in SWI-Prolog.  Here's a sample with two of the Regex string combinations, one that works and one that doesn't:

```<code>star(star(char(a))), []
star(star(char(a))), [a]
</code>```

The first one works and the second one runs out of stack.

Here's the predicates I'm using:

```<code>re_match(epsilon, []).
re_match(char(Letter), [Letter]).
re_match(star(_), []).
re_match(seq(Rx1, Rx2), List) :- append(List1, List2, List),  re_match(Rx2, List2),  re_match(Rx1, List1).
re_match(alt(Rx1, Rx2), List) :- re_match(Rx1, List); re_match(Rx2, List).
re_match(star(Rx), List) :- append(List1, List2, List), re_match(Rx, List1), re_match(star(Rx), List2).
</code>```

I'm not sure what change I need to make to get it to work right, but I'm not sure what else to do.

Also, changing List :- append(List1, List2, List) to [H|T] does not evaluate to true for one of the examples.

答:
Consider using DCG notation for better readability and to more easily reason about termination properties:

```<code>:- op(100, xf, *).

rexp(eps)      --> [].
rexp([T])      --> [T].
rexp(_*)       --> [].
rexp(R*)       --> rexp(R), rexp(R*).
rexp(s(R1,R2)) --> rexp(R1), rexp(R2).
rexp((R1|R2))    --> ( rexp(R1) ; rexp(R2) ).
</code>```

Example using length/2 to generate increasingly longer lists to generate strings that are matched by the regexp:

```<code>?- length(Ls, _), phrase(rexp(s(([a]|[b]),[c]*)), Ls).
Ls = [a] ;
Ls = [b] ;
Ls = [a, c] ;
Ls = [b, c] ;
Ls = [a, c, c] ;
etc.
</code>```

Title: RegEx Parser written in Prolog

Body:
I've been banging my head against the wall on this homework problem for a few hours now.  We have to parse a regular expression with Prolog. For the most part, the predicates I have work, but there's a few regular expression and string combos which cause them to run out of stack space in SWI-Prolog.  Here's a sample with two of the Regex string combinations, one that works and one that doesn't:

star(star(char(a))), []
star(star(char(a))), [a]

The first one works and the second one runs out of stack.

Here's the predicates I'm using:

re_match(epsilon, []).
re_match(char(Letter), [Letter]).
re_match(star(_), []).
re_match(seq(Rx1, Rx2), List) :- append(List1, List2, List),  re_match(Rx2, List2),  re_match(Rx1, List1).
re_match(alt(Rx1, Rx2), List) :- re_match(Rx1, List); re_match(Rx2, List).
re_match(star(Rx), List) :- append(List1, List2, List), re_match(Rx, List1), re_match(star(Rx), List2).

I'm not sure what change I need to make to get it to work right, but I'm not sure what else to do.

Also, changing List :- append(List1, List2, List) to [H|T] does not evaluate to true for one of the examples.

Body:
Consider using DCG notation for better readability and to more easily reason about termination properties:

:- op(100, xf, *).

rexp(eps)      --> [].
rexp([T])      --> [T].
rexp(_*)       --> [].
rexp(R*)       --> rexp(R), rexp(R*).
rexp(s(R1,R2)) --> rexp(R1), rexp(R2).
rexp((R1|R2))    --> ( rexp(R1) ; rexp(R2) ).

Example using length/2 to generate increasingly longer lists to generate strings that are matched by the regexp:

?- length(Ls, _), phrase(rexp(s(([a]|[b]),[c]*)), Ls).
Ls = [a] ;
Ls = [b] ;
Ls = [a, c] ;
Ls = [b, c] ;
Ls = [a, c, c] ;
etc.


问:
Setting a VM's mac address in Vagrant
The documentation lists that the mac address of a VM can be set in the Vagrantfile, however everything I add seems to end up being a syntax error. Anyone successfully done this?</p>

答:
On Vagrant version 2.0.1, I write in the Vagrantfile for a private_network (provider = VirtualBox ; version 5.2.0) :</p>

```<code>config.vm.network "private_network", ip: "X.X.X.X", mac: "080027xxxxxx"
</code>```

Title: Setting a VM's mac address in Vagrant

Body:
On Vagrant version 2.0.1, I write in the Vagrantfile for a private_network (provider = VirtualBox ; version 5.2.0) :

config.vm.network "private_network", ip: "X.X.X.X", mac: "080027xxxxxx"


问:
Spring Boot 1.4.2.RELEASE with Eureka Server - Exception: org.springframework.beans.factory.NoSuchBeanDefinitionException
I am getting the following error while trying to run Spring Boot 1.4.2.RELEASE with Eureka server:

```<code>2016-11-20 16:25:59.306  INFO 14263 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2177849e: startup date [Sun Nov 20 16:25:59 CET 2016]; root of context hierarchy
2016-11-20 16:25:59.581  INFO 14263 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2016-11-20 16:25:59.606  INFO 14263 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'configurationPropertiesRebinderAutoConfiguration' of type [class org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$fc4b31a3] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.4.2.RELEASE)

2016-11-20 16:26:04.988  INFO 14263 --- [           main] i.v.p.s.EurekaServerApplication          : No active profile set, falling back to default profiles: default
2016-11-20 16:26:05.005  INFO 14263 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@3e14c16d: startup date [Sun Nov 20 16:26:05 CET 2016]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@2177849e
2016-11-20 16:26:05.589  WARN 14263 --- [           main] o.s.c.a.ConfigurationClassPostProcessor  : Cannot enhance @Configuration bean definition 'refreshScope' since its singleton instance has been created too early. The typical cause is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor return type: Consider declaring such methods as 'static'.
2016-11-20 16:26:05.774  INFO 14263 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=05587591-c1ba-31c3-b56f-8b79a2e1951f
2016-11-20 16:26:05.787  INFO 14263 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2016-11-20 16:26:05.857  INFO 14263 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [class org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$fc4b31a3] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-11-20 16:26:06.180  INFO 14263 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8761 (http)
2016-11-20 16:26:06.197  INFO 14263 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2016-11-20 16:26:06.198  INFO 14263 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.6
2016-11-20 16:26:06.326  INFO 14263 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2016-11-20 16:26:06.327  INFO 14263 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1322 ms
2016-11-20 16:26:06.347 ERROR 14263 --- [ost-startStop-1] o.s.b.c.embedded.tomcat.TomcatStarter    : Error starting Tomcat context. Exception: org.springframework.beans.factory.UnsatisfiedDependencyException. Message: Error creating bean with name 'org.springframework.cloud.netflix.eureka.server.EurekaServerConfiguration': Unsatisfied dependency expressed through field 'applicationInfoManager'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.netflix.appinfo.ApplicationInfoManager' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2016-11-20 16:26:06.375  WARN 14263 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.boot.context.embedded.EmbeddedServletContainerException: Unable to start embedded Tomcat
2016-11-20 16:26:06.483 ERROR 14263 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

Field applicationInfoManager in org.springframework.cloud.netflix.eureka.server.EurekaServerConfiguration required a bean of type 'com.netflix.appinfo.ApplicationInfoManager' that could not be found.

Action:

Consider defining a bean of type 'com.netflix.appinfo.ApplicationInfoManager' in your configuration.
</code>```

Here is the pom file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>my.test.springMicroservices</groupId>
    <artifactId>EurekaServer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>EurekaServer</name>
    <description>Eureka discovery server example</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
        <relativePath />
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Camden.SR2</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

The application.yml:

```<code>server:
  port: 8761
spring:
  application:
    name: eureka-server1
eureka:
  client:
    enabled: false
    fetch-registry: false
</code>```

My Spring boot application class:

```<code>import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}
</code>```

This is my environment:

MacOS Sierra 10.12.1

Spring Tool Suite - Version: 3.8.2.RELEASE (Build Id: 201610040743 - Platform: Eclipse Neon.1 (4.6.1))

Do I missed something?

Thanks in advance

答: Remove eureka.client.enabled=false from the configuration. Then it will start the server

Body:
I am getting the following error while trying to run Spring Boot 1.4.2.RELEASE with Eureka server:

2016-11-20 16:25:59.306  INFO 14263 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2177849e: startup date [Sun Nov 20 16:25:59 CET 2016]; root of context hierarchy
2016-11-20 16:25:59.581  INFO 14263 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2016-11-20 16:25:59.606  INFO 14263 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'configurationPropertiesRebinderAutoConfiguration' of type [class org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$fc4b31a3] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.4.2.RELEASE)

2016-11-20 16:26:04.988  INFO 14263 --- [           main] i.v.p.s.EurekaServerApplication          : No active profile set, falling back to default profiles: default
2016-11-20 16:26:05.005  INFO 14263 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@3e14c16d: startup date [Sun Nov 20 16:26:05 CET 2016]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@2177849e
2016-11-20 16:26:05.589  WARN 14263 --- [           main] o.s.c.a.ConfigurationClassPostProcessor  : Cannot enhance @Configuration bean definition 'refreshScope' since its singleton instance has been created too early. The typical cause is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor return type: Consider declaring such methods as 'static'.
2016-11-20 16:26:05.774  INFO 14263 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=05587591-c1ba-31c3-b56f-8b79a2e1951f
2016-11-20 16:26:05.787  INFO 14263 --- [           main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2016-11-20 16:26:05.857  INFO 14263 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [class org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$fc4b31a3] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-11-20 16:26:06.180  INFO 14263 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8761 (http)
2016-11-20 16:26:06.197  INFO 14263 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2016-11-20 16:26:06.198  INFO 14263 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.6
2016-11-20 16:26:06.326  INFO 14263 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2016-11-20 16:26:06.327  INFO 14263 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1322 ms
2016-11-20 16:26:06.347 ERROR 14263 --- [ost-startStop-1] o.s.b.c.embedded.tomcat.TomcatStarter    : Error starting Tomcat context. Exception: org.springframework.beans.factory.UnsatisfiedDependencyException. Message: Error creating bean with name 'org.springframework.cloud.netflix.eureka.server.EurekaServerConfiguration': Unsatisfied dependency expressed through field 'applicationInfoManager'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.netflix.appinfo.ApplicationInfoManager' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2016-11-20 16:26:06.375  WARN 14263 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.boot.context.embedded.EmbeddedServletContainerException: Unable to start embedded Tomcat
2016-11-20 16:26:06.483 ERROR 14263 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

Field applicationInfoManager in org.springframework.cloud.netflix.eureka.server.EurekaServerConfiguration required a bean of type 'com.netflix.appinfo.ApplicationInfoManager' that could not be found.

Action:

Consider defining a bean of type 'com.netflix.appinfo.ApplicationInfoManager' in your configuration.

Here is the pom file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>my.test.springMicroservices</groupId>
    <artifactId>EurekaServer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>EurekaServer</name>
    <description>Eureka discovery server example</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</version>
        <relativePath />
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Camden.SR2</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

The application.yml:

server:
  port: 8761
spring:
  application:
    name: eureka-server1
eureka:
  client:
    enabled: false
    fetch-registry: false

My Spring boot application class:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}

This is my environment:

MacOS Sierra 10.12.1

Spring Tool Suite - Version: 3.8.2.RELEASE (Build Id: 201610040743 - Platform: Eclipse Neon.1 (4.6.1))

Do I missed something?

Thanks in advance


问:
how to use connect by method dynamically
How to achieve the following

I've got a query:

```<code>select sr.source_rel_id,
       sr.source_rel_start,
       sr.source_rel_end,
       sr.source_rel_end-sr.source_rel_start+ 1 as daycount
 from (SELECT RELEASES.REL_ID as source_rel_id,
              RELEASES.REL_START_DATE as source_rel_start,
              RELEASES.REL_END_DATE as source_rel_end
         FROM RELEASES) sr
</code>```

which delivers this result:

I'm trying to create an additionally coloumn (based on the attached screenshot) filled with incrementally rising dates between the given start and end interval.

Here's what I want to accomplish:

The number on the right side shows how many records should be generated for each IDs.

Sorry for my poor english, I hope it's understandable.

答:
If you're still on Oracle 11g (suggested in a comment), you can do this with a connect by hierarchical query, but because you're getting the data from multiple source rows you need include a reference to a non-deterministic function (I've used `dbms_random.value but others are available...) to prevent that:

```<code>select rel_id as source_rel_id,
  rel_start_date + level - 1 as days,
  rel_end_date - rel_start_date + 1 as daycount
from releases
connect by rel_id  = prior rel_id
and prior dbms_random.value is not null
and level <= rel_end_date - rel_start_date + 1;
</code>```

which gets, using just the first three rows of your sample data, 92 rows in the result set:

```<code>SOURCE_REL_ID DAYS         DAYCOUNT
------------- ---------- ----------
           68 2016-03-01         31
           68 2016-03-02         31
           68 2016-03-03         31
...
           68 2016-03-30         31
           68 2016-03-31         31
           71 2016-06-01         30
           71 2016-06-02         30
...
           71 2016-06-29         30
           71 2016-06-30         30
           73 2016-08-01         31
           73 2016-08-02         31
...
           73 2016-08-30         31
           73 2016-08-31         31
</code>```

If you're on 11gR2 (or higher) you can also do this with recursive subquery factoring a.k.a a recursive CTE:

```<code>with rcte (source_rel_id, rel_end_date, days, daycount) as (
  select rel_id, rel_end_date, rel_start_date, rel_end_date - rel_start_date + 1
  from releases
  union all
  select source_rel_id, rel_end_date, days + 1, daycount
  from rcte
  where days < rel_end_date
)
select source_rel_id, days, daycount
from rcte
order by source_rel_id, days;
</code>```

which gets the same result - other than being ordered explicitly, which probably isn't a bad thing.

The anchor branch of the CTE gets data from your base table and adds two extra columns: daycount which is calculated as before, and days which is the same as the start date for this first set of rows. The rel_end_date needs to be available to the recursive branch so that is included, but rel_start_date can be skipped.

The recursive branch then adds one day to days until it reaches the end date. If the days value from the previous generated row is already rel_end_date then the condition is not met so it stops, for that source row.

Finally you query only the columns you want to see from the CTE - in this case, just excluding the rel_end_date that was passed through to provide the stop condition, but which you don't actually want to see.

Body:
How to achieve the following

I've got a query:

select sr.source_rel_id,
       sr.source_rel_start,
       sr.source_rel_end,
       sr.source_rel_end-sr.source_rel_start+ 1 as daycount
 from (SELECT RELEASES.REL_ID as source_rel_id,
              RELEASES.REL_START_DATE as source_rel_start,
              RELEASES.REL_END_DATE as source_rel_end
         FROM RELEASES) sr

which delivers this result:

I'm trying to create an additionally coloumn (based on the attached screenshot) filled with incrementally rising dates between the given start and end interval.

Here's what I want to accomplish:

The number on the right side shows how many records should be generated for each IDs.

Sorry for my poor english, I hope it's understandable.

Body:
If you're still on Oracle 11g (suggested in a comment), you can do this with a connect by hierarchical query, but because you're getting the data from multiple source rows you need include a reference to a non-deterministic function (I've used `dbms_random.value but others are available...) to prevent that:

select rel_id as source_rel_id,
  rel_start_date + level - 1 as days,
  rel_end_date - rel_start_date + 1 as daycount
from releases
connect by rel_id  = prior rel_id
and prior dbms_random.value is not null
and level <= rel_end_date - rel_start_date + 1;

which gets, using just the first three rows of your sample data, 92 rows in the result set:

SOURCE_REL_ID DAYS         DAYCOUNT
------------- ---------- ----------
           68 2016-03-01         31
           68 2016-03-02         31
           68 2016-03-03         31
...
           68 2016-03-30         31
           68 2016-03-31         31
           71 2016-06-01         30
           71 2016-06-02         30
...
           71 2016-06-29         30
           71 2016-06-30         30
           73 2016-08-01         31
           73 2016-08-02         31
...
           73 2016-08-30         31
           73 2016-08-31         31

If you're on 11gR2 (or higher) you can also do this with recursive subquery factoring a.k.a a recursive CTE:

with rcte (source_rel_id, rel_end_date, days, daycount) as (
  select rel_id, rel_end_date, rel_start_date, rel_end_date - rel_start_date + 1
  from releases
  union all
  select source_rel_id, rel_end_date, days + 1, daycount
  from rcte
  where days < rel_end_date
)
select source_rel_id, days, daycount
from rcte
order by source_rel_id, days;

which gets the same result - other than being ordered explicitly, which probably isn't a bad thing.

The anchor branch of the CTE gets data from your base table and adds two extra columns: daycount which is calculated as before, and days which is the same as the start date for this first set of rows. The rel_end_date needs to be available to the recursive branch so that is included, but rel_start_date can be skipped.

The recursive branch then adds one day to days until it reaches the end date. If the days value from the previous generated row is already rel_end_date then the condition is not met so it stops, for that source row.

Finally you query only the columns you want to see from the CTE - in this case, just excluding the rel_end_date that was passed through to provide the stop condition, but which you don't actually want to see.


问:
Kendo UI flip effect in Internet Explorer shows back too soon
I'm developing a BI dashboard for a business app using the JavaScript Kendo UI version v2014.1.416, but I'm having a problem with some visuals in IE11.

I want to point out that due to real-world constraints, running IE11 is for all intents and purposes set in stone. The Kendo version number is somewhat easier to deal with, but still no picnic.

Specifically, I use the kendo.fx.flip() function to display a flip card. The card flips ok, but the "back of the card" is rendered before the flip animation starts. In contrast, the same effect in Chrome and Firefox plays out as it should, i.e., the back is shown halfway(-ish) through the animation.

I had a look at the API reference page for the flip effect, at http://docs.telerik.com/kendo-ui/api/javascript/effects/flip. As it turns out, the reference page example exhibits the same behavior in IE11.

I'm guessing the effect uses the CSS3 flip function under the hood (haven't looked yet though) and this seems to be somewhat of a general problem given the amount of questions regarding flip in IE.

My question is twofold:

1) Is there a way to "fix" the animation specifically for IE, using the provided version of Kendo and/or using regular CSS?

2) Is this effect fixed for IE in later Kendo versions, in spite of the behavior on the API reference page?

答: I could only get this to look nice by setting a large no-repeat fixed background image on both 'sides' (made out of a simple white png).</p>


问:
find the min of the second index, then find the max of the third index of a list Python
I have a nested list like this:

```<code>a = [[1, 3, 3],
   [7, 2, 6],
   [4, 2, 8]]
</code>```

I want to transpose it and find the min of the second index, followed by the max of the third index, such that the resulting list I get is [4,2,8].

I have the following: min(a, key=lambda x: x[1]) which helps me find the min of the second index, which is 2 but Python would pick [7, 2, 6]. I'd like Python to conditionally look for the max of the third index and then return the list.

Logic:

Find the min of the 2nd index from each nested list

Then find the max of the 3rd index from each nested list

Return the actual nested list from a that satisfies both 1,2

答:
It is kind of workaround solution, but code like:

```<code>min(a, key=lambda x: (x[1], -x[2]))
</code>```

Which finds minimal tuple consisting of second index and negated value of the third index (ergo: the biggest value from third index), returns results as you want it to:

```<code>>>> min(a, key=lambda x: (x[1], -x[2]))
`[4, 2, 8]`
</code>```

Body:
I have a nested list like this:

a = [[1, 3, 3],
   [7, 2, 6],
   [4, 2, 8]]

I want to transpose it and find the min of the second index, followed by the max of the third index, such that the resulting list I get is [4,2,8].

I have the following: min(a, key=lambda x: x[1]) which helps me find the min of the second index, which is 2 but Python would pick [7, 2, 6]. I'd like Python to conditionally look for the max of the third index and then return the list.

Logic:

Find the min of the 2nd index from each nested list

Then find the max of the 3rd index from each nested list

Return the actual nested list from a that satisfies both 1,2

Body:
It is kind of workaround solution, but code like:

min(a, key=lambda x: (x[1], -x[2]))

Which finds minimal tuple consisting of second index and negated value of the third index (ergo: the biggest value from third index), returns results as you want it to:

>>> min(a, key=lambda x: (x[1], -x[2]))
`[4, 2, 8]`


问:
UIAlertcontroller in TextfieldShouldBeginediting objective-c
I want to show alert before text enter in textfield after ok button click textfield will be editable but I am showing alert but textfield did not editable.

```<code>if(textField == contractValueField)
{
    [self showAlertWithTitle:@"Information" textfield:contractValueField];
    return YES;
}
</code>```

I search so many sites but I did not get right answer by using UIAlertView it is working but I want to use UIAlertController. I have more than 20 textfields in my project & every textfield I will show alert before edit begin.

```<code>- (void)showAlertWithTitle:(NSString *)title textfield:(UITextField*)textfield
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:@"Please enter Amount in Lakhs" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
    {
        [alert dismissViewControllerAnimated:YES completion:nil];
        [textfield becomeFirstResponder];
    }];

    [alert addAction:ok];
    [self.navigationController presentViewController:alert animated:YES completion:nil];
}
</code>```

答:
The reason is that when you call [textfield becomeFirstResponder], -(BOOL)textFieldShouldBeginEditing:(UITextField *)textField is also called again, which in turn shows your alertView, and when the ok button is selected from your alert, the alert view is shown again, and you are stuck in a loop. Here is a quick way to fix it:

```<code>-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    // check to see if the alert has already been shown, if it has the tag value will be 1
    if (textField == contractValueField && textField.tag != 1) {
        [self showAlertWithTitle:@"Information" textfield:textField];
        return false;
    }
    return true;
}
</code>```

The code for your alertView should be as follows:

```<code>- (void)showAlertWithTitle:(NSString *)title textfield:(UITextField*)textfield{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:@"Please enter Amount in Lakhs" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){
        textfield.tag = 1;
        [alert dismissViewControllerAnimated:YES completion:nil];
        [textfield becomeFirstResponder];
    }];

    [alert addAction:ok];
    [self presentViewController:alert animated:true completion:nil];
}
</code>```

Return the tag value of textField back to 0 when editing is finished:

```<code>-(BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    textField.tag = 0;
    return true;
}
</code>```

Body:
I want to show alert before text enter in textfield after ok button click textfield will be editable but I am showing alert but textfield did not editable.

if(textField == contractValueField)
{
    [self showAlertWithTitle:@"Information" textfield:contractValueField];
    return YES;
}

I search so many sites but I did not get right answer by using UIAlertView it is working but I want to use UIAlertController. I have more than 20 textfields in my project & every textfield I will show alert before edit begin.

- (void)showAlertWithTitle:(NSString *)title textfield:(UITextField*)textfield
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:@"Please enter Amount in Lakhs" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
    {
        [alert dismissViewControllerAnimated:YES completion:nil];
        [textfield becomeFirstResponder];
    }];

    [alert addAction:ok];
    [self.navigationController presentViewController:alert animated:YES completion:nil];
}

Body:
The reason is that when you call [textfield becomeFirstResponder], -(BOOL)textFieldShouldBeginEditing:(UITextField *)textField is also called again, which in turn shows your alertView, and when the ok button is selected from your alert, the alert view is shown again, and you are stuck in a loop. Here is a quick way to fix it:

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    // check to see if the alert has already been shown, if it has the tag value will be 1
    if (textField == contractValueField && textField.tag != 1) {
        [self showAlertWithTitle:@"Information" textfield:textField];
        return false;
    }
    return true;
}

The code for your alertView should be as follows:

- (void)showAlertWithTitle:(NSString *)title textfield:(UITextField*)textfield{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:@"Please enter Amount in Lakhs" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action){
        textfield.tag = 1;
        [alert dismissViewControllerAnimated:YES completion:nil];
        [textfield becomeFirstResponder];
    }];

    [alert addAction:ok];
    [self presentViewController:alert animated:true completion:nil];
}

Return the tag value of textField back to 0 when editing is finished:

-(BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    textField.tag = 0;
    return true;
}


问:
Play video file with VLC, then quit VLC
I am working on a simple Python script that is supposed to do something, then play a video file, and then do some more stuff.

I am forced to do this on a Windows XP machine with Python 3.2.3 and VLC to play my video file.

I am currently using this code...

```<code>vlc_path = '\\path\\to\\vlc.exe'
video_path = '\\path\\to\\video\\file'
subprocess.call([vlc_path, video_path])
</code>```

... to open VLC and play the video. It works nicely. However, the script waits for VLC to quit before it goes on. Which is good and I want to keep it that way.

My question is: Is there a way to quit VLC right after the video file has been played?

Thanks a lot for any help!

答: If nothing works try using the option --ignore-config at the beginning after vlc in addition to http://quit at the end

Title: Play video file with VLC, then quit VLC

Body:
I am working on a simple Python script that is supposed to do something, then play a video file, and then do some more stuff.

I am forced to do this on a Windows XP machine with Python 3.2.3 and VLC to play my video file.

I am currently using this code...

vlc_path = '\\path\\to\\vlc.exe'
video_path = '\\path\\to\\video\\file'
subprocess.call([vlc_path, video_path])

... to open VLC and play the video. It works nicely. However, the script waits for VLC to quit before it goes on. Which is good and I want to keep it that way.

My question is: Is there a way to quit VLC right after the video file has been played?

Thanks a lot for any help!


问:
Extracting POST data with Express
I've read node.js Extracting POST data.

But here's my problem, how to extract POST data with Express when I received a HTTP request looking like this?

```<code>POST /messages HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Content-Length: 9
User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5
Content-Type: application/xml
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: zh-TW,zh;q=0.8,en-US;q=0.6,en;q=0.4 Accept-Charset: UTF-8,*;q=0.5

msg=hello
</code>```

I can't seem to get the msg=hello key-value pair out of the body with Express.

I've tried all of these methods req.header() req.param() req.query() req.body but they seem to be empty.

How to get the body's content?

```<code>app.post('/messages', function (req, res) {
    req.??
});
</code>```

答:
You are posting xml as I can see, the answers you got were based on JSON input. If you want the content of your xml displayed, process the raw request :

```<code>app.post('/processXml',function (req, res)
{
    var thebody = '';
    req.on('data' , function(chunk)
    {
        thebody += chunk;
    }).on('end', function()
    {
        console.log("body:", thebody);
    });
});
</code>```

As an example using curl as your postman:

```<code>curl -d '<myxml prop1="white" prop2="red">this is great</myxml>' -H
"Content-type: application/xml" -X POST
http://localhost:3000/processXml
</code>```

Outputting:

```<code>'<myxml prop1="white" prop2="red">this is great</myxml>'
</code>```

Make sure your body-parser middleware doesn't get in the way: body-parser-xml processes your request object on the fly to a json object, after which you cannot process your raw request anymore. (And you can guess who was stuck several hours after this...)

Title: Extracting POST data with Express

Body:
I've read node.js Extracting POST data.

But here's my problem, how to extract POST data with Express when I received a HTTP request looking like this?

POST /messages HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Content-Length: 9
User-Agent: Mozilla/5.0 (X11; Linux i686) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5
Content-Type: application/xml
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: zh-TW,zh;q=0.8,en-US;q=0.6,en;q=0.4 Accept-Charset: UTF-8,*;q=0.5

msg=hello

I can't seem to get the msg=hello key-value pair out of the body with Express.

I've tried all of these methods req.header() req.param() req.query() req.body but they seem to be empty.

How to get the body's content?

app.post('/messages', function (req, res) {
    req.??
});

Body:
You are posting xml as I can see, the answers you got were based on JSON input. If you want the content of your xml displayed, process the raw request :

app.post('/processXml',function (req, res)
{
    var thebody = '';
    req.on('data' , function(chunk)
    {
        thebody += chunk;
    }).on('end', function()
    {
        console.log("body:", thebody);
    });
});

As an example using curl as your postman:

curl -d '<myxml prop1="white" prop2="red">this is great</myxml>' -H
"Content-type: application/xml" -X POST
http://localhost:3000/processXml

Outputting:

'<myxml prop1="white" prop2="red">this is great</myxml>'

Make sure your body-parser middleware doesn't get in the way: body-parser-xml processes your request object on the fly to a json object, after which you cannot process your raw request anymore. (And you can guess who was stuck several hours after this...)