问:
redux-promise use 'then()' after dispatching action
I want to delete a post. I'm using redux-promise as middleware.
My action looks like this:

```<code>export function deletePost(id) {
    const request = axios.delete(`${ROOT_URL}/${id}?apiKey=${API_KEY}`)

    return {
        type: DELETE_POST,
        payload: request
    }
}
</code>```

Then I have a button in my component to trigger action.

```<code>onDeleteClick() {
        deletePost(id)
        .then(setState({ redirect: true }))
    }
</code>```

The problem is that I can't use 'then()'. I would simply like to redirect user to homepage after deleting post.
Please help me guys.

Source code on request.

actions/index.js

```<code>import axios from 'axios';

export const DELETE_POST = 'DELETE_POST';

export const ROOT_URL = 'example.com';
export const API_KEY = 'randomstring';

export function deletePost(id) {
    const request = axios.delete(`${ROOT_URL}/${id}?apiKey=${API_KEY}`)

    return {
        type: DELETE_POST,
        payload: request
    }
}
</code>```

reducers/post_reducer.js

```<code>import {  DELETE_POST } from '../actions/index';

const INITIAL_STATE = { all: [], post: null };

export default function(state = INITIAL_STATE, action) {
    switch(action.type) {
            return state.all.filter(post => post !== action.payload.data);
        default:
            return state;
    }
}
</code>```

components/PostShow.js

```<code>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPost, deletePost } from '../actions/index';
import { Link } from 'react-router-dom';
import { Redirect } from 'react-router';

class PostsShow extends Component {
     constructor(props) {
        super(props)

        this.state = {
            redirect: false
        }
    }
    componentWillMount() {
        this.props.fetchPost(this.props.match.params.id)
    }

    onDeleteClick() {
        deletePost(this.props.match.params.id)
        .then(() => this.setState({ redirect: true }))
    }

    render() {

        if(!this.props.post) {
            return <div>Loading...</div>
        }
        if(this.state.redirect) {
            return <Redirect to='/'/>
        }

        return (

            <div className='blog-post container'>
                <h3>{this.props.post.title}</h3>
                <h6>Categories: {this.props.post.categories}</h6>
                <p>{this.props.post.content}</p>
                <Link to='/'><button className='btn btn-primary'>Back</button></Link>
                { this.props.user
                ? <button className='btn btn-danger' onClick={this.onDeleteClick.bind(this)}>Delete</button>
               : null }
            </div>
        );
    }
}

function mapStateToProps(state) {
    return {
        post: state.posts.post,
        user: state.user
    }
}

export default connect(mapStateToProps, { fetchPost, deletePost }) (PostsShow)
</code>```

答:
Per the redux-promise source code, it looks like it should return the chained promise:

```<code>return isPromise(action.payload)
  ? action.payload.then(
      result => dispatch({ ...action, payload: result }),
      error => {
        dispatch({ ...action, payload: error, error: true });
        return Promise.reject(error);
      }
    )
  : next(action);
</code>```

So, I would assume that you could chain off of the dispatch.

That said, your snippet has a couple potential issues.  If that's in a component, then where is deletePost coming from?  You're also not using this in front of setState.  Assuming that deletePost is a bound-up action creator, this example should be correct:

```<code>onDeleteClick() {
    this.props.deletePost(id)
        .then(() => this.setState({redirect : true});
}
</code>```

Body:
I want to delete a post. I'm using redux-promise as middleware.
My action looks like this:

export function deletePost(id) {
    const request = axios.delete(`${ROOT_URL}/${id}?apiKey=${API_KEY}`)

    return {
        type: DELETE_POST,
        payload: request
    }
}

Then I have a button in my component to trigger action.

onDeleteClick() {
        deletePost(id)
        .then(setState({ redirect: true }))
    }

The problem is that I can't use 'then()'. I would simply like to redirect user to homepage after deleting post.
Please help me guys.

Source code on request.

actions/index.js

import axios from 'axios';

export const DELETE_POST = 'DELETE_POST';

export const ROOT_URL = 'example.com';
export const API_KEY = 'randomstring';

export function deletePost(id) {
    const request = axios.delete(`${ROOT_URL}/${id}?apiKey=${API_KEY}`)

    return {
        type: DELETE_POST,
        payload: request
    }
}

reducers/post_reducer.js

import {  DELETE_POST } from '../actions/index';

const INITIAL_STATE = { all: [], post: null };

export default function(state = INITIAL_STATE, action) {
    switch(action.type) {
            return state.all.filter(post => post !== action.payload.data);
        default:
            return state;
    }
}

components/PostShow.js

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPost, deletePost } from '../actions/index';
import { Link } from 'react-router-dom';
import { Redirect } from 'react-router';

class PostsShow extends Component {
     constructor(props) {
        super(props)

        this.state = {
            redirect: false
        }
    }
    componentWillMount() {
        this.props.fetchPost(this.props.match.params.id)
    }

    onDeleteClick() {
        deletePost(this.props.match.params.id)
        .then(() => this.setState({ redirect: true }))
    }

    render() {

        if(!this.props.post) {
            return
Loading...

        }
        if(this.state.redirect) {
            return <Redirect to='/'/>
        }

        return (

{this.props.post.title}

Categories: {this.props.post.categories}

{this.props.post.content}

                <Link to='/'><button className='btn btn-primary'>Back</button></Link>
                { this.props.user
                ? <button className='btn btn-danger' onClick={this.onDeleteClick.bind(this)}>Delete</button>
               : null }

        );
    }
}

function mapStateToProps(state) {
    return {
        post: state.posts.post,
        user: state.user
    }
}

export default connect(mapStateToProps, { fetchPost, deletePost }) (PostsShow)

Body:
Per the redux-promise source code, it looks like it should return the chained promise:

return isPromise(action.payload)
  ? action.payload.then(
      result => dispatch({ ...action, payload: result }),
      error => {
        dispatch({ ...action, payload: error, error: true });
        return Promise.reject(error);
      }
    )
  : next(action);

So, I would assume that you could chain off of the dispatch.

That said, your snippet has a couple potential issues.  If that's in a component, then where is deletePost coming from?  You're also not using this in front of setState.  Assuming that deletePost is a bound-up action creator, this example should be correct:

onDeleteClick() {
    this.props.deletePost(id)
        .then(() => this.setState({redirect : true});
}


来源: stackexchange

问:
VarBinary vs Image SQL Server Data Type to Store Binary Data?
I need to store binary files to the SQL Server Database. Which is the better Data Type out of Varbinary and Image?</p>

答: There is also the rather spiffy FileStream, introduced in SQL Server 2008.

OwnerDisplayName: Yoann. B

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: Andrew Rollings

ContentLicense: CC BY-SA 2.5


问:
jQuery: Uploading an image on fileinput.change();
i have a fileinput control in my html form, which automatically uploads an image to the server once it has been picked up by the user:

```<code><input id="uploadedfile" name="uploadedfile" type="file" class="file" />
</code>```

I have attached this event to the $(document).ready

```<code>//uploader event
$('#uploadedfile').change(function(){
    ajaxFileUpload();
});

//upload file
function ajaxFileUpload(){
    $.ajaxFileUpload({
        url:'upload.php',
        secureuri:false,
        fileElementId:'uploadedfile',
        dataType: 'json',
        success: function(data,status){
            if(typeof(data.error) != 'undefined'){
                if(data.error){
                    //print error
                    alert(data.error);
                }else{
                    //clear
                    $('#img img').attr('src',url+'cache/'+data.msg);
                }
            }
        },
        error: function(data,status,e){
            //print error
            alert(e);
        }
    });
    return false;
}
</code>```

The big problem is that it only works on the first file selection. Any further selections of the fileinput, won't execute the ajaxFileUpload() function -- although, if i do replace ajaxFileUpload() with an alert() in the .change() event it does work.

Extra methods for the upload (the error is definitely not here)

```<code>jQuery.extend({
    createUploadIframe: function(id,uri){
        var frameId = 'jUploadFrame' + id;
        if(window.ActiveXObject){
            var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
            if(typeof uri== 'boolean') {
                io.src = 'javascript:false';
            } else if(typeof uri== 'string') {
                io.src = uri;
            }
        } else {
            var io = document.createElement('iframe');
            io.id = frameId;
            io.name = frameId;
        }
        io.style.position = 'absolute';
        io.style.top = '-1000px';
        io.style.left = '-1000px';
        document.body.appendChild(io);
        return io
    },
    createUploadForm: function(id,fileElementId){
        var formId = 'jUploadForm' + id;
        var fileId = 'jUploadFile' + id;
        var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
        var oldElement = $('#' + fileElementId);
        var newElement = $(oldElement).clone();
        $(oldElement).attr('id',fileId);
        $(oldElement).before(newElement);
        $(oldElement).appendTo(form);
        $(form).css('position','absolute');
        $(form).css('top','-1200px');
        $(form).css('left','-1200px');
        $(form).appendTo('body');
        return form;
    },
    ajaxFileUpload: function(s){
        s = jQuery.extend({},jQuery.ajaxSettings,s);
        var id = new Date().getTime();
        var form = jQuery.createUploadForm(id,s.fileElementId);
        var io = jQuery.createUploadIframe(id,s.secureuri);
        var frameId = 'jUploadFrame' + id;
        var formId = 'jUploadForm' + id;
        if(s.global && ! jQuery.active++) {
            jQuery.event.trigger('ajaxStart');
        }
        var requestDone = false;
        var xml = {}
        if(s.global)
            jQuery.event.trigger('ajaxSend',[xml,s]);
        var uploadCallback = function(isTimeout){
            var io = document.getElementById(frameId);
            try {
                if(io.contentWindow) {
                    xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
                    xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
                } else if(io.contentDocument) {
                    xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
                    xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
                }
            } catch(e) {
                jQuery.handleError(s,xml,null,e);
            }
            if(xml || isTimeout == 'timeout') {
                requestDone = true;
                var status;
                try {
                    status = isTimeout != 'timeout' ? 'success' : 'error';
                    if(status != 'error') {
                        var data = jQuery.uploadHttpData(xml,s.dataType);
                        if(s.success)
                            s.success(data,status);
                        if(s.global)
                            jQuery.event.trigger('ajaxSuccess',[xml,s]);
                    } else
                        jQuery.handleError(s,xml,status);
                } catch(e) {
                    status = 'error';
                    jQuery.handleError(s,xml,status,e);
                }
                if(s.global)
                    jQuery.event.trigger('ajaxComplete',[xml,s]);
                if(s.global && ! --jQuery.active)
                    jQuery.event.trigger('ajaxStop');
                if(s.complete)
                    s.complete(xml,status);
                jQuery(io).unbind();
                setTimeout(function(){
                    try {
                        $(io).remove();
                        $(form).remove();
                    } catch(e) {
                        jQuery.handleError(s,xml,null,e);
                    }
                },100);
                xml = null;
            }
        }
        if(s.timeout > 0) {
            setTimeout(function(){
                if(!requestDone) uploadCallback('timeout');
            },s.timeout);
        } try {
            var form = $('#' + formId);
            $(form).attr('action',s.url);
            $(form).attr('method','POST');
            $(form).attr('target',frameId);
            if(form.encoding) {
                form.encoding = 'multipart/form-data';
            } else {
                form.enctype = 'multipart/form-data';
            }
            $(form).submit();
        } catch(e) {
            jQuery.handleError(s,xml,null,e);
        }
        if(window.attachEvent){
            document.getElementById(frameId).attachEvent('onload',uploadCallback);
        } else {
            document.getElementById(frameId).addEventListener('load',uploadCallback,false);
        }
        return {abort: function () {}};
    },
    uploadHttpData: function(r,type) {
        var data = !type;
        data = type == 'xml' || data ? r.responseXML : r.responseText;
        if(type == 'script')
            jQuery.globalEval(data);
        if(type == 'json')
            eval('data = ' + data);
        if(type == 'html')
            jQuery("<div>").html(data).evalScripts();
        return data;
    }
})
</code>```

Any ideas will be appreciated. Thanks!

答:
why are you trying to reinvent the wheel?

Use the jquery form plugin

There is a section about ajax uploads in the examples..

Body:
i have a fileinput control in my html form, which automatically uploads an image to the server once it has been picked up by the user:

<input id="uploadedfile" name="uploadedfile" type="file" class="file" />

I have attached this event to the $(document).ready

//uploader event
$('#uploadedfile').change(function(){
    ajaxFileUpload();
});

//upload file
function ajaxFileUpload(){
    $.ajaxFileUpload({
        url:'upload.php',
        secureuri:false,
        fileElementId:'uploadedfile',
        dataType: 'json',
        success: function(data,status){
            if(typeof(data.error) != 'undefined'){
                if(data.error){
                    //print error
                    alert(data.error);
                }else{
                    //clear
                    $('#img img').attr('src',url+'cache/'+data.msg);
                }
            }
        },
        error: function(data,status,e){
            //print error
            alert(e);
        }
    });
    return false;
}

The big problem is that it only works on the first file selection. Any further selections of the fileinput, won't execute the ajaxFileUpload() function -- although, if i do replace ajaxFileUpload() with an alert() in the .change() event it does work.

Extra methods for the upload (the error is definitely not here)

jQuery.extend({
    createUploadIframe: function(id,uri){
        var frameId = 'jUploadFrame' + id;
        if(window.ActiveXObject){
            var io = document.createElement('');
            if(typeof uri== 'boolean') {
                io.src = 'javascript:false';
            } else if(typeof uri== 'string') {
                io.src = uri;
            }
        } else {
            var io = document.createElement('iframe');
            io.id = frameId;
            io.name = frameId;
        }
        io.style.position = 'absolute';
        io.style.top = '-1000px';
        io.style.left = '-1000px';
        document.body.appendChild(io);
        return io
    },
    createUploadForm: function(id,fileElementId){
        var formId = 'jUploadForm' + id;
        var fileId = 'jUploadFile' + id;
        var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
        var oldElement = $('#' + fileElementId);
        var newElement = $(oldElement).clone();
        $(oldElement).attr('id',fileId);
        $(oldElement).before(newElement);
        $(oldElement).appendTo(form);
        $(form).css('position','absolute');
        $(form).css('top','-1200px');
        $(form).css('left','-1200px');
        $(form).appendTo('body');
        return form;
    },
    ajaxFileUpload: function(s){
        s = jQuery.extend({},jQuery.ajaxSettings,s);
        var id = new Date().getTime();
        var form = jQuery.createUploadForm(id,s.fileElementId);
        var io = jQuery.createUploadIframe(id,s.secureuri);
        var frameId = 'jUploadFrame' + id;
        var formId = 'jUploadForm' + id;
        if(s.global && ! jQuery.active++) {
            jQuery.event.trigger('ajaxStart');
        }
        var requestDone = false;
        var xml = {}
        if(s.global)
            jQuery.event.trigger('ajaxSend',[xml,s]);
        var uploadCallback = function(isTimeout){
            var io = document.getElementById(frameId);
            try {
                if(io.contentWindow) {
                    xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
                    xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
                } else if(io.contentDocument) {
                    xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
                    xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
                }
            } catch(e) {
                jQuery.handleError(s,xml,null,e);
            }
            if(xml || isTimeout == 'timeout') {
                requestDone = true;
                var status;
                try {
                    status = isTimeout != 'timeout' ? 'success' : 'error';
                    if(status != 'error') {
                        var data = jQuery.uploadHttpData(xml,s.dataType);
                        if(s.success)
                            s.success(data,status);
                        if(s.global)
                            jQuery.event.trigger('ajaxSuccess',[xml,s]);
                    } else
                        jQuery.handleError(s,xml,status);
                } catch(e) {
                    status = 'error';
                    jQuery.handleError(s,xml,status,e);
                }
                if(s.global)
                    jQuery.event.trigger('ajaxComplete',[xml,s]);
                if(s.global && ! --jQuery.active)
                    jQuery.event.trigger('ajaxStop');
                if(s.complete)
                    s.complete(xml,status);
                jQuery(io).unbind();
                setTimeout(function(){
                    try {
                        $(io).remove();
                        $(form).remove();
                    } catch(e) {
                        jQuery.handleError(s,xml,null,e);
                    }
                },100);
                xml = null;
            }
        }
        if(s.timeout > 0) {
            setTimeout(function(){
                if(!requestDone) uploadCallback('timeout');
            },s.timeout);
        } try {
            var form = $('#' + formId);
            $(form).attr('action',s.url);
            $(form).attr('method','POST');
            $(form).attr('target',frameId);
            if(form.encoding) {
                form.encoding = 'multipart/form-data';
            } else {
                form.enctype = 'multipart/form-data';
            }
            $(form).submit();
        } catch(e) {
            jQuery.handleError(s,xml,null,e);
        }
        if(window.attachEvent){
            document.getElementById(frameId).attachEvent('onload',uploadCallback);
        } else {
            document.getElementById(frameId).addEventListener('load',uploadCallback,false);
        }
        return {abort: function () {}};
    },
    uploadHttpData: function(r,type) {
        var data = !type;
        data = type == 'xml' || data ? r.responseXML : r.responseText;
        if(type == 'script')
            jQuery.globalEval(data);
        if(type == 'json')
            eval('data = ' + data);
        if(type == 'html')
            jQuery("
").html(data).evalScripts();
        return data;
    }
})

Any ideas will be appreciated. Thanks!


问:
How difficult would it be to add a generic code-gen backend to Julia?
How difficult would it be to add a generic code-gen backend to Julia in the vein of go and chez-schemei.e. without the LLVM.

Would LLVM be a better way to do it - given that rust and crystal are also almost entirely self hosted and they can leverage the LLVM to emit binaries, even cross compile.

For a background, I've asked a question specifically about code-gen in case of various LLVM front-ends here What are the issues faced while implementing a self-hosted language on LLVM?

答:
Julia does have a form of code-gen which is its typed AST. You can see the typed AST using @code_typed in front of any function call. Theoretically you can use that to emit to any IR, and Julia chooses LLVM IR for reasons stated elsewhere. Transpiler.jl is a package which does this to output things like OpenCL code from Julia functions.

You can use the LLVM IR to emit other bytecodes. CUDANative.jl uses LLVM's .ptx backend to emit CUDA kernels directly from Julia functions. The @polly project is looking to do similar things whereby the macro would allow Julia to auto-accelerate some codes on the GPU (I admittedly have little knowledge of this, other than reading the post which suggested it and the followup. This was picked up as a GSoC project for LLVM).


问:
How to use git branch for refactoring legacy code?
If I want to refactor the legacy code then I need write tests for the code.So I make a new branch called 'refactor'.I will make a tests folder and some tests file in it.

But I found that when I finish the refactoring and want to merge to the master branch I need to merge tests folder and its files to master branch.

I do not want to merge these tests files to my master branch.

I want to keep the tests file and some other dev folders for the
  'refactor' branch.Because maybe I need to fix some bug under this
  'refactor' branch with those files.

How should I do?

答:
From master:

```<code>git merge --no-commit refactorbranch
git reset path/to/my/unwanted/tests
git reset path/to/unwanted/data
git commit -m "Merged refactoring"
</code>```

Body:
From master:

git merge --no-commit refactorbranch
git reset path/to/my/unwanted/tests
git reset path/to/unwanted/data
git commit -m "Merged refactoring"


问:
JQuery how to difference between a select option with an option selected attribute and a select without a selected value
I'm populating multiple select with a webservice.
This web service is returning the selected value.

Well, at the moment to render them, I have 2 different select

```<code><select id='select1'>
<option value='1'>Option 1</option>
<option value='3'>Option 3</option>
</select>

<select id='select2'>
<option selected="selected" value='A'>Option A</option>
<option value='B'>Option B</option>
</select>
</code>```

Well, the first select hasn't any selected attribute and the second one has it.

When I execute:

```<code>$("select1").find("option:selected").val(); //Returns 1
$("select2").find("option:selected").val(); //Returns A
</code>```

How I can identify when the select has an option really selected?

答:
Instead of using :selected which looks for the selected state, you can look for [selected], which will check for the selected attribute.

var $selectedOption = $("#select1 option[selected]");

if ($selectedOption.length) {
    //option selected
    console.log(selectedOption.val() + " selected.");
} else {
    //no option selected
    console.log("Nothing selected.");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='select1'>
<option value='1'>Option 1</option>
<option value='3'>Option 3</option>
</select>

<select id='select2'>
<option selected="selected" value='A'>Option A</option>
<option value='B'>Option B</option>
</select></code>```

Body:
I'm populating multiple select with a webservice.
This web service is returning the selected value.

Well, at the moment to render them, I have 2 different select

<select id='select1'>
<option value='1'>Option 1</option>
<option value='3'>Option 3</option>
</select>

<select id='select2'>
<option selected="selected" value='A'>Option A</option>
<option value='B'>Option B</option>
</select>

Well, the first select hasn't any selected attribute and the second one has it.

When I execute:

$("select1").find("option:selected").val(); //Returns 1
$("select2").find("option:selected").val(); //Returns A

How I can identify when the select has an option really selected?

Body:
Instead of using :selected which looks for the selected state, you can look for [selected], which will check for the selected attribute.

var $selectedOption = $("#select1 option[selected]");

if ($selectedOption.length) {
    //option selected
    console.log(selectedOption.val() + " selected.");
} else {
    //no option selected
    console.log("Nothing selected.");
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='select1'>
<option value='1'>Option 1</option>
<option value='3'>Option 3</option>
</select>

<select id='select2'>
<option selected="selected" value='A'>Option A</option>
<option value='B'>Option B</option>
</select>


问:
How to manage rotations in a subclass of UITableViewCell
I have a custom UITableViewCell in a universal application and I have to set different frame for iPhone and iPad and I have to consider the different orientations but can not be recognized  the orientation of the device. UIDeviceOrientation is in the wrong place? UIDeviceOrientation return 0.
This is the code in CustomCell.m

```<code> -(void) layoutCellPortrait{
 if(UI_USER_INTERFACE_IDIOM()== UIUserInterfaceIdiomPhone){

         //......frame subviews iPhone

 }else{

      //........frame subviews Ipad

 }

 }
 -(void) layoutCellLandscape{
     if(UI_USER_INTERFACE_IDIOM()== UIUserInterfaceIdiomPhone){

         //.....frame subviews iPhone

     }else{

        //.......frame subviews Ipad

 }

}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
   {

    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];

    if (self) {

    UIDeviceOrientation deviceOrientation = [[UIDevice currentDevice]orientation];
    NSLog(@"The orientation is è %d", deviceOrientation);//here return 0

    if(deviceOrientation == UIInterfaceOrientationPortrait || deviceOrientation== UIInterfaceOrientationPortraitUpsideDown) {

         [self layoutCellPortrait];

    }
    else if (deviceOrientation== UIInterfaceOrientationLandscapeRight){
        [self layoutCellLandscape];

    }
    else if (deviceOrientation==UIInterfaceOrientationLandscapeLeft){

        [self layoutCellLandscape];

    }

    [self.contentView addSubview:self.subviews];

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

答:
For Swift, if you have customs UIViews inside your UITableViewCell without AutoLayout and you want to update the UI at the orientation change, you can do this inside the UITableViewCell custom class:

```<code>override func layoutSubviews() {
    super.layoutSubviews()
    self.customView.layoutSubviews()
}
</code>```

Body:
I have a custom UITableViewCell in a universal application and I have to set different frame for iPhone and iPad and I have to consider the different orientations but can not be recognized  the orientation of the device. UIDeviceOrientation is in the wrong place? UIDeviceOrientation return 0.
This is the code in CustomCell.m

 -(void) layoutCellPortrait{
 if(UI_USER_INTERFACE_IDIOM()== UIUserInterfaceIdiomPhone){

         //......frame subviews iPhone

 }else{

      //........frame subviews Ipad

 }

 }
 -(void) layoutCellLandscape{
     if(UI_USER_INTERFACE_IDIOM()== UIUserInterfaceIdiomPhone){

         //.....frame subviews iPhone

     }else{

        //.......frame subviews Ipad

 }

}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
   {

    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];

    if (self) {

    UIDeviceOrientation deviceOrientation = [[UIDevice currentDevice]orientation];
    NSLog(@"The orientation is è %d", deviceOrientation);//here return 0

    if(deviceOrientation == UIInterfaceOrientationPortrait || deviceOrientation== UIInterfaceOrientationPortraitUpsideDown) {

         [self layoutCellPortrait];

    }
    else if (deviceOrientation== UIInterfaceOrientationLandscapeRight){
        [self layoutCellLandscape];

    }
    else if (deviceOrientation==UIInterfaceOrientationLandscapeLeft){

        [self layoutCellLandscape];

    }

    [self.contentView addSubview:self.subviews];

}
return self;
 }

Body:
For Swift, if you have customs UIViews inside your UITableViewCell without AutoLayout and you want to update the UI at the orientation change, you can do this inside the UITableViewCell custom class:

override func layoutSubviews() {
    super.layoutSubviews()
    self.customView.layoutSubviews()
}

ContentLicense: CC BY-SA 4.0


问:
Should I include file extensions when setting registry items?
In two instances I define registry items which I specify the name of the template and css files.  Should I include the file extension when setting the registry items, or exclude them as I am currently doing with my application?  What do you advise?

```<code> $registryItems['template']    = 'default'; //Name of .tpl file
 $registryItems['stylesheet']  = 'default'; //Name of .css file
</code>```

Thanks in advance!

答: I would look at comparable entries written by someone who knows the proper conventions.  Maybe Microsoft has some entries to look at?</p>

Body:
In two instances I define registry items which I specify the name of the template and css files.  Should I include the file extension when setting the registry items, or exclude them as I am currently doing with my application?  What do you advise?

 $registryItems['template']    = 'default'; //Name of .tpl file
 $registryItems['stylesheet']  = 'default'; //Name of .css file

Thanks in advance!


问:
How can I solve "XMLHttpRequest cannot load javascript"?
My view is like this :

```<code>@foreach($product->photo_list as $i => $photo)
    <a href="javascript:" class="text-danger confirm-delete"
       data-toggle="modal"
       data-target="#modal-delete-image"
       data-photo="{{ json_encode($photo) }}"
       data-product_id="{{ $product->id }}"
    >
        <span class="fa fa-trash"></span>
    </a>
@endforeach
</code>```

My modal is like this :

```<code><bs-modal id="modal-delete-image" v-cloak>
    <h4 slot="title" class="modal-title">...</h4>
    <div slot="body" class="modal-body">
       ...
    </div>
    <div slot="footer" class="modal-footer">
        ...
    </div>
</bs-modal>
</code>```

My javascript is like this :

```<code>$(document).on("click", ".confirm-delete", function () {
    var photo = $(this).data('photo');
    var product_id = $(this).data('product_id');
    console.log(photo)
    console.log(product_id)
});
</code>```

I put the js in global js

When executed the code, it works

The console.log success display the result. It's true

But when in chrome browser, there exist error like this :

XMLHttpRequest cannot load javascript:. Cross origin requests are only
  supported for protocol schemes: http, data, chrome, chrome-extension,
  https.

If I check on the firefox browser, there is no error

Why when I use chrome browser, there exist error?

How can I solve it?

答:
```<code> $(document).on("click", ".confirm-delete", function (e) {
    e.preventDefault();
    var photo = $(this).data('photo');
    var product_id = $(this).data('product_id');
     console.log(photo);
     console.log(product_id);
 });
</code>```

Body:
My view is like this :

@foreach($product->photo_list as $i => $photo)
    id }}"
    >

@endforeach

My modal is like this :

<bs-modal id="modal-delete-image" v-cloak>

...

       ...

        ...

</bs-modal>

My javascript is like this :

$(document).on("click", ".confirm-delete", function () {
    var photo = $(this).data('photo');
    var product_id = $(this).data('product_id');
    console.log(photo)
    console.log(product_id)
});

I put the js in global js

When executed the code, it works

The console.log success display the result. It's true

But when in chrome browser, there exist error like this :

XMLHttpRequest cannot load javascript:. Cross origin requests are only
  supported for protocol schemes: http, data, chrome, chrome-extension,
  https.

If I check on the firefox browser, there is no error

Why when I use chrome browser, there exist error?

How can I solve it?


问:
How to auto-center jQuery UI dialog when resizing browser?
When you use jquery UI dialog, all works well, except for one thing.
When the browser is resized, the dialog just stays in it's initial position which can be really annoying.

You can test it out on:
http://jqueryui.com/demos/dialog/

Click on the "modal dialog" example and resize your browser.

I'd love to be able to let dialogs auto-center when the browser resizes.
Can this be done in an efficient way for all my dialogs in my app?

答:
Hello everyone!

Vanilla JS solution:

```<code>(function() {
  window.addEventListener("resize", resizeThrottler, false);

  var resizeTimeout;

  function resizeThrottler() {
    if (!resizeTimeout) {
      resizeTimeout = setTimeout(function() {
        resizeTimeout = null;
        actualResizeHandler();
      }, 66);
    }
  }

  function actualResizeHandler() {
    $(".ui-dialog-content").dialog("option", "position", { my: "center", at: "center", of: window });
  }
}());
</code>```

Body:
Hello everyone!

Vanilla JS solution:

(function() {
  window.addEventListener("resize", resizeThrottler, false);

  var resizeTimeout;

  function resizeThrottler() {
    if (!resizeTimeout) {
      resizeTimeout = setTimeout(function() {
        resizeTimeout = null;
        actualResizeHandler();
      }, 66);
    }
  }

  function actualResizeHandler() {
    $(".ui-dialog-content").dialog("option", "position", { my: "center", at: "center", of: window });
  }
}());


问:
How to abort old request processing when new request arrives on ASP.NET MVC 5?
I have a form with hundreds of check boxes and dropdown menus (Which value of many of them are coupled together). In the action there is updating mechanism to update an object in Session. This object does all validation and coupling of values, for example if user types %50 in one input filed, we might add 3 new SelectListItem to a dropdown.

Everything works fine, but if use starts to clicking on check boxes very quick (which is the normal case in our scenario), controller get multiple posts while it is processing previous ones. Fortunately we are only interested in the last POST, so we need a way to abort\cancel on going requests when newer request from same form comes.

What I tried:
1- blocking client side to make multiple posts when server still working on previous one. It is not desirable because it makes noticeable pauses on browser side.

2- There are several solutions for blocking multiple post backs by using HASH codes or AntiForgeryToken. But they don't what I need, I need to abort on-going thread in favor of new request, not blocking incoming request.

3- I tried to extend pipeline by adding two message handlers (one before action and another after executing action) to keep a hash code (or AntiForgeryToken) but problem is still there, even I can detect there is on-going thread working on same request, I have no way to abort that thread or set older request to Complete.

Any thoughts?

答:
You are trying to implement transactional functionality (i.e. counting only the last request) over an asynchronous technology.  This is a design flaw.

Since you refuse to block on the client side, you have no method by which to control which requests process first, OR to correctly process the outcome again on the client-side.

You might actually run into this scenario:

Client sends Request A

Server starts processing Request B

Client sends Request B

Server starts processing Request B

Server returns results of Request B, and client changes accordingly

Server returns results of Request A, and client changes accordingly (and undoes prior changes resulting from Request B)

Blocking is the only way you can ensure the correct order.


问:
Smallest number in array and its position
What I am trying to achieve is to find smallest number in array and its initial position. Here's an example what it should do:

```<code>temp = new Array();
temp[0] = 43;
temp[1] = 3;
temp[2] = 23;
</code>```

So in the end I should know number 3 and position 1. I also had a look here: Obtain smallest value from array in Javascript?, but this way does not give me a number position in the array. Any tips, or code snippets are appreciated.

答:
One-liner:</p>

```<code>alist=[5,6,3,8,2]

idx=alist.indexOf(Math.min.apply(null,alist))
</code>```

Body:
What I am trying to achieve is to find smallest number in array and its initial position. Here's an example what it should do:

temp = new Array();
temp[0] = 43;
temp[1] = 3;
temp[2] = 23;

So in the end I should know number 3 and position 1. I also had a look here: Obtain smallest value from array in Javascript?, but this way does not give me a number position in the array. Any tips, or code snippets are appreciated.

Body:
One-liner:

alist=[5,6,3,8,2]

idx=alist.indexOf(Math.min.apply(null,alist))


问:
Android Layout with height in percent
I want to make layout like that:

But I don't know how to make panel 2 and 3 filling remaining space (after adding fixed size panel 1) in 50:50 ratio. There must be something I am missing or just don't know about Android layout, but what is it?

I forgot to mention that I want to use Constraint Layout for these panels. I use Android Studio.

答:
Use a LinearLayout and layout_weight

```<code><LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="2">
    <View
        android:layout_width="match_parent"
        android:background="@color/blue"
        android:layout_height="16dp" />
    <View
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@color/black"
        android:layout_weight="1"/>
    <View
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@color/red"/>

</LinearLayout>
</code>```

The Views can be changed to ConstraintLayouts

Title: Android Layout with height in percent

Body:
Use a LinearLayout and layout_weight

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="2">
    <View
        android:layout_width="match_parent"
        android:background="@color/blue"
        android:layout_height="16dp" />
    <View
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:background="@color/black"
        android:layout_weight="1"/>
    <View
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@color/red"/>

</LinearLayout>

The Views can be changed to ConstraintLayouts


问:
Yii2 Ajax returns whole page content
I am trying to make simple ajax :

```<code>$('.send-contact-button').on('click', function(e){
        e.preventDefault();

       var id = $('.send-contact-button').data('id');
       var flag = $('.send-contact-button').data('flag');

       $.ajax({
           method : 'GET',
           url : "contactHandler?id="+id+"&flag="+flag,
           success : function( data ){
                console.log( data );
           }
       });

    });
</code>```

but every time i get the html content. Tryied to send the data through json but without result. This Ajax is just test.
Controller:

```<code>public function contactHandler($id, $flag)
{
    echo $id;
}
</code>```

Can you guys tell me where i am wrong ? Thank you very much!

答:
You ajax call should be formatted using yii2 urlmanager rules (contact-handler instead of contactHandler

```<code>  $.ajax({
       method : 'GET',
       url : "contact-handler?id="+id+"&flag="+flag,
       success : function( data ){
            console.log( data );
       }
   });
</code>```

and in your controller you must add the action text to your function name

eg:public function actionContactHandler($id, $flag)

Title: Yii2 Ajax returns whole page content

Body:
I am trying to make simple ajax :

$('.send-contact-button').on('click', function(e){
        e.preventDefault();

       var id = $('.send-contact-button').data('id');
       var flag = $('.send-contact-button').data('flag');

       $.ajax({
           method : 'GET',
           url : "contactHandler?id="+id+"&flag="+flag,
           success : function( data ){
                console.log( data );
           }
       });

    });

but every time i get the html content. Tryied to send the data through json but without result. This Ajax is just test.
Controller:

public function contactHandler($id, $flag)
{
    echo $id;
}

Can you guys tell me where i am wrong ? Thank you very much!

Body:
You ajax call should be formatted using yii2 urlmanager rules (contact-handler instead of contactHandler

  $.ajax({
       method : 'GET',
       url : "contact-handler?id="+id+"&flag="+flag,
       success : function( data ){
            console.log( data );
       }
   });

and in your controller you must add the action text to your function name

eg:public function actionContactHandler($id, $flag)


问:
Javascript how to run some code after a forEach completes executing
So I want to turn my "loading" gif on and off with ng-show. I would specifically like to turn it off after my script is done loading the array through a forEach.

How do I run code when the forEach completes its entire cycle". Something similar to a .then(), but for for loops

```<code>function selectAll(bool) {
  vm.selectAllSpinner = true;
  vm.practicesLeftCol = [];
  if(bool === true){
    vm.practices.forEach(function(practice){
      practice.selected = true;
      vm.practicesLeftCol.push(practice)
    })
    I want this after the foreach ->vm.selectAllSpinner = false;

  } else if (bool === false){
    vm.practices.forEach(function(practice){
      practice.selected = false;
      vm.practicesLeftCol = [];
    })
    I want this after the foreach ->vm.selectAllSpinner = false;

  }
</code>```

答:
So forEach isn't asynchronous. As such, you could literally just write:

```<code>function selectAll(bool) {
          vm.selectAllSpinner = true;
          vm.practicesLeftCol = [];
          if(bool === true){
            vm.practices.forEach(function(practice){
              practice.selected = true;
              vm.practicesLeftCol.push(practice)
            })
          } else if (bool === false){
            vm.practices.forEach(function(practice){
              practice.selected = false;
              vm.practicesLeftCol = [];
            })
          }
    vm.selectAllSpinner = false;
}
</code>```

Having said that, I think the code could be cleaned up in general to be more like so:

```<code>  function selectAll(bool) {
    vm.selectAllSpinner = true;
    vm.practicesLeftCol = [];
    if (bool) {
      vm.practicesLeftCol = vm.practices.reduce(function(memo, practice) {
        practice.selected = true;
        memo.push(practice);
        return memo;
      }, []);
    }
   vm.selectAllSpinner = false;
}
</code>```

Again, neither reduce nor forEach are asynchronous, so this should just kinda work...

Body:
So I want to turn my "loading" gif on and off with ng-show. I would specifically like to turn it off after my script is done loading the array through a forEach.

How do I run code when the forEach completes its entire cycle". Something similar to a .then(), but for for loops

function selectAll(bool) {
  vm.selectAllSpinner = true;
  vm.practicesLeftCol = [];
  if(bool === true){
    vm.practices.forEach(function(practice){
      practice.selected = true;
      vm.practicesLeftCol.push(practice)
    })
    I want this after the foreach ->vm.selectAllSpinner = false;

  } else if (bool === false){
    vm.practices.forEach(function(practice){
      practice.selected = false;
      vm.practicesLeftCol = [];
    })
    I want this after the foreach ->vm.selectAllSpinner = false;

  }

Body:
So forEach isn't asynchronous. As such, you could literally just write:

function selectAll(bool) {
          vm.selectAllSpinner = true;
          vm.practicesLeftCol = [];
          if(bool === true){
            vm.practices.forEach(function(practice){
              practice.selected = true;
              vm.practicesLeftCol.push(practice)
            })
          } else if (bool === false){
            vm.practices.forEach(function(practice){
              practice.selected = false;
              vm.practicesLeftCol = [];
            })
          }
    vm.selectAllSpinner = false;
}

Having said that, I think the code could be cleaned up in general to be more like so:

  function selectAll(bool) {
    vm.selectAllSpinner = true;
    vm.practicesLeftCol = [];
    if (bool) {
      vm.practicesLeftCol = vm.practices.reduce(function(memo, practice) {
        practice.selected = true;
        memo.push(practice);
        return memo;
      }, []);
    }
   vm.selectAllSpinner = false;
}

Again, neither reduce nor forEach are asynchronous, so this should just kinda work...


问:
jQuery Color Picker on-functions fails
Hey all. I've added jQuery colorPicker to my webpage and I'm trying to implement the forth example of it. You can find it on this page.

http://www.eyecon.ro/colorpicker/#about

After my implementation, everything works except for the options added in the colorPicker. I can't change the standard color and onShow, onHide & onChange never fires.

Can anyone see why?

Here's my code:

```<code>jQuery('document').ready(function(){
$('#colorSelector').ColorPicker({
 color: '#0000ff',
 onShow: function (colpkr) {
  $(colpkr).fadeIn(500);
  return false;
 },
 onHide: function (colpkr) {
  $(colpkr).fadeOut(500);
  return false;
 },
 onChange: function (hsb, hex, rgb) {
  $('#colorSelector div').css('backgroundColor', '#' + hex);
 }
});
</code>```

});

And here's the rest of the code implemented:

```<code><div class="settings-color"><div id="colorSelector"></div></div>
</code>```

Added scripts:

```<code><script type="text/javascript" src="http://www.google.com/jsapi"></script>
</code>```

  google.load("jquery", "1.4.2");
  google.load("swfobject", "2.2");

  swfobject.embedSWF("signaturetool.swf", "tool", "490", "700", "9.0.0", "expressInstall.swf", null, {allowScriptAccess: "always", align: "middle"}, {id: "signaturetool", name: "signaturetool"});

 -->

```<code><script type="text/javascript" src="js/eye.js"></script>
<script type="text/javascript" src="js/utils.js"></script>
<script type="text/javascript" src="js/layout.js?ver=1.0.2"></script>
</code>```

I've tried with both jQuery 1.3.2 and jQuery 1.4.2. I've also tried with removing swfobject for a while and other css options. It all seems to fail, why?

答: The right settings was in the layout.js-file and that's why it didn't respond on the index.php-file. When I applied my functions in the layout.js everything worked.</p>

Title: jQuery Color Picker on-functions fails

Body:
Hey all. I've added jQuery colorPicker to my webpage and I'm trying to implement the forth example of it. You can find it on this page.

http://www.eyecon.ro/colorpicker/#about

After my implementation, everything works except for the options added in the colorPicker. I can't change the standard color and onShow, onHide & onChange never fires.

Can anyone see why?

Here's my code:

jQuery('document').ready(function(){
$('#colorSelector').ColorPicker({
 color: '#0000ff',
 onShow: function (colpkr) {
  $(colpkr).fadeIn(500);
  return false;
 },
 onHide: function (colpkr) {
  $(colpkr).fadeOut(500);
  return false;
 },
 onChange: function (hsb, hex, rgb) {
  $('#colorSelector div').css('backgroundColor', '#' + hex);
 }
});

});

And here's the rest of the code implemented:

Added scripts:

  google.load("jquery", "1.4.2");
  google.load("swfobject", "2.2");

  swfobject.embedSWF("signaturetool.swf", "tool", "490", "700", "9.0.0", "expressInstall.swf", null, {allowScriptAccess: "always", align: "middle"}, {id: "signaturetool", name: "signaturetool"});

 -->

I've tried with both jQuery 1.3.2 and jQuery 1.4.2. I've also tried with removing swfobject for a while and other css options. It all seems to fail, why?


问:
Join AMAZON.DATE and AMAZON.TIME into sql DATETIME in python
I have a python code which gets following two parameters: AMAZON.DATE and AMAZON.TIME (format definition here):

```<code>import pymysql

def func(date, start_time):
    conn = pymysql.connect(hostname, user=username,
                               passwd=password, db=database, connect_timeout=5)

    cur = conn.cursor()
    # SQL statement here
</code>```

Now what I want to do is join these two date and time types and insert them as a sql DATETIME type. So the insert statement should be like - INSERT INTO table1 VALUES (date_time);. What I am having difficulty in is joining the two Amazon types and forming sql DATETIME type. How can I do that?

答:
I would suggest you to convert AMAZON.DATE and AMAZON.TIME into datetime objects and then simply use

```<code> datetime.datetime.combine(datetime.date(2011, 01, 01), datetime.time(10, 23))
</code>```

For example -

```<code> import datetime
 date_object = datetime.datetime.strptime('2015-06-07T', '%Y-%M-%dT').date()
 time_object = datetime.datetime.strptime('04:00','%H:%M').time()
 date_obj_final = datetime.datetime.combine(date_object, time_object)

#output
2015-01-07
04:00:00
2015-01-07 04:00:00
</code>```

Let me know,if it works !

Body:
I have a python code which gets following two parameters: AMAZON.DATE and AMAZON.TIME (format definition here):

import pymysql

def func(date, start_time):
    conn = pymysql.connect(hostname, user=username,
                               passwd=password, db=database, connect_timeout=5)

    cur = conn.cursor()
    # SQL statement here

Now what I want to do is join these two date and time types and insert them as a sql DATETIME type. So the insert statement should be like - INSERT INTO table1 VALUES (date_time);. What I am having difficulty in is joining the two Amazon types and forming sql DATETIME type. How can I do that?

Body:
I would suggest you to convert AMAZON.DATE and AMAZON.TIME into datetime objects and then simply use

 datetime.datetime.combine(datetime.date(2011, 01, 01), datetime.time(10, 23))

For example -

 import datetime
 date_object = datetime.datetime.strptime('2015-06-07T', '%Y-%M-%dT').date()
 time_object = datetime.datetime.strptime('04:00','%H:%M').time()
 date_obj_final = datetime.datetime.combine(date_object, time_object)

#output
2015-01-07
04:00:00
2015-01-07 04:00:00

Let me know,if it works !


问:
VR View (Web) grabbing invalid URL
I'm trying to use VR View for the web to display a 360 degree image. I created a basic sample locally and it works without issue but once I got the code into my project, I'm getting a 404 error saying the resource couldn't be found.

The vrview.min.js file is converting my image path, entered like image: 'images/myImage.jpg', to something like:

```<code>http://localhost:80/Project/index.html?image=http://localhost/Project/images/myImage.jpg&is_stereo=false&
</code>```

IIS is not finding the image and the whole thing is throwing a big fat 404 server error.

Here's my code:

```<code><!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>View 360 Image</title>

        <script type="text/javascript">
            window.addEventListener('load', onVrViewLoad);

            function onVrViewLoad() {
                var vrView = new VRView.Player('#vrview', {
                    image: 'images/myImage.jpg',
                    width: 800,
                    height: 700,
                    is_stereo: false
                });
            }
        </script>
    </head>

    <body>
        <form id="form1" runat="server">
            <div id="vrview"></div> <!-- Placeholder where the VR player will display -->
        </form>

        <script src="includes/vrview.min.js"></script>
    </body>
</html>
</code>```

Any help would be fantastic. Thanks!

答:
It looks like you need to use google's service url if you want to pass the url to load.
You are hosting vrview.min.js on your local server and it's passing it to your localhost which doesn't have the service running.

```<code><iframe src="//storage.googleapis.com/vrview/2.0/index.html?image=//storage.googleapis.com/vrview/examples/coral.jpg&is_stereo=true">
</iframe>
</code>```

VS.

```<code><iframe src="//localhost/Project/index.html?image=//storage.googleapis.com/vrview/examples/coral.jpg&is_stereo=true">
</iframe>
</code>```

Here is the slightly modified version of your html that I used to test on my local machine. The sample google image is loading for me.

```<code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>View 360 Image</title>

        <script type="text/javascript">
            window.addEventListener('load', onVrViewLoad);

            function onVrViewLoad() {
                var vrView = new VRView.Player('#vrview', {
                    image: '//storage.googleapis.com/vrview/examples/coral.jpg',
                    width: 1440,
                    height: 680,
                    is_stereo: true
                });
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div id="vrview"></div>
        </form>
        <script src="//storage.googleapis.com/vrview/2.0/build/vrview.min.js"></script>
    </body>
</html>
</code>```

VR View docs: https://developers.google.com/vr/concepts/vrview-web

Title: VR View (Web) grabbing invalid URL

Body:
I'm trying to use VR View for the web to display a 360 degree image. I created a basic sample locally and it works without issue but once I got the code into my project, I'm getting a 404 error saying the resource couldn't be found.

The vrview.min.js file is converting my image path, entered like image: 'images/myImage.jpg', to something like:

http://localhost:80/Project/index.html?image=http://localhost/Project/images/myImage.jpg&is_stereo=false&

IIS is not finding the image and the whole thing is throwing a big fat 404 server error.

Here's my code:

<!DOCTYPE html>

        <title>View 360 Image</title>

        <form id="form1" runat="server">

        </form>

Any help would be fantastic. Thanks!

Body:
It looks like you need to use google's service url if you want to pass the url to load.
You are hosting vrview.min.js on your local server and it's passing it to your localhost which doesn't have the service running.

<iframe src="//storage.googleapis.com/vrview/2.0/index.html?image=//storage.googleapis.com/vrview/examples/coral.jpg&is_stereo=true">
</iframe>

VS.

<iframe src="//localhost/Project/index.html?image=//storage.googleapis.com/vrview/examples/coral.jpg&is_stereo=true">
</iframe>

Here is the slightly modified version of your html that I used to test on my local machine. The sample google image is loading for me.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>View 360 Image</title>

        <script type="text/javascript">
            window.addEventListener('load', onVrViewLoad);

            function onVrViewLoad() {
                var vrView = new VRView.Player('#vrview', {
                    image: '//storage.googleapis.com/vrview/examples/coral.jpg',
                    width: 1440,
                    height: 680,
                    is_stereo: true
                });
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <div id="vrview"></div>
        </form>
        <script src="//storage.googleapis.com/vrview/2.0/build/vrview.min.js"></script>
    </body>
</html>

VR View docs: https://developers.google.com/vr/concepts/vrview-web


问:
i have a list of dates and i want to use then in pairs as from and to in a pja query until all dates have been used end in java
i have a list of dates and i want to use them in pairs as datefrom and dateto in a query until all dates have been used in java. date list 2017-06-07, 2017-06-08,2017-06-09,2017-06-10,2017-06-11 etc. i want to use them in pairs as illustrated on the image attached.
I want these dates to be paired inside a loop until all dates have been used

```<code>List<String> times = Arrays.asList("2017-06-07", "2017-06-08","2017-06-
09","2017-06-10","2017-06-11");
for(String date: times){
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
    LocalDateTime dateFrom = LocalDateTime.parse(date, formatter);
    LocalDateTime dateTo = LocalDateTime.parse(times.get(count+1), formatter);
    List<xxx> rec =
        xxxxxxRepository.xxxxxDateGreaterThanEqualAndDateLessThanEqual(1,
            23,dateFrom, dateTo);
}
</code>```

Body:
i have a list of dates and i want to use them in pairs as datefrom and dateto in a query until all dates have been used in java. date list 2017-06-07, 2017-06-08,2017-06-09,2017-06-10,2017-06-11 etc. i want to use them in pairs as illustrated on the image attached.
I want these dates to be paired inside a loop until all dates have been used

List<String> times = Arrays.asList("2017-06-07", "2017-06-08","2017-06-
09","2017-06-10","2017-06-11");
for(String date: times){
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
    LocalDateTime dateFrom = LocalDateTime.parse(date, formatter);
    LocalDateTime dateTo = LocalDateTime.parse(times.get(count+1), formatter);
    List<xxx> rec =
        xxxxxxRepository.xxxxxDateGreaterThanEqualAndDateLessThanEqual(1,
            23,dateFrom, dateTo);
}

Body:
Do you mean like this?

List<String> times = Arrays.asList("2017-06-07", "2017-06-08","2017-06-09","2017-06-10","2017-06-11");
System.out.println("from         to");
String prev = null;
for (String date : times) {
    if (prev != null)
        System.out.println(prev + "   " + date);
    prev = date;
}

Output

from         to
2017-06-07   2017-06-08
2017-06-08   2017-06-09
2017-06-09   2017-06-10
2017-06-10   2017-06-11


答:
In Javascript, use the semicolon (;) delimiter, optionally followed by a newline, to append a command to a previous command.  Thus

```<code>function selectAll(bool) {
    vm.selectAllSpinner = true;
    vm.practicesLeftCol = [];
    if(bool === true){
        vm.practices.forEach(function(practice){
            practice.selected = true;
            vm.practicesLeftCol.push(practice)
        });
        vm.selectAllSpinner = false;  //<---
    } else if (bool === false) {
        vm.practices.forEach(function(practice){
            practice.selected = false;
            vm.practicesLeftCol = [];
        });
        vm.selectAllSpinner = false; //<---
    }
}
</code>```

Title: Javascript how to run some code after a forEach completes executing

Body:
In Javascript, use the semicolon (;) delimiter, optionally followed by a newline, to append a command to a previous command.  Thus

function selectAll(bool) {
    vm.selectAllSpinner = true;
    vm.practicesLeftCol = [];
    if(bool === true){
        vm.practices.forEach(function(practice){
            practice.selected = true;
            vm.practicesLeftCol.push(practice)
        });
        vm.selectAllSpinner = false;  //<---
    } else if (bool === false) {
        vm.practices.forEach(function(practice){
            practice.selected = false;
            vm.practicesLeftCol = [];
        });
        vm.selectAllSpinner = false; //<---
    }
}


问:
Can you assign a value to a returned object?
I am trying to implement Euclid's algorithm in Python3.
If max(a, b) returns the object with the largest value in (a, b),
why can't you operate on that object like so:

max(a, b) %= min(a, b)

答:
```<code>>>> a = 5
>>> b = 6
>>> max(a, b) %= min(a, b)
  File "<stdin>", line 1
SyntaxError: can't assign to function call
</code>```

The interpreter has spoken. You are trying to operate on a value/object, which is not possible. Assignments can be performed on variables only, which are references pointing to said values/objects.

Even if you could do it, it's pointless, because you're trying to change the return value of a function, that hasn't been captured by any variable. You can't even use it.

Body:
>>> a = 5
>>> b = 6
>>> max(a, b) %= min(a, b)
  File "<stdin>", line 1
SyntaxError: can't assign to function call

The interpreter has spoken. You are trying to operate on a value/object, which is not possible. Assignments can be performed on variables only, which are references pointing to said values/objects.

Even if you could do it, it's pointless, because you're trying to change the return value of a function, that hasn't been captured by any variable. You can't even use it.


问:
Method overriding of abstract class that implements an interface
My question might be a bit lame. I can't really understand how abstract class method overriding works. In the code bellow I have OrderController with method that accepts Order model which derives from Model class itself, why does it throw the error?

```<code>interface CrudInterface
{
    public function show(Model $model);
}

abstract class CrudController extends Controller implements CrudInterface {
    public function show(Model $model)
    {
        return $model;
    }
}

class OrderController extends CrudController {

    // Throws an erorr ("
    // Declaration of App\Http\Controllers\OrderController::show(App\Order $order) should be compatible with
    // App\Http\Controllers\CrudController::show(Illuminate\Database\Eloquent\Model $model
    // ")
    public function show (Order $order) {
        return $order
    }

}
</code>```

Thanks in advance.

答:
Interface should match:</p>

```<code>class OrderController extends CrudController {

    public function show (Model $order) {
        if (!$order instanceOf Order) {
           throw new InvalidArgumentException();
        }
        return $order
    }
}
</code>```

Body:
My question might be a bit lame. I can't really understand how abstract class method overriding works. In the code bellow I have OrderController with method that accepts Order model which derives from Model class itself, why does it throw the error?

interface CrudInterface
{
    public function show(Model $model);
}

abstract class CrudController extends Controller implements CrudInterface {
    public function show(Model $model)
    {
        return $model;
    }
}

class OrderController extends CrudController {

    // Throws an erorr ("
    // Declaration of App\Http\Controllers\OrderController::show(App\Order $order) should be compatible with
    // App\Http\Controllers\CrudController::show(Illuminate\Database\Eloquent\Model $model
    // ")
    public function show (Order $order) {
        return $order
    }

}

Thanks in advance.

Body:
Interface should match:

class OrderController extends CrudController {

    public function show (Model $order) {
        if (!$order instanceOf Order) {
           throw new InvalidArgumentException();
        }
        return $order
    }
}


问:
WCF Contracts and Models in a MVVM client
I have a WCF service, and a WPF client application, built using the MVVM Pattern. The referenced WCF service allows the WPF client to manipulate contracts which describes the data that can be sent and received from the service.

Exemple Contract, defined Service side :

```<code>[DataContract()]
public class UserContract : BaseContract
{
    [DataMember()]
    public string UserName { get; set; }
    [DataMember()]
    public string FirstName { get; set; }
}
</code>```

If I consider those referenced contracts as part of the Model Tier of my MVVM application, what should be the relationship between this contracts, and the model classes of my Model Tier ? (Code examples on client side)

1. Inheritance ? Models inherits contracts.

```<code>public class UserModel : UserContract
</code>```

2. Composition ? Models hold an instance of the corresponding contract.

```<code>public class UserModel
{
  public UserContract userContract {get;set;}
}
</code>```

3. Addition ? Contracts being declared Partial, I could just "complete" contracts, and use them directly as my model classes.

```<code>public partial class UserContract
{
}
</code>```

答:
I recommend you should keep your Model Layer separate from Contract Layer. I feel contracts should act like DTOs or Messages between application and service and that is it.

--EDIT--

Model Layer/Business Layer: Composed of Business Logic and Business Rules.

Contract Layer : Composed of Models and other information needed to send/receive data correctly.

Example :

[This example uses Request/Response pattern.]

Model:

```<code>public class User
{
    public String Username { get; set; }
    public String Password { get; set; }
}
</code>```

Contracts:

```<code>public class GetUsersRequest
{ }

public class GetUsersResponse
{
    public List<User> Users { get; set; }
    public Boolean IsSuccess { get; set; }
}
</code>```

Service:

```<code>public interface IUserService
{
    GetUsersResponse GetUsers(GetUsersRequest request);
}

public class UserService : IUserService
{
    public GetUsersResponse GetUsers(GetUsersRequest request)
    {
        GetUsersResponse response = new GetUsersResponse();
        //...
        return response;
    }
}
</code>```

If you see here, Contract GetUsersResponse is composed of List of Users. It is used to transfer Users from Service to Client.

On the other hand, Model Layer does not know anything about Contract Layer. That is important. Business Entities should not know anything about other Layers. There should always be classes in Business Layer that populate these entities from Data Layer.

Body:
I have a WCF service, and a WPF client application, built using the MVVM Pattern. The referenced WCF service allows the WPF client to manipulate contracts which describes the data that can be sent and received from the service.

Exemple Contract, defined Service side :

[DataContract()]
public class UserContract : BaseContract
{
    [DataMember()]
    public string UserName { get; set; }
    [DataMember()]
    public string FirstName { get; set; }
}

If I consider those referenced contracts as part of the Model Tier of my MVVM application, what should be the relationship between this contracts, and the model classes of my Model Tier ? (Code examples on client side)

1. Inheritance ? Models inherits contracts.

public class UserModel : UserContract

2. Composition ? Models hold an instance of the corresponding contract.

public class UserModel
{
  public UserContract userContract {get;set;}
}

3. Addition ? Contracts being declared Partial, I could just "complete" contracts, and use them directly as my model classes.

public partial class UserContract
{
}

Body:
I recommend you should keep your Model Layer separate from Contract Layer. I feel contracts should act like DTOs or Messages between application and service and that is it.

--EDIT--

Model Layer/Business Layer: Composed of Business Logic and Business Rules.

Contract Layer : Composed of Models and other information needed to send/receive data correctly.

Example :

[This example uses Request/Response pattern.]

Model:

public class User
{
    public String Username { get; set; }
    public String Password { get; set; }
}

Contracts:

public class GetUsersRequest
{ }

public class GetUsersResponse
{
    public List<User> Users { get; set; }
    public Boolean IsSuccess { get; set; }
}

Service:

public interface IUserService
{
    GetUsersResponse GetUsers(GetUsersRequest request);
}

public class UserService : IUserService
{
    public GetUsersResponse GetUsers(GetUsersRequest request)
    {
        GetUsersResponse response = new GetUsersResponse();
        //...
        return response;
    }
}

If you see here, Contract GetUsersResponse is composed of List of Users. It is used to transfer Users from Service to Client.

On the other hand, Model Layer does not know anything about Contract Layer. That is important. Business Entities should not know anything about other Layers. There should always be classes in Business Layer that populate these entities from Data Layer.


问:
Treating outerHTML as jQuery object
I'm trying to create just 2 simple boxes and allowing uses to choose data from 1 box, which copies it to the second box. If there is already a same one on the second box, append some simple text behind.

It works basically when the item is not in the second box. However, when it is, I'm unable to append data to the text.

Here's a simple example.

https://jsfiddle.net/9mbgw20e/5/

```<code><div id="inventory">
  <div class='item'>
    <span>Apple</span>
  </div>
  <div class='item'>
    <span>Pear</span>
  </div>
</div>
<hr>
<div id="selected">

</div>

// bring the items from inventory to selected
// if selected is found, add some text to the back of it

$('.item').on('click', function() {
  var h = $(this)[0].outerHTML;

  var found = false;
  var foundId = '';
  if ($('#selected').children().length < 1) {
    // if there's nothing selected, just straight add this
    return $('#selected').prepend(h);
  }

  $('#selected').children().each(function() {
    if ($(this).find('span').text() == $(h).find('span').text()) { // if there is already one in selected div
      console.log('Found duplicated.');
      found = true;
      foundId = $(this)[0].outerHTML;
    }
  });

  if (!found) {
    // if item is not in selected div, add
    $('#selected').prepend(h);
  } else {
    // if item is in selected div, add some text to it
    $(foundId).append('1, ');
  }
});
</code>```

Clicking the first time works, but after clicking it the second time, nothing happens.

答:
Try using the first() method instead:

```<code>foundId = $(this).first();
</code>```

Updated JSFiddle.

Title: Treating outerHTML as jQuery object

Body:
I'm trying to create just 2 simple boxes and allowing uses to choose data from 1 box, which copies it to the second box. If there is already a same one on the second box, append some simple text behind.

It works basically when the item is not in the second box. However, when it is, I'm unable to append data to the text.

Here's a simple example.

https://jsfiddle.net/9mbgw20e/5/

    Apple

    Pear

// bring the items from inventory to selected
// if selected is found, add some text to the back of it

$('.item').on('click', function() {
  var h = $(this)[0].outerHTML;

  var found = false;
  var foundId = '';
  if ($('#selected').children().length < 1) {
    // if there's nothing selected, just straight add this
    return $('#selected').prepend(h);
  }

  $('#selected').children().each(function() {
    if ($(this).find('span').text() == $(h).find('span').text()) { // if there is already one in selected div
      console.log('Found duplicated.');
      found = true;
      foundId = $(this)[0].outerHTML;
    }
  });

  if (!found) {
    // if item is not in selected div, add
    $('#selected').prepend(h);
  } else {
    // if item is in selected div, add some text to it
    $(foundId).append('1, ');
  }
});

Clicking the first time works, but after clicking it the second time, nothing happens.

Body:
Try using the first() method instead:

foundId = $(this).first();

Updated JSFiddle.


问:
About java.lang.UnsatisfiedLinkError：org.bytedeco.javacpp.avutil
I try to work it out a couple days. But it didn't work.

Below is full error logs:

```<code>02-19 09:41:31.239 17753-17753/com.superdata.cxim E/art: dlopen("/system/lib64/libdl.so", RTLD_LAZY) failed: dlopen failed: cannot locate symbol "__cxa_finalize" referenced by "/system/lib64/libdl.so"...
02-19 09:41:31.317 17753-17753/com.superdata.cxim E/art: dlopen("/data/app/com.superdata.cxim-1/lib/arm64/libavutil.so", RTLD_LAZY) failed: dlopen failed: "/data/app/com.superdata.cxim-1/lib/arm64/libavutil.so" is 32-bit instead of 64-bit
02-19 09:41:31.359 17753-17753/com.superdata.cxim E/InputEventReceiver: Exception dispatching input event.
02-19 09:41:31.360 17753-17753/com.superdata.cxim E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
02-19 09:41:31.361 17753-17753/com.superdata.cxim E/MessageQueue-JNI: java.lang.UnsatisfiedLinkError: org.bytedeco.javacpp.avutil
    at java.lang.Class.classForName(Native Method)
    at java.lang.Class.forName(Class.java:309)
    at org.bytedeco.javacpp.Loader.load(Loader.java:390)
    at org.bytedeco.javacpp.Loader.load(Loader.java:358)
    at org.bytedeco.javacpp.avcodec$AVPacket.<clinit>(avcodec.java:1407)
    at com.superdata.cxim.ui.camera.javacv.FFmpegFrameRecorder.<init>(FFmpegFrameRecorder.java:252)
    at com.superdata.cxim.ui.camera.recorder.WXLikeVideoRecorder.initRecorder(WXLikeVideoRecorder.java:174)
    at com.superdata.cxim.ui.camera.recorder.WXLikeVideoRecorder.startRecording(WXLikeVideoRecorder.java:278)
    at com.superdata.cxim.ui.camera.main.NewRecordVideoActivity.startRecord(NewRecordVideoActivity.java:158)
    at com.superdata.cxim.ui.camera.main.NewRecordVideoActivity.onTouch(NewRecordVideoActivity.java:234)
    at android.view.View.dispatchTouchEvent(View.java:8656)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2523)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2114)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2523)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2114)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2523)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2114)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2523)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2114)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2523)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2114)
    at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2511)
    at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1807)
    at android.app.Activity.dispatchTouchEvent(Activity.java:2841)
    at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2468)
    at android.view.View.dispatchPointerEvent(View.java:8873)
    at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4831)
    at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4689)
    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4188)
    at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4241)
    at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4207)
    at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4344)
    at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4215)
    at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4401)
    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4188)
    at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4241)
    at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4207)
    at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4215)
    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4188)
    at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6645)
    at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:6619)
    at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6572)
    at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:6812)
    at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
    at android.os.MessageQueue.nativePollOnce(Native Method)
    at android.os.MessageQueue.next(MessageQueue.java:148)
    at android.os.Looper.loop(Looper.java:151)
</code>```

答:
Simply Compile these lines in gradle file of your project</p>

```<code>compile(group: 'org.bytedeco', name: 'javacv-platform', version: '1.3'){
    exclude group: 'org.bytedeco.javacpp-presets'
}
compile group: 'org.bytedeco.javacpp-presets', name: 'ffmpeg', version: '3.2.1-1.3'
compile group: 'org.bytedeco.javacpp-presets', name: 'ffmpeg', version: '3.2.1-1.3', classifier: 'android-arm'
</code>```

Body:
I try to work it out a couple days. But it didn't work.

Below is full error logs:

02-19 09:41:31.239 17753-17753/com.superdata.cxim E/art: dlopen("/system/lib64/libdl.so", RTLD_LAZY) failed: dlopen failed: cannot locate symbol "__cxa_finalize" referenced by "/system/lib64/libdl.so"...
02-19 09:41:31.317 17753-17753/com.superdata.cxim E/art: dlopen("/data/app/com.superdata.cxim-1/lib/arm64/libavutil.so", RTLD_LAZY) failed: dlopen failed: "/data/app/com.superdata.cxim-1/lib/arm64/libavutil.so" is 32-bit instead of 64-bit
02-19 09:41:31.359 17753-17753/com.superdata.cxim E/InputEventReceiver: Exception dispatching input event.
02-19 09:41:31.360 17753-17753/com.superdata.cxim E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
02-19 09:41:31.361 17753-17753/com.superdata.cxim E/MessageQueue-JNI: java.lang.UnsatisfiedLinkError: org.bytedeco.javacpp.avutil
    at java.lang.Class.classForName(Native Method)
    at java.lang.Class.forName(Class.java:309)
    at org.bytedeco.javacpp.Loader.load(Loader.java:390)
    at org.bytedeco.javacpp.Loader.load(Loader.java:358)
    at org.bytedeco.javacpp.avcodec$AVPacket.<clinit>(avcodec.java:1407)
    at com.superdata.cxim.ui.camera.javacv.FFmpegFrameRecorder.<init>(FFmpegFrameRecorder.java:252)
    at com.superdata.cxim.ui.camera.recorder.WXLikeVideoRecorder.initRecorder(WXLikeVideoRecorder.java:174)
    at com.superdata.cxim.ui.camera.recorder.WXLikeVideoRecorder.startRecording(WXLikeVideoRecorder.java:278)
    at com.superdata.cxim.ui.camera.main.NewRecordVideoActivity.startRecord(NewRecordVideoActivity.java:158)
    at com.superdata.cxim.ui.camera.main.NewRecordVideoActivity.onTouch(NewRecordVideoActivity.java:234)
    at android.view.View.dispatchTouchEvent(View.java:8656)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2523)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2114)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2523)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2114)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2523)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2114)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2523)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2114)
    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2523)
    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2114)
    at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2511)
    at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1807)
    at android.app.Activity.dispatchTouchEvent(Activity.java:2841)
    at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2468)
    at android.view.View.dispatchPointerEvent(View.java:8873)
    at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4831)
    at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4689)
    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4188)
    at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4241)
    at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4207)
    at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4344)
    at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4215)
    at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4401)
    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4188)
    at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4241)
    at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4207)
    at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4215)
    at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4188)
    at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6645)
    at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:6619)
    at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6572)
    at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:6812)
    at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
    at android.os.MessageQueue.nativePollOnce(Native Method)
    at android.os.MessageQueue.next(MessageQueue.java:148)
    at android.os.Looper.loop(Looper.java:151)

