问:
React.js Firebase and Firepad Component
I am trying to spin up the Firepad Editor inside of my React Component, but I am encountering an error. Here is my Component:

```<code>import React, { Component } from 'react';
import * as firebase from 'firebase';
import CodeMirror from 'codemirror';
import Firepad from 'firepad';

export default class FirePadEditor extends Component {
  constructor() {
    super();
    firebase.initializeApp({
      apiKey: "AIzaSyCDre_vyeiK1a0qA8XSecI4elbF3hlobjc",
      authDomain: "firepad-test-d4679.firebaseapp.com",
      databaseURL: "https://firepad-test-d4679.firebaseio.com",
      projectId: "firepad-test-d4679",
      storageBucket: "firepad-test-d4679.appspot.com",
      messagingSenderId: "585682717429"
    });
  }

  componentDidMount() {
    var firepadRef = firebase.database().ref();
    var codeMirror = CodeMirror(document.getElementById('firepad'), { lineWrapping: true });
    var firepad = Firepad.fromCodeMirror(firepadRef, codeMirror, {
            richTextShortcuts: true,
            richTextToolbar: true,
            defaultText: 'Hello, World!'
          });
  }

    render() {
    return (
      <div>
        <div>testing</div>
        <div id='firepad'></div>
      </div>
  )
  }
}
</code>```

My Firebase credentials are correct and I am seeing the 'testing' text on my screen.

When I run on localhost, I encounter this error:

```<code>Uncaught TypeError: p is not a constructor
    at new c (bundle.js:30211)
    at Function.c (bundle.js:30211)
    at FirePadEditor.componentDidMount (bundle.js:19892)
    at CallbackQueue.notifyAll (bundle.js:6516)
    at ReactReconcileTransaction.close (bundle.js:16274)
    at ReactReconcileTransaction.closeAll (bundle.js:6877)
    at ReactReconcileTransaction.perform (bundle.js:6824)
    at batchedMountComponentIntoNode (bundle.js:2724)
    at ReactDefaultBatchingStrategyTransaction.perform (bundle.js:6811)
    at Object.batchedUpdates (bundle.js:10848)
</code>```

What I am seeing on my Node Console:

```<code>WARNING in ./~/firepad/dist/firepad.min.js
Critical dependencies:
14:3292-3299 require function is used in a way in which dependencies cannot be statically extracted
 @ ./~/firepad/dist/firepad.min.js 14:3292-3299

WARNING in ./~/firepad/dist/firepad.css
Module parse failed: /Users/Air/Desktop/firepad/firepad/node_modules/firepad/dist/firepad.css Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (1:0)
    at Parser.pp$4.raise (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:2221:15)
    at Parser.pp.unexpected (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:603:10)
    at Parser.pp$3.parseExprAtom (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1822:12)
    at Parser.pp$3.parseExprSubscripts (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1715:21)
    at Parser.pp$3.parseMaybeUnary (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1692:19)
    at Parser.pp$3.parseExprOps (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1637:21)
    at Parser.pp$3.parseMaybeConditional (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1620:21)
    at Parser.pp$3.parseMaybeAssign (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1597:21)
    at Parser.pp$3.parseExpression (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1573:21)
    at Parser.pp$1.parseStatement (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:727:47)
 @ ./~/firepad/dist ^\.\/.*$

WARNING in ./~/firepad/dist/firepad.eot
Module parse failed: /Users/Air/Desktop/firepad/firepad/node_modules/firepad/dist/firepad.eot Unexpected character '' (1:1)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected character '' (1:1)
    at Parser.pp$4.raise (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:2221:15)
    at Parser.pp$7.getTokenFromCode (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:2756:10)
    at Parser.pp$7.readToken (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:2477:17)
    at Parser.pp$7.nextToken (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:2468:15)
    at Parser.pp$7.next (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:2413:10)
    at Parser.pp$3.parseLiteral (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1830:10)
    at Parser.pp$3.parseExprAtom (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1786:19)
    at Parser.pp$3.parseExprSubscripts (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1715:21)
    at Parser.pp$3.parseMaybeUnary (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1692:19)
    at Parser.pp$3.parseExprOps (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1637:21)
    at Parser.pp$3.parseMaybeConditional (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1620:21)
    at Parser.pp$3.parseMaybeAssign (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1597:21)
 @ ./~/firepad/dist ^\.\/.*$

WARNING in ./~/firepad/dist/firepad.js
Critical dependencies:
2463:61-68 require function is used in a way in which dependencies cannot be statically extracted
 @ ./~/firepad/dist/firepad.js 2463:61-68
webpack: Compiled with warnings.
</code>```

Any ideas on how to solve this problem?

答:
Use these npm packages - brace, react-ace, firebase, firepad.

Since firepad needs aceto be present globally, assign brace to global var
like(not the best way, but works) before importing firepad

```<code>import firebase from 'firebase/app';
import 'firebase/database';
import brace from 'brace';
global.ace = brace;
global.ace.require = global.ace.acequire;
import Firepad from 'firepad';
</code>```

Use ref to get instance of ReactAce and initialize it in componentDidMount using:

```<code>new Firepad.fromACE(this.firepadRef, this.aceInstance.editor, options);
</code>```

Similarly for CodeMirror editor.

Title: React.js Firebase and Firepad Component

Body:
I am trying to spin up the Firepad Editor inside of my React Component, but I am encountering an error. Here is my Component:

import React, { Component } from 'react';
import * as firebase from 'firebase';
import CodeMirror from 'codemirror';
import Firepad from 'firepad';

export default class FirePadEditor extends Component {
  constructor() {
    super();
    firebase.initializeApp({
      apiKey: "AIzaSyCDre_vyeiK1a0qA8XSecI4elbF3hlobjc",
      authDomain: "firepad-test-d4679.firebaseapp.com",
      databaseURL: "https://firepad-test-d4679.firebaseio.com",
      projectId: "firepad-test-d4679",
      storageBucket: "firepad-test-d4679.appspot.com",
      messagingSenderId: "585682717429"
    });
  }

  componentDidMount() {
    var firepadRef = firebase.database().ref();
    var codeMirror = CodeMirror(document.getElementById('firepad'), { lineWrapping: true });
    var firepad = Firepad.fromCodeMirror(firepadRef, codeMirror, {
            richTextShortcuts: true,
            richTextToolbar: true,
            defaultText: 'Hello, World!'
          });
  }

    render() {
    return (

testing

  )
  }
}

My Firebase credentials are correct and I am seeing the 'testing' text on my screen.

When I run on localhost, I encounter this error:

Uncaught TypeError: p is not a constructor
    at new c (bundle.js:30211)
    at Function.c (bundle.js:30211)
    at FirePadEditor.componentDidMount (bundle.js:19892)
    at CallbackQueue.notifyAll (bundle.js:6516)
    at ReactReconcileTransaction.close (bundle.js:16274)
    at ReactReconcileTransaction.closeAll (bundle.js:6877)
    at ReactReconcileTransaction.perform (bundle.js:6824)
    at batchedMountComponentIntoNode (bundle.js:2724)
    at ReactDefaultBatchingStrategyTransaction.perform (bundle.js:6811)
    at Object.batchedUpdates (bundle.js:10848)

What I am seeing on my Node Console:

WARNING in ./~/firepad/dist/firepad.min.js
Critical dependencies:
14:3292-3299 require function is used in a way in which dependencies cannot be statically extracted
 @ ./~/firepad/dist/firepad.min.js 14:3292-3299

WARNING in ./~/firepad/dist/firepad.css
Module parse failed: /Users/Air/Desktop/firepad/firepad/node_modules/firepad/dist/firepad.css Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (1:0)
    at Parser.pp$4.raise (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:2221:15)
    at Parser.pp.unexpected (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:603:10)
    at Parser.pp$3.parseExprAtom (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1822:12)
    at Parser.pp$3.parseExprSubscripts (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1715:21)
    at Parser.pp$3.parseMaybeUnary (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1692:19)
    at Parser.pp$3.parseExprOps (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1637:21)
    at Parser.pp$3.parseMaybeConditional (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1620:21)
    at Parser.pp$3.parseMaybeAssign (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1597:21)
    at Parser.pp$3.parseExpression (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1573:21)
    at Parser.pp$1.parseStatement (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:727:47)
 @ ./~/firepad/dist ^\.\/.*$

WARNING in ./~/firepad/dist/firepad.eot
Module parse failed: /Users/Air/Desktop/firepad/firepad/node_modules/firepad/dist/firepad.eot Unexpected character '' (1:1)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected character '' (1:1)
    at Parser.pp$4.raise (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:2221:15)
    at Parser.pp$7.getTokenFromCode (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:2756:10)
    at Parser.pp$7.readToken (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:2477:17)
    at Parser.pp$7.nextToken (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:2468:15)
    at Parser.pp$7.next (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:2413:10)
    at Parser.pp$3.parseLiteral (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1830:10)
    at Parser.pp$3.parseExprAtom (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1786:19)
    at Parser.pp$3.parseExprSubscripts (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1715:21)
    at Parser.pp$3.parseMaybeUnary (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1692:19)
    at Parser.pp$3.parseExprOps (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1637:21)
    at Parser.pp$3.parseMaybeConditional (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1620:21)
    at Parser.pp$3.parseMaybeAssign (/Users/Air/Desktop/firepad/firepad/node_modules/webpack/node_modules/acorn/dist/acorn.js:1597:21)
 @ ./~/firepad/dist ^\.\/.*$

WARNING in ./~/firepad/dist/firepad.js
Critical dependencies:
2463:61-68 require function is used in a way in which dependencies cannot be statically extracted
 @ ./~/firepad/dist/firepad.js 2463:61-68
webpack: Compiled with warnings.

Any ideas on how to solve this problem?

Body:
Use these npm packages - brace, react-ace, firebase, firepad.

