问:
How to change my WCF service to RESTful service in VS2017?
I'm using Visual Studio 2017 and I have write a small WCF Service Application (Visual C#).

Now I'm trying to make it RESTful so that I can access the member function in my web browser.

This is my IService1.cs file:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService {
    [ServiceContract]
    public interface IService1 {

        [OperationContract]
        [WebGet(UriTemplate="/getdata",RequestFormat =WebMessageFormat.Xml,ResponseFormat =WebMessageFormat.Xml,BodyStyle =WebMessageBodyStyle.Bare)]
        //[WebGet]
        string GetData();
    }

}
</code>```

And this is my Web.config file:

```<code><?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>
</code>```

After pressing F5, I visited http://localhost:52110/Service1.svc/getdata in Edge, but what I got is http 400.

So, how can I make my service accessible via http request?

Thanks in advance.

答:
You might want to check binding information in your config as per below:

```<code><system.serviceModel>
   <services>
        <service name="WcfService.Service1" behaviorConfiguration="serviceBehavior">
                <endpoint address=""
                          binding="webHttpBinding"
                          contract="WcfService.IService1"
                          behaviorConfiguration="web"></endpoint>
          </service>
   </services>
   <behaviors>
          <serviceBehaviors>
              <behavior name="serviceBehavior">
                  <serviceMetadata httpGetEnabled="true"/>
                       <serviceDebug includeExceptionDetailInFaults="false"/>
            </behavior>
          </serviceBehaviors>
          <endpointBehaviors>
              <behavior name="web">
                    <webHttp/>
               </behavior>
          </endpointBehaviors>
  </behaviors>
   <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
</code>```

You can also do the above programmatically.

Body:
I'm using Visual Studio 2017 and I have write a small WCF Service Application (Visual C#).

Now I'm trying to make it RESTful so that I can access the member function in my web browser.

This is my IService1.cs file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService {
    [ServiceContract]
    public interface IService1 {

        [OperationContract]
        [WebGet(UriTemplate="/getdata",RequestFormat =WebMessageFormat.Xml,ResponseFormat =WebMessageFormat.Xml,BodyStyle =WebMessageBodyStyle.Bare)]
        //[WebGet]
        string GetData();
    }

}

And this is my Web.config file:

<?xml version="1.0"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>

          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>

          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>

    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

After pressing F5, I visited http://localhost:52110/Service1.svc/getdata in Edge, but what I got is http 400.

So, how can I make my service accessible via http request?

Thanks in advance.

Body:
You might want to check binding information in your config as per below:

<system.serviceModel>
   <services>
        <service name="WcfService.Service1" behaviorConfiguration="serviceBehavior">
                <endpoint address=""
                          binding="webHttpBinding"
                          contract="WcfService.IService1"
                          behaviorConfiguration="web"></endpoint>
          </service>
   </services>
   <behaviors>
          <serviceBehaviors>
              <behavior name="serviceBehavior">
                  <serviceMetadata httpGetEnabled="true"/>
                       <serviceDebug includeExceptionDetailInFaults="false"/>
            </behavior>
          </serviceBehaviors>
          <endpointBehaviors>
              <behavior name="web">
                    <webHttp/>
               </behavior>
          </endpointBehaviors>
  </behaviors>
   <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>

You can also do the above programmatically.


来源: stackexchange

问:
Why do we need to use `int main` and not `void main` in C++?
Why do we need to use int main and not void main in C++?

答:
The short answer, is because the C++ standard requires main() to return int.

As you probably know, the return value from the main() function is used by the runtime library as the exit code for the process. Both Unix and Win32 support the concept of a (small) integer returned from a process after it has finished. Returning a value from main() provides one way for the programmer to specify this value.

OwnerDisplayName: kasperasky

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: Greg Hewgill


问:
Exiting an infinite process in python subprocess
i have the following code

```<code>c = open("text.txt", 'a')

output = subprocess.Popen('ping -t 127.0.0.1', stdout=subprocess.PIPE).communicate()[0]

c.write(str(output))
</code>```

But as the ping is infinite , the code stucks at line two till i close the cmd

how can i close the infinite subprocess

i use python 2

答:
Alternatively you can use check_output and add a timeout:

```<code>from subprocess import check_output

output = check_output('ping -t 127.0.0.1', timeout=seconds)
</code>```

Body:
i have the following code

c = open("text.txt", 'a')

output = subprocess.Popen('ping -t 127.0.0.1', stdout=subprocess.PIPE).communicate()[0]

c.write(str(output))

But as the ping is infinite , the code stucks at line two till i close the cmd

how can i close the infinite subprocess

i use python 2

Body:
Alternatively you can use check_output and add a timeout:

from subprocess import check_output

output = check_output('ping -t 127.0.0.1', timeout=seconds)


问:
Statistical regression on multi-dimensional data
I have a set of data in (x, y, z) format where z is the output of some formula involving x and y. I want to find out what the formula is, and my Internet research suggests that statistical regression is the way to do this.

However, all of the examples I have found while researching only deal with two-dimensional data sets (x, y) which is not useful for my situation. Said examples also don't seem to provide a way to see what the resulting formula is, they just provide a function for predicting future outputs based on data not in a training data set.

The level of precision needed is that the formula for z needs to produce results within +/- 0.5 of actual values.

Can anyone tell me how I can do what I want to do? Please note I was not asking for specific recommendations on a software library to use.

答: If you can reuse code from an existing a Python 3 tkinter GUI application on GitHub, take a look at fitting the linear polynomial surface equation that you mentioned using my tkInterFit project - it will also create fitted surface and contour plots. The GitHub source code is at https://github.com/zunzun/tkInterFit with a BSD license.</p>


问:
Most efficient way to find the last digit of a^b
I am a python newbie. I am looking to compute (a ** b) % 10 in the most efficient way possible (i.e. simplifying the power part). I have found one way to do this: ((a % 10) ** b) % 10. My question is, are there more efficient ways to do this? This problem is an extension of a CodeFights task. The original problem accepted (a ** b) % 10.

答:
step 1: Take the inputs a and b as character string

step 2:

convert only the last character of a into integer and store in a variable say m.

convert only the last two character of b into integer and store in a variable say n.
If b is a single character, then convert this character only.

step 3: find x.   if n % 4 == 0:
                  x = 4
              else:
                  x = n % 4

step 4: last_digit = (m ** x) % 10

Short Explanation:
If you list out the initial expansions of a power, you will find a pattern.
So we can reduce a and b to m and x respectively.
Because it is just about the last digit.

you can visit: this site for the better explanation to find out last digit of a^b


问:
shared_ptr<> to an array custom deleter (with make_shared)
Is it possible to use make_shared and a custom deleter for an array that a shared_ptr<> points to (below is the way I tried doing it via the constructor, but I have no idea how that would work via using make_shared)?

```<code>int n = 5;
shared_ptr<int> a(new int[n], default_delete<int[]>());
</code>```

What I would like to make it look like is something similar to this, but with allocating memory for an int array and also having a custom deleter. Is that possible?

```<code>int n = 5;
shared_ptr<int> a;
a = make_shared<int>();
</code>```

答:
Unfortunately there is no way to specify a custom deleter as of right now with std::make_shared, you could however, make a wrapper around make_shared if you want

(a little less efficient, but ¯\_(ツ)_/¯)

```<code>template <typename Type, typename Deleter, typename... Args>
auto make_shared_deleter(Deleter&& deleter, Args&&... args) {
    auto u_ptr = std::make_unique<Type>(std::forward<Args>(args)...);
    auto with_deleter = std::shared_ptr<Type>{
        u_ptr.release(), std::forward<Deleter>(deleter)};
    return with_deleter;
}
</code>```

And then use it like so

```<code>int main() {
    auto ptr = make_shared_deleter<int>(std::default_delete<int>(), 1);
    cout << *ptr << endl;
}
</code>```

If you just want to use a shared_ptr and have it point to an array, see shared_ptr to an array : should it be used? for more

Body:
Is it possible to use make_shared and a custom deleter for an array that a shared_ptr<> points to (below is the way I tried doing it via the constructor, but I have no idea how that would work via using make_shared)?

int n = 5;
shared_ptr<int> a(new int[n], default_delete<int[]>());

What I would like to make it look like is something similar to this, but with allocating memory for an int array and also having a custom deleter. Is that possible?

int n = 5;
shared_ptr<int> a;
a = make_shared<int>();

Body:
Unfortunately there is no way to specify a custom deleter as of right now with std::make_shared, you could however, make a wrapper around make_shared if you want

(a little less efficient, but ¯\_(ツ)_/¯)

template <typename Type, typename Deleter, typename... Args>
auto make_shared_deleter(Deleter&& deleter, Args&&... args) {
    auto u_ptr = std::make_unique<Type>(std::forward<Args>(args)...);
    auto with_deleter = std::shared_ptr<Type>{
        u_ptr.release(), std::forward<Deleter>(deleter)};
    return with_deleter;
}

And then use it like so

int main() {
    auto ptr = make_shared_deleter<int>(std::default_delete<int>(), 1);
    cout << *ptr << endl;
}

If you just want to use a shared_ptr and have it point to an array, see shared_ptr to an array : should it be used? for more


问:
Dozer: Hibernate PersistentMap is not mapped to java.util.HashMap
I have a Hibernate annotated entity with a field:

```<code>@OneToMany(mappedBy="templateInstance", fetch = FetchType.EAGER)
@MapKey(name = "attributeName")
private Map<String, Component> components;
</code>```

Hibernate makes a PersistentMap out of this.
Then I want Dozer to map this to an object with such a field:

```<code>private Map<String, ComponentDto> components;
</code>```

After having LazyInitializationExceptions and some debugging, I found out, that it´s not a problem of a closed Hibernate session, but that Dozer tries not to map to a HashMap but to a PersistentMap! And therefore when Dozer accesses the target map the PersistentMap throws the Exception, because it has no session of course.

So, I thought that the intented behaviour of Dozer is to map to a HashMap. Now the question: am I doing something wrong or Dozer and how can I get Dozer to map the PersistentMap to normal Java standard map?

I had no problems when using a List before. Has anybody else used Dozer for mapping Hibernate PersistentMap?

Regards,
Konsumierer

答:
I found the solution by myself. The components field in the DTO has to look like this:

```<code>HashMap<String, Component> components = new HashMap<String, Component>;
</code>```

Only this way you can prevent Dozer from using the PersistentMap as the target object.

And the other important thing is to use a custom BeanMappingBuilder for the DO that holds the map and that looks like that:

```<code>public class TemplateInstanceMappingBuilder extends BeanMappingBuilder {

    @Override
    protected void configure() {

        mapping(TemplateInstance.class, TemplateInstanceDto.class)
            .fields("components", "components", FieldsMappingOptions.hintB(ComponentDto.class));

    }
}
</code>```

For further information about that problem, see the Dozer forums at https://sourceforge.net/projects/dozer/forums/forum/452530/topic/4020856/index/page/1

ContentLicense: CC BY-SA 2.5

Body:
I have a Hibernate annotated entity with a field:

@OneToMany(mappedBy="templateInstance", fetch = FetchType.EAGER)
@MapKey(name = "attributeName")
private Map<String, Component> components;

Hibernate makes a PersistentMap out of this.
Then I want Dozer to map this to an object with such a field:

private Map<String, ComponentDto> components;

After having LazyInitializationExceptions and some debugging, I found out, that it´s not a problem of a closed Hibernate session, but that Dozer tries not to map to a HashMap but to a PersistentMap! And therefore when Dozer accesses the target map the PersistentMap throws the Exception, because it has no session of course.

So, I thought that the intented behaviour of Dozer is to map to a HashMap. Now the question: am I doing something wrong or Dozer and how can I get Dozer to map the PersistentMap to normal Java standard map?

I had no problems when using a List before. Has anybody else used Dozer for mapping Hibernate PersistentMap?

Regards,
Konsumierer

Body:
I found the solution by myself. The components field in the DTO has to look like this:

HashMap<String, Component> components = new HashMap<String, Component>;

Only this way you can prevent Dozer from using the PersistentMap as the target object.

And the other important thing is to use a custom BeanMappingBuilder for the DO that holds the map and that looks like that:

public class TemplateInstanceMappingBuilder extends BeanMappingBuilder {

    @Override
    protected void configure() {

        mapping(TemplateInstance.class, TemplateInstanceDto.class)
            .fields("components", "components", FieldsMappingOptions.hintB(ComponentDto.class));

    }
}

For further information about that problem, see the Dozer forums at https://sourceforge.net/projects/dozer/forums/forum/452530/topic/4020856/index/page/1


问:
Image priority Java
I'm putting images on my JFrame using ImageIcon and then, to display the images:

```<code>getContentPane().add(label[3]);
getContentPane().add(label[2]);
getContentPane().add(label[1]);
</code>```

Now Image 3 will have priority over 2 and 2 over 1 etc
Is there anyway to set the priority or reverse it so the last image I put on screen will have priority over the other images?

答:
Your question is not clear at all, if you want to put the images along a third dimension axis, you should take a look at this layered panes tutorial.
From the official documentation:

A layered pane is a Swing container that provides a third dimension
  for positioning components: depth, also known as Z order. When adding
  a component to a layered pane, you specify its depth as an integer.
  The higher the number, closer the component is to the "top" position
  within the container. If components overlap, the "closer" components
  are drawn on top of components at a lower depth. The relationship
  between components at the same depth is determined by their positions
  within the depth.

As shown in this image, you should be able to position your components on the top of the others.

If this does not meet your requirement, please edit your question to be more specific.

Title: Image priority Java

Body:
I'm putting images on my JFrame using ImageIcon and then, to display the images:

getContentPane().add(label[3]);
getContentPane().add(label[2]);
getContentPane().add(label[1]);

Now Image 3 will have priority over 2 and 2 over 1 etc
Is there anyway to set the priority or reverse it so the last image I put on screen will have priority over the other images?


问:
Forecasting with LSTM
I have the following question, I have already created a forecasting model but it doesn't really predict the future, I just have a bunch of data, I split it into a "training" sample and into a "testing" sample and then I can check how good is my prediction. But now I want to forecast for the next 10 days that are not in the data I have. How on earth can I do it?

Example : Let's say I have the data for these days:

04-07-2017: 213

05-07-2017: 321

06-07-2017: 111

07-07-2017: 90

08-07-2017: 78

Now I want to forecast the data for the next 3 days. How can I do it?

答: I would assume you could use encoder/decoder. Something similar to seq2seq as in NLU.</p>

Title: Forecasting with LSTM


问:
React-router v4 route on click Button
I am try to implement a login page in React. I have a login component with 2 input fields (id and password) and a submit button. This button is Material-Ui button component. The button has an onClick method, that check if the id and password are correct. If so, it must route to another component.

```<code>class Connexion extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        identifiant: '',
        password: '',
        errorMessage: ''
    };

    this.checkIdentifiantAndPassaword = this.checkIdentifiantAndPassword.bind(this);
    this.handleIdentifiantChange = this.handleIdentifiantChange.bind(this);
    this.handlePasswordChange = this.handlePasswordChange.bind(this);
}
handleIdentifiantChange(e) {
    this.setState({
        identifiant: e.target.value
    });
}

