问:
React Native - Updating state upon pressing a button
I currently have two buttons (No, Yes)( component imported from native-base package) that when pressed should update the state with either 0 or 1 respectively and also toggle between true or false to notify if this field has been filled (by default, neither of the two will be pressed, hence set to false).

I have a handleOnClick() function bound to the "No" button with a debugger to test if I actually do hit it, but once inside this function, I'm not sure how to grab any info for associated components (i.e. the "No" text within the Text component) so I can perform logic to check if "No" or "Yes" was pressed.

If this was done in pure React, I know I can access certain data attributes that I add to DOM elements or traverse the DOM, but I'm not sure how to do this in React Native or if I'm able to add custom props to a built in component that I can then access.

```<code>class Toggle extends Component {
  constructor() {
    super()

    this.state = {
      selectedOption: '',
      isFilled: false
    }

    this.checkField = this.checkField.bind(this)
    this.handleOnClick = this.handleOnClick.bind(this)
  }

  checkField() {
    console.log(this)
    // debugger
  }

  handleOnClick(ev) {
    debugger
    console.log("I was pressed")
  }

  render() {
    const options = this.props.inputInfo.options //=> [0,1]
    const optionLabels = this.props.inputInfo.options_labels_en //=>["No","Yes"]

    return (
      <View style={{flexDirection: 'row'}}>
        <View style={styles.row} >
          <Button light full onPress={this.handleOnClick}><Text>No</Text></Button>
        </View>
        <View style={styles.row} >
          <Button success full><Text>Yes</Text></Button>
        </View>
      </View>
    )
  }
}
</code>```

答:
Have you tried:

```<code>render() {
    const options = this.props.inputInfo.options //=> [0,1]
    const optionLabels = this.props.inputInfo.options_labels_en //=>["No","Yes"]

return (
  <View style={{flexDirection: 'row'}}>
    <View style={styles.row} >
      <Button light full onPress={() => this.handleOnClick('No')}><Text>No</Text></Button>
    </View>
    <View style={styles.row} >
      <Button success full onPress={() => this.handleOnClick('Yes')}><Text>Yes</Text></Button>
    </View>
  </View>
)
</code>```

}

and

```<code>  handleOnClick(word) {
    this.setState({ selectedOption: word, isFilled: true })
  }
</code>```

Body:
I currently have two buttons (No, Yes)( component imported from native-base package) that when pressed should update the state with either 0 or 1 respectively and also toggle between true or false to notify if this field has been filled (by default, neither of the two will be pressed, hence set to false).

I have a handleOnClick() function bound to the "No" button with a debugger to test if I actually do hit it, but once inside this function, I'm not sure how to grab any info for associated components (i.e. the "No" text within the Text component) so I can perform logic to check if "No" or "Yes" was pressed.

If this was done in pure React, I know I can access certain data attributes that I add to DOM elements or traverse the DOM, but I'm not sure how to do this in React Native or if I'm able to add custom props to a built in component that I can then access.

class Toggle extends Component {
  constructor() {
    super()

    this.state = {
      selectedOption: '',
      isFilled: false
    }

    this.checkField = this.checkField.bind(this)
    this.handleOnClick = this.handleOnClick.bind(this)
  }

  checkField() {
    console.log(this)
    // debugger
  }

  handleOnClick(ev) {
    debugger
    console.log("I was pressed")
  }

  render() {
    const options = this.props.inputInfo.options //=> [0,1]
    const optionLabels = this.props.inputInfo.options_labels_en //=>["No","Yes"]

    return (
      <View style={{flexDirection: 'row'}}>
        <View style={styles.row} >
          <Button light full onPress={this.handleOnClick}><Text>No</Text></Button>
        </View>
        <View style={styles.row} >
          <Button success full><Text>Yes</Text></Button>
        </View>
      </View>
    )
  }
}

Body:
Have you tried:

render() {
    const options = this.props.inputInfo.options //=> [0,1]
    const optionLabels = this.props.inputInfo.options_labels_en //=>["No","Yes"]

return (
  <View style={{flexDirection: 'row'}}>
    <View style={styles.row} >
      <Button light full onPress={() => this.handleOnClick('No')}><Text>No</Text></Button>
    </View>
    <View style={styles.row} >
      <Button success full onPress={() => this.handleOnClick('Yes')}><Text>Yes</Text></Button>
    </View>
  </View>
)

}

and

  handleOnClick(word) {
    this.setState({ selectedOption: word, isFilled: true })
  }


来源: stackexchange

问:
What's the equivalent of jasmine.createSpy().and.callFake(fn) in sinonjs
I'm looking for the equivalent of jasmine.createSpy().and.callFake(fn) in sinonjs.

For example:

```<code>const mySpy = jasmine.createSpy('my spy')
.and
.callFake((options) => Object.assign({}, {name: 'foo'}, options));
</code>```

答:
This should work:

```<code>var stub = sinon.stub(object, "method", func);
</code>```

Check this out: http://legacy.sinonjs.org/docs/

ContentLicense: CC BY-SA 3.0

Body:
I'm looking for the equivalent of jasmine.createSpy().and.callFake(fn) in sinonjs.

For example:

const mySpy = jasmine.createSpy('my spy')
.and
.callFake((options) => Object.assign({}, {name: 'foo'}, options));

Body:
This should work:

var stub = sinon.stub(object, "method", func);

Check this out: http://legacy.sinonjs.org/docs/


问:
How exactly are function values ('function pointers') implemented in Go?
From the documentation for reflect.Value.Pointer():

If v's Kind is Func, the returned pointer is an underlying code pointer, but not necessarily enough to identify a single function uniquely. The only guarantee is that the result is zero if and only if v is a nil func Value.

It seems clear that function-valued variables must contain more than just a  code pointer.  Given that Go supports method pointers, this is hardly surprising - but what is the actual underlying implementation?

(And how does it differ, if at all, for function values created using reflection?  See comment in the source for Value.Pointer().)

答: The "New Implementation" section of the design document describes how function pointers are represented.</p>


问:
Firebase navbar login
here is a problem with my navigation bar, when I get my website, I sometimes see this soon:

I'm using ng-show and ng-hide, for when you are logged in or not.

Is this the best way or is there a better way?

Sincerely,

Jur Dekker

答:
you can use ng-cloak to prevent from being briefly displayed by the browser.

https://docs.angularjs.org/api/ng/directive/ngCloak

Title: Firebase navbar login


问:
Crystal Server doesn't seem to pass credential to SharePoint WebDAV folder?
We have Crystal Server setup to automatically deposit generated reports to a SharePoint WebDAV folder. The Crystal Server user is setup in sharepoint with the right permissions but yet, authentication fails when it tries to access the folder. We are using NTLM.

Any idea what could be causing this? Should we use Kerberos? Any help appreciated.

Thanks.

答: Crystal Report Server is Java-based (Tomcat or WAC) and Java SSO does not support NTLM so yes, you will need to use Kerberos.  I just walked through configuring SSO for our Crystal Report Server environment and had to go down the Kerberos route.</p>

ContentLicense: CC BY-SA 2.5


问:
Unexpected Token in JSX (React Component)
I am sorry if this is the wrong place to ask something like this, but I cannot find this error for the life of me. I even slept on it and tried for another couple hours this morning.

This is my error:

```<code>ERROR in ./src/components/results_instructor_view/weekly_report_results_instructor.js
Module build failed: SyntaxError: C:/Users/Temple/Source/Workspaces/LMS/TechAcademyLMS/TechAcademyLMS/Scripts/React-Redux-App/src/components/results_instructor_view/weekly_report_results_instructor.js: Unexpected token, expected , (139:4)

  137 |
  138 |
> 139 |                 } else {
      |                   ^
  140 |
  141 |                         return (<h6>No weekly reports yet</h6>);
  142 |                 }

 @ ./src/containers/main_display_container.js 85:40-121
 @ ./src/components/app.js
 @ ./src/routes.js
 @ ./src/Index.js
</code>```

This is my code:

```<code>// libraries
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

// Loader
import Loader from '../../components/loader/loader';

//actions
import { resultsInstructorViewAction } from '../../actions/Results/results_instructor_view_action';

class WeeklyReportResult extends Component {

    componentDidMount() {
        // getting the user info from the props/params
        const userInfo = this.props.match.params.value.split(',');
        // url for the getWeeklyReport
        const url = `/SPA/getWeeklyReport?Id=${userInfo[1]}`;

        this.props.resultsInstructorViewAction(url);
    }

    componentDidUpdate(prevProps, prevState) {

        // set loaded to true
        if (this.state.Loaded === false) {

            this.setState({ Loaded: true });
        }

    }

    render() {

        // checking to see if the data exists
        if (this.props.resultsInstructorView > [0]) {
            const renderList = this.props.resultsInstructorView.map((item, i) => {
                return (
                    // Key for error in console due to mapping
                    <div key={i}>
                        <hr className="style-two" />
                        <h4>Date Submitted: </h4><p>{item.Date}</p>
                        <h5>Course Position: </h5><p>{item.CoursePosition}</p>
                        <h5>Need Help: </h5><p>{item.NeedHelp}</p>
                        <h5>Materials and Supplies Needed: </h5><p>{item.MaterialsAndSupplies}</p>
                        <h5>Meetups: </h5><p>{item.Meetups}</p>
                        <h5>Positive Experiences: </h5><p>{item.Positives}</p>
                        <h5>Complaints: </h5><p>{item.Complaints}</p>
                        <h5>Hours Studied: </h5><p>{item.HoursStudied}</p>
                        <h5>Job Search: </h5><p>{item.JobSearch}</p>
                        <h5>Referral: </h5><p>{item.Referral}</p>
                        <h5>Miscellaneous: </h5><p>{item.Miscellaneous}</p>

                    <button type="button" className="btn btn-info btn-lg" onClick={this.toggleModal} id={item.DailyReportId}>
                                Give Feedback
                    </button>
                    </div>
            );
        });
    }

                    // building the already responded daily reports
const renderAllList = this.props.resultsInstructorView.map((item, i) => {
    if (item.Feedbacks.length > 0) {

        return (

            <Panel key={i} header={item.Date} eventKey={i} bsStyle="primary" className="text-center">
                <hr className="style-two" />
                <div className="text-left">
                    <h6><strong>Date Submitted :</strong> {item.Date}</h6>
                    <h6><strong>Course Position : </strong>{item.CoursePosition}</h6>
                    <h6><strong>Need Help : </strong>{item.NeedHelp}</h6>
                    <h6><strong>Materials and Supplies :</strong> {item.MaterialsAndSupplies}</h6>
                    <h6><strong>Positives : </strong>{item.Positives}</h6>
                    <h6><strong>Complaints :</strong> {item.Complaints}</h6>
                    <h6><strong>Hours Studied :</strong> {item.HoursStudied}</h6>
                    <h6><strong>Job Search :</strong> {item.JobSearch}</h6>
                    <h6><strong>Referral :</strong> {item.Referral}</h6>
                    <h6><strong>Miscellaneous :</strong> {item.Miscellaneous}</h6>
                    <h6><strong>Instructor Feedback : </strong><mark>{item.Feedbacks[0].Content}</mark></h6>
                </div>

            </Panel>
        );
}

            return (
                <div className="container text-center">

                    <div className="row">
                        <h1>Weekly Reports</h1>
                        <h3>Student Name: </h3><h5>{this.props.match.params.value.split(',')[2]}</h5>

                    </div>

                    <div className="col-sm-12 text-left">

                        {renderList}

                        <hr className="style-two" />
                            <h2 className="text-center">Past Reports</h2>

                            <Accordion>
                                {renderAllList}
                            </Accordion>
                            <FeedbackModal
                                show={this.state.isOpen}
                                toggleModal={this.toggleModal}
                                name={this.props.match.params.value.split(',')[0]}
                                id={this.props.match.params.value.split(',')[1]}
                                weeklyReportId={this.state.tempId}

                            />

                    </div>

                </div>

            );

        } else {

            return (<h6>No weekly reports yet</h6>);
        }

    }
    }

function mapStateToProps(state) {
    return { resultsInstructorView: state.ResultsInstructorView };
}

function mapDispatchToProps(dispatch) {
    return bindActionCreators({
        resultsInstructorViewAction
    }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(WeeklyReportResult);
</code>```

答:
The else statement should go before the second return statement, like so:</p>

```<code>render() {
   if (this.props.resultsInstructorView > [0]) {
 return (
//code here
);
} else {
return (
  //code here.
 );
}
</code>```

Body:
I am sorry if this is the wrong place to ask something like this, but I cannot find this error for the life of me. I even slept on it and tried for another couple hours this morning.

This is my error:

ERROR in ./src/components/results_instructor_view/weekly_report_results_instructor.js
Module build failed: SyntaxError: C:/Users/Temple/Source/Workspaces/LMS/TechAcademyLMS/TechAcademyLMS/Scripts/React-Redux-App/src/components/results_instructor_view/weekly_report_results_instructor.js: Unexpected token, expected , (139:4)

  137 |
  138 |
> 139 |                 } else {
      |                   ^
  140 |
  141 |                         return (
No weekly reports yet
);
  142 |                 }

 @ ./src/containers/main_display_container.js 85:40-121
 @ ./src/components/app.js
 @ ./src/routes.js
 @ ./src/Index.js

This is my code:

// libraries
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

// Loader
import Loader from '../../components/loader/loader';

//actions
import { resultsInstructorViewAction } from '../../actions/Results/results_instructor_view_action';

class WeeklyReportResult extends Component {

    componentDidMount() {
        // getting the user info from the props/params
        const userInfo = this.props.match.params.value.split(',');
        // url for the getWeeklyReport
        const url = `/SPA/getWeeklyReport?Id=${userInfo[1]}`;

        this.props.resultsInstructorViewAction(url);
    }

    componentDidUpdate(prevProps, prevState) {

        // set loaded to true
        if (this.state.Loaded === false) {

            this.setState({ Loaded: true });
        }

    }

