问:
Spring Quartz Setting up Constructor based Injection with Parent Class Constructor
I have a spring boot project that I want to use quartz with to run certain jobs at certain times. I have this class layout:

```<code>abstract public class AbstractFoo {
    protected final FooB fooB;

    public AbstractFoo(FooB fooB) {
        this.fooB = fooB;
    }
}

@Service
public class SomeJob extends AbstractFoo implements Job {
    public SomeJob(FooB fooB) {
        super(fooB);
    }

    @Override
    public void execute(final JobExecutionContext context) throws JobExecutionException {
        //do stuff
    }
}
</code>```

However, when I run this job I get the following error:

```<code>2017-12-06 14:18:01,383  ERROR --- [quartz-jobs] org.quartz.core.ErrorLogger                                                                : An error occured instantiating job to be executed. job= 'jobGroup.someJob'
org.quartz.SchedulerException: Job instantiation failed
    at org.springframework.scheduling.quartz.AdaptableJobFactory.newJob(AdaptableJobFactory.java:45)
    at org.quartz.core.JobRunShell.initialize(JobRunShell.java:127)
    at org.quartz.core.QuartzSchedulerThread.run(QuartzSchedulerThread.java:375)
Caused by: java.lang.InstantiationException: com.jobs.SomeJob
    at java.lang.Class.newInstance(Class.java:427)
    at org.springframework.scheduling.quartz.AdaptableJobFactory.createJobInstance(AdaptableJobFactory.java:58)
    at org.springframework.scheduling.quartz.SpringBeanJobFactory.createJobInstance(SpringBeanJobFactory.java:74)
    at com.config.AutowiringSpringBeanJobFactory.createJobInstance(AutowiringSpringBeanJobFactory.java:27)
    at org.springframework.scheduling.quartz.AdaptableJobFactory.newJob(AdaptableJobFactory.java:41)
    ... 2 common frames omitted
Caused by: java.lang.NoSuchMethodException: com.jobs.SomeJob.<init>()
    at java.lang.Class.getConstructor0(Class.java:3082)
    at java.lang.Class.newInstance(Class.java:412)
    ... 6 common frames omitted
</code>```

I already have an autowire factory like so:

```<code>public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements
        ApplicationContextAware {

    private transient AutowireCapableBeanFactory beanFactory;

    @Override
    public void setApplicationContext(final ApplicationContext context) {
        beanFactory = context.getAutowireCapableBeanFactory();
    }

    @Override
    protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
        final Object job = super.createJobInstance(bundle);
        beanFactory.autowireBean(job);
        return job;
    }
}
</code>```

And here's my quartz config:

```<code>@Configuration
public class QuartzConfig {
    @Autowired
    private DataSource dataSource;
    @Autowired
    private PlatformTransactionManager transactionManager;
    @Autowired
    private ApplicationContext applicationContext;

    @Bean
    public SchedulerFactoryBean quartzScheduler() {
        SchedulerFactoryBean quartzScheduler = new SchedulerFactoryBean();

        quartzScheduler.setDataSource(dataSource);
        quartzScheduler.setTransactionManager(transactionManager);
        quartzScheduler.setOverwriteExistingJobs(true);
        quartzScheduler.setSchedulerName("quartz-jobs");

        AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
        jobFactory.setApplicationContext(applicationContext);
        quartzScheduler.setJobFactory(jobFactory);

        quartzScheduler.setQuartzProperties(quartzProperties());

        Trigger[] triggers = {someJobTrigger().getObject();
        quartzScheduler.setTriggers(triggers);

        return quartzScheduler;
    }

    @Bean
    public CronTriggerFactoryBean someJobTrigger() {
        CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
        cronTriggerFactoryBean.setJobDetail(someJob().getObject());
        cronTriggerFactoryBean.setCronExpression(cronExp);
        cronTriggerFactoryBean.setGroup(someGroup);
        return cronTriggerFactoryBean;
    }

    @Bean
    public JobDetailFactoryBean someJob() {
        JobDetailFactoryBean jobDetailFactory = new JobDetailFactoryBean();
        jobDetailFactory.setJobClass(SomeJob.class);
        jobDetailFactory.setGroup(someGroup);
        jobDetailFactory.setDurability(true);
        return jobDetailFactory;
    }

    @Bean
    public Properties quartzProperties() {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
        Properties properties = null;
        try {
            propertiesFactoryBean.afterPropertiesSet();
            properties = propertiesFactoryBean.getObject();
        } catch (IOException e) {
        }

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

How do I get Quartz to wire in the appropriate dependencies through the constructor?

答:
As stated in docs:

One of the ramifications of this behavior is the fact that jobs must
  have a no-argument constructor (when using the default JobFactory
  implementation).

You essentially using default JobFactory with autowiring capability added. What I found from my personal tests is that autowiring will not work with constructor injection. Also, don't mark your job with Spring annotations (Component, Service, e.c.t) as it has no effect.

To solve your problem, refactor your job to have default constructor and autowire dependencies with field injection (maybe setter injection will work too).

```<code>abstract public class AbstractFoo {
    @Autowired
    protected FooB fooB;
}

public class SomeJob extends AbstractFoo implements Job {

    @Override
    public void execute(final JobExecutionContext context) throws JobExecutionException {
        //do stuff
    }
}
</code>```

Body:
I have a spring boot project that I want to use quartz with to run certain jobs at certain times. I have this class layout:

abstract public class AbstractFoo {
    protected final FooB fooB;

    public AbstractFoo(FooB fooB) {
        this.fooB = fooB;
    }
}

@Service
public class SomeJob extends AbstractFoo implements Job {
    public SomeJob(FooB fooB) {
        super(fooB);
    }

    @Override
    public void execute(final JobExecutionContext context) throws JobExecutionException {
        //do stuff
    }
}

However, when I run this job I get the following error:

2017-12-06 14:18:01,383  ERROR --- [quartz-jobs] org.quartz.core.ErrorLogger                                                                : An error occured instantiating job to be executed. job= 'jobGroup.someJob'
org.quartz.SchedulerException: Job instantiation failed
    at org.springframework.scheduling.quartz.AdaptableJobFactory.newJob(AdaptableJobFactory.java:45)
    at org.quartz.core.JobRunShell.initialize(JobRunShell.java:127)
    at org.quartz.core.QuartzSchedulerThread.run(QuartzSchedulerThread.java:375)
Caused by: java.lang.InstantiationException: com.jobs.SomeJob
    at java.lang.Class.newInstance(Class.java:427)
    at org.springframework.scheduling.quartz.AdaptableJobFactory.createJobInstance(AdaptableJobFactory.java:58)
    at org.springframework.scheduling.quartz.SpringBeanJobFactory.createJobInstance(SpringBeanJobFactory.java:74)
    at com.config.AutowiringSpringBeanJobFactory.createJobInstance(AutowiringSpringBeanJobFactory.java:27)
    at org.springframework.scheduling.quartz.AdaptableJobFactory.newJob(AdaptableJobFactory.java:41)
    ... 2 common frames omitted
Caused by: java.lang.NoSuchMethodException: com.jobs.SomeJob.<init>()
    at java.lang.Class.getConstructor0(Class.java:3082)
    at java.lang.Class.newInstance(Class.java:412)
    ... 6 common frames omitted

I already have an autowire factory like so:

public final class AutowiringSpringBeanJobFactory extends SpringBeanJobFactory implements
        ApplicationContextAware {

    private transient AutowireCapableBeanFactory beanFactory;

    @Override
    public void setApplicationContext(final ApplicationContext context) {
        beanFactory = context.getAutowireCapableBeanFactory();
    }

    @Override
    protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
        final Object job = super.createJobInstance(bundle);
        beanFactory.autowireBean(job);
        return job;
    }
}

And here's my quartz config:

@Configuration
public class QuartzConfig {
    @Autowired
    private DataSource dataSource;
    @Autowired
    private PlatformTransactionManager transactionManager;
    @Autowired
    private ApplicationContext applicationContext;

    @Bean
    public SchedulerFactoryBean quartzScheduler() {
        SchedulerFactoryBean quartzScheduler = new SchedulerFactoryBean();

        quartzScheduler.setDataSource(dataSource);
        quartzScheduler.setTransactionManager(transactionManager);
        quartzScheduler.setOverwriteExistingJobs(true);
        quartzScheduler.setSchedulerName("quartz-jobs");

        AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
        jobFactory.setApplicationContext(applicationContext);
        quartzScheduler.setJobFactory(jobFactory);

        quartzScheduler.setQuartzProperties(quartzProperties());

        Trigger[] triggers = {someJobTrigger().getObject();
        quartzScheduler.setTriggers(triggers);

        return quartzScheduler;
    }

    @Bean
    public CronTriggerFactoryBean someJobTrigger() {
        CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
        cronTriggerFactoryBean.setJobDetail(someJob().getObject());
        cronTriggerFactoryBean.setCronExpression(cronExp);
        cronTriggerFactoryBean.setGroup(someGroup);
        return cronTriggerFactoryBean;
    }

    @Bean
    public JobDetailFactoryBean someJob() {
        JobDetailFactoryBean jobDetailFactory = new JobDetailFactoryBean();
        jobDetailFactory.setJobClass(SomeJob.class);
        jobDetailFactory.setGroup(someGroup);
        jobDetailFactory.setDurability(true);
        return jobDetailFactory;
    }

    @Bean
    public Properties quartzProperties() {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
        Properties properties = null;
        try {
            propertiesFactoryBean.afterPropertiesSet();
            properties = propertiesFactoryBean.getObject();
        } catch (IOException e) {
        }

        return properties;
    }
}

How do I get Quartz to wire in the appropriate dependencies through the constructor?

Body:
As stated in docs:

One of the ramifications of this behavior is the fact that jobs must
  have a no-argument constructor (when using the default JobFactory
  implementation).

You essentially using default JobFactory with autowiring capability added. What I found from my personal tests is that autowiring will not work with constructor injection. Also, don't mark your job with Spring annotations (Component, Service, e.c.t) as it has no effect.

To solve your problem, refactor your job to have default constructor and autowire dependencies with field injection (maybe setter injection will work too).

abstract public class AbstractFoo {
    @Autowired
    protected FooB fooB;
}

public class SomeJob extends AbstractFoo implements Job {

    @Override
    public void execute(final JobExecutionContext context) throws JobExecutionException {
        //do stuff
    }
}


来源: stackexchange

问:
Python Pluginsystem
I am building a custom speech recognition and for that I defined a Command interface. The idea is that the speech recognition returns a String and I got a list of all supported commands. Then I would be going through the list and find the best matching one and execute it.

In order to keep the code maintainable I want to create a plugin system, where you define a class derived from ICommand in a separate file. The folder structure would be the following:

```<code>project/
├── ICommand
├── commands/
│   ├── command1.py (inherits ICommand)
│   ├── command2.py (inherits ICommand)
</code>```

I am facing multiple problems with that:

How can I import ICommand for inheritance in the command1.py file?

How do I create one instance of every class contained in a .py file in the commands folder?

Is there any way to ensure that the plugin file only contains a definition for a derived ICommand class?

答:
How can I import ICommand for inheritance in the command1.py file?

Your project would have to be inside a proper package. If you are not doing that already, you should.
Once Python understands that "command1" is inside a package, inside it you can do:

```<code>from ..ICommand import ICommand
</code>```

(ICommand must be a .py file defining your ICommand, of course).

How do I create one instance of every class contained in a .py file
in the commands folder?

For Python, unless you explicitly import a file, a .py file is as good as any data file sitting on the directory. The language allows you to, but does not perform any "auto-discovery" of whatever files you will have under your plug-ins.

You can do that yourself, our you can use a framework that does this kind of thing - zope.configuration is one, but you have to create xml-like files with the folders it should scan.

Doing it yourself can be easy, it is just a matter of listing the desired folders, and call __import__ for any Python files in there.
TThe object returned by the call to __import__ is the module itself, you can then just check its contents for subclasses (or otherwise implementations of) ICommand and instantiate then.

```<code>module = __import__(...)
plugins = {}
for name, obj in module.__dict__.items():
    if isinstance(obj, ICommand):
         plugins[name] = obj()   # This instatiate the class