Body:
Simply Compile these lines in gradle file of your project

compile(group: 'org.bytedeco', name: 'javacv-platform', version: '1.3'){
    exclude group: 'org.bytedeco.javacpp-presets'
}
compile group: 'org.bytedeco.javacpp-presets', name: 'ffmpeg', version: '3.2.1-1.3'
compile group: 'org.bytedeco.javacpp-presets', name: 'ffmpeg', version: '3.2.1-1.3', classifier: 'android-arm'


问:
golang google storage copy error
I get an error when trying to install google cloud storage SDK for Golang.

```<code>go get -u cloud.google.com/go/storage

# cloud.google.com/go/storage
../../../../cloud.google.com/go/storage/copy.go:81: cannot use
res.TotalBytesRewritten (type int64) as type uint64 in argument to c.ProgressFunc
../../../../cloud.google.com/go/storage/copy.go:81: cannot use
res.ObjectSize (type int64) as type uint64 in argument to c.ProgressFunc
</code>```

Has this happened to anyone else? How did you resolve this issue? Thank you in advance!

答: Answering my own question here, but there was a commit that broke the install. I filed a Github issue and they seemed to have fixed it. https://github.com/GoogleCloudPlatform/golang-samples/issues/266</p>

Title: golang google storage copy error

Body:
I get an error when trying to install google cloud storage SDK for Golang.