Since firepad needs aceto be present globally, assign brace to global var
like(not the best way, but works) before importing firepad

import firebase from 'firebase/app';
import 'firebase/database';
import brace from 'brace';
global.ace = brace;
global.ace.require = global.ace.acequire;
import Firepad from 'firepad';

Use ref to get instance of ReactAce and initialize it in componentDidMount using:

new Firepad.fromACE(this.firepadRef, this.aceInstance.editor, options);

Similarly for CodeMirror editor.


来源: stackexchange

问:
How do you display "%5d" in C?
How do you display the string "%5d" in C? I tried putting a backslash in front of the percent, but it won't print (and gave warnings). I tried Googling but to no avail. I guess this is too wide for me to find a specific answer.

```<code>#include <stdio.h>

int main(void)
{
    int test = 40;
    printf("\%5.1d %5.1d", test); //this is the one
    printf("%5.1d", test);
    return 0;
}
</code>```

Any help?

答: Or you could do printf("%s", "%5d") :) I understand this is kind of roundabout way, and ones described in other answers are better, but just mentioning this is a possibility too.

ContentLicense: CC BY-SA 2.5

Title: How do you display "%5d" in C?

Body:
How do you display the string "%5d" in C? I tried putting a backslash in front of the percent, but it won't print (and gave warnings). I tried Googling but to no avail. I guess this is too wide for me to find a specific answer.

#include <stdio.h>

int main(void)
{
    int test = 40;
    printf("\%5.1d %5.1d", test); //this is the one
    printf("%5.1d", test);
    return 0;
}

Any help?


问:
JQuery not able to prevent event bubbling
I am trying to highlight element over droppable. The list has child and parent type element and i have put appropriate classes as well. Things are find but i am not able to prevent event bubbling. i have tried below code but not working somehow. While draggable is dragged over the droppable, all element (with parent class) starts flickering the yellow background. i have no idea how to stop this. i have tried stopPropagation(),stopImmediatePropagation() in over function but nothing worked out. my code is as below,

```<code><!doctype html>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js" ></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>
<style>
#NodeDetails {
    border: solid 1px red;
    width: 40%;
    height: 200px;
    overflow-y: auto;
    overflow-x: auto;
    font-size:12px;
    float:right;
}
#TestContainer {
    border: solid 1px red;
    width: 40%;
    height: 400px;
    overflow-y: auto;
    overflow-x: auto;
    float:left;
    cursor:default;
}
ul{
    list-style-type: none;
    text-align: left;
    padding-left: 15px;
    padding-top: 3px;
}
li{
    padding-bottom: 0px;
    padding-top: 1px;
    display:inline;
}
img {
  vertical-align: top;
  padding-right: 0px ;
  margin-right: 0px ;
  height: 15px;
  width: 15px;
}

img .testcat {

}
span {
  vertical-align: top;
  padding-left: 5px ;
  padding-right: 5px ;
  color: black;
  font-size:15px;
}
.nochild {
    font-size:10px;
}
.droppable-below {
   border-bottom: 2px solid blue;
   margin-top: 0px;
   margin-bottom: 5px;
}
.droppable-in {
    border: 1px solid black;
    background-color: yellow;
}
/*
.TestContainer, .TestContainer ul, .TestContainer li {
     position: relative;
}
.TestContainer ul {
    list-style: none;
    padding-left: 12px;
}
.TestContainer li::before, .TestContainer li::after {
    content: "";
    position: absolute;
    left: -12px;
}
.TestContainer li::before {
    border-top: 2px solid #000;
    top: 5px;
    width: 6px;
    height: 0;
    margin-left: 6px;
}
.TestContainer li::after {
    border-left: 2px solid #000;
    height: 170%;
    width: 0px;
    top: -8px;
    margin-left: 6px;
}
.TestContainer ul > li:last-child::after {
    height: 8px;
} */
</style>

</head>
<body>
    <div ng-app="mainApp">
        <div ng-controller="TreeController">
             <div id="TestContainer" class="TestContainer">
             <collection collection='testdata'></collection>
             </div>
        </div>
    </div>
</body>
<script>
var mainApp = angular.module("mainApp", [])
mainApp.directive('collection', function () {
    return {
        restrict: "E",
        replace: true,
        scope: {collection: '='},
        template: "<ul><member ng-repeat='member in collection' member='member'></member></ul>"
    }
})

mainApp.directive('member', function ($compile) {
    var NewChild = "<li><img class=opcl ng-src={{PlusMinusImage}} ng-click=ShowHideFunc()></img><img class=testcat ng-src={{C15Image}}></img><span ng-click=ShowDetailsFunc()>{{member.TagName}}</span></li>";
    var linkerfunc = function(scope, element, attrs) {
                    var collectionSt = '<collection collection="member.children"></collection>';
                    $compile(collectionSt)(scope, function(cloned, scope)   {
                        //element.css("background-color", "#ff00ff");
                        if (scope.member.children.length === 0){
                        $(element[0]).children().first().remove()
                        $(element[0]).addClass("child");
                        } else
                        {
                        $(element[0]).addClass("parent");
                        }
                        element.attr('xml-path', scope.member.TagPath);
                        element.append(cloned);
                     });
                    scope.ShowHideFunc = function() {
                        scope.ShowHideCtrlFunc(element,event);
                        event.stopImmediatePropagation();
                      };
    }
    return {
        restrict: "E",
        replace: true,
        scope: {member: '=', ShowHideCtrlFunc : '&', ShowDetailsCtrlFunc : '&'},
        template: NewChild,
        controller: 'TreeController',
        link: linkerfunc
    }
})
mainApp.controller('TreeController', function ($scope,$http) {
    $scope.testdata = [{"TagName":"LandXML","TagPath":">MyRootNode>ChildItems>LandXML","children":[{"TagName":"Units","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Units","children":[{"TagName":"Imperial","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[1]>Imperial","children":[]},{"TagName":"Project","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Project","children":[]},{"TagName":"Application","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Application","children":[{"TagName":"Author","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[2]>Author","children":[]},{"TagName":"Alignments","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Alignments","children":[]},{"TagName":"Roadways","TagPath":">MyRootNode>ChildItems>ChildItems[1]>Roadways","children":[{"TagName":"Roadway1","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[1]","children":[]},{"TagName":"Roadway2","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[2]","children":[]},{"TagName":"Roadway3","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[3]","children":[]},{"TagName":"Roadway4","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[4]","children":[]},{"TagName":"Roadway5","TagPath":">MyRootNode>ChildItems>ChildItems[1]>ChildItems[3]>Roadway[5]","children":[]}]}]}]}]},{"TagName":"Surfaces","TagPath":">MyRootNode>ChildItems>Surfaces","children":[{"TagName":"Surface1","TagPath":">MyRootNode>ChildItems>ChildItems[2]>Surface1","children":[]},{"TagName":"Surface2","TagPath":">MyRootNode>ChildItems>ChildItems[2]>Surface2","children":[]}]}]
    $scope.PlusMinusImage = '../Images/Plus15.png';
    $scope.C15Image = '../Images/C15.png' ;

    $scope.ShowHideCtrlFunc = function(element,event) {
            //console.log("in function ShowHideCtrlFunc");
            if ($scope.PlusMinusImage === '../Images/Plus15.png') {
                $scope.PlusMinusImage = '../Images/Minus15.png';
            } else {
                $scope.PlusMinusImage = '../Images/Plus15.png';
            }
            $(element).children().last().toggle();
            event.stopImmediatePropagation();
      };
    makedraggable()
});
function makedraggable() {
    var myimg = $('<img/>').attr({
                        src:"images/whitebriefcase4.png"
                        })
    $("li").draggable({
                    containment: '#TestContainer',
                    cursorAt: { top: -0, left: -15 },
                    helper: function() {
                            return $("<div></div>").append(myimg);
                            },
                    revert: "invalid",
                    drag: function(event,ui) {
                                $(this).find('span').first().css({"font-weight": "bold", "background-color": "lightblue"});
                            },
                    stop: function(){
                            $(this).find('span').first().css({"font-weight": "normal", "background-color": "white"});
                         },
                    drop: function (event){
                                console.log("I am dragged and dropped")
                                //event.stopImmediatePropagation();
                                }
                });

    $('.parent').droppable({
        greedy: true,
        hoverClass: "droppable-in", //, border: 5px solid red;
        /*
        over: function() {
            //$(this).children().first().next().css({"border": "1px solid black", "background-color": "yellow"})
            $(this).css({"border": "1px solid black", "background-color": "yellow"})
            //console.log($(this).parent());
        },
        out: function() {
            $(this).css({"border": "none", "background-color": "white"})
        }, */
        drop: function(event, ui) {
            //console.log($(ui.draggable).text());
            //console.log($(this).next());
            $(this).next().append($(ui.draggable));
            $(this).css({"border": "none", "background-color": "white"})
        }
    });

};
</script>
</html>
</code>```

Please help

答:
You used droppable-in class in hoverClass like below:

```<code> $('.parent').droppable({
        greedy: true,
        hoverClass: "droppable-in",
        ...
    });
</code>```

This class defined as follows and causes yellow background.

```<code>.droppable-in {
    border: 1px solid black;
    background-color: yellow;
}
</code>```

You can comment code below and test drop again.

