问:
Generic type conversion
I'm having some serious design problems due to generics issues. Perhaps someone has some suggestions.

EDIT: So, I know this is not usually done, but I've completely changed my example code, because I've realized that the original pseudo-code did not really explain my problem. The following code much more closely resembles the real example I am dealing with. I hope that my problem will be clearer from it. I apologize ahead that it is a bit lengthy, but from my experience, problems with generics usually show up when you try to build a more complex structure. So:

```<code>class Program
    {
        static void Main(string[] args)
        {
            IConnector<IService> connector = ConnectorBuilderFactory.NewBuilder<IService>("someEndpoint").MakeReliable().GetConnector();
            connector.Connect();
        }
    }

    public interface IService : IConnectionMaintainable
    {
        void DoSomething();
    }

    public interface IConnectionMaintainable
    {
        DateTime GetServerTime();
    }

    public interface IConnector<T>
    {
        T Channel { get; }
        void Connect();
        void Disconnect();
    }

    public interface IConnectorBuilder<T>
    {
        IConnector<T> GetConnector();
        IConnectorBuilder<T> MakeReliable();
        // ...more connector-configuration methods
    }

    public class ChannelWatchDog<T> where T : IConnectionMaintainable
    {
        private IConnector<T> connector;

        public ChannelWatchDog(IConnector<T> connector /*various other parameters*/)
        {
            this.connector = connector;
        }

        // ...methods that use connector's Connect, Disconnect, and GetServerTime methods
    }

    public class Connector<T> : IConnector<T>
    {
        private T channel;

        public Connector(string endpoint)
        {
            // ...build channel
        }

        public T Channel
        {
            get { return channel; }
        }

        public void Connect()
        {
            // ...connect to server
        }

        public void Disconnect()
        {
            // ...disconnect from server
        }
    }

    public class ConnectorBuilder<T> : IConnectorBuilder<T>
    {
        private string endpoint;

        public ConnectorBuilder(string endpoint)
        {
            this.endpoint = endpoint;
        }

        public IConnector<T> GetConnector()
        {
            Connector<T> connector = new Connector<T>(endpoint);

            // If reliability was requested, build the ChannelWatchDog: Following line does not compile:
            // ChannelWatchDog<T> watchDog = new ChannelWatchDog<T>(connector);

            return connector;
        }

        public IConnectorBuilder<T> MakeReliable()
        {
            // save various parameters required to build the ChannelWatchDog
            return this;
        }
    }

    public static class ConnectorBuilderFactory
    {
        public static IConnectorBuilder<T> NewBuilder<T>(string endpoint)
        {
            return new ConnectorBuilder<T>(endpoint);
        }
    }
</code>```

So, firstly, if you find the GetConnector method in the ConnectorBuilder class, you will see the commented line of code, which does not compile if uncommented. This line is the essence of my problem. The problem might be obvious from the code, but I will try to explain it anyway in case it is not:

I have an internal class (ChannelWatchDog) that needs an IConnector. But not just any IConnector, an IConnector, because other than the non-generic IConnector methods, it also needs the GetServerTime method from the IConnectionMaintainable interface.

To simplify construction of connectors, I hoped to implement a builder using the Expression Builder pattern (the IConnectionBuilder interface). However, I want to be able to construct any IConnector, not just IConnector<IConnectionMaintainable>. Therefore, I cannot constrain T in IConnectorBuilder in the same way as I constrain it for the ChannelWatchDog. Lacking this constraint, I have no way to build it when GetConnector is called. Adding the constraint to the MakeReliable method does not help.

So, essentially the reason I posted this question was that I wanted to do something that is apparently impossible. I wanted the ChannelWatchDog and ConnectorBuilder class to look something like this:

```<code>public class ChannelWatchDog
    {
        private IConnector<IConnectionMaintainable> connector;

        public ChannelWatchDog(IConnector<IConnectionMaintainable> connector /*various other parameters*/)
        {
            this.connector = connector;
        }

        // ...methods that use connector's Connect, Disconnect, and GetServerTime methods
    }

    public class ConnectorBuilder<T> : IConnectorBuilder<T>
    {
        private string endpoint;

        public ConnectorBuilder(string endpoint)
        {
            this.endpoint = endpoint;
        }

        public IConnector<T> GetConnector()
        {
            Connector<T> connector = new Connector<T>(endpoint);

            // If reliability was requested, build the ChannelWatchDog: Following line does not compile:
            ChannelWatchDog watchDog = new ChannelWatchDog((IConnector<IConnectionMaintainable>)connector);

            return connector;
        }

        public IConnectorBuilder<TReliable> MakeReliable<TReliable>() where TReliable : T, IConnectionMaintainable
        {
            // save various parameters required to build the ChannelWatchDog
            return (IConnectorBuilder<TReliable>)this;
        }
    }
</code>```

But the cast to IConnector fails at runtime.

So that was much more lengthy than I had originally intended. If you've gotten this far in reading then you already have my thanks :)
Any ideas are welcome, including restructuring the code.

BTW, Having not found a solution to this myself, I created different ConnectorBuilders (in this case, a ReliableConnectorBuilder) and different factory methods in the factory. But I don't like this solution much.

EDIT: Just to clarify and reiterate: I cannot constrain the IConnector nor the ConnectionBuilder because these need to support cases in which the IConnectionMaintainable interface is not implemented.

答:
If this line not compiling is the main problem:

```<code>// If reliability was requested, build the ChannelWatchDog: Following line does not compile:
        ChannelWatchDog watchDog = new ChannelWatchDog((IConnector<IConnectionMaintainable>)connector);
</code>```

then I think it should be

```<code>ChannelWatchDog watchDog = new ChannelWatchDog(connector);
</code>```

except that your runtime cast fails, I believe because the IConnector would need to be constrained:

```<code>public interface IConnector<T> where T:IConnectionMaintainable
{
    T Channel { get; }
    void Connect();
    void Disconnect();
}
</code>```

This is from the hip, and hopefully provides insight or hints. The constraint does compile as per linqpad.

Also it results in cascading constraint requirements so here's the rest of the code that does compile:

```<code>void Main()
{

}

// Define other methods and classes here
  public interface IConnectionMaintainable
{
    DateTime GetServerTime();
}

public interface IConnector<T> where T:IConnectionMaintainable
{
    T Channel { get; }
    void Connect();
    void Disconnect();
}

 public interface IConnectorBuilder<T> where T:IConnectionMaintainable
{
    IConnector<T> GetConnector();
    IConnectorBuilder<T> MakeReliable();
    // ...more connector-configuration methods
}
public class ChannelWatchDog
{
    private IConnector<IConnectionMaintainable> connector;

    public ChannelWatchDog(IConnector<IConnectionMaintainable> connector /*various other parameters*/)
    {
        this.connector = connector;
    }

    // ...methods that use connector's Connect, Disconnect, and GetServerTime methods
}

public class ConnectorBuilder<T> : IConnectorBuilder<T> where T:IConnectionMaintainable
{
    private string endpoint;

    public ConnectorBuilder(string endpoint)
    {
        this.endpoint = endpoint;
    }
    public IConnectorBuilder<T> MakeReliable()
    {
        // save various parameters required to build the ChannelWatchDog
        return this;
    }
    public IConnector<T> GetConnector()
    {
        Connector<T> connector = new Connector<T>(endpoint);

        // If reliability was requested, build the ChannelWatchDog: Following line does not compile:
        ChannelWatchDog watchDog = new ChannelWatchDog((IConnector<IConnectionMaintainable>)connector);

        return connector;
    }

    public IConnectorBuilder<TReliable> MakeReliable<TReliable>() where TReliable : T, IConnectionMaintainable
    {
        // save various parameters required to build the ChannelWatchDog
        return (IConnectorBuilder<TReliable>)this;
    }
}

 public class Connector<T> : IConnector<T> where T:IConnectionMaintainable
{
    private T channel;

    public Connector(string endpoint)
    {
        // ...build channel
    }

    public T Channel
    {
        get { return channel; }
    }

    public void Connect()
    {
        // ...connect to server
    }

    public void Disconnect()
    {
        // ...disconnect from server
    }
}
</code>```

Title: Generic type conversion

Body:
I'm having some serious design problems due to generics issues. Perhaps someone has some suggestions.

EDIT: So, I know this is not usually done, but I've completely changed my example code, because I've realized that the original pseudo-code did not really explain my problem. The following code much more closely resembles the real example I am dealing with. I hope that my problem will be clearer from it. I apologize ahead that it is a bit lengthy, but from my experience, problems with generics usually show up when you try to build a more complex structure. So:

class Program
    {
        static void Main(string[] args)
        {
            IConnector<IService> connector = ConnectorBuilderFactory.NewBuilder<IService>("someEndpoint").MakeReliable().GetConnector();
            connector.Connect();
        }
    }

    public interface IService : IConnectionMaintainable
    {
        void DoSomething();
    }

    public interface IConnectionMaintainable
    {
        DateTime GetServerTime();
    }

    public interface IConnector<T>
    {
        T Channel { get; }
        void Connect();
        void Disconnect();
    }

    public interface IConnectorBuilder<T>
    {
        IConnector<T> GetConnector();
        IConnectorBuilder<T> MakeReliable();
        // ...more connector-configuration methods
    }

    public class ChannelWatchDog<T> where T : IConnectionMaintainable
    {
        private IConnector<T> connector;

        public ChannelWatchDog(IConnector<T> connector /*various other parameters*/)
        {
            this.connector = connector;
        }

        // ...methods that use connector's Connect, Disconnect, and GetServerTime methods
    }

    public class Connector<T> : IConnector<T>
    {
        private T channel;

        public Connector(string endpoint)
        {
            // ...build channel
        }

        public T Channel
        {
            get { return channel; }
        }

        public void Connect()
        {
            // ...connect to server
        }

        public void Disconnect()
        {
            // ...disconnect from server
        }
    }

    public class ConnectorBuilder<T> : IConnectorBuilder<T>
    {
        private string endpoint;

        public ConnectorBuilder(string endpoint)
        {
            this.endpoint = endpoint;
        }

        public IConnector<T> GetConnector()
        {
            Connector<T> connector = new Connector<T>(endpoint);

            // If reliability was requested, build the ChannelWatchDog: Following line does not compile:
            // ChannelWatchDog<T> watchDog = new ChannelWatchDog<T>(connector);

            return connector;
        }

        public IConnectorBuilder<T> MakeReliable()
        {
            // save various parameters required to build the ChannelWatchDog
            return this;
        }
    }

    public static class ConnectorBuilderFactory
    {
        public static IConnectorBuilder<T> NewBuilder<T>(string endpoint)
        {
            return new ConnectorBuilder<T>(endpoint);
        }
    }

So, firstly, if you find the GetConnector method in the ConnectorBuilder class, you will see the commented line of code, which does not compile if uncommented. This line is the essence of my problem. The problem might be obvious from the code, but I will try to explain it anyway in case it is not:

I have an internal class (ChannelWatchDog) that needs an IConnector. But not just any IConnector, an IConnector, because other than the non-generic IConnector methods, it also needs the GetServerTime method from the IConnectionMaintainable interface.

