问:
ckeditor pasting from google docs removes the styles
When I copy text from a google doc and paste it to the ckeditor using the paste from word button it removes all the styling (bold, italics, ...).

How can I fix that?

Steps to reproduce :

Copy one word from a google doc that is both underlined and italicized Paste it into editor.

Expected result :

The word is pasted in italicized and underlined.

Actual result:

The word is bolded, no underlines or italics to be found.

答:
I'm posting my solution in case it helps someone.
I had the same issue with pasting from googleDocs.
And I found someone made a branch of CKEditor in github (13877) which corrects this.

As I needed it to work with my version 4.5.6, I then adapted it into a plugin.
I have done this to work with Processwire which I cannont change the CKEditor version, and have only tested it in this context.

pasteFromGoogleDoc (folder)

plugin.js

content of plugin.js :

```<code>            /**
         * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
         * For licensing, see LICENSE.md or http://ckeditor.com/license

         * 2017-07-05
         * the code originally from Frederico Knabben, written in ckeditor-dev-t-13877 branch
         * (https://github.com/cksource/ckeditor-dev/tree/t/13877)
         * has been adapted in a plugin by Rpapier for use in Processwire. It hasn't been tested elsewhere.

         * DESCRIPTION
         * Filter to paste from Google Doc and keep style (bold, italic, underline)
         * Those style must be present in the toolbar for it to show, otherwise, it will bypass it

         * For processwire :
         * you must edit the field that has CKEditor and make sure that :
         *  - ACF is On
         *  - pasteFromGoogleDoc plugin is enabled
         *  - CKEditor toolbar configuration contains Bold, Italic and Underline
         *      - e.g : Format, Styles, -, Bold, Italic, Underline, -, RemoveFormat
         *      if Underline is not in the toolbar for example, it will be bypassed by the filter.
         */

        ( function() {
            'use strict';

            CKEDITOR.plugins.add( 'pasteFromGoogleDoc', {
                requires: ['clipboard'],

                init: function( editor ) {
                    // === arteractive hack for pasteFromGoogleDoc

                    var filterType,
                        filtersFactory = filtersFactoryFactory();

                    if ( editor.config.forcePasteAsPlainText ) {
                        filterType = 'plain-text';
                    } else if ( editor.config.pasteFilter ) {
                        filterType = editor.config.pasteFilter;
                    }
                    // On Webkit the pasteFilter defaults to 'webkit-default-filter' because pasted data is so terrible
                    // that it must be always filtered. (#13877)
                    else if ( CKEDITOR.env.webkit && !( 'pasteFilter' in editor.config ) ) {
                        filterType = 'webkit-default-filter';
                    }

                    //console.log(filterType);
                    editor.pasteFilter = filtersFactory.get( filterType );

                    editor.on( 'paste', function( evt ) {
                        // Init `dataTransfer` if `paste` event was fired without it, so it will be always available.
                        if ( !evt.data.dataTransfer ) {
                            evt.data.dataTransfer = new CKEDITOR.plugins.clipboard.dataTransfer();
                        }

                        // If dataValue is already set (manually or by paste bin), so do not override it.
                        if ( evt.data.dataValue ) {
                            return;
                        }

                        var dataTransfer = evt.data.dataTransfer,
                            // IE support only text data and throws exception if we try to get html data.
                            // This html data object may also be empty if we drag content of the textarea.
                            value = dataTransfer.getData( 'text/html' );

                        if ( value ) {
                            evt.data.dataValue = value;
                            evt.data.type = 'html';
                        } else {
                            // Try to get text data otherwise.
                            value = dataTransfer.getData( 'text/plain' );

                            if ( value ) {
                                evt.data.dataValue = editor.editable().transformPlainTextToHtml( value );
                                evt.data.type = 'text';
                            }
                        }
                    }, null, null, 1 );

                    editor.on( 'paste', function( evt ) {
                        var dataObj = evt.data,
                            type = dataObj.type,
                            data = dataObj.dataValue,
                            trueType,
                            // Default is 'html'.
                            defaultType = editor.config.clipboard_defaultContentType || 'html',
                            transferType = dataObj.dataTransfer.getTransferType( editor );

                        // If forced type is 'html' we don't need to know true data type.
                        if ( type == 'html' || dataObj.preSniffing == 'html' ) {
                            trueType = 'html';
                        } else {
                            trueType = recogniseContentType( data );
                        }

                        // Unify text markup.
                        if ( trueType == 'htmlifiedtext' ) {
                            data = htmlifiedTextHtmlification( editor.config, data );
                        }

                        // Strip presentational markup & unify text markup.
                        // Forced plain text (dialog or forcePAPT).
                        // Note: we do not check dontFilter option in this case, because forcePAPT was implemented
                        // before pasteFilter and pasteFilter is automatically used on Webkit&Blink since 4.5, so
                        // forcePAPT should have priority as it had before 4.5.
                        if ( type == 'text' && trueType == 'html' ) {
                            data = filterContent( editor, data, filtersFactory.get( 'plain-text' ) );
                        }
                        // External paste and pasteFilter exists and filtering isn't disabled.
                        else if ( transferType == CKEDITOR.DATA_TRANSFER_EXTERNAL && editor.pasteFilter && !dataObj.dontFilter ) {

                            // 2017-07-05 comment out this filter because it is already processsed somewhere...
                            //data = filterContent( editor, data, editor.pasteFilter );
                            //console.log(data);
                        }

                        if ( dataObj.startsWithEOL ) {
                            data = '<br data-cke-eol="1">' + data;
                        }
                        if ( dataObj.endsWithEOL ) {
                            data += '<br data-cke-eol="1">';
                        }

                        if ( type == 'auto' ) {
                            type = ( trueType == 'html' || defaultType == 'html' ) ? 'html' : 'text';
                        }

                        dataObj.type = type;
                        dataObj.dataValue = data;
                        delete dataObj.preSniffing;
                        delete dataObj.startsWithEOL;
                        delete dataObj.endsWithEOL;

                    /*  evt.data.dataValue = data;

                        evt.data.dataValue = evt.data.dataValue
                            .replace( /zooterkins/gi, 'z********s' )
                            .replace( /gadzooks/gi, 'g******s' );*/

                    }, null, null, 6 );

                }
            } );

            function filterContent( editor, data, filter ) {
                var fragment = CKEDITOR.htmlParser.fragment.fromHtml( data ),
                    writer = new CKEDITOR.htmlParser.basicWriter();

                filter.applyTo( fragment, true, false, editor.activeEnterMode );
                fragment.writeHtml( writer );

                return writer.getHtml();
            }

            // Returns:
            // * 'htmlifiedtext' if content looks like transformed by browser from plain text.
            //      See clipboard/paste.html TCs for more info.
            // * 'html' if it is not 'htmlifiedtext'.
            function recogniseContentType( data ) {
                if ( CKEDITOR.env.webkit ) {
                    // Plain text or ( <div><br></div> and text inside <div> ).
                    if ( !data.match( /^[^<]*$/g ) && !data.match( /^(<div><br( ?\/)?><\/div>|<div>[^<]*<\/div>)*$/gi ) )
                        return 'html';
                } else if ( CKEDITOR.env.ie ) {
                    // Text and <br> or ( text and <br> in <p> - paragraphs can be separated by new \r\n ).
                    if ( !data.match( /^([^<]|<br( ?\/)?>)*$/gi ) && !data.match( /^(<p>([^<]|<br( ?\/)?>)*<\/p>|(\r\n))*$/gi ) )
                        return 'html';
                } else if ( CKEDITOR.env.gecko ) {
                    // Text or <br>.
                    if ( !data.match( /^([^<]|<br( ?\/)?>)*$/gi ) )
                        return 'html';
                } else {
                    return 'html';
                }

                return 'htmlifiedtext';
            }

            // This function transforms what browsers produce when
            // pasting plain text into editable element (see clipboard/paste.html TCs
            // for more info) into correct HTML (similar to that produced by text2Html).
            function htmlifiedTextHtmlification( config, data ) {
                function repeatParagraphs( repeats ) {
                    // Repeat blocks floor((n+1)/2) times.
                    // Even number of repeats - add <br> at the beginning of last <p>.
                    return CKEDITOR.tools.repeat( '</p><p>', ~~( repeats / 2 ) ) + ( repeats % 2 == 1 ? '<br>' : '' );
                }

                    // Replace adjacent white-spaces (EOLs too - Fx sometimes keeps them) with one space.
                data = data.replace( /\s+/g, ' ' )
                    // Remove spaces from between tags.
                    .replace( /> +</g, '><' )
                    // Normalize XHTML syntax and upper cased <br> tags.
                    .replace( /<br ?\/>/gi, '<br>' );

                // IE - lower cased tags.
                data = data.replace( /<\/?[A-Z]+>/g, function( match ) {
                    return match.toLowerCase();
                } );

                // Don't touch single lines (no <br|p|div>) - nothing to do here.
                if ( data.match( /^[^<]$/ ) )
                    return data;

                // Webkit.
                if ( CKEDITOR.env.webkit && data.indexOf( '<div>' ) > -1 ) {
                        // One line break at the beginning - insert <br>
                    data = data.replace( /^(<div>(<br>|)<\/div>)(?!$|(<div>(<br>|)<\/div>))/g, '<br>' )
                        // Two or more - reduce number of new lines by one.
                        .replace( /^(<div>(<br>|)<\/div>){2}(?!$)/g, '<div></div>' );

                    // Two line breaks create one paragraph in Webkit.
                    if ( data.match( /<div>(<br>|)<\/div>/ ) ) {
                        data = '<p>' + data.replace( /(<div>(<br>|)<\/div>)+/g, function( match ) {
                            return repeatParagraphs( match.split( '</div><div>' ).length + 1 );
                        } ) + '</p>';
                    }

                    // One line break create br.
                    data = data.replace( /<\/div><div>/g, '<br>' );

                    // Remove remaining divs.
                    data = data.replace( /<\/?div>/g, '' );
                }

                // Opera and Firefox and enterMode != BR.
                if ( CKEDITOR.env.gecko && config.enterMode != CKEDITOR.ENTER_BR ) {
                    // Remove bogus <br> - Fx generates two <brs> for one line break.
                    // For two line breaks it still produces two <brs>, but it's better to ignore this case than the first one.
                    if ( CKEDITOR.env.gecko )
                        data = data.replace( /^<br><br>$/, '<br>' );

                    // This line satisfy edge case when for Opera we have two line breaks
                    //data = data.replace( /)

                    if ( data.indexOf( '<br><br>' ) > -1 ) {
                        // Two line breaks create one paragraph, three - 2, four - 3, etc.
                        data = '<p>' + data.replace( /(<br>){2,}/g, function( match ) {
                            return repeatParagraphs( match.length / 4 );
                        } ) + '</p>';
                    }
                }

                return switchEnterMode( config, data );
            }

            function filtersFactoryFactory() {
                var filters = {};

                // GDocs generates many spans and divs, therefore `all` parameter is used
                // to create default filter in Webkit/Blink. (#13877)
                function setUpTags( all ) {
                    var tags = {};

                    for ( var tag in CKEDITOR.dtd ) {
                        if ( tag.charAt( 0 ) != '$' && ( all || tag != 'div' && tag != 'span') ) {
                            tags[ tag ] = 1;
                        }
                    }

                    return tags;
                }

                // Checks if content is pasted from Google Docs.
                // Google Docs wraps everything in element with [id^=docs-internal-guid-],
                // so that function just checks if such element exists. (#13877)
                function isPastedFromGDocs( element ) {
                    if ( element.attributes.id && element.attributes.id.match( /^docs\-internal\-guid\-/ ) ) {
                        return true;
                    } else if ( element.parent && element.parent.name ) {
                        return isPastedFromGDocs( element.parent );
                    }

                    return false;
                }

                // Process data from Google Docs:
                // * turns `*[id^=docs-internal-guid-]` into `span`;
                // * turns `span(text-decoration=underline)` into `u`;
                // * turns `span(font-style=italic)` into `em`
                // * turns `span(font-style=italic)(text-decoration=underline)` into `u > em`. (#13877)
                //
                function processDataFromGDocs( element ) {

                    var styles = element.attributes.style && CKEDITOR.tools.parseCssText( element.attributes.style );

                    if ( element.attributes.id && element.attributes.id.match( /^docs\-internal\-guid\-/ ) ) {
                        return element.name = 'span';
                    }

                    if ( !styles ) {
                        return;
                    }

                    if ( styles[ 'font-style' ] == 'italic' && styles[ 'text-decoration' ] == 'underline' ) {
                        element.name = 'em';
                        element.wrapWith( new CKEDITOR.htmlParser.element( 'u' ) );
                        if (styles[ 'font-weight' ] > 400) {
                            element.wrapWith( new CKEDITOR.htmlParser.element( 'strong' ) );
                        }
                    } else if ( styles[ 'text-decoration' ] == 'underline' ) {
                        element.name = 'u';
                        if (styles[ 'font-weight' ] > 400) {
                            element.wrapWith( new CKEDITOR.htmlParser.element( 'strong' ) );
                        }
                    } else if ( styles[ 'font-style' ] == 'italic' ) {
                        element.name = 'em';
                        if (styles[ 'font-weight' ] > 400) {
                            element.wrapWith( new CKEDITOR.htmlParser.element( 'strong' ) );
                        }
                    }
                }

                function createSemanticContentFilter() {
                    var filter = new CKEDITOR.filter();

                    filter.allow( {
                        $1: {
                            elements: setUpTags(),
                            attributes: true,
                            styles: false,
                            classes: false
                        }
                    } );

                    return filter;
                }

                function createWebkitDefaultFilter() {
                    var filter = createSemanticContentFilter();

                    // Preserves formatting while pasting from Google Docs in Webkit/Blink
                    // with default paste filter. (#13877)
                    filter.allow( {
                        $2: {
                            elements: setUpTags( true ),
                            attributes: true,
                            styles: true,
                            match: function( element ) {
                                return isPastedFromGDocs( element );
                            }
                        }
                    } );

                    filter.addElementCallback( processDataFromGDocs );

                    return filter;
                }

                return {
                    get: function( type ) {
                        if ( type == 'plain-text' ) {
                            // Does this look confusing to you? Did we forget about enter mode?
                            // It is a trick that let's us creating one filter for edidtor, regardless of its
                            // activeEnterMode (which as the name indicates can change during runtime).
                            //
                            // How does it work?
                            // The active enter mode is passed to the filter.applyTo method.
                            // The filter first marks all elements except <br> as disallowed and then tries to remove
                            // them. However, it cannot remove e.g. a <p> element completely, because it's a basic structural element,
                            // so it tries to replace it with an element created based on the active enter mode, eventually doing nothing.
                            //
                            // Now you can sleep well.
                            return filters.plainText || ( filters.plainText = new CKEDITOR.filter( 'br' ) );
                        } else if ( type == 'semantic-content' ) {
                            return filters.semanticContent || ( filters.semanticContent = createSemanticContentFilter() );
                        } else if ( type == 'webkit-default-filter' ) {
                            // Webkit based browsers need semantic filter, because they produce terrible HTML without it.
                            // However original `'semantic-content'` filer is too strict and prevents pasting styled contents
                            // from many sources (e.g. Google Docs). Therefore that type extends original `'semantic-content'` filter. (#13877)
                            return filters.webkitDefaultFilter || ( filters.webkitDefaultFilter = createWebkitDefaultFilter() );
                        } else if ( type ) {
                            // Create filter based on rules (string or object).
                            return new CKEDITOR.filter( type );
                        }

                        return null;
                    }
                };
            }

            function switchEnterMode( config, data ) {
                if ( config.enterMode == CKEDITOR.ENTER_BR ) {
                    data = data.replace( /(<\/p><p>)+/g, function( match ) {
                        return CKEDITOR.tools.repeat( '<br>', match.length / 7 * 2 );
                    } ).replace( /<\/?p>/g, '' );
                } else if ( config.enterMode == CKEDITOR.ENTER_DIV ) {
                    data = data.replace( /<(\/)?p>/g, '<$1div>' );
                }

                return data;
            }

        } )();
</code>```