    render() {

        // checking to see if the data exists
        if (this.props.resultsInstructorView > [0]) {
            const renderList = this.props.resultsInstructorView.map((item, i) => {
                return (
                    // Key for error in console due to mapping

Date Submitted:

{item.Date}

Course Position:

{item.CoursePosition}

Need Help:

{item.NeedHelp}

Materials and Supplies Needed:

{item.MaterialsAndSupplies}

Meetups:

{item.Meetups}

Positive Experiences:

{item.Positives}

Complaints:

{item.Complaints}

Hours Studied:

{item.HoursStudied}

Job Search:

{item.JobSearch}

Referral:

{item.Referral}

Miscellaneous:

{item.Miscellaneous}

                    <button type="button" className="btn btn-info btn-lg" onClick={this.toggleModal} id={item.DailyReportId}>
                                Give Feedback
                    </button>

            );
        });
    }

                    // building the already responded daily reports
const renderAllList = this.props.resultsInstructorView.map((item, i) => {
    if (item.Feedbacks.length > 0) {

        return (

            <Panel key={i} header={item.Date} eventKey={i} bsStyle="primary" className="text-center">

Date Submitted : {item.Date}

Course Position : {item.CoursePosition}

Need Help : {item.NeedHelp}

Materials and Supplies : {item.MaterialsAndSupplies}

Positives : {item.Positives}

Complaints : {item.Complaints}

Hours Studied : {item.HoursStudied}

Job Search : {item.JobSearch}

Referral : {item.Referral}

Miscellaneous : {item.Miscellaneous}

Instructor Feedback : {item.Feedbacks[0].Content}

            </Panel>
        );
}

            return (

Weekly Reports

Student Name:

{this.props.match.params.value.split(',')[2]}

                        {renderList}

Past Reports

                            <Accordion>
                                {renderAllList}
                            </Accordion>
                            <FeedbackModal
                                show={this.state.isOpen}
                                toggleModal={this.toggleModal}
                                name={this.props.match.params.value.split(',')[0]}
                                id={this.props.match.params.value.split(',')[1]}
                                weeklyReportId={this.state.tempId}

                            />

            );

        } else {

            return (
No weekly reports yet
);
        }

    }
    }

function mapStateToProps(state) {
    return { resultsInstructorView: state.ResultsInstructorView };
}

function mapDispatchToProps(dispatch) {
    return bindActionCreators({
        resultsInstructorViewAction
    }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(WeeklyReportResult);

Body:
The else statement should go before the second return statement, like so:

render() {
   if (this.props.resultsInstructorView > [0]) {
 return (
//code here
);
} else {
return (
  //code here.
 );
}


问:
Embedded Jetty: A ServletContext is required to configure default servlet handling
I'm trying to setup a spring boot app with an embedded jetty server. This server shall run a small webapp. However, when starting I get the following exception, just after the war file has been loaded.

Trace

```<code>2016-10-02 16:07:59.302 ERROR 18765 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultServletHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123) ~[spring-beans-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018) ~[spring-beans-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510) ~[spring-beans-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772) ~[spring-beans-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839) ~[spring-context-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) ~[spring-context-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1191) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    ... 24 common frames omitted
Caused by: java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
    at org.springframework.util.Assert.notNull(Assert.java:115) ~[spring-core-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer.<init>(DefaultServletHandlerConfigurer.java:53) ~[spring-webmvc-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping(WebMvcConfigurationSupport.java:451) ~[spring-webmvc-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration$$EnhancerBySpringCGLIB$$671a10db.CGLIB$defaultServletHandlerMapping$28(<generated>) ~[spring-boot-autoconfigure-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration$$EnhancerBySpringCGLIB$$671a10db$$FastClassBySpringCGLIB$$f33d99c3.invoke(<generated>) ~[spring-boot-autoconfigure-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356) ~[spring-context-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration$$EnhancerBySpringCGLIB$$671a10db.defaultServletHandlerMapping(<generated>) ~[spring-boot-autoconfigure-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_111]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:1.7.0_111]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.7.0_111]
    at java.lang.reflect.Method.invoke(Method.java:606) ~[na:1.7.0_111]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    ... 25 common frames omitted
</code>```

I've trimmed down the code to a minimum and still get the error.

Main

```<code>@Configuration
@ComponentScan
@EnableAutoConfiguration
public class ServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServerApplication.class);
    }

}
</code>```

Configuration

```<code>@Configuration

@EnableAutoConfiguration
public class JettyServerCustomizer implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        if (container instanceof JettyEmbeddedServletContainerFactory) {
            customizeJetty((JettyEmbeddedServletContainerFactory) container);
        }
    }

    public void customizeJetty(
            JettyEmbeddedServletContainerFactory containerFactory) {
        containerFactory.addServerCustomizers(jettyServerCustomizer());
    }

    @Bean
    public JettyServerCustomizer jettyServerCustomizer() {
        return new JettyServerCustomizer() {

            @Override
            public void customize(Server server) {
                String jetty_home = System.getProperty("jetty.home","..");
                WebAppContext webapp = new WebAppContext();
                webapp.setContextPath("/");
                webapp.setWar(jetty_home+"/webapps/sample.war");
                server.setHandler(webapp);
            }
        };
    }
}
</code>```

Any suggestions? Thanks!

Update

After trying the suggestion from Strelok i get this error instead.

```<code>2016-10-02 16:55:03.715  INFO 20025 --- [           main] org.eclipse.jetty.servlet.ServletHolder  : unavailable

java.lang.NullPointerException: null
    at org.eclipse.jetty.servlet.ServletHolder.initMultiPart(ServletHolder.java:702) [jetty-servlet-9.2.16.v20160414.jar!/:9.2.16.v20160414]
    at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:607) [jetty-servlet-9.2.16.v20160414.jar!/:9.2.16.v20160414]
    at org.eclipse.jetty.servlet.ServletHolder.initialize(ServletHolder.java:396) [jetty-servlet-9.2.16.v20160414.jar!/:9.2.16.v20160414]
    at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:871) [jetty-servlet-9.2.16.v20160414.jar!/:9.2.16.v20160414]
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedWebAppContext$JettyEmbeddedServletHandler.deferredInitialize(JettyEmbeddedWebAppContext.java:46) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedWebAppContext.deferredInitialize(JettyEmbeddedWebAppContext.java:36) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainer.handleDeferredInitialize(JettyEmbeddedServletContainer.java:167) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainer.handleDeferredInitialize(JettyEmbeddedServletContainer.java:170) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainer.start(JettyEmbeddedServletContainer.java:114) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.startEmbeddedServletContainer(EmbeddedWebApplicationContext.java:293) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:141) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541) [spring-context-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1191) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
</code>```

答:
This error occurs due to WebMvc support being enabled. This can occur due to a configuration class containing @EnableWebMvc, but also due to auto configuration. Try excluding the WebMvc auto configuration.

```<code>@EnableAutoConfiguration(exclude = {WebMvcAutoConfiguration.class, WebMvcAutoConfiguration.EnableWebMvcConfiguration.class, WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter.class})
</code>```

In my case, I needed the WebMvc support, so I obtained access to the @Configuration class which inherited from WebMvcConfigurationSupport and set the servlet context with a Jetty configuration to fix the NPE.

```<code>@Bean
public org.eclipse.jetty.webapp.Configuration jettyConfiguration() {
    return new AbstractConfiguration() {
        @Override
        public void configure(WebAppContext context) throws Exception {
            // This line fixes the error in my case
            config.setServletContext(context.getServletContext());
        }
    };
}
</code>```

Body:
I'm trying to setup a spring boot app with an embedded jetty server. This server shall run a small webapp. However, when starting I get the following exception, just after the war file has been loaded.

Trace

2016-10-02 16:07:59.302 ERROR 18765 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultServletHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123) ~[spring-beans-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018) ~[spring-beans-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510) ~[spring-beans-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772) ~[spring-beans-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839) ~[spring-context-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) ~[spring-context-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1191) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    ... 24 common frames omitted
Caused by: java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
    at org.springframework.util.Assert.notNull(Assert.java:115) ~[spring-core-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer.<init>(DefaultServletHandlerConfigurer.java:53) ~[spring-webmvc-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping(WebMvcConfigurationSupport.java:451) ~[spring-webmvc-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration$$EnhancerBySpringCGLIB$$671a10db.CGLIB$defaultServletHandlerMapping$28(<generated>) ~[spring-boot-autoconfigure-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration$$EnhancerBySpringCGLIB$$671a10db$$FastClassBySpringCGLIB$$f33d99c3.invoke(<generated>) ~[spring-boot-autoconfigure-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356) ~[spring-context-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration$$EnhancerBySpringCGLIB$$671a10db.defaultServletHandlerMapping(<generated>) ~[spring-boot-autoconfigure-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_111]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:1.7.0_111]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.7.0_111]
    at java.lang.reflect.Method.invoke(Method.java:606) ~[na:1.7.0_111]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    ... 25 common frames omitted

I've trimmed down the code to a minimum and still get the error.

Main

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class ServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServerApplication.class);
    }

}

Configuration

@Configuration

@EnableAutoConfiguration
public class JettyServerCustomizer implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        if (container instanceof JettyEmbeddedServletContainerFactory) {
            customizeJetty((JettyEmbeddedServletContainerFactory) container);
        }
    }

    public void customizeJetty(
            JettyEmbeddedServletContainerFactory containerFactory) {
        containerFactory.addServerCustomizers(jettyServerCustomizer());
    }

    @Bean
    public JettyServerCustomizer jettyServerCustomizer() {
        return new JettyServerCustomizer() {

            @Override
            public void customize(Server server) {
                String jetty_home = System.getProperty("jetty.home","..");
                WebAppContext webapp = new WebAppContext();
                webapp.setContextPath("/");
                webapp.setWar(jetty_home+"/webapps/sample.war");
                server.setHandler(webapp);
            }
        };
    }
}

Any suggestions? Thanks!

Update

After trying the suggestion from Strelok i get this error instead.

2016-10-02 16:55:03.715  INFO 20025 --- [           main] org.eclipse.jetty.servlet.ServletHolder  : unavailable

java.lang.NullPointerException: null
    at org.eclipse.jetty.servlet.ServletHolder.initMultiPart(ServletHolder.java:702) [jetty-servlet-9.2.16.v20160414.jar!/:9.2.16.v20160414]
    at org.eclipse.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:607) [jetty-servlet-9.2.16.v20160414.jar!/:9.2.16.v20160414]
    at org.eclipse.jetty.servlet.ServletHolder.initialize(ServletHolder.java:396) [jetty-servlet-9.2.16.v20160414.jar!/:9.2.16.v20160414]
    at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:871) [jetty-servlet-9.2.16.v20160414.jar!/:9.2.16.v20160414]
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedWebAppContext$JettyEmbeddedServletHandler.deferredInitialize(JettyEmbeddedWebAppContext.java:46) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedWebAppContext.deferredInitialize(JettyEmbeddedWebAppContext.java:36) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainer.handleDeferredInitialize(JettyEmbeddedServletContainer.java:167) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainer.handleDeferredInitialize(JettyEmbeddedServletContainer.java:170) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainer.start(JettyEmbeddedServletContainer.java:114) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.startEmbeddedServletContainer(EmbeddedWebApplicationContext.java:293) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:141) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541) [spring-context-4.2.6.RELEASE.jar!/:4.2.6.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:766) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:361) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:307) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1191) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1180) [spring-boot-1.3.5.RELEASE.jar!/:1.3.5.RELEASE]

Body:
This error occurs due to WebMvc support being enabled. This can occur due to a configuration class containing @EnableWebMvc, but also due to auto configuration. Try excluding the WebMvc auto configuration.

@EnableAutoConfiguration(exclude = {WebMvcAutoConfiguration.class, WebMvcAutoConfiguration.EnableWebMvcConfiguration.class, WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter.class})

In my case, I needed the WebMvc support, so I obtained access to the @Configuration class which inherited from WebMvcConfigurationSupport and set the servlet context with a Jetty configuration to fix the NPE.

@Bean
public org.eclipse.jetty.webapp.Configuration jettyConfiguration() {
    return new AbstractConfiguration() {
        @Override
        public void configure(WebAppContext context) throws Exception {
            // This line fixes the error in my case
            config.setServletContext(context.getServletContext());
        }
    };
}


问:
Is it possible to generate the original files back from the minified JS file generated by webpack
I have lost my original react JS code files. All I have left with now is the final production minified JS file, which was generated from the original files using webpack. Is there any way that I could somehow unminify or generate back the original files from the availalbe minified file? I don't have any source mapping available.</p>

答:
Well thats "possible", but you won't be really able to read it.
You can try to use online "unminifier" tools e.g. http://unminify.com/ to pretty print your code.</p>


问:
Apache Spark how to append new column from list/array to Spark dataframe
I am using Apache Spark 2.0 Dataframe/Dataset API
I want to add a new column to my dataframe from List of values. My list has same number of values like given dataframe.

```<code>val list = List(4,5,10,7,2)
val df   = List("a","b","c","d","e").toDF("row1")
</code>```

I would like to do something like:

```<code>val appendedDF = df.withColumn("row2",somefunc(list))
df.show()
// +----+------+
// |row1 |row2 |
// +----+------+
// |a    |4    |
// |b    |5    |
// |c    |10   |
// |d    |7    |
// |e    |2    |
// +----+------+
</code>```

For any ideas I would be greatful, my dataframe in reality contains more columns.

