问:
Not able to edit text input react redux form
Unable to edit textinput after setting up value from db. The value gets changed by one character that one is recently typed while focusing out from that textinput. Initially, I am setting up each value of textinput by state property. Then edit mode I get that value from db and setting up through state property. After that, I am unable to edit in edit mode.</p>
```<code>import React, {
    Component
} from 'react';
import ReactDOM from 'react-dom';
import {
    Field,
    reduxForm
} from 'redux-form';
import _ from 'lodash';
import {
    addEmployee
} from '../actions/employeeAction';
import {
    editEmployee
} from '../actions/employeeAction';
import {
    connect
} from 'react-redux';
import UploadImage from './uploadimage/uploadImage';
import {
    Redirect
} from 'react-router-dom';
import Init from './index';

const FIELDS = {
    firstname: {
        type: 'input',
        label: 'First Name',
        key: 1,
        name: 'firstname',
        dbName: 'firstname'
    },
    lastname: {
        type: 'input',
        label: 'Last Name',
        key: 2,
        name: 'lastname',
        dbName: 'lastname'
    },
    password: {
        type: 'input',
        label: 'Password',
        key: 3,
        name: 'password',
        dbName: 'password'
    },
    reenterpassword: {
        type: 'input',
        label: 'Re-password',
        key: 4,
        name: 'reenterpassword',
        dbName: 'reenterpassword'
    },
    age: {
        type: 'Number',
        label: 'Age',
        key: 5,
        name: 'age',
        dbName: 'age'
    },
    occupation: {
        type: 'input',
        label: 'Occupation',
        key: 6,
        name: 'occupation',
        dbName: 'occupation'
    },
    city: {
        type: 'input',
        label: 'City',
        key: 7,
        name: 'city',
        dbName: 'city'
    },
    state: {
        type: 'input',
        label: 'State',
        key: 8,
        name: 'state',
        dbName: 'state'
    },
    pin: {
        type: 'input',
        label: 'Pin',
        key: 9,
        name: 'pin',
        dbName: 'pin'
    },
    phone: {
        type: 'input',
        label: 'Phone',
        key: 10,
        name: 'phone',
        dbName: 'phone'
    },
    email: {
        type: 'email',
        label: 'Email',
        key: 11,
        name: 'email',
        dbName: 'email'
    },
    dateOfJoin: {
        type: 'date',
        label: 'Date Of Join',
        key: 12,
        name: 'dateOfJoin',
        dbName: 'dateOfJoin'
    },
    uploadPhoto: {
        type: 'blob',
        label: 'Upload Image',
        key: 13,
        name: 'uploadPhoto',
        dbName: 'croppedImage'
    }
}

class PostNew extends Component {
    constructor() {
        super();
        this.renderField = this.renderField.bind(this);
        this.onCroppedImgData = this.onCroppedImgData.bind(this);
        this.valueChange = this.valueChange.bind(this);
        this.state = {
            croppedData: undefined,
            header: 'Registration Form',
            createdUser: false
        };
        /********Initial setup for state for each text input********/
        _.each(FIELDS, (type, field) => {
            let dbState = type.dbName;
            this.state = {
                dbState: ""
            };
        });
    }
    componentWillMount() {
        if (this.props.header) {
            this.setState({
                header: this.props.header
            });
        }
        if (this.props.userData) {
            _.each(FIELDS, (type, field) => {
                let dbState = type.dbName;
                this.setState({
                    [dbState]: this.props.userData[dbState]
                });
            });
        }

    }
    callAttribute(field) {
        return <Field label = {
            field.label
        }
        key = {
            field.key
        }
        type = {
            field.type
        }
        name = {
            field.name
        }
        dbname = {
            field.dbName
        }
        component = {
            this.renderField
        }
        />
    }
    onCroppedImgData(data) {
        this.setState({
            croppedData: data
        });
    }
    valueChange(e, dbName) {
        if (this.props.userData) {
            /**********Setting state dynamically here and called onChange method of textinput.And textinput value changed one character while we focused out.*********/
            this.setState({
                [dbName]: e.target.value
            });
        }

    }
    renderField(field) {
        const {
            meta: {
                touched,
                error
            }
        } = field;
        const {
            label,
            type,
            key,
            name,
            dbname
        } = field;

        if (label === "Upload Image") {
            let src;
            if (this.props.userData) {
                src = this.props.userData[dbname];
            }
            return ( <
                div className = "upload-image" >
                <
                UploadImage message = "Upload Image"
                callbackImgCropped = {
                    this.onCroppedImgData
                }
                profileImg = {
                    src
                }
                /> <
                /div>
            )
        } else {
            let val;
            if (this.props.userData) {
                console.log("=====this.state[dbname]===", this.state[dbname]);
                val = this.state[dbname];
                if (dbname === "dateOfJoin") {
                    val = "";
                }
            }

            return ( <
                div className = "field-div" >
                <
                div >
                <
                span className = "label-name" > {
                    label
                } < /span> <
                input className = "form-input"
                key = {
                    key
                }
                type = {
                    type
                } { ...field.input
                }
                ref = {
                    name
                }
                value = {
                    this.state[dbname]
                }
                onChange = {
                    (e) => {
                        this.valueChange(e, dbname)
                    }
                }
                /> <
                span className = "error-msg" > {
                    touched ? error : ' '
                } < /span> <
                /div> <
                /div>

            );
        }

    }
    onSubmit(obj) {
        if (this.state.croppedData) {
            obj.croppedImage = this.state.croppedData;
        }
        if (this.props.userData) {
            obj.id = this.props.userData.id;
            console.log("edit operation");
            this.props.editEmployee(obj, (data) => {
                this.props.reset();
            });
        } else {
            if (this.state.croppedData) {
                obj.croppedImage = this.state.croppedData;
            }
            this.props.addEmployee(obj, (data) => {
                this.setState({
                    createdUser: true
                });
                this.props.reset();
            });
        }

    }
    render() {
        const {
            handleSubmit,
            pristine,
            reset,
            submitting
        } = this.props;
        if (this.state.createdUser) {
            return ( < Redirect to = "/" / > );
        } else {
            return ( <
                div className = "form-div" >
                <
                div className = "form-header" > {
                    this.state.header
                } < /div> <
                form className = "employee-form"
                onSubmit = {
                    handleSubmit(this.onSubmit.bind(this))
                } > {
                    _.map(FIELDS, this.callAttribute.bind(this))
                } <
                div className = "form-button" >
                <
                button type = "submit"
                disabled = {
                    submitting
                } >
                Submit <
                /button> <
                button type = "button"
                disabled = {
                    pristine || submitting
                }
                onClick = {
                    reset
                } >
                Clear Values <
                /button> <
                /div> <
                /form> <
                /div>
            );
        }

    }
}

function validate(values) {
    const errors = {};
    _.each(FIELDS, (type, field) => {
        if (!values[field] && type.type != "blob" && type.label != "Date Of Join") {
            if (type.type == "email") {
                errors[field] = `Enter an ${field}`;
            } else {
                errors[field] = `Enter a ${field}`;
            }

        } else if (type.type == "email" && values[field]) {
            if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values[field])) {
                errors[field] = 'Invalid email address'
            }
        } else if (type.name == "reenterpassword" && values[field] !== values['password']) {
            errors[field] = 'Password mismatched.Please reenter password.';
        }
    });
    return errors;
}

export default reduxForm({
    validate,
    fields: _.keys(FIELDS),
    form: 'PostNewForm'
})(connect(null, {
    addEmployee,
    editEmployee
})(PostNew));
</code>```