Body:
I'm posting my solution in case it helps someone.
I had the same issue with pasting from googleDocs.
And I found someone made a branch of CKEditor in github (13877) which corrects this.

As I needed it to work with my version 4.5.6, I then adapted it into a plugin.
I have done this to work with Processwire which I cannont change the CKEditor version, and have only tested it in this context.

pasteFromGoogleDoc (folder)

plugin.js

content of plugin.js :

            /**
         * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
         * For licensing, see LICENSE.md or http://ckeditor.com/license

         * 2017-07-05
         * the code originally from Frederico Knabben, written in ckeditor-dev-t-13877 branch
         * (https://github.com/cksource/ckeditor-dev/tree/t/13877)
         * has been adapted in a plugin by Rpapier for use in Processwire. It hasn't been tested elsewhere.

         * DESCRIPTION
         * Filter to paste from Google Doc and keep style (bold, italic, underline)
         * Those style must be present in the toolbar for it to show, otherwise, it will bypass it

         * For processwire :
         * you must edit the field that has CKEditor and make sure that :
         *  - ACF is On
         *  - pasteFromGoogleDoc plugin is enabled
         *  - CKEditor toolbar configuration contains Bold, Italic and Underline
         *      - e.g : Format, Styles, -, Bold, Italic, Underline, -, RemoveFormat
         *      if Underline is not in the toolbar for example, it will be bypassed by the filter.
         */

        ( function() {
            'use strict';

            CKEDITOR.plugins.add( 'pasteFromGoogleDoc', {
                requires: ['clipboard'],

                init: function( editor ) {
                    // === arteractive hack for pasteFromGoogleDoc

                    var filterType,
                        filtersFactory = filtersFactoryFactory();

                    if ( editor.config.forcePasteAsPlainText ) {
                        filterType = 'plain-text';
                    } else if ( editor.config.pasteFilter ) {
                        filterType = editor.config.pasteFilter;
                    }
                    // On Webkit the pasteFilter defaults to 'webkit-default-filter' because pasted data is so terrible
                    // that it must be always filtered. (#13877)
                    else if ( CKEDITOR.env.webkit && !( 'pasteFilter' in editor.config ) ) {
                        filterType = 'webkit-default-filter';
                    }

                    //console.log(filterType);
                    editor.pasteFilter = filtersFactory.get( filterType );

                    editor.on( 'paste', function( evt ) {
                        // Init `dataTransfer` if `paste` event was fired without it, so it will be always available.
                        if ( !evt.data.dataTransfer ) {
                            evt.data.dataTransfer = new CKEDITOR.plugins.clipboard.dataTransfer();
                        }

                        // If dataValue is already set (manually or by paste bin), so do not override it.
                        if ( evt.data.dataValue ) {
                            return;
                        }

                        var dataTransfer = evt.data.dataTransfer,
                            // IE support only text data and throws exception if we try to get html data.
                            // This html data object may also be empty if we drag content of the textarea.
                            value = dataTransfer.getData( 'text/html' );

                        if ( value ) {
                            evt.data.dataValue = value;
                            evt.data.type = 'html';
                        } else {
                            // Try to get text data otherwise.
                            value = dataTransfer.getData( 'text/plain' );

                            if ( value ) {
                                evt.data.dataValue = editor.editable().transformPlainTextToHtml( value );
                                evt.data.type = 'text';
                            }
                        }
                    }, null, null, 1 );

                    editor.on( 'paste', function( evt ) {
                        var dataObj = evt.data,
                            type = dataObj.type,
                            data = dataObj.dataValue,
                            trueType,
                            // Default is 'html'.
                            defaultType = editor.config.clipboard_defaultContentType || 'html',
                            transferType = dataObj.dataTransfer.getTransferType( editor );

                        // If forced type is 'html' we don't need to know true data type.
                        if ( type == 'html' || dataObj.preSniffing == 'html' ) {
                            trueType = 'html';
                        } else {
                            trueType = recogniseContentType( data );
                        }

                        // Unify text markup.
                        if ( trueType == 'htmlifiedtext' ) {
                            data = htmlifiedTextHtmlification( editor.config, data );
                        }

                        // Strip presentational markup & unify text markup.
                        // Forced plain text (dialog or forcePAPT).
                        // Note: we do not check dontFilter option in this case, because forcePAPT was implemented
                        // before pasteFilter and pasteFilter is automatically used on Webkit&Blink since 4.5, so
                        // forcePAPT should have priority as it had before 4.5.
                        if ( type == 'text' && trueType == 'html' ) {
                            data = filterContent( editor, data, filtersFactory.get( 'plain-text' ) );
                        }
                        // External paste and pasteFilter exists and filtering isn't disabled.
                        else if ( transferType == CKEDITOR.DATA_TRANSFER_EXTERNAL && editor.pasteFilter && !dataObj.dontFilter ) {

                            // 2017-07-05 comment out this filter because it is already processsed somewhere...
                            //data = filterContent( editor, data, editor.pasteFilter );
                            //console.log(data);
                        }

                        if ( dataObj.startsWithEOL ) {
                            data = '<br data-cke-eol="1">' + data;
                        }
                        if ( dataObj.endsWithEOL ) {
                            data += '<br data-cke-eol="1">';
                        }

                        if ( type == 'auto' ) {
                            type = ( trueType == 'html' || defaultType == 'html' ) ? 'html' : 'text';
                        }

                        dataObj.type = type;
                        dataObj.dataValue = data;
                        delete dataObj.preSniffing;
                        delete dataObj.startsWithEOL;
                        delete dataObj.endsWithEOL;

                    /*  evt.data.dataValue = data;

                        evt.data.dataValue = evt.data.dataValue
                            .replace( /zooterkins/gi, 'z********s' )
                            .replace( /gadzooks/gi, 'g******s' );*/

                    }, null, null, 6 );

                }
            } );

            function filterContent( editor, data, filter ) {
                var fragment = CKEDITOR.htmlParser.fragment.fromHtml( data ),
                    writer = new CKEDITOR.htmlParser.basicWriter();

                filter.applyTo( fragment, true, false, editor.activeEnterMode );
                fragment.writeHtml( writer );

                return writer.getHtml();
            }

            // Returns:
            // * 'htmlifiedtext' if content looks like transformed by browser from plain text.
            //      See clipboard/paste.html TCs for more info.
            // * 'html' if it is not 'htmlifiedtext'.
            function recogniseContentType( data ) {
                if ( CKEDITOR.env.webkit ) {
                    // Plain text or ( <div><br></div> and text inside <div> ).
                    if ( !data.match( /^[^<]*$/g ) && !data.match( /^(<div><br( ?\/)?><\/div>|<div>[^<]*<\/div>)*$/gi ) )
                        return 'html';
                } else if ( CKEDITOR.env.ie ) {
                    // Text and <br> or ( text and <br> in <p> - paragraphs can be separated by new \r\n ).
                    if ( !data.match( /^([^<]|<br( ?\/)?>)*$/gi ) && !data.match( /^(<p>([^<]|<br( ?\/)?>)*<\/p>|(\r\n))*$/gi ) )
                        return 'html';
                } else if ( CKEDITOR.env.gecko ) {
                    // Text or <br>.
                    if ( !data.match( /^([^<]|<br( ?\/)?>)*$/gi ) )
                        return 'html';
                } else {
                    return 'html';
                }

                return 'htmlifiedtext';
            }

            // This function transforms what browsers produce when
            // pasting plain text into editable element (see clipboard/paste.html TCs
            // for more info) into correct HTML (similar to that produced by text2Html).
            function htmlifiedTextHtmlification( config, data ) {
                function repeatParagraphs( repeats ) {
                    // Repeat blocks floor((n+1)/2) times.
                    // Even number of repeats - add <br> at the beginning of last <p>.
                    return CKEDITOR.tools.repeat( '</p><p>', ~~( repeats / 2 ) ) + ( repeats % 2 == 1 ? '<br>' : '' );
                }

                    // Replace adjacent white-spaces (EOLs too - Fx sometimes keeps them) with one space.
                data = data.replace( /\s+/g, ' ' )
                    // Remove spaces from between tags.
                    .replace( /> +</g, '><' )
                    // Normalize XHTML syntax and upper cased <br> tags.
                    .replace( /<br ?\/>/gi, '<br>' );

                // IE - lower cased tags.
                data = data.replace( /<\/?[A-Z]+>/g, function( match ) {
                    return match.toLowerCase();
                } );

                // Don't touch single lines (no <br|p|div>) - nothing to do here.
                if ( data.match( /^[^<]$/ ) )
                    return data;

                // Webkit.
                if ( CKEDITOR.env.webkit && data.indexOf( '<div>' ) > -1 ) {
                        // One line break at the beginning - insert <br>
                    data = data.replace( /^(<div>(<br>|)<\/div>)(?!$|(<div>(<br>|)<\/div>))/g, '<br>' )
                        // Two or more - reduce number of new lines by one.
                        .replace( /^(<div>(<br>|)<\/div>){2}(?!$)/g, '<div></div>' );

                    // Two line breaks create one paragraph in Webkit.
                    if ( data.match( /<div>(<br>|)<\/div>/ ) ) {
                        data = '<p>' + data.replace( /(<div>(<br>|)<\/div>)+/g, function( match ) {
                            return repeatParagraphs( match.split( '</div><div>' ).length + 1 );
                        } ) + '</p>';
                    }

                    // One line break create br.
                    data = data.replace( /<\/div><div>/g, '<br>' );

                    // Remove remaining divs.
                    data = data.replace( /<\/?div>/g, '' );
                }

                // Opera and Firefox and enterMode != BR.
                if ( CKEDITOR.env.gecko && config.enterMode != CKEDITOR.ENTER_BR ) {
                    // Remove bogus <br> - Fx generates two <brs> for one line break.
                    // For two line breaks it still produces two <brs>, but it's better to ignore this case than the first one.
                    if ( CKEDITOR.env.gecko )
                        data = data.replace( /^<br><br>$/, '<br>' );

                    // This line satisfy edge case when for Opera we have two line breaks
                    //data = data.replace( /)

                    if ( data.indexOf( '<br><br>' ) > -1 ) {
                        // Two line breaks create one paragraph, three - 2, four - 3, etc.
                        data = '<p>' + data.replace( /(<br>){2,}/g, function( match ) {
                            return repeatParagraphs( match.length / 4 );
                        } ) + '</p>';
                    }
                }

                return switchEnterMode( config, data );
            }

            function filtersFactoryFactory() {
                var filters = {};

                // GDocs generates many spans and divs, therefore `all` parameter is used
                // to create default filter in Webkit/Blink. (#13877)
                function setUpTags( all ) {
                    var tags = {};

                    for ( var tag in CKEDITOR.dtd ) {
                        if ( tag.charAt( 0 ) != '$' && ( all || tag != 'div' && tag != 'span') ) {
                            tags[ tag ] = 1;
                        }
                    }

                    return tags;
                }

                // Checks if content is pasted from Google Docs.
                // Google Docs wraps everything in element with [id^=docs-internal-guid-],
                // so that function just checks if such element exists. (#13877)
                function isPastedFromGDocs( element ) {
                    if ( element.attributes.id && element.attributes.id.match( /^docs\-internal\-guid\-/ ) ) {
                        return true;
                    } else if ( element.parent && element.parent.name ) {
                        return isPastedFromGDocs( element.parent );
                    }

                    return false;
                }

                // Process data from Google Docs:
                // * turns `*[id^=docs-internal-guid-]` into `span`;
                // * turns `span(text-decoration=underline)` into `u`;
                // * turns `span(font-style=italic)` into `em`
                // * turns `span(font-style=italic)(text-decoration=underline)` into `u > em`. (#13877)
                //
                function processDataFromGDocs( element ) {

                    var styles = element.attributes.style && CKEDITOR.tools.parseCssText( element.attributes.style );

                    if ( element.attributes.id && element.attributes.id.match( /^docs\-internal\-guid\-/ ) ) {
                        return element.name = 'span';
                    }

                    if ( !styles ) {
                        return;
                    }

                    if ( styles[ 'font-style' ] == 'italic' && styles[ 'text-decoration' ] == 'underline' ) {
                        element.name = 'em';
                        element.wrapWith( new CKEDITOR.htmlParser.element( 'u' ) );
                        if (styles[ 'font-weight' ] > 400) {
                            element.wrapWith( new CKEDITOR.htmlParser.element( 'strong' ) );
                        }
                    } else if ( styles[ 'text-decoration' ] == 'underline' ) {
                        element.name = 'u';
                        if (styles[ 'font-weight' ] > 400) {
                            element.wrapWith( new CKEDITOR.htmlParser.element( 'strong' ) );
                        }
                    } else if ( styles[ 'font-style' ] == 'italic' ) {
                        element.name = 'em';
                        if (styles[ 'font-weight' ] > 400) {
                            element.wrapWith( new CKEDITOR.htmlParser.element( 'strong' ) );
                        }
                    }
                }

                function createSemanticContentFilter() {
                    var filter = new CKEDITOR.filter();

                    filter.allow( {
                        $1: {
                            elements: setUpTags(),
                            attributes: true,
                            styles: false,
                            classes: false
                        }
                    } );

                    return filter;
                }

                function createWebkitDefaultFilter() {
                    var filter = createSemanticContentFilter();

                    // Preserves formatting while pasting from Google Docs in Webkit/Blink
                    // with default paste filter. (#13877)
                    filter.allow( {
                        $2: {
                            elements: setUpTags( true ),
                            attributes: true,
                            styles: true,
                            match: function( element ) {
                                return isPastedFromGDocs( element );
                            }
                        }
                    } );

                    filter.addElementCallback( processDataFromGDocs );

                    return filter;
                }

                return {
                    get: function( type ) {
                        if ( type == 'plain-text' ) {
                            // Does this look confusing to you? Did we forget about enter mode?
                            // It is a trick that let's us creating one filter for edidtor, regardless of its
                            // activeEnterMode (which as the name indicates can change during runtime).
                            //
                            // How does it work?
                            // The active enter mode is passed to the filter.applyTo method.
                            // The filter first marks all elements except <br> as disallowed and then tries to remove
                            // them. However, it cannot remove e.g. a <p> element completely, because it's a basic structural element,
                            // so it tries to replace it with an element created based on the active enter mode, eventually doing nothing.
                            //
                            // Now you can sleep well.
                            return filters.plainText || ( filters.plainText = new CKEDITOR.filter( 'br' ) );
                        } else if ( type == 'semantic-content' ) {
                            return filters.semanticContent || ( filters.semanticContent = createSemanticContentFilter() );
                        } else if ( type == 'webkit-default-filter' ) {
                            // Webkit based browsers need semantic filter, because they produce terrible HTML without it.
                            // However original `'semantic-content'` filer is too strict and prevents pasting styled contents
                            // from many sources (e.g. Google Docs). Therefore that type extends original `'semantic-content'` filter. (#13877)
                            return filters.webkitDefaultFilter || ( filters.webkitDefaultFilter = createWebkitDefaultFilter() );
                        } else if ( type ) {
                            // Create filter based on rules (string or object).
                            return new CKEDITOR.filter( type );
                        }

                        return null;
                    }
                };
            }

            function switchEnterMode( config, data ) {
                if ( config.enterMode == CKEDITOR.ENTER_BR ) {
                    data = data.replace( /(<\/p><p>)+/g, function( match ) {
                        return CKEDITOR.tools.repeat( '<br>', match.length / 7 * 2 );
                    } ).replace( /<\/?p>/g, '' );
                } else if ( config.enterMode == CKEDITOR.ENTER_DIV ) {
                    data = data.replace( /<(\/)?p>/g, '<$1div>' );
                }

                return data;
            }

        } )();