handlePasswordChange(e) {
    this.setState({
        password: e.target.value
    });
}
checkIdentifiantAndPassword(e) {
    let { identifiant, password } = this.state;
    if (!identifiant) {
        console.log('check identifiant');
        this.setState({
            errorMessage: 'Identifiant vide ou incorrect.'
        });
        return;
    }
    if (!password) {
        this.setState({
            errorMessage: 'Mot de passe vide ou incorrect.'
        });
        return;
    }
    console.log(this.props);
    this.props.onLogin(true);
    console.log('Succés');
}
render() {
    let { errorMessage } = this.state;
    return (
        <Paper elevation={4} >
            <Typography type="display2" className="text-center header_title">Connexion</Typography>
            <div className="row content_container">
                <div className="small-4 small-centered columns">
                    <Typography type="body2" className="loginError">{errorMessage}</Typography>
                    <form>
                        <TextField required value={this.state.identifiant} onChange={this.handleIdentifiantChange} label="Identifiant" type="text" className="txtField" marginForm />
                        <TextField required value={this.state.password} onChange={this.handlePasswordChange} label="Mot de passe" type="password" className="txtField" marginForm />
                        <Button raised color="primary" className=" btn" onClick={this.checkIdentifiantAndPassword}>Se connecter</Button>
                    </form>
                </div>
            </div>
        </Paper>
    );
}
</code>```

};

My problem is, i don't know how to redirect to another component via the onClick handler. I tried many solutions like wrapping the Button component in a NavLink as below:

```<code><NavLink to="/new" ><Button raised color="primary" className=" btn" onClick={this.checkIdentifiantAndPassword}>Se connecter</Button></NavLink>
</code>```

but i get an error at the first line of the checkIdentifiantAndPassword method:

```<code>Cannot read property 'state' of null
</code>```

I know that i can remove the Button component and use only NavLink and add all the classes of Button component to the NavLink, but i don't like this workaround.

Do somebody have an idea of how i can achieve this. I am using React-router v4.
Thank you.

答:
You can use <Redirect/> from 'react-router-dom'.

In the documentation they explain how to use (plus Private Route). See https://reacttraining.com/react-router/web/example/auth-workflow.

I think maybe you can do sth like this:

```<code>this.state = {
  ....,
  doRedirect: false
}

.....

checkIdentifiantAndPassword(e) {
  .....
  this.setState({
    doRedirect: true
  });
}

.....

render() {
  if (this.state.doRedirect) {
    <Redirect to={/*Your next route*/}/>
  }
  .....
}
</code>```

Title: React-router v4 route on click Button

Body:
I am try to implement a login page in React. I have a login component with 2 input fields (id and password) and a submit button. This button is Material-Ui button component. The button has an onClick method, that check if the id and password are correct. If so, it must route to another component.

class Connexion extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        identifiant: '',
        password: '',
        errorMessage: ''
    };

    this.checkIdentifiantAndPassaword = this.checkIdentifiantAndPassword.bind(this);
    this.handleIdentifiantChange = this.handleIdentifiantChange.bind(this);
    this.handlePasswordChange = this.handlePasswordChange.bind(this);
}
handleIdentifiantChange(e) {
    this.setState({
        identifiant: e.target.value
    });
}

handlePasswordChange(e) {
    this.setState({
        password: e.target.value
    });
}
checkIdentifiantAndPassword(e) {
    let { identifiant, password } = this.state;
    if (!identifiant) {
        console.log('check identifiant');
        this.setState({
            errorMessage: 'Identifiant vide ou incorrect.'
        });
        return;
    }
    if (!password) {
        this.setState({
            errorMessage: 'Mot de passe vide ou incorrect.'
        });
        return;
    }
    console.log(this.props);
    this.props.onLogin(true);
    console.log('Succés');
}
render() {
    let { errorMessage } = this.state;
    return (
        <Paper elevation={4} >
            <Typography type="display2" className="text-center header_title">Connexion</Typography>

                    <Typography type="body2" className="loginError">{errorMessage}</Typography>
                    <form>
                        <TextField required value={this.state.identifiant} onChange={this.handleIdentifiantChange} label="Identifiant" type="text" className="txtField" marginForm />
                        <TextField required value={this.state.password} onChange={this.handlePasswordChange} label="Mot de passe" type="password" className="txtField" marginForm />
                        <Button raised color="primary" className=" btn" onClick={this.checkIdentifiantAndPassword}>Se connecter</Button>
                    </form>

        </Paper>
    );
}

};

My problem is, i don't know how to redirect to another component via the onClick handler. I tried many solutions like wrapping the Button component in a NavLink as below:

<NavLink to="/new" ><Button raised color="primary" className=" btn" onClick={this.checkIdentifiantAndPassword}>Se connecter</Button></NavLink>

but i get an error at the first line of the checkIdentifiantAndPassword method:

Cannot read property 'state' of null

I know that i can remove the Button component and use only NavLink and add all the classes of Button component to the NavLink, but i don't like this workaround.

Do somebody have an idea of how i can achieve this. I am using React-router v4.
Thank you.

Body:
You can use <Redirect/> from 'react-router-dom'.

In the documentation they explain how to use (plus Private Route). See https://reacttraining.com/react-router/web/example/auth-workflow.

I think maybe you can do sth like this:

this.state = {
  ....,
  doRedirect: false
}

.....

checkIdentifiantAndPassword(e) {
  .....
  this.setState({
    doRedirect: true
  });
}

.....

render() {
  if (this.state.doRedirect) {
    <Redirect to={/*Your next route*/}/>
  }
  .....
}


问:
How to add values from checkbox to database
Let me start by saying that I googled this and tried different things, but I'm still stuck and need some help as this is my first time trying out checkboxes with php...
I have a section in my HTML file as follows

```<code><label class="labelStyle" for="text">XXX:</label>
                        <div class="checkboxAlign">
                            <input type="checkbox" name="XX[]" value="Apple">Apple<br>
                            <input type="checkbox" name="XX[]" value="Orange">Orange<br>
                            <input type="checkbox" name="XX[]" value="Strawberry">Strawberry<br>
                        </div>