```<code>// hoverClass: "droppable-in",
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to highlight element over droppable. The list has child and parent type element and i have put appropriate classes as well. Things are find but i am not able to prevent event bubbling. i have tried below code but not working somehow. While draggable is dragged over the droppable, all element (with parent class) starts flickering the yellow background. i have no idea how to stop this. i have tried stopPropagation(),stopImmediatePropagation() in over function but nothing worked out. my code is as below,

<!doctype html>

             <collection collection='testdata'></collection>

Please help

Body:
You used droppable-in class in hoverClass like below:

 $('.parent').droppable({
        greedy: true,
        hoverClass: "droppable-in",
        ...
    });

This class defined as follows and causes yellow background.

.droppable-in {
    border: 1px solid black;
    background-color: yellow;
}

You can comment code below and test drop again.

// hoverClass: "droppable-in",


问:
Load CSV data in to Dataframe and convert to Array using Apache Spark (Java)
I have a CSV file with below data :

```<code>1,2,5
2,4
2,3
</code>```

I want to load them into a Dataframe having schema of string of array

The output should be like below.

```<code>[1, 2, 5]
[2, 4]
[2, 3]
</code>```

This has been answered using scala here:
Spark: Convert column of string to an array

I want to make it happen in Java.

Please help

答:
Below is the sample code in Java. You need to read your file using spark.read().text(String path) method and then call the split function.

```<code>import static org.apache.spark.sql.functions.split;

public class SparkSample {
    public static void main(String[] args) {
        SparkSession spark = SparkSession
                .builder()
                .appName("SparkSample")
                .master("local[*]")
                .getOrCreate();
        //Read file
        Dataset<Row> ds = spark.read().text("c://tmp//sample.csv").toDF("value");
        ds.show(false);
        Dataset<Row> ds1 = ds.select(split(ds.col("value"), ",")).toDF("new_value");
        ds1.show(false);
        ds1.printSchema();
    }
}
</code>```

Body:
I have a CSV file with below data :

1,2,5
2,4
2,3

I want to load them into a Dataframe having schema of string of array

The output should be like below.

[1, 2, 5]
[2, 4]
[2, 3]

This has been answered using scala here:
Spark: Convert column of string to an array

I want to make it happen in Java.

Please help

Body:
Below is the sample code in Java. You need to read your file using spark.read().text(String path) method and then call the split function.

import static org.apache.spark.sql.functions.split;

public class SparkSample {
    public static void main(String[] args) {
        SparkSession spark = SparkSession
                .builder()
                .appName("SparkSample")
                .master("local[*]")
                .getOrCreate();
        //Read file
        Dataset<Row> ds = spark.read().text("c://tmp//sample.csv").toDF("value");
        ds.show(false);
        Dataset<Row> ds1 = ds.select(split(ds.col("value"), ",")).toDF("new_value");
        ds1.show(false);
        ds1.printSchema();
    }
}


问:
Laravel 5.3 How to show Username in Notifications Email
I am trying to add the user's first name in the notification emails. At the moment, Laravel notification emails starts like:

```<code>Hello,
</code>```

And I want to change it to:

```<code>Hello Donald,
</code>```

Right now, I have a set-up like this. This example is for a Password Reset Notification email:

User Model:

```<code>public function sendPasswordResetNotification($token)
        {
            $this->notify(new PasswordReset($token));
        }