</code>```

I have two answers with explicit examples of how to do that:

Load module to invoke its decorators

Python: import every module from a folder?

Is there any way to ensure that the plugin file only contains a
definition for a derived ICommand class?

Yes.

But you should not put that restriction there, as you state it.
The snippet above for getting the ICommand subclasses inspect all of a modues top level contents, and you could easily raise an exception on any variable, function or class there that is not an ICommand subclass.
That however is not a rational restriction: it is usual in Python to need small "utility" functions that are not class related, or other variables that will hold constant values - it is not usefull to constrain those to be class members for your plug-in.  Likewise, if you are worried about the plugins containing arbitrary code that should not be there: you can't prevent that at all. It is not feasible to securely "sandbox" a Python file in a Python process. Very good people tried for years to have a "Python sandbox", only to be frustrated. (If that is a requirement, use O.S. level process resource restrictions, and run your plug-ins i.e. only import their files, in a process with those restrictions)

Otherwise, you may be meaning that you want "a single subclass of ICommand per file", with no other restrictions: then just insert a check in the above loop to instantiate the plug-in - if it finds a second class in the same file, raise an exception.

ContentLicense: CC BY-SA 3.0

Title: Python Pluginsystem

Body:
I am building a custom speech recognition and for that I defined a Command interface. The idea is that the speech recognition returns a String and I got a list of all supported commands. Then I would be going through the list and find the best matching one and execute it.

In order to keep the code maintainable I want to create a plugin system, where you define a class derived from ICommand in a separate file. The folder structure would be the following:

project/
├── ICommand
├── commands/
│   ├── command1.py (inherits ICommand)
│   ├── command2.py (inherits ICommand)

I am facing multiple problems with that:

How can I import ICommand for inheritance in the command1.py file?

How do I create one instance of every class contained in a .py file in the commands folder?

Is there any way to ensure that the plugin file only contains a definition for a derived ICommand class?

Body:
How can I import ICommand for inheritance in the command1.py file?

Your project would have to be inside a proper package. If you are not doing that already, you should.
Once Python understands that "command1" is inside a package, inside it you can do:

from ..ICommand import ICommand

(ICommand must be a .py file defining your ICommand, of course).

How do I create one instance of every class contained in a .py file
in the commands folder?

For Python, unless you explicitly import a file, a .py file is as good as any data file sitting on the directory. The language allows you to, but does not perform any "auto-discovery" of whatever files you will have under your plug-ins.

You can do that yourself, our you can use a framework that does this kind of thing - zope.configuration is one, but you have to create xml-like files with the folders it should scan.

Doing it yourself can be easy, it is just a matter of listing the desired folders, and call __import__ for any Python files in there.
TThe object returned by the call to __import__ is the module itself, you can then just check its contents for subclasses (or otherwise implementations of) ICommand and instantiate then.

module = __import__(...)
plugins = {}
for name, obj in module.__dict__.items():
    if isinstance(obj, ICommand):
         plugins[name] = obj()   # This instatiate the class

I have two answers with explicit examples of how to do that:

Load module to invoke its decorators

Python: import every module from a folder?

Is there any way to ensure that the plugin file only contains a
definition for a derived ICommand class?

Yes.

But you should not put that restriction there, as you state it.
The snippet above for getting the ICommand subclasses inspect all of a modues top level contents, and you could easily raise an exception on any variable, function or class there that is not an ICommand subclass.
That however is not a rational restriction: it is usual in Python to need small "utility" functions that are not class related, or other variables that will hold constant values - it is not usefull to constrain those to be class members for your plug-in.  Likewise, if you are worried about the plugins containing arbitrary code that should not be there: you can't prevent that at all. It is not feasible to securely "sandbox" a Python file in a Python process. Very good people tried for years to have a "Python sandbox", only to be frustrated. (If that is a requirement, use O.S. level process resource restrictions, and run your plug-ins i.e. only import their files, in a process with those restrictions)

Otherwise, you may be meaning that you want "a single subclass of ICommand per file", with no other restrictions: then just insert a check in the above loop to instantiate the plug-in - if it finds a second class in the same file, raise an exception.


问:
Resize handler works once, but not twice
I'm writing code that handles the resize event, and ran into some trouble.
Here is the code:

```<code>/*
   Timeline.js

   (Requires jquery, developed with jquery-1.4.4.min.js in mind)
*/

/*
  Timeline's two major functions are setup and draw. After instantiating a
  timeline object, the developer calls setup() to initialize the object. Later,
  the developer repeatedly calls on draw() to animate the canvas.
  In between, resizing the window may trigger the resize() function which
  adjusts the timeline's dimensions and other settings.
*/
function Timeline(){
    // constants
    Timeline._BORDER_SIDES = 20; // The border on each side of the timeline,
    // We'll need this value later when calculating back's top offset
    Timeline._OFFSET_LEFT = '8px';
    Timeline._OFFSET_TOP = '8px'; // top border, 8px seems to be chrome default
    Timeline._BUTTON_WIDTH = 17; // The length of the back and forward buttons
    Timeline._WIDTH_FACTOR = 2/3; // How much height timeline should take up
    // variables
    Timeline._id = 0; // An id wich is unique for each instance of Timeline

    /* This function is called when the user clicks the back div*/
    this._backHandler = function(){
    alert('back clicked');
    };

    this._testResize = function(){
    alert('resized');
    };

    /*
      timeline.setup()
      Create canvas, back and forward button, as well as slider for scale.
      timeline_wrapper_id is the id of an element which is to contain this
      specific timeline.
     */
    this.setup = function(timeline_wrapper_id){
    // add canvas
    this._id = Timeline._id++; // get id, create next id for next instance
    this._timeline_wrapper_id = timeline_wrapper_id;
    this._canvas = document.createElement('canvas');
    this._canvas.setAttribute('id', 'canvas' + this._id);
    $('#' + timeline_wrapper_id).append(this._canvas);

    // add back button
    this._back = document.createElement('div');
    this._back.setAttribute('id', 'back' + this._id);
    // id's help us jquery stuff, ensuring their unique across instances
    // lets us potentially put several instance on the same page.

    this._back.onclick = this._backHandler; // set event handler: onclick
    $('#' + timeline_wrapper_id).append(this._back);

    this._resizeHandler = function(){
        // First, we clear all style so as to prevent duplicates
        $('#canvas' + this._id).removeAttr('style');
        $('#back' + this._id).removeAttr('style');
        // later we'll insert an empty style before modifying the style.

        // set canvas attributes

        // Width of canvas is window width, with space for borders either
        // side.
        var canvas_width = $(window).width() - Timeline._BORDER_SIDES*2;
        var canvas_height = $(window).height() * Timeline._HEIGHT_FACTOR;

        /* The core feature of this block is the z-index. Everything else
           is there because otherwise I can't determine the z-index. At
           least that's what I read somewhere.

           The z-index determines how overlapping elements are drawn.
           The higher the z-index, the "closer to the user" the element is.

           In this case, we want to draw everything on top of the canvas,
           hence the lowest z-index in our application: 0.
        */
        $('#canvas'+this._id).attr('style', '');
        // this undoes our removeAttr('style') from earlier

        $('#canvas' + this._id).css({
        width: canvas_width,
        height: canvas_height,
        border: '1px solid', // to see what's going on
        position: 'relative', // "take canvas out of flow"-rough quote
        top: Timeline._BORDER_TOP, // seems to be the chrome default
        left: Timeline._BORDER_LEFT, // ditto
        'z-index': 0
        });

        /* Here we define the back button's visual properties.
           Where possible, we calculate them in terms of canvas attributes,
           to achieve a consistent layout as the browser is resized.
        */
        var back_left = $('#canvas' + this._id).css('left') + 'px';
        // same distance from left timeline_wrapper as canvas

        // This one is a little more difficult: An explanation will follow
        // as soon as I've figured it out myself.
        var back_top = ((-1)*$('#canvas' + this._id).height() - 6) + 'px';

        $('#back' + this._id).attr('style', '');
        $('#back' + this._id).css({
        'background-color': '#336699',
        width: Timeline._BUTTON_WIDTH,
        height: $('#canvas' + this._id).height(), // fill canvas height
        position: 'relative', // same reason as for canvas
        left: back_left,
        top: back_top,
        'z-index': 1
        });
    };

    this._resizeHandler();
    $(window).resize(this._resizeHandler);
    };

    /*
      timeline.draw()
      Update (or set for the first time) the styles of back and forward button,
      as well as the canvas.
      Assumes setup has been called.
     */
    this.draw = function(){
    console.log('dummy');
    };
}
</code>```

The code calling Timeline.js is pretty simple:

```<code><!doctype html>
<html>
  <head>
    <title>timeline-js</title>
    <script type="text/javascript" src="jquery-1.4.4.min.js"></script>
    <script type="text/javascript" src="Timeline.js"></script>
  </head>
  <body>
    <div id="timeline_wrapper"></div>
    <script type="text/javascript">