</code>```

But I am having trouble with the PHP part of it as it's not adding the checked items to my database.

Try this

```<code>if (!empty($_POST['XX']))
{
    foreach($_POST['XX'] as $check)
    {
        if(!($stmt = $mysqli->prepare("INSERT INTO table
            id = (
                SELECT id
                FROM yy
                WHERE xx = ?)"))){
            echo "Prepare failed: "  . $stmt->errno . " " . $stmt->error;
        }
         if(!($stmt->bind_param("s",  $_POST['XX'])))    {
        echo "Bind failed: "  . $stmt->errno . " " . $stmt->error;
    }

    }
}
</code>```

I know the issue is within this php snippet, but I'm not sure what I'm doing wrong. Any help would be appreciated.

Thanks!

答:
Try this</p>

```<code>if (!empty($_POST['XX']))
{
    foreach($_POST['XX'] as $check)
    {
        if(!($stmt = $mysqli->prepare("INSERT INTO table
            id = (
                SELECT id
                FROM yy
                WHERE xx = ?)"))){  //added ? in place of $check
            echo "Prepare failed: "  . $stmt->errno . " " . $stmt->error;
        }
        if(!($stmt->bind_param("s", $check)))    { // added $check in place of $_POST['XX']
            echo "Bind failed: "  . $stmt->errno . " " . $stmt->error;
        }

    }
}
</code>```

Body:
Let me start by saying that I googled this and tried different things, but I'm still stuck and need some help as this is my first time trying out checkboxes with php...
I have a section in my HTML file as follows

XXX:

                            <input type="checkbox" name="XX[]" value="Apple">Apple

                            <input type="checkbox" name="XX[]" value="Orange">Orange

                            <input type="checkbox" name="XX[]" value="Strawberry">Strawberry

But I am having trouble with the PHP part of it as it's not adding the checked items to my database.

Try this

if (!empty($_POST['XX']))
{
    foreach($_POST['XX'] as $check)
    {
        if(!($stmt = $mysqli->prepare("INSERT INTO table
            id = (
                SELECT id
                FROM yy
                WHERE xx = ?)"))){
            echo "Prepare failed: "  . $stmt->errno . " " . $stmt->error;
        }
         if(!($stmt->bind_param("s",  $_POST['XX'])))    {
        echo "Bind failed: "  . $stmt->errno . " " . $stmt->error;
    }

    }
}

I know the issue is within this php snippet, but I'm not sure what I'm doing wrong. Any help would be appreciated.

Thanks!

Body:
Try this

if (!empty($_POST['XX']))
{
    foreach($_POST['XX'] as $check)
    {
        if(!($stmt = $mysqli->prepare("INSERT INTO table
            id = (
                SELECT id
                FROM yy
                WHERE xx = ?)"))){  //added ? in place of $check
            echo "Prepare failed: "  . $stmt->errno . " " . $stmt->error;
        }
        if(!($stmt->bind_param("s", $check)))    { // added $check in place of $_POST['XX']
            echo "Bind failed: "  . $stmt->errno . " " . $stmt->error;
        }

    }
}


问:
Can not add backslash into input parameter using Python
I need to escape all special character and then add back slash () into input parameters using python. I have done something but it's not working. My code is below.

```<code>rname = request.POST.get('rname')
ename = re.escape(rname)
add_slash = ename + '\'
</code>```

Here I need to escape all special character first and then add the \ with that string.

答:
A backslash also needs to be escaped, like so</p>

```<code>add_slash = ename + '\\'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to escape all special character and then add back slash () into input parameters using python. I have done something but it's not working. My code is below.

rname = request.POST.get('rname')
ename = re.escape(rname)
add_slash = ename + '\'

Here I need to escape all special character first and then add the \ with that string.

Body:
A backslash also needs to be escaped, like so

add_slash = ename + '\\'


答:
change

```<code>if(!($stmt->bind_param("s", $_POST['FoodTriggerItem'])))    {
                    echo "Bind failed: "  . $stmt->errno . " " . $stmt->error;
                }
</code>```

TO

```<code>if(!($stmt->bind_param("s", $check)))    {
                    echo "Bind failed: "  . $stmt->errno . " " . $stmt->error;
                }
</code>```

Title: How to add values from checkbox to database

Body:
change

if(!($stmt->bind_param("s", $_POST['FoodTriggerItem'])))    {
                    echo "Bind failed: "  . $stmt->errno . " " . $stmt->error;
                }

TO

if(!($stmt->bind_param("s", $check)))    {
                    echo "Bind failed: "  . $stmt->errno . " " . $stmt->error;
                }


问:
When I create my 1st CollectionView using storyboard the CollectionViewCell has default insets from top?
When I create my 1st CollectionView using storyboard the CollectionViewCell has default insets from top(in size inspector it shows zero but it bit down from top of CollectionView) and I cant move it to top, but when I create a second CollectionView and further CollectionView its cell has no insets from top?</p>

答: In your storyboard, uncheck Adjust Scroll View Inset of the view controller containing the collection view.


问:
Scala: Not able to find implicit from object
I have the following scala code. I don't understand why the implicit is not being figured by the compiler. I also tried putting the import line inside Main. Note however that when the implicit object was created inside Main, then the code ran correctly

```<code>import LoggingAddon._

object Main {
  def main(args: Array[String]): Unit = {
    val dog = new Dog
    Util.act(dog)
  }
}

class Dog {
  def bark(): Unit = {
    println("woof")
  }
}

trait Action[A] {
  def action(x: A): Unit
}

trait WithoutLogging[A] extends Action[A] {
}

trait WithLogging[A] extends Action[A] {
}

object LoggingAddon {

  implicit object DogWithLogging extends WithLogging[Dog] {
    override def action(x: Dog): Unit = {
      println("before")
      x.bark()
      print("after")
    }
  }
}

object NoLoggingAddion {

  implicit object DogWithoutLogging extends WithoutLogging[Dog] {
    override def action(x: Dog): Unit = {
      x.bark()
    }
  }
}

object Util {
  def act(x: Dog)(implicit nolog: Action[Dog]): Unit = {
    nolog.action(x)
  }
}
</code>```

I have imported the necessary implicit from the LoggingAddon but still the scala compiler says could not find implicit Action[Dog]

All I'm trying to do is make a pluggable typeclass. Rather than changing any piece of code, merely change the import statements to have different side effects

答:
Simply move the order of usage where implicit is imported, I moved to the bottom in following example

```<code>class Dog {
  def bark(): Unit = {
    println("woof")
  }
}

trait Action[A] {
  def action(x: A): Unit
}

trait WithoutLogging[A] extends Action[A] {
}

trait WithLogging[A] extends Action[A] {
}

object LoggingAddon {

  implicit object DogWithLogging extends WithLogging[Dog] {
    override def action(x: Dog): Unit = {
      println("before")
      x.bark()
      print("after")
    }
  }
}

object NoLoggingAddion {

  implicit object DogWithoutLogging extends WithoutLogging[Dog] {
    override def action(x: Dog): Unit = {
      x.bark()
    }
  }
}

object Util {
  def act(x: Dog)(implicit nolog: Action[Dog]): Unit = {
    nolog.action(x)
  }
}

import LoggingAddon._
object Main {
  def main(args: Array[String]): Unit = {
    val dog = new Dog
    Util.act(dog)
  }
}
</code>```

Body:
I have the following scala code. I don't understand why the implicit is not being figured by the compiler. I also tried putting the import line inside Main. Note however that when the implicit object was created inside Main, then the code ran correctly

import LoggingAddon._

object Main {
  def main(args: Array[String]): Unit = {
    val dog = new Dog
    Util.act(dog)
  }
}

class Dog {
  def bark(): Unit = {
    println("woof")
  }
}

trait Action[A] {
  def action(x: A): Unit
}

trait WithoutLogging[A] extends Action[A] {
}

trait WithLogging[A] extends Action[A] {
}

object LoggingAddon {

  implicit object DogWithLogging extends WithLogging[Dog] {
    override def action(x: Dog): Unit = {
      println("before")
      x.bark()
      print("after")
    }
  }
}

object NoLoggingAddion {

  implicit object DogWithoutLogging extends WithoutLogging[Dog] {
    override def action(x: Dog): Unit = {
      x.bark()
    }
  }
}

object Util {
  def act(x: Dog)(implicit nolog: Action[Dog]): Unit = {
    nolog.action(x)
  }
}

I have imported the necessary implicit from the LoggingAddon but still the scala compiler says could not find implicit Action[Dog]

All I'm trying to do is make a pluggable typeclass. Rather than changing any piece of code, merely change the import statements to have different side effects

Body:
Simply move the order of usage where implicit is imported, I moved to the bottom in following example

class Dog {
  def bark(): Unit = {
    println("woof")
  }
}

trait Action[A] {
  def action(x: A): Unit
}

trait WithoutLogging[A] extends Action[A] {
}

trait WithLogging[A] extends Action[A] {
}

object LoggingAddon {

  implicit object DogWithLogging extends WithLogging[Dog] {
    override def action(x: Dog): Unit = {
      println("before")
      x.bark()
      print("after")
    }
  }
}

object NoLoggingAddion {

  implicit object DogWithoutLogging extends WithoutLogging[Dog] {
    override def action(x: Dog): Unit = {
      x.bark()
    }
  }
}

object Util {
  def act(x: Dog)(implicit nolog: Action[Dog]): Unit = {
    nolog.action(x)
  }
}

import LoggingAddon._
object Main {
  def main(args: Array[String]): Unit = {
    val dog = new Dog
    Util.act(dog)
  }
}


问:
Store one decimal digit
I have a problem which concern with large number of small integers (actually decimal digits). What is the space efficient way to store such a data?

Is it good idea to use std::bitset<4> to store one decimal digit?

答:
If you want a very compact way, then no, using bitset<4> is a bad idea, because bitset<4> will use at least one byte, instead of 4 bits.

I'd recommend using std::vector<std::uint32_t>

You can store multiple digits in an uint32_t. Two usual ways:

Use for 4 bits for each digit, and use bit operations. This way you can store 8 digits in 4 bytes. Here, set/get operations are pretty fast. Efficiency: 4bit/digit

Use base 10 encoding. uint32_t max value is 256^4-1, which is capable to store 9 digits in 4 bytes. Efficiency: 3.55bit/digit. Here, if you need to set/get all the 9 digits, then it is almost as fast than the previous version (as division by 10 will be optimized by a good compiler, no actual division will be done by the CPU). If you need random access, then set/get will be slower than the previous version (you can speed it up with libdivide).

If you use uint64_t instead of uint32_t, then you can store 16 digits with the first way (same 4bit/digit efficiency), and 19 digits with the second way: 3.36bit/digit efficieny, which is pretty close to the theoretical minimum: ~3.3219bit/digit

Title: Store one decimal digit


问:
HDFStore updating stored HDF5 python pandas dataframe
I have two dataframes, df1 which is stored in a pd.HDFStore object and the other which is to be appended to the dataframe.

```<code>store = pd.HDFStore('dataframe_store.h5')

df1 = pd.DataFrame(np.empty((100, 5)))
df2 = pd.DataFrame(np.empty((100, 5)))

store['df1'] = df1
</code>```

Effectively, I would like the end result to be equal to ...

```<code>store['df1'] = df1.append(df2)
</code>```

I would like to append df2 to the stored df1, rather completely overwrite the HDFStore object with a new dataframe.  Is this possible?

Furthermore, when I run the following code I return ValueError can only append to Tables... why is this?

```<code>df = pd.DataFrame(np.empty((1000, 5)))
df2 = pd.DataFrame(np.empty((1000, 5)))

store = pd.HDFStore('store.h5')

store['df'] = df

store.append('df', df2)
</code>```

答:
Per the docs (my emphasis):

HDFStore supports another PyTables format on disk, the table
  format. Conceptually a table is shaped very much like a DataFrame, with rows and
  columns. A table may be appended to in the same or other sessions. In addition,
  delete & query type operations are supported. This format is specified by
  format='table' or format='t' to append or put or to_hdf

New in version 0.13.

This format can be set as an option as well pd.set_option('io.hdf.default_format','table') to enable put/append/to_hdf to by default store in the table format.

```<code>In [361]: store = pd.HDFStore('store.h5')

In [362]: df1 = df[0:4]

In [363]: df2 = df[4:]

# append data (creates a table automatically)
In [364]: store.append('df', df1)

In [365]: store.append('df', df2)

In [366]: store
Out[366]:
<class 'pandas.io.pytables.HDFStore'>
File path: store.h5

# select the entire object
In [367]: store.select('df')
Out[367]:
                   A         B         C
2000-01-01  0.887163  0.859588 -0.636524
2000-01-02  0.015696 -2.242685  1.150036
2000-01-03  0.991946  0.953324 -2.021255
2000-01-04 -0.334077  0.002118  0.405453
2000-01-05  0.289092  1.321158 -1.546906
2000-01-06 -0.202646 -0.655969  0.193421
2000-01-07  0.553439  1.318152 -0.469305
2000-01-08  0.675554 -1.817027 -0.183109

# the type of stored data
In [368]: store.root.df._v_attrs.pandas_type
Out[368]: 'frame_table'
</code>```

Note: You can also create a table by passing format='table' or format='t' to a put operation.

Body:
I have two dataframes, df1 which is stored in a pd.HDFStore object and the other which is to be appended to the dataframe.

store = pd.HDFStore('dataframe_store.h5')

df1 = pd.DataFrame(np.empty((100, 5)))
df2 = pd.DataFrame(np.empty((100, 5)))

store['df1'] = df1

Effectively, I would like the end result to be equal to ...

store['df1'] = df1.append(df2)

I would like to append df2 to the stored df1, rather completely overwrite the HDFStore object with a new dataframe.  Is this possible?

Furthermore, when I run the following code I return ValueError can only append to Tables... why is this?

df = pd.DataFrame(np.empty((1000, 5)))
df2 = pd.DataFrame(np.empty((1000, 5)))

store = pd.HDFStore('store.h5')

store['df'] = df

store.append('df', df2)

Body:
Per the docs (my emphasis):

HDFStore supports another PyTables format on disk, the table
  format. Conceptually a table is shaped very much like a DataFrame, with rows and
  columns. A table may be appended to in the same or other sessions. In addition,
  delete & query type operations are supported. This format is specified by
  format='table' or format='t' to append or put or to_hdf

New in version 0.13.

This format can be set as an option as well pd.set_option('io.hdf.default_format','table') to enable put/append/to_hdf to by default store in the table format.

In [361]: store = pd.HDFStore('store.h5')

In [362]: df1 = df[0:4]

In [363]: df2 = df[4:]

# append data (creates a table automatically)
In [364]: store.append('df', df1)

In [365]: store.append('df', df2)

In [366]: store
Out[366]:
<class 'pandas.io.pytables.HDFStore'>
File path: store.h5

# select the entire object
In [367]: store.select('df')
Out[367]:
                   A         B         C
2000-01-01  0.887163  0.859588 -0.636524
2000-01-02  0.015696 -2.242685  1.150036
2000-01-03  0.991946  0.953324 -2.021255
2000-01-04 -0.334077  0.002118  0.405453
2000-01-05  0.289092  1.321158 -1.546906
2000-01-06 -0.202646 -0.655969  0.193421
2000-01-07  0.553439  1.318152 -0.469305
2000-01-08  0.675554 -1.817027 -0.183109

# the type of stored data
In [368]: store.root.df._v_attrs.pandas_type
Out[368]: 'frame_table'

Note: You can also create a table by passing format='table' or format='t' to a put operation.


问:
How does the compiler define the classes in type_traits?
In C++11 and later, the <type_traits> header contains many classes for type checking, such as std::is_empty, std::is_polymorphic, std::is_trivially_constructible and many others.

While we use these classes just like normal classes, I cannot figure out any way to possibly write the definition of these classes.  No amount of SFINAE (even with C++14/17 rules) or other method seems to be able to tell if a class is polymorphic, empty, or satisfy other properties.  An class that is empty still occupies a positive amount of space as the class must have a unique address.

How then, might compilers define such classes in C++?  Or perhaps it is necessary for the compiler to be intrinsically aware of these class names and parse them specially?

答:
Back in the olden days, when people were first fooling around with type traits, they wrote some really nasty template code in attempts to write portable code to detect certain properties. My take on this was that you had to put a drip-pan under your computer to catch the molten metal as the compiler overheated trying to compile this stuff. Steve Adamczyk, of Edison Design Group (provider of industrial-strength compiler frontends), had a more constructive take on the problem: instead of writing all this template code that takes enormous amounts of compiler time and often breaks them, ask me to provide a helper function.

When type traits were first formally introduced (in TR1, 2006), there were several traits that nobody knew how to implement portably. Since TR1 was supposed to be exclusively library additions, these couldn't count on compiler help, so their specifications allowed them to get an answer that was occasionally wrong, but they could be implemented in portable code.

Nowadays, those allowances have been removed; the library has to get the right answer. The compiler help for doing this isn't special knowledge of particular templates; it's a function call that tells you whether a particular class has a particular property. The compiler can recognize the name of the function, and provide an appropriate answer. This provides a lower-level toolkit that the traits templates can use, individually or in combination, to decide whether the class has the trait in question.


问:
Javascript alert messages in infinite loop
Alert boxes in infinite loop, here I am trying to put a popup alert message on 2 consecutive fields so they cannot be left blank, I know why it is happening - because when onblur event of 1st function is launched it gives focus to second one & when it jumps back to first one onblur of 2nd textfield is launched.

I know validation would be best when done at the form level, but this is the requirement I got.

Any help?

Javascript code

```<code>function x()
{
   if( document.getElementById("1").value.length==0)
   {
      alert('1 is required');
      document.getElementById("1").focus();
   }
}

function y()
{
   if(document.getElementById("2").value.length==0)
   {
      alert('2 is required');
      document.getElementById("2").focus();
   }
}
</code>```

HTML code

```<code><input type="text" name="City Name" id="1" onblur="javascript:x();">
<input type="text" name="Kitty Name" id="2" onblur="javascript:y();">
</code>```

答:
Try Below Js Code. It will solve your problem.</p>

```<code>function x()
{
   if( document.getElementById("1").value.length==0)
   {
      if(alert('1 is required')){
          document.getElementById("1").focus();
      }
      else
          document.activeElement.blur();
   }
}

function y()
{
   if(document.getElementById("2").value.length==0)
   {
      if(alert('2 is required')){
           document.getElementById("2").focus();
      }
      else
          document.activeElement.blur();
   }
}
</code>```

Body:
Alert boxes in infinite loop, here I am trying to put a popup alert message on 2 consecutive fields so they cannot be left blank, I know why it is happening - because when onblur event of 1st function is launched it gives focus to second one & when it jumps back to first one onblur of 2nd textfield is launched.

I know validation would be best when done at the form level, but this is the requirement I got.

Any help?

Javascript code

function x()
{
   if( document.getElementById("1").value.length==0)
   {
      alert('1 is required');
      document.getElementById("1").focus();
   }
}

function y()
{
   if(document.getElementById("2").value.length==0)
   {
      alert('2 is required');
      document.getElementById("2").focus();
   }
}

HTML code

<input type="text" name="City Name" id="1" onblur="javascript:x();">
<input type="text" name="Kitty Name" id="2" onblur="javascript:y();">

Body:
Try Below Js Code. It will solve your problem.

function x()
{
   if( document.getElementById("1").value.length==0)
   {
      if(alert('1 is required')){
          document.getElementById("1").focus();
      }
      else
          document.activeElement.blur();
   }
}

function y()
{
   if(document.getElementById("2").value.length==0)
   {
      if(alert('2 is required')){
           document.getElementById("2").focus();
      }
      else
          document.activeElement.blur();
   }
}


问:
activeadmin filter on dashboard
I have a table of companies and I'd like to have a dropdown form on the activeadmin dashboard header bar and so when a company is selected on it, I can pass it along to a page's scope_to method.

I've already found a way to pass the data to the scope_to method, but I don't know how to place the dropdown on the dashboard header; I've tried defining a form and then calling it with:

```<code>form do |f|
    render partial: 'form'
end
</code>```

And then placing the form in activeadmin/resource/_form.html.arb, but that won't work. Same for all other approaches so far.

Update:

I've found a "way" to have the partial in the dashboard header; I can use:

```<code>proc{`render partial: 'admin/dashboard/set_current_company'}
</code>```

on a menu's label and it works as intended...except I get two selects, only one of which works.

答: You can embed a partial containing a regular Rails form anywhere to maintain the session company_id.  The form can submit to a regular Rails controller or a custom page action.</p>

Title: activeadmin filter on dashboard

Body:
I have a table of companies and I'd like to have a dropdown form on the activeadmin dashboard header bar and so when a company is selected on it, I can pass it along to a page's scope_to method.

I've already found a way to pass the data to the scope_to method, but I don't know how to place the dropdown on the dashboard header; I've tried defining a form and then calling it with:

form do |f|
    render partial: 'form'
end

And then placing the form in activeadmin/resource/_form.html.arb, but that won't work. Same for all other approaches so far.

Update:

I've found a "way" to have the partial in the dashboard header; I can use:

proc{`render partial: 'admin/dashboard/set_current_company'}

on a menu's label and it works as intended...except I get two selects, only one of which works.


问:
How to name an eval script file in a browser debugger tools?
In a javascript file, I have a jquery function that loads a javascript file using getScript. The problem is when I want to debug the downloaded script, it is not easy to find it in debugger tools. It looks like this:

Where it says eval code, thats the downloaded script. Is there a way I can put a name on that? Like for example in the script thats being downloaded, I want something like

namespace("control.js");

Then in the debugger tools, instead of 'eval code' it will say 'control.js'.

Does anyone know a way for this?

Thanks

答:
A bit of a late response, but this might be useful for other people still;

//# sourceURL=url

The above can be added to the end of an eval string, to indicate its source. I am not sure if it would show up properly in those debugger tools. But it does at least show up properly when it is logging data in chrome.

source: https://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl


问:
What is the merit of the "function" type (not "pointer to function")
Reading the C++ Standard, i see that there are "function" types and "pointer to function" types:

```<code>typedef int func(int);     // function
typedef int (*pfunc)(int); // pointer to function
typedef func* pfunc;       // same as above
</code>```

I have never seen the function types used outside of examples (or maybe i didn't recognize their usage?). Some examples:

```<code>func increase, decrease;            // declares two functions
int increase(int), decrease(int);   // same as above

int increase(int x) {return x + 1;} // cannot use the typedef when defining functions
int decrease(int x) {return x - 1;} // cannot use the typedef when defining functions

struct mystruct
{
    func add, subtract, multiply;   // declares three member functions
    int member;
};

int mystruct::add(int x) {return x + member;} // cannot use the typedef
int mystruct::subtract(int x) {return x - member;}

int main()
{
    func k; // the syntax is correct but the variable k is useless!
    mystruct myobject;
    myobject.member = 4;

    cout << increase(5) << ' ' << decrease(5) << '\n'; // outputs 6 and 4
    cout << myobject.add(5) << ' ' << myobject.subtract(5) << '\n'; // 9 and 1
}
</code>```

Seeing that the function types support syntax that doesn't appear in C (declaring member functions), i guess they are not just a part of C baggage that C++ has to support for backward compatibility.

So is there any use for function types, other than demonstrating some funky syntax?

答:
An example of why this is useful is boost, where you see this a lot. For example in the signals2 library:

```<code>boost::signals2::signal<void (int, int)> MySignal;
</code>```

where the above declares a signal that will accept any function that takes two ints and has a void return type.

Body:
Reading the C++ Standard, i see that there are "function" types and "pointer to function" types:

typedef int func(int);     // function
typedef int (*pfunc)(int); // pointer to function
typedef func* pfunc;       // same as above

I have never seen the function types used outside of examples (or maybe i didn't recognize their usage?). Some examples:

func increase, decrease;            // declares two functions
int increase(int), decrease(int);   // same as above

int increase(int x) {return x + 1;} // cannot use the typedef when defining functions
int decrease(int x) {return x - 1;} // cannot use the typedef when defining functions

struct mystruct
{
    func add, subtract, multiply;   // declares three member functions
    int member;
};

int mystruct::add(int x) {return x + member;} // cannot use the typedef
int mystruct::subtract(int x) {return x - member;}

int main()
{
    func k; // the syntax is correct but the variable k is useless!
    mystruct myobject;
    myobject.member = 4;

    cout << increase(5) << ' ' << decrease(5) << '\n'; // outputs 6 and 4
    cout << myobject.add(5) << ' ' << myobject.subtract(5) << '\n'; // 9 and 1
}

Seeing that the function types support syntax that doesn't appear in C (declaring member functions), i guess they are not just a part of C baggage that C++ has to support for backward compatibility.

So is there any use for function types, other than demonstrating some funky syntax?

Body:
An example of why this is useful is boost, where you see this a lot. For example in the signals2 library:

boost::signals2::signal<void (int, int)> MySignal;

where the above declares a signal that will accept any function that takes two ints and has a void return type.


问:
ERROR in bundle.js from UglifyJs
I've completed a project and now it's time to build it. I'm using a boilerplate project and still don't fully understand all the npm/webpack stuff going on under the hood. When running "npm start", I'm receiving the error:

```<code>ERROR in bundle.js from UglifyJs
SyntaxError: Unexpected token: punc ()) [bundle.js:848,29]
</code>```

After an hour of searching the internet on this issue, I'm still unable to resolve it. From my understanding, this issue is happening because Uglify doesn't like ES2016 yet. However, the solutions I found on the internet don't seem to be working or don't make enough sense for me to implement.

I found this stackoverflow question and changed the webpack line in my project's package.json file to:

```<code>"webpack": "fulls1z3/webpack#v2.1.0-beta.27-harmony"
</code>```

But this didn't work. The other suggestion of forking webpack is beyond my understanding at the moment.

I also tried running babel on my src folder per another suggestion but that didn't seem to do anything or I ran it incorrectly.

Does anyone have a nice solution to this issue? I'm pretty stuck at the moment and haven't had time to learn npm/webpack from the ground up to fully grasp what's going on.

Much appreciated!

答:
try my cfg，actuality，i find the answer in
https://github.com/joeeames/WebpackFundamentalsCourse/issues/3

npm install babel --save-dev

npm install babel-preset-es2015 --save-dev

```
            {
                test: /\.js$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    query: {
                        presets: ["es2015"]
                    }
                }
            },
```

Title: ERROR in bundle.js from UglifyJs

Body:
I've completed a project and now it's time to build it. I'm using a boilerplate project and still don't fully understand all the npm/webpack stuff going on under the hood. When running "npm start", I'm receiving the error:

ERROR in bundle.js from UglifyJs
SyntaxError: Unexpected token: punc ()) [bundle.js:848,29]

After an hour of searching the internet on this issue, I'm still unable to resolve it. From my understanding, this issue is happening because Uglify doesn't like ES2016 yet. However, the solutions I found on the internet don't seem to be working or don't make enough sense for me to implement.

I found this stackoverflow question and changed the webpack line in my project's package.json file to:

"webpack": "fulls1z3/webpack#v2.1.0-beta.27-harmony"

But this didn't work. The other suggestion of forking webpack is beyond my understanding at the moment.

I also tried running babel on my src folder per another suggestion but that didn't seem to do anything or I ran it incorrectly.

Does anyone have a nice solution to this issue? I'm pretty stuck at the moment and haven't had time to learn npm/webpack from the ground up to fully grasp what's going on.

Much appreciated!

Body:
try my cfg，actuality，i find the answer in
https://github.com/joeeames/WebpackFundamentalsCourse/issues/3

npm install babel --save-dev

npm install babel-preset-es2015 --save-dev

            {
                test: /\.js$/,
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    query: {
                        presets: ["es2015"]
                    }
                }
            },


问:
how to get 1000 number of records in phpmyadmin ui
[how to see after 500 records in phpmyadmin user interface.if any one give answer][1][1]: https://i.stack.imgur.com/Ktk6Y.png</p>

答: If a table has more rows, you will see a page selector and links like ">" and ">>" on the same line as the one where you see the "Number of rows" selector.</p>


问:
getDatePicker().setMinDate of DatePickerDialog does not work
I want the DatePickerDialog to not show dates before current date. I'm using the setMinDate(long l) method. But it's not working.

I use a inner class where I set the minDate:

```<code>public static class DatePickerFragment extends DialogFragment
        implements DatePickerDialog.OnDateSetListener {
    DatePickerDialog datePickerDialog;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        String s = month + day + year+"";
        datePickerDialog = new DatePickerDialog(getActivity(),this,year,month,day);
        datePickerDialog.getDatePicker().setMinDate(Long.parseLong(s));

        // Create a new instance of DatePickerDialog and return it
            return  datePickerDialog;
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        SelectedDateView.setText(day+ (month + 1) + "-"  + "-" + year);

    }
}
</code>```

This is the method that shows it:

```<code>public void showDatePickerDialog(View v) {
    DialogFragment newFragment = new DatePickerFragment();
    newFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
}
</code>```

答:
For sdks older than 23, you will have to use "System.currentTimeMillis()" instead of "cal.getTimeInMillis()".

sdk < 23: datePickerStart.getDatePicker().setMinDate(System.currentTimeMillis())
sdk > 23: datePickerStart.getDatePicker().setMinDate(cal.getTimeInMillis())

Body:
I want the DatePickerDialog to not show dates before current date. I'm using the setMinDate(long l) method. But it's not working.

I use a inner class where I set the minDate:

public static class DatePickerFragment extends DialogFragment
        implements DatePickerDialog.OnDateSetListener {
    DatePickerDialog datePickerDialog;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        String s = month + day + year+"";
        datePickerDialog = new DatePickerDialog(getActivity(),this,year,month,day);
        datePickerDialog.getDatePicker().setMinDate(Long.parseLong(s));

        // Create a new instance of DatePickerDialog and return it
            return  datePickerDialog;
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        SelectedDateView.setText(day+ (month + 1) + "-"  + "-" + year);

    }
}

This is the method that shows it:

public void showDatePickerDialog(View v) {
    DialogFragment newFragment = new DatePickerFragment();
    newFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
}


问:
Enabling panel when php gets executed unless its hidden
I using php to display result to my page and I did a bit of styling using bootstrap

```<code><div class="alert alert-success" role="alert">
        <?php
        if(isset($_POST['submit'])){ //check if form was submitted
         include "assets/backend/newsletter.php";
        }
        ?>
</div>
</code>```

Even the php code is not executed I can see the blank panel.
How can I get rid of that?

答:
[Image for reference.][1]I think on ur case this makes way much more sens then what are u doing up there:

```<code><?php
if(isset($_POST['submit'])){ ?>
 <div class="alert alert-success" role="alert">
 <?php include "assets/backend/newsletter.php"; ?>
</div>
<?php}?>
</code>```

This way if the form was submitted the panel will appear if not submitted the panel will not be visible.

```<code>footer.php
 <div class="container">
    <div class="row">
    <?php
       if(isset($_POST['submit'])){
           echo '<div class="alert alert-success" role="alert"> ';
           include 'assets/backend/newsletter.php';
           echo '</div>';
       }
        ?>
    </div>

<div class="container-fluid" style="background-color:#222222">
    <div class="row">
        <div class="container" style="margin-top:15px;
            margin-bottom:15px">
            <div class="col-lg-4" style="color:#f3f6f9">
                <img src="images/pc%20logo.png" width="80px" height="80px">
                <h4 >
                    PLACEMENT
                    <cell style="font-weight:bold">CELL</cell>
                </h4>
                <p>Nehru Nagar, Ring Road <br>New Delhi <br>
                    Ph :(+91) 964 328 0581<br>
                    Email : placements.pgdav@gmail.com
                </p>
                <a href="https://www.facebook.com/pgdavplacements">  <img src="images/f.png" height="30px" width="30px" >
                </a>
                <img src="images/i.png" height="30px" width="30px">
                <img src="images/linkedin.png" height="30px" width="30px">
            </div>
            <div class="col-lg-4" style="color:#f3f6f9;
                padding-top:30px">
                <h4>Subscribe to Our Newsletter</h4>
                <form action=" " method="post">
                    <div class="form-group">
                        <input class="form-control" type="text"
                            id="inputemail" name="email_newsletter" placeholder="Your Email ID">
                    </div>
                    <input type="submit" name="submit" class="btn btn-default" value="subscribe">
                </form>
            </div>
            <div class="col-lg-4" style="color:#f3f6f9;
                padding-top:29px">
                <h4>Links</h4>
                <ol class="breadcrumb">
                    <li><a href="index.php">Home</a></li>
                    <li><a href="aboutcell.php">About Cell</a></li>
                    <li><a href="">Registration</a></li>
                    <li><a href="contactus.php">Contact Us</a></li>
                </ol>
            </div>
        </div>

        <div class="container-fluid" style="background-color:#f3f6f9">
            <div class="row">
                <div class="container" style="padding-top:7px">
                    <div class="col-lg-6 col-sm-12 col-xs-12">© All the Rights Reserved with Placement Cell</div>
                    <div class="col-lg-6 col-sm-12 col-xs-12" style="text-align:right"><a href="https://www.linkedin.com/in/bhanukrsingh/">Developed By Bhanu Singh</a></div>
                </div>
            </div>
        </div>
    </div>
</div></div>
</code>```

or this:

```<code> <div class="container">
    <div class="row">
    <?php
       if(isset($_POST['submit'])){ ?>
         <div class="alert alert-success" role="alert">
          <?php
           include 'assets/backend/newsletter.php';
           ?>
           </div>
       <?php
       }
        ?>
    </div>

<div class="container-fluid" style="background-color:#222222">
    <div class="row">
        <div class="container" style="margin-top:15px;
            margin-bottom:15px">
            <div class="col-lg-4" style="color:#f3f6f9">
                <img src="images/pc%20logo.png" width="80px" height="80px">
                <h4 >
                    PLACEMENT
                    <cell style="font-weight:bold">CELL</cell>
                </h4>
                <p>Nehru Nagar, Ring Road <br>New Delhi <br>
                    Ph :(+91) 964 328 0581<br>
                    Email : placements.pgdav@gmail.com
                </p>
                <a href="https://www.facebook.com/pgdavplacements">  <img src="images/f.png" height="30px" width="30px" >
                </a>
                <img src="images/i.png" height="30px" width="30px">
                <img src="images/linkedin.png" height="30px" width="30px">
            </div>
            <div class="col-lg-4" style="color:#f3f6f9;
                padding-top:30px">
                <h4>Subscribe to Our Newsletter</h4>
                <form action=" " method="post">
                    <div class="form-group">
                        <input class="form-control" type="text"
                            id="inputemail" name="email_newsletter" placeholder="Your Email ID">
                    </div>
                    <input type="submit" name="submit" class="btn btn-default" value="subscribe">
                </form>
            </div>
            <div class="col-lg-4" style="color:#f3f6f9;
                padding-top:29px">
                <h4>Links</h4>
                <ol class="breadcrumb">
                    <li><a href="index.php">Home</a></li>
                    <li><a href="aboutcell.php">About Cell</a></li>
                    <li><a href="">Registration</a></li>
                    <li><a href="contactus.php">Contact Us</a></li>
                </ol>
            </div>
        </div>

        <div class="container-fluid" style="background-color:#f3f6f9">
            <div class="row">
                <div class="container" style="padding-top:7px">
                    <div class="col-lg-6 col-sm-12 col-xs-12">© All the Rights Reserved with Placement Cell</div>
                    <div class="col-lg-6 col-sm-12 col-xs-12" style="text-align:right"><a href="https://www.linkedin.com/in/bhanukrsingh/">Developed By Bhanu Singh</a></div>
                </div>
            </div>
        </div>
    </div>
</div></div>
</code>```

tested both options are workin;

Body:
I using php to display result to my page and I did a bit of styling using bootstrap

        <?php
        if(isset($_POST['submit'])){ //check if form was submitted
         include "assets/backend/newsletter.php";
        }
        ?>

Even the php code is not executed I can see the blank panel.
How can I get rid of that?

Body:
[Image for reference.][1]I think on ur case this makes way much more sens then what are u doing up there:

<?php
if(isset($_POST['submit'])){ ?>
 <div class="alert alert-success" role="alert">
 <?php include "assets/backend/newsletter.php"; ?>
</div>
<?php}?>

This way if the form was submitted the panel will appear if not submitted the panel will not be visible.

footer.php
 <div class="container">
    <div class="row">
    <?php
       if(isset($_POST['submit'])){
           echo '<div class="alert alert-success" role="alert"> ';
           include 'assets/backend/newsletter.php';
           echo '</div>';
       }
        ?>
    </div>

<div class="container-fluid" style="background-color:#222222">
    <div class="row">
        <div class="container" style="margin-top:15px;
            margin-bottom:15px">
            <div class="col-lg-4" style="color:#f3f6f9">
                <img src="images/pc%20logo.png" width="80px" height="80px">
                <h4 >
                    PLACEMENT
                    <cell style="font-weight:bold">CELL</cell>
                </h4>
                <p>Nehru Nagar, Ring Road <br>New Delhi <br>
                    Ph :(+91) 964 328 0581<br>
                    Email : placements.pgdav@gmail.com
                </p>
                <a href="https://www.facebook.com/pgdavplacements">  <img src="images/f.png" height="30px" width="30px" >
                </a>
                <img src="images/i.png" height="30px" width="30px">
                <img src="images/linkedin.png" height="30px" width="30px">
            </div>
            <div class="col-lg-4" style="color:#f3f6f9;
                padding-top:30px">
                <h4>Subscribe to Our Newsletter</h4>
                <form action=" " method="post">
                    <div class="form-group">
                        <input class="form-control" type="text"
                            id="inputemail" name="email_newsletter" placeholder="Your Email ID">
                    </div>
                    <input type="submit" name="submit" class="btn btn-default" value="subscribe">
                </form>
            </div>
            <div class="col-lg-4" style="color:#f3f6f9;
                padding-top:29px">
                <h4>Links</h4>
                <ol class="breadcrumb">
                    <li><a href="index.php">Home</a></li>
                    <li><a href="aboutcell.php">About Cell</a></li>
                    <li><a href="">Registration</a></li>
                    <li><a href="contactus.php">Contact Us</a></li>
                </ol>
            </div>
        </div>

        <div class="container-fluid" style="background-color:#f3f6f9">
            <div class="row">
                <div class="container" style="padding-top:7px">
                    <div class="col-lg-6 col-sm-12 col-xs-12">© All the Rights Reserved with Placement Cell</div>
                    <div class="col-lg-6 col-sm-12 col-xs-12" style="text-align:right"><a href="https://www.linkedin.com/in/bhanukrsingh/">Developed By Bhanu Singh</a></div>
                </div>
            </div>
        </div>
    </div>
</div></div>

or this:

 <div class="container">
    <div class="row">
    <?php
       if(isset($_POST['submit'])){ ?>
         <div class="alert alert-success" role="alert">
          <?php
           include 'assets/backend/newsletter.php';
           ?>
           </div>
       <?php
       }
        ?>
    </div>

<div class="container-fluid" style="background-color:#222222">
    <div class="row">
        <div class="container" style="margin-top:15px;
            margin-bottom:15px">
            <div class="col-lg-4" style="color:#f3f6f9">
                <img src="images/pc%20logo.png" width="80px" height="80px">
                <h4 >
                    PLACEMENT
                    <cell style="font-weight:bold">CELL</cell>
                </h4>
                <p>Nehru Nagar, Ring Road <br>New Delhi <br>
                    Ph :(+91) 964 328 0581<br>
                    Email : placements.pgdav@gmail.com
                </p>
                <a href="https://www.facebook.com/pgdavplacements">  <img src="images/f.png" height="30px" width="30px" >
                </a>
                <img src="images/i.png" height="30px" width="30px">
                <img src="images/linkedin.png" height="30px" width="30px">
            </div>
            <div class="col-lg-4" style="color:#f3f6f9;
                padding-top:30px">
                <h4>Subscribe to Our Newsletter</h4>
                <form action=" " method="post">
                    <div class="form-group">
                        <input class="form-control" type="text"
                            id="inputemail" name="email_newsletter" placeholder="Your Email ID">
                    </div>
                    <input type="submit" name="submit" class="btn btn-default" value="subscribe">
                </form>
            </div>
            <div class="col-lg-4" style="color:#f3f6f9;
                padding-top:29px">
                <h4>Links</h4>
                <ol class="breadcrumb">
                    <li><a href="index.php">Home</a></li>
                    <li><a href="aboutcell.php">About Cell</a></li>
                    <li><a href="">Registration</a></li>
                    <li><a href="contactus.php">Contact Us</a></li>
                </ol>
            </div>
        </div>

        <div class="container-fluid" style="background-color:#f3f6f9">
            <div class="row">
                <div class="container" style="padding-top:7px">
                    <div class="col-lg-6 col-sm-12 col-xs-12">© All the Rights Reserved with Placement Cell</div>
                    <div class="col-lg-6 col-sm-12 col-xs-12" style="text-align:right"><a href="https://www.linkedin.com/in/bhanukrsingh/">Developed By Bhanu Singh</a></div>
                </div>
            </div>
        </div>
    </div>
</div></div>

tested both options are workin;


问:
How to display a text popup on single click and download on double click?
I am busy editing the aptoide code from github into something that will be used for users to suggest apps and be able to browse and download suggested apps.

The only problem is that aptoide does not display any explaination of what the app is.

So I would like to know firstly, is it possible to code a if single-click event and a double-click event?

And secondly, how would I go about coding this? I would like the single-click to show the info about the app and the double click to download the app. So you'd click the suggested app, it'll show the info and then you click again to download.

I am using Eclipse with the ADT plugin.

I have tried to be as thorough as possible.

I am not very good with eclipse and android just yet, so you might have to spoon feed me here.

答:
I would say Long press is the standard action people expect not double tap,
Check out the AdapterView.OnItemLongClickListener docs

Maybe I'm not understanding correctly what you're trying to do
Do you mean you want to change the OnClickListener once the first one has been run.


问:
fread() expects parameter 1 to be resource
I have a PHP Warning.

```<code>fread() expects parameter 1 to be resource, boolean given in /tmp/func.php on line 12
</code>```

My code :

```<code><?php

  $sqlite = 'teleinfo.sqlite';

  function getTeleinfo () {

    $handle = fopen ('/dev/ttyACM0', "r"); // ouverture du flux

    while (fread($handle, 1) != chr(2));
--------
</code>```

Thank you !

php --version

PHP 5.4.45-0+deb7u2 (cli) (built: Oct 27 2015 23:22:07)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2014 Zend Technologies

答:
If your are following this tutorial : http://www.magdiblog.fr/gpio/teleinfo-edf-suivi-conso-de-votre-compteur-electrique/

Data is recivied on /dev/ttyAMA0

```<code>stty -F /dev/ttyAMA0 1200 sane evenp parenb cs7 -crtscts
</code>```

But in php script is parsed on /dev/ttyACM0

You should change the filename in php script !

Body:
I have a PHP Warning.

fread() expects parameter 1 to be resource, boolean given in /tmp/func.php on line 12

My code :

<?php

  $sqlite = 'teleinfo.sqlite';

  function getTeleinfo () {

    $handle = fopen ('/dev/ttyACM0', "r"); // ouverture du flux

    while (fread($handle, 1) != chr(2));
--------

Thank you !

php --version

PHP 5.4.45-0+deb7u2 (cli) (built: Oct 27 2015 23:22:07)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2014 Zend Technologies

Body:
If your are following this tutorial : http://www.magdiblog.fr/gpio/teleinfo-edf-suivi-conso-de-votre-compteur-electrique/

Data is recivied on /dev/ttyAMA0

stty -F /dev/ttyAMA0 1200 sane evenp parenb cs7 -crtscts

But in php script is parsed on /dev/ttyACM0

You should change the filename in php script !


问:
Bash command in php script, get some lines of a file according values of a specific column
Via linux bash command(s) (grep + regex + another commands ?) from a php script, I want get the line(s) of a file according some conditions, see below :

An exemple of a file :

```<code>"id_line1","value_line1_column2","foo blablabla","value_line1_column4"
"id_line2","value_line2_column2","blablabla foo","value_line2_column4"
"id_line3","value_line3_column2","blabla foo blabla","value_line3_column4"
"id_line4","value_line4_column2","blablabla","value_line4_column4"
"id_line5","value_line5_column2","fooblabla bla","value_line5_column4"
"id_line6","value_line6_column2","blabla blafoo","value_line6_column4"
"id_line7","value_line7_column2","blabla foobla bla","value_line7_column4"
</code>```

I want search only on the column number X in the file ( the third column in this example ).

The regular expression

In the third column of all lines of my file, I want find string(s) containing a searched word that is : (via grep + regex ?)

At the beginning of the string of the specific column (here in the example, the third column)

OR at the end of the string of the specific column (here in the example, the third column)

OR somewhere in the string of the specific column (here in the example, the third column)

And find only the word not concatenated with another words. By example, with the example file above, if I search the word "foo" :

```<code>"id_line1","value_line1_column2","foo blablabla","value_line1_column4" // the regex must return true
"id_line2","value_line2_column2","blablabla foo","value_line2_column4" // the regex must return true
"id_line3","value_line3_column2","blabla foo blabla","value_line3_column4" // the regex must return true
"id_line4","value_line4_column2","blablabla","value_line4_column4" // the regex must return false
"id_line5","value_line5_column2","fooblabla bla","value_line5_column4" // the regex must return false
"id_line6","value_line6_column2","blabla blafoo","value_line6_column4" // the regex must return false
"id_line7","value_line7_column2","blabla foobla bla","value_line7_column4" // the regex must return false
</code>```

The result

Command(s) must return lines :

```<code>"id_line1","value_line1_column2","foo blablabla","value_line1_column4"
"id_line2","value_line2_column2","blablabla foo","value_line2_column4"
"id_line3","value_line3_column2","blabla foo blabla","value_line3_column4"
</code>```

How can I do this ?
If I can only get the id ("id_line1", "id_line2", "id_line3") it would be perfect :)

答:
Awk will do the job:

```<code>awk -F, '$3 ~ /"foo / || $3 ~ / foo"/ || $3 ~ /[[:blank:]]foo[[:blank:]]/ { print $0 }' filename
</code>```

Here we are checking the third piece of each line delimited by , and checking for "foo or ( signified by ||) a blank space and then foo and then another blank space and finally foo". If any of these occurances occur, print the line

Body:
Via linux bash command(s) (grep + regex + another commands ?) from a php script, I want get the line(s) of a file according some conditions, see below :

An exemple of a file :

"id_line1","value_line1_column2","foo blablabla","value_line1_column4"
"id_line2","value_line2_column2","blablabla foo","value_line2_column4"
"id_line3","value_line3_column2","blabla foo blabla","value_line3_column4"
"id_line4","value_line4_column2","blablabla","value_line4_column4"
"id_line5","value_line5_column2","fooblabla bla","value_line5_column4"
"id_line6","value_line6_column2","blabla blafoo","value_line6_column4"
"id_line7","value_line7_column2","blabla foobla bla","value_line7_column4"

I want search only on the column number X in the file ( the third column in this example ).

The regular expression

In the third column of all lines of my file, I want find string(s) containing a searched word that is : (via grep + regex ?)

At the beginning of the string of the specific column (here in the example, the third column)

OR at the end of the string of the specific column (here in the example, the third column)

OR somewhere in the string of the specific column (here in the example, the third column)

And find only the word not concatenated with another words. By example, with the example file above, if I search the word "foo" :

"id_line1","value_line1_column2","foo blablabla","value_line1_column4" // the regex must return true
"id_line2","value_line2_column2","blablabla foo","value_line2_column4" // the regex must return true
"id_line3","value_line3_column2","blabla foo blabla","value_line3_column4" // the regex must return true
"id_line4","value_line4_column2","blablabla","value_line4_column4" // the regex must return false
"id_line5","value_line5_column2","fooblabla bla","value_line5_column4" // the regex must return false
"id_line6","value_line6_column2","blabla blafoo","value_line6_column4" // the regex must return false
"id_line7","value_line7_column2","blabla foobla bla","value_line7_column4" // the regex must return false

The result

Command(s) must return lines :

"id_line1","value_line1_column2","foo blablabla","value_line1_column4"
"id_line2","value_line2_column2","blablabla foo","value_line2_column4"
"id_line3","value_line3_column2","blabla foo blabla","value_line3_column4"

How can I do this ?
If I can only get the id ("id_line1", "id_line2", "id_line3") it would be perfect :)