答:
```<code>    Yes got the solution ...We need to include  "change" method from 'redux-form' and we need to dispatch the method with 3 arguments.

this.props.dispatch(change('PostNewForm', [dbName], e.currentTarget.value));
1st argument = form name
2nd argument = state name
3rd argument = value
Below is the working code...These redux form controls are uncontrolled .so we need to include {change} from redux-form.

    import React, {Component} from 'react';
    import ReactDOM from 'react-dom';
    import { Field, reduxForm,change } from 'redux-form';
    import _ from 'lodash';
    import {addEmployee} from '../actions/employeeAction';
    import {editEmployee} from '../actions/employeeAction';
    import { connect } from 'react-redux';
    import UploadImage from './uploadimage/uploadImage';
    import { Redirect } from 'react-router-dom';
    import Init from './index';

    const FIELDS = {
      firstname:{
         type:'input',
         label:'First Name',
         key:1,
         name:'firstname',
         dbName:'firstname'
      },
      lastname:{
         type:'input',
         label:'Last Name',
         key:2,
         name:'lastname',
         dbName:'lastname'
      },
      password:{
         type:'password',
         label:'Password',
         key:3,
         name:'password',
         dbName:'password'
      },
      reenterpassword:{
         type:'password',
         label:'Re-password',
         key:4,
         name:'reenterpassword',
         dbName:'reenterpassword'
      },
      age:{
         type:'Number',
         label:'Age',
         key:5,
         name:'age',
         dbName:'age'
      },
      occupation:{
         type:'input',
         label:'Occupation',
         key:6,
         name:'occupation',
         dbName:'occupation'
      },
      city:{
         type:'input',
         label:'City',
         key:7,
         name:'city',
         dbName:'city'
      },
      state:{
         type:'input',
         label:'State',
         key:8,
         name:'state',
         dbName:'state'
      },
      pin:{
         type:'input',
         label:'Pin',
         key:9,
         name:'pin',
         dbName:'pin'
      },
      phone:{
         type:'input',
         label:'Phone',
         key:10,
         name:'phone',
         dbName:'phone'
      },
      email:{
         type:'email',
         label:'Email',
         key:11,
         name:'email',
         dbName:'email'
      },
      dateOfJoin:{
         type:'date',
         label:'Date Of Join',
         key:12,
         name:'dateOfJoin',
         dbName:'dateOfJoin'
      },
      uploadPhoto:{
         type:'blob',
         label:'Upload Image',
         key:13,
         name:'uploadPhoto',
         dbName:'croppedImage'
      }
    }

    class PostNew extends Component {
      constructor(){
        super();
        this.renderField = this.renderField.bind(this);
        this.onCroppedImgData = this.onCroppedImgData.bind(this);
        this.valueChange = this.valueChange.bind(this);
        var stateData = [];
        var constructState='{"croppedData":"undefined","header":"Registration Form","createdEditUser":false';
        _.each(FIELDS,(type,field)=>{
           let dbState = type.dbName;
           constructState = constructState+',"'+dbState+'":""';
        });
        constructState = constructState + '}';
        this.state = JSON.parse(constructState);
      }
      componentWillMount(){
        if(this.props.header){
          this.setState({header:this.props.header});
        }
        if(this.props.userData){
          _.each(FIELDS,(type,field)=>{
             let dbState = type.dbName;
             this.setState({[dbState]:this.props.userData[dbState]});
          });
        }
      }
      callAttribute(field){
        return <Field label={field.label} key={field.key} type={field.type}  name={field.name} dbname={field.dbName} component={this.renderField} />
      }
      onCroppedImgData(data)
      {
        this.setState({croppedData:data});
      }
      valueChange(e,dbName){
        this.setState({[dbName]:e.currentTarget.value});
        this.props.dispatch(change('PostNewForm', [dbName], e.currentTarget.value));

      }
      renderField(field){
        const {meta:{touched,error}} = field;
        const {label,type,key,name,dbname} = field;

        if(label === "Upload Image"){
          let src;
          if(this.props.userData){
            src = this.props.userData[dbname];
          }
           return(
              <div className="upload-image">
                  <UploadImage message="Upload Image" callbackImgCropped={this.onCroppedImgData} profileImg={src}/>
              </div>
           )
        }else{
          let val;
          let placeholder = 'Please enter your '+label;
          if(this.props.userData){

             val = this.state[dbname];
             if(dbname === "dateOfJoin"){
              val = "";
             }
          }
          console.log("=====this.state[dbname]===",this.state[dbname]);
          return(
            <div className="field-div">
              <div >
                 <span className="label-name">{label}</span>
                 <input className="form-input" key={key} type={type} {...field.input}  ref={name} value={this.state[dbname]} onChange={(e) => {this.valueChange(e,dbname)}} placeholder={placeholder}/>
                 <span className="error-msg">{touched ? error : ' '}</span>
              </div>
            </div>
          );
        }

      }
      onSubmit(obj){
        if(this.state.croppedData){
          obj.croppedImage = this.state.croppedData;
        }
        if(this.props.userData){
          obj.id = this.props.userData.id;
          console.log("edit operation");
          this.props.editEmployee(obj,(data) => {
             this.setState({createdEditUser:data.status});
             this.props.reset();
          });
        }else{
          if(this.state.croppedData){
            obj.croppedImage = this.state.croppedData;
          }
          this.props.addEmployee(obj,(data) => {
            this.setState({createdEditUser:true});
            this.props.reset();
          });
        }

      }
      render(){
        const { handleSubmit, pristine, reset, submitting } = this.props;
        if(this.state.createdEditUser){
          return( <Redirect to="/signin" /> );
        }else{
          return(
            <div className="form-div">
              <div className="form-header">{this.state.header}</div>
              <form className="employee-form" onSubmit={handleSubmit(this.onSubmit.bind(this))}>
              {_.map(FIELDS,this.callAttribute.bind(this))}
              <div className="form-button">
                <button type="submit" disabled={submitting}>
                  Submit
                </button>
                <button type="button" disabled={pristine || submitting} onClick={reset}>
                  Clear Values
                </button>
              </div>
              </form>
            </div>
          );
        }

      }
    }

    function validate(values){
       const errors = {};
       _.each(FIELDS,(type,field)=>{
         if(!values[field] && type.type != "blob" && type.label !="Date Of Join"){
          if(type.type == "email"){
            errors[field] = `Enter an ${field}`;
          }else{
            errors[field] = `Enter a ${field}`;
          }

         }
         else if(type.type == "email" && values[field]){
            if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values[field])) {
              errors[field] = 'Invalid email address'
            }
          }else if(type.name == "reenterpassword" && values[field]!==values['password']){
              errors[field] = 'Password mismatched.Please reenter password.';
          }
      });
       return errors;
    }

    export default reduxForm({
      validate,
      fields : _.keys(FIELDS),
      form:'PostNewForm'
    })(connect(null,{addEmployee,editEmployee})(PostNew));
</code>```

Body:
Unable to edit textinput after setting up value from db. The value gets changed by one character that one is recently typed while focusing out from that textinput. Initially, I am setting up each value of textinput by state property. Then edit mode I get that value from db and setting up through state property. After that, I am unable to edit in edit mode.

import React, {
    Component
} from 'react';
import ReactDOM from 'react-dom';
import {
    Field,
    reduxForm
} from 'redux-form';
import _ from 'lodash';
import {
    addEmployee
} from '../actions/employeeAction';
import {
    editEmployee
} from '../actions/employeeAction';
import {
    connect
} from 'react-redux';
import UploadImage from './uploadimage/uploadImage';
import {
    Redirect
} from 'react-router-dom';
import Init from './index';

const FIELDS = {
    firstname: {
        type: 'input',
        label: 'First Name',
        key: 1,
        name: 'firstname',
        dbName: 'firstname'
    },
    lastname: {
        type: 'input',
        label: 'Last Name',
        key: 2,
        name: 'lastname',
        dbName: 'lastname'
    },
    password: {
        type: 'input',
        label: 'Password',
        key: 3,
        name: 'password',
        dbName: 'password'
    },
    reenterpassword: {
        type: 'input',
        label: 'Re-password',
        key: 4,
        name: 'reenterpassword',
        dbName: 'reenterpassword'
    },
    age: {
        type: 'Number',
        label: 'Age',
        key: 5,
        name: 'age',
        dbName: 'age'
    },
    occupation: {
        type: 'input',
        label: 'Occupation',
        key: 6,
        name: 'occupation',
        dbName: 'occupation'
    },
    city: {
        type: 'input',
        label: 'City',
        key: 7,
        name: 'city',
        dbName: 'city'
    },
    state: {
        type: 'input',
        label: 'State',
        key: 8,
        name: 'state',
        dbName: 'state'
    },
    pin: {
        type: 'input',
        label: 'Pin',
        key: 9,
        name: 'pin',
        dbName: 'pin'
    },
    phone: {
        type: 'input',
        label: 'Phone',
        key: 10,
        name: 'phone',
        dbName: 'phone'
    },
    email: {
        type: 'email',
        label: 'Email',
        key: 11,
        name: 'email',
        dbName: 'email'
    },
    dateOfJoin: {
        type: 'date',
        label: 'Date Of Join',
        key: 12,
        name: 'dateOfJoin',
        dbName: 'dateOfJoin'
    },
    uploadPhoto: {
        type: 'blob',
        label: 'Upload Image',
        key: 13,
        name: 'uploadPhoto',
        dbName: 'croppedImage'
    }
}

class PostNew extends Component {
    constructor() {
        super();
        this.renderField = this.renderField.bind(this);
        this.onCroppedImgData = this.onCroppedImgData.bind(this);
        this.valueChange = this.valueChange.bind(this);
        this.state = {
            croppedData: undefined,
            header: 'Registration Form',
            createdUser: false
        };
        /********Initial setup for state for each text input********/
        _.each(FIELDS, (type, field) => {
            let dbState = type.dbName;
            this.state = {
                dbState: ""
            };
        });
    }
    componentWillMount() {
        if (this.props.header) {
            this.setState({
                header: this.props.header
            });
        }
        if (this.props.userData) {
            _.each(FIELDS, (type, field) => {
                let dbState = type.dbName;
                this.setState({
                    [dbState]: this.props.userData[dbState]
                });
            });
        }

    }
    callAttribute(field) {
        return <Field label = {
            field.label
        }
        key = {
            field.key
        }
        type = {
            field.type
        }
        name = {
            field.name
        }
        dbname = {
            field.dbName
        }
        component = {
            this.renderField
        }
        />
    }
    onCroppedImgData(data) {
        this.setState({
            croppedData: data
        });
    }
    valueChange(e, dbName) {
        if (this.props.userData) {
            /**********Setting state dynamically here and called onChange method of textinput.And textinput value changed one character while we focused out.*********/
            this.setState({
                [dbName]: e.target.value
            });
        }

    }
    renderField(field) {
        const {
            meta: {
                touched,
                error
            }
        } = field;
        const {
            label,
            type,
            key,
            name,
            dbname
        } = field;

        if (label === "Upload Image") {
            let src;
            if (this.props.userData) {
                src = this.props.userData[dbname];
            }
            return ( <
                div className = "upload-image" >
                <
                UploadImage message = "Upload Image"
                callbackImgCropped = {
                    this.onCroppedImgData
                }
                profileImg = {
                    src
                }
                /> <
                /div>
            )
        } else {
            let val;
            if (this.props.userData) {
                console.log("=====this.state[dbname]===", this.state[dbname]);
                val = this.state[dbname];
                if (dbname === "dateOfJoin") {
                    val = "";
                }
            }

            return ( <
                div className = "field-div" >
                <
                div >
                <
                span className = "label-name" > {
                    label
                }  <
                input className = "form-input"
                key = {
                    key
                }
                type = {
                    type
                } { ...field.input
                }
                ref = {
                    name
                }
                value = {
                    this.state[dbname]
                }
                onChange = {
                    (e) => {
                        this.valueChange(e, dbname)
                    }
                }
                /> <
                span className = "error-msg" > {
                    touched ? error : ' '
                }  <
                /div> <
                /div>

            );
        }

    }
    onSubmit(obj) {
        if (this.state.croppedData) {
            obj.croppedImage = this.state.croppedData;
        }
        if (this.props.userData) {
            obj.id = this.props.userData.id;
            console.log("edit operation");
            this.props.editEmployee(obj, (data) => {
                this.props.reset();
            });
        } else {
            if (this.state.croppedData) {
                obj.croppedImage = this.state.croppedData;
            }
            this.props.addEmployee(obj, (data) => {
                this.setState({
                    createdUser: true
                });
                this.props.reset();
            });
        }

    }
    render() {
        const {
            handleSubmit,
            pristine,
            reset,
            submitting
        } = this.props;
        if (this.state.createdUser) {
            return ( < Redirect to = "/" / > );
        } else {
            return ( <
                div className = "form-div" >
                <
                div className = "form-header" > {
                    this.state.header
                }
 <
                form className = "employee-form"
                onSubmit = {
                    handleSubmit(this.onSubmit.bind(this))
                } > {
                    _.map(FIELDS, this.callAttribute.bind(this))
                } <
                div className = "form-button" >
                <
                button type = "submit"
                disabled = {
                    submitting
                } >
                Submit <
                /button> <
                button type = "button"
                disabled = {
                    pristine || submitting
                }
                onClick = {
                    reset
                } >
                Clear Values <
                /button> <
                /div> <
                /form> <
                /div>
            );
        }

    }
}