var timeline = new Timeline();
timeline.setup('timeline_wrapper');
// timeline.draw();
//setInterval('timeline.draw()', 60);

    </script>
  </body>
</html>
</code>```

The resize function doesn't throw any errors in Chrome, and works when called like so:

```<code>this._resizeHandler();
</code>```

The error handler is called, I know that because setting window.onresize = this._testReszie works fine, too.

However, when I combine the two, the canvas doesn't resize with the window.
Can someone point me in the right direction here?

答:
The problem is that, in your _resizeHandler function, this does not refer to your Timeline instance. Instead it refers to window since that's what the handler has been attached to.

On way of fixing it (and this is not the only way) is to redefine _resizeHandler so that it gets a reference to the Timeline instance.

```<code>this._resizeHandler = function(self){
  ...same code but with 'this' replaced by 'self'...
}
</code>```

And then fix up the call sites:

```<code>this._resizeHandler(this);
var thisTimeline = this;
$(window).resize(function() { thisTimeline._resizeHandler(thisTimeline); });
};
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm writing code that handles the resize event, and ran into some trouble.
Here is the code:

/*
   Timeline.js

   (Requires jquery, developed with jquery-1.4.4.min.js in mind)
*/

/*
  Timeline's two major functions are setup and draw. After instantiating a
  timeline object, the developer calls setup() to initialize the object. Later,
  the developer repeatedly calls on draw() to animate the canvas.
  In between, resizing the window may trigger the resize() function which
  adjusts the timeline's dimensions and other settings.
*/
function Timeline(){
    // constants
    Timeline._BORDER_SIDES = 20; // The border on each side of the timeline,
    // We'll need this value later when calculating back's top offset
    Timeline._OFFSET_LEFT = '8px';
    Timeline._OFFSET_TOP = '8px'; // top border, 8px seems to be chrome default
    Timeline._BUTTON_WIDTH = 17; // The length of the back and forward buttons
    Timeline._WIDTH_FACTOR = 2/3; // How much height timeline should take up
    // variables
    Timeline._id = 0; // An id wich is unique for each instance of Timeline

    /* This function is called when the user clicks the back div*/
    this._backHandler = function(){
    alert('back clicked');
    };

    this._testResize = function(){
    alert('resized');
    };

    /*
      timeline.setup()
      Create canvas, back and forward button, as well as slider for scale.
      timeline_wrapper_id is the id of an element which is to contain this
      specific timeline.
     */
    this.setup = function(timeline_wrapper_id){
    // add canvas
    this._id = Timeline._id++; // get id, create next id for next instance
    this._timeline_wrapper_id = timeline_wrapper_id;
    this._canvas = document.createElement('canvas');
    this._canvas.setAttribute('id', 'canvas' + this._id);
    $('#' + timeline_wrapper_id).append(this._canvas);

    // add back button
    this._back = document.createElement('div');
    this._back.setAttribute('id', 'back' + this._id);
    // id's help us jquery stuff, ensuring their unique across instances
    // lets us potentially put several instance on the same page.

    this._back.onclick = this._backHandler; // set event handler: onclick
    $('#' + timeline_wrapper_id).append(this._back);

    this._resizeHandler = function(){
        // First, we clear all style so as to prevent duplicates
        $('#canvas' + this._id).removeAttr('style');
        $('#back' + this._id).removeAttr('style');
        // later we'll insert an empty style before modifying the style.

        // set canvas attributes

        // Width of canvas is window width, with space for borders either
        // side.
        var canvas_width = $(window).width() - Timeline._BORDER_SIDES*2;
        var canvas_height = $(window).height() * Timeline._HEIGHT_FACTOR;

        /* The core feature of this block is the z-index. Everything else
           is there because otherwise I can't determine the z-index. At
           least that's what I read somewhere.

           The z-index determines how overlapping elements are drawn.
           The higher the z-index, the "closer to the user" the element is.

           In this case, we want to draw everything on top of the canvas,
           hence the lowest z-index in our application: 0.
        */
        $('#canvas'+this._id).attr('style', '');
        // this undoes our removeAttr('style') from earlier

        $('#canvas' + this._id).css({
        width: canvas_width,
        height: canvas_height,
        border: '1px solid', // to see what's going on
        position: 'relative', // "take canvas out of flow"-rough quote
        top: Timeline._BORDER_TOP, // seems to be the chrome default
        left: Timeline._BORDER_LEFT, // ditto
        'z-index': 0
        });

        /* Here we define the back button's visual properties.
           Where possible, we calculate them in terms of canvas attributes,
           to achieve a consistent layout as the browser is resized.
        */
        var back_left = $('#canvas' + this._id).css('left') + 'px';
        // same distance from left timeline_wrapper as canvas

        // This one is a little more difficult: An explanation will follow
        // as soon as I've figured it out myself.
        var back_top = ((-1)*$('#canvas' + this._id).height() - 6) + 'px';

        $('#back' + this._id).attr('style', '');
        $('#back' + this._id).css({
        'background-color': '#336699',
        width: Timeline._BUTTON_WIDTH,
        height: $('#canvas' + this._id).height(), // fill canvas height
        position: 'relative', // same reason as for canvas
        left: back_left,
        top: back_top,
        'z-index': 1
        });
    };

    this._resizeHandler();
    $(window).resize(this._resizeHandler);
    };

    /*
      timeline.draw()
      Update (or set for the first time) the styles of back and forward button,
      as well as the canvas.
      Assumes setup has been called.
     */
    this.draw = function(){
    console.log('dummy');
    };
}

The code calling Timeline.js is pretty simple:

<!doctype html>

    <title>timeline-js</title>

The resize function doesn't throw any errors in Chrome, and works when called like so:

this._resizeHandler();

The error handler is called, I know that because setting window.onresize = this._testReszie works fine, too.

However, when I combine the two, the canvas doesn't resize with the window.
Can someone point me in the right direction here?

Body:
The problem is that, in your _resizeHandler function, this does not refer to your Timeline instance. Instead it refers to window since that's what the handler has been attached to.

On way of fixing it (and this is not the only way) is to redefine _resizeHandler so that it gets a reference to the Timeline instance.

this._resizeHandler = function(self){
  ...same code but with 'this' replaced by 'self'...
}

And then fix up the call sites:

this._resizeHandler(this);
var thisTimeline = this;
$(window).resize(function() { thisTimeline._resizeHandler(thisTimeline); });
};


问:
Assertion Failure: UI Testing Failure - Failure fetching attributes for element
When UI testing in Xcode(7.2 and 7.3), my tests sometimes fail with a rather generic error:

Assertion Failure: UI Testing Failure - Failure fetching attributes for element

I tend to get this error when calling .hittable or .tap() on an element but I cannot tell why. I've checked that the elements I'm dealing with all have their accessibility settings correctly setup and that any container views that they are in don't have accessibilty enabled. Alas, this doesn't seem to resolve the problem.

The console log reveals:

```<code>UI Testing Failure - Failure fetching attributes for element <XCAccessibilityElement: 0x7e68ae50> pid: 89032, context: 4D9272C7-3024-4062-B0FA-E16EF426F17A, payload: {
    pid = 89032;
    "uid.elementID" = 1432;
    "uid.elementOrHash" = 2125772976;
}: Error Domain=XCTestManagerErrorDomain Code=13 "Error copying attributes -25202" UserInfo={NSLocalizedDescription=Error copying attributes -25202}
</code>```