Body:
Awk will do the job:

awk -F, '$3 ~ /"foo / || $3 ~ / foo"/ || $3 ~ /[[:blank:]]foo[[:blank:]]/ { print $0 }' filename

Here we are checking the third piece of each line delimited by , and checking for "foo or ( signified by ||) a blank space and then foo and then another blank space and finally foo". If any of these occurances occur, print the line


问:
How to call a function after HTML content refresh in angular2?
When I hit an api to get data from server in constructor and store it in local variable. I loop this variable in html to build table and show data in table. But when I call a function on api success and in it I loop the same variable which is used in HTML, the loop in function will run first and after that HTML loop. My requirement is to run HTML loop first and after its completion loop in function.

HTML CODE

```<code><table>
   <tr *ngFor="let booking of jobHistory>
      <td>{{booking}}</td>
   </tr>
</table>
</code>```

TYPESCRIPT CODE

```<code>jobHistory : any;
constructor()
{
  this.service.getCustomerJobHistory().subscribe(   res => { this.jobHistory = res},
                                                    err => console.log(err),
                                                    () => this.setRating()
                                              );

}

setRating()
{
   //I want to run this loop after HTML loop completion.
   for(let booking of this.jobHistory)
   {
     console.log(booking);
   }
}
</code>```

答:
So i saw the answers (including the accepted one) and while they are definitely worth knowing, i don't think it's the best way to handle your situation.
The reasons already came up in the comments to the accepted answer:

When angular isn't run in prodMode you will get weird behaviour due to angulars double powered change detection if not run in prodMode. (Initializing and every change (even a single click on one of your elements) will your function twice due to change detection.

Even in prodMode depending on where your array is initialized, the function could be called multiple times. For example initializing your array like this:

export class YourComp {
      jobHistory: any[] = ['one', 'two', 'three' ];
      setRating() { ... }
 }

will call the function three times after it's initialized, even in prodMode (which is very weird...).

Every triggerd event, will trigger the change detection which will end in reevaluating the last property and therefore call your function again. So clicking on one of your elements (even though you didn't even setup a click listener) will call setRating again.

Because of this, i suggest to try another approach.
The probably easiest way i came up with would be to use another component.

Something like this:

```<code>export class MyTableComponent {
     @Input() data: any[];

     ngAfterViewInit() {
          this._setRating();
     }

     private _setRating() {
          console.log('set rating...');
     }
}
</code>```

As its template it should have the same table you posted in your question. In your parent component you would initialize it with something like <my-table [data]="jobHistory" *ngIf="jobHistory"></my-table>

If your jobHistory data will be updated in your main component, you just clear it (which will destruct the MyTableComponent), push your new / updated elements into the array again, which will reinitialize the component and finally call setRating.

If setRating is called too early, a little setTimeout(() => { this._setRating(); }); would do.

Hope i could help.

Body:
When I hit an api to get data from server in constructor and store it in local variable. I loop this variable in html to build table and show data in table. But when I call a function on api success and in it I loop the same variable which is used in HTML, the loop in function will run first and after that HTML loop. My requirement is to run HTML loop first and after its completion loop in function.

HTML CODE

      {{booking}}

TYPESCRIPT CODE

jobHistory : any;
constructor()
{
  this.service.getCustomerJobHistory().subscribe(   res => { this.jobHistory = res},
                                                    err => console.log(err),
                                                    () => this.setRating()
                                              );

}

setRating()
{
   //I want to run this loop after HTML loop completion.
   for(let booking of this.jobHistory)
   {
     console.log(booking);
   }
}

Body:
So i saw the answers (including the accepted one) and while they are definitely worth knowing, i don't think it's the best way to handle your situation.
The reasons already came up in the comments to the accepted answer:

When angular isn't run in prodMode you will get weird behaviour due to angulars double powered change detection if not run in prodMode. (Initializing and every change (even a single click on one of your elements) will your function twice due to change detection.

Even in prodMode depending on where your array is initialized, the function could be called multiple times. For example initializing your array like this:

export class YourComp {
      jobHistory: any[] = ['one', 'two', 'three' ];
      setRating() { ... }
 }

will call the function three times after it's initialized, even in prodMode (which is very weird...).

Every triggerd event, will trigger the change detection which will end in reevaluating the last property and therefore call your function again. So clicking on one of your elements (even though you didn't even setup a click listener) will call setRating again.

Because of this, i suggest to try another approach.
The probably easiest way i came up with would be to use another component.

Something like this:

export class MyTableComponent {
     @Input() data: any[];

     ngAfterViewInit() {
          this._setRating();
     }

     private _setRating() {
          console.log('set rating...');
     }
}

As its template it should have the same table you posted in your question. In your parent component you would initialize it with something like <my-table [data]="jobHistory" *ngIf="jobHistory"></my-table>

If your jobHistory data will be updated in your main component, you just clear it (which will destruct the MyTableComponent), push your new / updated elements into the array again, which will reinitialize the component and finally call setRating.

If setRating is called too early, a little setTimeout(() => { this._setRating(); }); would do.

Hope i could help.


问:
When I delete an item from the database and updatethe datagrid, I still see this object
I have two windows wpf.
On the first window I see data from DataGrid, on the second window I delete object from database.

First window:

```<code>private void mnRemoveProduct_Click(object sender, RoutedEventArgs e)
{
   RemoveProduct window = new RemoveProduct();
   window.ShowDialog();
   ShowWatchTable();
} // mnRemoveProduct_Click
</code>```

Second window:

```<code>private void btnDelete_Click(object sender, RoutedEventArgs e)
{
    if (cmbNameOfWatch.SelectedIndex > 0)
    {
        var value =
            (from watch in obj.Watch.Where(w => w.mark == cmbNameOfWatch.SelectedValue.ToString())
             select new { watch.id }).ToArray().First();

        Watch watchObj = obj.Watch.Find(value.id);
        obj.Watch.Remove(watchObj);
        obj.SaveChanges();

        this.Close();
    }
} // btnDelete_Click
</code>```

and function ShowTable

```<code>public void ShowWatchTable()
{
    obj.Watch.ToList();
    dataGrid.ItemsSource =
        from watch in obj.Watch.Local
        select new
        {
            ID = watch.id,
            Brand = watch.mark,
            Typ = watch.TypeWatch.typeName,
            Price = watch.price + " $".ToString(),
            Quantity = watch.number,
            Fabricator = watch.Fabricator.fName,
            Country = watch.Fabricator.Country.countryName
        };
}
</code>```

When I delete value from database, I still see this value in DataGrid. Only when I close and open this form then I no longer see this object. When I add an element, the same logic is used. Datagrid is updated with the ShowTable function and I see the updated database. But when deleting it it does not work. Please help

答:
Well, my guess your data source is a query result, but i'm not pretty sure that it's observable(f.e. when I need to bind to collections, I use IObservableCollection to notify that collection changed).
Probably you can try to call dbGrid.Items.Refresh(); method when your primary views gets focus back

Body:
I have two windows wpf.
On the first window I see data from DataGrid, on the second window I delete object from database.

First window:

private void mnRemoveProduct_Click(object sender, RoutedEventArgs e)
{
   RemoveProduct window = new RemoveProduct();
   window.ShowDialog();
   ShowWatchTable();
} // mnRemoveProduct_Click

Second window:

private void btnDelete_Click(object sender, RoutedEventArgs e)
{
    if (cmbNameOfWatch.SelectedIndex > 0)
    {
        var value =
            (from watch in obj.Watch.Where(w => w.mark == cmbNameOfWatch.SelectedValue.ToString())
             select new { watch.id }).ToArray().First();

        Watch watchObj = obj.Watch.Find(value.id);
        obj.Watch.Remove(watchObj);
        obj.SaveChanges();

        this.Close();
    }
} // btnDelete_Click

and function ShowTable

public void ShowWatchTable()
{
    obj.Watch.ToList();
    dataGrid.ItemsSource =
        from watch in obj.Watch.Local
        select new
        {
            ID = watch.id,
            Brand = watch.mark,
            Typ = watch.TypeWatch.typeName,
            Price = watch.price + " $".ToString(),
            Quantity = watch.number,
            Fabricator = watch.Fabricator.fName,
            Country = watch.Fabricator.Country.countryName
        };
}

When I delete value from database, I still see this value in DataGrid. Only when I close and open this form then I no longer see this object. When I add an element, the same logic is used. Datagrid is updated with the ShowTable function and I see the updated database. But when deleting it it does not work. Please help


问:
What are advantages of using @Transactional(readOnly = true)?
I am beginner and as I understand @Transactional simply make sure that all the internal work of a class or method annotated with @Transactional will be wrapped in one transaction and all of the calls from external sources will create a new transaction but why do we actually need these annotations in Repository below and what are advantages of using it with readOnly = true in common cases? This is Spring pet-clinic example application using Spring & Hibernate (https://github.com/spring-projects/spring-petclinic).

```<code>/**
 * Repository class for <code>Pet</code> domain objects All method names are compliant with Spring Data naming
 * conventions so this interface can easily be extended for Spring Data See here: http://static.springsource.org/spring-data/jpa/docs/current/reference/html/jpa.repositories.html#jpa.query-methods.query-creation
 *
 * @author Ken Krebs
 * @author Juergen Hoeller
 * @author Sam Brannen
 * @author Michael Isvy
 */
public interface PetRepository extends Repository<Pet, Integer> {

    /**
     * Retrieve all {@link PetType}s from the data store.
     * @return a Collection of {@link PetType}s.
     */
    @Query("SELECT ptype FROM PetType ptype ORDER BY ptype.name")
    @Transactional(readOnly = true)
    List<PetType> findPetTypes();

    /**
     * Retrieve a {@link Pet} from the data store by id.
     * @param id the id to search for
     * @return the {@link Pet} if found
     */
    @Transactional(readOnly = true)
    Pet findById(Integer id);

    /**
     * Save a {@link Pet} to the data store, either inserting or updating it.
     * @param pet the {@link Pet} to save
     */
    void save(Pet pet);

}
</code>```

答:
From the explanation of Oliver Gierke - the Spring Data author:

Reading methods like findAll() and findOne(…) are using
  @Transactional(readOnly = true) which is not strictly necessary but
  triggers a few optimizations in the transaction infrastructure
  (setting the FlushMode to MANUAL to let persistence providers
  potentially skip dirty checks when closing the EntityManager). Beyond
  that the flag is set on the JDBC Connection as well which causes
  further optimizations on that level.

Depending on what database you use it can omit table locks or even
  reject write operations you might trigger accidentally. Thus we
  recommend using @Transactional(readOnly = true) for query methods as
  well which you can easily achieve adding that annotation to you
  repository interface. Make sure you add a plain @Transactional to the
  manipulating methods you might have declared or re-decorated in that
  interface.

Further reading:

Spring read-only transaction Hibernate optimization

Read-write and read-only transaction routing with Spring

Body:
I am beginner and as I understand @Transactional simply make sure that all the internal work of a class or method annotated with @Transactional will be wrapped in one transaction and all of the calls from external sources will create a new transaction but why do we actually need these annotations in Repository below and what are advantages of using it with readOnly = true in common cases? This is Spring pet-clinic example application using Spring & Hibernate (https://github.com/spring-projects/spring-petclinic).

/**
 * Repository class for Pet domain objects All method names are compliant with Spring Data naming
 * conventions so this interface can easily be extended for Spring Data See here: http://static.springsource.org/spring-data/jpa/docs/current/reference/html/jpa.repositories.html#jpa.query-methods.query-creation
 *
 * @author Ken Krebs
 * @author Juergen Hoeller
 * @author Sam Brannen
 * @author Michael Isvy
 */
public interface PetRepository extends Repository<Pet, Integer> {

    /**
     * Retrieve all {@link PetType}s from the data store.
     * @return a Collection of {@link PetType}s.
     */
    @Query("SELECT ptype FROM PetType ptype ORDER BY ptype.name")
    @Transactional(readOnly = true)
    List<PetType> findPetTypes();

    /**
     * Retrieve a {@link Pet} from the data store by id.
     * @param id the id to search for
     * @return the {@link Pet} if found
     */
    @Transactional(readOnly = true)
    Pet findById(Integer id);

    /**
     * Save a {@link Pet} to the data store, either inserting or updating it.
     * @param pet the {@link Pet} to save
     */
    void save(Pet pet);

}


答:
You just need to manually refresh your DataGrid.
Add this after your datasource is updated:</p>

```<code>dataGrid.Items.Refresh();
</code>```

Title: When I delete an item from the database and updatethe datagrid, I still see this object

Body:
You just need to manually refresh your DataGrid.
Add this after your datasource is updated:

dataGrid.Items.Refresh();