go get -u cloud.google.com/go/storage

# cloud.google.com/go/storage
../../../../cloud.google.com/go/storage/copy.go:81: cannot use
res.TotalBytesRewritten (type int64) as type uint64 in argument to c.ProgressFunc
../../../../cloud.google.com/go/storage/copy.go:81: cannot use
res.ObjectSize (type int64) as type uint64 in argument to c.ProgressFunc

Has this happened to anyone else? How did you resolve this issue? Thank you in advance!


问:
To fault or not to fault
I'm having a discussion with a colleague about when to throw faults and when not to throw faults in a WCF service.

One opinion is, that we only throw faults when the service operation could not do its work due to some error; and something may be in an invalid state because of it. So, some examples:

ValidateMember(string name, string password, string country)
-> would throw a fault if the mandatory parameters are not passed, because the validation itself could not be executed;
-> would throw fault if some internal error occured, like database was down
-> would return a status contract in all other cases, that specifies the result of the validation (MemberValidated, WrongPassword, MemberNotKnown,...)

GetMember(int memberId)
-> would only throw fault if something is down, in all other cases it would return the member or null if not found

The other opinion is that we should also throw faults when GetMember does not find the member, or in the case of ValidateMember the password is wrong.

What do you think?

答:
My take on this...

There are three causes of failure:

The service code threw an exception, e.g. database error, logic error in your code. This is your fault.

The client code failed to use your service properly according to your documentation, e.g. it didn't set a required flag value, it failed to pass in an ID. This is the client software developer's fault.

The end user typed in something silly on screen, e.g. missing date of birth, negative salary. This is the end user's fault.

It's up to you how you choose to map actual fault contracts to each cause of failure. For example, we do this:

For causes 1 and 2, all the client code needs to know is that the service failed. We define a very simple "fatal error" fault contract that contains only a unique error ID. The full details of the error are logged on the server.

For cause 3, the end user needs to know exactly what he/she did wrong. We define a "validation errors" fault contract containing a collection of friendly error messages for the client code to display on screen.

We borrow the Microsoft EntLib class for cause 3, and use exception shielding to handle causes 1 and 2 declaratively. It makes for very simple code.

To Clarify:

We handle the three causes like this inside the service:

An unexpected exception is thrown in the service code. We catch it at the top level (actually exception shielding catches it, but the principle is the same). Log full details, then throw a FaultException<ServiceFault> to the client containing only the error ID.

We validate the input data and deliberately throw an exception. It's normally an ArgumentException, but any appropriate type would do. Once it is thrown, it is dealt with in exactly the same way as (1) because we want to make it appear the same to the client.