来源: stackexchange

问:
The run destination [user's] iPhone is not valid for Running the scheme
After successfully running apps, so many times on my iPhone, I am getting this error again and again. Any solution?

答: Scheme > Manage schemes > Autocreate schemes  may resove your problem

ContentLicense: CC BY-SA 3.0


问:
Why ButterKnife uses a DebouncingOnClickListener for @OnClick methods?
I was looking at the generated code of ButterKnife, and noticed that for @OnClick annotations it is using a DebouncingOnClickListener, implemented by the library.

What the DebouncingOnClickListener does it to avoid more than one click on any element using that listener on the same frame (to achieve this they use a static flag). You can see the implementation here.

I have tried to find an explanation on why they decided to use this for every on click event managed by the library, but could not find any.

So, why they use that?
Why have they decided that every user of ButterKnife need this?
Shouldn't be the user who decides to use that or not?
Why couple the view binding help it provides with this "feature"?
What happens if I want to receive more than one click on the same frame? I couldn't use ButterKnife for click events.

I don't pretend to be offensive, just want an explanation, maybe I am missing something.

答:
Long story short, it's to prevent a bug from happening since touch events are async. You can also use the library for binding still but assign regular on click listeners.

This podcast episode covers it pretty well
Fragmented 088


问:
CKeditor custom builder "hasFocus" error
I am trying to make a custom build of CKeditor. I am taking the full editor, removing some plugins and adding placeholder.
When putting it in my page I get:

```<code> ckeditor.js:731 Uncaught TypeError: Cannot read property 'hasFocus' of undefined
  at $.showBlock (ckeditor.js:731)
  at Object.execute (ckeditor.js:799)
  at $.<anonymous> (ckeditor.js:799)
  at ckeditor.js:31
  at Object.callFunction (ckeditor.js:31)
</code>```

My config file is empty - to make sure I am not adding errors.
I call the editor with:

```<code>CKEDITOR.replace( 'etiq_template', {});
</code>```

Of course, If I use the prebuilt full editor, it perfectly works, even when in my config I put:

```<code>config.removeButtons = 'Save,Form,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,HiddenField,Flash,Smiley,Iframe,Image';
</code>```

Any idea of what I am doing wrong ? I really would like to have the placeholder widget - but if I can't I will program something less fancy to replace it.

thanks for any idea and pointer

答:
I have it working now. I am not sure why, but this is what I did.
First I change browser to Chrome - I was using Safari and Firefox.

Second (and maybe this is the most important) I started from the standard editor and added the plugins I wanted, instead of starting from full editor and removing plugins.

It now works perfectly

Body:
I am trying to make a custom build of CKeditor. I am taking the full editor, removing some plugins and adding placeholder.
When putting it in my page I get:

 ckeditor.js:731 Uncaught TypeError: Cannot read property 'hasFocus' of undefined
  at $.showBlock (ckeditor.js:731)
  at Object.execute (ckeditor.js:799)
  at $.<anonymous> (ckeditor.js:799)
  at ckeditor.js:31
  at Object.callFunction (ckeditor.js:31)

My config file is empty - to make sure I am not adding errors.
I call the editor with:

CKEDITOR.replace( 'etiq_template', {});

Of course, If I use the prebuilt full editor, it perfectly works, even when in my config I put:

config.removeButtons = 'Save,Form,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,HiddenField,Flash,Smiley,Iframe,Image';

Any idea of what I am doing wrong ? I really would like to have the placeholder widget - but if I can't I will program something less fancy to replace it.

thanks for any idea and pointer


问:
I can not display the data from my json_encode ($.each)
Hello to every one and thank you for your time.
My problem is that i can not display the json_encode from my php database but in my chrome the data is appear.
The $.each is not dispaly all only one
enter image description here

now the code for the php :

comment.php

```<code>$data = $_REQUEST;
$photo_id =38;//$data['photo_id_comment'];
$con = mysqli_connect('localhost','root','','gallery');

$sql  = "SELECT * FROM comments";
$sql .= " WHERE photo_id = " . $database->escape_string($photo_id);
$sql .= " ORDER  BY photo_id ASC";

$result = mysqli_query( $con,$sql);

$arr = array();
$row_count = mysqli_num_rows($result);

while ($row = mysqli_fetch_array($result)) {
    array_push($arr , $row);
}

mysqli_close($con);
echo json_encode($arr);
</code>```

And the ajax to retrieve data is: script.js

```<code>function refreshComment() {

requestData = $("#photo_id_comment").serialize();
$.ajax({
    url: "http://localhost/udemy/app_php/includes/comment.php",
    type: "get",
    data: requestData,
    dataType: "text",
    success : function (data) {
        jQuery.each(data, function(index, item) {
            //now you can access properties using dot notation
            $('#chat_box').val( $('#chat_box').val() + item.body + '\n');
            /* $('#author_comment').html(item.author);
            $('#chat_box').html(item.body);*/
        });
    },
    error: function (http, status, error) {
        alert('Some error occurred :'+error);
    }
});

    return false;
}

setInterval( refreshComment , 5000 );
</code>```

And the html where the data is not display is: photo.php.

```<code> <div class="media">
                <a class="pull-left" href="#">
                    <img class="media-object" src="http://placehold.it/64x64" alt="">

                </a>
                <div class="media-body">
                    <h4 id="author_comment"  class="media-heading"></h4>
                    <p id="chat_box"></p>
                    <p class="text-info">This is post at: </p>
                </div>
            </div>
</code>```

答:
in your script.js file make change on success function of ajax:-     </p>

```<code> success : function (data) {
    $.each($.parseJSON(data), function(key,item){
           $('#chat_box').val( $('#chat_box').val() + item.body + '\n');
      });
  }
</code>```

Body:
Hello to every one and thank you for your time.
My problem is that i can not display the json_encode from my php database but in my chrome the data is appear.
The $.each is not dispaly all only one
enter image description here

now the code for the php :

comment.php

$data = $_REQUEST;
$photo_id =38;//$data['photo_id_comment'];
$con = mysqli_connect('localhost','root','','gallery');

$sql  = "SELECT * FROM comments";
$sql .= " WHERE photo_id = " . $database->escape_string($photo_id);
$sql .= " ORDER  BY photo_id ASC";

$result = mysqli_query( $con,$sql);

$arr = array();
$row_count = mysqli_num_rows($result);

while ($row = mysqli_fetch_array($result)) {
    array_push($arr , $row);
}

mysqli_close($con);
echo json_encode($arr);

And the ajax to retrieve data is: script.js

function refreshComment() {

requestData = $("#photo_id_comment").serialize();
$.ajax({
    url: "http://localhost/udemy/app_php/includes/comment.php",
    type: "get",
    data: requestData,
    dataType: "text",
    success : function (data) {
        jQuery.each(data, function(index, item) {
            //now you can access properties using dot notation
            $('#chat_box').val( $('#chat_box').val() + item.body + '\n');
            /* $('#author_comment').html(item.author);
            $('#chat_box').html(item.body);*/
        });
    },
    error: function (http, status, error) {
        alert('Some error occurred :'+error);
    }
});

    return false;
}

setInterval( refreshComment , 5000 );

And the html where the data is not display is: photo.php.

This is post at:

Body:
in your script.js file make change on success function of ajax:-

 success : function (data) {
    $.each($.parseJSON(data), function(key,item){
           $('#chat_box').val( $('#chat_box').val() + item.body + '\n');
      });
  }


问:
remove a instance from memory after doing "add" into a list
the code is very simple:

```<code>  myKpi = "a";
  Data.add(myKpi);
</code>```

and then I want to remove myKpi from memory because it has been saved in the list Data.

I have read that I can do sth like myKpi=null, but I don´t know if it will afect the value of Data.

答:
How about

```<code>Data.remove(myKpi);
</code>```

What type of List do you use?

Body:
the code is very simple:

  myKpi = "a";
  Data.add(myKpi);

and then I want to remove myKpi from memory because it has been saved in the list Data.

I have read that I can do sth like myKpi=null, but I don´t know if it will afect the value of Data.

Body:
How about

Data.remove(myKpi);

What type of List do you use?


问:
Angularjs limit to directive
I'm trying to make a filter be used as a directive in Angularjs 1.4

What I want to make is to limit string using limitTo filter but as a directive not (|) filter.

I made this but it's not working

charlimit.js directive

```<code>function controller($scope) {
    $scope.length = 15;
}

angular.module('xApp')
  .directive('charlimit', function () {
    return {
      restrict: 'A',
      scope: {
        limitTo: '@',
      },
      controller: ["$scope", controller]
    };
});
</code>```

index.html

```<code><p charlimit="5"></p>
</code>```

Do you have any thoughts?

Thanks.

答:
var app = angular.module("xApp", []);

app.directive('charLimit', function() {
  return {
    restrict: "A",
    link: function(scope, element, attrs) {
      var limitLength = parseInt(attrs.charLimit);
      scope.limittext = scope.limittext.substring(0, limitLength);
      return scope.limittext;
    }
  }
});

app.controller("IndexController", function($scope) {
$scope.limittext = 'Sample text';
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="xApp" ng-controller="IndexController">
  <p char-limit="5">{{limittext}}</p>
</body></code>```

Title: Angularjs limit to directive

Body:
I'm trying to make a filter be used as a directive in Angularjs 1.4

What I want to make is to limit string using limitTo filter but as a directive not (|) filter.

I made this but it's not working

charlimit.js directive

function controller($scope) {
    $scope.length = 15;
}

angular.module('xApp')
  .directive('charlimit', function () {
    return {
      restrict: 'A',
      scope: {
        limitTo: '@',
      },
      controller: ["$scope", controller]
    };
});

index.html

Do you have any thoughts?

Thanks.

Body:
var app = angular.module("xApp", []);

app.directive('charLimit', function() {
  return {
    restrict: "A",
    link: function(scope, element, attrs) {
      var limitLength = parseInt(attrs.charLimit);
      scope.limittext = scope.limittext.substring(0, limitLength);
      return scope.limittext;
    }
  }
});

app.controller("IndexController", function($scope) {
$scope.limittext = 'Sample text';
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="xApp" ng-controller="IndexController">
  <p char-limit="5">{{limittext}}</p>
</body>


问:
profiling a method of a class in Python using cProfile?
I'd like to profile a method of a function in Python, using cProfile. I tried the following:

```<code>import cProfile as profile

# Inside the class method...
profile.run("self.myMethod()", "output_file")
</code>```

But it does not work. How can I call a self.method with "run"?

答:
EDIT: Sorry, didn't realise that the profile call was in a class method.

run just tries to exec the string you pass it. If self isn't bound to anything in the scope of the profiler you are using, you can't use it in run! Use the runctx method to pass in the local and global variables in the scope of the call to the profiler:

```<code>>>> import time
>>> import cProfile as profile
>>> class Foo(object):
...     def bar(self):
...             profile.runctx('self.baz()', globals(), locals())
...
...     def baz(self):
...             time.sleep(1)
...             print 'slept'
...             time.sleep(2)
...
>>> foo = Foo()
>>> foo.bar()
slept
         5 function calls in 2.999 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    2.999    2.999 <stdin>:5(baz)
        1    0.000    0.000    2.999    2.999 <string>:1(<module>)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        2    2.999    1.499    2.999    1.499 {time.sleep}
</code>```

Notice the last line: time.sleep is what's taking up the time.

ContentLicense: CC BY-SA 4.0

Body:
I'd like to profile a method of a function in Python, using cProfile. I tried the following:

import cProfile as profile

# Inside the class method...
profile.run("self.myMethod()", "output_file")

But it does not work. How can I call a self.method with "run"?

Body:
EDIT: Sorry, didn't realise that the profile call was in a class method.

run just tries to exec the string you pass it. If self isn't bound to anything in the scope of the profiler you are using, you can't use it in run! Use the runctx method to pass in the local and global variables in the scope of the call to the profiler:

>>> import time
>>> import cProfile as profile
>>> class Foo(object):
...     def bar(self):
...             profile.runctx('self.baz()', globals(), locals())
...
...     def baz(self):
...             time.sleep(1)
...             print 'slept'
...             time.sleep(2)
...
>>> foo = Foo()
>>> foo.bar()
slept
         5 function calls in 2.999 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    2.999    2.999 <stdin>:5(baz)
        1    0.000    0.000    2.999    2.999 <string>:1(<module>)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        2    2.999    1.499    2.999    1.499 {time.sleep}

Notice the last line: time.sleep is what's taking up the time.

ContentLicense: CC BY-SA 2.5


问:
Parse User log out does not work
I am using Parse 1.9.0 for Android and I need to log out user on button click, so I call:

```<code>ParseUser.logOut();
</code>```

After that I need to open login screen and click on Facebook login button, and to check if user have saved custom custom field.

But, it seems that ParseUser.getCurrentUser() after log out is not null.

How I can remove current user from cache?

答:
Don't know what you want to do! But you can check at the onCreate method if the Current User is an Anonymous user and thus prevent it to auto-load Anonymous userData from the cache:

```<code>if (ParseAnonymousUtils.isLinked(ParseUser.getCurrentUser())) {
    //This is a Logged out Anonymous user
} else {
    //Getting Current User who is not logged off
    ParseUser currentUser = ParseUser.getCurrentUser();
    if (currentUser != null) {
        //Do your staff
    }
}
</code>```

Title: Parse User log out does not work

Body:
I am using Parse 1.9.0 for Android and I need to log out user on button click, so I call:

ParseUser.logOut();

After that I need to open login screen and click on Facebook login button, and to check if user have saved custom custom field.

But, it seems that ParseUser.getCurrentUser() after log out is not null.

How I can remove current user from cache?

Body:
Don't know what you want to do! But you can check at the onCreate method if the Current User is an Anonymous user and thus prevent it to auto-load Anonymous userData from the cache:

if (ParseAnonymousUtils.isLinked(ParseUser.getCurrentUser())) {
    //This is a Logged out Anonymous user
} else {
    //Getting Current User who is not logged off
    ParseUser currentUser = ParseUser.getCurrentUser();
    if (currentUser != null) {
        //Do your staff
    }
}


问:
What is the best way to ingest data from Terdata into Hadoop with Informatica?
What is the best ways to parallel ingest data from Teradata database into Hadoop with parallel data moving?

If we create a job which is simple opens one session to Teradata database it will take a lot of time to load huge table.

if we create a set of sessions to load data in parallel, and also make Select in each of the sessions, than it will make a set of Full table scans Teradata to produce a data

What is the recommended best practice to load data in parallelised streams and make unnecessary workload to Teradata?

答: If you use partition names in the select clause, Power Center will select only the rows within that partition so there won't be duplicate read (don't forget to choose Database partitioning in Informatica session level). However if you use key range partition you have to choose the range as you mentioned in settings. Usually we use NTILE oracle analytical function to split the table into multiple portions so that the read will be unique across the selects. Please let me know if you have any question. If you have range/auto generated/surrogate key column in the table use it in where clause - write a sub-query to divide the table into multiple portions.</p>


问:
Image has extra space at the top
I have an image on my website and there is about 50px of extra white space at the top. I have tried padding none and margin none, display block but none of them work. Here is a working jsfiddle of it.
Here's my HTML

     h1 {
     font-size: 100px;
     color: white;
     text-align: center;
     opacity: none;
     font-family: 'Noto Sans', sans-serif;
      }

    p {
    font-family: 'Roboto Condensed', sans-serif;
    font-size: 70px;
    color: black;
    text-align: center;
    }

      .rotate {
       float: left;
      -webkit-transform: rotate(180deg) 2s;
      transform: rotate(180deg) 2s;
      transition: all 2s ease;
      transition-delay: 0.4s;
        }

      .rotate:hover {
          -webkit-transform: rotateZ(-360deg);
          -ms-transform: rotateZ(-360deg);
          transform: rotateZ(-360deg);
         }

    .container {
    overflow: hidden;
    font-family: 'Roboto Condensed', sans-serif;
    position: static;
    z-index: 150;
     margin-bottom: -80px;
      }

    .container a {
    float: right;
    font-size: 20px;
    color: black;
    text-align: center;
    padding: 40px 70px;
    text-decoration: none;
        transition: background 1s;
       }

    .dropdown {
    float: right;
    overflow: hidden;
     }

    .dropdown .dropbtn {
    font-size: 20px;
    border: none;
    outline: white;
    color: black;
    padding: 40px 70px;
    background-color: inherit;
    font-family: 'Roboto Condensed', sans-serif;
        transition: background 1s;
      }

       .container a:hover, .dropdown:hover .dropbtn {
    background-color: lightgreen;
        }

     .dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
    border-right: 1px solid #bbb;
     }

    .dropdown-content a {
    float: none;
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
    font-size: 18px;
      }

    .dropdown-content a:hover {
    background-color: #ddd;
    border-right: 1px solid #bbb;
     }

    .dropdown:hover .dropdown-content {
    display: block;
         }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>     <body>
      <div class="active">
      <div id="background">
     <div class="opacity">
     <div class="container">
     <div class="rotate">
     <img class="chiz" src="kkk.png" alt="Vortex Games">
    </div>
       Home
       About
      FAQ
       Games
       <div class="dropdown">
      <button class="dropbtn"
       onclick="window.location.href='store.html'">Store</button>
      <div class="dropdown-content">
        Powerups
        Coins
      </div>
      </div>
       </div>
      </div>
       <p class="title">
       We're a top-of-the-line high tech <br>game company
      <br>
      <span style="color:white;font-size:20px;padding:none;display:inline-
       block;">
      <span style="color:red;font-size:100px;padding-top:none;">
      –<br></span>Driven by passion. Always at our best.</span>
    </p>
     <!--the background div-->
      </div>

      <div class="creative">
     <img src="cree.jpg" align="abstop">
      </div>
CSS</code>```

Any help would be appreciated.

Thanks

答:
It occurs because of some browser preset margin on the p element. You can remove it with this:</p>

```<code>p.title {
    margin-bottom: 0px;
}
</code>```

Title: Image has extra space at the top

Body:
I have an image on my website and there is about 50px of extra white space at the top. I have tried padding none and margin none, display block but none of them work. Here is a working jsfiddle of it.
Here's my HTML

     h1 {
     font-size: 100px;
     color: white;
     text-align: center;
     opacity: none;
     font-family: 'Noto Sans', sans-serif;
      }

    p {
    font-family: 'Roboto Condensed', sans-serif;
    font-size: 70px;
    color: black;
    text-align: center;
    }

      .rotate {
       float: left;
      -webkit-transform: rotate(180deg) 2s;
      transform: rotate(180deg) 2s;
      transition: all 2s ease;
      transition-delay: 0.4s;
        }

      .rotate:hover {
          -webkit-transform: rotateZ(-360deg);
          -ms-transform: rotateZ(-360deg);
          transform: rotateZ(-360deg);
         }

    .container {
    overflow: hidden;
    font-family: 'Roboto Condensed', sans-serif;
    position: static;
    z-index: 150;
     margin-bottom: -80px;
      }

    .container a {
    float: right;
    font-size: 20px;
    color: black;
    text-align: center;
    padding: 40px 70px;
    text-decoration: none;
        transition: background 1s;
       }

    .dropdown {
    float: right;
    overflow: hidden;
     }

    .dropdown .dropbtn {
    font-size: 20px;
    border: none;
    outline: white;
    color: black;
    padding: 40px 70px;
    background-color: inherit;
    font-family: 'Roboto Condensed', sans-serif;
        transition: background 1s;
      }

       .container a:hover, .dropdown:hover .dropbtn {
    background-color: lightgreen;
        }

     .dropdown-content {
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
    border-right: 1px solid #bbb;
     }

    .dropdown-content a {
    float: none;
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
    font-size: 18px;
      }

    .dropdown-content a:hover {
    background-color: #ddd;
    border-right: 1px solid #bbb;
     }

    .dropdown:hover .dropdown-content {
    display: block;
         }

       Home
       About
      FAQ
       Games

      <button class="dropbtn"
       onclick="window.location.href='store.html'">Store</button>

        Powerups
        Coins

       We're a top-of-the-line high tech
game company

      –
Driven by passion. Always at our best.

CSS

Any help would be appreciated.

Thanks

Body:
It occurs because of some browser preset margin on the p element. You can remove it with this:

p.title {
    margin-bottom: 0px;
}


问:
Populating HTML table rows with objects containing an array using Vue
I'm trying to populate rows in an HTML table using the Vue framework - the data is as seen below:

```<code>TeamRows: [
            { team: 'One', times: ['1', '2', '3'] },
            { team: 'Two', times: ['4', '5', '6'] },
            { team: 'Three', times: ['7', '8', '9'] }
          ]
</code>```

I've tried following this codepen, but with bad result - this is my HTML:

```<code><tbody>
   <tr v-for="(row, rindex) in teamRows">
      <td>{{rindex}}</td>
         <template>
            <cell v-for="(value, vindex) in row" :value="value" :vindex="vindex" :rindex="rindex"></cell>
         </template>
   </tr>
</tbody>
</table>
<template id="template-cell">
   <td>{{ value }}</td>
</template>
</code>```

And this is the Vue component:

```<code>Vue.component('cell', {
    template: '#template-cell',
    name: 'row-value',
    props: ['value', 'vindex', 'rindex']
});
</code>```

I would like the team to go in the first column in a row and the times to follow along in as many columns as there are times. Hope someone with more Vue knowledge is able to help me out here. Cheers.

答:
Turns out the reason is you're using in-DOM template and browser moves unknown cell element above the v-for, and Vue can't access row value anymore: https://v2.vuejs.org/v2/guide/components.html#DOM-Template-Parsing-Caveats

A solution without cell component, just with inline cell elements, works fine. Also, template wrapper is not needed in a table template:

new Vue({
  el: '#app',
  data: {
    teamRows: [
      { team: 'One', times: ['1', '2', '3'] },
      { team: 'Two', times: ['4', '5', '6'] },
      { team: 'Three', times: ['7', '8', '9'] }
    ]
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <table>
    <tbody>
     <tr v-for="row in teamRows" :key="row.team">
       <td>{{ row.team }}</td>
       <td v-for="time in row.times">{{ time }}</td>
     </tr>
    </tbody>
  </table>
</div></code>```

Also, as a result of a discussion, you can still use a component if you wrap your table into another component for example, so that browser don't interfere and Vue has a chance to render everything properly:

new Vue({
  el: '#app',
  data: {
    teamRows: [
      { team: 'One', times: ['1', '2', '3'] },
      { team: 'Two', times: ['4', '5', '6'] },
      { team: 'Three', times: ['7', '8', '9'] }
    ]
  },
  components: {
    'mytable': {
      template: `

       {{ row.team }}
       <cell v-for="time in row.times" :value="time" :key="time"></cell>

`,
      props: ['rows'],
      components: {
        'cell': {
          template: `<td>{{ value }}</td>`,
          props: ['value'],
        }
      }
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <mytable :rows="teamRows"></mytable>
</div></code>```

Body:
I'm trying to populate rows in an HTML table using the Vue framework - the data is as seen below:

TeamRows: [
            { team: 'One', times: ['1', '2', '3'] },
            { team: 'Two', times: ['4', '5', '6'] },
            { team: 'Three', times: ['7', '8', '9'] }
          ]

I've tried following this codepen, but with bad result - this is my HTML:

      {{rindex}}
         <template>
            <cell v-for="(value, vindex) in row" :value="value" :vindex="vindex" :rindex="rindex"></cell>
         </template>

<template id="template-cell">
   {{ value }}
</template>

And this is the Vue component:

Vue.component('cell', {
    template: '#template-cell',
    name: 'row-value',
    props: ['value', 'vindex', 'rindex']
});

I would like the team to go in the first column in a row and the times to follow along in as many columns as there are times. Hope someone with more Vue knowledge is able to help me out here. Cheers.

Body:
Turns out the reason is you're using in-DOM template and browser moves unknown cell element above the v-for, and Vue can't access row value anymore: https://v2.vuejs.org/v2/guide/components.html#DOM-Template-Parsing-Caveats

A solution without cell component, just with inline cell elements, works fine. Also, template wrapper is not needed in a table template:

new Vue({
  el: '#app',
  data: {
    teamRows: [
      { team: 'One', times: ['1', '2', '3'] },
      { team: 'Two', times: ['4', '5', '6'] },
      { team: 'Three', times: ['7', '8', '9'] }
    ]
  }
});

<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <table>
    <tbody>
     <tr v-for="row in teamRows" :key="row.team">
       <td>{{ row.team }}</td>
       <td v-for="time in row.times">{{ time }}</td>
     </tr>
    </tbody>
  </table>
</div>

Also, as a result of a discussion, you can still use a component if you wrap your table into another component for example, so that browser don't interfere and Vue has a chance to render everything properly:

new Vue({
  el: '#app',
  data: {
    teamRows: [
      { team: 'One', times: ['1', '2', '3'] },
      { team: 'Two', times: ['4', '5', '6'] },
      { team: 'Three', times: ['7', '8', '9'] }
    ]
  },
  components: {
    'mytable': {
      template: `<table>
    <tbody>
     <tr v-for="row in rows" :key="row.team">
       <td>{{ row.team }}</td>
       <cell v-for="time in row.times" :value="time" :key="time"></cell>
     </tr>
    </tbody>
  </table>`,
      props: ['rows'],
      components: {
        'cell': {
          template: `<td>{{ value }}</td>`,
          props: ['value'],
        }
      }
    }
  }
});

<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <mytable :rows="teamRows"></mytable>
</div>


问:
Compressed representation of polygons
I have a lot of (millions) of polygons from openstreetmap-data with mostly (more than 99%) exactly four coordinates representing houses.

Example

I currently save the four coordinates for each house explicitly as Tuple of floats (Latitude and Longitude), hence taking 32 bytes of memory.

Is there a way to store this information in a compressed way (fewer than 32 byte) since the four coordinates only differ very few in the last decimals?

答:
If your map patch is not too large, you can store relative coordinates against some base point (for example, bottom left corner). Get these differences, norm them by map size like this:

```<code>   uint16_diff  = (uint16) 65535 * (lat - latbottom) / (lattop - latbottom)
</code>```

This approach allows to store 16-bit integer values.

For rectangles (you can store them in separate list) there is a way to store 5 16-bit values instead of 8 values - coordinates of left top corner, width, height, and angle of rotation (there might be another sets of data, for example, including the second corner)

Combining both these methods, one might get data size loss upto 3.2 times

Title: Compressed representation of polygons

Body:
If your map patch is not too large, you can store relative coordinates against some base point (for example, bottom left corner). Get these differences, norm them by map size like this:

   uint16_diff  = (uint16) 65535 * (lat - latbottom) / (lattop - latbottom)

This approach allows to store 16-bit integer values.

For rectangles (you can store them in separate list) there is a way to store 5 16-bit values instead of 8 values - coordinates of left top corner, width, height, and angle of rotation (there might be another sets of data, for example, including the second corner)

Combining both these methods, one might get data size loss upto 3.2 times


问:
How to set videoView in Dialog android
How to set videoView in Dialog with fragment.

and I try is not work ( no show video )

```<code>    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    final AlertDialog dialog = builder.create();
    final VideoView video_player_view = (VideoView)dialog.findViewById(R.id.videos);
    LayoutInflater inflater = ((HomeActivity)context).getLayoutInflater();
    View dialogLayout = inflater.inflate(R.layout.fragment_fong, null);

    dialog.setView(dialogLayout);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.show();

    WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
    RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.copyFrom(dialog.getWindow().getAttributes());
    dialog.getWindow().setAttributes(lp);

    Uri uri = Uri.parse("http://file2.video9.in/english/movie/2014/x-men-_days_of_future_past/X-Men-%20Days%20of%20Future%20Past%20Trailer%20-%20[Webmusic.IN].3gp");
    video_player_view.setVideoURI(uri);
    video_player_view.start();
</code>```

and fragment_fong.xml (videoView)

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <VideoView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/videos" />
</RelativeLayout>
</code>```

How to set it, thanks for you help

答:
Video is not playing</p>

```<code> LayoutInflater inflater = ((HomeActivity) context).getLayoutInflater();
        View dialogLayout = inflater.inflate(R.layout.fragment_fong, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(context);

        final AlertDialog dialog = builder.create();
        dialog.setView(dialogLayout);
        dialog.show();
       // dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        final VideoView video_player_view = (VideoView) dialog.findViewById(R.id.videos);

        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        lp.copyFrom(dialog.getWindow().getAttributes());
        dialog.getWindow().setAttributes(lp);

        Uri uri = Uri.parse("http://file2.video9.in/english/movie/2014/x-men-_days_of_future_past/X-Men-%20Days%20of%20Future%20Past%20Trailer%20-%20[Webmusic.IN].3gp");
        video_player_view.setVideoURI(uri);
        video_player_view.start();
</code>```

Title: How to set videoView in Dialog android

Body:
How to set videoView in Dialog with fragment.

and I try is not work ( no show video )

    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    final AlertDialog dialog = builder.create();
    final VideoView video_player_view = (VideoView)dialog.findViewById(R.id.videos);
    LayoutInflater inflater = ((HomeActivity)context).getLayoutInflater();
    View dialogLayout = inflater.inflate(R.layout.fragment_fong, null);

    dialog.setView(dialogLayout);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.show();

    WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
    RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.copyFrom(dialog.getWindow().getAttributes());
    dialog.getWindow().setAttributes(lp);

    Uri uri = Uri.parse("http://file2.video9.in/english/movie/2014/x-men-_days_of_future_past/X-Men-%20Days%20of%20Future%20Past%20Trailer%20-%20[Webmusic.IN].3gp");
    video_player_view.setVideoURI(uri);
    video_player_view.start();

and fragment_fong.xml (videoView)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <VideoView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/videos" />
</RelativeLayout>

How to set it, thanks for you help

Body:
Video is not playing

 LayoutInflater inflater = ((HomeActivity) context).getLayoutInflater();
        View dialogLayout = inflater.inflate(R.layout.fragment_fong, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(context);

        final AlertDialog dialog = builder.create();
        dialog.setView(dialogLayout);
        dialog.show();
       // dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        final VideoView video_player_view = (VideoView) dialog.findViewById(R.id.videos);

        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        lp.copyFrom(dialog.getWindow().getAttributes());
        dialog.getWindow().setAttributes(lp);

        Uri uri = Uri.parse("http://file2.video9.in/english/movie/2014/x-men-_days_of_future_past/X-Men-%20Days%20of%20Future%20Past%20Trailer%20-%20[Webmusic.IN].3gp");
        video_player_view.setVideoURI(uri);
        video_player_view.start();


问:
How to create a web page with the link like page.example.com
I am creating a website in 000webhost. If I purchase a domain ( for example www.example.com ), the index.html page opens when the user types the address in the URL bar. I want a specific page (for example page.html) to open when the user types page.example.com . How do I do that?</p>

答:
Sorry, example.com domain is taken so u can't create sub domain like page.example.com.

suppose if example.com domain is yours, you can able to create a sub domain page.example.com using cpanel.

You registered your domain, signed up for a free 000webhost.com account, activated your account and am now trying to setup a subdomain for your blog like for example blog.yourdomain.com. Setting up the subdomain is a piece of cake really, all you need to do is to login to your 000webhost.com control panel, then click the Subdomains link and enter a name for your subdomain. The 000webhost.com servers will do the rest and create the necessary entires and directory on the server.
check Attachment


问:
Async calls with new keyword 'await'
I've used async methods today, calling methods asynchronously and using the caller's callback methods.

Recently, I can across this post which talks about the new way to do this using the new await keyword. Other than saving few lines of code, what are the main advantages of this new model?

Does it offer a built in solution for when you make two different async calls but want the control to return to only one of the caller's callback, after both have completed?

What does CTP (Community Technical Preview) mean? Is this new keyword available in next version of C# and VB.NET?

答:
I would say that "saving a few lines of code" is an understatement. The await keyword lets the compiler generate the all the necessary wiring to allow you to write an asynchronous method that looks pretty much like a regular synchronous method.

The current paradigm of using callbacks has a number of limitations, such as in inability to use certain language constructs, complex error handling and so forth. All this complexity is effectively hidden by the compiler generated code.

The Async CTP ships with a couple of Word documents, that go in to far more detail. If you haven't looked at them already, I recommend you do so. The "Asynchrony in .NET.docx" document has a very elaborate example, that shows the extend of the compiler generated code.

Title: Async calls with new keyword 'await'


问:
A Pythonic way to read CSV with row and column headers
Let's have a CSV table with row and column headers, e.g.:

, "Car", "Bike", "Boat", "Plane", "Shuttle"
"Red", 1, 7, 3, 0, 0
"Green", 5, 0, 0, 0, 0
"Blue", 1, 1, 4, 0, 1
```

<p>I want to get row and column headers, i.e.:</p>

```col_headers = ["Car", "Bike", "Boat", "Plane", "Shuttle"]
row_headers = ["Red", "Green", "Blue"]
data = [[1, 7, 3, 0, 0],
        [5, 0, 0, 0, 0],
        [1, 1, 4, 0, 1]]
```

<p>Of course I can do something like</p>

<pre class="lang-py prettyprint-override"><code>import csv
with open("path/to/file.csv", "r") as f:
    csvraw = list(csv.reader(f))
col_headers = csvraw[1][1:]
row_headers = [row[0] for row in csvraw[1:]]
data = [row[1:] for row in csvraw[1:]]
</code>```

...but it does not look Pythonic enough.

Is there a neater way for this natural operation?

答:
Agree, pandas is the best I found too. I'm interested into read specific values of my dataframe. Here is what I did:

```<code>import pandas as pd
d=pd.read_csv(pathToFile+"easyEx.csv")
print(d)
print(d.index.values)
print(d.index.values[2])
print(d.columns.values)
print(d.columns.values[2])
print(pd.DataFrame(d,index=['Blue'],columns=['Boat'])+0.333)
</code>```

And this is what it returns:

```<code>         Car  Bike  Boat  Plane  Shuttle
Red      1     7     3      0        0
Green    5     0     0      0        0
Blue     1     1     4      0        1
['Red' 'Green' 'Blue']
Blue
['Car' 'Bike' 'Boat' 'Plane' 'Shuttle']
Boat
      Boat
Blue     4.333
</code>```

Note that I can check row names with 'index' and column names with 'columns'. Also note that I can read a specific element of the 'dataframe' base on its row and column names, and that the values are still numeric, that why I added '+0.333' in the last print.

I chaged the data file, I removed the quote chars (" ") and spaces after commas in the first row. Here you have 'easyEx.csv' file:

```<code>Car,Bike,Boat,Plane,Shuttle
Red, 1, 7, 3, 0, 0
Green, 5, 0, 0, 0, 0
Blue, 1, 1, 4, 0, 1
</code>```

Hope this can help =)

Body:
Let's have a CSV table with row and column headers, e.g.:

, "Car", "Bike", "Boat", "Plane", "Shuttle"
"Red", 1, 7, 3, 0, 0
"Green", 5, 0, 0, 0, 0
"Blue", 1, 1, 4, 0, 1

I want to get row and column headers, i.e.:

col_headers = ["Car", "Bike", "Boat", "Plane", "Shuttle"]
row_headers = ["Red", "Green", "Blue"]
data = [[1, 7, 3, 0, 0],
        [5, 0, 0, 0, 0],
        [1, 1, 4, 0, 1]]

Of course I can do something like

import csv
with open("path/to/file.csv", "r") as f:
    csvraw = list(csv.reader(f))
col_headers = csvraw[1][1:]
row_headers = [row[0] for row in csvraw[1:]]
data = [row[1:] for row in csvraw[1:]]

...but it does not look Pythonic enough.

Is there a neater way for this natural operation?

Body:
Agree, pandas is the best I found too. I'm interested into read specific values of my dataframe. Here is what I did:

import pandas as pd
d=pd.read_csv(pathToFile+"easyEx.csv")
print(d)
print(d.index.values)
print(d.index.values[2])
print(d.columns.values)
print(d.columns.values[2])
print(pd.DataFrame(d,index=['Blue'],columns=['Boat'])+0.333)

And this is what it returns:

         Car  Bike  Boat  Plane  Shuttle
Red      1     7     3      0        0
Green    5     0     0      0        0
Blue     1     1     4      0        1
['Red' 'Green' 'Blue']
Blue
['Car' 'Bike' 'Boat' 'Plane' 'Shuttle']
Boat
      Boat
Blue     4.333

Note that I can check row names with 'index' and column names with 'columns'. Also note that I can read a specific element of the 'dataframe' base on its row and column names, and that the values are still numeric, that why I added '+0.333' in the last print.

I chaged the data file, I removed the quote chars (" ") and spaces after commas in the first row. Here you have 'easyEx.csv' file:

Car,Bike,Boat,Plane,Shuttle
Red, 1, 7, 3, 0, 0
Green, 5, 0, 0, 0, 0
Blue, 1, 1, 4, 0, 1

Hope this can help =)


问:
Java 8 Hijrah Date Error when Day of Month is 30
I have been getting an error when using Hijrah date

the error is:

```<code>Invalid Hijrah day of month: 30
</code>```

the code is:

```<code>String date = 13820630;
        HijrahDate hDate= HijrahChronology.INSTANCE.date(Integer.valueOf(date.substring(0, 4)),Integer.valueOf(date.substring(4, 6)), Integer.valueOf(date.substring(6, 8)));
</code>```

Any ideas?

Thanks

答:
According to the HijrahDate class, the month 1372-06 has only 29 days.

```<code>HijrahDate date = HijrahChronology.INSTANCE.date(1382, 6, 1);
System.out.println(date.lengthOfMonth());
</code>```

This code prints 29.

The comments for HijrahChronology say

The Hijrah calendar has several variants based on differences in when the new moon is determined to have occurred and where the observation is made. In some variants the length of each month is computed algorithmically from the astronomical data for the moon and earth and in others the length of the month is determined by an authorized sighting of the new moon. For the algorithmically based calendars the calendar can project into the future. For sighting based calendars only historical data from past sightings is available.

So it is possible that the variant used by this chronology may differ from what you are expecting.

Other variants may be available via Chronology.getAvailableChronologies()

Body:
I have been getting an error when using Hijrah date

the error is:

Invalid Hijrah day of month: 30

the code is:

String date = 13820630;
        HijrahDate hDate= HijrahChronology.INSTANCE.date(Integer.valueOf(date.substring(0, 4)),Integer.valueOf(date.substring(4, 6)), Integer.valueOf(date.substring(6, 8)));

Any ideas?

Thanks

Body:
According to the HijrahDate class, the month 1372-06 has only 29 days.

HijrahDate date = HijrahChronology.INSTANCE.date(1382, 6, 1);
System.out.println(date.lengthOfMonth());

This code prints 29.

The comments for HijrahChronology say

The Hijrah calendar has several variants based on differences in when the new moon is determined to have occurred and where the observation is made. In some variants the length of each month is computed algorithmically from the astronomical data for the moon and earth and in others the length of the month is determined by an authorized sighting of the new moon. For the algorithmically based calendars the calendar can project into the future. For sighting based calendars only historical data from past sightings is available.

So it is possible that the variant used by this chronology may differ from what you are expecting.

Other variants may be available via Chronology.getAvailableChronologies()


问:
Guid.NewGuid(); behind the scenes in .NET Core
Researching the subject yesterday, I found several interesting questions (such as this one) on how GUIDs are ultimately generated. In brief; it seems that Guid.NewGuid(); calls CoCreateGuid in the COM, which in turn calls UuidCreate in the Windows RPC (docs here and here).

I found myself wondering; How does this work when the OS is not Windows, such as might be the case with .NET Core, and does this affect the 'version' algorithm used to generate the GUID (which I understand is Version 4 on Windows)?

答:
On non-windows machines, .NET Core will use either uuid_create on BSD (which is "version 1") or libuuid's uuid_generate_random function on macOS and linux ("version 4").

The implementation for the replacement CoCreateGuid function can be found in CoreCLR's source code on GitHub.


问:
Python inheritance structure
Python 3.6

I just found myself programming this type of inheritance structure (below). Where a sub class is calling methods and attributes of an object a parent has.

In my use case I'm placing code in class A that would otherwise be ugly in class B.

Almost like a reverse inheritance call or something, which doesn't seem like a good idea... (Pycharm doesn't seem to like it)

Can someone please explain what is best practice in this scenario?

Thanks!

```<code>class A(object):

    def call_class_c_method(self):
        self.class_c.do_something(self)

class B(A):

    def __init__(self, class_c):
        self.class_c = class_c
        self.begin_task()

    def begin_task(self):
        self.call_class_c_method()

class C(object):

    def do_something(self):
        print("I'm doing something super() useful")

a = A
c = C
b = B(c)
</code>```

outputs:

```<code>I'm doing something super() useful
</code>```

答:
I find that reducing things to  abstract letters in cases like this makes it harder for me to reason about whether  the interaction makes sense.
In effect, you're asking whether it is reasonable for a class(A)  to depend on a member that conforms to a given interface (C).  The answer is that there are cases where it clearly does.
As an example, consider the model-view-controller pattern in web application design.
You might well have something like

```<code>class Controller:

    def get(self, request)
        return self.view.render(self, request)
</code>```

or similar.  Then elsewhere you'd have some code that found the view and populated self.view in the controller.  Typical examples of doing that include some routing lookups or include having a specific view associated with a controller.  While not Python, the Rails web framework does a lot of this.

When we have specific examples, it's a lot easier to reason about whether the abstractions make sense.

In the above example, the controller interface depends on having access to some instance of the view interface to do its work.  The controller instance encapsulates an instance that implements that view interface.

Here are some things to consider when evaluating such designs:

Can you clearly articulate the boundaries of each interface/class?  That is, can you explain what the controller's job is and what the view's job is?

Does your decision to encapsulate an instance agree with those scopes?

Do the interface and class scopes seem reasonable when you think about future extensibility and about minimizing the scope of code changes?

Title: Python inheritance structure

Body:
Python 3.6

I just found myself programming this type of inheritance structure (below). Where a sub class is calling methods and attributes of an object a parent has.

In my use case I'm placing code in class A that would otherwise be ugly in class B.

Almost like a reverse inheritance call or something, which doesn't seem like a good idea... (Pycharm doesn't seem to like it)

Can someone please explain what is best practice in this scenario?

Thanks!

class A(object):

    def call_class_c_method(self):
        self.class_c.do_something(self)

class B(A):

    def __init__(self, class_c):
        self.class_c = class_c
        self.begin_task()

    def begin_task(self):
        self.call_class_c_method()

class C(object):

    def do_something(self):
        print("I'm doing something super() useful")

a = A
c = C
b = B(c)

outputs:

I'm doing something super() useful

Body:
I find that reducing things to  abstract letters in cases like this makes it harder for me to reason about whether  the interaction makes sense.
In effect, you're asking whether it is reasonable for a class(A)  to depend on a member that conforms to a given interface (C).  The answer is that there are cases where it clearly does.
As an example, consider the model-view-controller pattern in web application design.
You might well have something like

class Controller:

    def get(self, request)
        return self.view.render(self, request)

or similar.  Then elsewhere you'd have some code that found the view and populated self.view in the controller.  Typical examples of doing that include some routing lookups or include having a specific view associated with a controller.  While not Python, the Rails web framework does a lot of this.

When we have specific examples, it's a lot easier to reason about whether the abstractions make sense.

In the above example, the controller interface depends on having access to some instance of the view interface to do its work.  The controller instance encapsulates an instance that implements that view interface.

Here are some things to consider when evaluating such designs:

Can you clearly articulate the boundaries of each interface/class?  That is, can you explain what the controller's job is and what the view's job is?

Does your decision to encapsulate an instance agree with those scopes?

Do the interface and class scopes seem reasonable when you think about future extensibility and about minimizing the scope of code changes?


问:
.NET library for PostegreSQL notify/listen
Is there any .NET library which can be used to listen to the notifications coming from PostgreSQL?

Npgsql has removed this support.

答: Npgsql definitely hasn't removed support for LISTEN/NOTIFY (although the API has changed somewhat over recent versions): http://www.npgsql.org/doc/wait.html</p>


问:
print 1 to 5 and even and odd in HTML and JavaScript
I have to create a html page which satisfy below requirement-
1. print 1 to 5 with another array
2. take number input from textbox then print on page whether it is Even or Odd.

I have create a page but it is not working as desired.

```<code>    <HTML>
    <HEAD>
    </HEAD>
    <BODY>
        <p id="demo"></p>
        <input type="number" id="myNumber">
        <button onclick="oddOrEven()">Try it</button>
        <input type="text" name="result" id="result" readonly="true"/>
            <SCRIPT>
            var numbers = [1,2,3,4,5];
            var myObjects = ["One","Two","Three","Four","Five"];
            var text = "";
            var myObjectsList =""
            var i;
            for (i = 0; i < numbers.length; i++) {
                text += numbers[i] + " : " + myObjects[i] + "<br>";
            }
            document.getElementById("demo").innerHTML = text;

            function oddOrEven() {
            var value = document.getElementById("myNumber").value;
            var res = if((value % 2) == 0) {"Even"} else {"Odd"}*/
            //if(value % 2 == 0) document.write("Even")
            //document.write(value);
            //document.getElementById("demo").innerHTML = res;
            readonly.value=res;
            }
            //document.write("Hello World!");

        </SCRIPT>

    </BODY>
    </HTML>
</code>```

Could someone please help me with the code.

答:
please see the updated solution

            var numbers = [1,2,3,4,5];
            var myObjects = ["One","Two","Three","Four","Five"];
            var text = "";
            var myObjectsList =""
            var i;
            for (i = 0; i < numbers.length; i++) {
                text += numbers[i] + " : " + myObjects[i] + "
";
            }
            document.getElementById("demo").innerHTML = text;

            function oddOrEven() {
            var value = document.getElementById("myNumber").value;
            var res = value % 2 == 0 ? "Even" : "Odd";
            document.getElementById("result").value=res;
            }
            //document.write("Hello World!");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="demo"></p>
        <input type="number" id="myNumber">
        <button onclick="oddOrEven()">Try it</button>
        <input type="text" name="result" id="result" readonly/></code>```

Updated code

var numbers = [1,2,3,4,5];
var myObjects = ["One","Two","Three","Four","Five"];
var text = "";
var myObjectsList =""
var i;
for (i = 0; i < numbers.length; i++) {
    text += numbers[i] + " : " + myObjects[i] + "
";
}
document.getElementById("demo").innerHTML = text;

function oddOrEven() {
var value = document.getElementById("myNumber").value;
var res = value % 2 == 0 ? "Even" : "Odd";
document.getElementById("result").innerHTML=res;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="demo"></p>
<input type="number" id="myNumber">
<button onclick="oddOrEven()">Try it</button>
<p id="result"></p></code>```

Update2
Replace

```<code><p id="result"></p>
</code>```

with

```<code><span id="result"></span>
</code>```

Body:
I have to create a html page which satisfy below requirement-
1. print 1 to 5 with another array
2. take number input from textbox then print on page whether it is Even or Odd.

I have create a page but it is not working as desired.

        <input type="number" id="myNumber">
        <button onclick="oddOrEven()">Try it</button>
        <input type="text" name="result" id="result" readonly="true"/>

Could someone please help me with the code.

Body:
please see the updated solution

            var numbers = [1,2,3,4,5];
            var myObjects = ["One","Two","Three","Four","Five"];
            var text = "";
            var myObjectsList =""
            var i;
            for (i = 0; i < numbers.length; i++) {
                text += numbers[i] + " : " + myObjects[i] + "<br>";
            }
            document.getElementById("demo").innerHTML = text;

            function oddOrEven() {
            var value = document.getElementById("myNumber").value;
            var res = value % 2 == 0 ? "Even" : "Odd";
            document.getElementById("result").value=res;
            }
            //document.write("Hello World!");

<p id="demo"></p>
        <input type="number" id="myNumber">
        <button onclick="oddOrEven()">Try it</button>
        <input type="text" name="result" id="result" readonly/>

Updated code

var numbers = [1,2,3,4,5];
var myObjects = ["One","Two","Three","Four","Five"];
var text = "";
var myObjectsList =""
var i;
for (i = 0; i < numbers.length; i++) {
    text += numbers[i] + " : " + myObjects[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;

function oddOrEven() {
var value = document.getElementById("myNumber").value;
var res = value % 2 == 0 ? "Even" : "Odd";
document.getElementById("result").innerHTML=res;
}

<p id="demo"></p>
<input type="number" id="myNumber">
<button onclick="oddOrEven()">Try it</button>
<p id="result"></p>

Update2
Replace

<p id="result"></p>

with

<span id="result"></span>