I've tried searching around and managed to find it's already been logged but there appears to be no current solution (radar link) even for Xcode 7.3.

It seems that sometimes if I restart the simulator/device this error doesn't happen but this isn't a nice solution.

答:
I tried waitForHittable() from http://masilotti.com/xctest-helpers/ but in my case I had to use sleep(seconds) before tapping. </p>

<p>Plus, don't think Joe Masilotti's methods are useless. They are great and I have added those in extension XCTest and extension XCUIElement. It is just that waitForHittable() didn't work just on first tap after main screen of my app loads. </p>

Body:
When UI testing in Xcode(7.2 and 7.3), my tests sometimes fail with a rather generic error:

Assertion Failure: UI Testing Failure - Failure fetching attributes for element

I tend to get this error when calling .hittable or .tap() on an element but I cannot tell why. I've checked that the elements I'm dealing with all have their accessibility settings correctly setup and that any container views that they are in don't have accessibilty enabled. Alas, this doesn't seem to resolve the problem.

The console log reveals:

UI Testing Failure - Failure fetching attributes for element <XCAccessibilityElement: 0x7e68ae50> pid: 89032, context: 4D9272C7-3024-4062-B0FA-E16EF426F17A, payload: {
    pid = 89032;
    "uid.elementID" = 1432;
    "uid.elementOrHash" = 2125772976;
}: Error Domain=XCTestManagerErrorDomain Code=13 "Error copying attributes -25202" UserInfo={NSLocalizedDescription=Error copying attributes -25202}

I've tried searching around and managed to find it's already been logged but there appears to be no current solution (radar link) even for Xcode 7.3.

It seems that sometimes if I restart the simulator/device this error doesn't happen but this isn't a nice solution.

Body:
I tried waitForHittable() from http://masilotti.com/xctest-helpers/ but in my case I had to use sleep(seconds) before tapping.

Plus, don't think Joe Masilotti's methods are useless. They are great and I have added those in extension XCTest and extension XCUIElement. It is just that waitForHittable() didn't work just on first tap after main screen of my app loads.


问:
Sqlite query - column with sum from first column
Let's say that I have this query

```<code>select
    count(customerid) as Count_Own,
    (select count(customerid) from Customers) Count_ALL
from
    Customers
where
    EmployeeID = 1
</code>```

It's showing count of customers for employeeid = 1 in first columns and all employees in second column.

Now I want to write similar query by instead of table Customers, I have big subquery:

```<code>select
    count(customerid) as Count_Own,
    (select count(customerid) from /*BIG QUERY*/) Count_ALL
from
    ( /*BIG QUERY*/   )
where
    EmployeeID = 1
</code>```

I have a problem now with column Count_ALL, because I wanted count this quick, without using my subquery. I wonder if it's simply solution for it.

答:
Workaround: create a fake column to join both queries:

```<code>select
  count(T1.customerid) as Count_Own, T2.Count_ALL
From ( Select 1 as joinField, --BIG QUERY--   ) T1
join (select count(customerid) Count_ALL, 1 as joinField
      from customers)  T2
on T1.joinField = T2.joinField
where T1.EmployeeID = 1
</code>```

Edited due OP comment.

You ca use CTE to avoid write big query for twice. Let's work with this simplified schema:

```<code>dh4@GLOW:~/tmp$ sqlite3 pepe.sql
SQLite version 3.11.0 2016-02-15 17:29:24
Enter ".help" for usage hints.
sqlite> create table t ( i int , e int );
sqlite> insert into t values
   ...> ( 1,1),
   ...> ( 2,1),
   ...> ( 3,1),
   ...> ( 1,2);
</code>```

Then, your query is:

```<code>sqlite> with big_query as
   ...> ( select i,e from t )
   ...> select count(i), (select count(*) from big_query)
   ...> from big_query
   ...> where e=1;
3|4
</code>```

Also you can use fake join trip to avoid subrogate subquery:

```<code>sqlite> with big_query as
   ...> ( select i,e from t ),
   ...> q1 as
   ...> ( select count(*) as n, 1 as fake  from big_query ),
   ...> q2 as
   ...> ( select count(*) as n, 1 as fake from big_query where e=1)
   ...> select q2.n, q1.n
   ...> from q1 inner join q2
   ...> on q1.fake=q2.fake;
3|4
</code>```

And the last approach is to use case:

```<code>sqlite> select count( case when e = 1 then 1 else null end) , count(*)
   ...> from t
   ...> ;
3|4
</code>```

Body:
Let's say that I have this query

select
    count(customerid) as Count_Own,
    (select count(customerid) from Customers) Count_ALL
from
    Customers
where
    EmployeeID = 1

It's showing count of customers for employeeid = 1 in first columns and all employees in second column.

Now I want to write similar query by instead of table Customers, I have big subquery:

select
    count(customerid) as Count_Own,
    (select count(customerid) from /*BIG QUERY*/) Count_ALL
from
    ( /*BIG QUERY*/   )
where
    EmployeeID = 1

I have a problem now with column Count_ALL, because I wanted count this quick, without using my subquery. I wonder if it's simply solution for it.

Body:
Workaround: create a fake column to join both queries:

select
  count(T1.customerid) as Count_Own, T2.Count_ALL
From ( Select 1 as joinField, --BIG QUERY--   ) T1
join (select count(customerid) Count_ALL, 1 as joinField
      from customers)  T2
on T1.joinField = T2.joinField
where T1.EmployeeID = 1

Edited due OP comment.

You ca use CTE to avoid write big query for twice. Let's work with this simplified schema:

dh4@GLOW:~/tmp$ sqlite3 pepe.sql
SQLite version 3.11.0 2016-02-15 17:29:24
Enter ".help" for usage hints.
sqlite> create table t ( i int , e int );
sqlite> insert into t values
   ...> ( 1,1),
   ...> ( 2,1),
   ...> ( 3,1),
   ...> ( 1,2);

Then, your query is:

sqlite> with big_query as
   ...> ( select i,e from t )
   ...> select count(i), (select count(*) from big_query)
   ...> from big_query
   ...> where e=1;
3|4

Also you can use fake join trip to avoid subrogate subquery:

sqlite> with big_query as
   ...> ( select i,e from t ),
   ...> q1 as
   ...> ( select count(*) as n, 1 as fake  from big_query ),
   ...> q2 as
   ...> ( select count(*) as n, 1 as fake from big_query where e=1)
   ...> select q2.n, q1.n
   ...> from q1 inner join q2
   ...> on q1.fake=q2.fake;
3|4

And the last approach is to use case:

sqlite> select count( case when e = 1 then 1 else null end) , count(*)
   ...> from t
   ...> ;
3|4


问:
Angular: ngOnChanges not updating value
I am new to ngOnchanges and facing below issue.

my parent component is setting recom value on ngOnChanges and sends the same value to child component. child receives the same as input in ngOnChanges. depending on some condition like totalVal>0 i set inputField  to true which is initially set to false. if inputField is true i show some component in reactive forms. but when my below structure execute model2Form() it still gets inputField as false. I cant post actual code so just created a structure as per my project as shown below.

Please suggest how do i solve this issue.

```<code>// parent component

ngOnchanges(){
  this.recom = [{
    totalVal: 5000,
    monthlydata: true
  }]
}

//child component

@Input()
private recom: any;

inputField: boolean = false;

ngOnChanges(){
  this.setValue();
  this.loadFuture();
}

setValue(){
  if(this.recom.totalVal > 0){
    this.inputField = true;
  }
}

loadFuture(){

}

model2Form(){

//getting input field as false even if i set it as true in setValue()

  if(inputField){
    this.heroForm.setControl('secretLairs', addressFormArray);
  }

}

<!-- parent component>

<parent-comp [recom]="recom"></parent-comp>

<!-- child component -->

<div [FormControlName]="secretLairs"> </div>
</code>```

答:
change event ngOnchange only occur when there is any change done to your input property of component. So in your case parentcomponent has no input property and so ngOnchange does not fire for you.

I created code for you which is working - in below code i used parentcomponent in my appcomponent.ts and when I loaded, ngOnchange does not work, but child ngOnchange works and its input property gets changed.

So I changed child property in OnChange event of textbox control and when i changed value in my textbox control, then child control ngOnchange got triggered and updated value came.

If you pass input value to parent control and make change in that than you parent and child ngOnchange  will work.

Parent component

```<code>import { Component } from '@angular/core';
import { OnChanges, SimpleChanges, OnInit } from '@angular/core';

@Component({
    selector: 'parentcomp',
    template: `
    this needs to be wok
  <h3>Countdown to Liftoff (via local variable)</h3>
  <input type="text" [ngModel] = "display"  (ngModelChange)="onChange($event)"/>
  {{display}}
  <Childcomp [recom] = "recom"> </Childcomp>
  `
})
export class ParentComponent implements OnChanges, OnInit {
    ngOnInit(): void {
        this.recom = [{
            totalVal: 5000,
            monthlydata: false
        }];
    }
    display: string;
    recom: any;

    constructor() {
        this.display = "test";
    }

    onChange()
    {
        this.recom = [{
            totalVal: 5000,
            monthlydata: true
        }];

    }

    //this will not trigger
    ngOnChanges(changes: SimpleChanges): void {
        debugger;
        this.recom = [{
            totalVal: 5000,
            monthlydata: true
        }];
    }
}
</code>```