To simplify construction of connectors, I hoped to implement a builder using the Expression Builder pattern (the IConnectionBuilder interface). However, I want to be able to construct any IConnector, not just IConnector<IConnectionMaintainable>. Therefore, I cannot constrain T in IConnectorBuilder in the same way as I constrain it for the ChannelWatchDog. Lacking this constraint, I have no way to build it when GetConnector is called. Adding the constraint to the MakeReliable method does not help.

So, essentially the reason I posted this question was that I wanted to do something that is apparently impossible. I wanted the ChannelWatchDog and ConnectorBuilder class to look something like this:

public class ChannelWatchDog
    {
        private IConnector<IConnectionMaintainable> connector;

        public ChannelWatchDog(IConnector<IConnectionMaintainable> connector /*various other parameters*/)
        {
            this.connector = connector;
        }

        // ...methods that use connector's Connect, Disconnect, and GetServerTime methods
    }

    public class ConnectorBuilder<T> : IConnectorBuilder<T>
    {
        private string endpoint;

        public ConnectorBuilder(string endpoint)
        {
            this.endpoint = endpoint;
        }

        public IConnector<T> GetConnector()
        {
            Connector<T> connector = new Connector<T>(endpoint);

            // If reliability was requested, build the ChannelWatchDog: Following line does not compile:
            ChannelWatchDog watchDog = new ChannelWatchDog((IConnector<IConnectionMaintainable>)connector);

            return connector;
        }

        public IConnectorBuilder<TReliable> MakeReliable<TReliable>() where TReliable : T, IConnectionMaintainable
        {
            // save various parameters required to build the ChannelWatchDog
            return (IConnectorBuilder<TReliable>)this;
        }
    }

But the cast to IConnector fails at runtime.

So that was much more lengthy than I had originally intended. If you've gotten this far in reading then you already have my thanks :)
Any ideas are welcome, including restructuring the code.

BTW, Having not found a solution to this myself, I created different ConnectorBuilders (in this case, a ReliableConnectorBuilder) and different factory methods in the factory. But I don't like this solution much.

EDIT: Just to clarify and reiterate: I cannot constrain the IConnector nor the ConnectionBuilder because these need to support cases in which the IConnectionMaintainable interface is not implemented.

Body:
If this line not compiling is the main problem:

// If reliability was requested, build the ChannelWatchDog: Following line does not compile:
        ChannelWatchDog watchDog = new ChannelWatchDog((IConnector<IConnectionMaintainable>)connector);

then I think it should be

ChannelWatchDog watchDog = new ChannelWatchDog(connector);

except that your runtime cast fails, I believe because the IConnector would need to be constrained:

public interface IConnector<T> where T:IConnectionMaintainable
{
    T Channel { get; }
    void Connect();
    void Disconnect();
}

This is from the hip, and hopefully provides insight or hints. The constraint does compile as per linqpad.

Also it results in cascading constraint requirements so here's the rest of the code that does compile:

void Main()
{

}

// Define other methods and classes here
  public interface IConnectionMaintainable
{
    DateTime GetServerTime();
}

public interface IConnector<T> where T:IConnectionMaintainable
{
    T Channel { get; }
    void Connect();
    void Disconnect();
}

 public interface IConnectorBuilder<T> where T:IConnectionMaintainable
{
    IConnector<T> GetConnector();
    IConnectorBuilder<T> MakeReliable();
    // ...more connector-configuration methods
}
public class ChannelWatchDog
{
    private IConnector<IConnectionMaintainable> connector;

    public ChannelWatchDog(IConnector<IConnectionMaintainable> connector /*various other parameters*/)
    {
        this.connector = connector;
    }

    // ...methods that use connector's Connect, Disconnect, and GetServerTime methods
}

public class ConnectorBuilder<T> : IConnectorBuilder<T> where T:IConnectionMaintainable
{
    private string endpoint;

    public ConnectorBuilder(string endpoint)
    {
        this.endpoint = endpoint;
    }
    public IConnectorBuilder<T> MakeReliable()
    {
        // save various parameters required to build the ChannelWatchDog
        return this;
    }
    public IConnector<T> GetConnector()
    {
        Connector<T> connector = new Connector<T>(endpoint);

        // If reliability was requested, build the ChannelWatchDog: Following line does not compile:
        ChannelWatchDog watchDog = new ChannelWatchDog((IConnector<IConnectionMaintainable>)connector);

        return connector;
    }

    public IConnectorBuilder<TReliable> MakeReliable<TReliable>() where TReliable : T, IConnectionMaintainable
    {
        // save various parameters required to build the ChannelWatchDog
        return (IConnectorBuilder<TReliable>)this;
    }
}

 public class Connector<T> : IConnector<T> where T:IConnectionMaintainable
{
    private T channel;

    public Connector(string endpoint)
    {
        // ...build channel
    }

    public T Channel
    {
        get { return channel; }
    }

    public void Connect()
    {
        // ...connect to server
    }

    public void Disconnect()
    {
        // ...disconnect from server
    }
}


来源: stackexchange

问:
Removing inputs leads to incorrect values
Ok, so the problem is pretty simple, but hard to explain.

I'm making an InputGenerator component, which generates a list of inputs.

Each generated input has a corresponding "remove" button next to it. The two elements (the input and the button) are wrapped in a div inside a map function. The div has a unique key prop. It looks like this (this is the whole component's jsx):

```<code>        <div style={[InputGenerator.style.wrapper]}>
            <div className="container" style={InputGenerator.style.container}>
                {this.state.inputs.map((input, idx) => {
                    return (
                        <div key={idx} style={[
                            InputGenerator.style.row,
                            InputGenerator.count > 1 && idx > 0 ? InputGenerator.style.input.pushTop : {},
                        ]}>
                            <InputText
                                id={input.id}
                                name={input.name}
                                placeholder={input.placeholder}
                                style={input.style}
                            />
                            <Button
                                style={InputGenerator.style.remove}
                                type={Button.TYPES.BASIC}
                                icon="ion-close-round"
                                onClick={this.remove.bind(this, input.id)}
                            />
                        </div>
                    );
                })}
            </div>

            <div className="controls" style={InputGenerator.style.controls}>
                <Button icon="ion-plus" type={Button.TYPES.PRIMARY} title="Add ingredient" onClick={this.add.bind(this)}/>
            </div>
        </div>
</code>```

As you may see, all the inputs are kept in the this.state object and each one is given an unique id.

Here are the are add and remove methods:

add():

```<code>add() {
    InputGenerator.count++;

    const newInput = {
        id: this.id,
        name: this.props.name,
        placeholder: this.props.placeholder,
        style: this.style,
        value: '',
    };

    const inputs = this.state.inputs;

    inputs.push(newInput);

    this.setState({ inputs });
}
</code>```

remove():

```<code>remove(id) {
    this.setState({
        inputs: this.state.inputs.filter(i => i.id !== id),
    });
}
</code>```

The problem is:

I generate three inputs (using the add button)

I put random values in the inputs (e.g: 1, 2, 3)

I click on the remove button, corresponding to the first element (with value 1)

Result: Two input items with values 1 and 2

Expected: Two input items with values 2 and 3

The problem: I suggest that the key prop on the wrapping div is not enough for react to keep track of the input's values.

So, I'm open for ideas and suggestions how to proceed.

Here's an isolated sandbox to play around with my component and see the "bug" in action: https://codesandbox.io/s/5985AKxRB

Thanks in advance! :)

答:
The issue you facing is because you are not handling state properly. You need to update state when you change input value.

```<code>  handleChange(index,event) {
    let inputs = this.state.inputs;
    inputs[index].value = event.target.value;
    this.setState({inputs:inputs})
  }
</code>```

DEMO : DEMO

Here is the updated code:

```<code>import React, { Component } from 'react';
    import { render } from 'react-dom';
    import Hello from './Hello';

    const styles = {
      fontFamily: 'sans-serif',
      textAlign: 'center',
    };

    const App = () =>
      <div style={styles}>
        <InputGenerator />
      </div>;

    class InputGenerator extends Component {
      constructor() {
        super();
        this.state = {
          inputs: [],
        };
      }
      componentWillMount() {
        this.add();
      }
      handleChange(index,event) {
        let inputs = this.state.inputs;
        inputs[index].value = event.target.value;
        this.setState({inputs:inputs})
      }
      add() {
        InputGenerator.count++;

        const newInput = {
          id: this.id,
          name: this.props.name,
          placeholder: this.props.placeholder,
          style: this.style,
          value: '',
        };

        const inputs = this.state.inputs;

        inputs.push(newInput);

        this.setState({ inputs });
      }
      get id() {
        if (this.props.id) {
          return `${this.props.id}-${InputGenerator.count}`;
        }

        return `InputGeneratorItem-${InputGenerator.count}`;
      }
      get style() {
        return [];
      }
      remove(id) {

        var state = this.state;
        state.inputs = state.inputs.filter(i => i.id !== id);
        this.setState({
          inputs: state.inputs
        });
      }
      render() {
        return (
          <div>
            <div className="container">
              {this.state.inputs.map((input, idx) => {
                return (
                  <div key={idx}>
                    <input
                      id={input.id}
                      name={input.name}
                      value = {input.value}
                      onChange={this.handleChange.bind(this,idx)}
                      placeholder={input.placeholder}
                    />
                    <button onClick={this.remove.bind(this, input.id)}>
                      Remove
                    </button>
                  </div>
                );
              })}
            </div>

            <div className="controls">
              <button onClick={this.add.bind(this)}>Add</button>
            </div>
          </div>
        );
      }
    }

    InputGenerator.count = 0;

    render(<App />, document.getElementById('root'));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Ok, so the problem is pretty simple, but hard to explain.

I'm making an InputGenerator component, which generates a list of inputs.

Each generated input has a corresponding "remove" button next to it. The two elements (the input and the button) are wrapped in a div inside a map function. The div has a unique key prop. It looks like this (this is the whole component's jsx):

                {this.state.inputs.map((input, idx) => {
                    return (

 1 && idx > 0 ? InputGenerator.style.input.pushTop : {},
                        ]}>
                            <InputText
                                id={input.id}
                                name={input.name}
                                placeholder={input.placeholder}
                                style={input.style}
                            />
                            <Button
                                style={InputGenerator.style.remove}
                                type={Button.TYPES.BASIC}
                                icon="ion-close-round"
                                onClick={this.remove.bind(this, input.id)}
                            />

                    );
                })}

                <Button icon="ion-plus" type={Button.TYPES.PRIMARY} title="Add ingredient" onClick={this.add.bind(this)}/>

As you may see, all the inputs are kept in the this.state object and each one is given an unique id.

Here are the are add and remove methods:

add():

add() {
    InputGenerator.count++;

    const newInput = {
        id: this.id,
        name: this.props.name,
        placeholder: this.props.placeholder,
        style: this.style,
        value: '',
    };

    const inputs = this.state.inputs;

    inputs.push(newInput);

    this.setState({ inputs });
}

remove():

remove(id) {
    this.setState({
        inputs: this.state.inputs.filter(i => i.id !== id),
    });
}

The problem is:

I generate three inputs (using the add button)

I put random values in the inputs (e.g: 1, 2, 3)

I click on the remove button, corresponding to the first element (with value 1)

Result: Two input items with values 1 and 2

Expected: Two input items with values 2 and 3

The problem: I suggest that the key prop on the wrapping div is not enough for react to keep track of the input's values.

So, I'm open for ideas and suggestions how to proceed.

Here's an isolated sandbox to play around with my component and see the "bug" in action: https://codesandbox.io/s/5985AKxRB

Thanks in advance! :)

Body:
The issue you facing is because you are not handling state properly. You need to update state when you change input value.

  handleChange(index,event) {
    let inputs = this.state.inputs;
    inputs[index].value = event.target.value;
    this.setState({inputs:inputs})
  }

DEMO : DEMO

Here is the updated code:

import React, { Component } from 'react';
    import { render } from 'react-dom';
    import Hello from './Hello';

    const styles = {
      fontFamily: 'sans-serif',
      textAlign: 'center',
    };

    const App = () =>
      <div style={styles}>
        <InputGenerator />
      </div>;

    class InputGenerator extends Component {
      constructor() {
        super();
        this.state = {
          inputs: [],
        };
      }
      componentWillMount() {
        this.add();
      }
      handleChange(index,event) {
        let inputs = this.state.inputs;
        inputs[index].value = event.target.value;
        this.setState({inputs:inputs})
      }
      add() {
        InputGenerator.count++;

        const newInput = {
          id: this.id,
          name: this.props.name,
          placeholder: this.props.placeholder,
          style: this.style,
          value: '',
        };

        const inputs = this.state.inputs;

        inputs.push(newInput);

        this.setState({ inputs });
      }
      get id() {
        if (this.props.id) {
          return `${this.props.id}-${InputGenerator.count}`;
        }

        return `InputGeneratorItem-${InputGenerator.count}`;
      }
      get style() {
        return [];
      }
      remove(id) {

        var state = this.state;
        state.inputs = state.inputs.filter(i => i.id !== id);
        this.setState({
          inputs: state.inputs
        });
      }
      render() {
        return (
          <div>
            <div className="container">
              {this.state.inputs.map((input, idx) => {
                return (
                  <div key={idx}>
                    <input
                      id={input.id}
                      name={input.name}
                      value = {input.value}
                      onChange={this.handleChange.bind(this,idx)}
                      placeholder={input.placeholder}
                    />
                    <button onClick={this.remove.bind(this, input.id)}>
                      Remove
                    </button>
                  </div>
                );
              })}
            </div>

            <div className="controls">
              <button onClick={this.add.bind(this)}>Add</button>
            </div>
          </div>
        );
      }
    }

    InputGenerator.count = 0;

    render(<App />, document.getElementById('root'));


问:
m2e-wtp error: <path>/target/m2e-wtp/web-resources/META-INF/MANIFEST.MF (No such file or directory)
I use m2e 1.2.0 and m2e-wtp 0.16.0, and occasionally my Eclipse build fails with the error:

```<code><path>/target/m2e-wtp/web-resources/META-INF/MANIFEST.MF (No such file or directory)
</code>```

The problem can be temporarily solved by doing a Maven->Update project..., but the error will come back after a while. Not sure what exactly the trigger is....

Any suggestions on how to fix the issue permanently?

[Edit] I found that the issue is triggered when I build the project externally using the Maven command line directly. This will remove the default MANIFEST.MF that m2e-wtp generates, and it apparently doesn't get regenerated until you do a rebuild in Eclipse.

答:
To make sure resources are properly refreshed, as maven cleans up target, you can setup maven build to automatically refresh project + target folder, etc.,.

Check the option to automatically refresh resources in your maven build

Body:
I use m2e 1.2.0 and m2e-wtp 0.16.0, and occasionally my Eclipse build fails with the error:

<path>/target/m2e-wtp/web-resources/META-INF/MANIFEST.MF (No such file or directory)

The problem can be temporarily solved by doing a Maven->Update project..., but the error will come back after a while. Not sure what exactly the trigger is....

Any suggestions on how to fix the issue permanently?

[Edit] I found that the issue is triggered when I build the project externally using the Maven command line directly. This will remove the default MANIFEST.MF that m2e-wtp generates, and it apparently doesn't get regenerated until you do a rebuild in Eclipse.


问:
How to set setContentView(); to GONE
I have my main layout which is, setContentView(R.layout.activity_detail),

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);
</code>```

how do i set the visibility of my layout as GONE within the below code

```<code>   if (extras.get("NAME").equals("Blog")) {
        Intent blog = new Intent(DetailActivity.this, ReportActivity.class);
        blog.putExtra("URL", "url");
        blog.putExtra("filename", "Blog");
        startActivity(blog);

  // I want to Perform the operation here

        }
</code>```

答:
set you content view in else part </p>

```<code>   if (extras.get("NAME").equals("Blog")) {
    Intent blog = new Intent(DetailActivity.this, ReportActivity.class);
    blog.putExtra("URL", "url");
    blog.putExtra("filename", "Blog");
    startActivity(blog);

    }else{
        setContentView(R.layout.activity_detail);
    }
</code>```

Title: How to set setContentView(); to GONE

Body:
I have my main layout which is, setContentView(R.layout.activity_detail),

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);

how do i set the visibility of my layout as GONE within the below code

   if (extras.get("NAME").equals("Blog")) {
        Intent blog = new Intent(DetailActivity.this, ReportActivity.class);
        blog.putExtra("URL", "url");
        blog.putExtra("filename", "Blog");
        startActivity(blog);

  // I want to Perform the operation here

        }

Body:
set you content view in else part

   if (extras.get("NAME").equals("Blog")) {
    Intent blog = new Intent(DetailActivity.this, ReportActivity.class);
    blog.putExtra("URL", "url");
    blog.putExtra("filename", "Blog");
    startActivity(blog);

    }else{
        setContentView(R.layout.activity_detail);
    }


问:
calculate minimum value from row calculation in pandas
I have a list of throughput values in one column of a pandas DataFrame.  I want to calculate a value's variation from a threshold as a percent of that threshold.

So if I have thresholds at 2 and 7.  I'd want to calculate the minimum of the following functions.

```<code>(df.throughput - 2)/2
(df.throughput - 7)/7

x   throughtput
1   3
4   4
7   9
</code>```

I tried using the following to create a new column, but I keep getting an error.  I fell like there's something really obvious i'm missing here.

```<code>df['pct'] =  np.min(  (df.throughput-2)/2,  (df.throughput - 7)/7  )
df['pct'] =  np.min(  (df['throughput']-2)/2,  (df['throughput'] - 7)/7  )
'Series' objects are mutable, thus they cannot be hashed
</code>```

Body:
I have a list of throughput values in one column of a pandas DataFrame.  I want to calculate a value's variation from a threshold as a percent of that threshold.

So if I have thresholds at 2 and 7.  I'd want to calculate the minimum of the following functions.

(df.throughput - 2)/2
(df.throughput - 7)/7

x   throughtput
1   3
4   4
7   9

I tried using the following to create a new column, but I keep getting an error.  I fell like there's something really obvious i'm missing here.

df['pct'] =  np.min(  (df.throughput-2)/2,  (df.throughput - 7)/7  )
df['pct'] =  np.min(  (df['throughput']-2)/2,  (df['throughput'] - 7)/7  )
'Series' objects are mutable, thus they cannot be hashed

Body:
Try this:

df['pct'] = [min(i,j) for i,j in (zip((df.throughput - 2)/2,(df.throughput - 7)/7))]
df

output will be:

    throughput  x   pct
0   3           1   -0.571429
1   4           4   -0.428571
2   9           7   0.285714

or:

df['cal_1'] = (df.throughput - 2)/2
df['cal_2'] = (df.throughput - 7)/7
df['pct'] = df[['cal_1','cal_2']].min(axis=1)
df[['x','throughput','pct']]

output will be:

    x   throughput  pct
0   1   3           -0.571429
1   4   4           -0.428571
2   7   9           0.285714


问:
Spring batch single threaded reader and multi threaded writer
Tried to find if this was asked before but couldn't.

Here is the problem. The following has to be achieved via Spring batch
There is one file to be read and processed. The item reader is not thread safe.
The plan is to have multithreaded homogenous processors and multithreaded homogenous writers injest items read by a single threaded reader.

Kind of like below:

```<code>        ----------> Processor #1 ----------> Writer #1
       |
    Reader -------> Processor #2 ----------> Writer #2
       |
        ----------> Processor #3 ----------> Writer #3
</code>```

Tried AsyncItemProcessor and AsyncItemWriter, but holding debug point on processor resulted in reader not being executed until the point was released i.e. single threaded processing.

Task executor was tried like below:

```<code><tasklet task-executor="taskExecutor" throttle-limit="20">
</code>```

Multiple threads on the reader were launched.

Synchronising the reader also didn't work.

I tried to read about partitioner but it seemed complex.

Is there an annotation to mark the reader as single threaded? Would pushing read data to Global context be a good idea?

Please guide towards a solution.

答:
Came across this with a similar problem at hand.

Here's how I am doing it at the moment. As @mminella suggested, synchronized itemReader with the flatfileItemReader as delegate. This works with decent performance. The code writes about ~4K records per second at the moment but the speed doesn't entirely depend on the design, other attributes contribute as well.

Tried other approaches to increase performance, both kind of failed.

Custom Synchronized ItemReader that aggregates with FlatFileItemReader as delegate but I ended up with maintaining a lot a state that caused performance drop. Maybe the code needed optimization or Synchronization is just faster.

Fired each insert PreparedStatement batch in different thread but didn't increase much performance but I still am counting on this in case I run into an environment where individual threads for batches would result in significant performance boost.

Body:
Tried to find if this was asked before but couldn't.

Here is the problem. The following has to be achieved via Spring batch
There is one file to be read and processed. The item reader is not thread safe.
The plan is to have multithreaded homogenous processors and multithreaded homogenous writers injest items read by a single threaded reader.

Kind of like below:

        ----------> Processor #1 ----------> Writer #1
       |
    Reader -------> Processor #2 ----------> Writer #2
       |
        ----------> Processor #3 ----------> Writer #3

Tried AsyncItemProcessor and AsyncItemWriter, but holding debug point on processor resulted in reader not being executed until the point was released i.e. single threaded processing.

Task executor was tried like below:

<tasklet task-executor="taskExecutor" throttle-limit="20">

Multiple threads on the reader were launched.

Synchronising the reader also didn't work.

I tried to read about partitioner but it seemed complex.

Is there an annotation to mark the reader as single threaded? Would pushing read data to Global context be a good idea?

Please guide towards a solution.


问:
How do you use the jquery 'load' method to load a page fragment when passing a variable?
Not sure if this has been asked, but here it goes, given the following code...

```<code>$('#infoPane').load('showInfo.php #info');
</code>```

How do a pass variable to the page yet only just load the page fragment?

```<code>$('#imgPane').load('showInfo.php?q='+$q+ '#picture');
</code>```

The above code does not work so any help would be appreciated

答:
I do not know how jQuery works here, exactly, but using the URL hash as ID seems odd. It should probably look like this:</p>