function validate(values) {
    const errors = {};
    _.each(FIELDS, (type, field) => {
        if (!values[field] && type.type != "blob" && type.label != "Date Of Join") {
            if (type.type == "email") {
                errors[field] = `Enter an ${field}`;
            } else {
                errors[field] = `Enter a ${field}`;
            }

        } else if (type.type == "email" && values[field]) {
            if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values[field])) {
                errors[field] = 'Invalid email address'
            }
        } else if (type.name == "reenterpassword" && values[field] !== values['password']) {
            errors[field] = 'Password mismatched.Please reenter password.';
        }
    });
    return errors;
}

export default reduxForm({
    validate,
    fields: _.keys(FIELDS),
    form: 'PostNewForm'
})(connect(null, {
    addEmployee,
    editEmployee
})(PostNew));


来源: stackexchange

问:
Slider Revolution in WordPress
I want to make a slider like a demo: https://ihatetomatoes.net/demos/simple-parallax-scrolling-tutorial/

I can do the parallax option but I need the effect of the content of the demo.
When scroll I need to fade out the content in Slider Revolution.

Regards,

答:
You will have to write custom Javascript that will hit the elements within RevSlider. I can tell you right now, this is going to be a huge pain, as the classes and id's on the layers are going to be dynamic and change all the time. Here's some untested jQuery I am throwing together to get you started.</p>

```<code>// Listen to the scroll event on the window element

$(window).scroll(function() {

  if ($(this).scrollTop() > 100 ) {

    // Find the class and fade it out
    // You might need to grab the ID for the layer

    $('.rev_layer_class').fadeOut();

  } else {

    // Fade back in if they scroll back up

    $('.rev_layer_class').fadeOut();
  }

});
</code>```

ContentLicense: CC BY-SA 3.0

Title: Slider Revolution in WordPress

Body:
You will have to write custom Javascript that will hit the elements within RevSlider. I can tell you right now, this is going to be a huge pain, as the classes and id's on the layers are going to be dynamic and change all the time. Here's some untested jQuery I am throwing together to get you started.

// Listen to the scroll event on the window element

$(window).scroll(function() {

  if ($(this).scrollTop() > 100 ) {

    // Find the class and fade it out
    // You might need to grab the ID for the layer

    $('.rev_layer_class').fadeOut();

  } else {

    // Fade back in if they scroll back up

    $('.rev_layer_class').fadeOut();
  }

});


问:
How to parse data between  and
I want to parse the information between ...	 under Number of samples	.For example, after parsing the following html will return 64.

```<code>...
<tr class="border">
    <th>Average FPKM</th>
    <td colspan="2">0.8</td>
</tr>
<tr class="border">
    <th>Number of samples</th>
    <td colspan="2">64</td>
</tr>
...
</code>```

How to get only return the value 64 here?

Thanks

答:
Get th, then parent, then find td.

```<code>$(document).ready(function() {
  var thGet=$('table').find('th');
  $.each(thGet, function (i, obj) {
    var text = $(obj).text();
    if(text == 'Number of samples' && $(obj).parent().find('td').attr('colspan') == '2')
    {
        alert($(obj).parent().find('td').html());
    }
  });
});
</code>```

non jQuery, need Javascript support

```<code>var x = document.querySelectorAll('th');
for (var i = 0; i < x.length; i++) {
    if(x[i].innerHTML == 'Number of samples')
    {
        var c = x[i].parentNode.childNodes;
      var j;
      for (j = 0; j < c.length; j++) {
          if(c[j].tagName == 'TD' && c[j].colSpan == '2')
          {
            console.log(c[j].innerHTML);
          }
      }
    }
};
</code>```

Title: How to parse data between <td colspan="2"> and </td>

Body:
I want to parse the information between ...	 under Number of samples	.For example, after parsing the following html will return 64.

...

    Average FPKM
    0.8

    Number of samples
    64

...

How to get only return the value 64 here?

Thanks

Body:
Get th, then parent, then find td.

$(document).ready(function() {
  var thGet=$('table').find('th');
  $.each(thGet, function (i, obj) {
    var text = $(obj).text();
    if(text == 'Number of samples' && $(obj).parent().find('td').attr('colspan') == '2')
    {
        alert($(obj).parent().find('td').html());
    }
  });
});

non jQuery, need Javascript support

var x = document.querySelectorAll('th');
for (var i = 0; i < x.length; i++) {
    if(x[i].innerHTML == 'Number of samples')
    {
        var c = x[i].parentNode.childNodes;
      var j;
      for (j = 0; j < c.length; j++) {
          if(c[j].tagName == 'TD' && c[j].colSpan == '2')
          {
            console.log(c[j].innerHTML);
          }
      }
    }
};


问:
OpenGL Texture not rendering
I'm currently trying to learn OpenGL. I've successfully rendered rainbow triangles to the screen, and I've successfully moved them about the screen.
However, I can not seem to properly render a texture to two triangles.

Whenever I run this program, I am greeted with a black screen with nothing rendering. I've checked, and the image file is definately in the correct directory (it wouldn't run otherwise!)

```<code>define STB_IMAGE_IMPLEMENTATION

#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <stb/stb_image.h>

int main()
{
    //Initialize glfw
    if (!glfwInit())
    {
        fprintf(stderr, "ERROR: Could not start GLFW3.\n");
        return 1;
    }

    //Create the rendering context
    GLFWwindow* window = glfwCreateWindow(480, 600, "Hello Rendering",
                                          nullptr, nullptr);

    if(!window)
    {
        fprintf(stderr, "ERROR: Could not create a rendering context with "
            "GLFW3.\n");
        return 1;
    }

    glfwMakeContextCurrent(window);

    //Start GLEW
    glewExperimental=GL_TRUE;
    GLenum err=glewInit();
    if(err!=GLEW_OK)
    {
        //Problem: glewInit failed, something is seriously wrong.
        std::cout<<"glewInit failed, aborting."<<std::endl;
    }

    ////////////////////////
    //Loading PNG
    ////////////////////////
    int x = 0;
    int y = 0;
    int n = 0;
    int force_channels = 4;
    unsigned char* image_data = stbi_load("spooky.png", &x, &y, &n,
                                          force_channels);
    if(!image_data)
    {
        fprintf(stderr, "ERROR: Could not load spooky.png\n.");
        return 1;
    }

    //NPOT Check
    if((x & (x - 1)) != 0 || (y & (y - 1)) != 0)
    {
        fprintf(stderr, "ERROR: Image is not a power of 2.\n");
        fprintf(stderr, "h: %d w: %d", y, x);
        return 1;
    }

    //Flip the image
    int width_in_bytes = x * 4;
    unsigned char* top = nullptr;
    unsigned char* bottom = nullptr;
    unsigned char temp = 0;
    int half_height = y / 2;

    for(int row = 0; row < half_height; row++)
    {
        top = image_data + row * width_in_bytes;
        bottom = image_data + (y - row - 1) * width_in_bytes;
        for(int col = 0; col < width_in_bytes; col++)
        {
            temp = *top;
            *top = *bottom;
            *bottom = temp;
            top++;
            bottom++;
        }
    }

    GLuint tex = 0;
    glGenTextures(1, &tex);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, tex);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, x, y, 0, GL_RGBA,
                 GL_UNSIGNED_BYTE, image_data);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

    //////////////////////////////////
    //Vertex shader
    //////////////////////////////////
    const char* vertShader =
        "#version 330 core"
        "layout(location = 0) in vec3 vertexPosition_modelspace;"
        "layout(location = 1) in vec2 vt;"
        "out vec2 texture_coordinates;"
        "void main() {"
        "   texture_coordinates = vt;"
        "   gl_Position.xyz = vertexPosition_modelspace;"
        "   gl_Position.w = 1.0;"
        "}";

    ///////////////////////////////////
    //Frag shader
    ///////////////////////////////////
    const char* fragShader =
        "#version 330 core"
        "uniform sampler2D basic_texture;"
        "out vec4 frag_color;"
        "void main() {"
        "   vec4 texel = texture(basic_texture, texture_coordinates);"
        "   frag_color = texel;"
        "}";

    ////////////////////////////////////
    //Create shader program
    ///////////////////////////////////
    GLuint vsp = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vsp, 1, &vertShader,  nullptr);
    glCompileShader(vsp);

    GLuint fsp = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fsp, 1, &fragShader, nullptr);
    glCompileShader(fsp);

    GLuint shader_program = glCreateProgram();
    glAttachShader(shader_program, fsp);
    glAttachShader(shader_program, vsp);
    glLinkProgram(shader_program);

    glUseProgram(shader_program);

    ////////////////////////////////////
    //Texture coordinates
    ////////////////////////////////////
    GLfloat texcoords[] = {
        0.0f, 1.0f,
        0.0f, 0.0f,
        1.0f, 0.0f,
        1.0f, 0.0f,
        1.0f, 1.0f,
        0.0f, 1.0f
    };

    GLuint vt_vbo;
    glGenBuffers(1, &vt_vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vt_vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof( texcoords), texcoords,
                 GL_STATIC_DRAW);

    GLuint vao;;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);
    glBindBuffer(GL_ARRAY_BUFFER, vt_vbo);
    int dimensions = 2;
    glVertexAttribPointer(1, dimensions, GL_FLOAT, GL_FALSE, 0, nullptr);
    glEnableVertexAttribArray(1);

    while(!glfwWindowShouldClose(window))
    {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        //Use the shader
        glUseProgram(shader_program);
        //Draw the two triangles (6 points)
        glDrawArrays(GL_TRIANGLES, 0, 6);
        glfwPollEvents();
        glfwSwapBuffers(window);
        if(GLFW_PRESS == glfwGetKey(window, GLFW_KEY_ESCAPE))
        {
            glfwSetWindowShouldClose(window, 1);
        }
    }

    std::cout << "Hello, World!" << std::endl;
    return 0;
}
</code>```