答:
Adding for completeness: the fact that the input list (which exists in driver memory) has the same size as the DataFrame suggests that this is a small DataFrame to begin with - so you might consider collect()-ing it, zipping with list, and converting back into a DataFrame if needed:

```<code>df.collect()
  .map(_.getAs[String]("row1"))
  .zip(list).toList
  .toDF("row1", "row2")
</code>```

That won't be faster, but if the data is really small it might be negligible and the code is (arguably) clearer.

Body:
I am using Apache Spark 2.0 Dataframe/Dataset API
I want to add a new column to my dataframe from List of values. My list has same number of values like given dataframe.

val list = List(4,5,10,7,2)
val df   = List("a","b","c","d","e").toDF("row1")

I would like to do something like:

val appendedDF = df.withColumn("row2",somefunc(list))
df.show()
// +----+------+
// |row1 |row2 |
// +----+------+
// |a    |4    |
// |b    |5    |
// |c    |10   |
// |d    |7    |
// |e    |2    |
// +----+------+

For any ideas I would be greatful, my dataframe in reality contains more columns.

Body:
Adding for completeness: the fact that the input list (which exists in driver memory) has the same size as the DataFrame suggests that this is a small DataFrame to begin with - so you might consider collect()-ing it, zipping with list, and converting back into a DataFrame if needed:

df.collect()
  .map(_.getAs[String]("row1"))
  .zip(list).toList
  .toDF("row1", "row2")

That won't be faster, but if the data is really small it might be negligible and the code is (arguably) clearer.


问:
Add multiple documents to envelope using c# sdk using Docusign API
I have a template in Docusign that I need to send to joe@acme.com

However Joe is responsible for managing 10 clients and instead of me sending Joe 10 separate envelopes for him to sign I want to send Joe 1 envelope with 10 documents and Joe needs to sign all 10 document in the envelope. The documents are identical except for the different data filled in the text field of the template

I am using the C# SDK provided by Docusign and I can send one document in an envelope using EnvelopeDefinition class and TemplateRole class but am lost as to how to create 10 documents in an envelope

The following recipe does it but it is in python and uses the REST API with which I am not sure how to translate to the C# SDK equivalent
https://www.docusign.com/developer-center/recipes/send-multiple-docs

答:
You can use compositeTemplates and reuse the same server template multiple times in the envelope. The below code uses the same server Template and repeats it 10 times in the envelope. See full example here</p>

```<code>public void CreateEnvelope()
{
  var envDef = new EnvelopeDefinition()
  {
      EmailSubject = "Envelope with multiple documents",
      Status = "sent",
      CompositeTemplates = new List<CompositeTemplate>()
  };

  for (int docNumber = 1; docNumber <= 10; docNumber++)
  {
      var compostiteTemplate = BuildCompositeTemplate(docNumber.ToString());
      envDef.CompositeTemplates.Add(compostiteTemplate);

  }

  EnvelopesApi envelopesApi = new EnvelopesApi();
  EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(accountId, envDef);
  Console.WriteLine(envelopeSummary);
}

public CompositeTemplate BuildCompositeTemplate(string docNumber)
{
    string serverTemplateId = "";//Add your server template ID here
    return new CompositeTemplate()
    {
          ServerTemplates = new List<ServerTemplate>()
          {
              new ServerTemplate()
              {
                  TemplateId = serverTemplateId,
                  Sequence = docNumber
              }
          },
          InlineTemplates = new List<InlineTemplate>()
          {
              new InlineTemplate()
              {
                  Sequence = docNumber,
                  Recipients = new Recipients()
                  {
                      Signers = new List<Signer>()
                      {
                          new Signer()
                          {
                              Email = "Janedoe@acme.com",
                              Name = "Jane Doe",
                              RecipientId = "1",
                              RoleName = "Signer1",
                              Tabs = new Tabs()
                              {
                                  TextTabs = new List<Text>()
                                  {
                                      new Text()
                                      {
                                          DocumentId = docNumber,
                                          PageNumber = "1",
                                          XPosition = "100",
                                          YPosition = "100",
                                          Width = 120,
                                          Value = "Some Tab Value " + docNumber
                                      }
                                  }

                              }
                          }
                      }
                  }
              }
          }
    }
}
</code>```

Body:
You can use compositeTemplates and reuse the same server template multiple times in the envelope. The below code uses the same server Template and repeats it 10 times in the envelope. See full example here

public void CreateEnvelope()
{
  var envDef = new EnvelopeDefinition()
  {
      EmailSubject = "Envelope with multiple documents",
      Status = "sent",
      CompositeTemplates = new List<CompositeTemplate>()
  };

  for (int docNumber = 1; docNumber <= 10; docNumber++)
  {
      var compostiteTemplate = BuildCompositeTemplate(docNumber.ToString());
      envDef.CompositeTemplates.Add(compostiteTemplate);

  }

  EnvelopesApi envelopesApi = new EnvelopesApi();
  EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(accountId, envDef);
  Console.WriteLine(envelopeSummary);
}

public CompositeTemplate BuildCompositeTemplate(string docNumber)
{
    string serverTemplateId = "";//Add your server template ID here
    return new CompositeTemplate()
    {
          ServerTemplates = new List<ServerTemplate>()
          {
              new ServerTemplate()
              {
                  TemplateId = serverTemplateId,
                  Sequence = docNumber
              }
          },
          InlineTemplates = new List<InlineTemplate>()
          {
              new InlineTemplate()
              {
                  Sequence = docNumber,
                  Recipients = new Recipients()
                  {
                      Signers = new List<Signer>()
                      {
                          new Signer()
                          {
                              Email = "Janedoe@acme.com",
                              Name = "Jane Doe",
                              RecipientId = "1",
                              RoleName = "Signer1",
                              Tabs = new Tabs()
                              {
                                  TextTabs = new List<Text>()
                                  {
                                      new Text()
                                      {
                                          DocumentId = docNumber,
                                          PageNumber = "1",
                                          XPosition = "100",
                                          YPosition = "100",
                                          Width = 120,
                                          Value = "Some Tab Value " + docNumber
                                      }
                                  }

                              }
                          }
                      }
                  }
              }
          }
    }
}


问:
Run task when show notification
(sorry for my English)

I need help with my first program, which i must make to friday to pass the course on study...

I'm trying to create an application that will display a notification with a description from the table to which the reminders are added. I have a problem with the mechanism of getting next description to display. I made a description of the application after the notification was displayed. Unfortunately, this does not work when the application is closed.

```<code>public void onReceive(Context context, Intent intent) {
    ScheduleNotification.completeWakefulIntent(intent);

    alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    descToShow = d1;

    DataBaseHandler dbh = new DataBaseHandler(context);
    dbh.open();
    dbh.DeleteRow(descToShow);
    dbh.close();

    Toast.makeText(context, descToShow, Toast.LENGTH_LONG).show();

    //notification
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setSmallIcon(R.drawable.icon);
    builder.setContentTitle(descToShow);
    builder.setContentText(descToShow); //--description event--
    builder.setAutoCancel(false).build();

    //from android dev:
    Intent resultIntent = new Intent(context, MainActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);

    stackBuilder.addParentStack(MainActivity.class);

    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT );
    builder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    mNotificationManager.notify(1, builder.build());
    PendingIntent notifyPIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
    builder.setContentIntent(notifyPIntent);
}
</code>```

Any ideas ?

all code on my github: https://github.com/azernax/dForget

答:
The problem is that you use static fields from your MainActivity when the MainActivity isn't in memory (so you get default values instead of those set in onCreate()). The correct solution is to load data again (in your case from SharedPreferences).

I hope this helps you. Comment if you have any questions

Title: Run task when show notification

Body:
(sorry for my English)

I need help with my first program, which i must make to friday to pass the course on study...

I'm trying to create an application that will display a notification with a description from the table to which the reminders are added. I have a problem with the mechanism of getting next description to display. I made a description of the application after the notification was displayed. Unfortunately, this does not work when the application is closed.

public void onReceive(Context context, Intent intent) {
    ScheduleNotification.completeWakefulIntent(intent);

    alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    descToShow = d1;

    DataBaseHandler dbh = new DataBaseHandler(context);
    dbh.open();
    dbh.DeleteRow(descToShow);
    dbh.close();

    Toast.makeText(context, descToShow, Toast.LENGTH_LONG).show();

    //notification
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setSmallIcon(R.drawable.icon);
    builder.setContentTitle(descToShow);
    builder.setContentText(descToShow); //--description event--
    builder.setAutoCancel(false).build();

    //from android dev:
    Intent resultIntent = new Intent(context, MainActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);

    stackBuilder.addParentStack(MainActivity.class);

    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT );
    builder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    mNotificationManager.notify(1, builder.build());
    PendingIntent notifyPIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
    builder.setContentIntent(notifyPIntent);
}

Any ideas ?

all code on my github: https://github.com/azernax/dForget


问:
Fast sorting/Filtering based on alternating values
Consider the following sample data table,

```<code>dt <- data.table(src = LETTERS[1:10],
                 dst = LETTERS[10:1],
                 src1 = letters[15:24],
                 dst1 = letters[24:15])

#which looks like,
#    src dst src1 dst1
# 1:   A   J    o    x
# 2:   B   I    p    w
# 3:   C   H    q    v
# 4:   D   G    r    u
# 5:   E   F    s    t
# 6:   F   E    t    s
# 7:   G   D    u    r
# 8:   H   C    v    q
# 9:   I   B    w    p
#10:   J   A    x    o
</code>```