</code>```

App\Notifications\PasswordReset:

```<code>class PasswordReset extends Notification
{
    use Queueable;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->line('The introduction to the notification.')
                    ->action('Notification Action', 'https://laravel.com')
                    ->line('Thank you for using our application!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}
</code>```

Is the User Model automatically binded with the Notification Class? How can I add the username in the view?

答:
The $notifiable variable passed to toMail() is User model.

Call to needed User model attribute, easy:

```<code>public function toMail($notifiable)
{
     return (new MailMessage)
        ->greeting('Hello '. $notifiable->username)
        ->line('The introduction to the notification.')
        ->action('Notification Action', 'https://laravel.com')
        ->line('Thank you for using our application!');
}
</code>```

Body:
I am trying to add the user's first name in the notification emails. At the moment, Laravel notification emails starts like:

Hello,

And I want to change it to:

Hello Donald,

Right now, I have a set-up like this. This example is for a Password Reset Notification email:

User Model:

public function sendPasswordResetNotification($token)
        {
            $this->notify(new PasswordReset($token));
        }

App\Notifications\PasswordReset:

class PasswordReset extends Notification
{
    use Queueable;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->line('The introduction to the notification.')
                    ->action('Notification Action', 'https://laravel.com')
                    ->line('Thank you for using our application!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}

Is the User Model automatically binded with the Notification Class? How can I add the username in the view?

Body:
The $notifiable variable passed to toMail() is User model.

Call to needed User model attribute, easy:

public function toMail($notifiable)
{
     return (new MailMessage)
        ->greeting('Hello '. $notifiable->username)
        ->line('The introduction to the notification.')
        ->action('Notification Action', 'https://laravel.com')
        ->line('Thank you for using our application!');
}


问:
How to get friend's birthday list using facebook api?
I am trying to get friend birthday list.

But how to find using my api I dont know.

答:
FB.api('me/friends?fields=id,name,birthday') doesnt work as of 09/12/2017.

Below is the debug message from graph explorer tool when i try to hit the endpoint.

```<code>Only friends who installed this app are returned in API v2.0 and higher. total_count in summary represents the total number of friends, including those who haven't installed the app
</code>```

For returning just the friends list of the user, you can try hitting the below endpoint with a valid access token

```<code>FB.api('me/friendlists')
</code>```

But note that you need read_custom_friendlists  permission from the user.

Body:
FB.api('me/friends?fields=id,name,birthday') doesnt work as of 09/12/2017.

Below is the debug message from graph explorer tool when i try to hit the endpoint.

Only friends who installed this app are returned in API v2.0 and higher. total_count in summary represents the total number of friends, including those who haven't installed the app

For returning just the friends list of the user, you can try hitting the below endpoint with a valid access token

FB.api('me/friendlists')

But note that you need read_custom_friendlists  permission from the user.


问:
Is jQuery's "each()" method a for loop?
I tried adding a serialized class to each of a set of objects like this:

```<code>jQuery('#preload img').each(function(){
    jQuery('#thumbs').append('<img class="index' + index + '" src="' + source + '" />');
    index = ++index;
    });
</code>```

And it worked. What resulted was a set of images, each with a class image1, image2, and so on. It's exactly what I wanted. But is this actually a reliable method of looping through a set of objects? Or is it possible that, if this anonymous function took longer to execute, the function might start on the next object before index is incremented?

Anybody know what's actually happening?

答:
This is the inner workings of the each function (1.4.4):

```<code>// args is for internal usage only
each: function( object, callback, args ) {
    var name, i = 0,
        length = object.length,
        isObj = length === undefined || jQuery.isFunction(object);

    if ( args ) {
        if ( isObj ) {
            for ( name in object ) {
                if ( callback.apply( object[ name ], args ) === false ) {
                    break;
                }
            }
        } else {
            for ( ; i < length; ) {
                if ( callback.apply( object[ i++ ], args ) === false ) {
                    break;
                }
            }
        }

    // A special, fast, case for the most common use of each
    } else {
        if ( isObj ) {
            for ( name in object ) {
                if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
                    break;
                }
            }
        } else {
            for ( var value = object[0];
                i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {}
        }
    }

    return object;
}
</code>```

You can see here that it has a few different cases but all of them use for loops and call the callback function. So your code should be fine.

You can look it up in the development version of jQuery (change the radio button on the main jQuery site, or click here).

Title: Is jQuery's "each()" method a for loop?

Body:
I tried adding a serialized class to each of a set of objects like this:

jQuery('#preload img').each(function(){
    jQuery('#thumbs').append('');
    index = ++index;
    });

And it worked. What resulted was a set of images, each with a class image1, image2, and so on. It's exactly what I wanted. But is this actually a reliable method of looping through a set of objects? Or is it possible that, if this anonymous function took longer to execute, the function might start on the next object before index is incremented?

Anybody know what's actually happening?

Body:
This is the inner workings of the each function (1.4.4):

// args is for internal usage only
each: function( object, callback, args ) {
    var name, i = 0,
        length = object.length,
        isObj = length === undefined || jQuery.isFunction(object);

    if ( args ) {
        if ( isObj ) {
            for ( name in object ) {
                if ( callback.apply( object[ name ], args ) === false ) {
                    break;
                }
            }
        } else {
            for ( ; i < length; ) {
                if ( callback.apply( object[ i++ ], args ) === false ) {
                    break;
                }
            }
        }

    // A special, fast, case for the most common use of each
    } else {
        if ( isObj ) {
            for ( name in object ) {
                if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
                    break;
                }
            }
        } else {
            for ( var value = object[0];
                i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {}
        }
    }

    return object;
}

You can see here that it has a few different cases but all of them use for loops and call the callback function. So your code should be fine.

You can look it up in the development version of jQuery (change the radio button on the main jQuery site, or click here).


问:
Dialogflow V2 Messenger Integration with Multiple Messages
I am trying to send to multiple messages within one Webhook call to Dialogflow, which shall be passed to Messenger. Right now my Webhook responds with a malfunctioning JSON body:

```<code>{
    'fulfillmentText': "Text",
    'fulfillmentMessages': [{
        "platform": "facebook",
        "text": [{
            "text": "Text"
        }]
    }],
    'source': "facebook"
}
</code>```

When I test the Webhook via Messenger I see the is typing symbol, but never receive the Text message. While testing the same Webhook from the Dialogflow Console I get

Webhook execution successful

returned. I guess I am missing some JSON fields to tell Dialogflow in which format it has to send the JSON two the Messenger API. Anybody having any clues on how to solve this issue?

Edit:
My latest not working trial...

```<code>{
  "fulfillmentText": "Hola!",
  "fulfillmentMessages": [
    {
      "text": {
        "text": [
          "Title: this is a title"
        ]
      },
      "platform": "FACEBOOK"
    },
    {
      "text": {
        "text": [
          "Title: this is a title"
        ]
      },
      "platform": "FACEBOOK"
    }
  ]
}
</code>```

答:
I mailed the Dialogflow support about this issue and it turns out that it is currently not possible to send multiple messages from a webhook.

Hi,

At this point, it's not possible to send sequential messages directly
  from webhook. However, if you are using one of our one-click
  integrations that support rich messages, you can invoke intents in
  which multiple messages are defined from webhook through an event as
  described at
  https://dialogflow.com/docs/events#invoking_event_from_webhook.

Let me know if you have any questions.

Regards,  Ankita from Dialogflow

Body:
I am trying to send to multiple messages within one Webhook call to Dialogflow, which shall be passed to Messenger. Right now my Webhook responds with a malfunctioning JSON body:

{
    'fulfillmentText': "Text",
    'fulfillmentMessages': [{
        "platform": "facebook",
        "text": [{
            "text": "Text"
        }]
    }],
    'source': "facebook"
}

When I test the Webhook via Messenger I see the is typing symbol, but never receive the Text message. While testing the same Webhook from the Dialogflow Console I get

Webhook execution successful

returned. I guess I am missing some JSON fields to tell Dialogflow in which format it has to send the JSON two the Messenger API. Anybody having any clues on how to solve this issue?

Edit:
My latest not working trial...

{
  "fulfillmentText": "Hola!",
  "fulfillmentMessages": [
    {
      "text": {
        "text": [
          "Title: this is a title"
        ]
      },
      "platform": "FACEBOOK"
    },
    {
      "text": {
        "text": [
          "Title: this is a title"
        ]
      },
      "platform": "FACEBOOK"
    }
  ]
}


问:
How to create UILabel programmatically using Swift?
How do I create a UILabel programmatically using Swift in Xcode 6?

I have started with a new "Single View Application" in Xcode 6 and selected Swift for this project. I have my files AppDelegate.swift and ViewController.swift and I'm not sure what to do from here.

答:
Another answer in Swift 3:</p>
```<code>let myLabel = UILabel()
myLabel.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
myLabel.center = CGPoint(x: 0, y: 0)
myLabel.textAlignment = .center
myLabel.text = "myLabel!!!!!"
self.view.addSubview(myLabel)
</code>```

Body:
Another answer in Swift 3:

let myLabel = UILabel()
myLabel.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
myLabel.center = CGPoint(x: 0, y: 0)
myLabel.textAlignment = .center
myLabel.text = "myLabel!!!!!"
self.view.addSubview(myLabel)

ContentLicense: CC BY-SA 4.0


问:
Too many ajax calls when form selections change
My webpage has two main sections: (1) search criteria (selection boxes in a form) used to access database information, and (2) a div in which the results are displayed. When the page loads initially, default values in the form are serialized and sent via ajax to php and the results are rendered. This results section is paginated to display all the results by clicking next, previous, etc. This all works perfectly.

Here’s the problem: each time the user makes a change to the criteria and the form’s data is serialized and sent via ajax, another layer of results is added somehow. When paginating through the results, it processes page 2 for each of the “layers” but only the last one that arrives from the server is displayed on the webpage. So, every time another change is made, another layer is added. Since ajax is asynchronous, the results displayed may or may not be the correct “layer.”

HTML:

```<code><form id='submitCriteria' action='' method='post'>
    <select id='selLevel' class='selectpicker'  name='levels'>
        <option title='Levels' value='No Preference'
            selected = 'selected'>No Preference</option>
        <option title='Levels:<br>  1+' value=1 >1+ </option>
        <option title='Levels:<br>  2+' value=2 >2+ </option>
        <option title='Levels:<br>  3+' value=3 >3+ </option>
    </select>
</form>

<!-- Pagination: -->
<div id="spinnerDet" class="spinnerA">
</div>
<div id="paginationdiv">
    <div id="pagination_container">
        <div class="pagination">
            <ul><li class="inactive">Previous</li>
                <li class="pagerange">
                    <span class="total" a=" 58">
                        Page 1 of 58 </span></li>
                <li p="2" class="active">Next</li>
            </ul>
        </div>

        <!-- Output from server: -->
        <table>
            <tr><td>Levels</td><td>3</td></tr>
        </table>
    </div>
</div>
</code>```

javascript/jQuery:

```<code>$("#submitCriteria").change(function(e) {
    e.preventDefault();
    e.stopPropagation();
    $.ajax({
         type: 'post',
         data: $("#submitCriteria").serialize(),
         url: "/load_plans.php",
         success: function(data) {
             paginateDetails (data)
         },
    });
    return false;
});

function paginateDetails (data) {
   selDetails = JSON.parse(data);
   var levels = selDetails.levels;
   var totalsline = "Number of levels: " + levels;
   $('#numResults').removeClass('spinnerA');
   $('#numResults').addClass('stop-spin');
   $('#numResults').html(totalsline);
   loadData(1); //initial output based on default values

   // Pagination buttons event:
   $('#paginationdiv').on('click touchend',
   '#pagination_container .pagination li.active', function (e) {
       e.stopPropagation();
       e.preventDefault();
       var page = $(this).attr('p');
       loadData(page);
   });

   function loadData(page) {
       $.ajax({
           type: "POST",
           data: eval("'page=' + page + '&levels=' + levels"),
           url: "loadDetails.php",
           success: function (msg) {
               $("#pagination_container").ajaxComplete(function (event, request, settings) {
                   $("#pagination_container").html(msg);
               });
           }
       });
   }
}
</code>```

How do I eliminate another “layer” when selections in the form are changed/updated?

答:
I think the problem is with the structure of your code, in this case you shouldn't be nesting the functions. Also you are repeatedly attaching click event to #paginationdiv (does it get removed and reatached when you reload data? You should use class instead of div in that case).

Without trying the code, i believe your problem might be caused by your loadData function - in your success callback you don't need to hook ajax complete again, success is called when your request is complete and successfull. I believe that part of your code was triggering twice ( on success and when ajaxComplete fired)

Your refactored code should look something like this:

```<code>$("#submitCriteria").change(function(e) {
    e.preventDefault();
    e.stopPropagation();
    $.ajax({
        type: 'post',
        data: $("#submitCriteria").serialize(),
        url: "/load_plans.php",
        success: function(data) {
            paginateDetails (data)
        },
    });
    return false;
});

function loadData(page) {
    $.ajax({
        type: "POST",
        data: eval("'page=' + page + '&levels=' + levels"),
        url: "loadDetails.php",
        success: function (msg) {
            //$("#pagination_container").ajaxComplete(function (event, request, settings) {
                $("#pagination_container").html(msg);
            //});
        }
    });
}

function paginateDetails (data) {
    selDetails = JSON.parse(data);
    var levels = selDetails.levels;
    var totalsline = "Number of levels: " + levels;
    $('#numResults').removeClass('spinnerA');
    $('#numResults').addClass('stop-spin');
    $('#numResults').html(totalsline);
    loadData(1); //initial output based on default values

    // remove previous click handlers
    $('#paginationdiv').off()
    // Pagination buttons event:
    $('#paginationdiv').on('click touchend',
    '#pagination_container .pagination li.active', function (e) {
        e.stopPropagation();
        e.preventDefault();
        var page = $(this).attr('p');
        loadData(page);
    });
}
</code>```

Body:
My webpage has two main sections: (1) search criteria (selection boxes in a form) used to access database information, and (2) a div in which the results are displayed. When the page loads initially, default values in the form are serialized and sent via ajax to php and the results are rendered. This results section is paginated to display all the results by clicking next, previous, etc. This all works perfectly.

Here’s the problem: each time the user makes a change to the criteria and the form’s data is serialized and sent via ajax, another layer of results is added somehow. When paginating through the results, it processes page 2 for each of the “layers” but only the last one that arrives from the server is displayed on the webpage. So, every time another change is made, another layer is added. Since ajax is asynchronous, the results displayed may or may not be the correct “layer.”

HTML:

<form id='submitCriteria' action='' method='post'>
    <select id='selLevel' class='selectpicker'  name='levels'>
        <option title='Levels' value='No Preference'
            selected = 'selected'>No Preference</option>
        <option title='Levels:
  1+' value=1 >1+ </option>
        <option title='Levels:
  2+' value=2 >2+ </option>
        <option title='Levels:
  3+' value=3 >3+ </option>
    </select>
</form>

Previous

                        Page 1 of 58

Next

Levels	3

javascript/jQuery:

$("#submitCriteria").change(function(e) {
    e.preventDefault();
    e.stopPropagation();
    $.ajax({
         type: 'post',
         data: $("#submitCriteria").serialize(),
         url: "/load_plans.php",
         success: function(data) {
             paginateDetails (data)
         },
    });
    return false;
});

function paginateDetails (data) {
   selDetails = JSON.parse(data);
   var levels = selDetails.levels;
   var totalsline = "Number of levels: " + levels;
   $('#numResults').removeClass('spinnerA');
   $('#numResults').addClass('stop-spin');
   $('#numResults').html(totalsline);
   loadData(1); //initial output based on default values

   // Pagination buttons event:
   $('#paginationdiv').on('click touchend',
   '#pagination_container .pagination li.active', function (e) {
       e.stopPropagation();
       e.preventDefault();
       var page = $(this).attr('p');
       loadData(page);
   });

   function loadData(page) {
       $.ajax({
           type: "POST",
           data: eval("'page=' + page + '&levels=' + levels"),
           url: "loadDetails.php",
           success: function (msg) {
               $("#pagination_container").ajaxComplete(function (event, request, settings) {
                   $("#pagination_container").html(msg);
               });
           }
       });
   }
}

How do I eliminate another “layer” when selections in the form are changed/updated?

Body:
I think the problem is with the structure of your code, in this case you shouldn't be nesting the functions. Also you are repeatedly attaching click event to #paginationdiv (does it get removed and reatached when you reload data? You should use class instead of div in that case).

Without trying the code, i believe your problem might be caused by your loadData function - in your success callback you don't need to hook ajax complete again, success is called when your request is complete and successfull. I believe that part of your code was triggering twice ( on success and when ajaxComplete fired)

Your refactored code should look something like this:

$("#submitCriteria").change(function(e) {
    e.preventDefault();
    e.stopPropagation();
    $.ajax({
        type: 'post',
        data: $("#submitCriteria").serialize(),
        url: "/load_plans.php",
        success: function(data) {
            paginateDetails (data)
        },
    });
    return false;
});

function loadData(page) {
    $.ajax({
        type: "POST",
        data: eval("'page=' + page + '&levels=' + levels"),
        url: "loadDetails.php",
        success: function (msg) {
            //$("#pagination_container").ajaxComplete(function (event, request, settings) {
                $("#pagination_container").html(msg);
            //});
        }
    });
}

function paginateDetails (data) {
    selDetails = JSON.parse(data);
    var levels = selDetails.levels;
    var totalsline = "Number of levels: " + levels;
    $('#numResults').removeClass('spinnerA');
    $('#numResults').addClass('stop-spin');
    $('#numResults').html(totalsline);
    loadData(1); //initial output based on default values

    // remove previous click handlers
    $('#paginationdiv').off()
    // Pagination buttons event:
    $('#paginationdiv').on('click touchend',
    '#pagination_container .pagination li.active', function (e) {
        e.stopPropagation();
        e.preventDefault();
        var page = $(this).attr('p');
        loadData(page);
    });
}


问:
Image toggle is not happening timely
I need to toggle a image from red to yellow after 10 second and to green 3 seconds after clicking a  button.

Images are "drawable" with three image stored into imgesView1 array.

The image is supposed to change its state into yellow after threadSleep 10 second and but when all communication is over with the server it changes to green state which is to come after yellow.

Here is my code.

```<code>new SendCommandRequest().execute(parameterForURL);
   try{Thread.sleep(10000);}
   catch (InterruptedException ie){}
   imageView1.setImageResource(images1[1]);
     switch(result1) {
       case "1":
         new SendCommandRequest().execute(parameterForURL);
         imageView1.setImageResource(images1[1]);
         try{Thread.sleep(3000);}
         catch (InterruptedException ie){}
         imageView1.setImageResource(images1[1]);
</code>```

All tasks are done on a single button click.

答:
Try not to use Thread.sleep, use a CountDownTimer or a Runnable and Handler.postDelayed:
https://developer.android.com/reference/android/os/CountDownTimer.html
how to use postDelayed() correctly in android studio?

Title: Image toggle is not happening timely

Body:
I need to toggle a image from red to yellow after 10 second and to green 3 seconds after clicking a  button.

Images are "drawable" with three image stored into imgesView1 array.

The image is supposed to change its state into yellow after threadSleep 10 second and but when all communication is over with the server it changes to green state which is to come after yellow.

Here is my code.

new SendCommandRequest().execute(parameterForURL);
   try{Thread.sleep(10000);}
   catch (InterruptedException ie){}
   imageView1.setImageResource(images1[1]);
     switch(result1) {
       case "1":
         new SendCommandRequest().execute(parameterForURL);
         imageView1.setImageResource(images1[1]);
         try{Thread.sleep(3000);}
         catch (InterruptedException ie){}
         imageView1.setImageResource(images1[1]);

All tasks are done on a single button click.


问:
Setting the initial value of a VisualState
I have a problem with a custom control using the VisualStateManager.

Transitions between states work as I expect, but I don't understand how to set the initial state.

I have made complete example to illustrate the problem.
This example uses a custom control based on ButtonBase.

The control has a VisualState group with two states "Checked" and "Unchecked".
This is the C# code of the control.

```<code>using System.Windows;
using System.Windows.Controls.Primitives;

namespace VisualStateTest
{
  [TemplateVisualStateAttribute(Name = "Checked",           GroupName = "CheckStates")]
  [TemplateVisualStateAttribute(Name = "Unchecked",         GroupName = "CheckStates")]
  public class CustomButton : ButtonBase
  {
    public static readonly DependencyProperty IsCheckedProperty =
        DependencyProperty.Register ( "IsChecked",
                                      typeof(bool),
                                      typeof(CustomButton),
                                      new FrameworkPropertyMetadata ( false,
                                                                      FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
                                                                      OnCheckedChanged ) ) ;

    static CustomButton()
    {
      DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomButton), new FrameworkPropertyMetadata(typeof(CustomButton)));
    }

    public bool IsChecked
    {
      get { return (bool)GetValue(IsCheckedProperty); }
      set { SetValue(IsCheckedProperty, value); }
    }

    public static void OnCheckedChanged ( DependencyObject d, DependencyPropertyChangedEventArgs e )
    {
      var button = d as CustomButton ;

      if ((bool)e.NewValue)
      {
        VisualStateManager.GoToState(button, "Checked", true);
      }
      else
      {
        VisualStateManager.GoToState(button, "Unchecked", true);
      }
    }

  }
}
</code>```

The control template shows a shadow on the left and top sides when the IsChecked property is set.

(I know that the design is poor, but this is not a question about graphical design.)

This is the control template:

```<code><ResourceDictionary
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:local="clr-namespace:VisualStateTest">

  <Style TargetType="{x:Type local:CustomButton}">
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="{x:Type local:CustomButton}">

          <Border x:Name="outerborder"
                  Background="{TemplateBinding Background}"
                  BorderBrush="{TemplateBinding BorderBrush}"
                  BorderThickness="{TemplateBinding BorderThickness}">

            <VisualStateManager.VisualStateGroups>

              <VisualStateGroup x:Name="CheckStates">

                <VisualState x:Name="Checked">
                  <Storyboard>

                    <DoubleAnimationUsingKeyFrames BeginTime="0:0:0"
                                              Storyboard.TargetName="topshadow"
                                              Storyboard.TargetProperty="(UIElement.Opacity)">
                      <SplineDoubleKeyFrame KeyTime="0:0:0.5" Value="1.0"/>
                    </DoubleAnimationUsingKeyFrames>

                    <DoubleAnimationUsingKeyFrames BeginTime="0:0:0"
                                              Storyboard.TargetName="leftshadow"
                                              Storyboard.TargetProperty="(UIElement.Opacity)">
                      <SplineDoubleKeyFrame KeyTime="0:0:0.5" Value="1.0"/>
                    </DoubleAnimationUsingKeyFrames>

                  </Storyboard>
                </VisualState>

                <VisualState x:Name="Unchecked">
                  <Storyboard>

                    <DoubleAnimationUsingKeyFrames BeginTime="0:0:0"
                                              Storyboard.TargetName="topshadow"
                                              Storyboard.TargetProperty="(UIElement.Opacity)">
                      <SplineDoubleKeyFrame KeyTime="0:0:0.5" Value="0"/>
                    </DoubleAnimationUsingKeyFrames>

                    <DoubleAnimationUsingKeyFrames BeginTime="0:0:0"
                                              Storyboard.TargetName="leftshadow"
                                              Storyboard.TargetProperty="(UIElement.Opacity)">
                      <SplineDoubleKeyFrame KeyTime="0:0:0.5" Value="0"/>
                    </DoubleAnimationUsingKeyFrames>

                  </Storyboard>
                </VisualState>

              </VisualStateGroup>

            </VisualStateManager.VisualStateGroups>

            <Grid Cursor="Hand" ClipToBounds="True">

              <Grid.RowDefinitions>
                <RowDefinition Height="10"/>
                <RowDefinition Height="*"/>
              </Grid.RowDefinitions>
              <Grid.ColumnDefinitions>
                <ColumnDefinition Width="10"/>
                <ColumnDefinition Width="*"/>
              </Grid.ColumnDefinitions>

              <Rectangle x:Name="lineargradient"
                         Grid.RowSpan="2" Grid.ColumnSpan="2"
                         Stroke="#7F000000"
                         StrokeThickness="0">
                <Rectangle.Fill>
                  <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="#20808080"/>
                    <GradientStop Color="#008A8A8A" Offset="0.5"/>
                    <GradientStop Color="#20000000" Offset="1"/>
                  </LinearGradientBrush>
                </Rectangle.Fill>
              </Rectangle>

              <ContentPresenter HorizontalAlignment="Center"
                                x:Name="contentPresenter"
                                Grid.RowSpan="2" Grid.ColumnSpan="2"
                                VerticalAlignment="Center" />

              <Rectangle x:Name="topshadow"  Fill="#40000000" Grid.Row="0" Grid.ColumnSpan="2" Opacity="0">
                <Rectangle.Effect>
                  <BlurEffect Radius="3"/>
                </Rectangle.Effect>
              </Rectangle>
              <Rectangle x:Name="leftshadow" Fill="#40000000" Grid.Row="1" Grid.Column="0" Opacity="0">
                <Rectangle.Effect>
                  <BlurEffect Radius="3"/>
                </Rectangle.Effect>
              </Rectangle>

            </Grid>

          </Border>

        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Style>
</ResourceDictionary>
</code>```

For this test I have defined a ViewModel with two boolean properties (Option1 and Option2).
One of the properties has the initial value false, the other one is true.

The main window with two CustomButton controls, wired up to the two option properties, and also two checkboxes connected to the same properties.

This is the complete code of the view model ...

```<code>using System;
using System.ComponentModel;
using System.Windows.Input;

namespace VisualStateTest
{
  public class ViewModel : INotifyPropertyChanged
  {
    // Events for INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;

    private bool        _option1 = false ;
    private bool        _option2 = true ;

    public  ICommand    Notify1Command    { get; private set; }
    public  ICommand    Notify2Command    { get; private set; }

    public ViewModel()
    {
      Notify1Command = new RelayCommand (new Action<object>(Execute_Notify1Command));
      Notify2Command = new RelayCommand (new Action<object>(Execute_Notify2Command));
    }

    public bool Option1
    {
      get { return _option1 ; }
      set
      {
        _option1 = value ;
        NotifyPropertyChanged ( "Option1" ) ;
      }
    }

    public bool Option2
    {
      get { return _option2 ; }
      set
      {
        _option2 = value ;
        NotifyPropertyChanged ( "Option2" ) ;
      }
    }

    public void Execute_Notify1Command ( object value )
    {
      Option1 = !Option1 ;
    }

    public void Execute_Notify2Command ( object value )
    {
      Option2 = !Option2 ;
    }

    private void NotifyPropertyChanged ( String propertyName )
    {
      if ( this.PropertyChanged != null )
      {
        this.PropertyChanged ( this, new PropertyChangedEventArgs(propertyName) ) ;
      }
    }
  }
}
</code>```

and the main window ...

```<code><Window x:Class="VisualStateTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:VisualStateTest"
        mc:Ignorable="d"
        WindowStartupLocation="CenterScreen"
        Title="MainWindow" Height="350" Width="525">

  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="*"/>
      <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="*"/>
      <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>

    <local:CustomButton Grid.Row="0" Grid.Column="0"
                        Command="{Binding Notify1Command}"
                        IsChecked="{Binding Option1, Mode=OneWay}"
                        Content="Option 1"
                        Margin="20"/>

    <local:CustomButton Grid.Row="0" Grid.Column="1"
                        Command="{Binding Notify2Command}"
                        IsChecked="{Binding Option2, Mode=OneWay}"
                        Content="Option 2"
                        Margin="20"/>

    <CheckBox Grid.Row="1" Grid.Column="0"
              IsChecked="{Binding Option1}"
              Content="Option 1"
              Margin="20 5"/>

    <CheckBox Grid.Row="1" Grid.Column="1"
              IsChecked="{Binding Option2}"
              Content="Option 2"
              Margin="20 5"/>

  </Grid>

</Window>
</code>```

After the program is started, clicking either the custom buttons or the checkboxes toggles the option and shows or hides the shadow effect.

This is what it looks like in a 'normal' state:

The problem is when the program starts. Although Option2 is initialized to true, and the function VisualStateManager.GoToState has been called, the shadow effect is not shown.

This is what it looks like on startup.

The checkbox on the right indicates that option 2 is true, but the shadow effect is not present.

I am sure that I am missing one small piece of the puzzle. If it helps, I can upload the sample program.

I'm sorry if this is too much detail.

答:
I think that I have found the answer.

I need to override the function OnApplyTemplate() in my custom control. I have extended the code of the CustomButton class with the following function:

```<code>public override void OnApplyTemplate()
{
  base.OnApplyTemplate();

  if ( IsChecked )
  {
    VisualStateManager.GoToState(this, "Checked", true);
  }
  else
  {
    VisualStateManager.GoToState(this, "Unchecked", true);
  }
}
</code>```

I found this information in by reading the Microsoft documentation. With reference to the method OnApplyTemplate it states

This is the earliest that the FrameworkElement in the ControlTemplate is available to the control.

Body:
I have a problem with a custom control using the VisualStateManager.

Transitions between states work as I expect, but I don't understand how to set the initial state.

I have made complete example to illustrate the problem.
This example uses a custom control based on ButtonBase.

The control has a VisualState group with two states "Checked" and "Unchecked".
This is the C# code of the control.

using System.Windows;
using System.Windows.Controls.Primitives;

namespace VisualStateTest
{
  [TemplateVisualStateAttribute(Name = "Checked",           GroupName = "CheckStates")]
  [TemplateVisualStateAttribute(Name = "Unchecked",         GroupName = "CheckStates")]
  public class CustomButton : ButtonBase
  {
    public static readonly DependencyProperty IsCheckedProperty =
        DependencyProperty.Register ( "IsChecked",
                                      typeof(bool),
                                      typeof(CustomButton),
                                      new FrameworkPropertyMetadata ( false,
                                                                      FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
                                                                      OnCheckedChanged ) ) ;

    static CustomButton()
    {
      DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomButton), new FrameworkPropertyMetadata(typeof(CustomButton)));
    }

    public bool IsChecked
    {
      get { return (bool)GetValue(IsCheckedProperty); }
      set { SetValue(IsCheckedProperty, value); }
    }

    public static void OnCheckedChanged ( DependencyObject d, DependencyPropertyChangedEventArgs e )
    {
      var button = d as CustomButton ;

      if ((bool)e.NewValue)
      {
        VisualStateManager.GoToState(button, "Checked", true);
      }
      else
      {
        VisualStateManager.GoToState(button, "Unchecked", true);
      }
    }

  }
}

The control template shows a shadow on the left and top sides when the IsChecked property is set.

(I know that the design is poor, but this is not a question about graphical design.)

This is the control template:

<ResourceDictionary
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:local="clr-namespace:VisualStateTest">

</ResourceDictionary>

For this test I have defined a ViewModel with two boolean properties (Option1 and Option2).
One of the properties has the initial value false, the other one is true.

The main window with two CustomButton controls, wired up to the two option properties, and also two checkboxes connected to the same properties.

This is the complete code of the view model ...

using System;
using System.ComponentModel;
using System.Windows.Input;

namespace VisualStateTest
{
  public class ViewModel : INotifyPropertyChanged
  {
    // Events for INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;

    private bool        _option1 = false ;
    private bool        _option2 = true ;

    public  ICommand    Notify1Command    { get; private set; }
    public  ICommand    Notify2Command    { get; private set; }

    public ViewModel()
    {
      Notify1Command = new RelayCommand (new Action<object>(Execute_Notify1Command));
      Notify2Command = new RelayCommand (new Action<object>(Execute_Notify2Command));
    }

    public bool Option1
    {
      get { return _option1 ; }
      set
      {
        _option1 = value ;
        NotifyPropertyChanged ( "Option1" ) ;
      }
    }

    public bool Option2
    {
      get { return _option2 ; }
      set
      {
        _option2 = value ;
        NotifyPropertyChanged ( "Option2" ) ;
      }
    }

    public void Execute_Notify1Command ( object value )
    {
      Option1 = !Option1 ;
    }

    public void Execute_Notify2Command ( object value )
    {
      Option2 = !Option2 ;
    }

    private void NotifyPropertyChanged ( String propertyName )
    {
      if ( this.PropertyChanged != null )
      {
        this.PropertyChanged ( this, new PropertyChangedEventArgs(propertyName) ) ;
      }
    }
  }
}

and the main window ...

<Window x:Class="VisualStateTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:VisualStateTest"
        mc:Ignorable="d"
        WindowStartupLocation="CenterScreen"
        Title="MainWindow" Height="350" Width="525">

  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="*"/>
      <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="*"/>
      <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>

    <local:CustomButton Grid.Row="0" Grid.Column="0"
                        Command="{Binding Notify1Command}"
                        IsChecked="{Binding Option1, Mode=OneWay}"
                        Content="Option 1"
                        Margin="20"/>

    <local:CustomButton Grid.Row="0" Grid.Column="1"
                        Command="{Binding Notify2Command}"
                        IsChecked="{Binding Option2, Mode=OneWay}"
                        Content="Option 2"
                        Margin="20"/>

    <CheckBox Grid.Row="1" Grid.Column="0"
              IsChecked="{Binding Option1}"
              Content="Option 1"
              Margin="20 5"/>

    <CheckBox Grid.Row="1" Grid.Column="1"
              IsChecked="{Binding Option2}"
              Content="Option 2"
              Margin="20 5"/>

  </Grid>

</Window>

After the program is started, clicking either the custom buttons or the checkboxes toggles the option and shows or hides the shadow effect.

This is what it looks like in a 'normal' state:

The problem is when the program starts. Although Option2 is initialized to true, and the function VisualStateManager.GoToState has been called, the shadow effect is not shown.

This is what it looks like on startup.

The checkbox on the right indicates that option 2 is true, but the shadow effect is not present.

I am sure that I am missing one small piece of the puzzle. If it helps, I can upload the sample program.

I'm sorry if this is too much detail.

Body:
I think that I have found the answer.

I need to override the function OnApplyTemplate() in my custom control. I have extended the code of the CustomButton class with the following function:

public override void OnApplyTemplate()
{
  base.OnApplyTemplate();

  if ( IsChecked )
  {
    VisualStateManager.GoToState(this, "Checked", true);
  }
  else
  {
    VisualStateManager.GoToState(this, "Unchecked", true);
  }
}

I found this information in by reading the Microsoft documentation. With reference to the method OnApplyTemplate it states

This is the earliest that the FrameworkElement in the ControlTemplate is available to the control.


问:
Having an issue with Wordpress save_post
I am having an issue where when I save a post under a custom post type I created, tb_template, The below code runs fine except rather than creating a new post with the post_type tb_table_cache it is setting the post type to tb_template. I do not understand why this is happening because any place in this code where I am setting the post_type I have it hardcoded to tb_table_cache so I have no idea why it would not be saving the post_type as that.

One thing to note, the code is identical on both, but this issue is happening on my live site and not on my dev site.

Any help is appreciated.

This is ran under the save_post hook.

```<code>function build_template_table_cache( $post_id ) {

    $tb_tables = get_posts(array(
        'post_type' => 'tb_table',
        'numberposts' => -1,
        'post_status' => 'publish'
    ));

    if($tb_tables) {
      foreach($tb_tables as $tb_table) {
      $tb_table_template = get_field('tb_table_template', $tb_table->ID);
            if($tb_table_template) {

        if($tb_table_template->ID == $post_id) {
                  self::build_table_cache($post_id, $tb_table->ID, true);
        }

              wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly
            }
      }
  }

}

function build_table_cache($post_id, $thispostid = 0, $fromtemplate = false) {
$used_postid = $post_id;
if($fromtemplate) {
      $used_postid = $thispostid;
    }

$post_type = get_post_type($used_postid);
if ( "tb_table" != $post_type || wp_is_post_revision( $used_postid ) ) { return; }

$item_args = array();
$item_args['post_type'] = 'tb_table';
$item_args['post_status'] = 'publish';
$item_args['posts_per_page'] = 1;
$item_args['p'] = $used_postid;

$item_data = new WP_Query($item_args);
if ( $item_data->have_posts() ) {
      while ($item_data->have_posts()) {
        $item_data->the_post();
    $current_post_title = get_the_title();

            $template_object = get_field('tb_table_template');
            if($template_object) {
              $template_type = get_field('tb_table_template_type', $template_object->ID);
      if (empty($template_type)) { $template_type = "normal"; }

          $template = $template_object->post_content;
                $tb_plugin_url = plugin_dir_url(dirname(__FILE__));

                include(plugin_dir_path( dirname( __FILE__ ) ) . "includes/inc/function-table-builder-".$template_type.".php");

                $version_args = array(
                    'post_status'    => 'publish',
                  'post_type'      => 'tb_table_cache',
            'meta_key'       => 'tb_cache_version',
            'orderby'        => 'meta_value_num',
            'order'          => 'DESC',
            'posts_per_page' => 1,
                  'meta_query'   => array(
              array(
                'key' => 'tb_cache_parent',
                'value' => $used_postid,
                'compare' => '=',
              )
                  )
                );
                $version_query = new WP_Query($version_args);
                if ( $version_query->have_posts() ) {
                    while ($version_query->have_posts()) {
                        $version_query->the_post();
          $prev_version = get_post_meta(get_the_ID(), 'tb_cache_version', true);
          if(empty($prev_version)) { $prev_version = 0; }
          if($prev_version < 1) {
            $new_version = 1;
          } else {
            $new_version = $prev_version + 1;
          }
                  }
                } else {
                    $new_version = 1;
      }

                $cache_args = array(
                    'post_status'    => 'publish',
                    'post_type'      => 'tb_table_cache',
                    'post_author'    => get_current_user_id(),
                    'post_title'     => $current_post_title . " - Cache",
                    'post_content'   => $template,
                'meta_input'     => array(
                'tb_cache_parent'  => $used_postid,
                  'tb_cache_version' => $new_version,
                ),
                );

                $cache_post_id = wp_insert_post( $cache_args );
    } // if($template_object)

  } // while ($item_data->have_posts())
    } // if ( $item_data->have_posts() )

} // function build_table_cache( $post_id )
</code>```

Here is the creation of the post type.

```<code>public function tb_table_cache_post_type() {
    register_post_type(
    'tb_table_cache',
    array(
        'labels' => array(
            'name' => __('Table Caches'),
            'singular_name' => __('Table Cache'),
            'add_new_item' => __('Add New Table Cache'),
            'edit_item' => __('Edit Table Cache'),
            'view_item' => __('View Table Cache'),
            'search_items' =>  __('Search Table Caches'),
            'not_found' => __('No Table Caches found!'),
            'not_found_in_trash' => __('No Table Caches found in trash'),
            'menu_name' => __('Table Caches'),
            'all_items' => __('All Table Caches')
        ),
        'description' => 'I15 Table Caches',
        'public' => false,
        'show_ui' => true,
        'menu_position' => 20,
        'hierarchical' => true,
        'supports' => array('title', 'editor'),
        //'show_in_nav_menus' => false,
        'show_in_menu' => 'i15-table-builder',
        'can_export' => true,
        'has_archive' => false,
        'exclude_from_search' => true
    ));

}
</code>```

答:
I figured out the issue. The problem was that we have a plugin installed called Post Type Switcher and that plugin used a filter to change the post type. So I just added my own filter before the insert function and then removed that filter after the insert function.

For anyone curious.

```<code>add_filter( 'wp_insert_post_data', array( $this, 'tb_cache_override_type' ), 99, 2 );
$cache_post_id = wp_insert_post( $cache_args );
remove_filter( 'wp_insert_post_data', array( $this, 'tb_cache_override_type' ), 99, 2 );
</code>```

Body:
I am having an issue where when I save a post under a custom post type I created, tb_template, The below code runs fine except rather than creating a new post with the post_type tb_table_cache it is setting the post type to tb_template. I do not understand why this is happening because any place in this code where I am setting the post_type I have it hardcoded to tb_table_cache so I have no idea why it would not be saving the post_type as that.

One thing to note, the code is identical on both, but this issue is happening on my live site and not on my dev site.

Any help is appreciated.

This is ran under the save_post hook.

function build_template_table_cache( $post_id ) {

    $tb_tables = get_posts(array(
        'post_type' => 'tb_table',
        'numberposts' => -1,
        'post_status' => 'publish'
    ));

    if($tb_tables) {
      foreach($tb_tables as $tb_table) {
      $tb_table_template = get_field('tb_table_template', $tb_table->ID);
            if($tb_table_template) {

        if($tb_table_template->ID == $post_id) {
                  self::build_table_cache($post_id, $tb_table->ID, true);
        }

              wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly
            }
      }
  }

}

function build_table_cache($post_id, $thispostid = 0, $fromtemplate = false) {
$used_postid = $post_id;
if($fromtemplate) {
      $used_postid = $thispostid;
    }

$post_type = get_post_type($used_postid);
if ( "tb_table" != $post_type || wp_is_post_revision( $used_postid ) ) { return; }

$item_args = array();
$item_args['post_type'] = 'tb_table';
$item_args['post_status'] = 'publish';
$item_args['posts_per_page'] = 1;
$item_args['p'] = $used_postid;

$item_data = new WP_Query($item_args);
if ( $item_data->have_posts() ) {
      while ($item_data->have_posts()) {
        $item_data->the_post();
    $current_post_title = get_the_title();

            $template_object = get_field('tb_table_template');
            if($template_object) {
              $template_type = get_field('tb_table_template_type', $template_object->ID);
      if (empty($template_type)) { $template_type = "normal"; }

          $template = $template_object->post_content;
                $tb_plugin_url = plugin_dir_url(dirname(__FILE__));

                include(plugin_dir_path( dirname( __FILE__ ) ) . "includes/inc/function-table-builder-".$template_type.".php");

                $version_args = array(
                    'post_status'    => 'publish',
                  'post_type'      => 'tb_table_cache',
            'meta_key'       => 'tb_cache_version',
            'orderby'        => 'meta_value_num',
            'order'          => 'DESC',
            'posts_per_page' => 1,
                  'meta_query'   => array(
              array(
                'key' => 'tb_cache_parent',
                'value' => $used_postid,
                'compare' => '=',
              )
                  )
                );
                $version_query = new WP_Query($version_args);
                if ( $version_query->have_posts() ) {
                    while ($version_query->have_posts()) {
                        $version_query->the_post();
          $prev_version = get_post_meta(get_the_ID(), 'tb_cache_version', true);
          if(empty($prev_version)) { $prev_version = 0; }
          if($prev_version < 1) {
            $new_version = 1;
          } else {
            $new_version = $prev_version + 1;
          }
                  }
                } else {
                    $new_version = 1;
      }

                $cache_args = array(
                    'post_status'    => 'publish',
                    'post_type'      => 'tb_table_cache',
                    'post_author'    => get_current_user_id(),
                    'post_title'     => $current_post_title . " - Cache",
                    'post_content'   => $template,
                'meta_input'     => array(
                'tb_cache_parent'  => $used_postid,
                  'tb_cache_version' => $new_version,
                ),
                );

                $cache_post_id = wp_insert_post( $cache_args );
    } // if($template_object)

  } // while ($item_data->have_posts())
    } // if ( $item_data->have_posts() )

} // function build_table_cache( $post_id )

Here is the creation of the post type.

public function tb_table_cache_post_type() {
    register_post_type(
    'tb_table_cache',
    array(
        'labels' => array(
            'name' => __('Table Caches'),
            'singular_name' => __('Table Cache'),
            'add_new_item' => __('Add New Table Cache'),
            'edit_item' => __('Edit Table Cache'),
            'view_item' => __('View Table Cache'),
            'search_items' =>  __('Search Table Caches'),
            'not_found' => __('No Table Caches found!'),
            'not_found_in_trash' => __('No Table Caches found in trash'),
            'menu_name' => __('Table Caches'),
            'all_items' => __('All Table Caches')
        ),
        'description' => 'I15 Table Caches',
        'public' => false,
        'show_ui' => true,
        'menu_position' => 20,
        'hierarchical' => true,
        'supports' => array('title', 'editor'),
        //'show_in_nav_menus' => false,
        'show_in_menu' => 'i15-table-builder',
        'can_export' => true,
        'has_archive' => false,
        'exclude_from_search' => true
    ));

}

Body:
I figured out the issue. The problem was that we have a plugin installed called Post Type Switcher and that plugin used a filter to change the post type. So I just added my own filter before the insert function and then removed that filter after the insert function.

For anyone curious.

add_filter( 'wp_insert_post_data', array( $this, 'tb_cache_override_type' ), 99, 2 );
$cache_post_id = wp_insert_post( $cache_args );
remove_filter( 'wp_insert_post_data', array( $this, 'tb_cache_override_type' ), 99, 2 );


问:
Weird behaviour of direction property in CSS
I was just playing around with CSS on Codepen with auto-save mode enabled when I encountered this weird behaviour,

Here's my code-

var inner_div = document.querySelector('.inner-div');
var width = inner_div.offsetWidth;
if(width > 200)
  {
    inner_div.style.fontSize = '20px';
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.outer-div {
    display: flex;
    height: 3.5em;
    width: 10%;
    border: 2px solid #000000a3;
    margin-left: 200px;
    align-items: center;
    border: 1px solid green;
    direction: rtl;
    white-space: nowrap;
    overflow-x: auto;
}
.inner-div {
    font-size: 40px;
}</code>```

       Hello World

```

As my auto-save mode was enabled, I was checking with each key press whether the text is being appended from right to left or not, but when I press slash(/), or any of the arithmetic operators(+, -, *), then these are first appended on the left first and then if the next keypress is alphanumeric then it appends it automatically to the right of the expression.
For e.g., if I type c, then b, then a, then it gets displayed as 'abc'(as desired from direction: rtl property), but if I then type slash(/), then the display is /abc, and then if I type any alphanumeric character, say d, then it displays abc/d .
Could someone explain me the reason for this. Thanks.

答:
I could not reproduce the behavior you describe. The direction tag alone will not change the way

```<code>abc
</code>```

is displayed. You were not typing c, then b and a.

The behavior you described happens when you type a, b, and, finally, c. If you type RTL characters, e.g. #x0627;بة - you will see ا ب ة appear from right to left. Note that this will work as well if you don't specify rtl direction. Also, the slash will appear on the left - no matter how you choose the direction.

You can achieve interesting effects if you add the unicode-bidi tag to your CSS.

Body:
I was just playing around with CSS on Codepen with auto-save mode enabled when I encountered this weird behaviour,

Here's my code-

var inner_div = document.querySelector('.inner-div');
var width = inner_div.offsetWidth;
if(width > 200)
  {
    inner_div.style.fontSize = '20px';
  }

.outer-div {
    display: flex;
    height: 3.5em;
    width: 10%;
    border: 2px solid #000000a3;
    margin-left: 200px;
    align-items: center;
    border: 1px solid green;
    direction: rtl;
    white-space: nowrap;
    overflow-x: auto;
}
.inner-div {
    font-size: 40px;
}

       Hello World

As my auto-save mode was enabled, I was checking with each key press whether the text is being appended from right to left or not, but when I press slash(/), or any of the arithmetic operators(+, -, *), then these are first appended on the left first and then if the next keypress is alphanumeric then it appends it automatically to the right of the expression.
For e.g., if I type c, then b, then a, then it gets displayed as 'abc'(as desired from direction: rtl property), but if I then type slash(/), then the display is /abc, and then if I type any alphanumeric character, say d, then it displays abc/d .
Could someone explain me the reason for this. Thanks.

Body:
I could not reproduce the behavior you describe. The direction tag alone will not change the way

abc

is displayed. You were not typing c, then b and a.

The behavior you described happens when you type a, b, and, finally, c. If you type RTL characters, e.g. #x0627;&#x0628;&#x0629; - you will see ا ب ة appear from right to left. Note that this will work as well if you don't specify rtl direction. Also, the slash will appear on the left - no matter how you choose the direction.

You can achieve interesting effects if you add the unicode-bidi tag to your CSS.


问:
How to stop showing a blank page when going to next fragment
For what I did is first to create a tapBar (Activity). Then under Activity, I have first, second and third fragments. I am trying to move to next fragment from first fragment but I get a blank page (since it is not blue color which I set in xml). Any suggestions?

Activity

```<code>public class TabBar extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tabbar);
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        SimpleFragmentPagerAdapter adapter = new SimpleFragmentPagerAdapter(this, getSupportFragmentManager());
        viewPager.setAdapter(adapter);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
        tabLayout.setupWithViewPager(viewPager);
    }
}
</code>```

First fragment

```<code>public class First extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.first, null);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Fragment fragment = new Next();
                FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.hide(First.this);
                fragmentTransaction.show(fragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
            }
        });
    return rootView;
}
</code>```

Next Fragment

```<code>public class Next extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.next, container, false);
        return rootView;
    }
}
</code>```

Next Fragment XML

```<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:background="@color/avoscloud_blue">
</RelativeLayout>
</code>```

答:
Try to use this method to change the fragment:

```<code>public void changeFragment() {
    Fragment fragment = new Next();
    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction transaction = fm.beginTransaction();
    transaction.replace(R.id.your_layout_id, fragment);
    transaction.commit();
}
</code>```

Body:
For what I did is first to create a tapBar (Activity). Then under Activity, I have first, second and third fragments. I am trying to move to next fragment from first fragment but I get a blank page (since it is not blue color which I set in xml). Any suggestions?

Activity

public class TabBar extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tabbar);
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        SimpleFragmentPagerAdapter adapter = new SimpleFragmentPagerAdapter(this, getSupportFragmentManager());
        viewPager.setAdapter(adapter);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
        tabLayout.setupWithViewPager(viewPager);
    }
}

First fragment

public class First extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.first, null);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Fragment fragment = new Next();
                FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.hide(First.this);
                fragmentTransaction.show(fragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
            }
        });
    return rootView;
}

Next Fragment

public class Next extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.next, container, false);
        return rootView;
    }
}

Next Fragment XML

<?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:background="@color/avoscloud_blue">
</RelativeLayout>

Body:
Try to use this method to change the fragment:

public void changeFragment() {
    Fragment fragment = new Next();
    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction transaction = fm.beginTransaction();
    transaction.replace(R.id.your_layout_id, fragment);
    transaction.commit();
}


答:
You should add .add(R.id.

FragmentTransaction add (int containerViewId,
                  Fragment fragment)

```<code> button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view)
            {
                Next childFrag = new Next ();
                getFragmentManager().beginTransaction().add(R.id.frame_child_fragment, childFrag)
                .addToBackStack(null)
                .commit();
            }
        });