答:
First of all, you should retrieve the error messages when compiling and linking your shader:

```<code>GLint status = GL_TRUE;
char error_msg[1024];
GLsizei read;

GLuint vsp = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vsp, 1, &vertShader,  nullptr);
glCompileShader(vsp);
glGetShaderiv( vsp, GL_COMPILE_STATUS, &status );
if ( status != GL_TRUE )
{
    glGetShaderInfoLog( vsp, 1024, &read, error_msg );
    std::cout << "compile error:" << std::endl << error_msg << std::endl;
}

GLuint fsp = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fsp, 1, &fragShader, nullptr);
glCompileShader(fsp);
glGetShaderiv( fsp, GL_COMPILE_STATUS, &status );
if ( status != GL_TRUE )
{
    glGetShaderInfoLog( fsp, 1024, &read, error_msg );
    std::cout << "compile error:" << std::endl << error_msg << std::endl;
}

GLuint shader_program = glCreateProgram();
glAttachShader(shader_program, fsp);
glAttachShader(shader_program, vsp);
glLinkProgram(shader_program);
glGetProgramiv( shader_program, GL_LINK_STATUS, &status );
if ( status != GL_TRUE )
{
    glGetProgramInfoLog( shader_program, 1024, &read, error_msg );
    std::cout << "compile error:" << std::endl << error_msg << std::endl;
}
</code>```

The first error message you will get is somehow like this:

0(1) : error C0205: invalid profile "corelayout"

  0(1) : error C0206: invalid token "" in version line

This is because you did not write the line ending "\n" after the first line of the shader code ("#version 330 core").

When you fixe this then you get the next error message:

0(2) : error C1008: undefined variable "texture_coordinates"

You have to add the declaration of the in variable texture_coordinates to the fragment shader.

```<code>in vec2 texture_coordinates;
</code>```

The final code looks like this:

```<code>const char* vertShader =
    "#version 330 core\n"
    "layout(location = 0) in vec3 vertexPosition_modelspace;"
    "layout(location = 1) in vec2 vt;"
    "out vec2 texture_coordinates;"
    "void main() {"
    "   texture_coordinates = vt;"
    "   gl_Position.xyz = vertexPosition_modelspace;"
    "   gl_Position.w = 1.0;"
    "}";

const char* fragShader =
    "#version 330 core\n"
    "uniform sampler2D basic_texture;"
    "out vec4 frag_color;"
    "in vec2 texture_coordinates;"
    "void main() {"
    "   vec4 texel = texture(basic_texture, texture_coordinates);"
    "   frag_color = texel;"
    "}";
</code>```

Of course you have to provide vertex data for the vertex attribute vertexPosition_modelspace:

```<code>GLfloat texcoords[] = {
    0.0f, 1.0f,
    0.0f, 0.0f,
    1.0f, 0.0f,
    1.0f, 0.0f,
    1.0f, 1.0f,
    0.0f, 1.0f
};

GLfloat vertex[] = {
    -1.0f,  1.0f, 0.0f,
    -1.0f, -1.0f, 0.0f,
     1.0f, -1.0f, 0.0f,
     1.0f, -1.0f, 0.0f,
     1.0f,  1.0f, 0.0f,
    -1.0f,  1.0f, 0.0f
};

GLuint vert_vbo;
glGenBuffers(1, &vert_vbo);
glBindBuffer(GL_ARRAY_BUFFER, vert_vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof( vertex ), vertex, GL_STATIC_DRAW);

GLuint vt_vbo;
glGenBuffers(1, &vt_vbo);
glBindBuffer(GL_ARRAY_BUFFER, vt_vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof( texcoords ), texcoords, GL_STATIC_DRAW);

GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vert_vbo);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vt_vbo);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
glEnableVertexAttribArray(1);
</code>```

Finally you should set the index of the texture unit, wher the texture is bound to, to the texture sampler uniform variable basic_texture:

```<code>int texture_unit_index = 0;
GLuint tex = 0;
glGenTextures(1, &tex);
glActiveTexture(GL_TEXTURE0 + texture_unit_index );
glBindTexture(GL_TEXTURE_2D, tex);

.....

// to do after    glLinkProgram(shader_program);
int tex_sampler_loc = glGetUniformLocation( shader_program, "basic_texture" );

.....

// to do after    glUseProgram(shader_program);
glUniform1i( tex_sampler_loc, texture_unit_index );
</code>```

Title: OpenGL Texture not rendering

Body:
I'm currently trying to learn OpenGL. I've successfully rendered rainbow triangles to the screen, and I've successfully moved them about the screen.
However, I can not seem to properly render a texture to two triangles.

Whenever I run this program, I am greeted with a black screen with nothing rendering. I've checked, and the image file is definately in the correct directory (it wouldn't run otherwise!)

define STB_IMAGE_IMPLEMENTATION

#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <stb/stb_image.h>

int main()
{
    //Initialize glfw
    if (!glfwInit())
    {
        fprintf(stderr, "ERROR: Could not start GLFW3.\n");
        return 1;
    }

    //Create the rendering context
    GLFWwindow* window = glfwCreateWindow(480, 600, "Hello Rendering",
                                          nullptr, nullptr);

    if(!window)
    {
        fprintf(stderr, "ERROR: Could not create a rendering context with "
            "GLFW3.\n");
        return 1;
    }

    glfwMakeContextCurrent(window);

    //Start GLEW
    glewExperimental=GL_TRUE;
    GLenum err=glewInit();
    if(err!=GLEW_OK)
    {
        //Problem: glewInit failed, something is seriously wrong.
        std::cout<<"glewInit failed, aborting."<<std::endl;
    }

    ////////////////////////
    //Loading PNG
    ////////////////////////
    int x = 0;
    int y = 0;
    int n = 0;
    int force_channels = 4;
    unsigned char* image_data = stbi_load("spooky.png", &x, &y, &n,
                                          force_channels);
    if(!image_data)
    {
        fprintf(stderr, "ERROR: Could not load spooky.png\n.");
        return 1;
    }

    //NPOT Check
    if((x & (x - 1)) != 0 || (y & (y - 1)) != 0)
    {
        fprintf(stderr, "ERROR: Image is not a power of 2.\n");
        fprintf(stderr, "h: %d w: %d", y, x);
        return 1;
    }

    //Flip the image
    int width_in_bytes = x * 4;
    unsigned char* top = nullptr;
    unsigned char* bottom = nullptr;
    unsigned char temp = 0;
    int half_height = y / 2;

    for(int row = 0; row < half_height; row++)
    {
        top = image_data + row * width_in_bytes;
        bottom = image_data + (y - row - 1) * width_in_bytes;
        for(int col = 0; col < width_in_bytes; col++)
        {
            temp = *top;
            *top = *bottom;
            *bottom = temp;
            top++;
            bottom++;
        }
    }

    GLuint tex = 0;
    glGenTextures(1, &tex);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, tex);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, x, y, 0, GL_RGBA,
                 GL_UNSIGNED_BYTE, image_data);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

    //////////////////////////////////
    //Vertex shader
    //////////////////////////////////
    const char* vertShader =
        "#version 330 core"
        "layout(location = 0) in vec3 vertexPosition_modelspace;"
        "layout(location = 1) in vec2 vt;"
        "out vec2 texture_coordinates;"
        "void main() {"
        "   texture_coordinates = vt;"
        "   gl_Position.xyz = vertexPosition_modelspace;"
        "   gl_Position.w = 1.0;"
        "}";

    ///////////////////////////////////
    //Frag shader
    ///////////////////////////////////
    const char* fragShader =
        "#version 330 core"
        "uniform sampler2D basic_texture;"
        "out vec4 frag_color;"
        "void main() {"
        "   vec4 texel = texture(basic_texture, texture_coordinates);"
        "   frag_color = texel;"
        "}";

    ////////////////////////////////////
    //Create shader program
    ///////////////////////////////////
    GLuint vsp = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vsp, 1, &vertShader,  nullptr);
    glCompileShader(vsp);

    GLuint fsp = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fsp, 1, &fragShader, nullptr);
    glCompileShader(fsp);

    GLuint shader_program = glCreateProgram();
    glAttachShader(shader_program, fsp);
    glAttachShader(shader_program, vsp);
    glLinkProgram(shader_program);

    glUseProgram(shader_program);

    ////////////////////////////////////
    //Texture coordinates
    ////////////////////////////////////
    GLfloat texcoords[] = {
        0.0f, 1.0f,
        0.0f, 0.0f,
        1.0f, 0.0f,
        1.0f, 0.0f,
        1.0f, 1.0f,
        0.0f, 1.0f
    };

    GLuint vt_vbo;
    glGenBuffers(1, &vt_vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vt_vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof( texcoords), texcoords,
                 GL_STATIC_DRAW);

    GLuint vao;;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);
    glBindBuffer(GL_ARRAY_BUFFER, vt_vbo);
    int dimensions = 2;
    glVertexAttribPointer(1, dimensions, GL_FLOAT, GL_FALSE, 0, nullptr);
    glEnableVertexAttribArray(1);

    while(!glfwWindowShouldClose(window))
    {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        //Use the shader
        glUseProgram(shader_program);
        //Draw the two triangles (6 points)
        glDrawArrays(GL_TRIANGLES, 0, 6);
        glfwPollEvents();
        glfwSwapBuffers(window);
        if(GLFW_PRESS == glfwGetKey(window, GLFW_KEY_ESCAPE))
        {
            glfwSetWindowShouldClose(window, 1);
        }
    }

    std::cout << "Hello, World!" << std::endl;
    return 0;
}

Body:
First of all, you should retrieve the error messages when compiling and linking your shader:

GLint status = GL_TRUE;
char error_msg[1024];
GLsizei read;

GLuint vsp = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vsp, 1, &vertShader,  nullptr);
glCompileShader(vsp);
glGetShaderiv( vsp, GL_COMPILE_STATUS, &status );
if ( status != GL_TRUE )
{
    glGetShaderInfoLog( vsp, 1024, &read, error_msg );
    std::cout << "compile error:" << std::endl << error_msg << std::endl;
}