Child Component

```<code>import { Component } from '@angular/core';
import { OnChanges, SimpleChanges, Input } from '@angular/core';

@Component({
    selector: 'Childcomp',
    template: `
  <h3>Child component</h3>

  `
})
export class Childcomponent implements OnChanges {
    @Input()
    private recom: any;

    constructor() {
    }

    ngOnChanges(changes: SimpleChanges): void {
       debugger;
       for (let propName in changes) {
        let chng = changes[propName];
        let cur:any  = chng.currentValue;
        let prev:any = chng.previousValue;
        alert(`${propName}: currentValue = ${cur[0].monthlydata}, previousValue = ${prev[0].monthlydata}`);
      }
    }
}
</code>```

Title: Angular: ngOnChanges not updating value

Body:
I am new to ngOnchanges and facing below issue.

my parent component is setting recom value on ngOnChanges and sends the same value to child component. child receives the same as input in ngOnChanges. depending on some condition like totalVal>0 i set inputField  to true which is initially set to false. if inputField is true i show some component in reactive forms. but when my below structure execute model2Form() it still gets inputField as false. I cant post actual code so just created a structure as per my project as shown below.

Please suggest how do i solve this issue.

// parent component

ngOnchanges(){
  this.recom = [{
    totalVal: 5000,
    monthlydata: true
  }]
}

//child component

@Input()
private recom: any;

inputField: boolean = false;

ngOnChanges(){
  this.setValue();
  this.loadFuture();
}

setValue(){
  if(this.recom.totalVal > 0){
    this.inputField = true;
  }
}

loadFuture(){

}

model2Form(){

//getting input field as false even if i set it as true in setValue()

  if(inputField){
    this.heroForm.setControl('secretLairs', addressFormArray);
  }

}

Body:
change event ngOnchange only occur when there is any change done to your input property of component. So in your case parentcomponent has no input property and so ngOnchange does not fire for you.

I created code for you which is working - in below code i used parentcomponent in my appcomponent.ts and when I loaded, ngOnchange does not work, but child ngOnchange works and its input property gets changed.

So I changed child property in OnChange event of textbox control and when i changed value in my textbox control, then child control ngOnchange got triggered and updated value came.

If you pass input value to parent control and make change in that than you parent and child ngOnchange  will work.

Parent component

import { Component } from '@angular/core';
import { OnChanges, SimpleChanges, OnInit } from '@angular/core';

@Component({
    selector: 'parentcomp',
    template: `
    this needs to be wok
  <h3>Countdown to Liftoff (via local variable)</h3>
  <input type="text" [ngModel] = "display"  (ngModelChange)="onChange($event)"/>
  {{display}}
  <Childcomp [recom] = "recom"> </Childcomp>
  `
})
export class ParentComponent implements OnChanges, OnInit {
    ngOnInit(): void {
        this.recom = [{
            totalVal: 5000,
            monthlydata: false
        }];
    }
    display: string;
    recom: any;

    constructor() {
        this.display = "test";
    }

    onChange()
    {
        this.recom = [{
            totalVal: 5000,
            monthlydata: true
        }];

    }

    //this will not trigger
    ngOnChanges(changes: SimpleChanges): void {
        debugger;
        this.recom = [{
            totalVal: 5000,
            monthlydata: true
        }];
    }
}

Child Component

import { Component } from '@angular/core';
import { OnChanges, SimpleChanges, Input } from '@angular/core';

@Component({
    selector: 'Childcomp',
    template: `
  <h3>Child component</h3>

  `
})
export class Childcomponent implements OnChanges {
    @Input()
    private recom: any;

    constructor() {
    }

    ngOnChanges(changes: SimpleChanges): void {
       debugger;
       for (let propName in changes) {
        let chng = changes[propName];
        let cur:any  = chng.currentValue;
        let prev:any = chng.previousValue;
        alert(`${propName}: currentValue = ${cur[0].monthlydata}, previousValue = ${prev[0].monthlydata}`);
      }
    }
}

ContentLicense: CC BY-SA 4.0


问:
Call function in jQuery
I have created a function inside a .click

```<code>$('#BeforeFunction').click(function(){

//something is entered here then the function below is called
Hello();

});

$('#HitMe').click(function(){
//something here.....
function Hello(){
alert ('Hit button is pressed');
}

});
</code>```

But the function when called causes an error, the message being Hello is not defined.

What is wrong exactly?

答:
Each of those click event handlers has its own scope. Anything that you create inside them can't be seen from anywhere else. The reason you're getting that error is that the first click handler doesn't know what Hello is. To get around, that, define your Hello function before your click handlers

```<code>function Hello() {
    alert ('Hit button is pressed');
}

$('#BeforeFunction').click(function(){
    //something is entered here then the function below is called
    Hello();
});

$('#HitMe').click(function(){
    //something here.....
});
</code>```

If you want to understand the concept of JavaScript scope any better, there's a pretty good explanation on Digital Web

Title: Call function in jQuery

Body:
I have created a function inside a .click

$('#BeforeFunction').click(function(){

//something is entered here then the function below is called
Hello();

});

$('#HitMe').click(function(){
//something here.....
function Hello(){
alert ('Hit button is pressed');
}

});

But the function when called causes an error, the message being Hello is not defined.

What is wrong exactly?

Body:
Each of those click event handlers has its own scope. Anything that you create inside them can't be seen from anywhere else. The reason you're getting that error is that the first click handler doesn't know what Hello is. To get around, that, define your Hello function before your click handlers

function Hello() {
    alert ('Hit button is pressed');
}

$('#BeforeFunction').click(function(){
    //something is entered here then the function below is called
    Hello();
});

$('#HitMe').click(function(){
    //something here.....
});

If you want to understand the concept of JavaScript scope any better, there's a pretty good explanation on Digital Web


问:
How to generate all possible pairs with permutations from list in Python?
How do I generate all possible pairs permutations from a list in Python?

Example:

```<code>input = [3, 8, 2]
output = ['3-8', '3-2', '8-3', '8-2', '2-3', '2-8']
</code>```

答:
Use itertools.permutations:

```<code>from itertools import permutations

input = [3, 8, 2]
output = map('-'.join, permutations(map(str, input), 2))
</code>```

Body:
How do I generate all possible pairs permutations from a list in Python?

Example:

input = [3, 8, 2]
output = ['3-8', '3-2', '8-3', '8-2', '2-3', '2-8']

Body:
Use itertools.permutations:

from itertools import permutations

input = [3, 8, 2]
output = map('-'.join, permutations(map(str, input), 2))


问:
<initializer_list> with references to functions
i would like to ask if there is any chance to fill up the <initializer_list> with references to functions. Let's say i have function:

```<code>double refce( double (&f1)(double), double in ){
    return f1(in);
}
</code>```

and instead of calling it like:

```<code>double a[3];

a[0] = refce( sin, 3.1415);
a[1] = refce( cos, 3.1415);
a[2] = refce( tan, 3.1415);
</code>```

is it possible to write function that will work like this:

```<code>double a*;
a = refce_list( {sin, cos, tan}, 3.1415);
</code>```

I have tried to use initializer list, but apparently i don't know ho to paste the type to the list. Also i tried #include "cstdarg" style but i could not figure out the proper syntax. Is it even possible?

Thanks
Buddy

答:
Like this:</p>

```<code>#include <initializer_list>

void refce(std::initializer_list<double (*)(double)> il, double in)
{
    for (auto* f : il)
    {
        f(in);
    }
}
</code>```

Body:
i would like to ask if there is any chance to fill up the <initializer_list> with references to functions. Let's say i have function:

double refce( double (&f1)(double), double in ){
    return f1(in);
}

and instead of calling it like:

double a[3];

a[0] = refce( sin, 3.1415);
a[1] = refce( cos, 3.1415);
a[2] = refce( tan, 3.1415);

is it possible to write function that will work like this:

double a*;
a = refce_list( {sin, cos, tan}, 3.1415);

I have tried to use initializer list, but apparently i don't know ho to paste the type to the list. Also i tried #include "cstdarg" style but i could not figure out the proper syntax. Is it even possible?

Thanks
Buddy

Body:
Like this:

#include <initializer_list>

void refce(std::initializer_list<double (*)(double)> il, double in)
{
    for (auto* f : il)
    {
        f(in);
    }
}


问:
IsTextSearchEnabled not working properly on ComboBox
What I'm trying to do

I'm trying to implement the AutoComplete feature on ComboBox without using WpfToolkit. If I'm not wrong, the ComboBox should support the AutoComplete for a simple string item so for example:

```<code><ComboBox IsEditable="True">
    <ComboBoxItem>Apple</ComboBoxItem>
    <ComboBoxItem>Banana</ComboBoxItem>
    <ComboBoxItem>Pear</ComboBoxItem>
    <ComboBoxItem>Orange</ComboBoxItem>
</ComboBox>
</code>```

Current object implementation

actually my ComboBox bound a custom object called CheckedListItem, this object have the following structure:

```<code>public class CheckedListItem<T> : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private bool isChecked;
    private T item;

    public CheckedListItem() { }

    public CheckedListItem(T item, bool isChecked = false)
    {
        this.item = item;
        this.isChecked = isChecked;
    }

    public T Item
    {
        get { return item; }
        set
        {
            item = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item"));
        }
    }

    public bool IsChecked
    {
        get { return isChecked; }
        set
        {
            isChecked = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IsChecked"));
        }
    }
}
</code>```