</code>```

Read Nested Fragments for better information.

Edit

You should set DEFAULT tab

```<code>tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(0); // 0 is FIRST
</code>```

Create a FrameLayout in R.layout.first

```<code><FrameLayout
        android:id="@+id/frame_child_fragment"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        />
</code>```

Title: How to stop showing a blank page when going to next fragment

Body:
You should add .add(R.id.

FragmentTransaction add (int containerViewId,
                  Fragment fragment)

 button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view)
            {
                Next childFrag = new Next ();
                getFragmentManager().beginTransaction().add(R.id.frame_child_fragment, childFrag)
                .addToBackStack(null)
                .commit();
            }
        });

Read Nested Fragments for better information.

Edit

You should set DEFAULT tab

tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(0); // 0 is FIRST

Create a FrameLayout in R.layout.first

<FrameLayout
        android:id="@+id/frame_child_fragment"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        />


问:
React-Bootstrap-Typeahead allowNew select-on-blur
Is it possible to configure this so when allowNew is set that any new entry in this field would be selected on blur rather than clicking on the new item "menu"

EDITED:
This is my existing child component

```<code><Typeahead
   labelKey="label"
   allowNew
   selectHintOnEnter
   options={props.campaignOptions}
   placeholder="Campaign Name..."
   onChange={props.campaignName}
 />