```<code>$('#imgPane').load('showInfo.php?q='+$q+' #picture');
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Not sure if this has been asked, but here it goes, given the following code...

$('#infoPane').load('showInfo.php #info');

How do a pass variable to the page yet only just load the page fragment?

$('#imgPane').load('showInfo.php?q='+$q+ '#picture');

The above code does not work so any help would be appreciated

Body:
I do not know how jQuery works here, exactly, but using the URL hash as ID seems odd. It should probably look like this:

$('#imgPane').load('showInfo.php?q='+$q+' #picture');


问:
How can I find duplicates in a list, and delete all duplicates except for a certain one?
I have a sorted list dataPts that is sorted based on the angle each point makes with the minimum Y value minY in dataPts, such as [(0, 0), (10, 10), (20, 20) ... ] (0, 0) being minY.

Then I create a new list angles which is a list of all those angles, for instance  [0, 45, 45, ...].

You will notice that angles contains duplicate values, for instance 45, 45,. What I want to do is locate the points in dataPts that share the same angle. I then want to delete those points, EXCEPT the one that is the furthest distance from  minY using a function that returns a value.

For example, (10, 10) and (20, 20) both have corresponding values in angles, which is 45. How can I pick out the value with greater distance to minY which is (20, 20) and delete (10, 10)?

答:
Try this

```<code>angles1 = [(0, 0), (10, 10), (20, 20)]
angles = [0, 45, 45]
dumy = {}
duplicates = []
for i,items in enumerate(angles):
    if (items not in dumy):
        dumy[items] = ""
    else:
        duplicates.append(i)
        if((angles[i-1] == items) and i-1 not in duplicates):
            duplicates.append(i-1)

for i in (duplicates):
    del angles1[i]
</code>```

Suppose if you want to remove the only duplicates,  try the following code

```<code>for i,items in enumerate(angles):
    if (items not in dumy):
    dumy[items] = ""
    else:
    duplicates.append(i)
    del angles1[i]
    if((angles[i-1] == items) and i-1 not in duplicates):
        del angles1[i-1]
</code>```

Body:
Try this

angles1 = [(0, 0), (10, 10), (20, 20)]
angles = [0, 45, 45]
dumy = {}
duplicates = []
for i,items in enumerate(angles):
    if (items not in dumy):
        dumy[items] = ""
    else:
        duplicates.append(i)
        if((angles[i-1] == items) and i-1 not in duplicates):
            duplicates.append(i-1)

for i in (duplicates):
    del angles1[i]

Suppose if you want to remove the only duplicates,  try the following code

for i,items in enumerate(angles):
    if (items not in dumy):
    dumy[items] = ""
    else:
    duplicates.append(i)
    del angles1[i]
    if((angles[i-1] == items) and i-1 not in duplicates):
        del angles1[i-1]


问:
Java for loop i++ as a string
Let's say we have a for loop

```<code>for(int i = 0; i < 10; i++) {
    ...
}
</code>```

What format is the i++ in?

I have a String increment = "i++" which tells me how much to increment i by.
But when I just directly try and put the increment string as an incrementor it doesn't work. I tried the below but it doesn't work.

```<code>for(int i = 0; i < 10; increment) {
    ...
}
</code>```

How can I make this work?

答:
You can simply get increment count in a string if you want to do increment dynamically, instead of whole increment statement. Here is an example:</p>

```<code>String inc = "2";
String max = "10";
for(int i = 0; i < Integer.valueOf(max); i=i+Integer.valueOf(inc)) {
    System.out.println(i);
}
</code>```

Title: Java for loop i++ as a string

Body:
Let's say we have a for loop

for(int i = 0; i < 10; i++) {
    ...
}

What format is the i++ in?

I have a String increment = "i++" which tells me how much to increment i by.
But when I just directly try and put the increment string as an incrementor it doesn't work. I tried the below but it doesn't work.

for(int i = 0; i < 10; increment) {
    ...
}

How can I make this work?

Body:
You can simply get increment count in a string if you want to do increment dynamically, instead of whole increment statement. Here is an example:

String inc = "2";
String max = "10";
for(int i = 0; i < Integer.valueOf(max); i=i+Integer.valueOf(inc)) {
    System.out.println(i);
}


问:
Why would SQL be very slow when doing updates?
Suddenly doing updates into a few tables have gotten 10 times slower than they used to be.  What are some good recommendations to determine root cause and optimization?  Could it be that indexing certain columns are causing updates to be slow?  Any other recommendations?

I guess more important than guesses would be help on the process of identifying the root cause or metrics around performance.

Is there anything in Fluent NHibernate that you can use to help identify the root cause of performance issues?

答: And as ever, running up SQL profiler on your SQL server will give you a good idea of exactly at what point your bottleneck is.</p>


问:
In c# , how to iterate IEnumerable in multithreading environment
I am in this situation that there is a large dictionary that is randomly updated by one thread at a fairly high frequency, and there is another thread that tries to take a snapshot of the dictionary to save as history.
I currently using something like this:

```<code>Dictionary<string, object> dict = new Dictionary<string, object>();
var items = dict.Values.ToList();
</code>```

This works fine for most of the time, except it occasionally throws:

System.InvalidOperationException: Collection was modified; enumeration
  operation may not execute.

I understand why this happen, but I don't know what can I do to avoid the collection modified error.

What is the best approach to iterate such collection?

I also tried ConcurrentDictionary, but no luck.
Why? Is ConcurrentDictionary thread safe only at item level?

答:
An ImmutableDictionary might be appropriate for you, as it supports scalable multi-threading and snapshotting as part of its basic feature-set.

```<code>// initialize.
ImmutableDictionary<string, int> dict = ImmutableDictionary.Create<string,int>();

// create a new dictionary with "foo" key added.
ImmutableDictionary<string, int> newdict = dict.Add("foo", 0);

// replace dict, thread-safe, with a new dictionary with "bar" added.
// note this is using dict, not newdict, so there is no "foo" in it.
ImmutableInterlocked.TryAdd(ref dict, "bar", 1);

// take a snapshot, thread-safe.
ImmutableDictionary<string,int> snapshot = dict;
</code>```

The immutable nature means that the dictionary can never change -- you can only add a value by creating a new dictionary.  And because of this property, you take a "snapshot" of it by simply keeping a reference around from the point you want to snapshot.

It is optimized under the hood to be efficient, not copying the entire thing for every operation. That said, for other operations it isn't as efficient as ConcurrentDictionary, but it's all a trade-off in what you want. For instance, a ConcurrentDictionary can be concurrently enumerated but it's impossible to enumerate a snapshot of it.

Body:
I am in this situation that there is a large dictionary that is randomly updated by one thread at a fairly high frequency, and there is another thread that tries to take a snapshot of the dictionary to save as history.
I currently using something like this:

Dictionary<string, object> dict = new Dictionary<string, object>();
var items = dict.Values.ToList();

This works fine for most of the time, except it occasionally throws:

System.InvalidOperationException: Collection was modified; enumeration
  operation may not execute.

I understand why this happen, but I don't know what can I do to avoid the collection modified error.

What is the best approach to iterate such collection?

I also tried ConcurrentDictionary, but no luck.
Why? Is ConcurrentDictionary thread safe only at item level?

Body:
An ImmutableDictionary might be appropriate for you, as it supports scalable multi-threading and snapshotting as part of its basic feature-set.

// initialize.
ImmutableDictionary<string, int> dict = ImmutableDictionary.Create<string,int>();

// create a new dictionary with "foo" key added.
ImmutableDictionary<string, int> newdict = dict.Add("foo", 0);

// replace dict, thread-safe, with a new dictionary with "bar" added.
// note this is using dict, not newdict, so there is no "foo" in it.
ImmutableInterlocked.TryAdd(ref dict, "bar", 1);

// take a snapshot, thread-safe.
ImmutableDictionary<string,int> snapshot = dict;

The immutable nature means that the dictionary can never change -- you can only add a value by creating a new dictionary.  And because of this property, you take a "snapshot" of it by simply keeping a reference around from the point you want to snapshot.

It is optimized under the hood to be efficient, not copying the entire thing for every operation. That said, for other operations it isn't as efficient as ConcurrentDictionary, but it's all a trade-off in what you want. For instance, a ConcurrentDictionary can be concurrently enumerated but it's impossible to enumerate a snapshot of it.


问:
Python OSC installation using pip
I am trying to install the Python package OSC using pip. It keeps showing up errors of:

Could not find a version that satisfies the requirement osc

I have pip 9.0.1. Do you know this error? How can I install OSC?

Thanks,

Miya

答:
I'm guessing you are trying to install Open Sound Control (OSC). Here is the Python package on PyPI: https://pypi.python.org/pypi/python-osc

To install: pip install python-osc

Title: Python OSC installation using pip


问:
Only allow access to action if redirected from specific action
Is there a good way to restrict the access to an action, so you can only access it, if you were redirected from another action. For example:</p>

```<code>    [HttpPost]
    public virtual ActionResult Create(MyViewModel vm)
    {
        if (ModelState.IsValid)
        {
            // do some work

            return RedirectToAction("CreateSuccess");
        }
        else
        {
            return View(vm);
        }
    }

    public virtual ActionResult CreateSuccess()
    {
        // only allow execution if you were redirected from Action "Create"
    }
</code>```

答:
First solution

You could just do this:

```<code>[HttpPost]
public virtual ActionResult Create(MyViewModel vm)
{
    if (ModelState.IsValid)
    {
        // do some work
        return this.CreateSuccess();
    }
    else
    {
        return View(vm);
    }
}

[NonAction]
public virtual ActionResult CreateSuccess()
{
    // do what's needed
}
</code>```

This last method will only be executed from other action methods. But it can't be executed per se.

Second solution

You could solve this by creating a custom action method selector attribute as well if you know you can reuse this. You could write a custom action method selector attribute that checks request referrer and uses appropriate method.

Read about custom action selector attributes.

Body:
Is there a good way to restrict the access to an action, so you can only access it, if you were redirected from another action. For example:

    [HttpPost]
    public virtual ActionResult Create(MyViewModel vm)
    {
        if (ModelState.IsValid)
        {
            // do some work

            return RedirectToAction("CreateSuccess");
        }
        else
        {
            return View(vm);
        }
    }

    public virtual ActionResult CreateSuccess()
    {
        // only allow execution if you were redirected from Action "Create"
    }

Body:
First solution

You could just do this:

[HttpPost]
public virtual ActionResult Create(MyViewModel vm)
{
    if (ModelState.IsValid)
    {
        // do some work
        return this.CreateSuccess();
    }
    else
    {
        return View(vm);
    }
}

[NonAction]
public virtual ActionResult CreateSuccess()
{
    // do what's needed
}

This last method will only be executed from other action methods. But it can't be executed per se.

Second solution

You could solve this by creating a custom action method selector attribute as well if you know you can reuse this. You could write a custom action method selector attribute that checks request referrer and uses appropriate method.

Read about custom action selector attributes.


问:
Find a key in array of object
The input is JSON array of object.

```<code>[
    {
        "name": "JOHN",
        "age": "90",
        "ID": "123",
        "country": "UK",
        "email": "john@test.com"
    }, {
        "name": "PETER",
        "age": "10",
        "ID": "456",
        "country": "",
    }
]
</code>```

What is the best way in Javascript to find a key in all of the arrays and return ok if it exists. For example, does "name" exist? Yes, JOHN and PETER. Does "email" exist? Yes, john@test.com. Does "city" exist? No.

Thank you for giving tips!

答:
if you like a magic-oneliner:</p>

```<code>your_array = [
    {
        "name": "JOHN",
        "age": "90",
        "ID": "123",
        "country": "UK",
        "email": "john@test.com"
    }, {
        "name": "PETER",
        "age": "10",
        "ID": "456",
        "country": "",
    }
]