this class show as ComboBoxItem a CheckBox near the Text of the Item, similar to:

```<code>[] Item1
[] Item2
...
</code>```

where [] is the Checkbox.

ComboBox structure

The ComboBox look like this:

```<code><ComboBox IsEditable="True" ItemSource={Binding Countries}/>
</code>```

where Countries is a List of CheckedListItem<Country>, the object country is implemented in this way:

```<code>public class Country
{
    public string Name { get; set; }
}
</code>```

the problem on this code is that when I type some text in the ComboBox this doesn't do anything, but should display on the items that contains the string typed.

What I tried so far

I tried to fix this by implementing a PreviewTextInput event, actually I managed in this way:

```<code>MyComboBox.IsDropDownOpen = true;
        CountryMenuComboBox.ItemsSource = Countries.Where(c => c.Item.Name.Contains(e.Text)).ToList();
</code>```

but this doesn't working correctly, cause if I type "England", the ItemSource display even all Items.

Any idea to fix this?

Thanks.

答:
Try to set the TextSearch.TextPath property to "Item.Name":

```<code><ComboBox IsEditable="True" ItemsSource="{Binding Countries}"
          TextSearch.TextPath="Item.Name">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <CheckBox IsChecked="{Binding Item.IsChecked}" />
                <TextBlock Text="{Binding Item.Name}" />
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>
</code>```

Body:
What I'm trying to do

I'm trying to implement the AutoComplete feature on ComboBox without using WpfToolkit. If I'm not wrong, the ComboBox should support the AutoComplete for a simple string item so for example:

<ComboBox IsEditable="True">
    <ComboBoxItem>Apple</ComboBoxItem>
    <ComboBoxItem>Banana</ComboBoxItem>
    <ComboBoxItem>Pear</ComboBoxItem>
    <ComboBoxItem>Orange</ComboBoxItem>
</ComboBox>

Current object implementation

actually my ComboBox bound a custom object called CheckedListItem, this object have the following structure:

public class CheckedListItem<T> : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private bool isChecked;
    private T item;

    public CheckedListItem() { }

    public CheckedListItem(T item, bool isChecked = false)
    {
        this.item = item;
        this.isChecked = isChecked;
    }

    public T Item
    {
        get { return item; }
        set
        {
            item = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item"));
        }
    }

    public bool IsChecked
    {
        get { return isChecked; }
        set
        {
            isChecked = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IsChecked"));
        }
    }
}

this class show as ComboBoxItem a CheckBox near the Text of the Item, similar to:

[] Item1
[] Item2
...

where [] is the Checkbox.

ComboBox structure

The ComboBox look like this:

<ComboBox IsEditable="True" ItemSource={Binding Countries}/>

where Countries is a List of CheckedListItem<Country>, the object country is implemented in this way:

public class Country
{
    public string Name { get; set; }
}

the problem on this code is that when I type some text in the ComboBox this doesn't do anything, but should display on the items that contains the string typed.

What I tried so far

I tried to fix this by implementing a PreviewTextInput event, actually I managed in this way:

MyComboBox.IsDropDownOpen = true;
        CountryMenuComboBox.ItemsSource = Countries.Where(c => c.Item.Name.Contains(e.Text)).ToList();

but this doesn't working correctly, cause if I type "England", the ItemSource display even all Items.

Any idea to fix this?

Thanks.

Body:
Try to set the TextSearch.TextPath property to "Item.Name":

<ComboBox IsEditable="True" ItemsSource="{Binding Countries}"
          TextSearch.TextPath="Item.Name">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <CheckBox IsChecked="{Binding Item.IsChecked}" />
                <TextBlock Text="{Binding Item.Name}" />
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>


问:
Regex.Match() vs new Regex().Match() is there a difference?
Specifically to memory here, would Regex.Match() and new Regex().Match() have a difference?

Would not creating a new assertion of the Regex class cost more memory then using Regex.Match?

The reason I am asking is I've always been doing new Regex("pattern").Match("Input") and saw Regex.Match and I'm now questioning if I'm doing it wrong!

答:
With that exact syntax, for you as the developer, there is no difference.
except that new Regex() is not a public constructor, you have to pass a pattern.

So in that case the Static probably better.

Where you would you new Regex() is, to assign it to an instance of a Regex like:

```<code>var myregex = new Regex("my pattern");
</code>```

You can then check things on the instance like timeout MatchTimeout and Options.

Body:
With that exact syntax, for you as the developer, there is no difference.
except that new Regex() is not a public constructor, you have to pass a pattern.

So in that case the Static probably better.

Where you would you new Regex() is, to assign it to an instance of a Regex like:

var myregex = new Regex("my pattern");

You can then check things on the instance like timeout MatchTimeout and Options.


问:
How do I sum up automatically specific parts of one vector?
I am very much a beginner in R Studio and programming in general and very often have the problem that I lack basic vocabulary to understand the help or the answers given here. If you are willing to help me, please keep in mind to use easy language...

I have a dataset spit out by a machine, that divides a range into many tiny little bins. E.g. the range of 2 to 3 is divided into up to 36 values  (2.02,2.025,2.03 etc), each bin has a certain number of measured data in another column (s1noml).
How do I sum up all values of the column "s1noml" that have e.g. a 2 before the period/comma in the bin-column? And afterwards automatically ( I guess via a loop?) all values with a 3 and then a 4 and so on

This is how the table looks like:
enter image description here

I'm sorry if I use words incorrectly and that the question is so basic.

Looking forward to your help!

答:
I think this is more efficient and safe than writing a loop.

```<code>df$temp <- round(df$bin, 0)  # round to 0 decimal places, store in a temporary var
df2 <- aggregate(df$s1noml, by=list(df$temp), FUN=sum)  # sum by group in temp var
</code>```

If this doesn't work quite right it'd be helpful to provide a reprex for us to work with.

Body:
I think this is more efficient and safe than writing a loop.

df$temp <- round(df$bin, 0)  # round to 0 decimal places, store in a temporary var
df2 <- aggregate(df$s1noml, by=list(df$temp), FUN=sum)  # sum by group in temp var

If this doesn't work quite right it'd be helpful to provide a reprex for us to work with.


问:
C++ Using lambda for implicit constructor call expecting a function pointer
I am trying to implicitly construct an object from a lambda function. The constructor of the object takes a function pointer as parameter. But the code [ 1 ] doesn't compile with the message:

```<code>6 : <source>:6:5: note: candidate constructor not viable: no known conversion from '(lambda at /tmp/compiler-explorer-compiler117117-54-dfxyju.lkw98/example.cpp:22:14)' to 'Bar' (aka 'bool (*)()') for 1st argument
    Foo(Bar b) : m_b{b} {}
</code>```

But the standard states that a lambda function is implicitly convertible to a function pointer with the same parameter and return type [ 2 ]. This should be applicable here and therefore I would expect the constructor to be callable.

So why doesn't the code compile? Thanks for your explanations!

[ 1 ] Code example:

```<code>using Bar = bool(*)();

class Foo
{
public:
    Foo(Bar b) : m_b{b} {}
private:
    Bar m_b;
};

int main()
{
    // working
    Foo f1 ( [](){ return true; });
    Foo f2 = Bar( [](){ return true; });

    // working implicit conversion
    bool(*tmp)() = []() { return true; };
    Foo f3 = tmp;

    // not working
    Foo f4 = [](){ return true; };

    return 0;
}
</code>```

https://godbolt.org/g/QE4v1Z

[ 2 ] The C++14 Standard states in section 5.1.2 that:

The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator.

Which means the lambda should be implicitly (non-explicit) convertable to the function pointer.

tested with:

Clang5.0.0 -std=c++14

MSVC14.12 /permissive-

答:
Yes it is implicitly convertible to the function pointer; that's why bool(*tmp)() = []() { return true; }; works. The point is that in one implicit conversion sequence, only one user-defined conversion is allowed.

Implicit conversion sequence consists of the following, in this order:

zero or one standard conversion sequence;

zero or one user-defined conversion;

zero or one standard conversion sequence.

When considering the argument to a constructor or to a user-defined
  conversion function, only one standard conversion sequence is allowed
  (otherwise user-defined conversions could be effectively chained).

For Foo f4 = [](){ return true; };, which is copy initialization, the lambda has to be converted to the function pointer via the user-defined conversion function of lambda, then converted to Foo via the converting constructor of Foo, two user-defined conversions are required, but not allowed.

BTW:

Foo f1 ( [](){ return true; }); works because for direct intialization the constructor of Foo will be invoked directly; the lambda is converted to the function pointer and then passed as the argument to the constructor, this is fine.

Foo f2 = Bar( [](){ return true; }); works because lambda is explicitly converted to function pointer, which is converted to Foo implicitly later.

bool(*tmp)() = []() { return true; }; Foo f3 = tmp; works because the lambda is implicitly converted to function pointer as tmp, then tmp is converted Foo; only one user-defined conversion is required for either implicit conversion sequence, then it's fine.

Foo f5 = +[](){ return true; }; works because operator+ causes lambda converted to function pointer, that means for +[](){ return true; } you'll get the function pointer with type bool(*)(), then the story is same as f2.

Body:
I am trying to implicitly construct an object from a lambda function. The constructor of the object takes a function pointer as parameter. But the code [ 1 ] doesn't compile with the message:

6 : <source>:6:5: note: candidate constructor not viable: no known conversion from '(lambda at /tmp/compiler-explorer-compiler117117-54-dfxyju.lkw98/example.cpp:22:14)' to 'Bar' (aka 'bool (*)()') for 1st argument
    Foo(Bar b) : m_b{b} {}

But the standard states that a lambda function is implicitly convertible to a function pointer with the same parameter and return type [ 2 ]. This should be applicable here and therefore I would expect the constructor to be callable.

So why doesn't the code compile? Thanks for your explanations!

[ 1 ] Code example:

using Bar = bool(*)();

class Foo
{
public:
    Foo(Bar b) : m_b{b} {}
private:
    Bar m_b;
};

int main()
{
    // working
    Foo f1 ( [](){ return true; });
    Foo f2 = Bar( [](){ return true; });

    // working implicit conversion
    bool(*tmp)() = []() { return true; };
    Foo f3 = tmp;

    // not working
    Foo f4 = [](){ return true; };

    return 0;
}

https://godbolt.org/g/QE4v1Z

[ 2 ] The C++14 Standard states in section 5.1.2 that:

The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator.

Which means the lambda should be implicitly (non-explicit) convertable to the function pointer.

tested with:

Clang5.0.0 -std=c++14

MSVC14.12 /permissive-


问:
How to allow text-selection of a DIV, but prevent the text-selection of the father DIV?
I would like to allow the users to select text that resides in multiple DIVs that are located one after the other with small gaps between them.
the problem is, that when the user drags the mouse to perform the selection, they pass over the "gaps", which causes the whole parent DIV is selected momentarily, until they enter into the following child DIV.
This causes "flickers" behaviour and bad user experience, because the parent DIV also has images, and for a moment, all of the images are being selected too.
I tried several method suggested in this forum, including:
-moz-user-select: none; -khtml-user-select: none; -webkit-user-select: none;  user-select: none;
unselectable=on, and overriding the event onselectstart: return false;
Unfortunately, if I were to disable selecting text in the parent DIV, all the children DIVs immediately adopted that behaviour, and that is not what I meant.
I want that the parent DIV won't be selected, but its children will.
Thanks

Update:

The "onselectstart" is called only for the parent DIV (and spans/paragraphs beneath it), but it is NOT called when the image is being selected. Therefore, trying to manipulate it and use "return false;" is not relevant; the image simply won't get that event.

答:
IE's unselectable expando property does this for you automatically; it isn't inherited. For other browsers, use an extra CSS rule. Assuming the following HTML:

```<code><div class="unselectable" unselectable="on">
    Some unselectable text
    <div>Some selectable text</div>
    Some more unselectable text
</div>
</code>```

Use the following CSS. This defines an extra rule specifically enabling text selection for descendants of unselectable elements:

```<code>*.unselectable {
   -moz-user-select: -moz-none;
   -khtml-user-select: none;
   -webkit-user-select: none;
   -o-user-select: none;
   user-select: none;
}

*.unselectable * {
   -moz-user-select: text;
   -khtml-user-select: text;
   -webkit-user-select: text;
   -o-user-select: text;
   user-select: text;
}
</code>```

Body:
IE's unselectable expando property does this for you automatically; it isn't inherited. For other browsers, use an extra CSS rule. Assuming the following HTML:

<div class="unselectable" unselectable="on">
    Some unselectable text
    <div>Some selectable text</div>
    Some more unselectable text
</div>

Use the following CSS. This defines an extra rule specifically enabling text selection for descendants of unselectable elements:

*.unselectable {
   -moz-user-select: -moz-none;
   -khtml-user-select: none;
   -webkit-user-select: none;
   -o-user-select: none;
   user-select: none;
}

*.unselectable * {
   -moz-user-select: text;
   -khtml-user-select: text;
   -webkit-user-select: text;
   -o-user-select: text;
   user-select: text;
}


问:
Generating/Creating dynamically tabs in Android via passed JSON
I am trying to dynamically create tabs (and later add another dynamically created content in the fragments for each tab) from loaded JSON file via Volley, but without success.

```<code>public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;

String myData = "";

public static String test;

//Fragment List
private final List<Fragment> mFragmentList = new ArrayList<>();
//Title List
private final List<String> mFragmentTitleList = new ArrayList<>();
private ViewPagerAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    loaddata();
    //create multiple titles, but use OneFragment() for every new tab
    for(int i = 0; i < mFragmentTitleList.size(); i++) {
        mFragmentList.add(new OneFragment());
    }
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    // Tab ViewPager setting
    viewPager.setOffscreenPageLimit(mFragmentList.size());
    tabLayout.setupWithViewPager(viewPager);
}

//Loading the JSON data, which will be used to create dynamically content such as tabs and info for the Fragments
private void loaddata() {
    RequestQueue queue = Volley.newRequestQueue(this);
    String url = "https://ipfs.io/ipfs/QmQ69ScwoqSsFAdGV4oUKNaDMzSDuY9zcdRoFYkHPUZM7E";
    String line = "";

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            myData = response;
            //Log.d("response", myData);

            JSONObject object = null;
            try {
                object = new JSONObject(myData);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            JSONObject menuitems = null;
            try {
                menuitems = object.getJSONObject("menuitems");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            for(int i = 0; i<menuitems.length(); i++) {
                try {
                    mFragmentTitleList.add(menuitems.names().getString(i));
                    //mFragmentTitleList gives output [Alcohol Drinks, Soups, Salads]
                    Log.d("test", String.valueOf(mFragmentTitleList));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //Log.d(TAG, "Key = " + menuitems.names().getString(i) + " value = " + menuitems.get(menuitems.names().getString(i)));
            }
            /*try {
                Log.d("testagain", "\"" +categories.getString(2)+ "\"");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            */

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Context context = getApplicationContext();
            int duration = Toast.LENGTH_SHORT;
            Toast.makeText(context, "That didn't work!", duration);
        }
    });
    queue.add(stringRequest);
}

private void setupViewPager(ViewPager viewPager) {
    adapter = new ViewPagerAdapter(getSupportFragmentManager(), mFragmentList, mFragmentTitleList);
    viewPager.setAdapter(adapter);
}

//ViewPagerAdapter settings
class ViewPagerAdapter extends FragmentPagerAdapter {
    private List<Fragment> mFragmentList = new ArrayList<>();
    private List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager fm, List<Fragment> fragments, List<String> titleLists) {
        super(fm);
        this.mFragmentList = fragments;
        this.mFragmentTitleList = titleLists;
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList == null ? 0 : mFragmentList.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }

}
</code>```

}

At the end I should have 3 tabs, called Alcohol Drinks, Soups, Salads

At the moment the app just starts without any tabs generated. Thanks for helping me ! :)

答:
You have to create tabs after loaddata -> onResponse fill "mFragmentList" list.

Edit Paste this code

```<code>public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;

String myData = "";

public static String test;

//Fragment List
private final List<Fragment> mFragmentList = new ArrayList<>();
//Title List
private final List<String> mFragmentTitleList = new ArrayList<>();
private ViewPagerAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

viewPager = (ViewPager) findViewById(R.id.viewpager);
loaddata();

tabLayout = (TabLayout) findViewById(R.id.tabs);
}

//Loading the JSON data, which will be used to create dynamically content
such as tabs and info for the Fragments
private void loaddata() {
    RequestQueue queue = Volley.newRequestQueue(this);
    String url =
    "https://ipfs.io/ipfs/QmQ69ScwoqSsFAdGV4oUKNaDMzSDuY9zcdRoFYkHPUZM7E";
    String line = "";

StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        myData = response;
        //Log.d("response", myData);

        JSONObject object = null;
        try {
            object = new JSONObject(myData);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JSONObject menuitems = null;
        try {
            menuitems = object.getJSONObject("menuitems");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        for(int i = 0; i<menuitems.length(); i++) {
            try {
                mFragmentTitleList.add(menuitems.names().getString(i));
                //mFragmentTitleList gives output [Alcohol Drinks, Soups, Salads]
                Log.d("test", String.valueOf(mFragmentTitleList));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            //Log.d(TAG, "Key = " + menuitems.names().getString(i) + " value = " + menuitems.get(menuitems.names().getString(i)));
        }
        //create multiple titles, but use OneFragment() for every new tab
        for(int i = 0; i < mFragmentTitleList.size(); i++) {
            mFragmentList.add(new OneFragment());
        }
        setupViewPager(viewPager);
        tabLayout.setupWithViewPager(viewPager);
        // Tab ViewPager setting
        viewPager.setOffscreenPageLimit(mFragmentList.size());
        tabLayout.setupWithViewPager(viewPager);
        /*try {
            Log.d("testagain", "\"" +categories.getString(2)+ "\"");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        */

    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Context context = getApplicationContext();
        int duration = Toast.LENGTH_SHORT;
        Toast.makeText(context, "That didn't work!", duration);
    }
});
queue.add(stringRequest);
}

private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getSupportFragmentManager(), mFragmentList, mFragmentTitleList);
viewPager.setAdapter(adapter);
}

//ViewPagerAdapter settings
class ViewPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> mFragmentList = new ArrayList<>();
private List<String> mFragmentTitleList = new ArrayList<>();

public ViewPagerAdapter(FragmentManager fm, List<Fragment> fragments, List<String> titleLists) {
    super(fm);
    this.mFragmentList = fragments;
    this.mFragmentTitleList = titleLists;
}

@Override
public Fragment getItem(int position) {
    return mFragmentList.get(position);
}

@Override
public int getCount() {
    return mFragmentList == null ? 0 : mFragmentList.size();
}

@Override
public CharSequence getPageTitle(int position) {
    return mFragmentTitleList.get(position);
}

}
}
</code>```

