问:
Inquiry/Response, Yes/No interface with Javascript/jQuery
I am a noob in the StackOverflow community, as we as a javascript/jquery noob. I am trying to put together a chat interface which would resemble SMS text messages. I am currently allowing user to enter text input, and have javascript look out for specified keywords (Yes/No) and show a specific hidden div in my html to simulate a response.

I have been trying to leverage a CodePen example (https://codepen.io/adobewordpress/pen/wGGMaV) which has gotten me pretty far. But I am also looking for duplicate Yes/No responses from the user, which if the user says "Yes" to multiple questions, javascript is serving up the FIRST Yes/No response.

I need a way to wrap my questions and look for specific user input answer per question, once input is received, serve the correct response- THEN move to the next question, which will also look for a Yes/No response from the user. Upon their response then serve question 2 response from javascript. Move on to Question 3, look for Yes/No response. Etc.

Any and all help is much appreciated. Hopefully even as a noob I can understand and work through any helpful responses.

My current CodePen (https://codepen.io/therise03/pen/bYXVLK) is using the above explaination of logic, but would like it to be using my condition workflow as typed out below.

Desired flow:

Condition1 [
    Question: Would you like to continue your magazine subscription? Text CONTINUE to continue or NO to stop {

```<code>If Yes: go to Condition2
If No: “Thanks you are not subscribed”
</code>```

}]

Condition2 [
    Question: Your total will be $XXXX.XX. Would you like to pay for your order with your card on file? Text YES to continue or NO to stop. {

```<code>If Yes: go to Condition3
If No: “OK we will not use card on file”
</code>```

]

Condition3 [
    Question3: We need to confirm your shipping address for this order.  Is 123 Main Street; O’Fallon, MO  63368 correct? Text YES to continue or NO to stop. {

```<code>If Yes: “OK address confirmed”
If No: “Address not confirmed”
</code>```

]

答:
After our conversation in the comments, I thought I'd submit an answer.

I thought it would be a good exercise for me to build a solution for this, while not clean, it works and you can improve it.

I have only made changes to the JS from your codepen.

codepen: codepen.io/anon/pen/POMbNw?editors=0010

Here is the code in case that codepen is not available anymore:

js:

```<code>/* START: HELPERS */

function appendFromThem(msg){ // append a "fromThem" msg
  $('<div class="message"><div class="fromThem"><p>'+msg+'</p></div></div>').insertAfter('.message:last');
}

function appendFromMe(msg){ // append a "myMessage" msg
  $('form.chat div.messages').append('<div class="message"><div class="myMessage"><p>' + msg + '</p></div></div>');
}

function isString(str){ // check if param is a string
  return jQuery.type(str) === "string";
}

function areEqual(str1, str2){ // check if strings are the same after trimming and setting to lower case
  if(!isString(str1) || !isString(str1)) return str1 === str2; // either of them is not a string, use the normal "==="
  return str1.trim().toLowerCase() === str2.trim().toLowerCase();
}

/* END: HELPERS */

// workflow types
var WF_TYPE = {
  Q: "question",
  END: "end",
  NEW: "new" // start new workflow after cuttent one
}

/*
 * The workflow object
 * each sub-object should have a "msg" and responses typically "yes" and "no"
 */
var wf = {
  type:WF_TYPE.Q,
  msg:"Would you like to continue your magazine subscription? Text CONTINUE to continue or NO to stop.",
  continue:{
    type: WF_TYPE.Q,
    msg:"Your total will be $XXXX.XX. Would you like to pay for your order with your card on file? Text YES to continue or NO to stop.",
    yes:{
      type:WF_TYPE.Q,
      msg:"We need to confirm your shipping address for this order.  Is 123 Main Street; O’Fallon, MO  63368 correct? Text YES to continue or NO to stop.",
      yes: {
        endMsg: "OK address confirmed",
        msg: "some new question?",
        type : WF_TYPE.NEW,
        yes:{
          msg: "OK cool.",
          type: WF_TYPE.END
        },
        no:{
          msg: "NOT cool...",
          type: WF_TYPE.END
        }

      },
      no: {
        msg:"Address not confirmed",
        type:WF_TYPE.END
      }
    },
    no:{
      msg: "OK we will not use card on file",
      type: WF_TYPE.END
    }
  },
  no:{
    msg:"Thanks you are not subscribed",
    type: WF_TYPE.END
  }
}

/*
 * Transitions current workflow to the next based on user response
 * @param msgFromUser the msg that user typed
 * @returns a response object containing the new workflow, response and other options
 */
function transition(currentWorkflow, msgFromUser){
  console.log('getResponse start', currentWorkflow, msgFromUser);
  if (currentWorkflow.type === WF_TYPE.END){
    return {
      wf: $.extend({}, currentWorkflow)
    }
  }
  else if (currentWorkflow.type === WF_TYPE.Q){
    var newWorkflow;
    var found = false; // if a user reponse was found in current workflow
    $.each(currentWorkflow, function(key, val){
      if(!found && key !== "msg" && areEqual(key, msgFromUser)){ // check if user msg matches any of the valid responses
        newWorkflow = $.extend({}, val); // cone the value
        console.log("found it", newWorkflow)
        found = true;
      }
    });

    return {
      wf: newWorkflow ? newWorkflow : $.extend({}, currentWorkflow),
      errorResponse: found ? undefined : "Sorry, we didn’t understand your response. Please try again."
    }
  }
  else if(currentWorkflow.type === WF_TYPE.NEW){
    return {
      wf: $.extend({}, currentWorkflow)
    }
  }
}

function scrollDown() {
  var focusBottom = document.getElementById("textMessage");
  focusBottom.scrollTop = focusBottom.scrollHeight;
}

$("input").keypress(function(event) {
  if (event.which == 13) { // if user clicked enter, submit
    event.preventDefault();
    $('form.chat input[type="submit"]').click();
  }
});

//appendFromThem(wf.msg);
$('form.chat input[type="submit"]').click(function(event) {
  $input = $('form.chat input[type="text"]');
  event.preventDefault();
  var message = $input.val();
  appendFromMe(message);
  $defered = $.Deferred();
  var responseAndWf = transition(wf, message); // get response from workflow
  if(responseAndWf){
     wf = responseAndWf.wf;
     var response = responseAndWf.errorResponse ? responseAndWf.errorResponse : wf.msg;
     setTimeout(function() {
       if(wf.type !== WF_TYPE.NEW){
         appendFromThem(response);
       }
       scrollDown();
       $defered.resolve();
     }, 1500);
  }

  if(wf.type === WF_TYPE.NEW){

    $defered.then(function(){
      appendFromThem(wf.endMsg);
      wf.type = WF_TYPE.Q;
      setTimeout(function() {
      appendFromThem(wf.msg);
      },2000)
    });
  }
  $input.val('');
  scrollDown();
});
</code>```

CSS:

```<code>input, textarea, [contenteditable] {
    color: #666;
    caret-color: blue;
}

body {
    background: #fff; /* For browsers that do not support gradients */
    font-family: 'Rubik';
    font-weight: 300;
    color: #fff;
    font-size:16px;

}

h1 {
    color: #fff;
    font-family: 'Rubik';
    font-weight: 400;
}

::-webkit-input-placeholder { /* WebKit, Blink, Edge */
 color:    #cdced2;
}
:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
 color:    #cdced2;
 opacity:  1;
}
::-moz-placeholder { /* Mozilla Firefox 19+ */
 color:    #cdced2;
 opacity:  1;
}
:-ms-input-placeholder { /* Internet Explorer 10-11 */
 color:    #cdced2;
}
::-ms-input-placeholder { /* Microsoft Edge */
 color:    #cdced2;
}
form.chat .myMessage, form.chat .fromThem {
    max-width: 90%;
}

form.chat *{
  transition:all .5s;
  box-sizing:border-box;
  -webkit-box-sizing:border-box;
  -moz-box-sizing:border-box;
}

form.chat {
  margin:0;
  cursor:default;
  position:absolute;
  left:0;
  right:0;
  bottom:0;
  top:0;
  -webkit-touch-callout: none; /* iOS Safari */
  -webkit-user-select: none;   /* Chrome/Safari/Opera */
  -khtml-user-select: none;    /* Konqueror */
  -moz-user-select: none;      /* Firefox */
  -ms-user-select: none;       /* IE/Edge */
  user-select: none;
    border:0 none;
}

form.chat span.spinner{
  -moz-animation: loading-bar 1s 1;
  -webkit-animation: loading-bar 1s 1;
  animation: loading-bar 1s 1;
  display: block;
  height: 2px;
  background-color: #00e34d;
  transition: width 0.2s;
  position:absolute;
  top:0; left:0; right:0;
  z-index:4
}

form.chat .messages{
  display:block;
  overflow-x: hidden;
  overflow-y: scroll;
  position:relative;
  height:90%;
  width:100%;
  padding:1% 3% 7% 3%;
  border:0 none;

}

form.chat ::-webkit-scrollbar {width: 3px; height:1px;transition:all .5s;z-index:10;}
form.chat ::-webkit-scrollbar-track {background-color: white;}
form.chat ::-webkit-scrollbar-thumb {
  background-color: #bec4c8;
  border-radius:3px;
}

form.chat .message{
  display:block;
  width:98%;
  padding:0.5%;
}

form.chat .message p{
  margin:0;
}

form.chat .myMessage,
form.chat .fromThem {
  max-width: 50%;
  word-wrap: break-word;
  margin-bottom: 20px;
}

form.chat .myMessage,.fromThem{
  position: relative;
  padding: 10px 20px;
  color: white;
  border-radius: 25px;
  clear: both;
  font: 400 15px 'Open Sans', sans-serif;
}

form.chat .myMessage {
  background: #00e34d;
  color:white;
  float:right;
  clear:both;
  border-bottom-right-radius: 20px 0px\9;
}

form.chat .myMessage:before {
  content: "";
  position: absolute;
  z-index: 1;
  bottom: -2px;
  right: -8px;
  height: 19px;
  border-right: 20px solid #00e34d;
  border-bottom-left-radius: 16px 14px;
  -webkit-transform: translate(0, -2px);
  transform: translate(0, -2px);
  border-bottom-left-radius: 15px 0px\9;
  transform: translate(-1px, -2px)\9;
}

form.chat .myMessage:after {
  content: "";
  position: absolute;
  z-index: 1;
  bottom: -2px;
  right: -42px;
  width: 12px;
  height: 20px;
  background: white;
  border-bottom-left-radius: 10px;
  -webkit-transform: translate(-30px, -2px);
  transform: translate(-30px, -2px);
}

form.chat .fromThem {
  background: #E5E5EA;
  color: black;
  float: left;
  clear:both;
  border-bottom-left-radius: 30px 0px\9;
}
form.chat .fromThem:before {
  content: "";
  position: absolute;
  z-index: 2;
  bottom: -2px;
  left: -7px;
  height: 19px;
  border-left: 20px solid #E5E5EA;
  border-bottom-right-radius: 16px 14px;
  -webkit-transform: translate(0, -2px);
  transform: translate(0, -2px);
  border-bottom-right-radius: 15px 0px\9;
  transform: translate(-1px, -2px)\9;
}

form.chat .fromThem:after {
  content: "";
  position: absolute;
  z-index: 3;
  bottom: -2px;
  left: 4px;
  width: 26px;
  height: 20px;
  background: white;
  border-bottom-right-radius: 10px;
  -webkit-transform: translate(-30px, -2px);
  transform: translate(-30px, -2px);
}

form.chat date {
  position:absolute;
  top: 10px;
  font-size:14px;
  white-space:nowrap;
  vertical-align:middle;
  color: #8b8b90;
  opacity: 0;
  z-index:4;
}

form.chat .myMessage date {
  left: 105%;
}

form.chat .fromThem date {
  right: 105%;
}

form.chat input{
  /* font: 400 13px 'Open Sans', sans-serif; */
  font: 400 1em 'Open Sans', sans-serif;
    border:0;
 /* padding:0 15px; */
    padding: 15px 15px 0 15px;
  height:10%;
  outline:0;
}

form.chat input[type='text']{
  width:73%;
  float:left;
}

form.chat input[type='submit']{
  width:23%;
  background:transparent;
  color:#00E34D;
  font-weight:700;
  text-align:right;
  float:right;
}

  form.chat .myMessage,form.chat .fromThem{
    font-size:1.1em;

  }

  form.chat .myMessage,
  form.chat .fromThem {
    max-width: 90%;
  }

@-moz-keyframes loading-bar {
  0% {
    width: 0%;
  }
  90% {
    width: 90%;
  }
  100% {
    width: 100%;
  }
}

@-webkit-keyframes loading-bar {
  0% {
    width: 0%;
  }
  90% {
    width: 90%;
  }
  100% {
    width: 100%;
  }
}

@keyframes loading-bar {
  0% {
    width: 0%;
  }
  90% {
    width: 90%;
  }
  100% {
    width: 100%;
  }
}

/* DEMO */
.iphone{
  /*
    width:300px;
  height:609px;
  background-image:url('http://www.adobewordpress.com/tasarim/images/iphone6.png');
  background-size:100% 100%;
  margin:0 auto;
    */
    width:100%;

}

.border{
    /* position:absolute;
    top:12.3%;right:7%;left:7%;bottom:12%;
    overflow:hidden; */
}

a.article{
  position:fixed;
  bottom:15px;left:15px;
  display:table;
  text-decoration:none;
  color:white;
  background-color:#00e34d;
  padding: 10px 20px;
  border-radius: 25px;
  font: 400 15px 'Open Sans', sans-serif;
}
</code>```

HTML:

```<code><div class="iphone">
  <div class="imessage-header"></div>
  <div class="border">
    <form class="chat">
      <span></span>
      <div class="messages" id="textMessage">
        <div class="message">
          <div class="fromThem">
            <p>Would you like to continue your magazine subscription? Text CONTINUE to continue or NO to stop.</p>
          </div>
        </div>
        <div class="message magPrice" style="display:none;">
          <div class="fromThem new">
            <p>Your total will be $XXXX.XX. Would you like to pay for your order with your card on file? Text YES to continue or NO to stop.</p>
          </div>
        </div>
        <div class="message addressVerification" style="display:none;">
          <div class="fromThem new">
            <p>We need to confirm your shipping address for this order.  Is 123 Main Street; O’Fallon, MO  63368 correct? Text YES to continue or NO to stop.</p>
          </div>
        </div>
        <div class="message goToWeb" style="display:none;">
          <div class="fromThem new">
              <p>To change your shipping address go to this <a href="#">website</a>.</p>
          </div>
        </div>
      </div>
      <div style="position:fixed;bottom:0;left:0;border:1px solid #ddd;width:100%;z-index:101;background-color:#fff;height:50px;">
        <input type="text" placeholder="Your message" autofocus style="height:auto;">
        <input type="submit" value="Send" style="height:auto;">
      </div>
    </form>
  </div>
</div>
</code>```

Body:
I am a noob in the StackOverflow community, as we as a javascript/jquery noob. I am trying to put together a chat interface which would resemble SMS text messages. I am currently allowing user to enter text input, and have javascript look out for specified keywords (Yes/No) and show a specific hidden div in my html to simulate a response.

I have been trying to leverage a CodePen example (https://codepen.io/adobewordpress/pen/wGGMaV) which has gotten me pretty far. But I am also looking for duplicate Yes/No responses from the user, which if the user says "Yes" to multiple questions, javascript is serving up the FIRST Yes/No response.

I need a way to wrap my questions and look for specific user input answer per question, once input is received, serve the correct response- THEN move to the next question, which will also look for a Yes/No response from the user. Upon their response then serve question 2 response from javascript. Move on to Question 3, look for Yes/No response. Etc.

Any and all help is much appreciated. Hopefully even as a noob I can understand and work through any helpful responses.

My current CodePen (https://codepen.io/therise03/pen/bYXVLK) is using the above explaination of logic, but would like it to be using my condition workflow as typed out below.

Desired flow:

Condition1 [
    Question: Would you like to continue your magazine subscription? Text CONTINUE to continue or NO to stop {

If Yes: go to Condition2
If No: “Thanks you are not subscribed”

}]

Condition2 [
    Question: Your total will be $XXXX.XX. Would you like to pay for your order with your card on file? Text YES to continue or NO to stop. {

If Yes: go to Condition3
If No: “OK we will not use card on file”

]

Condition3 [
    Question3: We need to confirm your shipping address for this order.  Is 123 Main Street; O’Fallon, MO  63368 correct? Text YES to continue or NO to stop. {

If Yes: “OK address confirmed”
If No: “Address not confirmed”

]

Body:
After our conversation in the comments, I thought I'd submit an answer.

I thought it would be a good exercise for me to build a solution for this, while not clean, it works and you can improve it.

I have only made changes to the JS from your codepen.

codepen: codepen.io/anon/pen/POMbNw?editors=0010

Here is the code in case that codepen is not available anymore:

js:

/* START: HELPERS */

function appendFromThem(msg){ // append a "fromThem" msg
  $('<div class="message"><div class="fromThem"><p>'+msg+'</p></div></div>').insertAfter('.message:last');
}

function appendFromMe(msg){ // append a "myMessage" msg
  $('form.chat div.messages').append('<div class="message"><div class="myMessage"><p>' + msg + '</p></div></div>');
}

function isString(str){ // check if param is a string
  return jQuery.type(str) === "string";
}

function areEqual(str1, str2){ // check if strings are the same after trimming and setting to lower case
  if(!isString(str1) || !isString(str1)) return str1 === str2; // either of them is not a string, use the normal "==="
  return str1.trim().toLowerCase() === str2.trim().toLowerCase();
}

/* END: HELPERS */

// workflow types
var WF_TYPE = {
  Q: "question",
  END: "end",
  NEW: "new" // start new workflow after cuttent one
}

/*
 * The workflow object
 * each sub-object should have a "msg" and responses typically "yes" and "no"
 */
var wf = {
  type:WF_TYPE.Q,
  msg:"Would you like to continue your magazine subscription? Text CONTINUE to continue or NO to stop.",
  continue:{
    type: WF_TYPE.Q,
    msg:"Your total will be $XXXX.XX. Would you like to pay for your order with your card on file? Text YES to continue or NO to stop.",
    yes:{
      type:WF_TYPE.Q,
      msg:"We need to confirm your shipping address for this order.  Is 123 Main Street; O’Fallon, MO  63368 correct? Text YES to continue or NO to stop.",
      yes: {
        endMsg: "OK address confirmed",
        msg: "some new question?",
        type : WF_TYPE.NEW,
        yes:{
          msg: "OK cool.",
          type: WF_TYPE.END
        },
        no:{
          msg: "NOT cool...",
          type: WF_TYPE.END
        }

      },
      no: {
        msg:"Address not confirmed",
        type:WF_TYPE.END
      }
    },
    no:{
      msg: "OK we will not use card on file",
      type: WF_TYPE.END
    }
  },
  no:{
    msg:"Thanks you are not subscribed",
    type: WF_TYPE.END
  }
}

/*
 * Transitions current workflow to the next based on user response
 * @param msgFromUser the msg that user typed
 * @returns a response object containing the new workflow, response and other options
 */
function transition(currentWorkflow, msgFromUser){
  console.log('getResponse start', currentWorkflow, msgFromUser);
  if (currentWorkflow.type === WF_TYPE.END){
    return {
      wf: $.extend({}, currentWorkflow)
    }
  }
  else if (currentWorkflow.type === WF_TYPE.Q){
    var newWorkflow;
    var found = false; // if a user reponse was found in current workflow
    $.each(currentWorkflow, function(key, val){
      if(!found && key !== "msg" && areEqual(key, msgFromUser)){ // check if user msg matches any of the valid responses
        newWorkflow = $.extend({}, val); // cone the value
        console.log("found it", newWorkflow)
        found = true;
      }
    });

    return {
      wf: newWorkflow ? newWorkflow : $.extend({}, currentWorkflow),
      errorResponse: found ? undefined : "Sorry, we didn’t understand your response. Please try again."
    }
  }
  else if(currentWorkflow.type === WF_TYPE.NEW){
    return {
      wf: $.extend({}, currentWorkflow)
    }
  }
}

function scrollDown() {
  var focusBottom = document.getElementById("textMessage");
  focusBottom.scrollTop = focusBottom.scrollHeight;
}

$("input").keypress(function(event) {
  if (event.which == 13) { // if user clicked enter, submit
    event.preventDefault();
    $('form.chat input[type="submit"]').click();
  }
});

//appendFromThem(wf.msg);
$('form.chat input[type="submit"]').click(function(event) {
  $input = $('form.chat input[type="text"]');
  event.preventDefault();
  var message = $input.val();
  appendFromMe(message);
  $defered = $.Deferred();
  var responseAndWf = transition(wf, message); // get response from workflow
  if(responseAndWf){
     wf = responseAndWf.wf;
     var response = responseAndWf.errorResponse ? responseAndWf.errorResponse : wf.msg;
     setTimeout(function() {
       if(wf.type !== WF_TYPE.NEW){
         appendFromThem(response);
       }
       scrollDown();
       $defered.resolve();
     }, 1500);
  }

  if(wf.type === WF_TYPE.NEW){

    $defered.then(function(){
      appendFromThem(wf.endMsg);
      wf.type = WF_TYPE.Q;
      setTimeout(function() {
      appendFromThem(wf.msg);
      },2000)
    });
  }
  $input.val('');
  scrollDown();
});

CSS:

input, textarea, [contenteditable] {
    color: #666;
    caret-color: blue;
}

body {
    background: #fff; /* For browsers that do not support gradients */
    font-family: 'Rubik';
    font-weight: 300;
    color: #fff;
    font-size:16px;

}

h1 {
    color: #fff;
    font-family: 'Rubik';
    font-weight: 400;
}

::-webkit-input-placeholder { /* WebKit, Blink, Edge */
 color:    #cdced2;
}
:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
 color:    #cdced2;
 opacity:  1;
}
::-moz-placeholder { /* Mozilla Firefox 19+ */
 color:    #cdced2;
 opacity:  1;
}
:-ms-input-placeholder { /* Internet Explorer 10-11 */
 color:    #cdced2;
}
::-ms-input-placeholder { /* Microsoft Edge */
 color:    #cdced2;
}
form.chat .myMessage, form.chat .fromThem {
    max-width: 90%;
}

form.chat *{
  transition:all .5s;
  box-sizing:border-box;
  -webkit-box-sizing:border-box;
  -moz-box-sizing:border-box;
}

form.chat {
  margin:0;
  cursor:default;
  position:absolute;
  left:0;
  right:0;
  bottom:0;
  top:0;
  -webkit-touch-callout: none; /* iOS Safari */
  -webkit-user-select: none;   /* Chrome/Safari/Opera */
  -khtml-user-select: none;    /* Konqueror */
  -moz-user-select: none;      /* Firefox */
  -ms-user-select: none;       /* IE/Edge */
  user-select: none;
    border:0 none;
}

form.chat span.spinner{
  -moz-animation: loading-bar 1s 1;
  -webkit-animation: loading-bar 1s 1;
  animation: loading-bar 1s 1;
  display: block;
  height: 2px;
  background-color: #00e34d;
  transition: width 0.2s;
  position:absolute;
  top:0; left:0; right:0;
  z-index:4
}

form.chat .messages{
  display:block;
  overflow-x: hidden;
  overflow-y: scroll;
  position:relative;
  height:90%;
  width:100%;
  padding:1% 3% 7% 3%;
  border:0 none;

}

form.chat ::-webkit-scrollbar {width: 3px; height:1px;transition:all .5s;z-index:10;}
form.chat ::-webkit-scrollbar-track {background-color: white;}
form.chat ::-webkit-scrollbar-thumb {
  background-color: #bec4c8;
  border-radius:3px;
}

form.chat .message{
  display:block;
  width:98%;
  padding:0.5%;
}

form.chat .message p{
  margin:0;
}

form.chat .myMessage,
form.chat .fromThem {
  max-width: 50%;
  word-wrap: break-word;
  margin-bottom: 20px;
}

form.chat .myMessage,.fromThem{
  position: relative;
  padding: 10px 20px;
  color: white;
  border-radius: 25px;
  clear: both;
  font: 400 15px 'Open Sans', sans-serif;
}

form.chat .myMessage {
  background: #00e34d;
  color:white;
  float:right;
  clear:both;
  border-bottom-right-radius: 20px 0px\9;
}

form.chat .myMessage:before {
  content: "";
  position: absolute;
  z-index: 1;
  bottom: -2px;
  right: -8px;
  height: 19px;
  border-right: 20px solid #00e34d;
  border-bottom-left-radius: 16px 14px;
  -webkit-transform: translate(0, -2px);
  transform: translate(0, -2px);
  border-bottom-left-radius: 15px 0px\9;
  transform: translate(-1px, -2px)\9;
}

form.chat .myMessage:after {
  content: "";
  position: absolute;
  z-index: 1;
  bottom: -2px;
  right: -42px;
  width: 12px;
  height: 20px;
  background: white;
  border-bottom-left-radius: 10px;
  -webkit-transform: translate(-30px, -2px);
  transform: translate(-30px, -2px);
}

form.chat .fromThem {
  background: #E5E5EA;
  color: black;
  float: left;
  clear:both;
  border-bottom-left-radius: 30px 0px\9;
}
form.chat .fromThem:before {
  content: "";
  position: absolute;
  z-index: 2;
  bottom: -2px;
  left: -7px;
  height: 19px;
  border-left: 20px solid #E5E5EA;
  border-bottom-right-radius: 16px 14px;
  -webkit-transform: translate(0, -2px);
  transform: translate(0, -2px);
  border-bottom-right-radius: 15px 0px\9;
  transform: translate(-1px, -2px)\9;
}

form.chat .fromThem:after {
  content: "";
  position: absolute;
  z-index: 3;
  bottom: -2px;
  left: 4px;
  width: 26px;
  height: 20px;
  background: white;
  border-bottom-right-radius: 10px;
  -webkit-transform: translate(-30px, -2px);
  transform: translate(-30px, -2px);
}

form.chat date {
  position:absolute;
  top: 10px;
  font-size:14px;
  white-space:nowrap;
  vertical-align:middle;
  color: #8b8b90;
  opacity: 0;
  z-index:4;
}

form.chat .myMessage date {
  left: 105%;
}

form.chat .fromThem date {
  right: 105%;
}

form.chat input{
  /* font: 400 13px 'Open Sans', sans-serif; */
  font: 400 1em 'Open Sans', sans-serif;
    border:0;
 /* padding:0 15px; */
    padding: 15px 15px 0 15px;
  height:10%;
  outline:0;
}

form.chat input[type='text']{
  width:73%;
  float:left;
}

form.chat input[type='submit']{
  width:23%;
  background:transparent;
  color:#00E34D;
  font-weight:700;
  text-align:right;
  float:right;
}

  form.chat .myMessage,form.chat .fromThem{
    font-size:1.1em;

  }

  form.chat .myMessage,
  form.chat .fromThem {
    max-width: 90%;
  }

@-moz-keyframes loading-bar {
  0% {
    width: 0%;
  }
  90% {
    width: 90%;
  }
  100% {
    width: 100%;
  }
}

@-webkit-keyframes loading-bar {
  0% {
    width: 0%;
  }
  90% {
    width: 90%;
  }
  100% {
    width: 100%;
  }
}

@keyframes loading-bar {
  0% {
    width: 0%;
  }
  90% {
    width: 90%;
  }
  100% {
    width: 100%;
  }
}

/* DEMO */
.iphone{
  /*
    width:300px;
  height:609px;
  background-image:url('http://www.adobewordpress.com/tasarim/images/iphone6.png');
  background-size:100% 100%;
  margin:0 auto;
    */
    width:100%;

}

.border{
    /* position:absolute;
    top:12.3%;right:7%;left:7%;bottom:12%;
    overflow:hidden; */
}

a.article{
  position:fixed;
  bottom:15px;left:15px;
  display:table;
  text-decoration:none;
  color:white;
  background-color:#00e34d;
  padding: 10px 20px;
  border-radius: 25px;
  font: 400 15px 'Open Sans', sans-serif;
}

HTML:

<div class="iphone">
  <div class="imessage-header"></div>
  <div class="border">
    <form class="chat">
      <span></span>
      <div class="messages" id="textMessage">
        <div class="message">
          <div class="fromThem">
            <p>Would you like to continue your magazine subscription? Text CONTINUE to continue or NO to stop.</p>
          </div>
        </div>
        <div class="message magPrice" style="display:none;">
          <div class="fromThem new">
            <p>Your total will be $XXXX.XX. Would you like to pay for your order with your card on file? Text YES to continue or NO to stop.</p>
          </div>
        </div>
        <div class="message addressVerification" style="display:none;">
          <div class="fromThem new">
            <p>We need to confirm your shipping address for this order.  Is 123 Main Street; O’Fallon, MO  63368 correct? Text YES to continue or NO to stop.</p>
          </div>
        </div>
        <div class="message goToWeb" style="display:none;">
          <div class="fromThem new">
              <p>To change your shipping address go to this <a href="#">website</a>.</p>
          </div>
        </div>
      </div>
      <div style="position:fixed;bottom:0;left:0;border:1px solid #ddd;width:100%;z-index:101;background-color:#fff;height:50px;">
        <input type="text" placeholder="Your message" autofocus style="height:auto;">
        <input type="submit" value="Send" style="height:auto;">
      </div>
    </form>
  </div>
</div>


来源: stackexchange

问:
Keep animation when changing viewController
I'm trying to code an animation behind the profile picture, in order to encourage the user to click on it.
It's a circle which become bigger and smaller then.

```<code>override func layoutSubviews() {
  super.layoutSubviews()

  UIView.animate(withDuration: 1.0, delay: 0, options: [.repeat, .autoreverse], animations: {

     self.bouncedView.transform = CGAffineTransform(scaleX:
        1.3, y: 1.3)

      }, completion: nil)

}
</code>```

The problem is that, when I go to another viewController, the animation is stopped and the circle stays like you can the on the screen shot. Do you know how I could avoid this issue ?

答:
Well, I don't yet have a satisfying answer yet (at least that would satisfy me), but I would like to add at least some insight to which I was able to get by a bit of experimenting.

First of all, it seems that the animation gets ended when the viewController is not currently the one presented. In your case that means that the animation stops and finishes with the state, in which the view is 1.3 times bigger, and stops repeating. layoutSubviews gets called only when you present it the first time. At least the viewController.viewDidLayoutSubviews gets called only at the beginning and not when you go back (so layoutSubviews will not get executed when the view reappears) - so the animation won't get restarted.

I tried to move the animation to the viewDidAppear of a UIViewController - that did not work either, because stopping animation resulted in state in which the view was already scaled 1.3 times. Resetting the state to CGAffineTransform.identity before creating the animation did work.

Now as I said, this can serve you as a workaround on how to get it working, however, I think what you really are looking for is some hook that would tell your view (not viewController) that it got presented again. But the following minimal example can at least help others to take a look at it and not start from scratch.

```<code>import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {

    let animator = UIViewPropertyAnimator(duration: 1, timingParameters: UICubicTimingParameters(animationCurve: .linear))

    init(title: String) {
        super.init(nibName: nil, bundle: nil)
        self.title = title
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    let animatableView = UIView()

    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        animatableView.frame = CGRect(x: 150, y: 400, width: 100, height: 100)
        animatableView.backgroundColor = UIColor.magenta
        view.addSubview(animatableView)

        self.view = view
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        self.animatableView.transform = CGAffineTransform.identity
        UIView.animate(withDuration: 1.0, delay: 0, options: [.repeat, .autoreverse], animations: {
            self.animatableView.transform = CGAffineTransform(scaleX:
                1.3, y: 1.3)
        }, completion: nil)
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        print("\(self.title) >> Lay out")
    }
}

let tabBar = UITabBarController()
tabBar.viewControllers = [MyViewController(title: "first"), MyViewController(title: "second"), MyViewController(title: "third")]
tabBar.selectedIndex = 0
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = tabBar
</code>```

EDIT

I added few lines to check if the self.animatableView.layer.animationKeys() contains any animations, it seems that switching tabs removes the animation from the view's layer - so you have to find a way to add the animation everytime the view reappears.

EDIT 2
So I would go with @SWAT's answer and use willMove(toWindow:) instead of layoutSubviews.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to code an animation behind the profile picture, in order to encourage the user to click on it.
It's a circle which become bigger and smaller then.

override func layoutSubviews() {
  super.layoutSubviews()

  UIView.animate(withDuration: 1.0, delay: 0, options: [.repeat, .autoreverse], animations: {

     self.bouncedView.transform = CGAffineTransform(scaleX:
        1.3, y: 1.3)

      }, completion: nil)

}

The problem is that, when I go to another viewController, the animation is stopped and the circle stays like you can the on the screen shot. Do you know how I could avoid this issue ?

Body:
Well, I don't yet have a satisfying answer yet (at least that would satisfy me), but I would like to add at least some insight to which I was able to get by a bit of experimenting.

First of all, it seems that the animation gets ended when the viewController is not currently the one presented. In your case that means that the animation stops and finishes with the state, in which the view is 1.3 times bigger, and stops repeating. layoutSubviews gets called only when you present it the first time. At least the viewController.viewDidLayoutSubviews gets called only at the beginning and not when you go back (so layoutSubviews will not get executed when the view reappears) - so the animation won't get restarted.

I tried to move the animation to the viewDidAppear of a UIViewController - that did not work either, because stopping animation resulted in state in which the view was already scaled 1.3 times. Resetting the state to CGAffineTransform.identity before creating the animation did work.

Now as I said, this can serve you as a workaround on how to get it working, however, I think what you really are looking for is some hook that would tell your view (not viewController) that it got presented again. But the following minimal example can at least help others to take a look at it and not start from scratch.

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {

    let animator = UIViewPropertyAnimator(duration: 1, timingParameters: UICubicTimingParameters(animationCurve: .linear))

    init(title: String) {
        super.init(nibName: nil, bundle: nil)
        self.title = title
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    let animatableView = UIView()

    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        animatableView.frame = CGRect(x: 150, y: 400, width: 100, height: 100)
        animatableView.backgroundColor = UIColor.magenta
        view.addSubview(animatableView)

        self.view = view
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        self.animatableView.transform = CGAffineTransform.identity
        UIView.animate(withDuration: 1.0, delay: 0, options: [.repeat, .autoreverse], animations: {
            self.animatableView.transform = CGAffineTransform(scaleX:
                1.3, y: 1.3)
        }, completion: nil)
    }

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        print("\(self.title) >> Lay out")
    }
}

let tabBar = UITabBarController()
tabBar.viewControllers = [MyViewController(title: "first"), MyViewController(title: "second"), MyViewController(title: "third")]
tabBar.selectedIndex = 0
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = tabBar

EDIT

I added few lines to check if the self.animatableView.layer.animationKeys() contains any animations, it seems that switching tabs removes the animation from the view's layer - so you have to find a way to add the animation everytime the view reappears.

EDIT 2
So I would go with @SWAT's answer and use willMove(toWindow:) instead of layoutSubviews.


问:
Properly structuring a couchDB app
Use Case

I want to serve multiple customers from 1 couchdb

Each customer will have their own set of data (and a subset of child data - head office as the parent and each location as the
children)

Each customer could have different UI screens

Within each customer different users may have different UI screens

The system will be a couchapp and distributed globally and will use replication

The Options

For each customer store all pages in one _design document and serve the appropriate pages based on user type (permission)

For each customer store each page into it's own _design document

For each customer, store all pages associated with the user permission level in one _design document so that each user type will be served from a different _design document

Also, I've read two books now on couchDB and it's still not clear the advantages of using a _design document as opposed to a normal document to serve the web pages.

UPDATE 1:

I think I will need to give a clearer example.

Company A has a head office in Bangkok with management and administrative (secretaries) staff using the app.  These users will belong to different user groups and have different permissions which will provide them access to different HMTL documents (or the same template doc but serving different content via js).  This company has offices in Pattaya, Phuket and Chang Mai.  At each of these offices they have different user types who will have access to different parts of the app and see different versions of HTML screens.  The local apps will be based on filtered replication.

This couchDB will provide this service to multiple companies structured just like Company A, all from the same db (reason being that we need to be able to aggregate data for all companies and couchDB cannot aggregate across multiple databases since views are db specific if I read correctly.)  However, each master Company could have slight differences to their HTML pages from other master Companies.

So focusing on structure only, my initial idea is to do multiple _design documents, one for each master Company.  In each of these _design documents we store each and every HTML page for that company (which may or may not be the same as other master companies.

Is there a better way to structure this?
Do you see scaling issues when we have say 1000 master companies?

P.S. Even if we can't complete solve ACL issues directly via couchDB we can always do it ourselves so this isn't a primary concern right now.

UPDATE 2:

So after more research I see how the show functions (shows) play a role in this by using templates.  It doesn't fully answer my question,  so I guess, based on this, I am also wondering now if there is ever a situation where you might want to have any other HTML attachement in the _design document other than index.html?

答:
CouchDB is directly servicing all queries from the Internet. It doesn't care if the client was a browser (Couch app), iPhone, or command-line cURL. Design documents do not affect read permissions of the database at all.

Design documents are a completely transparent and exposed thing. Nothing private should be in it. For example, it might contain template files, but the private data is in other documents.

A database can have pretty much any design document because the secret information is the other documents, only some of which replicate to the users' individual databases.

ContentLicense: CC BY-SA 2.5

Title: Properly structuring a couchDB app


问:
Any way to implement OAuth integration to an external application with NetSuite?
I'm trying to implement NetSuite with an external application. My application is embeded to run in an iframe, so I'm using a portlet to load it up and simply display it. Now, the issue is that my app uses OAuth 2.0 for authentication and I would like the users to be able to login using this. NetSuite doesn't seem to provide any kind of support or straightforward way to do this, so I tried to elaborate something on my own.

The idea I had was to configure the app to redirect to a NetSuite restlet to exchange auth_code for tokens and finally get and save the token, but I couldn't make it work for several reasons.

First, RESTlets calls coming from external applications need to have all the authentication headers required by NetSuite.

Second, even if I was able to pull that off, how am I supposed to save the token in a secure way and use it on every subsecuent call on my application? (which again, runs inside an iframe).

In short, I don't see any light at the end of the tunel and was wodering if anybody was able to work this out.

Thanks in advance for all your help.

答: You can use Restlet to communicate with NetSuite for that you'll need to enable Tokens based authentication in NetSuite. Also you'll need to create an app in NetSuite and generate OAuth tokens in NetSuite and save them in your app or server whichever you are going to use and then use these tokens to communicate with NetSuite.</p>


问:
Generate a random number tab without the same number
I wish create a tab of number but never have the same number.
Example of result wished [1,4,7,5,0,2,3,8,9,6]

I have this error :

maximum call stack size exceeded

I think it caused by recursive but I don't know what to do.

```<code>cardsAlreadyUsed = [1,4,7]

setNumCardsToUsed(cardsAlreadyUsed){
    var nbMin = 0; var nbMax = 9;
    var result = Math.floor((Math.random() * nbMax) + nbMin);
    var i = 0;

    while (i < cardsAlreadyUsed.length) {
      if (result == cardsAlreadyUsed[i]) {
        result = null;
        break;
      }
      i++;
    }
    if (result == null)
        setNumCardsToUsed(cardsAlreadyUsed);
    else
        cardsAlreadyUsed.push(result);

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

答:
You could create a range of numbers based on your min and max values, and just shuffle it.

// Create an array of integers ranging from `min` to `max` (both inclusive).
function range( min, max ){
  return Array(max - min + 1).fill().map(function(_, i){ return i + min; });
}

// Shuffle an array in place and return it.
function shuffle( a ) {
   var j, x, i;
   for (i = a.length - 1; i > 0; i--) {
      j = Math.floor(Math.random() * (i + 1));
      x = a[i];
      a[i] = a[j];
      a[j] = x;
   }
   return a;
}

// Create wanted range of integers, shuffle and return it.
function generateShuffledArray( min, max ){
   return shuffle(range(min, max));
}

console.log( generateShuffledArray(0, 9) )```

Body:
I wish create a tab of number but never have the same number.
Example of result wished [1,4,7,5,0,2,3,8,9,6]

I have this error :

maximum call stack size exceeded

I think it caused by recursive but I don't know what to do.

cardsAlreadyUsed = [1,4,7]

setNumCardsToUsed(cardsAlreadyUsed){
    var nbMin = 0; var nbMax = 9;
    var result = Math.floor((Math.random() * nbMax) + nbMin);
    var i = 0;

    while (i < cardsAlreadyUsed.length) {
      if (result == cardsAlreadyUsed[i]) {
        result = null;
        break;
      }
      i++;
    }
    if (result == null)
        setNumCardsToUsed(cardsAlreadyUsed);
    else
        cardsAlreadyUsed.push(result);

    return result;
};


问:
Loading shared Javascript code between vue-electron components
I've created a new vue-electron project using vue init simulatedgreg/electron-vue <my project name>. I can create some basic components that use a database backend like so (src/rendered/components/Tagger/TagList.vue):

```<code><template>
  <ul>
    <li v-for="tag in tags">
      <input type="checkbox" :id="tag" :value="tag" v-model="selectedTags">
      <label :for="tag">{{ tag }}</label>
    </li>
  </ul>
</template>

<script>
export default {
  data () {

    var db, sqlite3, tags;
    sqlite3 = require('sqlite3');
    db = new sqlite3.Database('/tmp/tagister.tmp.sqlite3');
    tags = [];
    db.each("SELECT id,tag FROM tags", function(err, row) {
      tags.push(row.tag)
    });
    db.close;

    return {
      tags: tags,
      selectedTags: ['someTag']
    }
  }
}
</script>

<style>
</style>
</code>```

I have a Tagger.vue that imports that component and it renders correctly, pulling a list of tags from the sqlite database.

Now I want to abstract the database code so I can use it with multiple components. I created a database.js. It looks like this:

```<code>"use strict";

sqlite3 = require('sqlite3')

export default class Database {
  constructor(dbFile) {
    this.db = new sqlite3.Database(dbFile);
    log.console('Opened Database: ' + dbFile)
  }

  tags() {
    var tags = [];
    this.db.each("SELECT id,tag FROM tags", function(err, row) {
      tags.push(row.tag)
    });
    return tags;
  }

  files() {
    var files = [];
    this.db.each("SELECT id,name FROM files", function(err, row) {
      files.push(row.name)
    });
    return files;
  }

  close() {
    this.db.close();
  }
}
</code>```

I've tried placing it in src and src/main and tried importing it using var db = requrie('database') and var db = require('src/main/database') and several other variations, but I always get an error that the module cannot be found. What's the correct way to build and import modules in vue-electron projects?

答:
I ended up settling placing my database library in the src/render part of the tree. My src/renderer/database.coffee looked like the following:

```<code>Database = require('better-sqlite3')

class TagDB

  constructor: (dbFile) ->
    @db = new Database(dbFile)
    console.log("Opened Database #{dbFile}")

  tags: ->
    @db.prepare("SELECT id,tag FROM tags").all().map( (row) => row.tag )

  files: ->
    @db.prepare("SELECT id,name FROM files").all()

  close: ->
    @db.close()

export default TagDB
</code>```

Then I have a component at src/renderer/components/Tagger.vue which has the following in its

Body:
I've created a new vue-electron project using vue init simulatedgreg/electron-vue <my project name>. I can create some basic components that use a database backend like so (src/rendered/components/Tagger/TagList.vue):

<template>

      <input type="checkbox" :id="tag" :value="tag" v-model="selectedTags">
      {{ tag }}

</template>

I have a Tagger.vue that imports that component and it renders correctly, pulling a list of tags from the sqlite database.

Now I want to abstract the database code so I can use it with multiple components. I created a database.js. It looks like this:

"use strict";

sqlite3 = require('sqlite3')

export default class Database {
  constructor(dbFile) {
    this.db = new sqlite3.Database(dbFile);
    log.console('Opened Database: ' + dbFile)
  }

  tags() {
    var tags = [];
    this.db.each("SELECT id,tag FROM tags", function(err, row) {
      tags.push(row.tag)
    });
    return tags;
  }

  files() {
    var files = [];
    this.db.each("SELECT id,name FROM files", function(err, row) {
      files.push(row.name)
    });
    return files;
  }

  close() {
    this.db.close();
  }
}

I've tried placing it in src and src/main and tried importing it using var db = requrie('database') and var db = require('src/main/database') and several other variations, but I always get an error that the module cannot be found. What's the correct way to build and import modules in vue-electron projects?

Body:
I ended up settling placing my database library in the src/render part of the tree. My src/renderer/database.coffee looked like the following:

Database = require('better-sqlite3')

class TagDB

  constructor: (dbFile) ->
    @db = new Database(dbFile)
    console.log("Opened Database #{dbFile}")

  tags: ->
    @db.prepare("SELECT id,tag FROM tags").all().map( (row) => row.tag )

  files: ->
    @db.prepare("SELECT id,name FROM files").all()

  close: ->
    @db.close()

export default TagDB

Then I have a component at src/renderer/components/Tagger.vue which has the following in its <script> section:

<script>
  import TagDB from '../database'
  var tagdb = new TagDB('/tmp/tagster.tmp.sqlite3')
  ...
  ...

And finally I added the following to .electron-vue/webpack.renderer.config.js so I could compile my coffeescript:

  module: {
    rules: [
      {
        test:  /\.coffee$/,
        use: 'coffeescript-loader'
      },
  ...
  ...
  extensions: ['.js', '.vue', '.json', '.css', '.node', '.coffee']


问:
Dispatching new action after global state changes in react redux
Lets say i have a form where user is about to click on combination of buttons.

Each button triggers an action of type T and reducer R then updates its state and new combination is rendered on a website.

Now comes the tricky part:
I have my business logic implemented in reducer which applies new state which is about to be rendered. What i need now is when that state accepts a condition, i want to dispatch new action (api request).

What is the right approach to accomplish this kind of problem?

Set a flag into state, and call new action in component after?
Somehow dispatch a function in reducer?

...?

答:
Redux Thunk allows you to dispatch multiple actions and dispatch asynchronous actions inside your action creators. For your scenario, you can do something like this:</p>

```<code>function myAction() {
  return (dispatch, getState) => {
    ...
    dispatch(firstAction);

    const state = getState();

    // Check your state conditions from first action here.
    dispatch(secondAction);
    ...
  }
}
</code>```

Body:
Redux Thunk allows you to dispatch multiple actions and dispatch asynchronous actions inside your action creators. For your scenario, you can do something like this:

function myAction() {
  return (dispatch, getState) => {
    ...
    dispatch(firstAction);

    const state = getState();

    // Check your state conditions from first action here.
    dispatch(secondAction);
    ...
  }
}


问:
LLVM - given a register, get where it was last used in the IR representation
I am trying to keep track of data flow in my source code. For that, I'm looking at instructions of type load and obtaining which register they're loading the value from with the use of

```<code>*(LI->getPointerOperand())
</code>```

LI being the instruction of type LoadInst. Now I need to know where this register was last accessed so that I can point that check the data flow from that instruction to this one. Any suggestions will be highly appreciated.

答:
Initially, simplify the problem by excluding loops and functions with multiple exits, so that you have a function CFG as a single entry and single exit graph.

One (probably simplistic) way would be to first find all its users by doing something like:

```<code>llvm::Instruction i = [the register for that LoadInst];
auto users = i->users();
</code>```

Then using the PostDominatorTree and the getLevel method of the DomTreeNodeBase (I think this was introduced with LLVM 5.0.0, if not available in your version you could use getChildren and perform a BFS traversal), you could filter through those with the highest level number.

I'm not sure what you want to do with loops, but if nothing special, the above should suffice. For dealing with multiple exits from functions you could make use of the mergereturn pass prior to any processing.

Body:
I am trying to keep track of data flow in my source code. For that, I'm looking at instructions of type load and obtaining which register they're loading the value from with the use of

*(LI->getPointerOperand())

LI being the instruction of type LoadInst. Now I need to know where this register was last accessed so that I can point that check the data flow from that instruction to this one. Any suggestions will be highly appreciated.

Body:
Initially, simplify the problem by excluding loops and functions with multiple exits, so that you have a function CFG as a single entry and single exit graph.

One (probably simplistic) way would be to first find all its users by doing something like:

llvm::Instruction i = [the register for that LoadInst];
auto users = i->users();

Then using the PostDominatorTree and the getLevel method of the DomTreeNodeBase (I think this was introduced with LLVM 5.0.0, if not available in your version you could use getChildren and perform a BFS traversal), you could filter through those with the highest level number.

I'm not sure what you want to do with loops, but if nothing special, the above should suffice. For dealing with multiple exits from functions you could make use of the mergereturn pass prior to any processing.


问:
Compilation error - Inversions counting algorithm
I am struggling in my code with an error.

This is the error I got:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:

The method recur(Integer[]) in the type D_and_con is not applicable for the arguments (int[])

at edu.uqu.algorithms.inversions.D_and_con.recur(D_and_con.java:27)

  at edu.uqu.algorithms.inversions.MainTest.main(MainTest.java:27)

The code computes the number of inversions.

It is:

```<code>package edu.uqu.algorithms.inversions;

import java.io.FileNotFoundException;
import java.util.Arrays;

import edu.uqu.algorithms.inversions.util.IOUtil;

public class MainTest {

    public static void main(String[] args) {

        try {

            /*//Inversions using BRUTE FORCE
            Integer[] tokens1 = IOUtil.loadFileIntoArray("IntegerArray.txt");
            long startTime1 = System.currentTimeMillis();
            System.out.println("Started Computing Total nb of invertions BRUTE FORCE..........................");
            System.out.println("Total nb of invertions BRUTE FORCE: " + Inversions.countInvertionsBruteForce(tokens1));
            long runningTime1 = (System.currentTimeMillis() - startTime1);
            System.out.println("BRUTE FORCE Running time: " + runningTime1);
            System.out.println("\n");*/

            //Inversions using DIVIDE & CONQUER
            Integer[] tokens2 = IOUtil.loadFileIntoArray("IntegerArray.txt");
            long startTime2 = System.currentTimeMillis();
            System.out.println("Started Computing Total nb of invertions DIVIDE & CONQUER..........................");
            System.out.println("MMMMM" + D_and_con.recur(tokens2) );
            long runningTime2 = (System.currentTimeMillis() - startTime2);
            System.out.println("DIVIDE & CONQUER Running time: " + runningTime2);

            System.out.println("----------------------- FINISHED -------------------------");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

}
----------------------------------------
/************************************
 *
 *  The aim of this code is to count the number of inversions in
 *  an array of integers. Two ways of counting are used, a Brute Force algorithm and
 *  a recursive Divide and Conquer algorithm.
 *
 ***********************************/

package edu.uqu.algorithms.inversions;

/**
public class Inversions{

/**
 * Brute force inversions counting method.
 */
public static long countInvertionsBruteForce(Integer[] entries_p)
{
    long result = 0;
    for(int i = 0; i < entries_p.length; i++){
        for(int j = i+1; j < entries_p.length; j++){
            if(entries_p[i] > entries_p[j]) result++;
        }
        //System.out.println("BRUTE FORCE intermediate result for i = " + i + " IS: " + result);
    }
    return result;
}

}
--------------------------
Divide and conquer
/************************************
 *
 *  The aim of this code is to count the number of inversions in
 *  an array of integers. Two ways of counting are used, a Brute Force algorithm and
 *  a recursive Divide and Conquer algorithm.
 *
 ***********************************/

package edu.uqu.algorithms.inversions;

import java.math.BigDecimal;

public class D_and_con{
    private static BigDecimal totalcount = new BigDecimal(0);
    public static Integer[] recur(Integer[] entries_p)
    {
    int n = entries_p.length;
    if(n == 1)
    {
    return entries_p;
    }
    int middel = n/2;
    int[] Larray = new int[middel];
    int[] Rarray = new int[n - middel];
    System.arraycopy(entries_p , 0 , Larray, 0 , Larray.length );
    System.arraycopy(entries_p , Larray.length , Rarray , 0 , Rarray.length);
    recur(Larray);\\ERROR APPEAR HERE
    recur(Rarray);\\ERROR APPEAR HERE
    comb(Larray , Rarray , entries_p );
    return entries_p;
    }

    private static void comb(int[] Larray, int[] Rarray, Integer[] newarray)
    {
        int LarrayL = Larray.length;
        int RarrayL = Rarray.length;
        int i=0 , j=0 , k=0 ;
        while(i< LarrayL && i<RarrayL)
            {
                if(Larray[i] < Rarray[i] )
                {
                newarray[k] = Larray[i];
                i++;
                }

                else
                {
                    newarray[k] = Rarray[j];
                    i++;
                totalcount = totalcount.add (new BigDecimal(Larray.length - 1));

                }
                k++;
            }
            while(i < LarrayL) {
            newarray[k] = Larray[i];
            i++;
            k++;
          }
          while(j < RarrayL) {
            newarray[k] = Rarray[j];
            j++;
            k++;
          }

    }
}
</code>```

答:
"int" is a primitive data-type and "Integer" is a Class.

To solve your problem:-

```<code>1 - Integer[] tokens2 = IOUtil.loadFileIntoArray("IntegerArray.txt"); //Read data from file in int[].

2 - Integer[] recur(Integer[] entries_p){} //change it as int[] recur(int[] entries_p)
</code>```

Body:
I am struggling in my code with an error.

This is the error I got:

Exception in thread "main" java.lang.Error: Unresolved compilation problems:

The method recur(Integer[]) in the type D_and_con is not applicable for the arguments (int[])

at edu.uqu.algorithms.inversions.D_and_con.recur(D_and_con.java:27)

  at edu.uqu.algorithms.inversions.MainTest.main(MainTest.java:27)

The code computes the number of inversions.

It is:

package edu.uqu.algorithms.inversions;

import java.io.FileNotFoundException;
import java.util.Arrays;

import edu.uqu.algorithms.inversions.util.IOUtil;

public class MainTest {

    public static void main(String[] args) {

        try {

            /*//Inversions using BRUTE FORCE
            Integer[] tokens1 = IOUtil.loadFileIntoArray("IntegerArray.txt");
            long startTime1 = System.currentTimeMillis();
            System.out.println("Started Computing Total nb of invertions BRUTE FORCE..........................");
            System.out.println("Total nb of invertions BRUTE FORCE: " + Inversions.countInvertionsBruteForce(tokens1));
            long runningTime1 = (System.currentTimeMillis() - startTime1);
            System.out.println("BRUTE FORCE Running time: " + runningTime1);
            System.out.println("\n");*/

            //Inversions using DIVIDE & CONQUER
            Integer[] tokens2 = IOUtil.loadFileIntoArray("IntegerArray.txt");
            long startTime2 = System.currentTimeMillis();
            System.out.println("Started Computing Total nb of invertions DIVIDE & CONQUER..........................");
            System.out.println("MMMMM" + D_and_con.recur(tokens2) );
            long runningTime2 = (System.currentTimeMillis() - startTime2);
            System.out.println("DIVIDE & CONQUER Running time: " + runningTime2);

            System.out.println("----------------------- FINISHED -------------------------");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }

}
----------------------------------------
/************************************
 *
 *  The aim of this code is to count the number of inversions in
 *  an array of integers. Two ways of counting are used, a Brute Force algorithm and
 *  a recursive Divide and Conquer algorithm.
 *
 ***********************************/

package edu.uqu.algorithms.inversions;

/**
public class Inversions{

/**
 * Brute force inversions counting method.
 */
public static long countInvertionsBruteForce(Integer[] entries_p)
{
    long result = 0;
    for(int i = 0; i < entries_p.length; i++){
        for(int j = i+1; j < entries_p.length; j++){
            if(entries_p[i] > entries_p[j]) result++;
        }
        //System.out.println("BRUTE FORCE intermediate result for i = " + i + " IS: " + result);
    }
    return result;
}

}
--------------------------
Divide and conquer
/************************************
 *
 *  The aim of this code is to count the number of inversions in
 *  an array of integers. Two ways of counting are used, a Brute Force algorithm and
 *  a recursive Divide and Conquer algorithm.
 *
 ***********************************/

package edu.uqu.algorithms.inversions;

import java.math.BigDecimal;

public class D_and_con{
    private static BigDecimal totalcount = new BigDecimal(0);
    public static Integer[] recur(Integer[] entries_p)
    {
    int n = entries_p.length;
    if(n == 1)
    {
    return entries_p;
    }
    int middel = n/2;
    int[] Larray = new int[middel];
    int[] Rarray = new int[n - middel];
    System.arraycopy(entries_p , 0 , Larray, 0 , Larray.length );
    System.arraycopy(entries_p , Larray.length , Rarray , 0 , Rarray.length);
    recur(Larray);\\ERROR APPEAR HERE
    recur(Rarray);\\ERROR APPEAR HERE
    comb(Larray , Rarray , entries_p );
    return entries_p;
    }

    private static void comb(int[] Larray, int[] Rarray, Integer[] newarray)
    {
        int LarrayL = Larray.length;
        int RarrayL = Rarray.length;
        int i=0 , j=0 , k=0 ;
        while(i< LarrayL && i<RarrayL)
            {
                if(Larray[i] < Rarray[i] )
                {
                newarray[k] = Larray[i];
                i++;
                }

                else
                {
                    newarray[k] = Rarray[j];
                    i++;
                totalcount = totalcount.add (new BigDecimal(Larray.length - 1));

                }
                k++;
            }
            while(i < LarrayL) {
            newarray[k] = Larray[i];
            i++;
            k++;
          }
          while(j < RarrayL) {
            newarray[k] = Rarray[j];
            j++;
            k++;
          }

    }
}

Body:
"int" is a primitive data-type and "Integer" is a Class.

To solve your problem:-

1 - Integer[] tokens2 = IOUtil.loadFileIntoArray("IntegerArray.txt"); //Read data from file in int[].

2 - Integer[] recur(Integer[] entries_p){} //change it as int[] recur(int[] entries_p)


问:
XSD.exe warning-error
I have some xsd's given to me and i want to generate C# classes to create xml documents based on these classes. I have problem generating classes though from those xsd!

I get schema validation warning: Type'http://ww...../types:ExampleNameType' is not declared, or is not a simple type. Ok they gave me some xsd's declaring the types and these xsd's are named on imports section e.g.:

```<code><xs:import namespace="http://www..../types" schemaLocation="types.xsd"/>
<xs:import namespace="http://www..../tms" schemaLocation="tms.xsd"/>.
</code>```

I'm kinda newbie on XML and i cant get this xsd schema thing.

Any help?

答:
Make sure that you put in all xsd files, e.g.:</p>

```<code>xsd.exe /c types.xsd tms.xsd root.xsd
</code>```

Title: XSD.exe warning-error

Body:
I have some xsd's given to me and i want to generate C# classes to create xml documents based on these classes. I have problem generating classes though from those xsd!

I get schema validation warning: Type'http://ww...../types:ExampleNameType' is not declared, or is not a simple type. Ok they gave me some xsd's declaring the types and these xsd's are named on imports section e.g.:

<xs:import namespace="http://www..../types" schemaLocation="types.xsd"/>
<xs:import namespace="http://www..../tms" schemaLocation="tms.xsd"/>.

I'm kinda newbie on XML and i cant get this xsd schema thing.

Any help?

Body:
Make sure that you put in all xsd files, e.g.:

xsd.exe /c types.xsd tms.xsd root.xsd


问:
PhpStorm FTP 425 Unable to build data connection: Cannot assign requested address
PhpStorm FTP upload failed.

```<code>[17-1-16 下午5:17] Failed to transfer file '/a': cant open output connection for file "ftp://192.168.1.229:21/a". Reason: "425 Unable to build data connection: Cannot assign requested address".
[17-1-16 下午5:17] Upload to server completed in less than a minute: 108 files transferred, 3 items failed (541.1 Kb/s)
</code>```

My PhpStorm running on deepin system (Linux)

```<code>net.ipv4.tcp_fin_timeout=30
net.ipv4.tcp_timestamps=1
net.ipv4.tcp_tw_recycle=1
net.ipv4.ip_local_port_range = 10000     65000
</code>```

I tried to change the number of ports, but still failed to upload.
Who can help me ?

答:
I got the same problem in IntelliJ IDEA.

Changing the connection type from FTP to SFTP helped. I hope it's also possible for you.

Body:
PhpStorm FTP upload failed.

[17-1-16 下午5:17] Failed to transfer file '/a': cant open output connection for file "ftp://192.168.1.229:21/a". Reason: "425 Unable to build data connection: Cannot assign requested address".
[17-1-16 下午5:17] Upload to server completed in less than a minute: 108 files transferred, 3 items failed (541.1 Kb/s)

My PhpStorm running on deepin system (Linux)

net.ipv4.tcp_fin_timeout=30
net.ipv4.tcp_timestamps=1
net.ipv4.tcp_tw_recycle=1
net.ipv4.ip_local_port_range = 10000     65000

I tried to change the number of ports, but still failed to upload.
Who can help me ?


问:
Initialize tensor Variable to numpyArray - Reduced Sum Issues
I am pre-processing a numpy array and want to enter it in as a tensorflow Variable.  I've tried following other stack exchange advice, but so far without success.  I would like to see if I'm doing something uniquely wrong here.

```<code>  npW = np.zeros((784,10))
  npW[0,0] = 20
  W = tf.Variable(tf.convert_to_tensor(npW, dtype = tf.float32))

  sess = tf.InteractiveSession()
  tf.global_variables_initializer().run()

  print("npsum", np.sum(npW))
  print(tf.reduce_sum(W))
</code>```

And this is the result.

```<code>npsum 20.0
Tensor("Sum:0", shape=(), dtype=float32)
</code>```

I don't know why the reduced sum of the W variable remains zero.  Am i missing something here?

答:
So i tested it a bit differently and found out that the variable is getting assigned properly,  but, the reduced_sum function isn't working as expected.  If any one has explanations on that it would be much appreciated.

```<code>  npW = np.zeros((2,2))
  npW[0,0] = 20
  W = tf.Variable(npW, dtype = tf.float32)
  A= tf.constant([[20,0],[0,0]])
  sess = tf.InteractiveSession()
  tf.global_variables_initializer().run()
  # Train
  print("npsum", np.sum(npW))

  x=tf.reduce_sum(W,0)
  print(x)
  print(tf.reduce_sum(A))
  print(W.eval())
  print(A.eval())
</code>```

This had output

```<code>npsum 20.0
Tensor("Sum:0", shape=(2,), dtype=float32)
Tensor("Sum_1:0", shape=(), dtype=int32)
[[ 20.   0.],
[  0.   0.]]
[[20  0],
[ 0  0]]
</code>```

Body:
I am pre-processing a numpy array and want to enter it in as a tensorflow Variable.  I've tried following other stack exchange advice, but so far without success.  I would like to see if I'm doing something uniquely wrong here.

  npW = np.zeros((784,10))
  npW[0,0] = 20
  W = tf.Variable(tf.convert_to_tensor(npW, dtype = tf.float32))

  sess = tf.InteractiveSession()
  tf.global_variables_initializer().run()

  print("npsum", np.sum(npW))
  print(tf.reduce_sum(W))

And this is the result.

npsum 20.0
Tensor("Sum:0", shape=(), dtype=float32)

I don't know why the reduced sum of the W variable remains zero.  Am i missing something here?

Body:
So i tested it a bit differently and found out that the variable is getting assigned properly,  but, the reduced_sum function isn't working as expected.  If any one has explanations on that it would be much appreciated.

  npW = np.zeros((2,2))
  npW[0,0] = 20
  W = tf.Variable(npW, dtype = tf.float32)
  A= tf.constant([[20,0],[0,0]])
  sess = tf.InteractiveSession()
  tf.global_variables_initializer().run()
  # Train
  print("npsum", np.sum(npW))

  x=tf.reduce_sum(W,0)
  print(x)
  print(tf.reduce_sum(A))
  print(W.eval())
  print(A.eval())

This had output

npsum 20.0
Tensor("Sum:0", shape=(2,), dtype=float32)
Tensor("Sum_1:0", shape=(), dtype=int32)
[[ 20.   0.],
[  0.   0.]]
[[20  0],
[ 0  0]]


问:
Tensorflow: 'tf.get_default_session()` after sess=tf.Session() is None
I was trying to figure out why tf.get_default_session() always returns None type:

```<code>import tensorflow as tf

tf.reset_default_graph()
init=tf.global_variables_initializer()

sess = tf.Session()
sess.run(init)

default = tf.get_default_session()
default == None # True
</code>```

I do not know why default = tf.get_default_session() is None since I thought it should return the previous session.
Could anyone figures out what's wrong with my code?

答:
Just creating a tf.Session() doesn't make it a default. This is basically the difference between tf.Session and tf.InteractiveSession:

sess = tf.InteractiveSession()
print(tf.get_default_session())    # this is not None!
```

<p>Unlike <code>tf.InteractiveSession</code>, a <code>tf.Session</code> becomes a default only inside <code>with</code> block (it's a context manager):</p>

<pre class="lang-py prettyprint-override"><code>sess = tf.Session()
with sess:
  print(tf.get_default_session())  # this is not None!
</code>```

Body:
I was trying to figure out why tf.get_default_session() always returns None type:

import tensorflow as tf

tf.reset_default_graph()
init=tf.global_variables_initializer()

sess = tf.Session()
sess.run(init)

default = tf.get_default_session()
default == None # True

I do not know why default = tf.get_default_session() is None since I thought it should return the previous session.
Could anyone figures out what's wrong with my code?

Body:
Just creating a tf.Session() doesn't make it a default. This is basically the difference between tf.Session and tf.InteractiveSession:

sess = tf.InteractiveSession()
print(tf.get_default_session())    # this is not None!

Unlike tf.InteractiveSession, a tf.Session becomes a default only inside with block (it's a context manager):

sess = tf.Session()
with sess:
  print(tf.get_default_session())  # this is not None!


问:
How to get the address of an array and save it to a register in assembly?
I want to save the memory address of A[ ] in a register, say $a0 because I will pass this as an argument to a procedure even though I can reach A in any scope of the program.

In the code, the reason I used sb instead of sw is there is an allignment problem when I assemble it.

When I say lb $a0, A it stores 4 to $a0, which is the value not the address.

```<code>.data
    A: .space 16

.globl main
main:
    # Initialize values in the array
    addi $s0, $zero, 4
    addi $s1, $zero, 8
    addi $s2, $zero, 3
    addi $s3, $zero, 5

    # This $t0 is just used for indexing while inserting to A
    addi $t0, $zero, 0

    sb $s0, A($t0)
    addi $t0, $t0, 4
    sb $s1, A($t0)
    addi $t0, $t0, 4
    sb $s2, A($t0)
    addi $t0, $t0, 4
    sb $s3, A($t0)
    li $t0, 0
</code>```

答:
Use the la pseudo-instruction.  la $t0, A.

If A doesn't fit in 16 bits, this will assemble to a sequence like

lui $t0, high16(A) ; ori $t0, $zero, low16(A).  See this basic MIPS instruction-set reference for LUI.  Your assembler may use addui instead of ori; I think some assemblers have an option for which to choose for li / la pseudo-instructions.

There's also an li pseudo-instruction (for load-immediate) for use with numeric constants instead of addresses, but it works identically.

For the alignment problem, try making sure A's address is word-aligned.  I would have thought this would happen automatically, but maybe you left out a .asciz string constant earlier in .data from the code you posted?  Anyway, either put A first before non-multiple-of-4 sized objects, or use a .align directive to pad to the next multiple of 4.

```<code>.data
    .align 4         # align by 4 bytes.
    A: .space 16
</code>```

If A's address fits in 16 bits, you don't need it or the offset in a register, just use sb $s0, A+4($zero) and so on.  (But if you're using sb / lb, then why still offset by 4 bytes between elements?  Why not make it a 4-byte long array of 4 bytes?)

```<code>.globl main
main:
    # Initialize values in the array

    li     $t0, 4
    sw     $t0, A($zero)

    addui   $t0, $zero, 8     # doing it manually without an LI pseudo-instruction
    sw     $t0, A+4($zero)

    li     $t0, 3
    sw     $t0, A+8($zero)

    li     $t0, 5
    sw     $t0, A+12($zero)

    #li    $t0, 0
</code>```

You don't need to use a different register every time, although I guess without register-renaming a classic-RISC pipeline might stall for a Write-After-Read hazard (WAR) when li tried to write t0 before the previous sw had read it.  On a superscalar CPU, it makes sense to mix different instruction types (ALU addui and memory sw) so they can execute in parallel instead of maybe waiting longer than necessary before the first store executes.

Also, this is arguably more human readable because the value and address go together.

Body:
I want to save the memory address of A[ ] in a register, say $a0 because I will pass this as an argument to a procedure even though I can reach A in any scope of the program.

In the code, the reason I used sb instead of sw is there is an allignment problem when I assemble it.

When I say lb $a0, A it stores 4 to $a0, which is the value not the address.

.data
    A: .space 16

.globl main
main:
    # Initialize values in the array
    addi $s0, $zero, 4
    addi $s1, $zero, 8
    addi $s2, $zero, 3
    addi $s3, $zero, 5

    # This $t0 is just used for indexing while inserting to A
    addi $t0, $zero, 0

    sb $s0, A($t0)
    addi $t0, $t0, 4
    sb $s1, A($t0)
    addi $t0, $t0, 4
    sb $s2, A($t0)
    addi $t0, $t0, 4
    sb $s3, A($t0)
    li $t0, 0

Body:
Use the la pseudo-instruction.  la $t0, A.

If A doesn't fit in 16 bits, this will assemble to a sequence like

lui $t0, high16(A) ; ori $t0, $zero, low16(A).  See this basic MIPS instruction-set reference for LUI.  Your assembler may use addui instead of ori; I think some assemblers have an option for which to choose for li / la pseudo-instructions.

There's also an li pseudo-instruction (for load-immediate) for use with numeric constants instead of addresses, but it works identically.

For the alignment problem, try making sure A's address is word-aligned.  I would have thought this would happen automatically, but maybe you left out a .asciz string constant earlier in .data from the code you posted?  Anyway, either put A first before non-multiple-of-4 sized objects, or use a .align directive to pad to the next multiple of 4.

.data
    .align 4         # align by 4 bytes.
    A: .space 16

If A's address fits in 16 bits, you don't need it or the offset in a register, just use sb $s0, A+4($zero) and so on.  (But if you're using sb / lb, then why still offset by 4 bytes between elements?  Why not make it a 4-byte long array of 4 bytes?)

.globl main
main:
    # Initialize values in the array

    li     $t0, 4
    sw     $t0, A($zero)

    addui   $t0, $zero, 8     # doing it manually without an LI pseudo-instruction
    sw     $t0, A+4($zero)

    li     $t0, 3
    sw     $t0, A+8($zero)

    li     $t0, 5
    sw     $t0, A+12($zero)

    #li    $t0, 0

You don't need to use a different register every time, although I guess without register-renaming a classic-RISC pipeline might stall for a Write-After-Read hazard (WAR) when li tried to write t0 before the previous sw had read it.  On a superscalar CPU, it makes sense to mix different instruction types (ALU addui and memory sw) so they can execute in parallel instead of maybe waiting longer than necessary before the first store executes.

Also, this is arguably more human readable because the value and address go together.


问:
How to edit lists using input function
I am trying to edit and fill the lists in A, B and C using the input function.

```<code>A = ['']
B = ['']
C = ['']
key = input()
key[0] = 'X'
</code>```

But i get this error.

```<code>TypeError: 'str' object does not support item assignment
</code>```

How can i use the input function to edit my list. Or you might have better way to do this?

Thank You!

答:
Python strings are immutable objects which means you cannot change an existing string. The best you can do is create a new string that is a variation on the original. For e.g :

```<code>newstring = 'newchar' + oldstring[1:]
</code>```

In your case it would be something like:

```<code>key = input()
newkey = 'X' +key[1:]
</code>```

Title: How to edit lists using input function

Body:
I am trying to edit and fill the lists in A, B and C using the input function.

A = ['']
B = ['']
C = ['']
key = input()
key[0] = 'X'

But i get this error.

TypeError: 'str' object does not support item assignment

How can i use the input function to edit my list. Or you might have better way to do this?

Thank You!

Body:
Python strings are immutable objects which means you cannot change an existing string. The best you can do is create a new string that is a variation on the original. For e.g :

newstring = 'newchar' + oldstring[1:]

In your case it would be something like:

key = input()
newkey = 'X' +key[1:]


问:
Hardcode Boolean Query In Room Database
I'm building an Android application that displays a list of potential matches for a user. The user can click on one to like the user, and I save all of those likes locally.

I can write a query to get the list of matches like this:

```<code>@Query("SELECT * FROM match WHERE liked = :liked ORDER BY match DESC LIMIT :limit")
fun getMatches(limit: Int = 6, liked: Boolean = true): Flowable<List<Match>>
</code>```

I've learned that this works fine. However, I don't foresee any scenario where I'll ever set liked to false, and so I'm curious if there is a way to hardcode my Boolean condition? If I try:

```<code>@Query("SELECT * FROM match WHERE liked = true ORDER BY match DESC LIMIT :limit")
</code>```

I get the following error at compile time:

```<code>Error:(8, 0) Gradle: error: There is a problem with the query: [SQLITE_ERROR] SQL error or missing database (no such column: true)
</code>```

How can I hard code this Boolean in my query string?

I have also tried:

Wrapping the condition in single quotes

@Query("SELECT * FROM match WHERE liked = 'true' ORDER BY match DESC LIMIT :limit")

答:
SQLite does not have a boolean data type. Room maps it to an INTEGER column, mapping true to 1 and false to 0.

So, I would expect this to work:

```<code>@Query("SELECT * FROM match WHERE liked = 1 ORDER BY match DESC LIMIT :limit")
</code>```

Bear in mind that this behavior is undocumented. However, it shouldn't change — at least not without alarm klaxons sounding — as we'd need to use migrations to deal with any changes.

Title: Hardcode Boolean Query In Room Database

Body:
I'm building an Android application that displays a list of potential matches for a user. The user can click on one to like the user, and I save all of those likes locally.

I can write a query to get the list of matches like this:

@Query("SELECT * FROM match WHERE liked = :liked ORDER BY match DESC LIMIT :limit")
fun getMatches(limit: Int = 6, liked: Boolean = true): Flowable<List<Match>>

I've learned that this works fine. However, I don't foresee any scenario where I'll ever set liked to false, and so I'm curious if there is a way to hardcode my Boolean condition? If I try:

@Query("SELECT * FROM match WHERE liked = true ORDER BY match DESC LIMIT :limit")

I get the following error at compile time:

Error:(8, 0) Gradle: error: There is a problem with the query: [SQLITE_ERROR] SQL error or missing database (no such column: true)

How can I hard code this Boolean in my query string?

I have also tried:

Wrapping the condition in single quotes

@Query("SELECT * FROM match WHERE liked = 'true' ORDER BY match DESC LIMIT :limit")

Body:
SQLite does not have a boolean data type. Room maps it to an INTEGER column, mapping true to 1 and false to 0.

So, I would expect this to work:

@Query("SELECT * FROM match WHERE liked = 1 ORDER BY match DESC LIMIT :limit")

Bear in mind that this behavior is undocumented. However, it shouldn't change — at least not without alarm klaxons sounding — as we'd need to use migrations to deal with any changes.


问:
What is a possible alternative to these static variables?
I have created a simple GUI engine which I plan to use in a game.
The issue I am having is understanding how to instance a class that will be accessed in multiple stack frames without being static (people have made it quite clear that static variables are just evil).

I have a code example below:

```<code>class MyGame
{
    class InputEngine
    {
        internal void DoInput()
        {
            if (Keys["F1"].IsPressed)
            {
                // Create a window using the gui engine
            }
        }
    }
    class GuiEngine
    {
        internal void Update() { }
        internal void Draw() { }
    }
    private GuiEngine engine;
    private InputEngine input;

    internal MyGame()
    {
        this.input = new InputEngine();
        this.engine = new GuiEngine();
    }

    internal void Update()
    {
        this.engine.Update();
        this.input.DoInput();
    }
    internal void Draw()
    {
        this.engine.Draw();
    }
}
</code>```

How can I access the gui engine instance not only from the input example, but from tens of other places without making it static. (I would really rather not pass it as a parameter).

答: You can use an IoC framework and use dependency injection to have the input engine where you need. Alternativeli you can use the "service locator" pattern.</p>

Body:
I have created a simple GUI engine which I plan to use in a game.
The issue I am having is understanding how to instance a class that will be accessed in multiple stack frames without being static (people have made it quite clear that static variables are just evil).

I have a code example below:

class MyGame
{
    class InputEngine
    {
        internal void DoInput()
        {
            if (Keys["F1"].IsPressed)
            {
                // Create a window using the gui engine
            }
        }
    }
    class GuiEngine
    {
        internal void Update() { }
        internal void Draw() { }
    }
    private GuiEngine engine;
    private InputEngine input;

    internal MyGame()
    {
        this.input = new InputEngine();
        this.engine = new GuiEngine();
    }

    internal void Update()
    {
        this.engine.Update();
        this.input.DoInput();
    }
    internal void Draw()
    {
        this.engine.Draw();
    }
}

How can I access the gui engine instance not only from the input example, but from tens of other places without making it static. (I would really rather not pass it as a parameter).


问:
Python 3: using requests does not get the full content of a web page
I am testing using the requests module to get the content of a webpage. But when I look at the content I see that it does not get the full content of the page.

Here is my code:

```<code>import requests
from bs4 import BeautifulSoup

url = "https://shop.nordstrom.com/c/womens-dresses-shop?origin=topnav&cm_sp=Top%20Navigation-_-Women-_-Dresses&offset=11&page=3&top=72"
page = requests.get(url)

soup = BeautifulSoup(page.content, 'html.parser')
print(soup.prettify())
</code>```

Also on the chrome web-browser if I look at the page source I do not see the full content.

Is there a way to get the full content of the example page that I have provided?

答:
The page is rendered with JavaScript making more requests to fetch additional data. You can fetch the complete page with selenium.

```<code>from bs4 import BeautifulSoup
from selenium import webdriver
driver = webdriver.Chrome()
url = "https://shop.nordstrom.com/c/womens-dresses-shop?origin=topnav&cm_sp=Top%20Navigation-_-Women-_-Dresses&offset=11&page=3&top=72"
driver.get(url)
soup = BeautifulSoup(driver.page_source, 'html.parser')
driver.quit()
print(soup.prettify())
</code>```

For other solutions see my answer to Scraping Google Finance (BeautifulSoup)

Body:
I am testing using the requests module to get the content of a webpage. But when I look at the content I see that it does not get the full content of the page.

Here is my code:

import requests
from bs4 import BeautifulSoup

url = "https://shop.nordstrom.com/c/womens-dresses-shop?origin=topnav&cm_sp=Top%20Navigation-_-Women-_-Dresses&offset=11&page=3&top=72"
page = requests.get(url)

soup = BeautifulSoup(page.content, 'html.parser')
print(soup.prettify())

Also on the chrome web-browser if I look at the page source I do not see the full content.

Is there a way to get the full content of the example page that I have provided?

Body:
The page is rendered with JavaScript making more requests to fetch additional data. You can fetch the complete page with selenium.

from bs4 import BeautifulSoup
from selenium import webdriver
driver = webdriver.Chrome()
url = "https://shop.nordstrom.com/c/womens-dresses-shop?origin=topnav&cm_sp=Top%20Navigation-_-Women-_-Dresses&offset=11&page=3&top=72"
driver.get(url)
soup = BeautifulSoup(driver.page_source, 'html.parser')
driver.quit()
print(soup.prettify())

For other solutions see my answer to Scraping Google Finance (BeautifulSoup)


答:
Perhaps you could implement the singleton pattern in your game engine type?
If you're not ever creating more than 1 object instances of it, I think this is the ideal choice.

Otherwise you could try using an IoC solution, like Mincrosoft's Unity.

Title: What is a possible alternative to these static variables?


问:
warning: field width specifier '*' expects argument of type 'int', but argument 2 has type 'size_t' {aka 'long unsigned int'}
Code:

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

int main(void) {
    int number = 2;
    printf("%*s\n", strlen("foo") + number, "foo");
    return 0;
}
</code>```

Warning:

```<code>prog.c: In function 'main':
prog.c:5:14: warning: field width specifier '*' expects argument of type 'int', but argument 2 has type 'size_t' {aka 'long unsigned int'} [-Wformat=]
     printf("%*s\n", strlen("foo") + number, "foo");
             ~^~     ~~~~~~~~~~~~~~~~~
</code>```

Is it possible to eliminate this warning without casting the result of strlen() to an int, while keeping the width specifier as a variable? If yes, how?

答:
printf expects an int for * , so just give it an int.-->> cast it to int.

```<code>printf("%*s\n", (int)(strlen("foo")+number), "foo");
</code>```

But if you want to avoid the cast, you could use a variable for the length argument:

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

int main(void) {
    int number = 2;
    int fmtlen;

    fmtlen = strlen("foo") + number;
    printf("%*s\n", fmtlen, "foo");
    return 0;
}
</code>```

Note: the correct types are essential for printf()s arguments, since it is a varargs function: the only way for printf to determine the types of its arguments is by inpecting the format string. And * expects an int.

Body:
Code:

#include <stdio.h>
#include <string.h>

int main(void) {
    int number = 2;
    printf("%*s\n", strlen("foo") + number, "foo");
    return 0;
}

Warning:

prog.c: In function 'main':
prog.c:5:14: warning: field width specifier '*' expects argument of type 'int', but argument 2 has type 'size_t' {aka 'long unsigned int'} [-Wformat=]
     printf("%*s\n", strlen("foo") + number, "foo");
             ~^~     ~~~~~~~~~~~~~~~~~

Is it possible to eliminate this warning without casting the result of strlen() to an int, while keeping the width specifier as a variable? If yes, how?

Body:
printf expects an int for * , so just give it an int.-->> cast it to int.

printf("%*s\n", (int)(strlen("foo")+number), "foo");

But if you want to avoid the cast, you could use a variable for the length argument:

#include <stdio.h>
#include <string.h>

int main(void) {
    int number = 2;
    int fmtlen;

    fmtlen = strlen("foo") + number;
    printf("%*s\n", fmtlen, "foo");
    return 0;
}

Note: the correct types are essential for printf()s arguments, since it is a varargs function: the only way for printf to determine the types of its arguments is by inpecting the format string. And * expects an int.


问:
SharedPreferences helper class
I am doing SharedPreferences helper class to make my code looks nice.

```<code>public class SharedPreferencesHelper {
    Context context;

    public SharedPreferencesHelper(Context context){
        this.context = context;
    }

    public boolean isLogged(String prefs){
        return context.getSharedPreferences(prefs,Context.MODE_PRIVATE)
                      .getBoolean("LOGGED",false);
    }

    public void setLogged(String prefs){
        context.getSharedPreferences(prefs,Context.MODE_PRIVATE)
               .edit().putBoolean("LOGGED",true).apply();
    }
}
</code>```

The question is should I make these methods static and initialize SharedPreferences in each method or better to left it not static and call SharedPreferencesHelper class once from my other classes? Thanks

答:
I ended up with singleton pattern, keeping only one instance at the time:

```<code>import android.content.Context;
import android.support.annotation.NonNull;

public class SharedPrefsUtil {
    private static SharedPrefsUtil instance;
    private static final String PREFS_NAME = "default_preferences";

    public synchronized static SharedPrefsUtil getInstance() {
        if (instance == null) {
            instance = new SharedPrefsUtil();
        }
        return instance;
    }

    private SharedPrefsUtil() {
    }

    public boolean isLoggedIn(@NonNull Context context) {
        return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
                .getBoolean("LOGGED", false);
    }

    public void setLoggedIn(@NonNull Context context, boolean value) {
        context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
                .edit().putBoolean("LOGGED", value).apply();
    }
}
</code>```

Note the same singleton could be easily achieved using Dagger library.

Title: SharedPreferences helper class

Body:
I am doing SharedPreferences helper class to make my code looks nice.

public class SharedPreferencesHelper {
    Context context;

    public SharedPreferencesHelper(Context context){
        this.context = context;
    }

    public boolean isLogged(String prefs){
        return context.getSharedPreferences(prefs,Context.MODE_PRIVATE)
                      .getBoolean("LOGGED",false);
    }

    public void setLogged(String prefs){
        context.getSharedPreferences(prefs,Context.MODE_PRIVATE)
               .edit().putBoolean("LOGGED",true).apply();
    }
}

The question is should I make these methods static and initialize SharedPreferences in each method or better to left it not static and call SharedPreferencesHelper class once from my other classes? Thanks

Body:
I ended up with singleton pattern, keeping only one instance at the time:

import android.content.Context;
import android.support.annotation.NonNull;

public class SharedPrefsUtil {
    private static SharedPrefsUtil instance;
    private static final String PREFS_NAME = "default_preferences";

    public synchronized static SharedPrefsUtil getInstance() {
        if (instance == null) {
            instance = new SharedPrefsUtil();
        }
        return instance;
    }

    private SharedPrefsUtil() {
    }

    public boolean isLoggedIn(@NonNull Context context) {
        return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
                .getBoolean("LOGGED", false);
    }

    public void setLoggedIn(@NonNull Context context, boolean value) {
        context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
                .edit().putBoolean("LOGGED", value).apply();
    }
}

Note the same singleton could be easily achieved using Dagger library.


答: The technique is called dependency injection. In effect you are "injecting" the "static variable" into the instance. As far as the instance is concerned it's a normal instance variable. You simply pass your instance of the gui to the constructor. </p>


问:
IOS App archive and uploading
When I tried to archive the app I just created, I received this error. Is there any guru who can help me explain this issue and give me instruction step by step how to fix this problem. Appreciate it.

But there really is one in my keychain

答:
If you sure your Profile is same as you selected in General Tab drop down. Also, you are confident that you are having the p12 for the profile. Do the following.

Go to the Build Settings tab and navigate to codesign. In that section, there is CodeSign, Provisioning profile and profile(deprecated), team selection. Please select those manually so they don't have "Multiple values"  displayed. Go to each line and do the right profile selection.

Optional: If you have another targets and extn associated with the app make sure to go in the capabilities group and select the ones that are enabled in the provisioning -profile. (You may check this from your developer portal) I face that my AppGroupID was selected wrongly once to profile I selected in the 1st tab of General.

Once the build settings are done correcting the General tab will show no issues. Try this.

Title: IOS App archive and uploading