The first goal is to order it based on reversed rowwise paired elements (src - dst & src1 - dst1) which can be achieved as follows to create the 5 'pairs':

```<code>dt[, key := paste0(pmin(src, dst), pmax(src, dst), pmin(src1, dst1), pmax(src1, dst1))][order(key)]

#    src dst src1 dst1  key
# 1:   A   J    o    x AJox
# 2:   J   A    x    o AJox
# 3:   B   I    p    w BIpw
# 4:   I   B    w    p BIpw
# 5:   C   H    q    v CHqv
# 6:   H   C    v    q CHqv
# 7:   D   G    r    u DGru
# 8:   G   D    u    r DGru
# 9:   E   F    s    t EFst
#10:   F   E    t    s EFst
</code>```

However, in real life there could be at least one row that does not have a pair ("incomplete flow"). So a real life example of that would be,

```<code>#              cdatetime   srcaddr dstaddr  srcport   dstport     key    totals time_diff
# 1: 2017-05-12 14:58:32    IP_1    IP_2   54793    8080 182808054793      3        NA
# 2: 2017-05-12 14:58:32    IP_2    IP_1    8080   54793 182808054793      3         0
# 3: 2017-05-17 08:37:16    IP_1    IP_2   54793    8080 182808054793      3    409124
# 4: 2017-05-11 08:12:28    IP_1    IP_2   54813    8080 182808054813      3        NA
# 5: 2017-05-11 08:12:28    IP_2    IP_1    8080   54813 182808054813      3         0
# 6: 2017-05-17 08:37:16    IP_1    IP_2   54813    8080 182808054813      3    519888
# 7: 2017-05-02 06:51:16    IP_1    IP_2   50794    8080 182808050794      5        NA
# 8: 2017-05-02 06:51:16    IP_2    IP_1    8080   50794 182808050794      5         0
# 9: 2017-05-08 06:57:08    IP_1    IP_2   50794    8080 182808050794      5    518752
#10: 2017-05-11 06:32:49    IP_1    IP_2   50794    8080 182808050794      5    257741
#11: 2017-05-11 06:32:49    IP_2    IP_1    8080   50794 182808050794      5         0
#12: 2017-05-04 06:52:05    IP_1    IP_2   51896    8080 182808051896      5        NA
#13: 2017-05-04 06:52:05    IP_2    IP_1    8080   51896 182808051896      5         0
#14: 2017-05-04 10:22:26    IP_1    IP_2   51896    8080 182808051896      5     12621
#15: 2017-05-04 10:22:26    IP_2    IP_1    8080   51896 182808051896      5         0
#16: 2017-05-08 07:22:47    IP_1    IP_2   51896    8080 182808051896      5    334821
#17: 2017-05-15 05:56:00    IP_1    IP_2   62744     162  17016262744      3        NA
#18: 2017-05-17 10:41:00    IP_1    IP_2   62744     162  17016262744      3    189900
#19: 2017-05-18 09:31:00    IP_1    IP_2   62744     162  17016262744      3     82200
</code>```

The second goal now is to remove those incomplete flows. Now, to identify those "incomplete flows" we calculate the time difference between them and set 30 as the threshold. The tricky part comes here; If we have only 2 rows and they are more than 30 seconds apart, then filter them both out and for 3 rows (for a certain key) then the one with time diff > 30 needs to go - or if two of them have  > 30 seconds apart, remove all 3. However, when we have 4 or more rows, then we need to drop the one(s) with time difference > 30 that do not have another pair with < 30. From the above table, rows 3, 6, 9, 16, 17, 18, 19 have to be removed based on the condition that they are more than 30 seconds apart. Looking at cdatetime will clarify which are the complete flows.

Expected output would be,

```<code> #        cdatetime      srcaddr dstaddr srcport dstport          key totals time_diff
# 1: 2017-05-12 14:58:32    IP_1    IP_2   54793    8080 182808054793      3        NA
# 2: 2017-05-12 14:58:32    IP_2    IP_1    8080   54793 182808054793      3         0
# 3: 2017-05-11 08:12:28    IP_1    IP_2   54813    8080 182808054813      3        NA
# 4: 2017-05-11 08:12:28    IP_2    IP_1    8080   54813 182808054813      3         0
# 5: 2017-05-02 06:51:16    IP_1    IP_2   50794    8080 182808050794      5        NA
# 6: 2017-05-02 06:51:16    IP_2    IP_1    8080   50794 182808050794      5         0
# 7: 2017-05-11 06:32:49    IP_1    IP_2   50794    8080 182808050794      5    257741
# 8: 2017-05-11 06:32:49    IP_2    IP_1    8080   50794 182808050794      5         0
# 9: 2017-05-04 06:52:05    IP_1    IP_2   51896    8080 182808051896      5        NA
#10: 2017-05-04 06:52:05    IP_2    IP_1    8080   51896 182808051896      5         0
#11: 2017-05-04 10:22:26    IP_1    IP_2   51896    8080 182808051896      5     12621
#12: 2017-05-04 10:22:26    IP_2    IP_1    8080   51896 182808051896      5         0
</code>```

DATA OF REAL LIFE EXAMPLES ABOVE

```<code>structure(list(cdatetime = structure(c(1494590312, 1494590312,
1494999436, 1494479548, 1494479548, 1494999436, 1493697076, 1493697076,
1494215828, 1494473569, 1494473569, 1493869925, 1493869925, 1493882546,
1493882546, 1494217367, 1494816960, 1495006860, 1495089060), class = c("POSIXct",
"POSIXt"), tzone = ""), srcaddr = structure(c(1L, 2L, 1L, 1L,
2L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L), .Label = c("IP_1",
"IP_2"), class = "factor"), dstaddr = structure(c(2L, 1L, 2L,
2L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L
), .Label = c("IP_1", "IP_2"), class = "factor"), srcport = c(54793L,
8080L, 54793L, 54813L, 8080L, 54813L, 50794L, 8080L, 50794L,
50794L, 8080L, 51896L, 8080L, 51896L, 8080L, 51896L, 62744L,
62744L, 62744L), dstport = c(8080L, 54793L, 8080L, 8080L, 54813L,
8080L, 8080L, 50794L, 8080L, 8080L, 50794L, 8080L, 51896L, 8080L,
51896L, 8080L, 162L, 162L, 162L), key = c(182808054793, 182808054793,
182808054793, 182808054813, 182808054813, 182808054813, 182808050794,
182808050794, 182808050794, 182808050794, 182808050794, 182808051896,
182808051896, 182808051896, 182808051896, 182808051896, 17016262744,
17016262744, 17016262744), totals = c(3L, 3L, 3L, 3L, 3L, 3L,
5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 3L, 3L, 3L), time_diff = c(NA,
0, 409124, NA, 0, 519888, NA, 0, 518752, 257741, 0, NA, 0, 12621,
0, 334821, NA, 189900, 82200)), .Names = c("cdatetime", "srcaddr",
"dstaddr", "srcport", "dstport", "key", "totals", "time_diff"
), row.names = c(NA, -19L), class = c("data.table", "data.frame"
))
</code>```

All the above will run on a dataSet with approx. 180M rows, so efficiency is the key word here.

Body:
Consider the following sample data table,

dt <- data.table(src = LETTERS[1:10],
                 dst = LETTERS[10:1],
                 src1 = letters[15:24],
                 dst1 = letters[24:15])

#which looks like,
#    src dst src1 dst1
# 1:   A   J    o    x
# 2:   B   I    p    w
# 3:   C   H    q    v
# 4:   D   G    r    u
# 5:   E   F    s    t
# 6:   F   E    t    s
# 7:   G   D    u    r
# 8:   H   C    v    q
# 9:   I   B    w    p
#10:   J   A    x    o

The first goal is to order it based on reversed rowwise paired elements (src - dst & src1 - dst1) which can be achieved as follows to create the 5 'pairs':

dt[, key := paste0(pmin(src, dst), pmax(src, dst), pmin(src1, dst1), pmax(src1, dst1))][order(key)]

#    src dst src1 dst1  key
# 1:   A   J    o    x AJox
# 2:   J   A    x    o AJox
# 3:   B   I    p    w BIpw
# 4:   I   B    w    p BIpw
# 5:   C   H    q    v CHqv
# 6:   H   C    v    q CHqv
# 7:   D   G    r    u DGru
# 8:   G   D    u    r DGru
# 9:   E   F    s    t EFst
#10:   F   E    t    s EFst

However, in real life there could be at least one row that does not have a pair ("incomplete flow"). So a real life example of that would be,