We validate the input data and deliberately throw an exception. This time, it's a FaultException<ValidationFault>. We configure exception shielding to pass this one through un-wrapped, so it appears on the client as FaultException<ValidationFault> not FaultException<ServiceFault>.

End result:

No catch blocks at all inside the service (nice clean code).

Client only has to catch FaultException<ValidationFault> if it wants to display messages to the user. All other exception types including FaultException<ServiceFault> are dealt with by the client's global error handler as fatal errors, since a fatal error in the service generally means a fatal error in the client as well.

Title: To fault or not to fault


答:
change foundID to this foundId = $(this);

JSFiddle

Title: Treating outerHTML as jQuery object


问:
Fallback Font Weights in CSS
My font stylesheets are hosted on Fonts.com and out of my control. On the stylesheet, different weights of Avenir are implemented as different font families, each with a weight of 400. If the weight is anything but the default normal (400), the font renders oddly. So how do I make my fallback fonts bold while keeping the primary font weight as normal?

I tried to accomplish this by using the font CSS shorthand, thinking I could define different weights for each comma-separated value, like so:

```<code>font:   normal 400 18px 'Avenir 85 Heavy',
        normal 800 18px 'Calbri',
        normal 800 18px sans-serif;
</code>```

But the browser doesn't recognize this structure, unfortunately, unless I eliminate all properties besides  on the fallbacks. Any suggestions, even inelegant ones?