</code>```

And this is my parent component...

```<code>campaignName (campaign){
  campaign.length ? this.setState({campaignSelected:campaign}) : this.setState({campaignSelected:''})
  }
</code>```

...

```<code><FormGroup>
    <Campaign
     campaignName={this.campaignName.bind(this)}
     campaignOptions={[...new Set(this.props.records.map(options => options.campaign))]}/>
 </FormGroup>
</code>```

答:
Thanks for the advice, but I managed to get this to work with a much simpler approach that means that I don't need to use onBlur and I just store the onInputChange in the state in the parent. </p>

```<code>  const {campaignOptions, campaignValue, campaignName} = this.props;

  ...

<Typeahead
    labelKey="label"
      allowNew
      placeholder="Campaign Name..."
      onInputChange={campaignName}
      options={campaignOptions}
      selected={campaignValue}
/>
</code>```

Body:
Is it possible to configure this so when allowNew is set that any new entry in this field would be selected on blur rather than clicking on the new item "menu"

EDITED:
This is my existing child component

<Typeahead
   labelKey="label"
   allowNew
   selectHintOnEnter
   options={props.campaignOptions}
   placeholder="Campaign Name..."
   onChange={props.campaignName}
 />

And this is my parent component...

campaignName (campaign){
  campaign.length ? this.setState({campaignSelected:campaign}) : this.setState({campaignSelected:''})
  }

...

<FormGroup>
    <Campaign
     campaignName={this.campaignName.bind(this)}
     campaignOptions={[...new Set(this.props.records.map(options => options.campaign))]}/>
 </FormGroup>

Body:
Thanks for the advice, but I managed to get this to work with a much simpler approach that means that I don't need to use onBlur and I just store the onInputChange in the state in the parent.

  const {campaignOptions, campaignValue, campaignName} = this.props;

  ...

<Typeahead
    labelKey="label"
      allowNew
      placeholder="Campaign Name..."
      onInputChange={campaignName}
      options={campaignOptions}
      selected={campaignValue}
/>


问:
DOMException: Failed to execute 'texImage2D' on 'WebGLRenderingContext': The cross-origin image at "https://xxxx.xxxx" may not be loaded

Chrome shows:

DOMException: Failed to execute 'texImage2D' on 'WebGLRenderingContext': The cross-origin image at "https://xxxx.xxxx/models/skin.png " may not be loaded.

The project work like this:

--index.html

   --live2d.js

   --models (folder)

   ---| model.json

   ---| skin.png

This model.json defined the pictures needed in the model, and the live2d.js get data from model.json and make the model animate.

If I put these in my main domain, everything works well, but when I tried to load these from my CDN domain (means load only index.html from maindomain, but load other files from CDN), I got this:

enter image description here

But as you can see, although I belive I've set cross-origin of CDN server well, and the live2d.js and model.json load from CDN domain normally, only the picture getting wrong.

I've searched for a while, like this, but my problem is pretty different, cause all my files were load from a server, include index.html.

答:
I also had the same problem and I fixed it by setting the crossorigin for the loader which is used to load and parse the obj file.

Like this,

```<code>loader.setCrossOrigin ( value )
</code>```

Suppose if you are using ObjectLoader, set the crossorigin like this,

```<code>var loader = new THREE.ObjectLoader();
loader.setCrossOrigin ( 'anonymous' ):
</code>```

Body:
I also had the same problem and I fixed it by setting the crossorigin for the loader which is used to load and parse the obj file.

Like this,

loader.setCrossOrigin ( value )

Suppose if you are using ObjectLoader, set the crossorigin like this,

var loader = new THREE.ObjectLoader();
loader.setCrossOrigin ( 'anonymous' ):