问:
jQuery - hide input if maxTags reached using tags.js
Using the tags() function, there is a parameter for maximum number of tags (maxTags) you can enter into each input.

I need to hide(); the tags-input when maxTags = 2 and then
    show(); when the tag is removed / not at the max.

maxTags :1 isn't working but it should be. Only 2 or more is acceptable. I tried debugging the max tags parameter but couldn't find out why maxTags: 1 is
unacceptable.

How can I change the function to allow maxTags: 1 and also show/hide the tag-input when maxTags is reached?

```<code>// max tags in tags() function:

      if (opts.maxTags) {
        if ($self.val().split(",").length == opts.maxTags) {
          otherCheck = false;
          $input.val("");
          $next.val("");
        }
      }

// Calling the tags() function:

    $("#" + formId)
      .find(".input--proj")
      .tags({
        unique: true,
        maxTags: 2
      })
      .autofill({
        data: autolist
      });
</code>```

(function($) {
  $.fn.tags = function(opts) {
    var selector = this.selector;
    //console.log("selector",selector);
    // updates the original input
    function update($original) {
      var all = [];
      var list = $original.closest(".tags-wrapper").find("li.tag span").each(function() {
        all.push($(this).text());
      });
      all = all.join(",");
      $original.val(all);
    }

    return this.each(function() {
      var self = this,
        $self = $(this),
        $wrapper = $("

</div");
      tags = $self.val(),
        tagsArray = tags.split(","),
        $ul = $wrapper.find("ul");

      // make sure have opts
      if (!opts) opts = {};
      opts.maxSize = 50;

      // add tags to start
      tagsArray.forEach(function(tag) {
        if (tag) {
          $ul.append("
" + tag + "x
");
        }
      });

      // get classes on this element
      if (opts.classList) $wrapper.addClass(opts.classList);

      // add input
      $ul.append("
<input type='text' class='tags-secret'/>
");
      // set to dom
      $self.after($wrapper);
      // add the old element
      $wrapper.append($self);

      // size the text
      var $input = $ul.find("input"),
        size = parseInt($input.css("font-size")) - 4;
      // delete a tag
      $wrapper.on("click", "li.tag a", function(e) {
        e.preventDefault();
        $(this).closest("li").remove();
        $self.trigger("tagRemove", $(this).closest("li").find("span").text());
        update($self);
        $("[data-search]").keyup();
      });

      // backspace needs to check before keyup
      $wrapper.on("keydown", "li input", function(e) {
        // backspace
        if (e.keyCode == 8 && !$input.val()) {
          var $li = $ul.find("li.tag:last").remove();
          update($self);
          $self.trigger("tagRemove", $li.find("span").text());
        }
        // prevent for tab
        if (e.keyCode == 9) {
          e.preventDefault();
        }

      });

      // as we type
      $wrapper.on("keyup", "li input", function(e) {
        e.preventDefault();
        $ul = $wrapper.find("ul");
        var $next = $input.next(),
          usingAutoFill = $next.hasClass("autofill-bg"),
          $inputLi = $ul.find("li.tags-input");

        // regular size adjust
        $input.width($input.val().length * (size));

        // if combined with autofill, check the bg for size
        if (usingAutoFill) {
          $next.width($next.val().length * (size));
          $input.width($next.val().length * (size));
          // make sure autofill doesn't get too big
          if ($next.width() < opts.maxSize) $next.width(opts.maxSize);
          var list = $next.data().data;
        }

        // make sure we don't get too high
        if ($input.width() < opts.maxSize) $input.width(opts.maxSize);

        // tab, comma, enter
        if (!!~[9, 188, 13].indexOf(e.keyCode)) {

          var val = $input.val().replace(",", "");
          var otherCheck = true;

          // requring a tag to be in autofill
          if (opts.requireData && usingAutoFill) {
            if (!~list.indexOf(val)) {
              otherCheck = false;
              $input.val("");
            }
          }

          // unique
          if (opts.unique) {
            // found a match already there
            if (!!~$self.val().split(",").indexOf(val)) {
              otherCheck = false;
              $input.val("");
              $next.val("");
            }
          }

          // max tags
          if (opts.maxTags) {
            if ($self.val().split(",").length == opts.maxTags) {
              otherCheck = false;
              $input.val("");
              $next.val("");
            }
          }

          // if we have a value, and other checks pass, add the tag
          if (val && otherCheck) {
            // place the new tag
            $inputLi.before("
" + val + "x
");
            // clear the values
            $input.val("");
            if (usingAutoFill) $next.val("");
            update($self);
            $self.trigger("tagAdd", val);
          }

        }

      });

    });
  }
})(jQuery);
var uniqueId = 1;
$(function() {
  $(".btn--new").click(function() {
    var copy = $("#s_item").clone(true, true);
    var formId = "item_" + uniqueId;
    copy.attr("id", formId);
    $("#s_list").append(copy);
    $("#" + formId)
      .find(".input--proj")
      .each(function() {
        var autolist = new Array();
        $.each($(".studio__project"), function(index, value) {
          if ($.inArray($(value).attr("data-proj"), autolist) < 1) {
            autolist.push($(value).attr("data-proj").toLowerCase());
          }
        });
        $("#" + formId)
          .find(".input--proj")
          .tags({
            unique: true,
            maxTags: 2
          })
          .autofill({
            data: autolist
          });

        function placeholderproj() {
          $(".search__label--proj")
            .find(".tags-secret")
            .attr("placeholder", "Enter Keyword");
        }
        $(document).ready(placeholderproj);
      });
    uniqueId++;
  });
});
$(document).on("keyup , keypress", "li input", function(e) {
  $.each($(".tag"), function(index, value) {
    $.each($(".studio__project"), function(subIndex, subValue) {
      if (
        $(subValue).attr("data-proj").toLowerCase() ==
        $(value).find("span").html()
      ) {
        var itemColor = $(subValue).attr("data-color");
        $(value).css("background-color", itemColor);
      }
    });
  });
  $("[data-search]").keyup();
});
$(document).on("click", ".tag a", function(e) {
  $("[data-search]").keyup();
});
$(document).ready(function() {
  $(".btn--new").trigger("click");
  $(".btn--new").trigger("click");
  $(".btn--new").trigger("click");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>::-webkit-input-placeholder {
  /* Chrome/Opera/Safari */
  color: #8e8e8e;
}

::-moz-placeholder {
  /* Firefox 19+ */
  color: #8e8e8e;
}

:-ms-input-placeholder {
  /* IE 10+ */
  color: #8e8e8e;
}

:-moz-placeholder {
  /* Firefox 18- */
  color: #8e8e8e;
}

.tags-wrapper {
  background: white;
  display: flex;
  position: relative;
  width: 100%;
  height: 50px;
  top: -1px;
  border: 1px solid whitesmoke;
  overflow: hidden;
}

.tags-wrapper ul {
  position: absolute;
  display: flex;
  flex: 1;
  align-items: center;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  list-style-type: none;
  margin: 0;
  padding: 0;
}

.tags-wrapper li {
  flex-grow: 1;
  margin-left: 5px;
}

.tags-wrapper li input {
  display: block;
  border: none;
  width: 100% !important;
}

.tags-wrapper li.tag {
  display: flex;
  flex-grow: 0;
  position: relative;
  padding: 10px;
  font-size: 14px;
  align-items: center;
  border-radius: 5px;
  list-style: none;
  background-image: none;
  box-shadow: none;
  color: white;
}

.tags-wrapper li a {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  text-decoration: none;
  color: rgba(0, 0, 0, 0);
}

.tags-wrapper li a:hover {
  background-color: rgba(0, 0, 0, 0.4);
  border-radius: 5px;
  color: rgba(0, 0, 0);
  background-image: url("http://svgshare.com/i/3yv.svg");
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

.tags-wrapper input {
  display: none;
}

#s_item {
  display: none
}</code>```

Create

keywords are: blue, red, green

          <input type="text" class="input--proj" autocomplete="off" placeholder="">

```

答:
I've added code to test maxTags value from 1 to 3.  Just replace it.

Removed a tag.  Show input.

```<code>  $wrapper.on("click", "li.tag a", function(e) {
    e.preventDefault();
    $(this).closest("li").remove();
    $self.trigger("tagRemove", $(this).closest("li").find("span").text());
    update($self);
    $("[data-search]").keyup();

    $input.show(); // show input on remove
  });
</code>```

If string has no content, return 0.  Else use split to find number of elements.

```<code>      if (opts.maxTags) {
        var len = $self.val();
        len = len.trim().length > 0 ? len.split(',').length : 0;
</code>```

(function($) {
  $.fn.tags = function(opts) {
    var selector = this.selector;
    //console.log("selector",selector);
    // updates the original input
    function update($original) {
      var all = [];
      var list = $original.closest(".tags-wrapper").find("li.tag span").each(function() {
        all.push($(this).text());
      });
      all = all.join(",");
      $original.val(all);
    }

    return this.each(function() {
      var self = this,
        $self = $(this),
        $wrapper = $("

</div");
      tags = $self.val(),
        tagsArray = tags.split(","),
        $ul = $wrapper.find("ul");

      // make sure have opts
      if (!opts) opts = {};
      opts.maxSize = 50;

      // add tags to start
      tagsArray.forEach(function(tag) {
        if (tag) {
          $ul.append("
" + tag + "x
");
        }
      });

      // get classes on this element
      if (opts.classList) $wrapper.addClass(opts.classList);

      // add input
      $ul.append("
<input type='text' class='tags-secret'/>
");
      // set to dom
      $self.after($wrapper);
      // add the old element
      $wrapper.append($self);

      // size the text
      var $input = $ul.find("input"),
        size = parseInt($input.css("font-size")) - 4;
      // delete a tag
      $wrapper.on("click", "li.tag a", function(e) {
        e.preventDefault();
        $(this).closest("li").remove();
        $self.trigger("tagRemove", $(this).closest("li").find("span").text());
        update($self);
        $("[data-search]").keyup();

        $input.show(); // show input on remove
      });

      // backspace needs to check before keyup
      $wrapper.on("keydown", "li input", function(e) {
        // backspace
        if (e.keyCode == 8 && !$input.val()) {
          var $li = $ul.find("li.tag:last").remove();
          update($self);
          $self.trigger("tagRemove", $li.find("span").text());
        }
        // prevent for tab
        if (e.keyCode == 9) {
          e.preventDefault();
        }

      });

      // as we type
      $wrapper.on("keyup", "li input", function(e) {
        e.preventDefault();
        $ul = $wrapper.find("ul");
        var $next = $input.next(),
          usingAutoFill = $next.hasClass("autofill-bg"),
          $inputLi = $ul.find("li.tags-input");

        // regular size adjust
        $input.width($input.val().length * (size));

        // if combined with autofill, check the bg for size
        if (usingAutoFill) {
          $next.width($next.val().length * (size));
          $input.width($next.val().length * (size));
          // make sure autofill doesn't get too big
          if ($next.width() < opts.maxSize) $next.width(opts.maxSize);
          var list = $next.data().data;
        }

        // make sure we don't get too high
        if ($input.width() < opts.maxSize) $input.width(opts.maxSize);

        // tab, comma, enter
        if (!!~[9, 188, 13].indexOf(e.keyCode)) {

          var val = $input.val().replace(",", "");
          var otherCheck = true;

          // requring a tag to be in autofill
          if (opts.requireData && usingAutoFill) {
            if (!~list.indexOf(val)) {
              otherCheck = false;
              $input.val("");
            }
          }

          // unique
          if (opts.unique) {
            // found a match already there
            if (!!~$self.val().split(",").indexOf(val)) {
              otherCheck = false;
              $input.val("");
              $next.val("");
            }
          }

          // max tags
          if (opts.maxTags) {
            var len = $self.val();
            len = len.trim().length > 0 ? len.split(',').length : 0;
            if (len == opts.maxTags - 1) $input.hide();
            if (len == opts.maxTags) {
              otherCheck = false;
              $input.val("");
              $next.val("");
            }
          }

          // if we have a value, and other checks pass, add the tag
          if (val && otherCheck) {
            // place the new tag
            $inputLi.before("
" + val + "x
");
            // clear the values
            $input.val("");
            if (usingAutoFill) $next.val("");
            update($self);
            $self.trigger("tagAdd", val);
          }

        }

      });

    });
  }
})(jQuery);
var uniqueId = 1;

$(function() {
  $(".btn--new").click(function() {
    var copy = $("#s_item").clone(true, true);
    var formId = "item_" + uniqueId;
    copy.attr("id", formId);
    $("#s_list").append(copy);
    $("#" + formId)
      .find(".input--proj")
      .each(function() {
        var autolist = new Array();
        $.each($(".studio__project"), function(index, value) {
          if ($.inArray($(value).attr("data-proj"), autolist) < 1) {
            autolist.push($(value).attr("data-proj").toLowerCase());
          }
        });
        $("#" + formId)
          .find(".input--proj")
          .tags({
            unique: true,
            maxTags: 1
          })
          .autofill({
            data: autolist
          });

        function placeholderproj() {
          $(".search__label--proj")
            .find(".tags-secret")
            .attr("placeholder", "Enter Keyword");
        }
        $(document).ready(placeholderproj);
      });
    uniqueId++;
  });
});
$(document).on("keyup , keypress", "li input", function(e) {
  $.each($(".tag"), function(index, value) {
    $.each($(".studio__project"), function(subIndex, subValue) {
      if (
        $(subValue).attr("data-proj").toLowerCase() ==
        $(value).find("span").html()
      ) {
        var itemColor = $(subValue).attr("data-color");
        $(value).css("background-color", itemColor);
      }
    });
  });
  $("[data-search]").keyup();
});
$(document).on("click", ".tag a", function(e) {
  $("[data-search]").keyup();
});
$(document).ready(function() {
  $(".btn--new").trigger("click");
  $(".btn--new").trigger("click");
  $(".btn--new").trigger("click");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>::-webkit-input-placeholder {
  /* Chrome/Opera/Safari */
  color: #8e8e8e;
}

::-moz-placeholder {
  /* Firefox 19+ */
  color: #8e8e8e;
}

:-ms-input-placeholder {
  /* IE 10+ */
  color: #8e8e8e;
}

:-moz-placeholder {
  /* Firefox 18- */
  color: #8e8e8e;
}

.tags-wrapper {
  background: white;
  display: flex;
  position: relative;
  width: 100%;
  height: 50px;
  top: -1px;
  border: 1px solid whitesmoke;
  overflow: hidden;
}

.tags-wrapper ul {
  position: absolute;
  display: flex;
  flex: 1;
  align-items: center;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  list-style-type: none;
  margin: 0;
  padding: 0;
}

.tags-wrapper li {
  flex-grow: 1;
  margin-left: 5px;
}

.tags-wrapper li input {
  display: block;
  border: none;
  width: 100% !important;
}

.tags-wrapper li.tag {
  display: flex;
  flex-grow: 0;
  position: relative;
  padding: 10px;
  font-size: 14px;
  align-items: center;
  border-radius: 5px;
  list-style: none;
  background-image: none;
  box-shadow: none;
  color: white;
}

.tags-wrapper li a {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  text-decoration: none;
  color: rgba(0, 0, 0, 0);
}

.tags-wrapper li a:hover {
  background-color: rgba(0, 0, 0, 0.4);
  border-radius: 5px;
  color: rgba(0, 0, 0);
  background-image: url("http://svgshare.com/i/3yv.svg");
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

.tags-wrapper input {
  display: none;
}

#s_item {
  display: none
}</code>```

Create

keywords are: blue, red, green

          <input type="text" class="input--proj" autocomplete="off" placeholder="">

```

Body:
Using the tags() function, there is a parameter for maximum number of tags (maxTags) you can enter into each input.

I need to hide(); the tags-input when maxTags = 2 and then
    show(); when the tag is removed / not at the max.

maxTags :1 isn't working but it should be. Only 2 or more is acceptable. I tried debugging the max tags parameter but couldn't find out why maxTags: 1 is
unacceptable.

How can I change the function to allow maxTags: 1 and also show/hide the tag-input when maxTags is reached?

// max tags in tags() function:

      if (opts.maxTags) {
        if ($self.val().split(",").length == opts.maxTags) {
          otherCheck = false;
          $input.val("");
          $next.val("");
        }
      }

// Calling the tags() function:

    $("#" + formId)
      .find(".input--proj")
      .tags({
        unique: true,
        maxTags: 2
      })
      .autofill({
        data: autolist
      });

(function($) {
  $.fn.tags = function(opts) {
    var selector = this.selector;
    //console.log("selector",selector);
    // updates the original input
    function update($original) {
      var all = [];
      var list = $original.closest(".tags-wrapper").find("li.tag span").each(function() {
        all.push($(this).text());
      });
      all = all.join(",");
      $original.val(all);
    }

    return this.each(function() {
      var self = this,
        $self = $(this),
        $wrapper = $("

</div");
      tags = $self.val(),
        tagsArray = tags.split(","),
        $ul = $wrapper.find("ul");

      // make sure have opts
      if (!opts) opts = {};
      opts.maxSize = 50;

      // add tags to start
      tagsArray.forEach(function(tag) {
        if (tag) {
          $ul.append("
" + tag + "x
");
        }
      });

      // get classes on this element
      if (opts.classList) $wrapper.addClass(opts.classList);

      // add input
      $ul.append("
<input type='text' class='tags-secret'/>
");
      // set to dom
      $self.after($wrapper);
      // add the old element
      $wrapper.append($self);

      // size the text
      var $input = $ul.find("input"),
        size = parseInt($input.css("font-size")) - 4;
      // delete a tag
      $wrapper.on("click", "li.tag a", function(e) {
        e.preventDefault();
        $(this).closest("li").remove();
        $self.trigger("tagRemove", $(this).closest("li").find("span").text());
        update($self);
        $("[data-search]").keyup();
      });

      // backspace needs to check before keyup
      $wrapper.on("keydown", "li input", function(e) {
        // backspace
        if (e.keyCode == 8 && !$input.val()) {
          var $li = $ul.find("li.tag:last").remove();
          update($self);
          $self.trigger("tagRemove", $li.find("span").text());
        }
        // prevent for tab
        if (e.keyCode == 9) {
          e.preventDefault();
        }

      });

      // as we type
      $wrapper.on("keyup", "li input", function(e) {
        e.preventDefault();
        $ul = $wrapper.find("ul");
        var $next = $input.next(),
          usingAutoFill = $next.hasClass("autofill-bg"),
          $inputLi = $ul.find("li.tags-input");

        // regular size adjust
        $input.width($input.val().length * (size));

        // if combined with autofill, check the bg for size
        if (usingAutoFill) {
          $next.width($next.val().length * (size));
          $input.width($next.val().length * (size));
          // make sure autofill doesn't get too big
          if ($next.width() < opts.maxSize) $next.width(opts.maxSize);
          var list = $next.data().data;
        }

        // make sure we don't get too high
        if ($input.width() < opts.maxSize) $input.width(opts.maxSize);

        // tab, comma, enter
        if (!!~[9, 188, 13].indexOf(e.keyCode)) {

          var val = $input.val().replace(",", "");
          var otherCheck = true;

          // requring a tag to be in autofill
          if (opts.requireData && usingAutoFill) {
            if (!~list.indexOf(val)) {
              otherCheck = false;
              $input.val("");
            }
          }

          // unique
          if (opts.unique) {
            // found a match already there
            if (!!~$self.val().split(",").indexOf(val)) {
              otherCheck = false;
              $input.val("");
              $next.val("");
            }
          }

          // max tags
          if (opts.maxTags) {
            if ($self.val().split(",").length == opts.maxTags) {
              otherCheck = false;
              $input.val("");
              $next.val("");
            }
          }

          // if we have a value, and other checks pass, add the tag
          if (val && otherCheck) {
            // place the new tag
            $inputLi.before("
" + val + "x
");
            // clear the values
            $input.val("");
            if (usingAutoFill) $next.val("");
            update($self);
            $self.trigger("tagAdd", val);
          }

        }

      });

    });
  }
})(jQuery);
var uniqueId = 1;
$(function() {
  $(".btn--new").click(function() {
    var copy = $("#s_item").clone(true, true);
    var formId = "item_" + uniqueId;
    copy.attr("id", formId);
    $("#s_list").append(copy);
    $("#" + formId)
      .find(".input--proj")
      .each(function() {
        var autolist = new Array();
        $.each($(".studio__project"), function(index, value) {
          if ($.inArray($(value).attr("data-proj"), autolist) < 1) {
            autolist.push($(value).attr("data-proj").toLowerCase());
          }
        });
        $("#" + formId)
          .find(".input--proj")
          .tags({
            unique: true,
            maxTags: 2
          })
          .autofill({
            data: autolist
          });

        function placeholderproj() {
          $(".search__label--proj")
            .find(".tags-secret")
            .attr("placeholder", "Enter Keyword");
        }
        $(document).ready(placeholderproj);
      });
    uniqueId++;
  });
});
$(document).on("keyup , keypress", "li input", function(e) {
  $.each($(".tag"), function(index, value) {
    $.each($(".studio__project"), function(subIndex, subValue) {
      if (
        $(subValue).attr("data-proj").toLowerCase() ==
        $(value).find("span").html()
      ) {
        var itemColor = $(subValue).attr("data-color");
        $(value).css("background-color", itemColor);
      }
    });
  });
  $("[data-search]").keyup();
});
$(document).on("click", ".tag a", function(e) {
  $("[data-search]").keyup();
});
$(document).ready(function() {
  $(".btn--new").trigger("click");
  $(".btn--new").trigger("click");
  $(".btn--new").trigger("click");
});

::-webkit-input-placeholder {
  /* Chrome/Opera/Safari */
  color: #8e8e8e;
}

::-moz-placeholder {
  /* Firefox 19+ */
  color: #8e8e8e;
}

:-ms-input-placeholder {
  /* IE 10+ */
  color: #8e8e8e;
}

:-moz-placeholder {
  /* Firefox 18- */
  color: #8e8e8e;
}

.tags-wrapper {
  background: white;
  display: flex;
  position: relative;
  width: 100%;
  height: 50px;
  top: -1px;
  border: 1px solid whitesmoke;
  overflow: hidden;
}

.tags-wrapper ul {
  position: absolute;
  display: flex;
  flex: 1;
  align-items: center;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  list-style-type: none;
  margin: 0;
  padding: 0;
}

.tags-wrapper li {
  flex-grow: 1;
  margin-left: 5px;
}

.tags-wrapper li input {
  display: block;
  border: none;
  width: 100% !important;
}

.tags-wrapper li.tag {
  display: flex;
  flex-grow: 0;
  position: relative;
  padding: 10px;
  font-size: 14px;
  align-items: center;
  border-radius: 5px;
  list-style: none;
  background-image: none;
  box-shadow: none;
  color: white;
}

.tags-wrapper li a {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  text-decoration: none;
  color: rgba(0, 0, 0, 0);
}

.tags-wrapper li a:hover {
  background-color: rgba(0, 0, 0, 0.4);
  border-radius: 5px;
  color: rgba(0, 0, 0);
  background-image: url("http://svgshare.com/i/3yv.svg");
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

.tags-wrapper input {
  display: none;
}

#s_item {
  display: none
}

Create

keywords are: blue, red, green

          <input type="text" class="input--proj" autocomplete="off" placeholder="">

Body:
I've added code to test maxTags value from 1 to 3.  Just replace it.

Removed a tag.  Show input.

  $wrapper.on("click", "li.tag a", function(e) {
    e.preventDefault();
    $(this).closest("li").remove();
    $self.trigger("tagRemove", $(this).closest("li").find("span").text());
    update($self);
    $("[data-search]").keyup();

    $input.show(); // show input on remove
  });

If string has no content, return 0.  Else use split to find number of elements.

      if (opts.maxTags) {
        var len = $self.val();
        len = len.trim().length > 0 ? len.split(',').length : 0;

(function($) {
  $.fn.tags = function(opts) {
    var selector = this.selector;
    //console.log("selector",selector);
    // updates the original input
    function update($original) {
      var all = [];
      var list = $original.closest(".tags-wrapper").find("li.tag span").each(function() {
        all.push($(this).text());
      });
      all = all.join(",");
      $original.val(all);
    }

    return this.each(function() {
      var self = this,
        $self = $(this),
        $wrapper = $("<div class='tags-wrapper'><ul></ul></div");
      tags = $self.val(),
        tagsArray = tags.split(","),
        $ul = $wrapper.find("ul");

      // make sure have opts
      if (!opts) opts = {};
      opts.maxSize = 50;

      // add tags to start
      tagsArray.forEach(function(tag) {
        if (tag) {
          $ul.append("<li class='tag'><span>" + tag + "</span><a href='#'>x</a></li>");
        }
      });

      // get classes on this element
      if (opts.classList) $wrapper.addClass(opts.classList);

      // add input
      $ul.append("<li class='tags-input'><input type='text' class='tags-secret'/></li>");
      // set to dom
      $self.after($wrapper);
      // add the old element
      $wrapper.append($self);

      // size the text
      var $input = $ul.find("input"),
        size = parseInt($input.css("font-size")) - 4;
      // delete a tag
      $wrapper.on("click", "li.tag a", function(e) {
        e.preventDefault();
        $(this).closest("li").remove();
        $self.trigger("tagRemove", $(this).closest("li").find("span").text());
        update($self);
        $("[data-search]").keyup();

        $input.show(); // show input on remove
      });

      // backspace needs to check before keyup
      $wrapper.on("keydown", "li input", function(e) {
        // backspace
        if (e.keyCode == 8 && !$input.val()) {
          var $li = $ul.find("li.tag:last").remove();
          update($self);
          $self.trigger("tagRemove", $li.find("span").text());
        }
        // prevent for tab
        if (e.keyCode == 9) {
          e.preventDefault();
        }

      });

      // as we type
      $wrapper.on("keyup", "li input", function(e) {
        e.preventDefault();
        $ul = $wrapper.find("ul");
        var $next = $input.next(),
          usingAutoFill = $next.hasClass("autofill-bg"),
          $inputLi = $ul.find("li.tags-input");

        // regular size adjust
        $input.width($input.val().length * (size));

        // if combined with autofill, check the bg for size
        if (usingAutoFill) {
          $next.width($next.val().length * (size));
          $input.width($next.val().length * (size));
          // make sure autofill doesn't get too big
          if ($next.width() < opts.maxSize) $next.width(opts.maxSize);
          var list = $next.data().data;
        }

        // make sure we don't get too high
        if ($input.width() < opts.maxSize) $input.width(opts.maxSize);

        // tab, comma, enter
        if (!!~[9, 188, 13].indexOf(e.keyCode)) {

          var val = $input.val().replace(",", "");
          var otherCheck = true;

          // requring a tag to be in autofill
          if (opts.requireData && usingAutoFill) {
            if (!~list.indexOf(val)) {
              otherCheck = false;
              $input.val("");
            }
          }

          // unique
          if (opts.unique) {
            // found a match already there
            if (!!~$self.val().split(",").indexOf(val)) {
              otherCheck = false;
              $input.val("");
              $next.val("");
            }
          }

          // max tags
          if (opts.maxTags) {
            var len = $self.val();
            len = len.trim().length > 0 ? len.split(',').length : 0;
            if (len == opts.maxTags - 1) $input.hide();
            if (len == opts.maxTags) {
              otherCheck = false;
              $input.val("");
              $next.val("");
            }
          }

          // if we have a value, and other checks pass, add the tag
          if (val && otherCheck) {
            // place the new tag
            $inputLi.before("<li class='tag'><span>" + val + "</span><a href='#'>x</a></li>");
            // clear the values
            $input.val("");
            if (usingAutoFill) $next.val("");
            update($self);
            $self.trigger("tagAdd", val);
          }

        }

      });

    });
  }
})(jQuery);
var uniqueId = 1;

$(function() {
  $(".btn--new").click(function() {
    var copy = $("#s_item").clone(true, true);
    var formId = "item_" + uniqueId;
    copy.attr("id", formId);
    $("#s_list").append(copy);
    $("#" + formId)
      .find(".input--proj")
      .each(function() {
        var autolist = new Array();
        $.each($(".studio__project"), function(index, value) {
          if ($.inArray($(value).attr("data-proj"), autolist) < 1) {
            autolist.push($(value).attr("data-proj").toLowerCase());
          }
        });
        $("#" + formId)
          .find(".input--proj")
          .tags({
            unique: true,
            maxTags: 1
          })
          .autofill({
            data: autolist
          });

        function placeholderproj() {
          $(".search__label--proj")
            .find(".tags-secret")
            .attr("placeholder", "Enter Keyword");
        }
        $(document).ready(placeholderproj);
      });
    uniqueId++;
  });
});
$(document).on("keyup , keypress", "li input", function(e) {
  $.each($(".tag"), function(index, value) {
    $.each($(".studio__project"), function(subIndex, subValue) {
      if (
        $(subValue).attr("data-proj").toLowerCase() ==
        $(value).find("span").html()
      ) {
        var itemColor = $(subValue).attr("data-color");
        $(value).css("background-color", itemColor);
      }
    });
  });
  $("[data-search]").keyup();
});
$(document).on("click", ".tag a", function(e) {
  $("[data-search]").keyup();
});
$(document).ready(function() {
  $(".btn--new").trigger("click");
  $(".btn--new").trigger("click");
  $(".btn--new").trigger("click");
});

::-webkit-input-placeholder {
  /* Chrome/Opera/Safari */
  color: #8e8e8e;
}

::-moz-placeholder {
  /* Firefox 19+ */
  color: #8e8e8e;
}

:-ms-input-placeholder {
  /* IE 10+ */
  color: #8e8e8e;
}

:-moz-placeholder {
  /* Firefox 18- */
  color: #8e8e8e;
}

.tags-wrapper {
  background: white;
  display: flex;
  position: relative;
  width: 100%;
  height: 50px;
  top: -1px;
  border: 1px solid whitesmoke;
  overflow: hidden;
}

.tags-wrapper ul {
  position: absolute;
  display: flex;
  flex: 1;
  align-items: center;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  list-style-type: none;
  margin: 0;
  padding: 0;
}

.tags-wrapper li {
  flex-grow: 1;
  margin-left: 5px;
}

.tags-wrapper li input {
  display: block;
  border: none;
  width: 100% !important;
}

.tags-wrapper li.tag {
  display: flex;
  flex-grow: 0;
  position: relative;
  padding: 10px;
  font-size: 14px;
  align-items: center;
  border-radius: 5px;
  list-style: none;
  background-image: none;
  box-shadow: none;
  color: white;
}

.tags-wrapper li a {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  text-decoration: none;
  color: rgba(0, 0, 0, 0);
}

.tags-wrapper li a:hover {
  background-color: rgba(0, 0, 0, 0.4);
  border-radius: 5px;
  color: rgba(0, 0, 0);
  background-image: url("http://svgshare.com/i/3yv.svg");
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

.tags-wrapper input {
  display: none;
}

#s_item {
  display: none
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.staticaly.com/gh/moofawsaw/donorport/master/auto-fill.min.js"></script>
<a id="btn_studio" href="#" class="btn btn--new ripple w-button">Create</a>
<div>keywords are: blue, red, green</div>
<div id="s_list">
  <div id="s_item" data-item="studio" data-mode="none" class="post__item studio__item">
    <div data-item="studio" class="post__itemwrap post__itemwrap--studio">
      <div class="search search--proj w-embed"><label class="search__label--proj" data-color="">
          <input type="text" class="input--proj" autocomplete="off" placeholder="">
        </label></div>
      <div class="w-dyn-list">
        <div class="w-dyn-items">
          <div class="w-dyn-item">
            <div class="w-embed">
              <div class="studio__project" data-proj="Blue" data-color="blue"></div>
            </div>
          </div>
          <div class="w-dyn-item">
            <div class="w-embed">
              <div class="studio__project" data-proj="Green" data-color="green"></div>
            </div>
          </div>
          <div class="w-dyn-item">
            <div class="w-embed">
              <div class="studio__project" data-proj="Red" data-color="red"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>


来源: stackexchange

问:
In Hello World flask app, Flask cannot find the app
I am running the minimal Hello World app from the Flask documentation. The code is below. I get no module named "flask.hello." The traceback is also below. I would like to know how to direct the flask to resolve the location of the app. The name of the source file is hello.py. I set

```<code>FLASK_APP='hello.py' and PYTHONPATH="."
</code>```

I start Flask with the command:

```<code>flask run --host=0.0.0.0 --port=3000

</code>```

```<code>from flask import Flask
app=Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello world!"
</code>```

```<code>Traceback (most recent call last):
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 240, in locate_app
    __import__(module_name)
ModuleNotFoundError: No module named 'flask.hello'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 338, in __call__
    self._flush_bg_loading_exception()
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 326, in _flush_bg_loading_exception
    reraise(*exc_info)
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 314, in _load_app
    self._load_unlocked()
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 330, in _load_unlocked
    self._app = rv = self.loader()
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 388, in load_app
    app = locate_app(self, import_name, name)
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 250, in locate_app
    raise NoAppException('Could not import "{name}".'.format(name=module_name))
flask.cli.NoAppException: Could not import "flask.hello".
</code>```

答: My working directory was called "flask" which apparently confused flask. When I renamed it to flask_dir, all works.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am running the minimal Hello World app from the Flask documentation. The code is below. I get no module named "flask.hello." The traceback is also below. I would like to know how to direct the flask to resolve the location of the app. The name of the source file is hello.py. I set

FLASK_APP='hello.py' and PYTHONPATH="."

I start Flask with the command:

flask run --host=0.0.0.0 --port=3000

from flask import Flask
app=Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello world!"

Traceback (most recent call last):
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 240, in locate_app
    __import__(module_name)
ModuleNotFoundError: No module named 'flask.hello'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 338, in __call__
    self._flush_bg_loading_exception()
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 326, in _flush_bg_loading_exception
    reraise(*exc_info)
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 314, in _load_app
    self._load_unlocked()
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 330, in _load_unlocked
    self._app = rv = self.loader()
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 388, in load_app
    app = locate_app(self, import_name, name)
  File "/home/anna_user2/.venv/projects/web-plots/lib/python3.7/site-packages/flask/cli.py", line 250, in locate_app
    raise NoAppException('Could not import "{name}".'.format(name=module_name))
flask.cli.NoAppException: Could not import "flask.hello".


问:
a good sample on dec atomic operation on floating field
Is mongoengine broken for atomic dec operation a FloatField or DecimalField?

Here is what i am trying -

```<code>class Account (DynamicDocument):
user = ReferenceField(User,passthrough=True,reverse_delete_rule=True,required=True,unique=True)
amount = FloatField(min_value=0,required=True)
</code>```

::::

Now I am trying to perform a atomic "dec" operation. The "amnt" value is passed as 10

```<code> Account.objects(user=usr).update(dec__amount=amnt)
</code>```

However, I am getting error - mongoengine.error.ValidationError: Float value is too small.
Any help is greatly appreciated.
Thanks

答: Locate the issue -  min_value=0 is the culprit. Removing this, it started working again. Not sure, why this is the issue? I thought this is a value constrain to the column

Body:
Is mongoengine broken for atomic dec operation a FloatField or DecimalField?

Here is what i am trying -

class Account (DynamicDocument):
user = ReferenceField(User,passthrough=True,reverse_delete_rule=True,required=True,unique=True)
amount = FloatField(min_value=0,required=True)

::::

Now I am trying to perform a atomic "dec" operation. The "amnt" value is passed as 10

 Account.objects(user=usr).update(dec__amount=amnt)

However, I am getting error - mongoengine.error.ValidationError: Float value is too small.
Any help is greatly appreciated.
Thanks


问:
imported python module from another directory fails
I have imported a python module from another directory in Linux by using sys.path.insert but when I run that module it fails. As the imported module is trying to open a file that is local to that module. Please let me know how to fix this.

```<code>users/adr/release/invoke.py  #this one fails with can’t open file ./config.ini

import sys

sys.path.insert(0, ‘/user/cdw/audit/’)

import audit_main
</code>```

The path where the original module file resides.

```<code>/user/cdw/audit/audit_main.py  # this module opens config.ini file to read pplication credentials.
/user/cdw/audit/config.ini

/user/cdw/audit/__ini__.py
</code>```

答:
When python loads a module it adds metadata to its global namespace that can be used by the module. __file__ is the filename of its .py file - when such a name makes sense. You can use it to get your config file

```<code>import os
config_filename = os.path.join(os.path.dirname(__file__), "config.ini")
</code>```

except for when you can't. If this is a C extension file or if the file was in some other packaging like zip or egg or pyinstaller bundle or exe, it may not work. A ini file, which I assume is user editable, may need to be some place other than the module directory. If you make this .py part of an installable package, it may end up in a system directory the user can't edit. This may not be a problem for this project, just laying out some of the considerations.

Body:
I have imported a python module from another directory in Linux by using sys.path.insert but when I run that module it fails. As the imported module is trying to open a file that is local to that module. Please let me know how to fix this.

users/adr/release/invoke.py  #this one fails with can’t open file ./config.ini

import sys

sys.path.insert(0, ‘/user/cdw/audit/’)

import audit_main

The path where the original module file resides.

/user/cdw/audit/audit_main.py  # this module opens config.ini file to read pplication credentials.
/user/cdw/audit/config.ini

/user/cdw/audit/__ini__.py

Body:
When python loads a module it adds metadata to its global namespace that can be used by the module. __file__ is the filename of its .py file - when such a name makes sense. You can use it to get your config file

import os
config_filename = os.path.join(os.path.dirname(__file__), "config.ini")

except for when you can't. If this is a C extension file or if the file was in some other packaging like zip or egg or pyinstaller bundle or exe, it may not work. A ini file, which I assume is user editable, may need to be some place other than the module directory. If you make this .py part of an installable package, it may end up in a system directory the user can't edit. This may not be a problem for this project, just laying out some of the considerations.


问:
Cloud Formation - can't upload template file
I try and create a stack by uploading a template.

That fails with an error heading that is blank.

I have permissions to create buckets, upload files, create EC2 instances, etc.
I tried switching to my root account even but that didn't help.

I've tried different YAML files and examples but none seem to work.
Without meaningful error messages with actionable items I am stuck.

```<code>{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Metadata": {
        "AWS::CloudFormation::Designer": {
            "213de823-ad0a-4f4c-af04-e3c9e565eef8": {
                "size": {
                    "width": 60,
                    "height": 60
                },
                "position": {
                    "x": 581,
                    "y": 148
                },
                "z": 0
            }
        }
    },
    "Resources": {
        "EC2I4PJFK": {
            "Type": "AWS::EC2::Instance",
            "Properties": {},
            "Metadata": {
                "AWS::CloudFormation::Designer": {
                    "id": "213de823-ad0a-4f4c-af04-e3c9e565eef8"
                }
            }
        }
    }
}
</code>```

答:
Resolution

Had the same issue when trying to upload a template.yml file I had created. My solution was to create a Public Object in S3 and then copy the Object URL into Cloudformation.

The solution proposed by the author did not help me.

Debugging

Inspecting the console and http requests didn't lead to much unfortunately.
The request to: https://console.aws.amazon.com/cloudformation/service/upload/uploadSuccess?bucket=cf-templates-jcexs078zt-us-east-1&key=somekey-template.yml&etag=someetag

Returns a 200.

Request Headers:

```<code>Host: console.aws.amazon.com
Referer: https://console.aws.amazon.com/cloudformation/home?region=us-east-1
Sec-Fetch-Dest: iframe
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: cross-site
Sec-Fetch-User: ?1
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36
</code>```

Response Headers:

```<code>Cache-Control: private, no-cache, no store
Connection: keep-alive
Content-Length: 0
Date: Sun, 31 May 2020 00:05:20 GMT
Expires: Sat, 30 May 2020 00:05:20 GMT
Pragma: no-cache
Server: Server
Strict-Transport-Security: max-age=47304000; includeSubDomains
Vary: Accept-Encoding,X-Amzn-CDN-Cache,X-Amzn-AX-Treatment,User-Agent
x-amz-rid: {sensitive-info?}
X-CloudFormation-RequestId: 885b8352-3178-4658-8326-b6a696a89579
</code>```

Expected Behavior

I would expect my file to be uploaded to s3 automatically, and if it fails I would expect a meaningful error message to be returned and displayed.

Body:
I try and create a stack by uploading a template.

That fails with an error heading that is blank.

I have permissions to create buckets, upload files, create EC2 instances, etc.
I tried switching to my root account even but that didn't help.

I've tried different YAML files and examples but none seem to work.
Without meaningful error messages with actionable items I am stuck.

{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Metadata": {
        "AWS::CloudFormation::Designer": {
            "213de823-ad0a-4f4c-af04-e3c9e565eef8": {
                "size": {
                    "width": 60,
                    "height": 60
                },
                "position": {
                    "x": 581,
                    "y": 148
                },
                "z": 0
            }
        }
    },
    "Resources": {
        "EC2I4PJFK": {
            "Type": "AWS::EC2::Instance",
            "Properties": {},
            "Metadata": {
                "AWS::CloudFormation::Designer": {
                    "id": "213de823-ad0a-4f4c-af04-e3c9e565eef8"
                }
            }
        }
    }
}

Body:
Resolution

Had the same issue when trying to upload a template.yml file I had created. My solution was to create a Public Object in S3 and then copy the Object URL into Cloudformation.

The solution proposed by the author did not help me.

Debugging

Inspecting the console and http requests didn't lead to much unfortunately.
The request to: https://console.aws.amazon.com/cloudformation/service/upload/uploadSuccess?bucket=cf-templates-jcexs078zt-us-east-1&key=somekey-template.yml&etag=someetag

Returns a 200.

Request Headers:

Host: console.aws.amazon.com
Referer: https://console.aws.amazon.com/cloudformation/home?region=us-east-1
Sec-Fetch-Dest: iframe
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: cross-site
Sec-Fetch-User: ?1
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36

Response Headers:

Cache-Control: private, no-cache, no store
Connection: keep-alive
Content-Length: 0
Date: Sun, 31 May 2020 00:05:20 GMT
Expires: Sat, 30 May 2020 00:05:20 GMT
Pragma: no-cache
Server: Server
Strict-Transport-Security: max-age=47304000; includeSubDomains
Vary: Accept-Encoding,X-Amzn-CDN-Cache,X-Amzn-AX-Treatment,User-Agent
x-amz-rid: {sensitive-info?}
X-CloudFormation-RequestId: 885b8352-3178-4658-8326-b6a696a89579

Expected Behavior

I would expect my file to be uploaded to s3 automatically, and if it fails I would expect a meaningful error message to be returned and displayed.


问:
Assigning value to a setter method in PHP
I have this class which let's me change the private data property using the setData method:

```<code>abstract class FooBase{

  public function __set($name, $value){
    $setter = 'set'.ucfirst($name);
    if(method_exists($this, $setter)) return $this->$setter($value);
    throw new Exception("Property {$setter} is not defined.");
  }

}

class Foo extends FooBase{

  static $instance;
  private $data;

  public static function app(){
    if(!(self::$instance instanceof self)){
      self::$instance = new self();
      self::app()->data = array('a' => 'somedata', 'b' => 'moredata');
    }
    return self::$instance;
  }

  public function setData($newdata){
    $this->data = $newdata;
  }
}
</code>```

So to change it I call it like:

Foo::app()->data = array('a' => 'newdata', 'b' => 'morenewdata');

I was wondering if it's possible to somehow change only one array value from $data, like:

```<code>Foo::app()->data['a'] = 'newdata'; // <-- this doesn't work, but it's what I would like to do...
</code>```

答: You could do this if data was public instead of private. Private means only the object can get that value internally. Public would allow you to do this. Either that or create a method to do what you want, as this could access the array internally, leaving data private.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have this class which let's me change the private data property using the setData method:

abstract class FooBase{

  public function __set($name, $value){
    $setter = 'set'.ucfirst($name);
    if(method_exists($this, $setter)) return $this->$setter($value);
    throw new Exception("Property {$setter} is not defined.");
  }

}

class Foo extends FooBase{

  static $instance;
  private $data;

  public static function app(){
    if(!(self::$instance instanceof self)){
      self::$instance = new self();
      self::app()->data = array('a' => 'somedata', 'b' => 'moredata');
    }
    return self::$instance;
  }

  public function setData($newdata){
    $this->data = $newdata;
  }
}

So to change it I call it like:

Foo::app()->data = array('a' => 'newdata', 'b' => 'morenewdata');

I was wondering if it's possible to somehow change only one array value from $data, like:

Foo::app()->data['a'] = 'newdata'; // <-- this doesn't work, but it's what I would like to do...


问:
C++: random number generation using Stroustrup example?
I'm using the random number generation from Stroustrup C++ 4th Ed. Page 129.  Unfortunately, it does not appear to be random and keeps generating and int 1.  Does anyone know why it's not generating a random number 1-6?  </p>

```<code>#include <random>
#include <iostream>
#include <functional>
using namespace std;

int main(int argc, char *argv[])
{
    using my_engine = default_random_engine;
    using my_distribution = uniform_int_distribution<>;

    my_engine re {};
    my_distribution one_to_six {1,6};
    auto die = bind(one_to_six,re);

    int x = die();

    cout << x << endl;

    return 0;
}

g++ -pedantic -lpthread test92.cc && ./a.out
1
</code>```

答:
You have to seed your engine (re) with some random:

Replace:

```<code>my_engine re {};
</code>```

With:

```<code>std::random_device rd;  //Will be used to obtain a seed for the random number engine
my_engine re(rd());
</code>```

Body:
I'm using the random number generation from Stroustrup C++ 4th Ed. Page 129.  Unfortunately, it does not appear to be random and keeps generating and int 1.  Does anyone know why it's not generating a random number 1-6?

#include <random>
#include <iostream>
#include <functional>
using namespace std;

int main(int argc, char *argv[])
{
    using my_engine = default_random_engine;
    using my_distribution = uniform_int_distribution<>;

    my_engine re {};
    my_distribution one_to_six {1,6};
    auto die = bind(one_to_six,re);

    int x = die();

    cout << x << endl;

    return 0;
}

g++ -pedantic -lpthread test92.cc && ./a.out
1

Body:
You have to seed your engine (re) with some random:

Replace:

my_engine re {};

With:

std::random_device rd;  //Will be used to obtain a seed for the random number engine
my_engine re(rd());


问:
Get Last Word from String in Table
I am attempting to get the last word from table Project in SQL-Server 2017.

My code is as follows:

```<code>select
reverse(substring(reverse(ProjectDescription),1, charindex(' ', reverse(ProjectDescription)) -1)) as LastWord
from Project
</code>```

The code works if I ask isolate the table to a single line, but I need the last word for all lines in the field ProjectDescription.

When I run the code as above, I get the following error:

Invalid length parameter passed to the LEFT or SUBSTRING function.

Please can someone assist me on where I am going wrong.

答:
You can use this simple function:

```<code>create function dbo.getLastWord(@s varchar(100))
returns varchar(200)
as
begin
declare @i int
set @i=len(@s)
 while substring(@s,@i,1)<>' '
  set @i=@i-1
 return substring(@s,@i,len(@s)-@i+1)
end
</code>```

And call it:

```<code>select dbo.getLastWord('Feels things getting better')
</code>```

which gets:

```<code>better
</code>```

Title: Get Last Word from String in Table

Body:
I am attempting to get the last word from table Project in SQL-Server 2017.

My code is as follows:

select
reverse(substring(reverse(ProjectDescription),1, charindex(' ', reverse(ProjectDescription)) -1)) as LastWord
from Project

The code works if I ask isolate the table to a single line, but I need the last word for all lines in the field ProjectDescription.

When I run the code as above, I get the following error:

Invalid length parameter passed to the LEFT or SUBSTRING function.

Please can someone assist me on where I am going wrong.

Body:
You can use this simple function:

create function dbo.getLastWord(@s varchar(100))
returns varchar(200)
as
begin
declare @i int
set @i=len(@s)
 while substring(@s,@i,1)<>' '
  set @i=@i-1
 return substring(@s,@i,len(@s)-@i+1)
end

And call it:

select dbo.getLastWord('Feels things getting better')

which gets:

better


问:
Spring boot JMS reconnects infinitely in wildfly
I have an Spring Boot app whose different parts connected via JMS. I use external ActiveMQ Artemis (in different docker container).

When I run the Spring Boot app via gradle bootRun all works perfectly - messages are delivered without loss.

But when I run app in Wildfly not all messages are delivered. Some messages are lost (about half). I configure external message broker use in Wildfly with pooled connection factory and execute commands for creating the outbound-socket-binding, remote-connector, & pooled-connection-factory.

In logs of Wildfly I get tons of:

```<code>2020-05-24 20:52:28,508 DEBUG [org.apache.activemq.artemis.service.extensions.xa.recovery] (Periodic Recovery) looking for recover at ClientSessionImpl [name=44c73a79-9dff-11ea-8d1c-0242ac110004, username=null, closed=false, factory = org.apache.activemq.artemis.core.client.impl.ClientSessionFactoryImpl@2af3f7bd, metaData=()]@410fad2f configuration [XARecoveryConfig [transportConfiguration=[TransportConfiguration(name=, factory=org-apache-activemq-artemis-core-remoting-impl-netty-NettyConnectorFactory) ?port=61616&localAddress=0-0-0-0&host=my-host], discoveryConfiguration=null, username=null, password=****, JNDI_NAME=java:/jms/remoteArtemisJms]]
</code>```

And in ActiveMQ logs permanently appears:

```<code>2020-05-24 21:16:18,063 DEBUG [org.apache.activemq.artemis.core.server.impl.QueueImpl] QueueImpl[name=30b977b0-ac39-431e-9957-2a9ac1f8b64f, postOffice=PostOfficeImpl [server=ActiveMQServerImpl::serverUUID=0b678ade-9de8-11ea-9475-0242ac110002], temp=true]@3a205718 adding consumer ServerConsumerImpl [id=1860, filter=null, binding=LocalQueueBinding [address=jms.topic.tasks, queue=QueueImpl[name=30b977b0-ac39-431e-9957-2a9ac1f8b64f, postOffice=PostOfficeImpl [server=ActiveMQServerImpl::serverUUID=0b678ade-9de8-11ea-9475-0242ac110002], temp=true]@3a205718, filter=null, name=30b977b0-ac39-431e-9957-2a9ac1f8b64f, clusterName=30b977b0-ac39-431e-9957-2a9ac1f8b64f0b678ade-9de8-11ea-9475-0242ac110002]]
</code>```

for every queue or topic. Looks like permanently reconnection.

And ActiveMQ Management console blinking when I start Wildfly app (and icons became gray in left menu). When I stop app, blinking in Management console stops, menu items are green.

So, questions:

How I can troubleshoot and fix messaging issue in Wildfly (permanently reconnection)?

What is periodic recovery? Why it occurs?

What means green and gray icons in ActiveMQ management console? And why it is blinking and how to fix it?

答:
So, seems it was configuration issue. What I do:

Change spring activemq starter to artemis

Create different connection factories to queues and topics

Create different DefaultMessageListenerContainer for different topics and queues using connection factories from p.2

Now all works fine.

Body:
I have an Spring Boot app whose different parts connected via JMS. I use external ActiveMQ Artemis (in different docker container).

When I run the Spring Boot app via gradle bootRun all works perfectly - messages are delivered without loss.

But when I run app in Wildfly not all messages are delivered. Some messages are lost (about half). I configure external message broker use in Wildfly with pooled connection factory and execute commands for creating the outbound-socket-binding, remote-connector, & pooled-connection-factory.

In logs of Wildfly I get tons of:

2020-05-24 20:52:28,508 DEBUG [org.apache.activemq.artemis.service.extensions.xa.recovery] (Periodic Recovery) looking for recover at ClientSessionImpl [name=44c73a79-9dff-11ea-8d1c-0242ac110004, username=null, closed=false, factory = org.apache.activemq.artemis.core.client.impl.ClientSessionFactoryImpl@2af3f7bd, metaData=()]@410fad2f configuration [XARecoveryConfig [transportConfiguration=[TransportConfiguration(name=, factory=org-apache-activemq-artemis-core-remoting-impl-netty-NettyConnectorFactory) ?port=61616&localAddress=0-0-0-0&host=my-host], discoveryConfiguration=null, username=null, password=****, JNDI_NAME=java:/jms/remoteArtemisJms]]

And in ActiveMQ logs permanently appears:

2020-05-24 21:16:18,063 DEBUG [org.apache.activemq.artemis.core.server.impl.QueueImpl] QueueImpl[name=30b977b0-ac39-431e-9957-2a9ac1f8b64f, postOffice=PostOfficeImpl [server=ActiveMQServerImpl::serverUUID=0b678ade-9de8-11ea-9475-0242ac110002], temp=true]@3a205718 adding consumer ServerConsumerImpl [id=1860, filter=null, binding=LocalQueueBinding [address=jms.topic.tasks, queue=QueueImpl[name=30b977b0-ac39-431e-9957-2a9ac1f8b64f, postOffice=PostOfficeImpl [server=ActiveMQServerImpl::serverUUID=0b678ade-9de8-11ea-9475-0242ac110002], temp=true]@3a205718, filter=null, name=30b977b0-ac39-431e-9957-2a9ac1f8b64f, clusterName=30b977b0-ac39-431e-9957-2a9ac1f8b64f0b678ade-9de8-11ea-9475-0242ac110002]]

for every queue or topic. Looks like permanently reconnection.

And ActiveMQ Management console blinking when I start Wildfly app (and icons became gray in left menu). When I stop app, blinking in Management console stops, menu items are green.

So, questions:

How I can troubleshoot and fix messaging issue in Wildfly (permanently reconnection)?

What is periodic recovery? Why it occurs?

What means green and gray icons in ActiveMQ management console? And why it is blinking and how to fix it?


问:
I would like to put a word counter in this code but can't
I need to be able to count the number of words I put into the string that I enter. I have tried many different things and none of them have worked for me</p>

```<code>import java.util.Scanner;

public class Main
{
   public static void main(String args[])
   {
    Scanner in = new Scanner(System.in);
    System.out.println("Enter some text: ");
    String str = in.nextLine().toLowerCase();
    String vowels = "aeiou";
    System.out.println(str);

    int vcount = 0;
    int ccount = 0;

for (char c : str.toCharArray()) {

  if (Character.isLetter(c)) {

      if (vowels.indexOf(c) >= 0)
      {
        vcount++;
      }
      else
      {
        ccount++;
        }
    }
}

    System.out.print("your input has " + vcount + " vowels" + "\n");
    System.out.print("your input has " + ccount + " consonants" + "\n");
    //System.out.print("your input has " + words + " words");
   }
}

</code>```

答:
Split the string on whitespace and the length of the resulting array is your word count:

```<code>int wordcount = str.split( "\\s+" ).length;
</code>```

The "\\s+" is a regex that matches one or more whitespace character.

Body:
I need to be able to count the number of words I put into the string that I enter. I have tried many different things and none of them have worked for me

import java.util.Scanner;

public class Main
{
   public static void main(String args[])
   {
    Scanner in = new Scanner(System.in);
    System.out.println("Enter some text: ");
    String str = in.nextLine().toLowerCase();
    String vowels = "aeiou";
    System.out.println(str);

    int vcount = 0;
    int ccount = 0;

for (char c : str.toCharArray()) {

  if (Character.isLetter(c)) {

      if (vowels.indexOf(c) >= 0)
      {
        vcount++;
      }
      else
      {
        ccount++;
        }
    }
}

    System.out.print("your input has " + vcount + " vowels" + "\n");
    System.out.print("your input has " + ccount + " consonants" + "\n");
    //System.out.print("your input has " + words + " words");
   }
}

Body:
Split the string on whitespace and the length of the resulting array is your word count:

int wordcount = str.split( "\\s+" ).length;

The "\\s+" is a regex that matches one or more whitespace character.


问:
CSS selector that excludes some child elements
I have this HTML:

```<code><div class="item-cost">
    <a data-passage="Shop" class="link-internal macro-link" tabindex="0" id="Link1">$10 <sup>1</sup></a>
</div>
</code>```

I am writing this testcafe code to get the cost:

```<code>.expect(Selector('.item-cost').nth(0).innerText)
.eql('$1')
</code>```

This fails because the inner text is $11, not $1. The reason it's failing is because the contents of the sup element are included in the inner text. Is there any way I can modify the selector above so that it gives me the inner text without including the sup element? I cannot modify the HTML.

答:
How about using  in your test too?

.expect(Selector('.item-cost').nth(0).innerText)
.eql('$1 ' + Selector('.item-cost sup').nth(0).innerText)
```

Body:
I have this HTML:

    $10 1

I am writing this testcafe code to get the cost:

.expect(Selector('.item-cost').nth(0).innerText)
.eql('$1')

This fails because the inner text is $11, not $1. The reason it's failing is because the contents of the sup element are included in the inner text. Is there any way I can modify the selector above so that it gives me the inner text without including the sup element? I cannot modify the HTML.

Body:
How about using <sup> in your test too?

.expect(Selector('.item-cost').nth(0).innerText)
.eql('$1 ' + Selector('.item-cost sup').nth(0).innerText)


问:
Any ideas about how to use CSS to emulate a messy stamp?
I'm interested in ways to render a span that to look something like one of these:

Here are the tricks I plan on using:

@font-face

-{moz/webkit/o}-transform:rotate

It's for a personal project so assuming the most modern CSS support is fine. Maybe border-images could help? I'd like to avoid image splicing all over the place -- if it really comes down to that I'll just skip the border all together and rely on a font for the look.

I'm just curious how the CSS gurus around here would approach this.

UPDATE

There is now a CSS property for this, mask-image. More here.

答: You could use a font face for the font, but you'd still need an image for the borders.  I would suggest saving yourself the hassle of cross browser debugging and using a transparent .png if possible.</p>


问:
Why does the BERT NSP head linear layer have two outputs?
Here's the code in question.

https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_bert.py#L491

```<code>class BertOnlyNSPHead(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.seq_relationship = nn.Linear(config.hidden_size, 2)

    def forward(self, pooled_output):
        seq_relationship_score = self.seq_relationship(pooled_output)
        return seq_relationship_score
</code>```

I think it was just ranking how likely one sentence would follow another? Wouldn't it be one score?

答:
The two scores are meant to represent unnormalized probabilities (logits) from the model. If we softmax them, we get our predictions, where index 0 indicates next sentence, and index 1 indicates random.

This is just a stylistic choice on the HuggingFace author's behalf, probably to keep the loss function consistent.

Here's the forward method of BertForPretraining, where self.cls is BertOnlyNSPHead:

```<code>    prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)

    outputs = (prediction_scores, seq_relationship_score,) + outputs[
        2:
    ]  # add hidden states and attention if they are here

    if masked_lm_labels is not None and next_sentence_label is not None:
        loss_fct = CrossEntropyLoss()
        masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1))
        next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
        total_loss = masked_lm_loss + next_sentence_loss
        outputs = (total_loss,) + outputs
</code>```

it's convenient to use the same CrossEntropyLoss for both MLM and NSP.

As you describe, it would be equivalent to have NSP produce a single output, then feed that number through a sigmoid to get probability of the next sentence. We can then train with BCEWithLogitsLoss. (where BCE is just the special binary case of cross entropy loss).

Body:
Here's the code in question.

https://github.com/huggingface/transformers/blob/master/src/transformers/modeling_bert.py#L491

class BertOnlyNSPHead(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.seq_relationship = nn.Linear(config.hidden_size, 2)

    def forward(self, pooled_output):
        seq_relationship_score = self.seq_relationship(pooled_output)
        return seq_relationship_score

I think it was just ranking how likely one sentence would follow another? Wouldn't it be one score?

Body:
The two scores are meant to represent unnormalized probabilities (logits) from the model. If we softmax them, we get our predictions, where index 0 indicates next sentence, and index 1 indicates random.

This is just a stylistic choice on the HuggingFace author's behalf, probably to keep the loss function consistent.

Here's the forward method of BertForPretraining, where self.cls is BertOnlyNSPHead:

    prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)

    outputs = (prediction_scores, seq_relationship_score,) + outputs[
        2:
    ]  # add hidden states and attention if they are here

    if masked_lm_labels is not None and next_sentence_label is not None:
        loss_fct = CrossEntropyLoss()
        masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), masked_lm_labels.view(-1))
        next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
        total_loss = masked_lm_loss + next_sentence_loss
        outputs = (total_loss,) + outputs

it's convenient to use the same CrossEntropyLoss for both MLM and NSP.

As you describe, it would be equivalent to have NSP produce a single output, then feed that number through a sigmoid to get probability of the next sentence. We can then train with BCEWithLogitsLoss. (where BCE is just the special binary case of cross entropy loss).


问:
RealmSwift: Count number of unique words
Given the following setup:

```<code>class Message: Object {

    @objc dynamic var name: String = ""
    @objc dynamic var message: String = ""
}

class Chat: Object {

    var messages = List<Message>()
    var people = List<Person>()

    @objc dynamic var name:String = ""
    @objc dynamic var path:String = ""
}
</code>```

Is there a more efficient way using functional programming to calculate teh number of unique words within the message variable within Message?

```<code>let messages = Array(chat.messages)
let wordDictionary = [String:Int]()
let peopleDictionary = [String]()

for messageObject in messages {

   let words = messageObject.message.components(separatedBy: " ")
   for word in words {
      if wordDictionary[word] != nil {
          wordDictionary[word] += 1
      }else{
         wordDictionary[word] = 0
      }
   }
}
</code>```

答:
Yes you can use enumerateSubstrings(in: Range) .byWords to break your sentence down into words and use reduce method to calculate its frequency. Don't forget to lowercase the words to make sure they don't count as different words:

```<code>extension StringProtocol {
    var byWords: [SubSequence] { components(separated: .byWords) }
    func components(separated options: String.EnumerationOptions)-> [SubSequence] {
        var components: [SubSequence] = []
        enumerateSubstrings(in: startIndex..., options: options) { _, range, _, _ in components.append(self[range]) }
        return components
    }
}
</code>```

```<code>extension Sequence where Element: Hashable {
    var frequency: [Element: Int] { reduce(into: [:]) { $0[$1, default: 0] += 1 } }
}
</code>```

Usage:

```<code>let sentence1 = "Given the following setup:"
let sentence2 = "Is there a more efficient way using functional programming to calculate the number of unique words within the message variable within Message"

let sentences = [sentence1, sentence2]
let frequency = sentences
    .joined(separator: "\n")
    .lowercased()
    .byWords
    .frequency

print(frequency.sorted(by: {$0.value > $1.value }))
</code>```

This will print

[(key: "the", value: 3), (key: "within", value: 2), (key: "message",
  value: 2), (key: "following", value: 1), (key: "way", value: 1), (key:
  "more", value: 1), (key: "to", value: 1), (key: "calculate", value:
  1), (key: "number", value: 1), (key: "there", value: 1), (key: "a",
  value: 1), (key: "is", value: 1), (key: "unique", value: 1), (key:
  "setup", value: 1), (key: "using", value: 1), (key: "programming",
  value: 1), (key: "given", value: 1), (key: "words", value: 1), (key:
  "variable", value: 1), (key: "functional", value: 1), (key:
  "efficient", value: 1), (key: "of", value: 1)]

Body:
Given the following setup:

class Message: Object {

    @objc dynamic var name: String = ""
    @objc dynamic var message: String = ""
}

class Chat: Object {

    var messages = List<Message>()
    var people = List<Person>()

    @objc dynamic var name:String = ""
    @objc dynamic var path:String = ""
}

Is there a more efficient way using functional programming to calculate teh number of unique words within the message variable within Message?

let messages = Array(chat.messages)
let wordDictionary = [String:Int]()
let peopleDictionary = [String]()

for messageObject in messages {

   let words = messageObject.message.components(separatedBy: " ")
   for word in words {
      if wordDictionary[word] != nil {
          wordDictionary[word] += 1
      }else{
         wordDictionary[word] = 0
      }
   }
}

Body:
Yes you can use enumerateSubstrings(in: Range) .byWords to break your sentence down into words and use reduce method to calculate its frequency. Don't forget to lowercase the words to make sure they don't count as different words:

extension StringProtocol {
    var byWords: [SubSequence] { components(separated: .byWords) }
    func components(separated options: String.EnumerationOptions)-> [SubSequence] {
        var components: [SubSequence] = []
        enumerateSubstrings(in: startIndex..., options: options) { _, range, _, _ in components.append(self[range]) }
        return components
    }
}

extension Sequence where Element: Hashable {
    var frequency: [Element: Int] { reduce(into: [:]) { $0[$1, default: 0] += 1 } }
}

Usage:

let sentence1 = "Given the following setup:"
let sentence2 = "Is there a more efficient way using functional programming to calculate the number of unique words within the message variable within Message"

let sentences = [sentence1, sentence2]
let frequency = sentences
    .joined(separator: "\n")
    .lowercased()
    .byWords
    .frequency

print(frequency.sorted(by: {$0.value > $1.value }))

This will print

[(key: "the", value: 3), (key: "within", value: 2), (key: "message",
  value: 2), (key: "following", value: 1), (key: "way", value: 1), (key:
  "more", value: 1), (key: "to", value: 1), (key: "calculate", value:
  1), (key: "number", value: 1), (key: "there", value: 1), (key: "a",
  value: 1), (key: "is", value: 1), (key: "unique", value: 1), (key:
  "setup", value: 1), (key: "using", value: 1), (key: "programming",
  value: 1), (key: "given", value: 1), (key: "words", value: 1), (key:
  "variable", value: 1), (key: "functional", value: 1), (key:
  "efficient", value: 1), (key: "of", value: 1)]


问:
Disconnected from the target VM, address: '127.0.0.1:62535', transport: 'socket' on intellij idea CE. I can't debug my program. Any suggestions?
Connected to the target VM, address: '127.0.0.1:63073', transport: 'socket'
Disconnected from the target VM, address: '127.0.0.1:63073', transport: 'socket'</p>

答: maven clean followed by maven install worked for me. </p>


问:
iPhone: Store and Display Push Notification
In my iphone application, I want to store all the push notifications that a device receives and then display it in table.

I also want to show the number of notifications received till now on application icon.

Is this possible?

Can anyone please help?

Thanks.

答:
You can not store push notification. Your app is closed and the notification are received by the os, if the user press ok button the os will open your application.

What you can do is to keep all the notification on your server and when the app is open sync your local data with the server data.


问:
How to give another chance to input if conditions are not met
I want to check if an user types an word only including strings.

So, if the user types a number (32) or a compound of number+string (Fight2win), I want to let the user to type once again before move on.

I have problems on giving another chance to input when the prior input contains a number. So, I was going to use the "While loop", but now I can't figure out how to break it after it finishes checking.

Also, I was trying to go every single alphabets and see if it can be converted into integer or not. I know there is other ways like isalpha, but still I need to know how I can give another chance to type and re-check the second input if it only contains string..

here is my original code.

while True:
    x = input(f"Please type a word.").lower()

    for i in x:
        try:
            int(x)
            print("Type Error: Please insert alphabets only!!!")

        else:
            pass
```

答:
This trick worked for me, now user can try as many times he want, and you can specify the breaks

```<code>start=[]
while True:
     start=list(input(f"Please type a word.").lower())
...
</code>```

Rest your logic follows since you asked how to incorporate multiple tries for user.

Happy coding.

Body:
This trick worked for me, now user can try as many times he want, and you can specify the breaks

start=[]
while True:
     start=list(input(f"Please type a word.").lower())
...

Rest your logic follows since you asked how to incorporate multiple tries for user.

Happy coding.


问:
How to cast an object to Type?
I want to cast an object to a type that a System.Type object defines. I only know the object and the Type as inputs, I can't add type parameters.

```<code>void Test()
{
    object obj = 3;
    Type type = typeof(int);

    int number = Cast(obj, type);

    Console.WriteLine($"{number}, {number.GetType()}"); // Should output "3, System.Int32"
}

// I can't change the inputs
??? Cast(object obj, Type type)
{
    // return the obj casted to type, but how?
}
</code>```

I guess there's a way to solve it using reflection but I couldn't find anything like this.

答:
You can use ChangeType method :

1 - Cast method:

```<code>public static T Cast<T>(object obj)
{
    return (T)Convert.ChangeType(obj, typeof(T));
}
</code>```

2 - Test method:

```<code>void Test()
{
    object obj = 3;

    int number = Cast<int>(obj);

    Console.WriteLine($"{number}, {number.GetType()}");
}
</code>```

Result:

```<code>3, System.Int32
</code>```

I hope you find this helpful.

Title: How to cast an object to Type?

Body:
I want to cast an object to a type that a System.Type object defines. I only know the object and the Type as inputs, I can't add type parameters.

void Test()
{
    object obj = 3;
    Type type = typeof(int);

    int number = Cast(obj, type);

    Console.WriteLine($"{number}, {number.GetType()}"); // Should output "3, System.Int32"
}

// I can't change the inputs
??? Cast(object obj, Type type)
{
    // return the obj casted to type, but how?
}

I guess there's a way to solve it using reflection but I couldn't find anything like this.

Body:
You can use ChangeType method :

1 - Cast method:

public static T Cast<T>(object obj)
{
    return (T)Convert.ChangeType(obj, typeof(T));
}

2 - Test method:

void Test()
{
    object obj = 3;

    int number = Cast<int>(obj);

    Console.WriteLine($"{number}, {number.GetType()}");
}

Result:

3, System.Int32

I hope you find this helpful.


答:
Solution

You need to consider the following two situations (and hence two methods). The first method presents a rather universal/generic solution if you only want to drop inputs with digits (note that we have alphabets, digits and special characters).

Let us consider these inputs:

values = ["10", "me@home2", "me2@ho10me", "me@home", "myhome"]

Method-1 will accept "me@home" and come out of the while loop

Method-2 will accept only "myhome" from the list of values above before coming out of the while loop.

You need to choose which method to use depending on your usecase.

Method-1: Using regex

This will not allow inputs with

digits alone

alphanumeric data

But, this will allow special characters, if you need them.

import re
result = ['0']
pat = re.compile('\d')
# Control printing of message if
# invalid input is provided
verbose = 0 # set 1 for printing

while result:
    value = input("Enter alphabets only: ").lower()
    result = pat.findall(value)
    if result and verbose>0:
        print(f" >>> Invalid Input: {value} \n >>> Try again...")

## Output
# Enter alphabets only: 10
# Enter alphabets only: me@home2
# Enter alphabets only: me2@ho10me
# Enter alphabets only: me@home --> LOOP EXITED HERE
```

<h2>Method-2: Using <code>str.isalpha()</code> or <code>str.isalnum()</code></h2>

<p>This will not allow inputs with special characters as well as digits.</p>

<pre class="lang-py prettyprint-override"><code>value = '0'
# Control printing of message if
# invalid input is provided
verbose = 0 # set 1 for printing

# Method-2.A
while not value.isalpha():
    value = input("Enter alphabets only: ").lower()
    if not value.isalpha() and verbose>0:
        print(f" >>> Invalid Input: {value} \n >>> Try again...")

# Method-2.B
while value.isalnum():
    value = input("Enter alphabets only: ").lower()
    if value.isalnum() and verbose>0:
        print(f" >>> Invalid Input: {value} \n >>> Try again...")

## Output
# Enter alphabets only: 10
# Enter alphabets only: me@home2
# Enter alphabets only: me2@ho10me
# Enter alphabets only: me@home
# Enter alphabets only: myhome --> LOOP EXITED HERE
</code>```

Use str.isalpha() to check if it is purely alphabet or not.

values = ['abcd', '10', 'abc23knh']
[value.isalpha() for value in values]

## Output
# [True, False, False]
```

Title: How to give another chance to input if conditions are not met

Body:
I want to check if an user types an word only including strings.

So, if the user types a number (32) or a compound of number+string (Fight2win), I want to let the user to type once again before move on.

I have problems on giving another chance to input when the prior input contains a number. So, I was going to use the "While loop", but now I can't figure out how to break it after it finishes checking.

Also, I was trying to go every single alphabets and see if it can be converted into integer or not. I know there is other ways like isalpha, but still I need to know how I can give another chance to type and re-check the second input if it only contains string..

here is my original code.

while True:
    x = input(f"Please type a word.").lower()

    for i in x:
        try:
            int(x)
            print("Type Error: Please insert alphabets only!!!")

        else:
            pass

Body:
Solution

You need to consider the following two situations (and hence two methods). The first method presents a rather universal/generic solution if you only want to drop inputs with digits (note that we have alphabets, digits and special characters).

Let us consider these inputs:

values = ["10", "me@home2", "me2@ho10me", "me@home", "myhome"]

Method-1 will accept "me@home" and come out of the while loop

Method-2 will accept only "myhome" from the list of values above before coming out of the while loop.

You need to choose which method to use depending on your usecase.

Method-1: Using regex

This will not allow inputs with

digits alone

alphanumeric data

But, this will allow special characters, if you need them.

import re
result = ['0']
pat = re.compile('\d')
# Control printing of message if
# invalid input is provided
verbose = 0 # set 1 for printing

while result:
    value = input("Enter alphabets only: ").lower()
    result = pat.findall(value)
    if result and verbose>0:
        print(f" >>> Invalid Input: {value} \n >>> Try again...")

## Output
# Enter alphabets only: 10
# Enter alphabets only: me@home2
# Enter alphabets only: me2@ho10me
# Enter alphabets only: me@home --> LOOP EXITED HERE

Method-2: Using str.isalpha() or str.isalnum()

This will not allow inputs with special characters as well as digits.

value = '0'
# Control printing of message if
# invalid input is provided
verbose = 0 # set 1 for printing

# Method-2.A
while not value.isalpha():
    value = input("Enter alphabets only: ").lower()
    if not value.isalpha() and verbose>0:
        print(f" >>> Invalid Input: {value} \n >>> Try again...")

# Method-2.B
while value.isalnum():
    value = input("Enter alphabets only: ").lower()
    if value.isalnum() and verbose>0:
        print(f" >>> Invalid Input: {value} \n >>> Try again...")

## Output
# Enter alphabets only: 10
# Enter alphabets only: me@home2
# Enter alphabets only: me2@ho10me
# Enter alphabets only: me@home
# Enter alphabets only: myhome --> LOOP EXITED HERE

Use str.isalpha() to check if it is purely alphabet or not.

values = ['abcd', '10', 'abc23knh']
[value.isalpha() for value in values]

## Output
# [True, False, False]


问:
reload vue component from outside
I have a laravel vue project that displays a list of items in a component. The component when mounted makes an ajax call to populate the data element. However, there's other items on the page (not in vue) that can add elements to the database, and I'd like to make sure the list is reactive in the component.

```<code>mounted() {
    this.getTasks();
},
methods: {
    getTasks() {
        let self = this;
        axios.get('/tasks').then(response => {
            self.tasks = response.data;
        })
        .catch(function (error) {
            console.log(error);
        });
    },
}
</code>```

When the user does an action that would add a task to the list, is there a way to fire the getTasks method on the component from outside the component?

答:
You can declare a global function (binding context to Vue component) when component is mounted:

```<code>mounted() {
  windows.getTasks = this.getTasks.bind(this);
  this.getTasks();
},
</code>```

Then you can use it outside calling getTasks() or windows.getTasks()

Title: reload vue component from outside

Body:
I have a laravel vue project that displays a list of items in a component. The component when mounted makes an ajax call to populate the data element. However, there's other items on the page (not in vue) that can add elements to the database, and I'd like to make sure the list is reactive in the component.

mounted() {
    this.getTasks();
},
methods: {
    getTasks() {
        let self = this;
        axios.get('/tasks').then(response => {
            self.tasks = response.data;
        })
        .catch(function (error) {
            console.log(error);
        });
    },
}

When the user does an action that would add a task to the list, is there a way to fire the getTasks method on the component from outside the component?

Body:
You can declare a global function (binding context to Vue component) when component is mounted:

mounted() {
  windows.getTasks = this.getTasks.bind(this);
  this.getTasks();
},

Then you can use it outside calling getTasks() or windows.getTasks()


问:
Why is this component not applying the css rule?
I have a component called app-list-container, the structure of which is as follows:

HTML

```<code><ul [attr.styleName]="styleName" [style.flexGrow]="flexGrow">
    <!-- ITEM <li> -->
    <ng-content></ng-content>
</ul>
</code>```

SCSS

```<code>@import 'placeholders/scrollbar';

ul {
    &[styleName='CHAT_MESSAGE'],
    &[styleName='CHAT_LAST_MESSAGE'] {
        @extend %scrollbar-y;
    }
}
</code>```

With this I generate the items (
) inside this component ... Now I don't understand why it is not applying this css rule.

The rule is only applied when I insert it in his father (app-list-container), for me it does not make sense to also insert the style through the father.

Notice in the image below that the css is being applied to the html element, but if it is applied to the
 it doesn't work, but it works if it is applied to the parent (<app-list-containr>):

What to do? (Note: I like to do and know the CORRECT mode).

答:
For those who want to know, I did it as follows:

TS:

```<code>export class ListContainerComponent implements OnInit {
    @HostBinding('attr.styleName') hostStyleName: IListStyleName;
    @Input() styleName: IListStyleName;
    @Input() flexGrow = ICssFlexGrow.INITIAL;

    constructor() {}

    ngOnInit(): void {
        this.checkInput();
        this.setHostStyleName(this.styleName);
    }

    protected checkInput(): void {
        if (!IListStyleName[this.styleName.toUpperCase()]) {
            throw new Error(`The inserted style: "${this.styleName}" does not exist in this component!`);
        }

        if (!ICssFlexGrow[this.flexGrow.toUpperCase()]) {
            throw new Error(`The inserted flex-grown: "${this.flexGrow}" does not exist in this component!`);
        }
    }

    protected setHostStyleName(styleName: IListStyleName): void {
        this.hostStyleName = styleName;
    }
}
</code>```

SCSS:

```<code>:host {
    &[styleName='CHAT_MESSAGE'],
    &[styleName='CHAT_LAST_MESSAGE'] {
        @extend %scrollbar-y;
    }
}
</code>```

Body:
I have a component called app-list-container, the structure of which is as follows:

HTML

    <ng-content></ng-content>

SCSS

@import 'placeholders/scrollbar';

ul {
    &[styleName='CHAT_MESSAGE'],
    &[styleName='CHAT_LAST_MESSAGE'] {
        @extend %scrollbar-y;
    }
}

With this I generate the items (
) inside this component ... Now I don't understand why it is not applying this css rule.

The rule is only applied when I insert it in his father (app-list-container), for me it does not make sense to also insert the style through the father.

Notice in the image below that the css is being applied to the html element, but if it is applied to the
 it doesn't work, but it works if it is applied to the parent (<app-list-containr>):

What to do? (Note: I like to do and know the CORRECT mode).

Body:
For those who want to know, I did it as follows:

TS:

export class ListContainerComponent implements OnInit {
    @HostBinding('attr.styleName') hostStyleName: IListStyleName;
    @Input() styleName: IListStyleName;
    @Input() flexGrow = ICssFlexGrow.INITIAL;

    constructor() {}

    ngOnInit(): void {
        this.checkInput();
        this.setHostStyleName(this.styleName);
    }

    protected checkInput(): void {
        if (!IListStyleName[this.styleName.toUpperCase()]) {
            throw new Error(`The inserted style: "${this.styleName}" does not exist in this component!`);
        }

        if (!ICssFlexGrow[this.flexGrow.toUpperCase()]) {
            throw new Error(`The inserted flex-grown: "${this.flexGrow}" does not exist in this component!`);
        }
    }

    protected setHostStyleName(styleName: IListStyleName): void {
        this.hostStyleName = styleName;
    }
}

SCSS:

:host {
    &[styleName='CHAT_MESSAGE'],
    &[styleName='CHAT_LAST_MESSAGE'] {
        @extend %scrollbar-y;
    }
}


问:
Reset scroll position after Async postback - ASP.NET
What is the best way to reset the scroll position to the top of page after the an asynchronous postback?

The asynchronous postback is initiated from a ASP.NET GridView CommandField column and the ASP.NET update panel Update method is called in the GridView OnRowCommand.

My current application is an ASP.NET 3.5 web site.

EDIT: I have received excellent feedback from everyone, and I ended using the PageRequestManager method in a script tag, but my next question is:

How do I configure it to only execute when the user clicks the ASP.NET CommandField in my GridView control?  I have other buttons on the page that perform an asynchronous postback that I do not want to scroll to the top of the page.

EDIT 1: I have developed a solution where I do not need to use the PageRequestManager.  See my follow up answer for solution.

答:
taken from this tutorial:

https://web.archive.org/web/20211020134824/https://aspnet.4guysfromrolla.com/articles/111407-1.aspx

We set MaintainScrollPositionOnPostback=true

Then if we need to reset scroll position call the method:

```<code>Private Sub ResetScrollPosition()
If Not ClientScript.IsClientScriptBlockRegistered(Me.GetType(), "CreateResetScrollPosition") Then
   'Create the ResetScrollPosition() function
   ClientScript.RegisterClientScriptBlock(Me.GetType(), "CreateResetScrollPosition", _
                    "function ResetScrollPosition() {" & vbCrLf & _
                    " var scrollX = document.getElementById('__SCROLLPOSITIONX');" & vbCrLf & _
                    " var scrollY = document.getElementById('__SCROLLPOSITIONY');" & vbCrLf & _
                    " if (scrollX && scrollY) {" & vbCrLf & _
                    "    scrollX.value = 0;" & vbCrLf & _
                    "    scrollY.value = 0;" & vbCrLf & _
                    " }" & vbCrLf & _
                    "}", True)

   'Add the call to the ResetScrollPosition() function
   ClientScript.RegisterStartupScript(Me.GetType(), "CallResetScrollPosition", "ResetScrollPosition();", True)
End If
End Sub
</code>```

OwnerDisplayName: Michael Kniskern

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Michael Kniskern

Body:
taken from this tutorial:

https://web.archive.org/web/20211020134824/https://aspnet.4guysfromrolla.com/articles/111407-1.aspx

We set MaintainScrollPositionOnPostback=true

Then if we need to reset scroll position call the method:

Private Sub ResetScrollPosition()
If Not ClientScript.IsClientScriptBlockRegistered(Me.GetType(), "CreateResetScrollPosition") Then
   'Create the ResetScrollPosition() function
   ClientScript.RegisterClientScriptBlock(Me.GetType(), "CreateResetScrollPosition", _
                    "function ResetScrollPosition() {" & vbCrLf & _
                    " var scrollX = document.getElementById('__SCROLLPOSITIONX');" & vbCrLf & _
                    " var scrollY = document.getElementById('__SCROLLPOSITIONY');" & vbCrLf & _
                    " if (scrollX && scrollY) {" & vbCrLf & _
                    "    scrollX.value = 0;" & vbCrLf & _
                    "    scrollY.value = 0;" & vbCrLf & _
                    " }" & vbCrLf & _
                    "}", True)

   'Add the call to the ResetScrollPosition() function
   ClientScript.RegisterStartupScript(Me.GetType(), "CallResetScrollPosition", "ResetScrollPosition();", True)
End If
End Sub

OwnerDisplayName: chrisg


问:
add start from constraint to a column in mysql
hey i am creating an application for invoicing(computer generated bill).
i have a table sales_log where ref no. column is set to auto_increment.i didnt assign the start value. i mean if the ref no. of 1st bill is 101 then i should automatically get 102..103...etc for the rest...i just dont know how to alter the table constraint and set a starting value for that column.
here is the description of my table</p>

```<code>mysql> desc sales_log;
+----------+---------+------+-----+---------+----------------+
| Field    | Type    | Null | Key | Default | Extra          |
+----------+---------+------+-----+---------+----------------+
| date     | date    | YES  |     | NULL    |                |
| item_id  | int(11) | YES  | MUL | NULL    |                |
| C_Id     | int(11) | YES  | MUL | NULL    |                |
| Quantity | double  | YES  |     | NULL    |                |
| Ref      | int(11) | NO   | PRI | NULL    | auto_increment |
| price    | double  | YES  |     | NULL    |                |
+----------+---------+------+-----+---------+----------------+
</code>```

答:
CREATE TABLE users (user_id  int NOT NULL, name varchar(50),PRIMARY KEY (user_id));

NSERT INTO users VALUES (1, 'Bob');

INSERT INTO users VALUES (2, 'Joe');

INSERT INTO users VALUES (3, 'Paul');

ALTER TABLE users MODIFY user_id int NOT NULL AUTO_INCREMENT;

ALTER TABLE users AUTO_INCREMENT = 6000;

INSERT INTO users (name) VALUES ('Keith');

INSERT INTO users (name) VALUES ('Steve');

INSERT INTO users (name) VALUES ('Jack');

SELECT * FROM users;

user_id  name

1        Bob

 2        Joe

 3        Paul

 6000     Keith

6001     Steve

6002     Jack

Body:
hey i am creating an application for invoicing(computer generated bill).
i have a table sales_log where ref no. column is set to auto_increment.i didnt assign the start value. i mean if the ref no. of 1st bill is 101 then i should automatically get 102..103...etc for the rest...i just dont know how to alter the table constraint and set a starting value for that column.
here is the description of my table

mysql> desc sales_log;
+----------+---------+------+-----+---------+----------------+
| Field    | Type    | Null | Key | Default | Extra          |
+----------+---------+------+-----+---------+----------------+
| date     | date    | YES  |     | NULL    |                |
| item_id  | int(11) | YES  | MUL | NULL    |                |
| C_Id     | int(11) | YES  | MUL | NULL    |                |
| Quantity | double  | YES  |     | NULL    |                |
| Ref      | int(11) | NO   | PRI | NULL    | auto_increment |
| price    | double  | YES  |     | NULL    |                |
+----------+---------+------+-----+---------+----------------+