GLuint fsp = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fsp, 1, &fragShader, nullptr);
glCompileShader(fsp);
glGetShaderiv( fsp, GL_COMPILE_STATUS, &status );
if ( status != GL_TRUE )
{
    glGetShaderInfoLog( fsp, 1024, &read, error_msg );
    std::cout << "compile error:" << std::endl << error_msg << std::endl;
}

GLuint shader_program = glCreateProgram();
glAttachShader(shader_program, fsp);
glAttachShader(shader_program, vsp);
glLinkProgram(shader_program);
glGetProgramiv( shader_program, GL_LINK_STATUS, &status );
if ( status != GL_TRUE )
{
    glGetProgramInfoLog( shader_program, 1024, &read, error_msg );
    std::cout << "compile error:" << std::endl << error_msg << std::endl;
}

The first error message you will get is somehow like this:

0(1) : error C0205: invalid profile "corelayout"

  0(1) : error C0206: invalid token "" in version line

This is because you did not write the line ending "\n" after the first line of the shader code ("#version 330 core").

When you fixe this then you get the next error message:

0(2) : error C1008: undefined variable "texture_coordinates"

You have to add the declaration of the in variable texture_coordinates to the fragment shader.

in vec2 texture_coordinates;

The final code looks like this:

const char* vertShader =
    "#version 330 core\n"
    "layout(location = 0) in vec3 vertexPosition_modelspace;"
    "layout(location = 1) in vec2 vt;"
    "out vec2 texture_coordinates;"
    "void main() {"
    "   texture_coordinates = vt;"
    "   gl_Position.xyz = vertexPosition_modelspace;"
    "   gl_Position.w = 1.0;"
    "}";

const char* fragShader =
    "#version 330 core\n"
    "uniform sampler2D basic_texture;"
    "out vec4 frag_color;"
    "in vec2 texture_coordinates;"
    "void main() {"
    "   vec4 texel = texture(basic_texture, texture_coordinates);"
    "   frag_color = texel;"
    "}";

Of course you have to provide vertex data for the vertex attribute vertexPosition_modelspace:

GLfloat texcoords[] = {
    0.0f, 1.0f,
    0.0f, 0.0f,
    1.0f, 0.0f,
    1.0f, 0.0f,
    1.0f, 1.0f,
    0.0f, 1.0f
};

GLfloat vertex[] = {
    -1.0f,  1.0f, 0.0f,
    -1.0f, -1.0f, 0.0f,
     1.0f, -1.0f, 0.0f,
     1.0f, -1.0f, 0.0f,
     1.0f,  1.0f, 0.0f,
    -1.0f,  1.0f, 0.0f
};

GLuint vert_vbo;
glGenBuffers(1, &vert_vbo);
glBindBuffer(GL_ARRAY_BUFFER, vert_vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof( vertex ), vertex, GL_STATIC_DRAW);

GLuint vt_vbo;
glGenBuffers(1, &vt_vbo);
glBindBuffer(GL_ARRAY_BUFFER, vt_vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof( texcoords ), texcoords, GL_STATIC_DRAW);

GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vert_vbo);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vt_vbo);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
glEnableVertexAttribArray(1);

Finally you should set the index of the texture unit, wher the texture is bound to, to the texture sampler uniform variable basic_texture:

int texture_unit_index = 0;
GLuint tex = 0;
glGenTextures(1, &tex);
glActiveTexture(GL_TEXTURE0 + texture_unit_index );
glBindTexture(GL_TEXTURE_2D, tex);

.....

// to do after    glLinkProgram(shader_program);
int tex_sampler_loc = glGetUniformLocation( shader_program, "basic_texture" );

.....

// to do after    glUseProgram(shader_program);
glUniform1i( tex_sampler_loc, texture_unit_index );


问:
Can I create vps(linux or windows) with higher ram than physical ram?
Can I create vps (Linux or windows) with higher ram than physical ram?
Suppose, I have a physical PC (CentOS) with 16 GM RAM. I want to install multiple OS on VPS. Every VPS having 8 GB RAM. Total 4 VPS, total 4x8=32 GB RAM require.  But none of the VPS OS take more than 4 GB RAM (I assumed). In this situation can I do it? My clients want to see 8 GB RAM and I manage their VPS. They (each vps) never used 8 GB RAM.
If not possible, is there any way to show RAM (8GB) more than actual RAM (4GB) in vmware/xenserver vps?
Thank you.</p>

答: Can be created. Because your guest os all started unused 16GB RAM. You can run it. But if your guest os  fills up with 16GB of RAM, your VM will hang up, causing it to be unusable. vSphere,vcenter will recycle your RAM in a variety of ways, such as compression, forced occupancy, and balloon.</p>


问:
Xcode 9.2 Upload to App Store fails with description length and invalid toolchain errors
I've read through a bunch of forums including here:

https://forums.developer.apple.com/thread/87862

and some Stack Overflow posts.

I have tried modifying my plist using the proposed solution of

```<code>find Products/ -name Info.plist -print0 | xargs -0n1 plutil -replace BuildMachineOSBuild -string 16A323
</code>```

in the archive directory that I'm trying to load, and I'm still receiving the error below. I believe I have valid Xcode and Mac OS versions. I'm running Xcode 9.2 which was released today and High Sierra 10.13.1. Why does my upload fail with these errors and how can I fix it?

The errors in text (to make this post more searchable):

The following issues occurred while distributing your application.

⚠ iTunes Store Operation Failed

   description length:2651858

⚠ iTunes Store Operation Failed

   ERROR ITMS-90534: "Invalid Toolchain. New apps and app updates must be built with the public (GM) versions of Xcode 6 or later, macOS, and iOS SDK or later. Don't submit apps built with beta software including beta macOS builds."

答: Already Fixed, just try again to submit the app.</p>

Body:
I've read through a bunch of forums including here:

https://forums.developer.apple.com/thread/87862

and some Stack Overflow posts.

I have tried modifying my plist using the proposed solution of

find Products/ -name Info.plist -print0 | xargs -0n1 plutil -replace BuildMachineOSBuild -string 16A323

in the archive directory that I'm trying to load, and I'm still receiving the error below. I believe I have valid Xcode and Mac OS versions. I'm running Xcode 9.2 which was released today and High Sierra 10.13.1. Why does my upload fail with these errors and how can I fix it?

The errors in text (to make this post more searchable):

The following issues occurred while distributing your application.

⚠ iTunes Store Operation Failed

   description length:2651858

⚠ iTunes Store Operation Failed

   ERROR ITMS-90534: "Invalid Toolchain. New apps and app updates must be built with the public (GM) versions of Xcode 6 or later, macOS, and iOS SDK or later. Don't submit apps built with beta software including beta macOS builds."


问:
codeIgniter print result failed on view
I want to get and send data from MySQL to views in my CodeIgniter.

This is my function in my Model :

```<code>public function getProduct()
{
   // EDIT : remove ; from ->from('table') and add ' ' to select ->select('*');
   $a = $this->db->select('*')
             -from('table')
             ->get();
   return $a->result();
}
</code>```

This is my Function in controller :

```<code>public function sendView()
{
    $d['product'] = $this->model->getProduct();
    $this->load->view('product', $d);
}
</code>```

This is my views :

```<code><a href="#"><?php echo $product; ?></a>
</code>```

It's not getting all product data from MySQL.

答:
You was return the data using result. But, check your model ->from('table'); dont use ; in the end of that row. So, just ->from('table')

So what you need to do in you view is

```<code><?php foreach($product as $pr)
      { ?>
         <a href="#"><?php echo $pr->example_product_name; ?></a>
<?php } ?>
</code>```

You can try it, change example_product_name into your column_name you wanted to call it.

Title: codeIgniter print result failed on view

Body:
I want to get and send data from MySQL to views in my CodeIgniter.

This is my function in my Model :

public function getProduct()
{
   // EDIT : remove ; from ->from('table') and add ' ' to select ->select('*');
   $a = $this->db->select('*')
             -from('table')
             ->get();
   return $a->result();
}

This is my Function in controller :

public function sendView()
{
    $d['product'] = $this->model->getProduct();
    $this->load->view('product', $d);
}

This is my views :

<?php echo $product; ?>

It's not getting all product data from MySQL.

Body:
You was return the data using result. But, check your model ->from('table'); dont use ; in the end of that row. So, just ->from('table')

So what you need to do in you view is

<?php foreach($product as $pr)
      { ?>
         <a href="#"><?php echo $pr->example_product_name; ?></a>
<?php } ?>

You can try it, change example_product_name into your column_name you wanted to call it.


问:
Group a collection by a certain criteria
so I have a collection in mongoDB that has an structure like the following:

```<code>{
    "_id": 129flaslkfja,
    "number": 10
}
</code>```

in this collection some elements have the number field set to 1 others to 2, others to 3, etc. in random order. I want to get an array that has in the first position all models with the number 1 in the next position all the models with the number  2 and so on. I know I can do this with a loop and a simple find or where but I want to know if there's a simpler, cleaner and more effective way in terms of performance.

I have tried with $group, $match but this is not what I want.

For example this is the data in my database:

```<code>[{
  "_id": a1,
  "number": 1
},
{
  "_id": a2,
  "number": 3
},
{
  "_id": a3,
  "number": 2
},
{
  "_id": a4,
  "number": 2
},
{
  "_id": a5,
  "number": 2
},
{
  "_id": a6,
  "number": 1
}]
</code>```

So I want to group by number value like this:

```<code>[
    [{
      "_id": a1,
      "number": 1
    },
    {
      "_id": a6,
      "number": 1
    }],

    [{
      "_id": a3,
      "number": 2
    },
    {
      "_id": a4,
      "number": 2
    },
    {
      "_id": a5,
      "number": 2
    }],

    [{
      "_id": a2,
      "number": 3
    }]
]
</code>```

答:
You can also try below code</p>

```<code>original_list.group_by(&:number).values
</code>```

Body:
so I have a collection in mongoDB that has an structure like the following:

{
    "_id": 129flaslkfja,
    "number": 10
}