Body:
I am trying to dynamically create tabs (and later add another dynamically created content in the fragments for each tab) from loaded JSON file via Volley, but without success.

public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;

String myData = "";

public static String test;

//Fragment List
private final List<Fragment> mFragmentList = new ArrayList<>();
//Title List
private final List<String> mFragmentTitleList = new ArrayList<>();
private ViewPagerAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    loaddata();
    //create multiple titles, but use OneFragment() for every new tab
    for(int i = 0; i < mFragmentTitleList.size(); i++) {
        mFragmentList.add(new OneFragment());
    }
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    // Tab ViewPager setting
    viewPager.setOffscreenPageLimit(mFragmentList.size());
    tabLayout.setupWithViewPager(viewPager);
}

//Loading the JSON data, which will be used to create dynamically content such as tabs and info for the Fragments
private void loaddata() {
    RequestQueue queue = Volley.newRequestQueue(this);
    String url = "https://ipfs.io/ipfs/QmQ69ScwoqSsFAdGV4oUKNaDMzSDuY9zcdRoFYkHPUZM7E";
    String line = "";

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            myData = response;
            //Log.d("response", myData);

            JSONObject object = null;
            try {
                object = new JSONObject(myData);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            JSONObject menuitems = null;
            try {
                menuitems = object.getJSONObject("menuitems");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            for(int i = 0; i<menuitems.length(); i++) {
                try {
                    mFragmentTitleList.add(menuitems.names().getString(i));
                    //mFragmentTitleList gives output [Alcohol Drinks, Soups, Salads]
                    Log.d("test", String.valueOf(mFragmentTitleList));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                //Log.d(TAG, "Key = " + menuitems.names().getString(i) + " value = " + menuitems.get(menuitems.names().getString(i)));
            }
            /*try {
                Log.d("testagain", "\"" +categories.getString(2)+ "\"");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            */

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Context context = getApplicationContext();
            int duration = Toast.LENGTH_SHORT;
            Toast.makeText(context, "That didn't work!", duration);
        }
    });
    queue.add(stringRequest);
}

private void setupViewPager(ViewPager viewPager) {
    adapter = new ViewPagerAdapter(getSupportFragmentManager(), mFragmentList, mFragmentTitleList);
    viewPager.setAdapter(adapter);
}

//ViewPagerAdapter settings
class ViewPagerAdapter extends FragmentPagerAdapter {
    private List<Fragment> mFragmentList = new ArrayList<>();
    private List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager fm, List<Fragment> fragments, List<String> titleLists) {
        super(fm);
        this.mFragmentList = fragments;
        this.mFragmentTitleList = titleLists;
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList == null ? 0 : mFragmentList.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }

}

}

At the end I should have 3 tabs, called Alcohol Drinks, Soups, Salads

At the moment the app just starts without any tabs generated. Thanks for helping me ! :)

Body:
You have to create tabs after loaddata -> onResponse fill "mFragmentList" list.

Edit Paste this code

public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;

String myData = "";

public static String test;

//Fragment List
private final List<Fragment> mFragmentList = new ArrayList<>();
//Title List
private final List<String> mFragmentTitleList = new ArrayList<>();
private ViewPagerAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

viewPager = (ViewPager) findViewById(R.id.viewpager);
loaddata();

tabLayout = (TabLayout) findViewById(R.id.tabs);
}

//Loading the JSON data, which will be used to create dynamically content
such as tabs and info for the Fragments
private void loaddata() {
    RequestQueue queue = Volley.newRequestQueue(this);
    String url =
    "https://ipfs.io/ipfs/QmQ69ScwoqSsFAdGV4oUKNaDMzSDuY9zcdRoFYkHPUZM7E";
    String line = "";

StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        myData = response;
        //Log.d("response", myData);

        JSONObject object = null;
        try {
            object = new JSONObject(myData);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JSONObject menuitems = null;
        try {
            menuitems = object.getJSONObject("menuitems");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        for(int i = 0; i<menuitems.length(); i++) {
            try {
                mFragmentTitleList.add(menuitems.names().getString(i));
                //mFragmentTitleList gives output [Alcohol Drinks, Soups, Salads]
                Log.d("test", String.valueOf(mFragmentTitleList));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            //Log.d(TAG, "Key = " + menuitems.names().getString(i) + " value = " + menuitems.get(menuitems.names().getString(i)));
        }
        //create multiple titles, but use OneFragment() for every new tab
        for(int i = 0; i < mFragmentTitleList.size(); i++) {
            mFragmentList.add(new OneFragment());
        }
        setupViewPager(viewPager);
        tabLayout.setupWithViewPager(viewPager);
        // Tab ViewPager setting
        viewPager.setOffscreenPageLimit(mFragmentList.size());
        tabLayout.setupWithViewPager(viewPager);
        /*try {
            Log.d("testagain", "\"" +categories.getString(2)+ "\"");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        */

    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Context context = getApplicationContext();
        int duration = Toast.LENGTH_SHORT;
        Toast.makeText(context, "That didn't work!", duration);
    }
});
queue.add(stringRequest);
}

private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getSupportFragmentManager(), mFragmentList, mFragmentTitleList);
viewPager.setAdapter(adapter);
}

//ViewPagerAdapter settings
class ViewPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> mFragmentList = new ArrayList<>();
private List<String> mFragmentTitleList = new ArrayList<>();

public ViewPagerAdapter(FragmentManager fm, List<Fragment> fragments, List<String> titleLists) {
    super(fm);
    this.mFragmentList = fragments;
    this.mFragmentTitleList = titleLists;
}

@Override
public Fragment getItem(int position) {
    return mFragmentList.get(position);
}

@Override
public int getCount() {
    return mFragmentList == null ? 0 : mFragmentList.size();
}

@Override
public CharSequence getPageTitle(int position) {
    return mFragmentTitleList.get(position);
}

}
}


问:
How to get the access token of REST API endpoint using Rest Assured with POST method, Currently I am getting 404 error?
I am trying to run  POST method to get the access token using REST Assured Code. But it is returning  404 error. My code is as below.
POSTMAN Configuration as below same  trying to replicate using Rest Assured

```<code>Method : POST

Authorization tab:
             Type : Basic Auth
             UserName :  ABCD
             Passsowrd : Test@1234

Body Tab :
           Selecting  "application/x-www-form-urlencode" Radio Button
           Key : grant_type  Value : Client_Credentials
           Key : Scope       value : ABCDAPI

given().auth().basic("Username Here","Password type here")
.header("Authorization", "Basic T1VUUkVBQ0hfQVBJX0NMSUVOVDpIWmRwREwydkR5UE5iQmtvWEdxSkFpK1Qxa08yWSszNndxQXhoYTVXUWhZPQ==n")
.header("Content-Type","application/x-www-form-urlencoded")
.contentType("application/x-www-form-urlencoded")
.body("[{\"grant_type\":\"client_credentials\"}]")
.body("[{\"scope\":\"ABCDpi\"}]").when()
.post("https://ABCD.KLM.id.XYZ-Cloud.net/oauth2/access_token?realm=PQR")
.then().contentType("").statusCode(200);
</code>```

I am also attaching the screenshot of Postman where it is working enter image description here

答:
Before trying the below code give yourself some time to look here.

Also application/x-www-form-urlencoded has its POST variables stored as key-value pairs in the body.

```<code>given().auth().basic(username, password)
.header("Content-Type","application/x-www-form-urlencoded")
.formParam("grant_type", "client_credentials")
.formParam("scope", "ABCDpi")
.post("https://ABCD.KLM.id.XYZ-Cloud.net/oauth2/access_token?realm=PQR")
.then().contentType("").statusCode(200);
</code>```

Body:
I am trying to run  POST method to get the access token using REST Assured Code. But it is returning  404 error. My code is as below.
POSTMAN Configuration as below same  trying to replicate using Rest Assured

Method : POST

Authorization tab:
             Type : Basic Auth
             UserName :  ABCD
             Passsowrd : Test@1234

Body Tab :
           Selecting  "application/x-www-form-urlencode" Radio Button
           Key : grant_type  Value : Client_Credentials
           Key : Scope       value : ABCDAPI

given().auth().basic("Username Here","Password type here")
.header("Authorization", "Basic T1VUUkVBQ0hfQVBJX0NMSUVOVDpIWmRwREwydkR5UE5iQmtvWEdxSkFpK1Qxa08yWSszNndxQXhoYTVXUWhZPQ==n")
.header("Content-Type","application/x-www-form-urlencoded")
.contentType("application/x-www-form-urlencoded")
.body("[{\"grant_type\":\"client_credentials\"}]")
.body("[{\"scope\":\"ABCDpi\"}]").when()
.post("https://ABCD.KLM.id.XYZ-Cloud.net/oauth2/access_token?realm=PQR")
.then().contentType("").statusCode(200);

I am also attaching the screenshot of Postman where it is working enter image description here

Body:
Before trying the below code give yourself some time to look here.

Also application/x-www-form-urlencoded has its POST variables stored as key-value pairs in the body.

given().auth().basic(username, password)
.header("Content-Type","application/x-www-form-urlencoded")
.formParam("grant_type", "client_credentials")
.formParam("scope", "ABCDpi")
.post("https://ABCD.KLM.id.XYZ-Cloud.net/oauth2/access_token?realm=PQR")
.then().contentType("").statusCode(200);