your_array.some(x => 'email' in x)
your_array.some(x => 'name' in x)
your_array.some(x => 'city' in x)
</code>```

Title: Find a key in array of object

Body:
The input is JSON array of object.

[
    {
        "name": "JOHN",
        "age": "90",
        "ID": "123",
        "country": "UK",
        "email": "john@test.com"
    }, {
        "name": "PETER",
        "age": "10",
        "ID": "456",
        "country": "",
    }
]

What is the best way in Javascript to find a key in all of the arrays and return ok if it exists. For example, does "name" exist? Yes, JOHN and PETER. Does "email" exist? Yes, john@test.com. Does "city" exist? No.

Thank you for giving tips!

Body:
if you like a magic-oneliner:

your_array = [
    {
        "name": "JOHN",
        "age": "90",
        "ID": "123",
        "country": "UK",
        "email": "john@test.com"
    }, {
        "name": "PETER",
        "age": "10",
        "ID": "456",
        "country": "",
    }
]

your_array.some(x => 'email' in x)
your_array.some(x => 'name' in x)
your_array.some(x => 'city' in x)


问:
Filling list nan values
How to fill nan values with 0's in a list. I can do it for dataframes but don't know how to do it for lists?

```<code>listname=listname.fillna(0)
</code>```

This isn't working.

答:
You can convert to a pandas series and back to a list

```<code>pd.Series(listname).fillna(0).tolist()
</code>```

Consider the list listname

```<code>listname = [1, np.nan, 2, None, 3]
</code>```

Then

```<code>pd.Series(listname, dtype=object).fillna(0).tolist()

[1, 0, 2, 0, 3]
</code>```

Title: Filling list nan values

Body:
How to fill nan values with 0's in a list. I can do it for dataframes but don't know how to do it for lists?

listname=listname.fillna(0)

This isn't working.

Body:
You can convert to a pandas series and back to a list

pd.Series(listname).fillna(0).tolist()

Consider the list listname

listname = [1, np.nan, 2, None, 3]

Then

pd.Series(listname, dtype=object).fillna(0).tolist()

[1, 0, 2, 0, 3]


问:
when use onerror, ontimeout properties? (XMLHttpRequest)
I use XMLHttpRequest class to send payload data from web client to web server.

I want to handle errors such as follows...

REQUEST TIMEOUT (CONNECTION TIMEOUT)

500, INTERNAL SERVER ERROR

502, BAD GATEWAY

503, SERVICE UNAVAILABLE

I do not know the obvious usage of onstatechange, onerror, ontimeout properties.
I do not know if onreadystatechange alone can catch those errors.

Also, if I have to use onerror, ontimeout, I want to know what is the difference with onreadystatechange.

答:
onreadystatechange is the function that is triggered when the xmlhttprequest object state changes, similar to the onclick.

readystate is used to catch the xmlhttprequest object state , it has five values listening the server response state

status is the status code returned after the server responds successfully.
such as 500, INTERNAL SERVER ERROR.....


问:
How to get the exact authorization status of location service?
If user has explicitly denied authorization for this application, or location services are disabled in Settings, it will return Denied status. How can I know the exact reason of it?</p>

答:
Swift:

I've made this two function to check for each case

If user explicitly denied authorization for your app only you can check it like this,

```<code>class func isLocationDisableForMyAppOnly() -> Bool {
    if CLLocationManager.locationServicesEnabled() && CLLocationManager.authorizationStatus() == .denied {
        return true
    }
    return false
}
</code>```

If location services are disabled in Settings,

```<code>class func userLocationAvailable() -> Bool {
    return CLLocationManager.locationServicesEnabled()
}
</code>```

And I'm using it like this,

```<code>if UserLocation.userLocationAvailable() {
        //.... Get location.
} else {
    if UserLocation.isLocationDisableForMyAppOnly() {
        //... Location not available. Denied accessing location.
    } else {
        //... Location not available. Enable location services from settings.
    }
}
</code>```

P.S. UserLocation is a custom class to get user location.

Body:
Swift:

I've made this two function to check for each case

If user explicitly denied authorization for your app only you can check it like this,

class func isLocationDisableForMyAppOnly() -> Bool {
    if CLLocationManager.locationServicesEnabled() && CLLocationManager.authorizationStatus() == .denied {
        return true
    }
    return false
}

If location services are disabled in Settings,

class func userLocationAvailable() -> Bool {
    return CLLocationManager.locationServicesEnabled()
}

And I'm using it like this,

if UserLocation.userLocationAvailable() {
        //.... Get location.
} else {
    if UserLocation.isLocationDisableForMyAppOnly() {
        //... Location not available. Denied accessing location.
    } else {
        //... Location not available. Enable location services from settings.
    }
}

P.S. UserLocation is a custom class to get user location.


问:
Creating an Image Icon from a local file for eclipse
So I am trying to add an image to a JLabel object which is added to a JPanel called "topPanel" which is part of a JFrame called
"primaryWindow". I have already declared the "topPanel" and "primaryWindow". I found on other forms that you have to create a separate source folder and add the image file in that folder in order to access it and I did so.

However, when I execute the following, the image does not appear to be on the Label. I know that it has nothing to do with adding the JLabel to the panel properly because when I enter a String into the JLabel constructor, the String appears on the panel. An image however does not appear. Am I properly adding the image? I am using a mac if this helps.

```<code>private JLabel image = new JLabel();
image.setIcon(new ImageIcon("Check.png"));
topPanel.add(image);
primaryWindow.add(topPanel, BorderLayout.NORTH);
</code>```

答:
You can also use BufferedImage

```<code> BufferedImage myPicture = ImageIO.read(new File("C:\\xx\\xxx\\Check.png.jpg"));
 Image scaled = myPicture.getScaledInstance(100,70,Image.SCALE_SMOOTH);
 image = new JLabel(new ImageIcon(scaled));
 topPanel.add(image);
 primaryWindow.add(topPanel, BorderLayout.NORTH);