#              cdatetime   srcaddr dstaddr  srcport   dstport     key    totals time_diff
# 1: 2017-05-12 14:58:32    IP_1    IP_2   54793    8080 182808054793      3        NA
# 2: 2017-05-12 14:58:32    IP_2    IP_1    8080   54793 182808054793      3         0
# 3: 2017-05-17 08:37:16    IP_1    IP_2   54793    8080 182808054793      3    409124
# 4: 2017-05-11 08:12:28    IP_1    IP_2   54813    8080 182808054813      3        NA
# 5: 2017-05-11 08:12:28    IP_2    IP_1    8080   54813 182808054813      3         0
# 6: 2017-05-17 08:37:16    IP_1    IP_2   54813    8080 182808054813      3    519888
# 7: 2017-05-02 06:51:16    IP_1    IP_2   50794    8080 182808050794      5        NA
# 8: 2017-05-02 06:51:16    IP_2    IP_1    8080   50794 182808050794      5         0
# 9: 2017-05-08 06:57:08    IP_1    IP_2   50794    8080 182808050794      5    518752
#10: 2017-05-11 06:32:49    IP_1    IP_2   50794    8080 182808050794      5    257741
#11: 2017-05-11 06:32:49    IP_2    IP_1    8080   50794 182808050794      5         0
#12: 2017-05-04 06:52:05    IP_1    IP_2   51896    8080 182808051896      5        NA
#13: 2017-05-04 06:52:05    IP_2    IP_1    8080   51896 182808051896      5         0
#14: 2017-05-04 10:22:26    IP_1    IP_2   51896    8080 182808051896      5     12621
#15: 2017-05-04 10:22:26    IP_2    IP_1    8080   51896 182808051896      5         0
#16: 2017-05-08 07:22:47    IP_1    IP_2   51896    8080 182808051896      5    334821
#17: 2017-05-15 05:56:00    IP_1    IP_2   62744     162  17016262744      3        NA
#18: 2017-05-17 10:41:00    IP_1    IP_2   62744     162  17016262744      3    189900
#19: 2017-05-18 09:31:00    IP_1    IP_2   62744     162  17016262744      3     82200

The second goal now is to remove those incomplete flows. Now, to identify those "incomplete flows" we calculate the time difference between them and set 30 as the threshold. The tricky part comes here; If we have only 2 rows and they are more than 30 seconds apart, then filter them both out and for 3 rows (for a certain key) then the one with time diff > 30 needs to go - or if two of them have  > 30 seconds apart, remove all 3. However, when we have 4 or more rows, then we need to drop the one(s) with time difference > 30 that do not have another pair with < 30. From the above table, rows 3, 6, 9, 16, 17, 18, 19 have to be removed based on the condition that they are more than 30 seconds apart. Looking at cdatetime will clarify which are the complete flows.

Expected output would be,

 #        cdatetime      srcaddr dstaddr srcport dstport          key totals time_diff
# 1: 2017-05-12 14:58:32    IP_1    IP_2   54793    8080 182808054793      3        NA
# 2: 2017-05-12 14:58:32    IP_2    IP_1    8080   54793 182808054793      3         0
# 3: 2017-05-11 08:12:28    IP_1    IP_2   54813    8080 182808054813      3        NA
# 4: 2017-05-11 08:12:28    IP_2    IP_1    8080   54813 182808054813      3         0
# 5: 2017-05-02 06:51:16    IP_1    IP_2   50794    8080 182808050794      5        NA
# 6: 2017-05-02 06:51:16    IP_2    IP_1    8080   50794 182808050794      5         0
# 7: 2017-05-11 06:32:49    IP_1    IP_2   50794    8080 182808050794      5    257741
# 8: 2017-05-11 06:32:49    IP_2    IP_1    8080   50794 182808050794      5         0
# 9: 2017-05-04 06:52:05    IP_1    IP_2   51896    8080 182808051896      5        NA
#10: 2017-05-04 06:52:05    IP_2    IP_1    8080   51896 182808051896      5         0
#11: 2017-05-04 10:22:26    IP_1    IP_2   51896    8080 182808051896      5     12621
#12: 2017-05-04 10:22:26    IP_2    IP_1    8080   51896 182808051896      5         0

DATA OF REAL LIFE EXAMPLES ABOVE

structure(list(cdatetime = structure(c(1494590312, 1494590312,
1494999436, 1494479548, 1494479548, 1494999436, 1493697076, 1493697076,
1494215828, 1494473569, 1494473569, 1493869925, 1493869925, 1493882546,
1493882546, 1494217367, 1494816960, 1495006860, 1495089060), class = c("POSIXct",
"POSIXt"), tzone = ""), srcaddr = structure(c(1L, 2L, 1L, 1L,
2L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L), .Label = c("IP_1",
"IP_2"), class = "factor"), dstaddr = structure(c(2L, 1L, 2L,
2L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L
), .Label = c("IP_1", "IP_2"), class = "factor"), srcport = c(54793L,
8080L, 54793L, 54813L, 8080L, 54813L, 50794L, 8080L, 50794L,
50794L, 8080L, 51896L, 8080L, 51896L, 8080L, 51896L, 62744L,
62744L, 62744L), dstport = c(8080L, 54793L, 8080L, 8080L, 54813L,
8080L, 8080L, 50794L, 8080L, 8080L, 50794L, 8080L, 51896L, 8080L,
51896L, 8080L, 162L, 162L, 162L), key = c(182808054793, 182808054793,
182808054793, 182808054813, 182808054813, 182808054813, 182808050794,
182808050794, 182808050794, 182808050794, 182808050794, 182808051896,
182808051896, 182808051896, 182808051896, 182808051896, 17016262744,
17016262744, 17016262744), totals = c(3L, 3L, 3L, 3L, 3L, 3L,
5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 3L, 3L, 3L), time_diff = c(NA,
0, 409124, NA, 0, 519888, NA, 0, 518752, 257741, 0, NA, 0, 12621,
0, 334821, NA, 189900, 82200)), .Names = c("cdatetime", "srcaddr",
"dstaddr", "srcport", "dstport", "key", "totals", "time_diff"
), row.names = c(NA, -19L), class = c("data.table", "data.frame"
))

All the above will run on a dataSet with approx. 180M rows, so efficiency is the key word here.

Body:
Apparently this works:

DT[, keep :=
  (!is.na(time_diff) & time_diff < 30) |
  shift(time_diff, type="lead", fill = 999) < 30
, by=key]

DT[(keep), !"keep"]

              cdatetime srcaddr dstaddr srcport dstport          key totals time_diff
 1: 2017-05-12 07:58:32    IP_1    IP_2   54793    8080 182808054793      3        NA
 2: 2017-05-12 07:58:32    IP_2    IP_1    8080   54793 182808054793      3         0
 3: 2017-05-11 01:12:28    IP_1    IP_2   54813    8080 182808054813      3        NA
 4: 2017-05-11 01:12:28    IP_2    IP_1    8080   54813 182808054813      3         0
 5: 2017-05-01 23:51:16    IP_1    IP_2   50794    8080 182808050794      5        NA
 6: 2017-05-01 23:51:16    IP_2    IP_1    8080   50794 182808050794      5         0
 7: 2017-05-10 23:32:49    IP_1    IP_2   50794    8080 182808050794      5    257741
 8: 2017-05-10 23:32:49    IP_2    IP_1    8080   50794 182808050794      5         0
 9: 2017-05-03 23:52:05    IP_1    IP_2   51896    8080 182808051896      5        NA
10: 2017-05-03 23:52:05    IP_2    IP_1    8080   51896 182808051896      5         0
11: 2017-05-04 03:22:26    IP_1    IP_2   51896    8080 182808051896      5     12621
12: 2017-05-04 03:22:26    IP_2    IP_1    8080   51896 182808051896      5         0

There are plenty of ways to make this faster, I guess, but it's probably more important to clarify whether it's doing what the OP wants (considering the code is much simpler than the OP's rules).


问:
Download time remaning predictor
Are there any widgets for predicting when a download (or any other process) will finish based on percent done history?

The trivial version would just do a 2 point fit based on the start time, current time and percent done but better option are possible.

A GUI widgest would be nice but a class that just returns the value would be just fine.

答:
For the theoretical algorithm that I would attempt, if I would write such a widget, would be something like:

Record the amount of data transferred within a one second period (a literal KiB/s)

Remember the last 5 or 10 such periods (to get an an recent average KiB/s)

Subtract the total size from the transferred size (to get a "bytes remaining")

???

Widget!

That oughta do it...

(the missing step being: kibibytes remaining divided by average KiB/s)

OwnerDisplayName: BCS

Title: Download time remaning predictor

LastEditorDisplayName: BCS

OwnerDisplayName: wolfie


问:
Save or Download Javascript String as a file
I have an HTML string in javascript variable. I have to save/Download the string as a file on link click. It should be cross browser compatible.

I thought window.open with attachment Content-Disposition header, but not good solution because popup may be blocked.

答: As mentioned here, you could use downloadify: https://github.com/dcneiner/Downloadify. The client will need flash though.</p>


答:
Looks like you first ought to work on fixing up the formatting for that code - it would help make it easier to read and find issues :)