in this collection some elements have the number field set to 1 others to 2, others to 3, etc. in random order. I want to get an array that has in the first position all models with the number 1 in the next position all the models with the number  2 and so on. I know I can do this with a loop and a simple find or where but I want to know if there's a simpler, cleaner and more effective way in terms of performance.

I have tried with $group, $match but this is not what I want.

For example this is the data in my database:

[{
  "_id": a1,
  "number": 1
},
{
  "_id": a2,
  "number": 3
},
{
  "_id": a3,
  "number": 2
},
{
  "_id": a4,
  "number": 2
},
{
  "_id": a5,
  "number": 2
},
{
  "_id": a6,
  "number": 1
}]

So I want to group by number value like this:

[
    [{
      "_id": a1,
      "number": 1
    },
    {
      "_id": a6,
      "number": 1
    }],

    [{
      "_id": a3,
      "number": 2
    },
    {
      "_id": a4,
      "number": 2
    },
    {
      "_id": a5,
      "number": 2
    }],

    [{
      "_id": a2,
      "number": 3
    }]
]

Body:
You can also try below code

original_list.group_by(&:number).values


问:
Tuple vs Class in Java
Are there any advantages of using Tuples instead of creating a new class in Java?
I've seen something like this a few times
return Pair.of (username, password);. And I've always wondered what kind of advantages it has in relation to something like this return new Credentials (username, password).

答:
A Pair (Apache) is immutable, for one. You cannot change it’s values after creation. Many people do in fact choose to create their own class and add methods as necessary.

In general it’s considered better practise to make your own class. You can validate parameters and so on and have the ability to add additional functionality if the need arises.

Title: Tuple vs Class in Java


问:
How do I protect JavaScript files?
I know it's impossible to hide source code but, for example, if I have to link a JavaScript file from my CDN to a web page and I don't want the people to know the location and/or content of this script, is this possible?

For example, to link a script from a website, we use:

```<code><script type="text/javascript" src="http://somedomain.example/scriptxyz.js">
</script>
</code>```

Now, is possible to hide from the user where the script comes from, or hide the script content and still use it on a web page?

For example, by saving it in my private CDN that needs password to access files, would that work? If not, what would work to get what I want?

答: The only thing you can do is obfuscate your code to make it more difficult to read. No matter what you do, if you want the javascript to execute in their browser they'll have to have the code.</p>

ContentLicense: CC BY-SA 4.0

Title: How do I protect JavaScript files?

Body:
I know it's impossible to hide source code but, for example, if I have to link a JavaScript file from my CDN to a web page and I don't want the people to know the location and/or content of this script, is this possible?

For example, to link a script from a website, we use:

Now, is possible to hide from the user where the script comes from, or hide the script content and still use it on a web page?

For example, by saving it in my private CDN that needs password to access files, would that work? If not, what would work to get what I want?

ContentLicense: CC BY-SA 2.5


问:
Embedding tables of data into a DocuSign template
I've got a form (in an ASP.NET application) that a person will add multiple rows to that represent items they are wishing to purchase. These items I want to display on a DocuSign document for them to sign.

Since there could be 1 item, or there could be 100, I'm not quite sure how to embed a field in the DocuSign template that I can populate with this data, they all seem to be for a single item when you use the DocuSign API to set a value.

答:
Kim's solution is a good one. Another solution is for your app to dynamically create the document itself.

For example, there are many libraries available that enable your app to create a PDF. Your app would then upload the PDF to DocuSign and programmatically create the fields (tabs) that you want.

Instead of PDF, your app can create an HTML, RTF or other type of document that will then be automatically converted to PDF by DocuSign.


问:
Deploying JavaFx for different OS
I' m using netbeans IDE for create JavaFx application on ubuntu.My question that can i deploy installer for MAC Os and Windows OS on ubuntu?

答:
For Mac OS you can look into Bundle Java program for Mac users with maven from GNU/Linux

For Windows look into Inno setup.

Title: Deploying JavaFx for different OS


问:
how to link the cells with numbers? python 3 (I tried zip function and another ways)
I'm attempting to replace each zero into the specific odd number in ascending order. For instance: I have a raw with this list of lists [[0], [0, 0], [0,0,0] and etc.] and I need to get this: [[1], [3,5], [7,9,11], [13,15,17,19] and etc.]

```<code>def x(n):
    obj = iter(list(range(1, 100, 2)))
    odds = list(range(1, 100, 2))
    a =[y*[0] for y,x in enumerate(odds,1)]
    for i in range(0,50):
        a[i] = next(obj)
    return odds
print(x(10))
</code>```

I need a small hint. How continue/fix this code.

答:
Since you're trying to use an iterator...

```<code>#this gives you your zero lists...
def zero(n):
    return [[0] * i for i in range(1, n)]

z = zero(5) # this gives the same input as what you show in your example

x = iter(range(1, 1000, 2)) # you should calc and be sure 1000 is big enough
replacement = [[next(x) for i in chunk if i is 0] for chunk in z]
</code>```

This uses something called list comprehension.  The function uses list comprehension to create your initial list, and the last line uses it to create the final answer. I'll add a second example, more simple, in a moment.

Here's the simpler solution:

```<code>def xx(ll):
    obj = iter(range(1, 1000, 2))
    for chunk in ll:
        for i in range(len(chunk)):
            if chunk[i] is 0:
                chunk[i] = next(obj)
    return ll

def zero(n):
    return [[0] * i for i in range(1, n)]

zeros = zero(5)
print(zeros)
result = xx(zeros)
print(result)
</code>```

And the output:

```<code>[[0], [0, 0], [0, 0, 0], [0, 0, 0, 0]]
[[1], [3, 5], [7, 9, 11], [13, 15, 17, 19]]
</code>```

Again, the xx() function uses an iterator to pull out the odd numbers. I did it that way since I'm guessing that's part of what you want to see.  From there I step through each chunk of the master list, which is another smaller list. For each smaller list, I check to see if the value is zero, and if it is, I replace it with the next value from the iterator object.  Finally, the updated master list gets returned.

On a side note, one nice thing about this implementation is that, if the inputted master list did not include only zeroes, this code would replace only the zeros, which is where I thought you were going with this at first, till I saw how simple your input data set it.

Body:
I'm attempting to replace each zero into the specific odd number in ascending order. For instance: I have a raw with this list of lists [[0], [0, 0], [0,0,0] and etc.] and I need to get this: [[1], [3,5], [7,9,11], [13,15,17,19] and etc.]

def x(n):
    obj = iter(list(range(1, 100, 2)))
    odds = list(range(1, 100, 2))
    a =[y*[0] for y,x in enumerate(odds,1)]
    for i in range(0,50):
        a[i] = next(obj)
    return odds
print(x(10))

I need a small hint. How continue/fix this code.

Body:
Since you're trying to use an iterator...

#this gives you your zero lists...
def zero(n):
    return [[0] * i for i in range(1, n)]

z = zero(5) # this gives the same input as what you show in your example

x = iter(range(1, 1000, 2)) # you should calc and be sure 1000 is big enough
replacement = [[next(x) for i in chunk if i is 0] for chunk in z]

This uses something called list comprehension.  The function uses list comprehension to create your initial list, and the last line uses it to create the final answer. I'll add a second example, more simple, in a moment.

Here's the simpler solution:

def xx(ll):
    obj = iter(range(1, 1000, 2))
    for chunk in ll:
        for i in range(len(chunk)):
            if chunk[i] is 0:
                chunk[i] = next(obj)
    return ll

def zero(n):
    return [[0] * i for i in range(1, n)]

zeros = zero(5)
print(zeros)
result = xx(zeros)
print(result)

And the output:

[[0], [0, 0], [0, 0, 0], [0, 0, 0, 0]]
[[1], [3, 5], [7, 9, 11], [13, 15, 17, 19]]

Again, the xx() function uses an iterator to pull out the odd numbers. I did it that way since I'm guessing that's part of what you want to see.  From there I step through each chunk of the master list, which is another smaller list. For each smaller list, I check to see if the value is zero, and if it is, I replace it with the next value from the iterator object.  Finally, the updated master list gets returned.

On a side note, one nice thing about this implementation is that, if the inputted master list did not include only zeroes, this code would replace only the zeros, which is where I thought you were going with this at first, till I saw how simple your input data set it.


问:
How to submit a form with javascript without having the button trigger a new page?
I have a simpel form that I would like to submit with Ajax. It seems that regardless how I approach this, the form keeps insisting to refresh the page.

I would like the form to be submitted with a GET request, submitted with javascript, because I need a js response back from the server.

```<code><div id='form_wrapper'>
  <div class='gradient'></div>
   <form action='' class='my-form' method='get' name='my-form'>
    <div class='header'>
      <h1>Submit this form</h1>
      <span>Please fill out all fields, and then submit the form.</span>
    </div>
    <div class='content'>
      <input class='input full_name' name='full_name' placeholder='Your full name' type='text'>
      <div class='full_name-icon input-icon'></div>
      <input class='input address' name='address' placeholder='Your full address' type='text'>
      <div class='address-icon input-icon'></div>
    </div>
    <div class='form-footer'>
      <input class='button' name='submit' type='submit' value='SUBMIT'>
      <input class='help' name='submit' type='submit' value='HELP?'>
    </div>
  </form>
</div>
</code>```

Also, I would like my submit button to not look like it is being pushed down - meaning that I would like to avoid having that blue border around the button once it has been pushed. I usually avoid the blue border by letting my buttons have href='javascript:void(0)', but as this is a form button I don't suppose I can apply my own href.

答:
You could do the following if you're using vanilla JavaScript;