</code>```

Note that "C:\\xx\\xxx\\Check.png.jpg" is the path where you save Check.png.

Hope this helped.

Body:
So I am trying to add an image to a JLabel object which is added to a JPanel called "topPanel" which is part of a JFrame called
"primaryWindow". I have already declared the "topPanel" and "primaryWindow". I found on other forms that you have to create a separate source folder and add the image file in that folder in order to access it and I did so.

However, when I execute the following, the image does not appear to be on the Label. I know that it has nothing to do with adding the JLabel to the panel properly because when I enter a String into the JLabel constructor, the String appears on the panel. An image however does not appear. Am I properly adding the image? I am using a mac if this helps.

private JLabel image = new JLabel();
image.setIcon(new ImageIcon("Check.png"));
topPanel.add(image);
primaryWindow.add(topPanel, BorderLayout.NORTH);

Body:
You can also use BufferedImage

 BufferedImage myPicture = ImageIO.read(new File("C:\\xx\\xxx\\Check.png.jpg"));
 Image scaled = myPicture.getScaledInstance(100,70,Image.SCALE_SMOOTH);
 image = new JLabel(new ImageIcon(scaled));
 topPanel.add(image);
 primaryWindow.add(topPanel, BorderLayout.NORTH);

Note that "C:\\xx\\xxx\\Check.png.jpg" is the path where you save Check.png.

Hope this helped.


问:
Sass source maps not showing in Chrome, running on MAMP Pro
I have seen the question of source maps not being displayed in Chrome answered a few times, none of these quite cover my issue or set up.

I am running MAMP Pro as my local web server and am sure the problem isn't there, Safari and Firefox are showing the source maps for my sass project. This problem started in Chrome on my Mac last week.

My Chrome  Dev settings have Enable CSS source maps checked.

Inspector is still showing only the generated style.css file as the source.

The Gulp task I'm running to generate the source maps is:

```<code>gulp.task('css', function() {
return gulp.src(scss + '{style.scss,rtl.scss}')
.pipe(sourcemaps.init())
.pipe(sass({
    outputStyle: 'expanded',
    indentType: 'tab',
    indentWidth: '1'
}).on('error', sass.logError))
.pipe(postcss([
    autoprefixer('last 2 versions', '> 1%')
]))
.pipe(sourcemaps.write(scss + 'maps'))
.pipe(gulp.dest(root));
</code>```

});

I'd really appreciate any help on getting this working, Chrome is my preferred dev browser.

Shaun.

答: It seems I I made a really simple mistake. The gulp file was outputting the source maps to a folder outside of the project I had my webserver pointed at. I changed the code and the source maps are now working.</p>

Body:
I have seen the question of source maps not being displayed in Chrome answered a few times, none of these quite cover my issue or set up.

I am running MAMP Pro as my local web server and am sure the problem isn't there, Safari and Firefox are showing the source maps for my sass project. This problem started in Chrome on my Mac last week.

My Chrome  Dev settings have Enable CSS source maps checked.

Inspector is still showing only the generated style.css file as the source.

The Gulp task I'm running to generate the source maps is:

gulp.task('css', function() {
return gulp.src(scss + '{style.scss,rtl.scss}')
.pipe(sourcemaps.init())
.pipe(sass({
    outputStyle: 'expanded',
    indentType: 'tab',
    indentWidth: '1'
}).on('error', sass.logError))
.pipe(postcss([
    autoprefixer('last 2 versions', '> 1%')
]))
.pipe(sourcemaps.write(scss + 'maps'))
.pipe(gulp.dest(root));

});

I'd really appreciate any help on getting this working, Chrome is my preferred dev browser.

Shaun.


问:
How to trace "Parse error: syntax error" in a PHP program?
I've tried repl, linter and can't find what's missing. I am new to PHP.

Error:Parse error: syntax error, unexpected $end on line 62

'Line 62' is the last line of code and it's for an email form for my site

Code:

```<code><?php
if(isset($_POST['email'])) {

   $email_to = "(my email is in here)";
   $email_subject = "Enquiry";

   // validation expected data exists
   if(!isset($_POST['first_name']) ||
       !isset($_POST['email']) ||
       !isset($_POST['comments'])) {
       died('We are sorry, but there appears to be a problem with the form you submitted.');
   }

   $first_name = $_POST['first_name']; // required

   $email_from = $_POST['email']; // required
   $comments = $_POST['comments']; // required

   $error_message = "";
   $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
 if(!preg_match($email_exp,$email_from)) {
   $error_message .= 'The Email Address you entered does not appear to be valid.<br />';
 }
   $string_exp = "/^[A-Za-z\s.'-]+$/";
 if(!preg_match($string_exp,$first_name)) {
   $error_message .= 'The First Name you entered does not appear to be valid.<br />';
 }

 if(strlen($comments) < 2) {
   $error_message .= 'The Comments you entered do not appear to be valid.<br />';
 }
 if(strlen($error_message) > 0) {
   died($error_message);
 }
   $email_message = "Details below.\n\n";

   function clean_string($string) {
     $bad = array("content-type","bcc:","to:","cc:","href");
     return str_replace($bad,"",$string);
   }

   $email_message .= "First Name: ".clean_string($first_name)."\n";

   $email_message .= "Email: ".clean_string($email_from)."\n";
   $email_message .= "Comments: ".clean_string($comments)."\n";

// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_to."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
sleep(1);
echo "<meta http-equiv='refresh' content=\"0; url=http://kahlilashanti.com">";
?>

<?php
}
?>-->
</code>```

答:
you have no escape on the double quote at the end of the content at the end of the line:

```<code>echo "<meta http-equiv='refresh' content=\"0; url=http://kahlilashanti.com">";
</code>```

should be

```<code>echo "<meta http-equiv='refresh' content=\"0; url=http://kahlilashanti.com\">";
</code>```

Body:
I've tried repl, linter and can't find what's missing. I am new to PHP.

Error:Parse error: syntax error, unexpected $end on line 62

'Line 62' is the last line of code and it's for an email form for my site

Code:

<?php
if(isset($_POST['email'])) {

   $email_to = "(my email is in here)";
   $email_subject = "Enquiry";

   // validation expected data exists
   if(!isset($_POST['first_name']) ||
       !isset($_POST['email']) ||
       !isset($_POST['comments'])) {
       died('We are sorry, but there appears to be a problem with the form you submitted.');
   }

   $first_name = $_POST['first_name']; // required

   $email_from = $_POST['email']; // required
   $comments = $_POST['comments']; // required

   $error_message = "";
   $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
 if(!preg_match($email_exp,$email_from)) {
   $error_message .= 'The Email Address you entered does not appear to be valid.
';
 }
   $string_exp = "/^[A-Za-z\s.'-]+$/";
 if(!preg_match($string_exp,$first_name)) {
   $error_message .= 'The First Name you entered does not appear to be valid.
';
 }

 if(strlen($comments) < 2) {
   $error_message .= 'The Comments you entered do not appear to be valid.
';
 }
 if(strlen($error_message) > 0) {
   died($error_message);
 }
   $email_message = "Details below.\n\n";

   function clean_string($string) {
     $bad = array("content-type","bcc:","to:","cc:","href");
     return str_replace($bad,"",$string);
   }

   $email_message .= "First Name: ".clean_string($first_name)."\n";

   $email_message .= "Email: ".clean_string($email_from)."\n";
   $email_message .= "Comments: ".clean_string($comments)."\n";

// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_to."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
sleep(1);
echo "<meta http-equiv='refresh' content=\"0; url=http://kahlilashanti.com">";
?>

<?php
}
?>-->

Body:
you have no escape on the double quote at the end of the content at the end of the line:

echo "<meta http-equiv='refresh' content=\"0; url=http://kahlilashanti.com">";

should be

echo "<meta http-equiv='refresh' content=\"0; url=http://kahlilashanti.com\">";


答:
you could create a dict using the angles as keys, where the values are all of the elements with a given angle, then choose the max based on your distance function.

i.e. something like:

```<code>d = defaultdict(lambda: [])

for angle, pt in zip(angles, dataPts):
    d[angle].append(pt)

result = [max(pt, key=my_dist_func) for angle, pt in d.items()]
</code>```

Given the ymin and distance function you're describing, I think this works:

```<code>from collections import defaultdict

dataPts = [(0, 0), (10, 10), (20, 20) ]
angles = [0,45,45]
ymin = min((p[1] for p in dataPts))

d = defaultdict(lambda: [])

for angle, pt in zip(angles, dataPts):
    d[angle].append(pt)

result = [max(pt, key=lambda p: p[1]-ymin) for angle, pt in d.items()]
</code>```

Title: How can I find duplicates in a list, and delete all duplicates except for a certain one?

Body:
I have a sorted list dataPts that is sorted based on the angle each point makes with the minimum Y value minY in dataPts, such as [(0, 0), (10, 10), (20, 20) ... ] (0, 0) being minY.

Then I create a new list angles which is a list of all those angles, for instance  [0, 45, 45, ...].

You will notice that angles contains duplicate values, for instance 45, 45,. What I want to do is locate the points in dataPts that share the same angle. I then want to delete those points, EXCEPT the one that is the furthest distance from  minY using a function that returns a value.

For example, (10, 10) and (20, 20) both have corresponding values in angles, which is 45. How can I pick out the value with greater distance to minY which is (20, 20) and delete (10, 10)?

Body:
you could create a dict using the angles as keys, where the values are all of the elements with a given angle, then choose the max based on your distance function.

i.e. something like:

d = defaultdict(lambda: [])

for angle, pt in zip(angles, dataPts):
    d[angle].append(pt)

result = [max(pt, key=my_dist_func) for angle, pt in d.items()]

Given the ymin and distance function you're describing, I think this works:

from collections import defaultdict

dataPts = [(0, 0), (10, 10), (20, 20) ]
angles = [0,45,45]
ymin = min((p[1] for p in dataPts))

d = defaultdict(lambda: [])

for angle, pt in zip(angles, dataPts):
    d[angle].append(pt)

result = [max(pt, key=lambda p: p[1]-ymin) for angle, pt in d.items()]


问:
How to provide a plugin with data capabilities?
I have an application in which i want to provide the people who write plugins to it (plugins are made by implementing a basic interface, then i load the .dll). I want to give them the possibility to create settings and save data in my existing database. I would like to do this without having to create a table for each plugin - but if its required im willing to do it. I have come up with two basic scenarios:

Give the plugin an interface, where it can get a Dictionary  and serialize it to xml and save it in my database.

The plugin must be contained within a .zip file with a manifest file (my own invention) where it has a create sql script and a drop script for tables.

The first has limitations towards complex data types. The second has a larger complexity in the plugin, since it needs to be within a .zip file and unpacked etc...

Please advice on either of these approaces, or alternatives.

Cheers

答: I am a little hesitant toward option 2, as you are giving a third party access to essentially write SQL directly against your database. However, option 1 seems feasible and safe. As @Euphoric said, you can use multiple keys if you need to do more complicated things.</p>


问:
Why is a program that updates a large static floating point array slower in Rust than in C?
I wrote a simple program to compare Rust and C performance.

The Rust version:

use std::time::Instant;

const STREAM_ARRAY_SIZE: usize = 10000000;
static mut A: [f64; STREAM_ARRAY_SIZE] = [1.0; STREAM_ARRAY_SIZE];

fn main() {
    let now = Instant::now();

    unsafe {
        for i in 0..STREAM_ARRAY_SIZE {
            A[i] = 2.0E0 * A[i];
        }
    }

    let duration = now.elapsed();
    println!("{}", (duration.as_secs() * 1_000_000_000 + duration.subsec_nanos() as u64) / 1000);
}
```

<p>Run it in debug & release mode:  </p>

<pre class="lang-none prettyprint-override"><code>$ ./target/debug/calc
472046 us.
$ ./target/release/calc
62860 us.
</code>```

The release version has a drastic performance gain compared to debug.

The C version does the same thing and runs on the same server:

#include <sys/time.h>
#include <stdio.h>

#define STREAM_ARRAY_SIZE   10000000

static double A[STREAM_ARRAY_SIZE];
int mysecond(void)
{
        struct timeval tp;
        struct timezone tzp;
        int i;

        i = gettimeofday(&tp,&tzp);
        return (tp.tv_sec * 1000000 + tp.tv_usec);
}

int main(void)
{
    int j = 0;
    for (j = 0; j < STREAM_ARRAY_SIZE; j++)
    {
        A[j] = 1.0;
    }

    int t = mysecond();
    for (j = 0; j < STREAM_ARRAY_SIZE; j++)
    {
        A[j] = 2.0E0 * A[j];
    }
    printf("%d us.\n", mysecond() - t);
    return 0;
}
```

<p>Compile and run it with <code>-O0</code> and <code>-O2</code>:  </p>

<pre class="lang-none prettyprint-override"><code>$ gcc test.c
$ ./a.out
41626 us.
$ gcc -O2 test.c
$ ./a.out
13499 us.
</code>```

The Rust optimized version only compares to gcc -O0, and is very weak compared to gcc -O2. Is this reasonable? How can I improve the performance of the Rust version?

答:
Rust compiles the loop to:

.LBB0_1:
    movupd  xmm0, xmmword ptr [rcx + 8*rax - 48]
    movupd  xmm1, xmmword ptr [rcx + 8*rax - 32]
    addpd   xmm0, xmm0
    addpd   xmm1, xmm1
    movupd  xmmword ptr [rcx + 8*rax - 48], xmm0
    movupd  xmmword ptr [rcx + 8*rax - 32], xmm1
    movupd  xmm0, xmmword ptr [rcx + 8*rax - 16]
    movupd  xmm1, xmmword ptr [rcx + 8*rax]
    addpd   xmm0, xmm0
    addpd   xmm1, xmm1
    movupd  xmmword ptr [rcx + 8*rax - 16], xmm0
    movupd  xmmword ptr [rcx + 8*rax], xmm1
    add rax, 8
    cmp rax, 100006
    jne .LBB0_1
```

<p>While GCC 7.1.0 compiles to:</p>

<pre class="lang-none prettyprint-override"><code>L6:
    movsd   (%rbx), %xmm0
    addq    $8, %rbx
    addsd   %xmm0, %xmm0
    movsd   %xmm0, -8(%rbx)
    cmpq    %rbp, %rbx
    jne     L6
</code>```

Rust puts the array in a data section, while C actually writes (memset with pattern) to the memory. This means that your OS running the app likely just maps the range and relies on virtual memory to do the right thing.

If you change the code to run the same loop before the measurement, the runtime goes down considerably. It's actually faster than the C version on my machine. (possibly due to that loop unrolling)

unsafe {
    for i in 0..STREAM_ARRAY_SIZE {
        A[i] = 2.0E0 * A[i];
    }
}

let now = Instant::now();

unsafe {
    for i in 0..STREAM_ARRAY_SIZE {
        A[i] = 2.0E0 * A[i];
    }
}

let duration = now.elapsed();
```

Body:
I wrote a simple program to compare Rust and C performance.

The Rust version:

use std::time::Instant;

const STREAM_ARRAY_SIZE: usize = 10000000;
static mut A: [f64; STREAM_ARRAY_SIZE] = [1.0; STREAM_ARRAY_SIZE];

fn main() {
    let now = Instant::now();

    unsafe {
        for i in 0..STREAM_ARRAY_SIZE {
            A[i] = 2.0E0 * A[i];
        }
    }

    let duration = now.elapsed();
    println!("{}", (duration.as_secs() * 1_000_000_000 + duration.subsec_nanos() as u64) / 1000);
}

Run it in debug & release mode:

$ ./target/debug/calc
472046 us.
$ ./target/release/calc
62860 us.

The release version has a drastic performance gain compared to debug.

The C version does the same thing and runs on the same server:

#include <sys/time.h>
#include <stdio.h>

#define STREAM_ARRAY_SIZE   10000000

static double A[STREAM_ARRAY_SIZE];
int mysecond(void)
{
        struct timeval tp;
        struct timezone tzp;
        int i;

        i = gettimeofday(&tp,&tzp);
        return (tp.tv_sec * 1000000 + tp.tv_usec);
}

int main(void)
{
    int j = 0;
    for (j = 0; j < STREAM_ARRAY_SIZE; j++)
    {
        A[j] = 1.0;
    }

    int t = mysecond();
    for (j = 0; j < STREAM_ARRAY_SIZE; j++)
    {
        A[j] = 2.0E0 * A[j];
    }
    printf("%d us.\n", mysecond() - t);
    return 0;
}

Compile and run it with -O0 and -O2:

$ gcc test.c
$ ./a.out
41626 us.
$ gcc -O2 test.c
$ ./a.out
13499 us.

The Rust optimized version only compares to gcc -O0, and is very weak compared to gcc -O2. Is this reasonable? How can I improve the performance of the Rust version?

Body:
Rust compiles the loop to:

.LBB0_1:
    movupd  xmm0, xmmword ptr [rcx + 8*rax - 48]
    movupd  xmm1, xmmword ptr [rcx + 8*rax - 32]
    addpd   xmm0, xmm0
    addpd   xmm1, xmm1
    movupd  xmmword ptr [rcx + 8*rax - 48], xmm0
    movupd  xmmword ptr [rcx + 8*rax - 32], xmm1
    movupd  xmm0, xmmword ptr [rcx + 8*rax - 16]
    movupd  xmm1, xmmword ptr [rcx + 8*rax]
    addpd   xmm0, xmm0
    addpd   xmm1, xmm1
    movupd  xmmword ptr [rcx + 8*rax - 16], xmm0
    movupd  xmmword ptr [rcx + 8*rax], xmm1
    add rax, 8
    cmp rax, 100006
    jne .LBB0_1

While GCC 7.1.0 compiles to:

L6:
    movsd   (%rbx), %xmm0
    addq    $8, %rbx
    addsd   %xmm0, %xmm0
    movsd   %xmm0, -8(%rbx)
    cmpq    %rbp, %rbx
    jne     L6

Rust puts the array in a data section, while C actually writes (memset with pattern) to the memory. This means that your OS running the app likely just maps the range and relies on virtual memory to do the right thing.

If you change the code to run the same loop before the measurement, the runtime goes down considerably. It's actually faster than the C version on my machine. (possibly due to that loop unrolling)

unsafe {
    for i in 0..STREAM_ARRAY_SIZE {
        A[i] = 2.0E0 * A[i];
    }
}

let now = Instant::now();

unsafe {
    for i in 0..STREAM_ARRAY_SIZE {
        A[i] = 2.0E0 * A[i];
    }
}

let duration = now.elapsed();


问:
Set button type
I am creating a button programatically and I would like to know how to set that button's UIButtonType.

This is how I am creating my button:

```<code>let headerPlusButon:UIButton = UIButton(frame: CGRectMake(5, tableView.frame.width - 30, 20, 20))
headerPlusButon.addTarget(self, action: "paymentAddButtonTapped", forControlEvents:.TouchUpInside)
</code>```

There is no "setButtonTypeFor..." method like how you would change the title's text and obviously this doesn't work:

```<code>headerPlusButon.buttonType = UIButtonType.ContactAdd
</code>```

答:
Here is my code

let tutorialButton = UIButton.init(type: .infoDark)
        tutorialButton.frame = CGRect(x: self.view.frame.size.width - 20, y: 42, width: 20, height: 20)
        tutorialButton.addTarget(self, action: #selector(self.showTutorial), for: .touchUpInside)

        view.addSubview(tutorialButton)```

I hope it can help you!

Title: Set button type

Body:
I am creating a button programatically and I would like to know how to set that button's UIButtonType.

This is how I am creating my button:

let headerPlusButon:UIButton = UIButton(frame: CGRectMake(5, tableView.frame.width - 30, 20, 20))
headerPlusButon.addTarget(self, action: "paymentAddButtonTapped", forControlEvents:.TouchUpInside)

There is no "setButtonTypeFor..." method like how you would change the title's text and obviously this doesn't work:

headerPlusButon.buttonType = UIButtonType.ContactAdd

Body:
Here is my code

let tutorialButton = UIButton.init(type: .infoDark)
        tutorialButton.frame = CGRect(x: self.view.frame.size.width - 20, y: 42, width: 20, height: 20)
        tutorialButton.addTarget(self, action: #selector(self.showTutorial), for: .touchUpInside)

        view.addSubview(tutorialButton)

I hope it can help you!


问:
ggplot: Error: Aesthetics must be either length 1 or the same as the data (10): x, y, group
I have a small dataset and I want to plot it with a line graph:

```<code> > Gain
     quantile Positives Total_Examples Positive_Prevalence     Lift Cumsum_Positives
 1:     (0, ]         1              1                   1 1.428571        0.1428571
 2: (1.9,2.8]         1              1                   1 1.428571        0.2857143
 3: (2.8,3.7]         1              1                   1 1.428571        0.4285714
 4: (3.7,4.6]         1              1                   1 1.428571        0.5714286
 5: (4.6,5.5]         1              1                   1 1.428571        0.7142857
 6: (5.5,6.4]         1              1                   1 1.428571        0.8571429
 7: (6.4,7.3]         1              1                   1 1.428571        1.0000000
 8: (7.3,8.2]         0              1                   0 0.000000        1.0000000
 9: (8.2,9.1]         0              1                   0 0.000000        1.0000000
10:  (9.1,10]         0              1                   0 0.000000        1.0000000
</code>```

My code is the following:

```<code>    ggplot(Gain ) +
  geom_area(aes(x = quantile, y = Cumsum_Positives, group = 1), color = "red", fill = "red", alpha = 0.5, size = 2) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  geom_line(aes(x = quantile, y = seq(0, 1 , by = 0.1)  , group = 1), color = "blue", size = 2, alpha = 0.5) +
  scale_x_discrete(name ="% of the Data Set",
                   labels=c("0%", "10%","20%","30%", "40%", "50%", "60%","70%","80%", "90%", "100%"))
</code>```

However, I get an error message :

```<code>  Error: Aesthetics must be either length 1 or the same as the data (10): x, y, group
</code>```

I have read posts relating to this sort of error and usually the error implies that the variables called within the aesthetics are not present in the original dataframe.  But this is not the case here.

I also tried this code, but it returns the same error message as well:

```<code>Gain$index <- row.names(Gain)

ggplot(Gain ) +
  geom_area(aes(x = index, y = Cumsum_Positives, group = 1), color = "red", fill = "red", alpha = 0.5, size = 2) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  geom_line(aes(x = quantile, y = seq(0, 1 , by = 0.1)  , group = 1), color = "blue", size = 2, alpha = 0.5) +
  scale_x_discrete(name ="% of the Data Set",
                   labels=c("0%", "10%","20%","30%", "40%", "50%", "60%","70%","80%", "90%", "100%"))
</code>```

Your advice will be appreciated.

Body:
I have a small dataset and I want to plot it with a line graph:

 > Gain
     quantile Positives Total_Examples Positive_Prevalence     Lift Cumsum_Positives
 1:     (0, ]         1              1                   1 1.428571        0.1428571
 2: (1.9,2.8]         1              1                   1 1.428571        0.2857143
 3: (2.8,3.7]         1              1                   1 1.428571        0.4285714
 4: (3.7,4.6]         1              1                   1 1.428571        0.5714286
 5: (4.6,5.5]         1              1                   1 1.428571        0.7142857
 6: (5.5,6.4]         1              1                   1 1.428571        0.8571429
 7: (6.4,7.3]         1              1                   1 1.428571        1.0000000
 8: (7.3,8.2]         0              1                   0 0.000000        1.0000000
 9: (8.2,9.1]         0              1                   0 0.000000        1.0000000
10:  (9.1,10]         0              1                   0 0.000000        1.0000000

My code is the following:

    ggplot(Gain ) +
  geom_area(aes(x = quantile, y = Cumsum_Positives, group = 1), color = "red", fill = "red", alpha = 0.5, size = 2) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  geom_line(aes(x = quantile, y = seq(0, 1 , by = 0.1)  , group = 1), color = "blue", size = 2, alpha = 0.5) +
  scale_x_discrete(name ="% of the Data Set",
                   labels=c("0%", "10%","20%","30%", "40%", "50%", "60%","70%","80%", "90%", "100%"))

However, I get an error message :

  Error: Aesthetics must be either length 1 or the same as the data (10): x, y, group

I have read posts relating to this sort of error and usually the error implies that the variables called within the aesthetics are not present in the original dataframe.  But this is not the case here.

I also tried this code, but it returns the same error message as well:

Gain$index <- row.names(Gain)

ggplot(Gain ) +
  geom_area(aes(x = index, y = Cumsum_Positives, group = 1), color = "red", fill = "red", alpha = 0.5, size = 2) +
  theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
  geom_line(aes(x = quantile, y = seq(0, 1 , by = 0.1)  , group = 1), color = "blue", size = 2, alpha = 0.5) +
  scale_x_discrete(name ="% of the Data Set",
                   labels=c("0%", "10%","20%","30%", "40%", "50%", "60%","70%","80%", "90%", "100%"))

Your advice will be appreciated.

Body:
Your data is of length 10, while your y aesthetic in geom_line is of length 11.

seq(0, 1 , by = 0.1)
[1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0

Try seq(0,0.9,by=0.1) or seq(0.1,1,by=0.1)


问:
resize images over a certain size only
I am using a Wordpress plugin to import blog posts off other sites using RSS feeds. The imported posts contain images which I have set to a uniform size using css

```<code>img {
    width:200px !important;
}
</code>```

This works OK, since only the width size is set the height adjusts to the correct proportion for the original image, and the !important overrides the image size set in the imported posts.

However there are also social-media share images in the imported posts (e.g. from feedburner etc.) which I do not want to resize, e.g.

Can I add a filter to the css image size to only apply to images over a certain size (e.g. over 100 pixels wide)?

N.B. I tried adding this in the header

```
</div>
</div>
</p>

<p>Where the div with the images I want to resize is</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><DIV class="myDivClass"></code>```

But this didn't work.

答:
You have to choose image using div class.

For example your code is:

```<code><div class="parentofall">
    <div class="firstparent">
        <img src="imageurl">
    </div>
    <div class="secondparent">
        <img src="imageurl">
    </div>
    <div class="thirdparent">
        <img src="imageurl">
    </div>
</div>
</code>```

Your css should like to this:

```<code>.parentofall .firstparent img {
    width: 100px;
    height: 100px;
}
</code>```

To choose selected image, or you can just simply choose firstparent without parentofall.

Another way of go to selected image is:

```<code>.parentofall > firstparent img {
width: 100px;
height: 100px;
}
</code>```

Title: resize images over a certain size only

Body:
I am using a Wordpress plugin to import blog posts off other sites using RSS feeds. The imported posts contain images which I have set to a uniform size using css

img {
    width:200px !important;
}

This works OK, since only the width size is set the height adjusts to the correct proportion for the original image, and the !important overrides the image size set in the imported posts.

However there are also social-media share images in the imported posts (e.g. from feedburner etc.) which I do not want to resize, e.g.

Can I add a filter to the css image size to only apply to images over a certain size (e.g. over 100 pixels wide)?

N.B. I tried adding this in the header

Where the div with the images I want to resize is

But this didn't work.

Body:
You have to choose image using div class.

For example your code is:

<div class="parentofall">
    <div class="firstparent">
        <img src="imageurl">
    </div>
    <div class="secondparent">
        <img src="imageurl">
    </div>
    <div class="thirdparent">
        <img src="imageurl">
    </div>
</div>

Your css should like to this:

.parentofall .firstparent img {
    width: 100px;
    height: 100px;
}

To choose selected image, or you can just simply choose firstparent without parentofall.

Another way of go to selected image is:

.parentofall > firstparent img {
width: 100px;
height: 100px;
}


问:
Having Troubles with trying to fix an error I'm receiving from MYSQL
Here is the PHP Code I have that is Causing this Error, I haven't had this error come up before and I searched and looked around before posting and Couldn't find a way to get ride of the error.

PHP (WORKING PHP) :

```<code>   <?php
    require('includes/config.php');
    $username = $_SESSION['username'];

    if($_POST['username'] != $_SESSION['user']['username'])
    {
        // Define our query parameter values
        $query_params = array(
            ':username' => $_POST['username']
        );

        $stmt = $db->prepare("SELECT username FROM members WHERE username = :username");
        $stmt->execute($query_params);

        // Retrieve results (if any)
        if($stmt->rowCount() > 0)
        {
            die("This username is already in use");
        }

        try
        {
            $query_params = array(
                ':username' => $_POST['username'],
                ':last_username' => $username
            );

            // Execute the query
            $stmt = $db->prepare("UPDATE members SET username = :username WHERE username = :last_username");
            $result = $stmt->execute($query_params);
        }
        catch(PDOException $ex)
        {
            // Note: On a production website, you should not output $ex->getMessage().
            // It may provide an attacker with helpful information about your code.
            die("Failed to run query: " . $ex->getMessage());
        }
          }

?>
</code>```

HTML:

```<code>                               <div id="changeusername" class="tab-pane">
                     <h3> Change Your Username : </h3>
  <form  method="post" action="changeusername.php" autocomplete="off">
                    <input type="text" name="username" id="username" class="form-control" placeholder="New Username" autofocus  value="<?php if(isset($error)){ echo $_POST['username']; } ?>" tabindex="1">
                    <br>
                    <input type="password" name="password" id="password" class="form-control" placeholder="Confirm Your Password">
                   <br>
                    <button class="btn btn-theme btn-block" name="submit" type="submit"><i class="fa fa-lock"></i> Change Username</button>

              </form>
</code>```

Error I'm Receiving, after I input Boom2 Which is the New Username and boom1 is the oldd Username:
Failed to run query: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''boom2' WHERE username = 'boom1'' at line 1

答:
Try to change

```<code>$stmt = $db->prepare("UPDATE members SET :username WHERE username = '$username'");
</code>```

to

```<code>$stmt = $db->prepare("UPDATE members SET username=:username WHERE username = '$username'");
</code>```

Body:
Here is the PHP Code I have that is Causing this Error, I haven't had this error come up before and I searched and looked around before posting and Couldn't find a way to get ride of the error.

PHP (WORKING PHP) :

   <?php
    require('includes/config.php');
    $username = $_SESSION['username'];

    if($_POST['username'] != $_SESSION['user']['username'])
    {
        // Define our query parameter values
        $query_params = array(
            ':username' => $_POST['username']
        );

        $stmt = $db->prepare("SELECT username FROM members WHERE username = :username");
        $stmt->execute($query_params);

        // Retrieve results (if any)
        if($stmt->rowCount() > 0)
        {
            die("This username is already in use");
        }

        try
        {
            $query_params = array(
                ':username' => $_POST['username'],
                ':last_username' => $username
            );

            // Execute the query
            $stmt = $db->prepare("UPDATE members SET username = :username WHERE username = :last_username");
            $result = $stmt->execute($query_params);
        }
        catch(PDOException $ex)
        {
            // Note: On a production website, you should not output $ex->getMessage().
            // It may provide an attacker with helpful information about your code.
            die("Failed to run query: " . $ex->getMessage());
        }
          }

?>

HTML:

 Change Your Username :

  <form  method="post" action="changeusername.php" autocomplete="off">
                    <input type="text" name="username" id="username" class="form-control" placeholder="New Username" autofocus  value="<?php if(isset($error)){ echo $_POST['username']; } ?>" tabindex="1">

                    <input type="password" name="password" id="password" class="form-control" placeholder="Confirm Your Password">

                    <button class="btn btn-theme btn-block" name="submit" type="submit"> Change Username</button>

              </form>

Error I'm Receiving, after I input Boom2 Which is the New Username and boom1 is the oldd Username:
Failed to run query: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''boom2' WHERE username = 'boom1'' at line 1

Body:
Try to change

$stmt = $db->prepare("UPDATE members SET :username WHERE username = '$username'");

to

$stmt = $db->prepare("UPDATE members SET username=:username WHERE username = '$username'");


问:
Not able to implement Facebook login in php 5.3
We need to implement facebook login on our website.The latest facebook sdk supports only php 5.4 or greater.We are running 5.3.Tried using old versions of facebook sdk but running in to errors all the time.Any possible solutions other than upgrading to php 5.4 ?

The problem is, latest PHP SDK requires PHP 5.4 or greater. but I am not able to upgrade my existing PHP version 5.3 to 5.4 (my application code is not compatible with PHP 5.4)

I tried this but not solved my problem. Are there any other older version of Facebook PHP SDK that I could use, that can work with graph API v2.0 or later and still compatible with PHP 5.3?

答:
Graph API 2.0 is not more work because it's unavailable as of August 7, 2016:

Check this: https://developers.facebook.com/docs/apps/changelog

So, you have to update your PHP version to 5.4 or latest 7.0/7.1 And Then you can used Graph API version v2.3 to v2.9, and then follow below steps:

Login with Facebook using PHP 5.6 and latest

Pre - Requirements

PHP version should be 5.6 or greater (7.0/1).

The mbstring extension should be enabled.

Steps : https://www.codexworld.com/login-with-facebook-using-php/

Or

Steps : http://www.krizna.com/demo/login-with-facebook-using-php/

NOTE : Which type of code you did in application, which is not compatible with PHP 5.4 or greater? Can you update your question with that code.

Follow the following steps to upgrade your PHP version from 5.3 to 5.4/5.6

We can access the new PHP (php5.4 /php5.6) and old php (php5.x). Both are easily accessible.

Just to need to change the PHP version like below:

Download PHP5.4 From http://windows.php.net/download/#php-5.4 (Download Thread Safe) or download PHP5.6 from http://windows.php.net/download/#php-5.6 (download thread safe)

Go to PHP folder location (i.e C:\wamp\bin\php)

Create a new folder with name php5.4.42. or php5.6.30

Extract the download files and save in C:\wamp\bin\php\php5.4.42. or  C:\wamp\bin\php\php5.6.30.

Copy the following files from your old PHP directory to your new PHP directory ().

```<code>php.ini
phpForApache.ini
wampserver.conf`
</code>```

Open new copied php.ini file.

Update the extension_dir path in file.

Open new phpForApache.ini file.

Update the extension_dir path in file

Reboot your system.

Start wamp Server

Go to wampserver =>PHP=>Version=>PHP 5.4.42  or PHP 5.6.30`

Now running PHP5.4.42 or PHP5.6.30 or PHP7.0/1

Note: you might need to re-enable the PHP extension like CURL, Openssl etc

Body:
Graph API 2.0 is not more work because it's unavailable as of August 7, 2016:

Check this: https://developers.facebook.com/docs/apps/changelog

So, you have to update your PHP version to 5.4 or latest 7.0/7.1 And Then you can used Graph API version v2.3 to v2.9, and then follow below steps:

Login with Facebook using PHP 5.6 and latest

Pre - Requirements

PHP version should be 5.6 or greater (7.0/1).

The mbstring extension should be enabled.

Steps : https://www.codexworld.com/login-with-facebook-using-php/

Or

Steps : http://www.krizna.com/demo/login-with-facebook-using-php/

NOTE : Which type of code you did in application, which is not compatible with PHP 5.4 or greater? Can you update your question with that code.

Follow the following steps to upgrade your PHP version from 5.3 to 5.4/5.6

We can access the new PHP (php5.4 /php5.6) and old php (php5.x). Both are easily accessible.

Just to need to change the PHP version like below:

Download PHP5.4 From http://windows.php.net/download/#php-5.4 (Download Thread Safe) or download PHP5.6 from http://windows.php.net/download/#php-5.6 (download thread safe)

Go to PHP folder location (i.e C:\wamp\bin\php)

Create a new folder with name php5.4.42. or php5.6.30

Extract the download files and save in C:\wamp\bin\php\php5.4.42. or  C:\wamp\bin\php\php5.6.30.

Copy the following files from your old PHP directory to your new PHP directory ().

php.ini
phpForApache.ini
wampserver.conf`

Open new copied php.ini file.

Update the extension_dir path in file.

Open new phpForApache.ini file.

Update the extension_dir path in file

Reboot your system.

Start wamp Server

Go to wampserver =>PHP=>Version=>PHP 5.4.42  or PHP 5.6.30`

Now running PHP5.4.42 or PHP5.6.30 or PHP7.0/1

Note: you might need to re-enable the PHP extension like CURL, Openssl etc

ContentLicense: CC BY-SA 4.0


问:
Getting a Run Time Error on the following Code
The Question:-
https://www.codechef.com/JUNE17/problems/NEO01

My solution, which according to me should be the right solution to the aforementioned question but I am constantly getting a RTE.

https://ideone.com/COnlog

```<code>#include<stdio.h>
int main()
{
    long arr[10000];
    int t,n,p=0;
    scanf("%d",&t);

    while(t--)
    {
        long hap1=0,hap2=0;
        scanf("%d",&n);
        for(int i=0;i<n;i++)
        {
            scanf("%d",&arr[i]);
        }

        for(int i=0;i<n;i++)
        {
            if(arr[i]>=0)
            {
                hap1+=arr[i];
                p++;
            }
            else
            {
                hap2+=arr[i];
            }
        }
        printf("%d\n",hap1*p+hap2);
    }
    return 0;
}
</code>```

Edit: Sorry, I am a beginner who usually uses cout and cin, used scanf and printf to save time, and just forgot to add & while using scanf.

Although my code works fine on Dev-C++ 5.11 it shows a Runtime error(SIGSEGV) and I have no idea why is it happening.

答: The constraint for N in the problem is 1 ≤ N ≤ 10^5 so you need to declare a[size],size=10^5.</p>

Body:
The Question:-
https://www.codechef.com/JUNE17/problems/NEO01

My solution, which according to me should be the right solution to the aforementioned question but I am constantly getting a RTE.

https://ideone.com/COnlog

#include<stdio.h>
int main()
{
    long arr[10000];
    int t,n,p=0;
    scanf("%d",&t);

    while(t--)
    {
        long hap1=0,hap2=0;
        scanf("%d",&n);
        for(int i=0;i<n;i++)
        {
            scanf("%d",&arr[i]);
        }

        for(int i=0;i<n;i++)
        {
            if(arr[i]>=0)
            {
                hap1+=arr[i];
                p++;
            }
            else
            {
                hap2+=arr[i];
            }
        }
        printf("%d\n",hap1*p+hap2);
    }
    return 0;
}

Edit: Sorry, I am a beginner who usually uses cout and cin, used scanf and printf to save time, and just forgot to add & while using scanf.

Although my code works fine on Dev-C++ 5.11 it shows a Runtime error(SIGSEGV) and I have no idea why is it happening.