The } right before the else currently matches up with the { for the resultsInstructorview.map() call, so that's not valid syntax.

Title: Unexpected Token in JSX (React Component)


问:
UITableView automatically scrolls down after a reloadData
I have a table view that is automatically scrolling down a bit in my iPad app (OS X 10.7.3, Xcode 4.3.2), and not sure where to look for the cause. Here is the situation:

The UITableView fills the whole screen, and most of the cells are fixed height cells. The one exception is a cell that contains a UITextView, and is of dynamic height (or in other words, the height of the cell adjusts to fit the amount of text).

The problem manifests itself if the table happens to have the dynamic height cell be cut off when the table view is at the top. When the view first loads, the table is drawn as normal, with just part of the UITextView cell visible. However, if I display a UIPopoverController, I need to do a reloadData after the popover is dismissed, and when I do, the table view will scroll down just enough to show all of the UITextView. (Not the cell containing the UITextView mind you, just the UITextView. The table is a grouped table, and the UITextView cell is the only cell in the section, so the rounded bottom edge is still not visible after this phantom scroll.)

I can't see any code in my app that is scrolling the table view or setting a content offset, so I am totally confused as to what could be causing this.

To try and narrow it down, I set up my view to honor the UIScrollViewDelegate, and if I put a breakpoint in the scrollViewDidScroll: method, the program does in fact stop after the popover goes away and gives me the following backtrace:

```<code>(lldb) bt
* thread #1: tid = 0x1f03, 0x0005245f MyApp`-[ContactDisplayViewController scrollViewDidScroll:] + 31 at ContactDisplayViewController.m:1143, stop reason = breakpoint 3.1
    frame #0: 0x0005245f MyApp`-[ContactDisplayViewController scrollViewDidScroll:] + 31 at ContactDisplayViewController.m:1143
    frame #1: 0x017e3494 UIKit`-[UIScrollView setContentOffset:] + 521
    frame #2: 0x0180804d UIKit`-[UITableView setContentOffset:] + 334
    frame #3: 0x017d495e UIKit`-[UIScrollViewScrollAnimation setProgress:] + 523
    frame #4: 0x0183d234 UIKit`-[UIAnimator(Static) _advance:] + 255
    frame #5: 0x02c013a3 GraphicsServices`HeartbeatTimerCallback + 35
    frame #6: 0x023278c3 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 19
    frame #7: 0x02328e74 CoreFoundation`__CFRunLoopDoTimer + 1220
    frame #8: 0x022852c9 CoreFoundation`__CFRunLoopRun + 1817
    frame #9: 0x02284840 CoreFoundation`CFRunLoopRunSpecific + 208
    frame #10: 0x02284761 CoreFoundation`CFRunLoopRunInMode + 97
    frame #11: 0x02bfe1c4 GraphicsServices`GSEventRunModal + 217
    frame #12: 0x02bfe289 GraphicsServices`GSEventRun + 115
    frame #13: 0x017a4c93 UIKit`UIApplicationMain + 1160
    frame #14: 0x0000263d MyApp`main + 125 at main.m:14
</code>```

And if I print out the scrollView in that method, it shows that the UITableView is in motion (not sure where the contentOffset is coming from):

```<code>Printing description of scrollView:
<UITableView: 0xc3ed400; frame = (0 99; 383 817); clipsToBounds = YES;
autoresize = W+RM+H; layer = <CALayer: 0x7bf1a40>; contentOffset: {0, 14}>
</code>```

This phantom scrolling is showing up on the device and the simulator, and in iOS 4.3, 5.0, and 5.1.  Does anyone have any ideas?

答:
I subclassed the UIScrollView subclass (in my case subclassed UITextField) and make sure I don't accept "arbitrary" content offsets:

```<code>override var contentOffset: CGPoint {
    set {
        let maxContentOffsetY = max(self.contentSize.height - self.frame.size.height, 0.0)
        super.contentOffset.y = min(newValue.y, maxContentOffsetY)
    }
    get {
        return super.contentOffset
    }
}
</code>```

Body:
I have a table view that is automatically scrolling down a bit in my iPad app (OS X 10.7.3, Xcode 4.3.2), and not sure where to look for the cause. Here is the situation:

The UITableView fills the whole screen, and most of the cells are fixed height cells. The one exception is a cell that contains a UITextView, and is of dynamic height (or in other words, the height of the cell adjusts to fit the amount of text).

The problem manifests itself if the table happens to have the dynamic height cell be cut off when the table view is at the top. When the view first loads, the table is drawn as normal, with just part of the UITextView cell visible. However, if I display a UIPopoverController, I need to do a reloadData after the popover is dismissed, and when I do, the table view will scroll down just enough to show all of the UITextView. (Not the cell containing the UITextView mind you, just the UITextView. The table is a grouped table, and the UITextView cell is the only cell in the section, so the rounded bottom edge is still not visible after this phantom scroll.)

I can't see any code in my app that is scrolling the table view or setting a content offset, so I am totally confused as to what could be causing this.

To try and narrow it down, I set up my view to honor the UIScrollViewDelegate, and if I put a breakpoint in the scrollViewDidScroll: method, the program does in fact stop after the popover goes away and gives me the following backtrace:

(lldb) bt
* thread #1: tid = 0x1f03, 0x0005245f MyApp`-[ContactDisplayViewController scrollViewDidScroll:] + 31 at ContactDisplayViewController.m:1143, stop reason = breakpoint 3.1
    frame #0: 0x0005245f MyApp`-[ContactDisplayViewController scrollViewDidScroll:] + 31 at ContactDisplayViewController.m:1143
    frame #1: 0x017e3494 UIKit`-[UIScrollView setContentOffset:] + 521
    frame #2: 0x0180804d UIKit`-[UITableView setContentOffset:] + 334
    frame #3: 0x017d495e UIKit`-[UIScrollViewScrollAnimation setProgress:] + 523
    frame #4: 0x0183d234 UIKit`-[UIAnimator(Static) _advance:] + 255
    frame #5: 0x02c013a3 GraphicsServices`HeartbeatTimerCallback + 35
    frame #6: 0x023278c3 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 19
    frame #7: 0x02328e74 CoreFoundation`__CFRunLoopDoTimer + 1220
    frame #8: 0x022852c9 CoreFoundation`__CFRunLoopRun + 1817
    frame #9: 0x02284840 CoreFoundation`CFRunLoopRunSpecific + 208
    frame #10: 0x02284761 CoreFoundation`CFRunLoopRunInMode + 97
    frame #11: 0x02bfe1c4 GraphicsServices`GSEventRunModal + 217
    frame #12: 0x02bfe289 GraphicsServices`GSEventRun + 115
    frame #13: 0x017a4c93 UIKit`UIApplicationMain + 1160
    frame #14: 0x0000263d MyApp`main + 125 at main.m:14

And if I print out the scrollView in that method, it shows that the UITableView is in motion (not sure where the contentOffset is coming from):

Printing description of scrollView:
<UITableView: 0xc3ed400; frame = (0 99; 383 817); clipsToBounds = YES;
autoresize = W+RM+H; layer = <CALayer: 0x7bf1a40>; contentOffset: {0, 14}>

This phantom scrolling is showing up on the device and the simulator, and in iOS 4.3, 5.0, and 5.1.  Does anyone have any ideas?

Body:
I subclassed the UIScrollView subclass (in my case subclassed UITextField) and make sure I don't accept "arbitrary" content offsets:

override var contentOffset: CGPoint {
    set {
        let maxContentOffsetY = max(self.contentSize.height - self.frame.size.height, 0.0)
        super.contentOffset.y = min(newValue.y, maxContentOffsetY)
    }
    get {
        return super.contentOffset
    }
}


问:
How to write a shell script that runs next command even if current command fails?
I currently need to automate a task where I need to execute 5 commands, even if any command fails, all next commands should get executed, currently if 4th commands fails, shell script exits and dont run 5th command.

So, what should I do so that, shell script run all the next commands even if current command fails?

答:
The "trap" command may be helpful here:

trap


问:
How do I disable all old meeting reminders (from years ago)
Just installed the new Outlook on mac and sync'd up with gmail and yahoo - but it keeps flooding me with meeting reminders from 10 years ago.  How do I disable/delete all these old meeting reminders.</p>

答: Is this what you are looking for as an answer: Office 2016 can't dismiss old notifications (Mac)</p>


问:
Re-asking for Declined Facebook Permissions (auth_type=rerequest) does not work
we are developing a Facebook application with PHP SDK 3.2.3 and Javascript SDK. I need to re-ask users permission to publish on their wall if they denied access to publish on Facebook at login.

As documentation says:

[...] Your app must re-ask for declined permissions with special handling. [...]

[...] Web apps must explicitly pass a new option to the Login Dialog: auth_type: rerequest. Details on how the new option works on the web is covered in our documentation on using the JavaScript SDK on the Web.

but we tried with this request:

https://www.facebook.com/dialog/oauth?auth_type=rerequest&client_id=1...7&redirect_uri=MY_PAGE&state=a1f4412db0617ef1a620ac1d1ebc2af8&sdk=php-sdk-3.2.3&campaign_page_with_active_panel=MY_PAGE

but users are redirected directly on MY_PAGE url and permissions are not re-requested.

This (wrong) behavior may be due to the fact that application is a test application?

答:
In php SDK (3.x) auth_type rerequest can be send to Facebook via getLoginUrl parameter:</p>

```<code>$loginUrl = $facebook->getLoginUrl(array(
    'scope' => 'public_profile, user_friends, email',
    'redirect_url' => 'http://www.yourul.com/example.php',
    'auth_type' => 'rerequest',
));
</code>```

Body:
In php SDK (3.x) auth_type rerequest can be send to Facebook via getLoginUrl parameter:

$loginUrl = $facebook->getLoginUrl(array(
    'scope' => 'public_profile, user_friends, email',
    'redirect_url' => 'http://www.yourul.com/example.php',
    'auth_type' => 'rerequest',
));


问:
Create path from javascript object property
Let's say I've got the following javascript object

```<code>var obj = {
            a:{
                b:"value",
                c:{
                    d:"value2"
                }
            }
        }
</code>```

What function would, when input with the "d" object (for example, function getPath(obj, d)), output the "a.c.d" string? I've tried various things including object-path, but it doesn't seem to be designed for that

答:
You could use an iterative and recursive approach.

function getPath(object, key) {

    function iter(o, p) {
        if (typeof o === 'object') {
            return Object.keys(o).some(function (k) {
                return iter(o[k], p.concat(k));
            });
        }
        if (p[p.length - 1] === key) {
            path = p;
            return true;
        }
    }

    var path = [];
    iter(object, []);
    return path.join('.');
}

console.log(getPath({ d: { d: { d: { d: 'val' } } } }, 'd'));
console.log(getPath({ a: { b: 'value', c: { d: 'value2' } } }, 'd'));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
Let's say I've got the following javascript object

var obj = {
            a:{
                b:"value",
                c:{
                    d:"value2"
                }
            }
        }

What function would, when input with the "d" object (for example, function getPath(obj, d)), output the "a.c.d" string? I've tried various things including object-path, but it doesn't seem to be designed for that

Body:
You could use an iterative and recursive approach.

function getPath(object, key) {

    function iter(o, p) {
        if (typeof o === 'object') {
            return Object.keys(o).some(function (k) {
                return iter(o[k], p.concat(k));
            });
        }
        if (p[p.length - 1] === key) {
            path = p;
            return true;
        }
    }

    var path = [];
    iter(object, []);
    return path.join('.');
}

console.log(getPath({ d: { d: { d: { d: 'val' } } } }, 'd'));
console.log(getPath({ a: { b: 'value', c: { d: 'value2' } } }, 'd'));

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
How could I go about using two ListViews with a BaseAdapter?
Basically, I want to be able to use two ListViews through my BaseAdapter class in the same activity.  The ListViews will be displayed side-by-side and each item within the ListView will contain multiple views (ImageView, TextView, etc.).

My main issue is retreiving/displaying data through the getView() method inherited from BaseAdapter.  How would I go about detecting which ListView is being updated through this method so I will know which code to call/update?  I've tried looking at the ViewGroup parameter in getView() hoping that it led me to the parent of the ListItem but the id it returns was different from my ListView's resource ID...in fact it wasn't even in my R.java file at all:

```<code>12-14 04:44:58.613: ERROR/ParentFromGetView(312): 16908298
12-14 04:44:58.623: ERROR/MyListViewId(312): 2131165191
</code>```

I was hoping to do something like so:

```<code>public View getView(int position, View convertView, ViewGroup parent) {
    if (parent.getId() == R.id.ListView1) {
        //Do stuff
    } else if (parent.getId() == R.id.ListView2) {
        //Do different stuff
    }
}
</code>```

...but the Ids are drastically off as seen above.

Thanks in advance!

答:
You cannot share a ListAdapter between two ListViews.

Well, I would like for them both to run on the same activity.

So?

Currently I'm extending my activity as a ListActivity and I set my adapter accordingly.

That only affects one of the two ListViews, whichever one has the @android:id/list value. You need to create a second ListAdapter for use with the second ListView. You get the second ListView by calling findViewById(), and you associate the adapter with that ListView via setAdapter().

Body:
Basically, I want to be able to use two ListViews through my BaseAdapter class in the same activity.  The ListViews will be displayed side-by-side and each item within the ListView will contain multiple views (ImageView, TextView, etc.).

My main issue is retreiving/displaying data through the getView() method inherited from BaseAdapter.  How would I go about detecting which ListView is being updated through this method so I will know which code to call/update?  I've tried looking at the ViewGroup parameter in getView() hoping that it led me to the parent of the ListItem but the id it returns was different from my ListView's resource ID...in fact it wasn't even in my R.java file at all:

12-14 04:44:58.613: ERROR/ParentFromGetView(312): 16908298
12-14 04:44:58.623: ERROR/MyListViewId(312): 2131165191

I was hoping to do something like so:

public View getView(int position, View convertView, ViewGroup parent) {
    if (parent.getId() == R.id.ListView1) {
        //Do stuff
    } else if (parent.getId() == R.id.ListView2) {
        //Do different stuff
    }
}

...but the Ids are drastically off as seen above.

Thanks in advance!


问:
How to play a movie in swift
I am new at Swift Language. I want to develop simple movie player app for learning.  I added some movies(".avi, .flv, .f4u.... which format is best) to my project. My view is just simple.There is a button on my view. ITs called "Play". When user tap on that button the movies will start.

Plus I need to play audio files too, like mp3 or .mid files. Can you give me how i can do that in Swift? IF you explain with example, It will be perfect.

Edit

I am not asking all code. I get confused when I try to convert my Objective C code to Swift. I want to know how I can develop below code in Swift?

```<code>NSString *path = [[NSBundle mainBundle] pathForResource:@"eminem1" ofType:@"mp4"];

MPMoviePlayerController *myPlayer = [[MPMoviePlayerController alloc] init];
myPlayer.shouldAutoplay = YES;
myPlayer.repeatMode = MPMovieRepeatModeOne;
myPlayer.fullscreen = YES;
myPlayer.movieSourceType = MPMovieSourceTypeFile;
myPlayer.scalingMode = MPMovieScalingModeAspectFit;
myPlayer.contentURL =[NSURL fileURLWithPath:path];
[self.view addSubview:myPlayer.view];
[myPlayer play];
</code>```

答:
Selected answer is deprecatedfor iOS 9+ versions.

Use this answer instead: How to play a local video with Swift?

Title: How to play a movie in swift

Body:
I am new at Swift Language. I want to develop simple movie player app for learning.  I added some movies(".avi, .flv, .f4u.... which format is best) to my project. My view is just simple.There is a button on my view. ITs called "Play". When user tap on that button the movies will start.

Plus I need to play audio files too, like mp3 or .mid files. Can you give me how i can do that in Swift? IF you explain with example, It will be perfect.

Edit

I am not asking all code. I get confused when I try to convert my Objective C code to Swift. I want to know how I can develop below code in Swift?

NSString *path = [[NSBundle mainBundle] pathForResource:@"eminem1" ofType:@"mp4"];

MPMoviePlayerController *myPlayer = [[MPMoviePlayerController alloc] init];
myPlayer.shouldAutoplay = YES;
myPlayer.repeatMode = MPMovieRepeatModeOne;
myPlayer.fullscreen = YES;
myPlayer.movieSourceType = MPMovieSourceTypeFile;
myPlayer.scalingMode = MPMovieScalingModeAspectFit;
myPlayer.contentURL =[NSURL fileURLWithPath:path];
[self.view addSubview:myPlayer.view];
[myPlayer play];


问:
Problems with backgrounds and layers (Android Studio)
I have a problem with the background of a View in this project.

There is one View with a transparent layer, which is not always displayed... It looks like if, in some cases, the height of this View was automatically set to 0, as I can see in the preview of the activity that contains the View. The code of this element is as follows:

```<code>    <View
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="16dp"
        android:alpha="0.5"
        android:background="@drawable/background_layers" />
</code>```

The main view group in this activity is a ScrollView. If the whole layout is displayed and is visible on the screen (so you don't need to scroll down) everything works fine (look at the transparent layer, which is the topic of this question):

But if the screen density is low, or if the device is in portrait orientation, and I must use the scroll because the full layout is not displayed at the same time... the previous View is not shown, the transparent layer is not visible :(

It happens when the app is running and also in Android Studio, in the preview screen, as I said. Here is an example with vertical orientation and low screen density, as seen on the preview tab of the activity in Android Studio:

Any idea to fix this isue?

Thanks in advance.

David.

答: I think I found the problem with your layout. The transparent_background view sometimes takes height 0 because its height is match_parent and its parent (the main_relative_layout view) has its height set as wrap_content. You should set the transparent_background dimensions relatively to another view, the LinearLayout that wraps the content maybe, using android:layout_alignTop, android:layout_alignBottom, android:layout_alignLeft and android:layout_alignRight attributes. You may need to remove the LinearLayout margin and use padding instead to align the transparent_background view correctly, let me know if you need some help.

Body:
I have a problem with the background of a View in this project.

There is one View with a transparent layer, which is not always displayed... It looks like if, in some cases, the height of this View was automatically set to 0, as I can see in the preview of the activity that contains the View. The code of this element is as follows:

    <View
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="16dp"
        android:alpha="0.5"
        android:background="@drawable/background_layers" />

The main view group in this activity is a ScrollView. If the whole layout is displayed and is visible on the screen (so you don't need to scroll down) everything works fine (look at the transparent layer, which is the topic of this question):

But if the screen density is low, or if the device is in portrait orientation, and I must use the scroll because the full layout is not displayed at the same time... the previous View is not shown, the transparent layer is not visible :(

It happens when the app is running and also in Android Studio, in the preview screen, as I said. Here is an example with vertical orientation and low screen density, as seen on the preview tab of the activity in Android Studio:

Any idea to fix this isue?

Thanks in advance.

David.