function myFunc(){
  alert(1);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="formID" onsubmit="myFunc(); return false;">
<input type="submit" value="Submit">
</form></code>```

When you click the submit button, it will activate the myFunc() JavaScript function and using return false in this manner will prevent the page from being changed. Then simply call document.getElementById('formID') to load the form details up. Alternatively you can use an active selector or jQuery $("#formID").

Happy Coding!

Body:
I have a simpel form that I would like to submit with Ajax. It seems that regardless how I approach this, the form keeps insisting to refresh the page.

I would like the form to be submitted with a GET request, submitted with javascript, because I need a js response back from the server.

   <form action='' class='my-form' method='get' name='my-form'>

Submit this form

      Please fill out all fields, and then submit the form.

      <input class='input full_name' name='full_name' placeholder='Your full name' type='text'>

      <input class='input address' name='address' placeholder='Your full address' type='text'>

      <input class='button' name='submit' type='submit' value='SUBMIT'>
      <input class='help' name='submit' type='submit' value='HELP?'>

  </form>

Also, I would like my submit button to not look like it is being pushed down - meaning that I would like to avoid having that blue border around the button once it has been pushed. I usually avoid the blue border by letting my buttons have href='javascript:void(0)', but as this is a form button I don't suppose I can apply my own href.

Body:
You could do the following if you're using vanilla JavaScript;

function myFunc(){
  alert(1);
}

<form id="formID" onsubmit="myFunc(); return false;">
<input type="submit" value="Submit">
</form>

When you click the submit button, it will activate the myFunc() JavaScript function and using return false in this manner will prevent the page from being changed. Then simply call document.getElementById('formID') to load the form details up. Alternatively you can use an active selector or jQuery $("#formID").

Happy Coding!


问:
Linq To Sql Many-Many Join Table
I am a somewhat experienced Rails developer and I thought I would try out ASP.NET's version of MVC. In doing so I also decided to try Linq->Sql...

I am a bit confused about the way Linq->Sql handles joins.

A trivial example of my schema is :

books:

id

title

categories:

id

name

books_categories:

book_id

category_id

Simply dragging these tables to the .dbml file doesn't seem to do it. I get a property on my Book class books_categories, what I expect is a property that I can iterate over and get Category classes directly.

Right now I have to do something that feels very wrong

```<code>        foreach (books_categories bc in book.books_categories)
        {
            category_names.Add(bc.Category.category.Trim());
        }
</code>```

[In Response to Accepted answer]

I grudgingly accepted the answer of "write your own glue code". After continuing my research of Linq->Sql I discovered that it is apparently slowly being let go in favor of the (more powereful, IMO) Entity Framework. EF still allows one to use LINQ for queries and does a decent job of figuring out relationships like Ruby's ActiveRecord.

答:
Use a partial class implementation for Book and add appropriate methods for categories and their properties.  Have the properties front-end the Books_Categories property (you can make this have private visibility to force implementation through your Categories property).

```<code>public partial class Books
{
    public IEnumerable<string> CategoryNames
    {
       get
       {
            return this.Books_Categories
                       .Select( bc => bc.Category.category.Trim() );
       }
    }

    public void AddCategory( Category category )
    {
       this.Books_Categories.Add( new Book_Category
                                  {
                                      Category = category,
                                      Book = this
                                  } );
    }

    public void RemoveCategory( Category category )
    {
       var bc = this.Book_Categories
                    .Where( c => c.Category == category )
                    .SingleOrDefault();
       this.Books_Categories.Remove( bc );
    }
}
</code>```

Obviously, you'll need to add some error/bounds checking, etc.  but you get the idea.

I'll grant you this is not ideal, but at least you have the flexibility to determine how it works.

OwnerDisplayName: Bill

Title: Linq To Sql Many-Many Join Table

Body:
I am a somewhat experienced Rails developer and I thought I would try out ASP.NET's version of MVC. In doing so I also decided to try Linq->Sql...

I am a bit confused about the way Linq->Sql handles joins.

A trivial example of my schema is :

books:

id

title

categories:

id

name

books_categories:

book_id

category_id

Simply dragging these tables to the .dbml file doesn't seem to do it. I get a property on my Book class books_categories, what I expect is a property that I can iterate over and get Category classes directly.

Right now I have to do something that feels very wrong

        foreach (books_categories bc in book.books_categories)
        {
            category_names.Add(bc.Category.category.Trim());
        }

[In Response to Accepted answer]

I grudgingly accepted the answer of "write your own glue code". After continuing my research of Linq->Sql I discovered that it is apparently slowly being let go in favor of the (more powereful, IMO) Entity Framework. EF still allows one to use LINQ for queries and does a decent job of figuring out relationships like Ruby's ActiveRecord.

LastEditorDisplayName: Bill

Body:
Use a partial class implementation for Book and add appropriate methods for categories and their properties.  Have the properties front-end the Books_Categories property (you can make this have private visibility to force implementation through your Categories property).

public partial class Books
{
    public IEnumerable<string> CategoryNames
    {
       get
       {
            return this.Books_Categories
                       .Select( bc => bc.Category.category.Trim() );
       }
    }

    public void AddCategory( Category category )
    {
       this.Books_Categories.Add( new Book_Category
                                  {
                                      Category = category,
                                      Book = this
                                  } );
    }

    public void RemoveCategory( Category category )
    {
       var bc = this.Book_Categories
                    .Where( c => c.Category == category )
                    .SingleOrDefault();
       this.Books_Categories.Remove( bc );
    }
}

Obviously, you'll need to add some error/bounds checking, etc.  but you get the idea.

I'll grant you this is not ideal, but at least you have the flexibility to determine how it works.

OwnerDisplayName: tvanfosson


问:
Java custom class loader issue
I'm sending a Class object from client to server side. Every time the server needs to load the Class object sent by the client instead of reusing it by parent delegation model (when it was loaded during the 1st iteration).

I'm trying to use a custom class loader on the server side whose loadClass(String) simply calls findClass() instead of checking with parent hierarchy.
To achieve this, I'm doing following:

Generate byte[] by reading the .class file on the client side as following:

```<code>Class cl = com.example.XYZ.class;
String path = cl.getName().replace('.', '/') + ".class";
InputStream is = cl.getClassLoader().getResourceAsStream(path);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int data = -1;
while((data=is.read())!=-1)
  bos.write(data);
byte[] classBinaryData = bos.toByteArray();
</code>```

I'm sending classBinaryData to the server side.

On the server side, every time I retrieve the byte[], verify if it's the same as on client side by matching MD5 checksum, then I create a new instance of my custom class loader and pass the byte array so it could be used in calling defineClass from within findClass.

However, I'm getting either of the errors (depending on the way I create byte[] out of .class)

Incompatible magic value ..... in class file <Unknown>

OR

com/example/XYZ (wrong name: com/example/XYZ) coming from defineClass

I need help in figuring out the mistake in my approach/code.

答:
1. Missing Dot Notation

com/example/XYZ (wrong name: com/example/XYZ) coming from defineClass

You should be using dot notation, i.e., com.example.XYZ

```<code>Class clazz = classLoader.loadCustomClass("com.example.XYZ", bytes);
</code>```

2. Invalid Magic Number (Corrupt Class Bytes)

Incompatible magic value ..... in class file

You are getting the above error because the start of the class byte array is corrupted. It's complaining about Incompatible magic value by throwing a java.lang.ClassFormatError. It usually happens when the class loader doesn't find 0xCAFEBABE (magic number) at the beginning of the class bytes.

Here is a simple example by which you can recreate the error.

In this example, the com.basaki.model.Book class file is saved as a Base64 encoded string.

The method testLoadingClassWithCorrectMagicNumber tries to load the class from the Base64 encoded string after decoding it to a byte array. It loads normally without any incident.

In method testLoadingClassWithIncorrectCorrectMagicNumber, the byte array (after the Base64 string is decoded) is corrupted by replacing the first character from c to b. Now instead of the magic number being 0xCAFEBABE, it is 0xBAFEBABE. The class loader now throws the following exception while trying to load the corrupt binary array,

java.lang.ClassFormatError: Incompatible magic value 3137256126 in class file com/basaki/model/Book

```<code>public class LoadingBookFromBinaryArrayTest {

    private static class MyCustomClassLoader extends ClassLoader {

        public Class loadCustomClass(String name, byte[] bytes) {
            return defineClass(name, bytes, 0, bytes.length);
        }
    }

    public static String BOOK_CLAZZ = "yv66vgAAADQAHQoABQAYCQAEABkJAAQAGgcAGwcAHAEABXRpdGxlAQASTGphdmEvbGFuZy9TdHJpbmc7AQAGYXV0aG9yAQAGPGluaXQ-AQADKClWAQAEQ29kZQEAD0xpbmVOdW1iZXJUYWJsZQEAEkxvY2FsVmFyaWFibGVUYWJsZQEABHRoaXMBABdMY29tL2Jhc2FraS9tb2RlbC9Cb29rOwEACGdldFRpdGxlAQAUKClMamF2YS9sYW5nL1N0cmluZzsBAAhzZXRUaXRsZQEAFShMamF2YS9sYW5nL1N0cmluZzspVgEACWdldEF1dGhvcgEACXNldEF1dGhvcgEAClNvdXJjZUZpbGUBAAlCb29rLmphdmEMAAkACgwABgAHDAAIAAcBABVjb20vYmFzYWtpL21vZGVsL0Jvb2sBABBqYXZhL2xhbmcvT2JqZWN0ACEABAAFAAAAAgACAAYABwAAAAIACAAHAAAABQABAAkACgABAAsAAAAvAAEAAQAAAAUqtwABsQAAAAIADAAAAAYAAQAAAAMADQAAAAwAAQAAAAUADgAPAAAAAQAQABEAAQALAAAALwABAAEAAAAFKrQAArAAAAACAAwAAAAGAAEAAAAJAA0AAAAMAAEAAAAFAA4ADwAAAAEAEgATAAEACwAAAD4AAgACAAAABiortQACsQAAAAIADAAAAAoAAgAAAA0ABQAOAA0AAAAWAAIAAAAGAA4ADwAAAAAABgAGAAcAAQABABQAEQABAAsAAAAvAAEAAQAAAAUqtAADsAAAAAIADAAAAAYAAQAAABEADQAAAAwAAQAAAAUADgAPAAAAAQAVABMAAQALAAAAPgACAAIAAAAGKiu1AAOxAAAAAgAMAAAACgACAAAAFQAFABYADQAAABYAAgAAAAYADgAPAAAAAAAGAAgABwABAAEAFgAAAAIAFw==";

    @Test
    public void testLoadingClassWithCorrectMagicNumber() throws IllegalAccessException, InstantiationException, DecoderException {
        byte[] bytes = Base64.getUrlDecoder().decode(BOOK_CLAZZ);
        MyCustomClassLoader classLoader = new MyCustomClassLoader();
        Class clazz = classLoader.loadCustomClass("com.basaki.model.Book", bytes);
    }

    @Test(expected = ClassFormatError.class)
    public void testLoadingClassWithIncorrectCorrectMagicNumber() throws IllegalAccessException, InstantiationException, DecoderException {
        byte[] bytes = Base64.getUrlDecoder().decode(BOOK_CLAZZ);
        String hex = Hex.encodeHexString(bytes);
        System.out.println(hex);

        // changing magic number 0xCAFEBABE to invalid 0xBAFEBABE
        String malHex = "b" + hex.substring(1, hex.length());
        System.out.println(malHex);
        byte[] malBytes = Hex.decodeHex(malHex.toCharArray());

        MyCustomClassLoader classLoader = new MyCustomClassLoader();
        Class clazz = classLoader.loadCustomClass("com.basaki.model.Book", bytes9);
    }
}
</code>```

Title: Java custom class loader issue

Body:
I'm sending a Class object from client to server side. Every time the server needs to load the Class object sent by the client instead of reusing it by parent delegation model (when it was loaded during the 1st iteration).

I'm trying to use a custom class loader on the server side whose loadClass(String) simply calls findClass() instead of checking with parent hierarchy.
To achieve this, I'm doing following:

Generate byte[] by reading the .class file on the client side as following:

Class cl = com.example.XYZ.class;
String path = cl.getName().replace('.', '/') + ".class";
InputStream is = cl.getClassLoader().getResourceAsStream(path);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int data = -1;
while((data=is.read())!=-1)
  bos.write(data);
byte[] classBinaryData = bos.toByteArray();

I'm sending classBinaryData to the server side.

On the server side, every time I retrieve the byte[], verify if it's the same as on client side by matching MD5 checksum, then I create a new instance of my custom class loader and pass the byte array so it could be used in calling defineClass from within findClass.

However, I'm getting either of the errors (depending on the way I create byte[] out of .class)

Incompatible magic value ..... in class file <Unknown>

OR

com/example/XYZ (wrong name: com/example/XYZ) coming from defineClass

I need help in figuring out the mistake in my approach/code.

Body:
1. Missing Dot Notation

com/example/XYZ (wrong name: com/example/XYZ) coming from defineClass

You should be using dot notation, i.e., com.example.XYZ

Class clazz = classLoader.loadCustomClass("com.example.XYZ", bytes);

2. Invalid Magic Number (Corrupt Class Bytes)

Incompatible magic value ..... in class file

You are getting the above error because the start of the class byte array is corrupted. It's complaining about Incompatible magic value by throwing a java.lang.ClassFormatError. It usually happens when the class loader doesn't find 0xCAFEBABE (magic number) at the beginning of the class bytes.

Here is a simple example by which you can recreate the error.

In this example, the com.basaki.model.Book class file is saved as a Base64 encoded string.

The method testLoadingClassWithCorrectMagicNumber tries to load the class from the Base64 encoded string after decoding it to a byte array. It loads normally without any incident.

In method testLoadingClassWithIncorrectCorrectMagicNumber, the byte array (after the Base64 string is decoded) is corrupted by replacing the first character from c to b. Now instead of the magic number being 0xCAFEBABE, it is 0xBAFEBABE. The class loader now throws the following exception while trying to load the corrupt binary array,

java.lang.ClassFormatError: Incompatible magic value 3137256126 in class file com/basaki/model/Book

public class LoadingBookFromBinaryArrayTest {

    private static class MyCustomClassLoader extends ClassLoader {

        public Class loadCustomClass(String name, byte[] bytes) {
            return defineClass(name, bytes, 0, bytes.length);
        }
    }

    public static String BOOK_CLAZZ = "yv66vgAAADQAHQoABQAYCQAEABkJAAQAGgcAGwcAHAEABXRpdGxlAQASTGphdmEvbGFuZy9TdHJpbmc7AQAGYXV0aG9yAQAGPGluaXQ-AQADKClWAQAEQ29kZQEAD0xpbmVOdW1iZXJUYWJsZQEAEkxvY2FsVmFyaWFibGVUYWJsZQEABHRoaXMBABdMY29tL2Jhc2FraS9tb2RlbC9Cb29rOwEACGdldFRpdGxlAQAUKClMamF2YS9sYW5nL1N0cmluZzsBAAhzZXRUaXRsZQEAFShMamF2YS9sYW5nL1N0cmluZzspVgEACWdldEF1dGhvcgEACXNldEF1dGhvcgEAClNvdXJjZUZpbGUBAAlCb29rLmphdmEMAAkACgwABgAHDAAIAAcBABVjb20vYmFzYWtpL21vZGVsL0Jvb2sBABBqYXZhL2xhbmcvT2JqZWN0ACEABAAFAAAAAgACAAYABwAAAAIACAAHAAAABQABAAkACgABAAsAAAAvAAEAAQAAAAUqtwABsQAAAAIADAAAAAYAAQAAAAMADQAAAAwAAQAAAAUADgAPAAAAAQAQABEAAQALAAAALwABAAEAAAAFKrQAArAAAAACAAwAAAAGAAEAAAAJAA0AAAAMAAEAAAAFAA4ADwAAAAEAEgATAAEACwAAAD4AAgACAAAABiortQACsQAAAAIADAAAAAoAAgAAAA0ABQAOAA0AAAAWAAIAAAAGAA4ADwAAAAAABgAGAAcAAQABABQAEQABAAsAAAAvAAEAAQAAAAUqtAADsAAAAAIADAAAAAYAAQAAABEADQAAAAwAAQAAAAUADgAPAAAAAQAVABMAAQALAAAAPgACAAIAAAAGKiu1AAOxAAAAAgAMAAAACgACAAAAFQAFABYADQAAABYAAgAAAAYADgAPAAAAAAAGAAgABwABAAEAFgAAAAIAFw==";

    @Test
    public void testLoadingClassWithCorrectMagicNumber() throws IllegalAccessException, InstantiationException, DecoderException {
        byte[] bytes = Base64.getUrlDecoder().decode(BOOK_CLAZZ);
        MyCustomClassLoader classLoader = new MyCustomClassLoader();
        Class clazz = classLoader.loadCustomClass("com.basaki.model.Book", bytes);
    }

    @Test(expected = ClassFormatError.class)
    public void testLoadingClassWithIncorrectCorrectMagicNumber() throws IllegalAccessException, InstantiationException, DecoderException {
        byte[] bytes = Base64.getUrlDecoder().decode(BOOK_CLAZZ);
        String hex = Hex.encodeHexString(bytes);
        System.out.println(hex);

        // changing magic number 0xCAFEBABE to invalid 0xBAFEBABE
        String malHex = "b" + hex.substring(1, hex.length());
        System.out.println(malHex);
        byte[] malBytes = Hex.decodeHex(malHex.toCharArray());

        MyCustomClassLoader classLoader = new MyCustomClassLoader();
        Class clazz = classLoader.loadCustomClass("com.basaki.model.Book", bytes9);
    }
}


问:
Redirect URL is not allowed: Liferay Page Delete
When I go to Liferay 6.2 page management, and I delete a page from there the page is deleted from db but I get a error that "Dockbar is temporarily unavailable".

Also the logs says:

```<code>Redirect URL ....controlPanelCategory=current_site.pages is not allowed
ERROR [http-bio-8080-exec-26][render_portlet_jsp:132] null
com.liferay.portal.NoSuchLayoutException: No Layout exists with the primary key
</code>```

答:
We had a similar issue. Some links were missing/not working when we went to the webcontent edit page.
We already had the redirect.url.security.mode=domain, but adding all the URLs to domain allowed solved the issue:
redirect.url.domains.allowed=t1.url.com,t2.url.com (Liferay 6.2.)

In Liferay 7 wildcards should work redirect.url.domains.allowed=*.url.com according to https://docs.liferay.com/portal/7.0/propertiesdoc/portal.properties.html

Body:
When I go to Liferay 6.2 page management, and I delete a page from there the page is deleted from db but I get a error that "Dockbar is temporarily unavailable".

Also the logs says:

Redirect URL ....controlPanelCategory=current_site.pages is not allowed
ERROR [http-bio-8080-exec-26][render_portlet_jsp:132] null
com.liferay.portal.NoSuchLayoutException: No Layout exists with the primary key


问:
How to get last 5 years and next year in Java
I want to get the last 5 years from the current year and next year from the current year in Java. All those value needs to be stored in an array .The intent is to only allow a total of 7 years as options.  So for 2018, the array would show 2012-2018.  And then in 2019, the array would show 2013-2019 and so on.]

Below code i have tried but not able to figure out how to store in array :

```<code>Integer currentYear = gregorianDate.getYear();
 Integer newYear = currentYear+1;
 Integer prevYear = currentYear-1;
</code>```

答:
You can get it this way I suppose:

```<code>Integer currentYear = Calendar.getInstance().get(Calendar.YEAR) + 1;
int[] yearsSpan = new int[7];
for (int i = 7; i > 0; i--) {
    yearsSpan[7-i] = currentYear - (i-1);
}
</code>```

To quickly display array contents:

```<code>System.out.println(Arrays.toString(yearsSpan));
</code>```

Body:
I want to get the last 5 years from the current year and next year from the current year in Java. All those value needs to be stored in an array .The intent is to only allow a total of 7 years as options.  So for 2018, the array would show 2012-2018.  And then in 2019, the array would show 2013-2019 and so on.]

Below code i have tried but not able to figure out how to store in array :

Integer currentYear = gregorianDate.getYear();
 Integer newYear = currentYear+1;
 Integer prevYear = currentYear-1;

Body:
You can get it this way I suppose:

Integer currentYear = Calendar.getInstance().get(Calendar.YEAR) + 1;
int[] yearsSpan = new int[7];
for (int i = 7; i > 0; i--) {
    yearsSpan[7-i] = currentYear - (i-1);
}

To quickly display array contents:

System.out.println(Arrays.toString(yearsSpan));


答:
From my knowledge, this is not possible.

Your browser has to have access to JS files to be able to execute them. If the browser has access, then browser's user also has access.

If you password protect your JS files, then the browser won't be able to access them, defeating the purpose of having JS in the first place.

Title: How do I protect JavaScript files?