答:
When using @font-face, you typically want to apply a different font variant (= different font file), depending on whether your font is (1) normal, (2) italic, (3) bold or (4) italic + bold.

If you use the same font-family name for each variant along with their corresponding font-style and font-weight in your @font-face definitions, the correct font file will automatically be chosen depending on the font-style and font-weight of your elements.

Do this for all fonts defined with @font-face, and behavior should be as expected.

Demo

@font-face {
  font-family : 'Droid Serif';
  font-style : normal;
  font-weight : 400;
  src: local('Droid Serif'),
       local('DroidSerif'),
       url(https://fonts.gstatic.com/s/droidserif/v6/0AKsP294HTD-nvJgucYTaI4P5ICox8Kq3LLUNMylGO4.woff2)
       format('woff2');
}

@font-face {
  font-family : 'Droid Serif';
  font-style : normal;
  font-weight : 700;
  src : local('Droid Serif Bold'),
        local('DroidSerif-Bold'),
        url(https://fonts.gstatic.com/s/droidserif/v6/QQt14e8dY39u-eYBZmppwYlIZu-HDpmDIZMigmsroc4.woff2)
        format('woff2');
}

@font-face {
  font-family : 'Droid Serif';
  font-style : italic;
  font-weight : 400;
  src : local('Droid Serif Italic'),
        local('DroidSerif-Italic'),
        url(https://fonts.gstatic.com/s/droidserif/v6/cj2hUnSRBhwmSPr9kS5898u2Q0OS-KeTAWjgkS85mDg.woff2)
        format('woff2');
}

@font-face {
  font-family : 'Droid Serif';
  font-style : italic;
  font-weight : 700;
  src : local('Droid Serif Bold Italic'),
        local('DroidSerif-BoldItalic'),
        url(https://fonts.gstatic.com/s/droidserif/v6/c92rD_x0V1LslSFt3-QEpo9ObOXPY1wUIXqKtDjSdsY.woff2)
        format('woff2');
}

body {
  font-family : "Droid Serif", Georgia, serif;
}

.bold, .both {
  font-weight : 700;
}

.italics, .both {
  font-style : italic;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Title</h1>
<p>This is a paragraph with <b>some bold text</b>, <em>some text in italics </em> and <em><b>some text that is both bold and in italics</b></em>!</p>
<p>Depending on whether your text is <span class="bold">bold</span >, <span class="italics">in italics</span > or <span class="both">both</span >, a different font will be used for the same font family!</p></code>```

Title: Fallback Font Weights in CSS

Body:
My font stylesheets are hosted on Fonts.com and out of my control. On the stylesheet, different weights of Avenir are implemented as different font families, each with a weight of 400. If the weight is anything but the default normal (400), the font renders oddly. So how do I make my fallback fonts bold while keeping the primary font weight as normal?

I tried to accomplish this by using the font CSS shorthand, thinking I could define different weights for each comma-separated value, like so:

font:   normal 400 18px 'Avenir 85 Heavy',
        normal 800 18px 'Calbri',
        normal 800 18px sans-serif;

But the browser doesn't recognize this structure, unfortunately, unless I eliminate all properties besides  on the fallbacks. Any suggestions, even inelegant ones?

Body:
When using @font-face, you typically want to apply a different font variant (= different font file), depending on whether your font is (1) normal, (2) italic, (3) bold or (4) italic + bold.

If you use the same font-family name for each variant along with their corresponding font-style and font-weight in your @font-face definitions, the correct font file will automatically be chosen depending on the font-style and font-weight of your elements.

Do this for all fonts defined with @font-face, and behavior should be as expected.

Demo

@font-face {
  font-family : 'Droid Serif';
  font-style : normal;
  font-weight : 400;
  src: local('Droid Serif'),
       local('DroidSerif'),
       url(https://fonts.gstatic.com/s/droidserif/v6/0AKsP294HTD-nvJgucYTaI4P5ICox8Kq3LLUNMylGO4.woff2)
       format('woff2');
}

@font-face {
  font-family : 'Droid Serif';
  font-style : normal;
  font-weight : 700;
  src : local('Droid Serif Bold'),
        local('DroidSerif-Bold'),
        url(https://fonts.gstatic.com/s/droidserif/v6/QQt14e8dY39u-eYBZmppwYlIZu-HDpmDIZMigmsroc4.woff2)
        format('woff2');
}

@font-face {
  font-family : 'Droid Serif';
  font-style : italic;
  font-weight : 400;
  src : local('Droid Serif Italic'),
        local('DroidSerif-Italic'),
        url(https://fonts.gstatic.com/s/droidserif/v6/cj2hUnSRBhwmSPr9kS5898u2Q0OS-KeTAWjgkS85mDg.woff2)
        format('woff2');
}

@font-face {
  font-family : 'Droid Serif';
  font-style : italic;
  font-weight : 700;
  src : local('Droid Serif Bold Italic'),
        local('DroidSerif-BoldItalic'),
        url(https://fonts.gstatic.com/s/droidserif/v6/c92rD_x0V1LslSFt3-QEpo9ObOXPY1wUIXqKtDjSdsY.woff2)
        format('woff2');
}

body {
  font-family : "Droid Serif", Georgia, serif;
}

.bold, .both {
  font-weight : 700;
}

.italics, .both {
  font-style : italic;
}

<h1>Title</h1>
<p>This is a paragraph with <b>some bold text</b>, <em>some text in italics </em> and <em><b>some text that is both bold and in italics</b></em>!</p>
<p>Depending on whether your text is <span class="bold">bold</span >, <span class="italics">in italics</span > or <span class="both">both</span >, a different font will be used for the same font family!</p>