问:
Check if is there any duplicate values in a table
I have a Table with multiple rows and in each row there are some input fields and i want check if there is  Duplicates value in table.

Here is my code , first I'm trying to find if is there any empty value , how can I check if is there any duplicates value too?

JavaScript:

```<code><script>
 var isValid;
    function Step2Validation(e) {
        $(".trtickets").each(function () {

            var FindName = $(this).find(".navn");
            var FindLastName = $(this).find(".efternavn");

            if (FindName.val() == "") {
                isValid = false;
                alert("Empty Name");
                return false;
            }
            if (FindLastName.val() == "") {
                isValid = false;
                alert("Empty Lastname");
                return false;
            }

            else {
                $(e).closest('fieldset').slideUp().next().slideDown();

            }

        });
    }

    function step2(e) {

        Step2Validation(e);

    }
</script>
</code>```

HTML:

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

 <tr class="trtickets">
  <td>
    <input type="text" name="model.RegistrationLists[0].Name" value="John" class="form-control navn" placeholder="Name">
  </td>
  <td>
    <input type="text" name="model.RegistrationLists[0].Lastname" class="form-control efternavn" placeholder="Lastname">
  </td>
</tr>
<tr class="trtickets">
  <td>
    <input type="text" name="model.RegistrationLists[1].Name" value="John" class="form-control navn" placeholder="Name">
  </td>
  <td>
    <input type="text" name="model.RegistrationLists[1].Lastname" class="form-control efternavn" placeholder="Lastname">
  </td>
</tr>

   <button type="button" onclick="step2(this);" class="step2">Next</button>
</code>```

答:
I would suggest avoiding the alert() as it causes the browser to freeze.  Instead, consider adding the error message to the page as a displayable.

var isValid = false;

function findDuplicates ($elements, selector) {
                    // filter to just the elements that match the selector
  var valueGroups = $elements.filter(selector).get()
    // reduce to elements to a map consisting of a key being their input value
    // and the map value being an array of elements with that input value
    .reduce(function(elementsByValue, element){
      var value = element.value.trim();

      // if we do not have a value, ignore as these will already have an
      // error of Entry required
      if (value) {
        elementsByValue[value] = elementsByValue[value] || [];
        elementsByValue[value].push(element);
      }

      return elementsByValue;
    }, {});

  // now that we have elements grouped by their input values, any input value
  // that is associated with multiple elements needs to mark those elements
  // as duplicates
  Object.values(valueGroups).forEach(function(group){
    if (group.length > 1) {
      $(group).next('.message').addClass('error').text('Duplicate value');
    }
  });
}

function Step2Validation (e) {
  // find all the inputs
  var $requiredInputs = $('.trtickets').find('.navn, .efternavn');

  // find all the inputs that previously had errors, remove the errors
  $requiredInputs.next('.message.error')
    .removeClass('error').html(' ');

  $requiredInputs
    // filter to just the elements without a value
    .filter(function(){ return !this.value.trim(); })
    // go to each one of the empty inputs next message element
    .next('.message')
    // add the error class
    .addClass('error')
    // add the error text
    .text('Entry required');

  // find duplicates in each separate group
  findDuplicates($requiredInputs, '.navn');
  findDuplicates($requiredInputs, '.efternavn');

  // if any of the messages has the error class, it is not valid
  isValid = $requiredInputs.next('.message.error').length < 1;

  if (isValid) {
    $(e.target).closest('fieldset').slideUp().next().slideDown();
  }
}

$('.step2').on('click', Step2Validation);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.message.error { color: red; }</code>```

        <input type="text" name="model.RegistrationLists[0].Name" class="form-control navn" placeholder="Name">

        <input type="text" name="model.RegistrationLists[0].Lastname" class="form-control efternavn" placeholder="Lastname">

        <input type="text" name="model.RegistrationLists[1].Name" class="form-control navn" placeholder="Name">

        <input type="text" name="model.RegistrationLists[1].Lastname" class="form-control efternavn" placeholder="Lastname">

<button type="button" class="step2">Next</button>```

Body:
I have a Table with multiple rows and in each row there are some input fields and i want check if there is  Duplicates value in table.

Here is my code , first I'm trying to find if is there any empty value , how can I check if is there any duplicates value too?

JavaScript:

HTML:

    <input type="text" name="model.RegistrationLists[0].Name" value="John" class="form-control navn" placeholder="Name">

    <input type="text" name="model.RegistrationLists[0].Lastname" class="form-control efternavn" placeholder="Lastname">

    <input type="text" name="model.RegistrationLists[1].Name" value="John" class="form-control navn" placeholder="Name">

    <input type="text" name="model.RegistrationLists[1].Lastname" class="form-control efternavn" placeholder="Lastname">

   <button type="button" onclick="step2(this);" class="step2">Next</button>

Body:
I would suggest avoiding the alert() as it causes the browser to freeze.  Instead, consider adding the error message to the page as a displayable.

var isValid = false;

function findDuplicates ($elements, selector) {
                    // filter to just the elements that match the selector
  var valueGroups = $elements.filter(selector).get()
    // reduce to elements to a map consisting of a key being their input value
    // and the map value being an array of elements with that input value
    .reduce(function(elementsByValue, element){
      var value = element.value.trim();

      // if we do not have a value, ignore as these will already have an
      // error of Entry required
      if (value) {
        elementsByValue[value] = elementsByValue[value] || [];
        elementsByValue[value].push(element);
      }

      return elementsByValue;
    }, {});

  // now that we have elements grouped by their input values, any input value
  // that is associated with multiple elements needs to mark those elements
  // as duplicates
  Object.values(valueGroups).forEach(function(group){
    if (group.length > 1) {
      $(group).next('.message').addClass('error').text('Duplicate value');
    }
  });
}

function Step2Validation (e) {
  // find all the inputs
  var $requiredInputs = $('.trtickets').find('.navn, .efternavn');

  // find all the inputs that previously had errors, remove the errors
  $requiredInputs.next('.message.error')
    .removeClass('error').html('&nbsp;');

  $requiredInputs
    // filter to just the elements without a value
    .filter(function(){ return !this.value.trim(); })
    // go to each one of the empty inputs next message element
    .next('.message')
    // add the error class
    .addClass('error')
    // add the error text
    .text('Entry required');

  // find duplicates in each separate group
  findDuplicates($requiredInputs, '.navn');
  findDuplicates($requiredInputs, '.efternavn');

  // if any of the messages has the error class, it is not valid
  isValid = $requiredInputs.next('.message.error').length < 1;

  if (isValid) {
    $(e.target).closest('fieldset').slideUp().next().slideDown();
  }
}

$('.step2').on('click', Step2Validation);

.message.error { color: red; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="Tickettbl" class="table">
  <tbody id="output">
    <tr class="trtickets">
      <td>
        <input type="text" name="model.RegistrationLists[0].Name" class="form-control navn" placeholder="Name">
        <div class="message">&nbsp;</div>
      </td>
      <td>
        <input type="text" name="model.RegistrationLists[0].Lastname" class="form-control efternavn" placeholder="Lastname">
        <div class="message">&nbsp;</div>
      </td>
    </tr>
    <tr class="trtickets">
      <td>
        <input type="text" name="model.RegistrationLists[1].Name" class="form-control navn" placeholder="Name">
        <div class="message">&nbsp;</div>
      </td>
      <td>
        <input type="text" name="model.RegistrationLists[1].Lastname" class="form-control efternavn" placeholder="Lastname">
        <div class="message">&nbsp;</div>
      </td>
    </tr>
  </tbody>
</table>

<button type="button" class="step2">Next</button>


来源: stackexchange

问:
Reducing the height so that the section does not take up so much of the screen
I am trying to make this section not so big when scrolling I feel it takes too much of the screen. Does anyone have any ideas to make it not so long? Thanks in advance to any one who helps.

.content-sm {
    padding-top: 60px;
    padding-bottom: 60px;
}
@media (min-width: 1200px)
.container {
    width: 1170px;
}
@media (min-width: 992px)
.container {
    width: 970px;
}
@media (min-width: 768px)
.container {
    width: 750px;
}
.container {
    padding-right: 15px;
    padding-left: 15px;
    margin-right: auto;
    margin-left: auto;
}
* {
    border-radius: 0;
}

/*Business Posts Section
------------------------------------*/
.business-post-section {
  position: relative;
  background: #f7f7f7;
}

/*Business Posts Links/Buttons
------------------------------------*/
.business-post-link {
 padding-top: 25px;
 text-align: center;
}

.business-post-link i {
 color: #fff;
 width: 90px;
 height: 90px;
 padding: 30px;
 font-size: 30px;
 line-height: 30px;
 position: relative;
 text-align: center;
 background: #00539c;
 margin-bottom: 25px;
 display: inline-block;
}

.business-post-link i:after {
 top: -8px;
 left: -8px;
 right: -8px;
 bottom: -8px;
 content: " ";
 position: absolute;
 border: 1px solid #dedede;
 border-radius: 50% !important;
}

.business-post-link:hover i,
.business-post-link:hover i:after {
 transition: all 0.3s ease-in-out;
}

.business-post-link:hover i {
 background: #db9e33;
}

.business-post-link:hover i:after {
 border-color: #db9e33;
}

.rounded-x {
    border-radius: 50% !important;
}

.business-post-title {
 font-size: 20px;
 line-height: 24px;
 color: #555;
}

@media (min-width: 768px)
.col-sm-4 {
    width: 33.33333333%;
}
@media (min-width: 768px)
.col-sm-6 {
    width: 50%;
}
@media (min-width: 768px)
.col-sm-1, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9 {
    float: left;
}
.col-lg-1, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-md-1, .col-md-10, .col-md-11, .col-md-12, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-sm-1, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-xs-1, .col-xs-10, .col-xs-11, .col-xs-12, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9 {
    position: relative;
    min-height: 1px;
    padding-right: 15px;
    padding-left: 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.css" rel="stylesheet"/>
<div class="wrapper">
  <!--=== Business Block ===-->
  <div class="business-post-section">
  <div class="container content-sm">
   <div class="row ">

    <div class="col-sm-4 business-post-link">
     <i class="rounded-x icon-drawer"></i>
     <h2 class="business-post-title">Tax Collection Solutions</h2>
    </div>

    <div class="col-sm-4 business-post-link">
     <i class="rounded-x icon-flag"></i>
     <h2 class="business-post-title">Auction Solutions</h2>
    </div>

    <div class="col-sm-4 business-post-link">
     <i class="rounded-x icon-wallet"></i>
     <h2 class="business-post-title">Payment Solutions</h2>
    </div>

   </div><!--/row-->
  </div><!--/container-->
  </div>

  <!--=== Contact Us Block ===-->
  <div class="business-post-section">
  <div class="container content-sm">
   <div class="row ">
    <div class="col-sm-2"></div>

    <div class="col-sm-4 business-post-link">
     <i class="rounded-x icon-screen-desktop"></i>
     <h2 class="business-post-title">Request a Demo</h2>
    </div>

    <div class="col-sm-4 business-post-link">
     <i class="rounded-x icon-call-in"></i>
     <h2 class="business-post-title">Contact Us</h2>
    </div>

    <div class="col-sm-2"></div>
   </div><!--/row-->
  </div><!--/container-->
  </div>

    </div></code>```

答:
I'd adjust padding-top and padding-bottom for .content-sm to 1rem as follows:

.content-sm {
  padding-top: 1rem;
  padding-bottom: 1rem;
}

@media (min-width: 1200px) .container {
  width: 1170px;
}

@media (min-width: 992px) .container {
  width: 970px;
}

@media (min-width: 768px) .container {
  width: 750px;
}

.container {
  padding-right: 15px;
  padding-left: 15px;
  margin-right: auto;
  margin-left: auto;
}

* {
  border-radius: 0;
}

/*Business Posts Section
------------------------------------*/

.business-post-section {
  position: relative;
  background: #f7f7f7;
}

/*Business Posts Links/Buttons
------------------------------------*/

.business-post-link {
  padding-top: 25px;
  text-align: center;
}

.business-post-link i {
  color: #fff;
  width: 90px;
  height: 90px;
  padding: 30px;
  font-size: 30px;
  line-height: 30px;
  position: relative;
  text-align: center;
  background: #00539c;
  margin-bottom: 25px;
  display: inline-block;
}

.business-post-link i:after {
  top: -8px;
  left: -8px;
  right: -8px;
  bottom: -8px;
  content: " ";
  position: absolute;
  border: 1px solid #dedede;
  border-radius: 50% !important;
}

.business-post-link:hover i,
.business-post-link:hover i:after {
  transition: all 0.3s ease-in-out;
}

.business-post-link:hover i {
  background: #db9e33;
}

.business-post-link:hover i:after {
  border-color: #db9e33;
}

.rounded-x {
  border-radius: 50% !important;
}

.business-post-title {
  font-size: 20px;
  line-height: 24px;
  color: #555;
}

@media (min-width: 768px) .col-sm-4 {
  width: 33.33333333%;
}

@media (min-width: 768px) .col-sm-6 {
  width: 50%;
}

@media (min-width: 768px) .col-sm-1,
.col-sm-10,
.col-sm-11,
.col-sm-12,
.col-sm-2,
.col-sm-3,
.col-sm-4,
.col-sm-5,
.col-sm-6,
.col-sm-7,
.col-sm-8,
.col-sm-9 {
  float: left;
}

.col-lg-1,
.col-lg-10,
.col-lg-11,
.col-lg-12,
.col-lg-2,
.col-lg-3,
.col-lg-4,
.col-lg-5,
.col-lg-6,
.col-lg-7,
.col-lg-8,
.col-lg-9,
.col-md-1,
.col-md-10,
.col-md-11,
.col-md-12,
.col-md-2,
.col-md-3,
.col-md-4,
.col-md-5,
.col-md-6,
.col-md-7,
.col-md-8,
.col-md-9,
.col-sm-1,
.col-sm-10,
.col-sm-11,
.col-sm-12,
.col-sm-2,
.col-sm-3,
.col-sm-4,
.col-sm-5,
.col-sm-6,
.col-sm-7,
.col-sm-8,
.col-sm-9,
.col-xs-1,
.col-xs-10,
.col-xs-11,
.col-xs-12,
.col-xs-2,
.col-xs-3,
.col-xs-4,
.col-xs-5,
.col-xs-6,
.col-xs-7,
.col-xs-8,
.col-xs-9 {
  position: relative;
  min-height: 1px;
  padding-right: 15px;
  padding-left: 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.css" rel="stylesheet" />
<div class="wrapper">
  <!--=== Business Block ===-->
  <div class="business-post-section">
    <div class="container content-sm">
      <div class="row ">

          <div class="col-sm-4 business-post-link">
            <i class="rounded-x icon-drawer"></i>
            <h2 class="business-post-title">Tax Collection Solutions</h2>
          </div>

          <div class="col-sm-4 business-post-link">
            <i class="rounded-x icon-flag"></i>
            <h2 class="business-post-title">Auction Solutions</h2>
          </div>

          <div class="col-sm-4 business-post-link">
            <i class="rounded-x icon-wallet"></i>
            <h2 class="business-post-title">Payment Solutions</h2>
          </div>

      </div>
      <!--/row-->
    </div>
    <!--/container-->
  </div>

  <!--=== Contact Us Block ===-->
  <div class="business-post-section">
    <div class="container content-sm">
      <div class="row ">
        <div class="col-sm-2"></div>

          <div class="col-sm-4 business-post-link">
            <i class="rounded-x icon-screen-desktop"></i>
            <h2 class="business-post-title">Request a Demo</h2>
          </div>

          <div class="col-sm-4 business-post-link">
            <i class="rounded-x icon-call-in"></i>
            <h2 class="business-post-title">Contact Us</h2>
          </div>

        <div class="col-sm-2"></div>
      </div>
      <!--/row-->
    </div>
    <!--/container-->
  </div>

</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to make this section not so big when scrolling I feel it takes too much of the screen. Does anyone have any ideas to make it not so long? Thanks in advance to any one who helps.

.content-sm {
    padding-top: 60px;
    padding-bottom: 60px;
}
@media (min-width: 1200px)
.container {
    width: 1170px;
}
@media (min-width: 992px)
.container {
    width: 970px;
}
@media (min-width: 768px)
.container {
    width: 750px;
}
.container {
    padding-right: 15px;
    padding-left: 15px;
    margin-right: auto;
    margin-left: auto;
}
* {
    border-radius: 0;
}

/*Business Posts Section
------------------------------------*/
.business-post-section {
  position: relative;
  background: #f7f7f7;
}

/*Business Posts Links/Buttons
------------------------------------*/
.business-post-link {
 padding-top: 25px;
 text-align: center;
}

.business-post-link i {
 color: #fff;
 width: 90px;
 height: 90px;
 padding: 30px;
 font-size: 30px;
 line-height: 30px;
 position: relative;
 text-align: center;
 background: #00539c;
 margin-bottom: 25px;
 display: inline-block;
}

.business-post-link i:after {
 top: -8px;
 left: -8px;
 right: -8px;
 bottom: -8px;
 content: " ";
 position: absolute;
 border: 1px solid #dedede;
 border-radius: 50% !important;
}

.business-post-link:hover i,
.business-post-link:hover i:after {
 transition: all 0.3s ease-in-out;
}

.business-post-link:hover i {
 background: #db9e33;
}

.business-post-link:hover i:after {
 border-color: #db9e33;
}

.rounded-x {
    border-radius: 50% !important;
}

.business-post-title {
 font-size: 20px;
 line-height: 24px;
 color: #555;
}

@media (min-width: 768px)
.col-sm-4 {
    width: 33.33333333%;
}
@media (min-width: 768px)
.col-sm-6 {
    width: 50%;
}
@media (min-width: 768px)
.col-sm-1, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9 {
    float: left;
}
.col-lg-1, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-md-1, .col-md-10, .col-md-11, .col-md-12, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-sm-1, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-xs-1, .col-xs-10, .col-xs-11, .col-xs-12, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9 {
    position: relative;
    min-height: 1px;
    padding-right: 15px;
    padding-left: 15px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.css" rel="stylesheet"/>

Tax Collection Solutions

Auction Solutions

Payment Solutions

Request a Demo

Contact Us

Body:
I'd adjust padding-top and padding-bottom for .content-sm to 1rem as follows:

.content-sm {
  padding-top: 1rem;
  padding-bottom: 1rem;
}

@media (min-width: 1200px) .container {
  width: 1170px;
}

@media (min-width: 992px) .container {
  width: 970px;
}

@media (min-width: 768px) .container {
  width: 750px;
}

.container {
  padding-right: 15px;
  padding-left: 15px;
  margin-right: auto;
  margin-left: auto;
}

* {
  border-radius: 0;
}

/*Business Posts Section
------------------------------------*/

.business-post-section {
  position: relative;
  background: #f7f7f7;
}

/*Business Posts Links/Buttons
------------------------------------*/

.business-post-link {
  padding-top: 25px;
  text-align: center;
}

.business-post-link i {
  color: #fff;
  width: 90px;
  height: 90px;
  padding: 30px;
  font-size: 30px;
  line-height: 30px;
  position: relative;
  text-align: center;
  background: #00539c;
  margin-bottom: 25px;
  display: inline-block;
}

.business-post-link i:after {
  top: -8px;
  left: -8px;
  right: -8px;
  bottom: -8px;
  content: " ";
  position: absolute;
  border: 1px solid #dedede;
  border-radius: 50% !important;
}

.business-post-link:hover i,
.business-post-link:hover i:after {
  transition: all 0.3s ease-in-out;
}

.business-post-link:hover i {
  background: #db9e33;
}

.business-post-link:hover i:after {
  border-color: #db9e33;
}

.rounded-x {
  border-radius: 50% !important;
}

.business-post-title {
  font-size: 20px;
  line-height: 24px;
  color: #555;
}

@media (min-width: 768px) .col-sm-4 {
  width: 33.33333333%;
}

@media (min-width: 768px) .col-sm-6 {
  width: 50%;
}

@media (min-width: 768px) .col-sm-1,
.col-sm-10,
.col-sm-11,
.col-sm-12,
.col-sm-2,
.col-sm-3,
.col-sm-4,
.col-sm-5,
.col-sm-6,
.col-sm-7,
.col-sm-8,
.col-sm-9 {
  float: left;
}

.col-lg-1,
.col-lg-10,
.col-lg-11,
.col-lg-12,
.col-lg-2,
.col-lg-3,
.col-lg-4,
.col-lg-5,
.col-lg-6,
.col-lg-7,
.col-lg-8,
.col-lg-9,
.col-md-1,
.col-md-10,
.col-md-11,
.col-md-12,
.col-md-2,
.col-md-3,
.col-md-4,
.col-md-5,
.col-md-6,
.col-md-7,
.col-md-8,
.col-md-9,
.col-sm-1,
.col-sm-10,
.col-sm-11,
.col-sm-12,
.col-sm-2,
.col-sm-3,
.col-sm-4,
.col-sm-5,
.col-sm-6,
.col-sm-7,
.col-sm-8,
.col-sm-9,
.col-xs-1,
.col-xs-10,
.col-xs-11,
.col-xs-12,
.col-xs-2,
.col-xs-3,
.col-xs-4,
.col-xs-5,
.col-xs-6,
.col-xs-7,
.col-xs-8,
.col-xs-9 {
  position: relative;
  min-height: 1px;
  padding-right: 15px;
  padding-left: 15px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.css" rel="stylesheet" />
<div class="wrapper">
  <!--=== Business Block ===-->
  <div class="business-post-section">
    <div class="container content-sm">
      <div class="row ">
        <a href="http://www.test.com">
          <div class="col-sm-4 business-post-link">
            <i class="rounded-x icon-drawer"></i>
            <h2 class="business-post-title">Tax Collection Solutions</h2>
          </div>
        </a>
        <a href="http://www.test.com">
          <div class="col-sm-4 business-post-link">
            <i class="rounded-x icon-flag"></i>
            <h2 class="business-post-title">Auction Solutions</h2>
          </div>
        </a>
        <a href="http://www.test.com">
          <div class="col-sm-4 business-post-link">
            <i class="rounded-x icon-wallet"></i>
            <h2 class="business-post-title">Payment Solutions</h2>
          </div>
        </a>
      </div>
      <!--/row-->
    </div>
    <!--/container-->
  </div>

  <!--=== Contact Us Block ===-->
  <div class="business-post-section">
    <div class="container content-sm">
      <div class="row ">
        <div class="col-sm-2"></div>
        <a href="http://www.test.com">
          <div class="col-sm-4 business-post-link">
            <i class="rounded-x icon-screen-desktop"></i>
            <h2 class="business-post-title">Request a Demo</h2>
          </div>
        </a>
        <a href="http://www.test.com">
          <div class="col-sm-4 business-post-link">
            <i class="rounded-x icon-call-in"></i>
            <h2 class="business-post-title">Contact Us</h2>
          </div>
        </a>
        <div class="col-sm-2"></div>
      </div>
      <!--/row-->
    </div>
    <!--/container-->
  </div>

</div>


问:
How to read in line from file, split after the second space so name and score are separated?
Not sure where it is that this is throwing an exception, but basically I'm trying to isolate the score so I can call the scores in a comparable function and print out the associated name and score in order of the score.

```<code>public void loadDataFromFile(String fileName) throws FileNotFoundException {
    FileReader reader = new FileReader(fileName);
    Scanner in = new Scanner(reader);

    while(in.hasNextLine()) {
        String line = in.nextLine();
        String name = line.substring(0, line.indexOf(' ', line.indexOf(' ') + 1));
        String score = line.substring(line.indexOf(name));
        int studentScore = Integer.parseInt(score);

        Student s = new Student(name, studentScore);
        student_list.add(s);
    }
}

public void printInOrder() {
    Collections.sort(this.student_list);
    for(Student s : student_list) {
        s.toString();
    }
}
</code>```

Text file that I'm reading from

答:
Thanks for the help, it ended up just being the issue of not grabbing the individual number, where studentScore was grabbing the whole line. I fixed and posted for other's reference.

public void loadDataFromFile(String fileName) throws FileNotFoundException {
  FileReader reader = new FileReader(fileName);
  Scanner in = new Scanner(reader);

  while ( in .hasNextLine()) {
    String line = in .nextLine();
    String name = line.substring(0, line.indexOf(' ', line.indexOf(' ') + 1));
    String studentScore1 = line.substring(line.length() - 2);
    int studentScore = Integer.parseInt(studentScore1);
    Student s = new Student(name, studentScore);
    student_list.add(s);
  }
}

public void printInOrder() {
  Collections.sort(this.student_list);
  for (Student s: student_list) {
    System.out.println(s.toString());
  }
}```

Body:
Not sure where it is that this is throwing an exception, but basically I'm trying to isolate the score so I can call the scores in a comparable function and print out the associated name and score in order of the score.

public void loadDataFromFile(String fileName) throws FileNotFoundException {
    FileReader reader = new FileReader(fileName);
    Scanner in = new Scanner(reader);

    while(in.hasNextLine()) {
        String line = in.nextLine();
        String name = line.substring(0, line.indexOf(' ', line.indexOf(' ') + 1));
        String score = line.substring(line.indexOf(name));
        int studentScore = Integer.parseInt(score);

        Student s = new Student(name, studentScore);
        student_list.add(s);
    }
}

public void printInOrder() {
    Collections.sort(this.student_list);
    for(Student s : student_list) {
        s.toString();
    }
}

Text file that I'm reading from


问:
How would you design a good search UI?
I want to provide my users with an 'advanced' search engine.
I basically have a lot of search criteria to chose from :

some are very simple/common and will be largely use (ie time period, item id)

some are a bit less mainstream

and some won't be used a lot, but I still want to provide them

Overall, I have around 30+ criteria to chose from

The result is a dataset which I display in a grid.

I've search for inspiration on internet, and even google doesn't seem to have a nice solution for advanced search.

I've designed this kind of tools in the past, and I wasn't really pleased by the result, although the user were eventually able to use it quite effectively.

Do you think the search panel should be visible all the time (ie displayed on top of my result grid) or available in a separate form (which would let me use more place for all the controls)

Do you think it's better to display all the search criteria, or to let the user click on 'advanced' if he wants to see/use more criteria

How would you organize the criteria? by usage frequency, or rather by area (ie. criteria related to user, to location, to time, etc.)

Where should I put the 'Search' button? next to the more common search controls, or at the bottom, or both?

And more generally, do you have tips you want to share on how to design a nice search UI ?
What kind of functionalities do you usually miss in this kind of 'advanced' search engines?

答:
1) Do you think the search panel should be visible on top of my result grid?

A simple search panel like Google’s basic search may be on the Results page since it’s compact. This allows the user to re-try the search with different criteria without wasting time going to a new page or window. Advanced search is much more cluttering so there’s a more important tradeoff between easy access to the results (in a smaller pane) and easy access to re-search, so you need to appraise the frequency users re-searching versus the work they do with the results. For example, if re-search happens 50% of the time, but including an Advanced Search panel in the Results page requires additional scrolling 75% of the time, your users are better off without an Advanced Search panel on the Results. As a general rule, Advanced Search should not be on the Results page unless the task is really cut-and-try exploration of the data.

Another issue with the Search panel at the top of the results is what to do if the results do not correspond to the criteria (e.g., if the user changes a criterion after the results are shown but before clicking Search again). With Advanced Search it is much easier for users to forget or miss whether they changed a criterion or not and then be confused about what criteria is in effect for the results. Putting Advanced Search on a separate page prevents this, although there are other ways to avoid this problem if Advanced Search is on the Results page (e.g., using instant-apply “faceted” search).

In any case, the Results page should display the criteria used in making the search.

2) Do you think it's better to let the user click on 'advanced' for more criteria?

For most database apps, users of a particular group (e.g., job position) have 2 to 5 specific sets of search criteria that get them through the vast majority of their work, (e.g., search for orders made between two user-supplied dates), sometimes including criteria that even have specific criterion values (e.g., search for all orders with a pending status). In this situation, users will be fastest and least likely to be confused if you have an Advanced button for ad hoc searching, while the default search has controls tailored for these specific searches. Default to Advanced Search only if your users will primarily be conducting exploratory ad hoc searches.

3) How would you organize the criteria?

If there are certain criteria that are used especially often, then they’re handled through Basic Search as described for 2, so there’s little advantage to sorting criteria in Advanced Search by frequency. It just makes it hard for users to find the criterion they’re looking for. Generally you can rely on users having a specific named field in mind, so sort the criterion alphabetically, or, if users are familiar with the Results Page and its fields are laid out in a manner consistent with how the users think, use the same order as used for the Results columns.

4) Where should I put the 'Search' button?

The Search Button ideally should always be visible. The best solution is to have all the criteria on a scrollable pane with the button outside the pane. Putting the button at the top and bottom is a common but kludgey alternative. I wouldn’t put it by the common criteria because if your users have gone from Basic to Advanced Search, they’re probably not using common criteria. Consider no Search Button if you can keep response time under 500 ms, instead providing instant-apply like seen in Vista.

5) How to design a nice search UI?

For field-based multi-criteria Search, there are two basic designs:

a. A form of all fields with a place to enter criterion values for each field. The problem with this is fields with set values can scroll out of view and users may have forgotten they’ve set a value. Thus you want to keep this as compact as possible. See the chapter Improving Data Retrieval in Alan Cooper’s About Face 2.0 for one approach. You can also provide a summary string of the selected criteria near the Search buttons which the user can check. Clicking each criteria in the string can even jump the user to the criteria for changing it.

b. The user selects from a list of fields those to be used in the criteria, then sets the values for the criteria in consolidated location. The main challenge here is to minimize the number of “overhead” clicks to select a field. Ideally, the list of fields are always available and one click selects the field, puts it in the consolidated location, and places the cursor in the value control, something like shown in http://www.zuschlogin.com/content/blogimages/37/FindAdvanced.gif, only for Search rather than Find. (By arbitrary convention “Find” is very different than “Search” for users; Find highlights things within the current page matching a given criteria while Search retrieves things matching a given criteria)

Both of these designs link the criterion for each field by logical ANDs and are limited in the joins among the underlying database tables, but that is likely satisfy nearly all your users. If the tasks require more complicated joins and Boolean combinations, look into graphical querying designs (e.g., Badre AN, Catarci T, Massari A, & Santucci G 1996. Comparative ease of use of a diagrammatic vs. An iconic query language. In J Kennedy & P Barclay (Eds) Interfaces to Databases (IDS-3): Proceedings of the 3rd International Workshop on Interfaces to Databases, Napier University, Edinburgh, 8-10 July) and Query by Example designs.

OwnerDisplayName: Brann

ContentLicense: CC BY-SA 2.5

Title: How would you design a good search UI?

LastEditorDisplayName: onnodb

OwnerDisplayName: Michael Zuschlag


问:
.NET Remoting with Reflection
I need to dynamically load an interface assembly that I use on client-side remoting. Something like this.

```<code>static void Main(string[] args)
{
  TcpClientChannel clientChannel = new TcpClientChannel();
  ChannelServices.RegisterChannel(clientChannel, false);

  Assembly interfaceAssembly = Assembly.LoadFile("RemotingInterface.dll");
  Type iTheInterface =
    interfaceAssembly.GetType("RemotingInterface.ITheService");

  RemotingConfiguration.RegisterWellKnownClientType(iTheInterface,
                                        "tcp://localhost:9090/Remotable.rem");
  object wellKnownObject = Activator.GetObject(iTheInterface,
                                        "tcp://localhost:9090/Remotable.rem");
}
</code>```

Only I can't seem to grasp how to call any methods as I can't cast the Activator.GetObject. How can I create a proxy of ITheService without knowing the interface at compile-time?

答:
The returned object implements the interface, so you can use reflection to get its member methods and invoke them.

Or, in C#4, you can use dynamic:

```<code>dynamic wellKnownObject = Activator.GetObject(iTheInterface,
    "tcp://localhost:9090/Remotable.rem");

wellKnownObject.SomeMethod(etc ..);
</code>```

ContentLicense: CC BY-SA 3.0

Title: .NET Remoting with Reflection

Body:
I need to dynamically load an interface assembly that I use on client-side remoting. Something like this.

static void Main(string[] args)
{
  TcpClientChannel clientChannel = new TcpClientChannel();
  ChannelServices.RegisterChannel(clientChannel, false);

  Assembly interfaceAssembly = Assembly.LoadFile("RemotingInterface.dll");
  Type iTheInterface =
    interfaceAssembly.GetType("RemotingInterface.ITheService");

  RemotingConfiguration.RegisterWellKnownClientType(iTheInterface,
                                        "tcp://localhost:9090/Remotable.rem");
  object wellKnownObject = Activator.GetObject(iTheInterface,
                                        "tcp://localhost:9090/Remotable.rem");
}

Only I can't seem to grasp how to call any methods as I can't cast the Activator.GetObject. How can I create a proxy of ITheService without knowing the interface at compile-time?

Body:
The returned object implements the interface, so you can use reflection to get its member methods and invoke them.

Or, in C#4, you can use dynamic:

dynamic wellKnownObject = Activator.GetObject(iTheInterface,
    "tcp://localhost:9090/Remotable.rem");

wellKnownObject.SomeMethod(etc ..);


问:
Create multiple sequences with different lengths (length.out)
Let's say I have a vector,

```<code>n <- c(1:100)
</code>```

and I want to output multiple sequences for each value 'n' takes in the vector above.

I tried doing something like this:

```<code>x <- seq (0,5, length.out = n+1)
x <- x[-1]
</code>```

I get the error:

Warning Message:
In seq.default(0,5, length.out = n+1)
First element used of length.out argument

I then want to use 'x' for a calculating in:

```<code>fx <- dnorm(x, mean = 0 , sd = 4)
</code>```

Where fx[1] will output the first value of fx and so on up to fx[n]

Body:
Let's say I have a vector,

n <- c(1:100)

and I want to output multiple sequences for each value 'n' takes in the vector above.

I tried doing something like this:

x <- seq (0,5, length.out = n+1)
x <- x[-1]

I get the error:

Warning Message:
In seq.default(0,5, length.out = n+1)
First element used of length.out argument

I then want to use 'x' for a calculating in:

fx <- dnorm(x, mean = 0 , sd = 4)

Where fx[1] will output the first value of fx and so on up to fx[n]

Body:
Is this what you wanted x to look like?

x <- lapply(n, function(i) seq (0,5, length.out = i+1))
x
[[1]]
[1] 0 5

[[2]]
[1] 0.0 2.5 5.0

[[3]]
[1] 0.000000 1.666667 3.333333 5.000000

[[4]]
[1] 0.00 1.25 2.50 3.75 5.00

[[5]]
[1] 0 1 2 3 4 5

[[6]]
[1] 0.0000000 0.8333333 1.6666667 2.5000000 3.3333333 4.1666667 5.0000000


问:
comparing two strings and their index seeing if all of string 2 is in string 1 with same order but different letter in between
Assume all letters in the given words are lowercase.
You may use string methods if any are useful.

```<code>>>> occurs_within('aaacaabxyt', 'cat')
True

>>> occurs_within('tac', 'cat')
False

>>> occurs_within('oboe', 'bob')
False

>>> occurs_within('ecxbtalt', 'exalt')
True

>>> occurs_within('ecxbtal', 'exalt')
False

if len(word1) > len(word2):
    for i in range(0,len(word1)):
        if word2[i] < word2[i+1]:
            return True
        else:
            return False
else:
    return False
</code>```

I tried using a nested for loop inside an if function comparing the two strings and looping to find if the next index of string 2 that is with in string 1 is greater than that of the previous index, but it turns out my result are all True somehow, and I cant figure out what seem to be the problem.

答:
You can try this. Take O(n) time.

```<code>def func(a,b):
     a1=len(a)
     b1=len(b)
     i,j=0,0
     while(i<a1 and j<b1):
         if a[i]==b[j]:
             j=j+1
         i=i+1
     return j==b1
</code>```

```<code>>>> func('aaacaabxyt', 'cat')
True
>>> func('tac', 'cat')
False
>>> func('oboe', 'bob')
False
>>> func('ecxbtalt', 'exalt')
True
>>> func('ecxbtal', 'exalt')
False
</code>```

Body:
Assume all letters in the given words are lowercase.
You may use string methods if any are useful.

>>> occurs_within('aaacaabxyt', 'cat')
True

>>> occurs_within('tac', 'cat')
False

>>> occurs_within('oboe', 'bob')
False

>>> occurs_within('ecxbtalt', 'exalt')
True

>>> occurs_within('ecxbtal', 'exalt')
False

if len(word1) > len(word2):
    for i in range(0,len(word1)):
        if word2[i] < word2[i+1]:
            return True
        else:
            return False
else:
    return False

I tried using a nested for loop inside an if function comparing the two strings and looping to find if the next index of string 2 that is with in string 1 is greater than that of the previous index, but it turns out my result are all True somehow, and I cant figure out what seem to be the problem.

Body:
You can try this. Take O(n) time.

def func(a,b):
     a1=len(a)
     b1=len(b)
     i,j=0,0
     while(i<a1 and j<b1):
         if a[i]==b[j]:
             j=j+1
         i=i+1
     return j==b1

>>> func('aaacaabxyt', 'cat')
True
>>> func('tac', 'cat')
False
>>> func('oboe', 'bob')
False
>>> func('ecxbtalt', 'exalt')
True
>>> func('ecxbtal', 'exalt')
False


问:
clang-tidy report error unknown argument when contain other compiler options
I have a project, I built it with intel compiler. I want use the clang-tidy to help detect code problems.

I am using CMake to generate compile_commands.json and I'm getting the follow error when I using clang-tidy:

```<code>$ run-clang-tidy
# output
# ...
clang-tidy-6.0 -header-filter=^/home/xuhui/temp/build/.* -p=/home/xuhui/temp/build /home/xuhui/temp/main.cpp
1 warning and 1 error generated.
Error while processing /home/xuhui/temp/main.cpp.
error: unknown argument: '-w2' [clang-diagnostic-error]
warning: unknown warning option '-Wno-maybe-uninitialized'; did you mean '-Wno-uninitialized'? [clang-diagnostic-unknown-warning-option]
</code>```

Actually, there is a very simliar question exist: clang-tidy reporting unknown warnings

However, when I try to using the method refered above, there is no help. The warning can be suppressed but error still exist.

```<code>$ run-clang-tidy -extra-arg=-Wno-unknown-warning-option

# output
# ...
clang-tidy-6.0 -header-filter=^/home/xuhui/temp/build/.* -extra-arg=-Wno-unknown-warning-option -p=/home/xuhui/temp/build /home/xuhui/temp/main.cpp
1 error generated.
Error while processing /home/xuhui/temp/main.cpp.
error: unknown argument: '-w2' [clang-diagnostic-error]
</code>```

How can I deal with the error?

-w2 options is used to control warning in intel compiler.

Although the problem occurs to me because of the intel compiler, but may be other compiler's options can also leads to the problem.

Appendix

The follow code snippets can help reproduce the problem.

```<code>// CMakeLists.txt
SET(CMAKE_CXX_COMPILER "icc")
SET(CMAKE_CXX_COMPILER "icpc")

project(test)

# leads to warning, can be settled by refer link
add_compile_options("-Wno-maybe-uninitialized")

# leads to error, can not be settled by refer link
add_compile_options("-w2")

add_executable(a.out main.cpp)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
</code>```

```<code>// main.cpp
#include <iostream>
int main()
{
    std::cout << "hello!" << std::endl;
    return 0;
}
</code>```

the above code can generate compile_commands.json like follows:

```<code>[
{
  "directory": "/home/xuhui/temp/build",
  "command": "/opt/intel/compilers_and_libraries_2019.0.117/linux/bin/intel64/icpc      -Wno-maybe-uninitialized -w2 -o CMakeFiles/a.out.dir/main.o -c /home/xuhui/temp/main.cpp",
  "file": "/home/xuhui/temp/main.cpp"
}
]
</code>```

Thanks for your time.

答:
This is not a clang-tidy error per se. Clang-diagnostic-error is basically a compiler error. Clang has made unknown arguments a hard error some time ago and it cannot be degraded to a warning. There used to be -Qunused-arguments but that doesn't work in Clang 11 AFAIK.

You will have to remove the argument before passing the compile commands to clang-tidy, I suggest CMake - remove a compile flag for a single translation unit.

Body:
I have a project, I built it with intel compiler. I want use the clang-tidy to help detect code problems.

I am using CMake to generate compile_commands.json and I'm getting the follow error when I using clang-tidy:

$ run-clang-tidy
# output
# ...
clang-tidy-6.0 -header-filter=^/home/xuhui/temp/build/.* -p=/home/xuhui/temp/build /home/xuhui/temp/main.cpp
1 warning and 1 error generated.
Error while processing /home/xuhui/temp/main.cpp.
error: unknown argument: '-w2' [clang-diagnostic-error]
warning: unknown warning option '-Wno-maybe-uninitialized'; did you mean '-Wno-uninitialized'? [clang-diagnostic-unknown-warning-option]

Actually, there is a very simliar question exist: clang-tidy reporting unknown warnings

However, when I try to using the method refered above, there is no help. The warning can be suppressed but error still exist.

$ run-clang-tidy -extra-arg=-Wno-unknown-warning-option

# output
# ...
clang-tidy-6.0 -header-filter=^/home/xuhui/temp/build/.* -extra-arg=-Wno-unknown-warning-option -p=/home/xuhui/temp/build /home/xuhui/temp/main.cpp
1 error generated.
Error while processing /home/xuhui/temp/main.cpp.
error: unknown argument: '-w2' [clang-diagnostic-error]

How can I deal with the error?

-w2 options is used to control warning in intel compiler.

Although the problem occurs to me because of the intel compiler, but may be other compiler's options can also leads to the problem.

Appendix

The follow code snippets can help reproduce the problem.

// CMakeLists.txt
SET(CMAKE_CXX_COMPILER "icc")
SET(CMAKE_CXX_COMPILER "icpc")

project(test)

# leads to warning, can be settled by refer link
add_compile_options("-Wno-maybe-uninitialized")

# leads to error, can not be settled by refer link
add_compile_options("-w2")

add_executable(a.out main.cpp)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

// main.cpp
#include <iostream>
int main()
{
    std::cout << "hello!" << std::endl;
    return 0;
}

the above code can generate compile_commands.json like follows:

[
{
  "directory": "/home/xuhui/temp/build",
  "command": "/opt/intel/compilers_and_libraries_2019.0.117/linux/bin/intel64/icpc      -Wno-maybe-uninitialized -w2 -o CMakeFiles/a.out.dir/main.o -c /home/xuhui/temp/main.cpp",
  "file": "/home/xuhui/temp/main.cpp"
}
]

Thanks for your time.


问:
count matches based on list of values in a cell
This seems like it should be simple but after googling for hours and trying many different approaches I'm stumped.

I have a table of values containing single and two digit numbers, and a cell containing the list of values to be counted. This list of values is separated by spaces and can be any length.

The first version of this I did worked fine because I was only using single digit numbers in the table. This is the formula I used: =countIf(arrayFormula(regexMatch(
, substitute(<cell>, " ", "|"))), TRUE)

So in my list cell I can put 2 4 6 and all the cells containing those numbers will be counted.

For the second version I need to able to put 3 12 and make sure values like 2 and 13 would not be counted.

I would like to avoid using VBA since I want this to work in sheets, number, excel, etc.

答:
try:

```<code>=COUNTIF(ARRAYFORMULA(REGEXMATCH(B:B&"", "^"&SUBSTITUTE(A1, " ", "$|^")&"$")), TRUE)
</code>```

Body:
try:

=COUNTIF(ARRAYFORMULA(REGEXMATCH(B:B&"", "^"&SUBSTITUTE(A1, " ", "$|^")&"$")), TRUE)


问:
How do you test pages that require authentication with Selenium?
I need to test a web application using Selenium. The app is fairly common in its setup: it requires signing in for most of the functionality to be exposed. Upon loading a page, if the user is not authenticated, it will redirect to a login form and then back to the requested page once credentials are supplied.

What's the usual way to go around this with Selenium? I take it people are not logging in on every single test as this would cause significant overhead on big test suites. Is there a way to set up a session in a test and then use the cookie information for subsequent tests, or do a conditional sign-in (without incurring in massive code repetition!)?

I am using PHPUnit with Selenium ATM.

Thank you!

Gonzalo

答:
(I'm using C#+NUnit+Selenium RC)

Most of the time, each test goes through the login form. However, if I'm writing a series of tests that are very short (< 10 seconds each) and there are a lot of them, I usually share the same browser instance across tests by moving the selenium start\close calls from the SetUp\TearDown methods to the Test Fixture SetUp\TearDown methods. This avoids the cost of re-authenticating as well as the cost of launching a new browser every time. I'm sure you can do something similar with PHPUnit.


问:
How to forcefully close an async generator?
Let's say I have an async generator like this:

async def event_publisher(connection, queue):
    while True:
        if not await connection.is_disconnected():
            event = await queue.get()
            yield event
        else:
            return
```

<p>I consume it like this:</p>

<pre class="lang-py prettyprint-override"><code>published_events = event_publisher(connection, queue)
async for event in published_events:
    # do event processing here
</code>```

It works just fine, however when the connection is disconnected and there is no new event published the async for will just wait forever, so ideally I would like to close the generator forcefully like this:

if connection.is_disconnected():
    await published_events.aclose()
```

But I get the following error:

RuntimeError: aclose(): asynchronous generator is already running

Is there a way to stop processing of an already running generator?

答:
It seems to be related to this issue. Noticable:

As shown in
  https://gist.github.com/1st1/d9860cbf6fe2e5d243e695809aea674c, it's an
  error to close a synchronous generator while it is being iterated.

...

In 3.8, calling "aclose()" can crash with a RuntimeError.  It's no
  longer possible to reliably cancel a running asynchrounous
  generator.

Well, since we can't cancel running asynchrounous generator, let's try to cancel its running.

```<code>import asyncio
from contextlib import suppress

async def cancel_gen(agen):
    task = asyncio.create_task(agen.__anext__())
    task.cancel()
    with suppress(asyncio.CancelledError):
        await task
    await agen.aclose()  # probably a good idea,
                         # but if you'll be getting errors, try to comment this line
</code>```

...

```<code>if connection.is_disconnected():
    await cancel_gen(published_events)
</code>```

Can't test if it'll work since you didn't provide reproducable example.

Body:
Let's say I have an async generator like this:

async def event_publisher(connection, queue):
    while True:
        if not await connection.is_disconnected():
            event = await queue.get()
            yield event
        else:
            return

I consume it like this:

published_events = event_publisher(connection, queue)
async for event in published_events:
    # do event processing here

It works just fine, however when the connection is disconnected and there is no new event published the async for will just wait forever, so ideally I would like to close the generator forcefully like this:

if connection.is_disconnected():
    await published_events.aclose()

But I get the following error:

RuntimeError: aclose(): asynchronous generator is already running

Is there a way to stop processing of an already running generator?

Body:
It seems to be related to this issue. Noticable:

As shown in
  https://gist.github.com/1st1/d9860cbf6fe2e5d243e695809aea674c, it's an
  error to close a synchronous generator while it is being iterated.

...

In 3.8, calling "aclose()" can crash with a RuntimeError.  It's no
  longer possible to reliably cancel a running asynchrounous
  generator.

Well, since we can't cancel running asynchrounous generator, let's try to cancel its running.

import asyncio
from contextlib import suppress

async def cancel_gen(agen):
    task = asyncio.create_task(agen.__anext__())
    task.cancel()
    with suppress(asyncio.CancelledError):
        await task
    await agen.aclose()  # probably a good idea,
                         # but if you'll be getting errors, try to comment this line

...

if connection.is_disconnected():
    await cancel_gen(published_events)

Can't test if it'll work since you didn't provide reproducable example.


问:
How do we run a single test using Google bazel
For running all the tests under a target I use the command line command

```<code>bazel test //src/code_path:target_name
</code>```

What should be additional parameters to run a test single_test from the above target?

答:
You'll want to use --test_filter:

https://docs.bazel.build/versions/2.0.0/command-line-reference.html#flag--test_filter

The specific format of the value to the flag depends on the test runner.

Body:
For running all the tests under a target I use the command line command

bazel test //src/code_path:target_name

What should be additional parameters to run a test single_test from the above target?


问:
pandas calculate time series resampling
If I had some random data created on a one hour sample..

```<code>import pandas as pd
import numpy as np
from numpy.random import randint

np.random.seed(10)  # added for reproductibility

rng = pd.date_range('10/9/2018 00:00', periods=1000, freq='1H')
df = pd.DataFrame({'Random_Number':randint(1, 100, 1000)}, index=rng)
</code>```

I can use the groupby to break out each day:

```<code>for idx, day in df.groupby(df.index.date):
    print(day)
</code>```

Now is there a way to calculate the time difference between daily min & max value based on the timestamp in hours? for each day record the daily min & max & time difference?

Title: pandas calculate time series resampling

Body:
If I had some random data created on a one hour sample..

import pandas as pd
import numpy as np
from numpy.random import randint

np.random.seed(10)  # added for reproductibility

rng = pd.date_range('10/9/2018 00:00', periods=1000, freq='1H')
df = pd.DataFrame({'Random_Number':randint(1, 100, 1000)}, index=rng)

I can use the groupby to break out each day:

for idx, day in df.groupby(df.index.date):
    print(day)

Now is there a way to calculate the time difference between daily min & max value based on the timestamp in hours? for each day record the daily min & max & time difference?

Body:
After some discussion (thanks @Erfan):

(df.Random_Number
   .groupby(df.index.date)
   .agg(['idxmin','idxmax'])
   .diff(axis=1).iloc[:,1]
   .div(pd.to_timedelta('1H'))
)

Output:

2018-10-09    -4.0
2018-10-10    -1.0
2018-10-11    -4.0
2018-10-12    12.0
2018-10-13    21.0
2018-10-14     6.0
2018-10-15    -6.0
2018-10-16   -18.0
2018-10-17    -8.0
2018-10-18     9.0
2018-10-19   -10.0
2018-10-20     3.0
2018-10-21    10.0
2018-10-22     2.0
2018-10-23     9.0
2018-10-24     2.0
2018-10-25     3.0
2018-10-26     2.0
2018-10-27   -22.0
2018-10-28     6.0
2018-10-29    -8.0
2018-10-30    -1.0
2018-10-31   -11.0
2018-11-01    19.0
2018-11-02     7.0
2018-11-03     4.0
2018-11-04    18.0
2018-11-05    -1.0
2018-11-06    15.0
2018-11-07   -14.0
2018-11-08   -16.0
2018-11-09    -2.0
2018-11-10    -7.0
2018-11-11   -14.0
2018-11-12    12.0
2018-11-13   -14.0
2018-11-14     2.0
2018-11-15     2.0
2018-11-16     6.0
2018-11-17    -7.0
2018-11-18     5.0
2018-11-19     9.0
Name: idxmax, dtype: float64


问:
C - how to add a char to an array
I'm trying to figure out how to add a simple char to an array created with malloc.

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

int main() {
    char *array = malloc(2);
    array[0] = "h";
    printf("%s", array);
    return 0;
}
</code>```

It gives the warning:

```<code> warning: assignment makes integer from pointer without a cast [-Wint-conversion]
array[0] = "h";
</code>```

and if I run the program anyway, it just prints out 3 random symbols.

答:
For starters in this statement

```<code>array[0] = "h";
</code>```

there is used a string literal instead of a single character (integer) 'h'. The string literal is converted to pointer to its first character. So in this statement you are trying to assign a pointer to a character.

You have to use a character literal like

```<code>array[0] = 'h';
</code>```

But in this case the array will not contain a string because the second character of the array is not initialized and has indeterminate value. And the conversion specifier %s is used to output strings.

So You need to append one more statement like this

```<code>array[1] = '\0';
</code>```

Or you could initially to use calloc instead of malloc.

```<code>char *array = calloc(2);
</code>```

and then it will be enough to write

```<code>array[0] = 'h';
</code>```

If you want to use the string literal then instead of the assignment you should use the standard C function strcpy like

```<code>strcpy( array, "h" );
</code>```

to copy the string literal into allocated dynamically array.

You should free the allocated memory when the array is not needed any more.

```<code>free( array );
</code>```

Title: C - how to add a char to an array

Body:
I'm trying to figure out how to add a simple char to an array created with malloc.

#include <stdio.h>
#include <stdlib.h>

int main() {
    char *array = malloc(2);
    array[0] = "h";
    printf("%s", array);
    return 0;
}

It gives the warning:

 warning: assignment makes integer from pointer without a cast [-Wint-conversion]
array[0] = "h";

and if I run the program anyway, it just prints out 3 random symbols.

Body:
For starters in this statement

array[0] = "h";

there is used a string literal instead of a single character (integer) 'h'. The string literal is converted to pointer to its first character. So in this statement you are trying to assign a pointer to a character.

You have to use a character literal like

array[0] = 'h';

But in this case the array will not contain a string because the second character of the array is not initialized and has indeterminate value. And the conversion specifier %s is used to output strings.

So You need to append one more statement like this

array[1] = '\0';

Or you could initially to use calloc instead of malloc.

char *array = calloc(2);

and then it will be enough to write

array[0] = 'h';

If you want to use the string literal then instead of the assignment you should use the standard C function strcpy like

strcpy( array, "h" );

to copy the string literal into allocated dynamically array.

You should free the allocated memory when the array is not needed any more.

free( array );


问:
Not able to figure out the logical error in C program
A program that prints its input one word per line.

```<code>int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c== ' ' || c== '\n' ||c == '\t')
                putchar('\n');
        else {
            putchar(c);
        }
    }
    return 0;
}
</code>```

The above program prints the result correctly, one word per line. After changing the condition accordingly, I was expecting the program below to also print one word per line. However I am not getting the correct result. Am I making some silly mistake or is something wrong?

```<code>int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c != ' ' || c != '\n' || c != '\t')
            putchar(c);
        else {
            putchar('\n');
        }
    }

    return 0;

}
</code>```

答: You need to study a bit more on DeMorgan's Laws.  It is not enough to change the combination operators from "||" to "&&", you must also negate all of the elements being combined to obtain the same solution set.</p>

Body:
A program that prints its input one word per line.

int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c== ' ' || c== '\n' ||c == '\t')
                putchar('\n');
        else {
            putchar(c);
        }
    }
    return 0;
}

The above program prints the result correctly, one word per line. After changing the condition accordingly, I was expecting the program below to also print one word per line. However I am not getting the correct result. Am I making some silly mistake or is something wrong?

int main() {

    int c;

    while ((c=getchar()) != EOF) {

        if (c != ' ' || c != '\n' || c != '\t')
            putchar(c);
        else {
            putchar('\n');
        }
    }

    return 0;

}


问:
How can I execute a SQL Server stored procedure from a Batch file and get the Output parameter value?
I have this SQL Server stored procedure that has an output parameter

```<code>PROCEDURE [dbo].[test]
    @outputx int output
AS
    SELECT @outputx = 123
</code>```

When I run it in SQL Server Management Studio, it returns 123:

```<code>DECLARE @outputx int
EXEC test @outputx output

SELECT @outputx  --> returns 123
</code>```

I need to call this stored procedure from a batch file or PowerShell.

I use this code in a .BAT file (I use OSQL):

```<code>SET tempfile = "C:\myFolder\tempfile.txt"
SET outputx = 0
SET Cmd = EXEC test @outputx output;
SET Cmd = "%Cmd%"

OSQL -S myDBServer -d myDbName -E -e -p -b -Q %Cmd% >%tempfile%
</code>```

When I checked tempfile.txt, it says this:

Msg 137, Level 15, State 2, Server myDBServer, Line 1

  Must declare the scalar variable "@outputx".

  EXEC test @outputx output;

How can I execute a SQL Server stored procedure from a batch file and get the output parameter value?

Thank you

答:
Have you tried the SqlServer module for PowerShell?  After installing that module, you have access to the Invoke-SqlCmd cmdlet.  You can use this cmdlet to retrieve anything that will run in SQLMgr.

```<code>$ReturnValue = invoke-sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $QueryString
</code>```

There are other commands in that module including commands to read and write tables and views.

I hope this helps you out.

Body:
I have this SQL Server stored procedure that has an output parameter

PROCEDURE [dbo].[test]
    @outputx int output
AS
    SELECT @outputx = 123

When I run it in SQL Server Management Studio, it returns 123:

DECLARE @outputx int
EXEC test @outputx output

SELECT @outputx  --> returns 123

I need to call this stored procedure from a batch file or PowerShell.

I use this code in a .BAT file (I use OSQL):

SET tempfile = "C:\myFolder\tempfile.txt"
SET outputx = 0
SET Cmd = EXEC test @outputx output;
SET Cmd = "%Cmd%"

OSQL -S myDBServer -d myDbName -E -e -p -b -Q %Cmd% >%tempfile%

When I checked tempfile.txt, it says this:

Msg 137, Level 15, State 2, Server myDBServer, Line 1

  Must declare the scalar variable "@outputx".

  EXEC test @outputx output;

How can I execute a SQL Server stored procedure from a batch file and get the output parameter value?

Thank you

Body:
Have you tried the SqlServer module for PowerShell?  After installing that module, you have access to the Invoke-SqlCmd cmdlet.  You can use this cmdlet to retrieve anything that will run in SQLMgr.

$ReturnValue = invoke-sqlcmd -ServerInstance $ServerInstance -Database $Database -Query $QueryString

There are other commands in that module including commands to read and write tables and views.

I hope this helps you out.


问:
How can I junit test the last block of this equal?
How can I JUnit test the last block of this equal?

Any help would be much appreciated. This is the method in question:

```<code>@Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    //unreachable block
    ServiceOrderRelationship serviceOrderRelationship = (ServiceOrderRelationship) o;
    return Objects.equals(this.id, serviceOrderRelationship.id) &&
        Objects.equals(this.href, serviceOrderRelationship.href) &&
        Objects.equals(this.relationshipType, serviceOrderRelationship.relationshipType) &&
        Objects.equals(this.baseType, serviceOrderRelationship.baseType) &&
        Objects.equals(this.schemaLocation, serviceOrderRelationship.schemaLocation) &&
        Objects.equals(this.type, serviceOrderRelationship.type) &&
        Objects.equals(this.referredType, serviceOrderRelationship.referredType);
  }
</code>```

This is what I've been doing but I can never reach the last block of code inside the equals method:

```<code>@Test
public void testEquals() throws Exception {

    assertFalse(serviceOrderRelationship.equals(null));
    assertTrue(serviceOrderRelationship.equals(serviceOrderRelationship));
    assertFalse(serviceOrderRelationship.equals(serviceOrderRelationship1));
}
</code>```

答:
Your problem might be that one of the follow cases, in which the method would return prematurely.
If serviceOrderRelationship and serviceOrderRelationship1 are references to the same object, the  true would be returned. Similarly, if they are not of the same type, false would be returned. If serviceOrderRelationship1 is null, false would be returned.
If serviceOrderRelationship is null, then calling equals on it would throw a NullPointerException.

Body:
How can I JUnit test the last block of this equal?

Any help would be much appreciated. This is the method in question:

@Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    //unreachable block
    ServiceOrderRelationship serviceOrderRelationship = (ServiceOrderRelationship) o;
    return Objects.equals(this.id, serviceOrderRelationship.id) &&
        Objects.equals(this.href, serviceOrderRelationship.href) &&
        Objects.equals(this.relationshipType, serviceOrderRelationship.relationshipType) &&
        Objects.equals(this.baseType, serviceOrderRelationship.baseType) &&
        Objects.equals(this.schemaLocation, serviceOrderRelationship.schemaLocation) &&
        Objects.equals(this.type, serviceOrderRelationship.type) &&
        Objects.equals(this.referredType, serviceOrderRelationship.referredType);
  }

This is what I've been doing but I can never reach the last block of code inside the equals method:

@Test
public void testEquals() throws Exception {

    assertFalse(serviceOrderRelationship.equals(null));
    assertTrue(serviceOrderRelationship.equals(serviceOrderRelationship));
    assertFalse(serviceOrderRelationship.equals(serviceOrderRelationship1));
}


问:
How to block a page from any content modifications in SharePoint
We have several pages in our Office 365 modern pages. Those contents are editable meaning any user can edit those pages. However, sometimes those pages need to be blocked from any content modification?

How to block a page from any content modifications in the Office 365 modern site? Should it be an admin feature or contributor feature?

Can we get this using OOTB SP (out of the box SharePoint)

答:
You should set page-item-level permissions to lock those pages down to certain users.

If you have a specific set of users that should always retain contribute rights on those pages, you should first create a SharePoint Group to hold those users.

Find the page in the sitepages library that you want to protect.

Click the vertical ellipses button to open the context menu and choose "Manage Access" (see screenshot)

In the right-hand pane that appears with permissions, click the "Advanced" link at the bottom.

On the Advanced Permissions page, click the "Stop Inheriting Permissions" button (see screenshot).

Now you can control the permissions on this page by removing the site-level Members group or other permissions and/or adding whatever individuals or groups should still have access.


问:
including a .c file in another .c file
This is part of a homework assignment. What we have to do is write a makefile to compile previous homework solutions. The solutions were provided by the professor, and they're what will be used to test our makefiles. One of the files has an #include "quicksort.c".

I know the usage of something like that is discouraged, but that doesn't really help me :)

What would be the best approach to getting the two files to compile (the file quicksortTest.c, which includes quicksort.c, and quicksort.c itself)?

What I currently have as part of my makefile is the following:

```<code>    quicksort: quicksort.c quicksortTest.c
               $(CC) quicksortTest.c quicksort.c -o quicksortTest
</code>```

Where quicksortTest.c has the #include "quicksort.c".

When I try it, I get several gcc compiler errors... ideas?

答:
Don't pass quicksort.c to gcc.  Since you are including the file you should not compile it seperately:

```<code>quicksort: quicksort.c quicksortTest.c
       $(CC) quicksortTest.c -o quicksortTest
</code>```

Title: including a .c file in another .c file

Body:
This is part of a homework assignment. What we have to do is write a makefile to compile previous homework solutions. The solutions were provided by the professor, and they're what will be used to test our makefiles. One of the files has an #include "quicksort.c".

I know the usage of something like that is discouraged, but that doesn't really help me :)

What would be the best approach to getting the two files to compile (the file quicksortTest.c, which includes quicksort.c, and quicksort.c itself)?

What I currently have as part of my makefile is the following:

    quicksort: quicksort.c quicksortTest.c
               $(CC) quicksortTest.c quicksort.c -o quicksortTest

Where quicksortTest.c has the #include "quicksort.c".

When I try it, I get several gcc compiler errors... ideas?

Body:
Don't pass quicksort.c to gcc.  Since you are including the file you should not compile it seperately:

quicksort: quicksort.c quicksortTest.c
       $(CC) quicksortTest.c -o quicksortTest


问:
Best way to split data of varying length into columns
I have some data that includes 4 columns. First column is a place and last three columns are numbers or ranges of numbers.

What is the best way to split this data into four columns?

```<code>Red Coast Van 240-250 240-250 285-365
Beanbelt 310-400 310-400 450-540
North Star 310-400 310-400 450-540
Hamilton Fines, TA 380-390 380-390 505-530
Western Beanbelt 310-400 310-400 450-525
Main, PA 370-380 370-380 505-525
Dust Dodge, NY 380-390 380-390 520-525
Midwest Bean Belt (Des) m 400-475 400-475 572-615
</code>```

Desired Output

```<code>Red Coast Van; 240-250; 240-250; 285-365
Beanbelt; 310-400; 310-400; 450-540
North Star; 310-400; 310-400; 450-540
Hamilton Fines, TA; 380-390; 380-390; 505-530
Western Beanbelt; 310-400; 310-400; 450-525
Main, PA; 370-380; 370-380; 505-525
Dust Dodge, NY; 380-390; 380-390; 520-525
Midwest Bean Belt (Des) m; 400-475; 400-475; 572-615
</code>```

答:
Since you tagged vim, here's a Vim solution:

```<code>:%s/ \(\d\+-\d\+\) \(\d\+-\d\+\) \(\d\+-\d\+\)$/; \1; \2; \3/
</code>```

which can be "prettified" with verymagic, or \v:

```<code>:%s/\v (\d+-\d+) (\d+-\d+) (\d+-\d+)$/; \1; \2; \3/
</code>```

Note that there's no need to match whatever the first column is made up of; you only need to match the last 3 columns and prepend ; to each.

The above solution does not make any assumption on how the first column is structured. If, instead, the first column is guaranteed not to contain a digit preceded by space, than an easier solution is possible (which is the slim version of another answer):

```<code>:%s/\ze \d/;/g
</code>```

Obviously, if any of your lines is of the form

```<code>Western 666 Beanbelt 310-400 310-400 450-525
</code>```

this last solution will break the first column in two.

Body:
I have some data that includes 4 columns. First column is a place and last three columns are numbers or ranges of numbers.

What is the best way to split this data into four columns?

Red Coast Van 240-250 240-250 285-365
Beanbelt 310-400 310-400 450-540
North Star 310-400 310-400 450-540
Hamilton Fines, TA 380-390 380-390 505-530
Western Beanbelt 310-400 310-400 450-525
Main, PA 370-380 370-380 505-525
Dust Dodge, NY 380-390 380-390 520-525
Midwest Bean Belt (Des) m 400-475 400-475 572-615

Desired Output

Red Coast Van; 240-250; 240-250; 285-365
Beanbelt; 310-400; 310-400; 450-540
North Star; 310-400; 310-400; 450-540
Hamilton Fines, TA; 380-390; 380-390; 505-530
Western Beanbelt; 310-400; 310-400; 450-525
Main, PA; 370-380; 370-380; 505-525
Dust Dodge, NY; 380-390; 380-390; 520-525
Midwest Bean Belt (Des) m; 400-475; 400-475; 572-615

Body:
Since you tagged vim, here's a Vim solution:

:%s/ \(\d\+-\d\+\) \(\d\+-\d\+\) \(\d\+-\d\+\)$/; \1; \2; \3/

which can be "prettified" with verymagic, or \v:

:%s/\v (\d+-\d+) (\d+-\d+) (\d+-\d+)$/; \1; \2; \3/

Note that there's no need to match whatever the first column is made up of; you only need to match the last 3 columns and prepend ; to each.

The above solution does not make any assumption on how the first column is structured. If, instead, the first column is guaranteed not to contain a digit preceded by space, than an easier solution is possible (which is the slim version of another answer):

:%s/\ze \d/;/g

Obviously, if any of your lines is of the form

Western 666 Beanbelt 310-400 310-400 450-525

this last solution will break the first column in two.


问:
Missing App configuration value: "projectId" even though I am passing it in
I am able to send, view and click on web notifications fine, and nothing appears wrong. However the console yields this when I click on a notification

```<code>Uncaught FirebaseError: Messaging: Missing App configuration value: "projectId" (messaging/missing-app-config-values).
</code>```

projectId is definitely being passed to the configuration

Chrome version: Version 79.0.3945.130 (Official Build) (64-bit)

here is how I am configuring firebase:

```<code>var messaging;
if( firebase.messaging.isSupported() ){

    var config = {
      apiKey: "*************",
      authDomain: "*************",
      databaseURL: "*************",
      projectId: "*************",
      storageBucket: "*************",
      messagingSenderId: "*************",
      appId: "*************"
    };
    firebase.initializeApp(config);
    messaging = firebase.messaging();
    messaging.usePublicVapidKey("*************");
    messaging.onMessage(function(payload) {
        ...
        ...
    }
}
</code>```

And my firebase-messeging-sw.js:

```<code>self.addEventListener('notificationclick', function(event) {
    ...
    ...
}
importScripts('https://www.gstatic.com/firebasejs/7.8.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.8.2/firebase-messaging.js');

firebase.initializeApp({'messagingSenderId': '***********'});

const messaging = firebase.messaging();

messaging.setBackgroundMessageHandler(function(payload) {
    ...
});
</code>```

Any ideas?

答: You have to call initializeApp() before calling any other Firebase APIs.  Your code is calling firebase.messaging.isSupported() first before initializeApp().  It looks like perhaps you only want to initialize Firebase if FCM is going to work, but that's simply not supported.  I suggest initializing Firebase unconditionally.  There is very little cost to doing so if you don't actually make use of any of the Firebase products.

Body:
I am able to send, view and click on web notifications fine, and nothing appears wrong. However the console yields this when I click on a notification

Uncaught FirebaseError: Messaging: Missing App configuration value: "projectId" (messaging/missing-app-config-values).

projectId is definitely being passed to the configuration

Chrome version: Version 79.0.3945.130 (Official Build) (64-bit)

here is how I am configuring firebase:

var messaging;
if( firebase.messaging.isSupported() ){

    var config = {
      apiKey: "*************",
      authDomain: "*************",
      databaseURL: "*************",
      projectId: "*************",
      storageBucket: "*************",
      messagingSenderId: "*************",
      appId: "*************"
    };
    firebase.initializeApp(config);
    messaging = firebase.messaging();
    messaging.usePublicVapidKey("*************");
    messaging.onMessage(function(payload) {
        ...
        ...
    }
}

And my firebase-messeging-sw.js:

self.addEventListener('notificationclick', function(event) {
    ...
    ...
}
importScripts('https://www.gstatic.com/firebasejs/7.8.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.8.2/firebase-messaging.js');

firebase.initializeApp({'messagingSenderId': '***********'});

const messaging = firebase.messaging();

messaging.setBackgroundMessageHandler(function(payload) {
    ...
});

Any ideas?


问:
Getting first 3 letters of first and last name
This is my first google app question.  I would appreciate any help.  I did try searching for similar questions, but because my knowledge is basic, it's hard to adapt an "almost the same" question... so please forgive me to asking my own.

If I take my name, Daniel Bonallack in cell A1, I want to convert that to BON_DAN and set that to a variable.

So,

First 3 letters of last name

First 3 letters of first name

underscore between them

all capitalized

I have this basic code:

```<code>  var vv = SpreadsheetApp.getActiveSheet().getActiveCell().getValue();

  var firstName = vv.substring(0, 3)
</code>```

Which gives me the first 3 letters of the active cell.  And that's as far as I got.  Can someone help?

Thanks!!

答:
Use String.replace and String.toUpperCase

const name = "Daniel Bonallack";
const abb = name.replace(/(\w{1,3})\w*\s+(\w{1,3})\w*/,"$2_$1").toUpperCase();
console.log(abb)```

\w:  letter(word)

\s:  space

Body:
This is my first google app question.  I would appreciate any help.  I did try searching for similar questions, but because my knowledge is basic, it's hard to adapt an "almost the same" question... so please forgive me to asking my own.

If I take my name, Daniel Bonallack in cell A1, I want to convert that to BON_DAN and set that to a variable.

So,

First 3 letters of last name

First 3 letters of first name

underscore between them

all capitalized

I have this basic code:

  var vv = SpreadsheetApp.getActiveSheet().getActiveCell().getValue();

  var firstName = vv.substring(0, 3)

Which gives me the first 3 letters of the active cell.  And that's as far as I got.  Can someone help?

Thanks!!

Body:
Use String.replace and String.toUpperCase

const name = "Daniel Bonallack";
const abb = name.replace(/(\w{1,3})\w*\s+(\w{1,3})\w*/,"$2_$1").toUpperCase();
console.log(abb)

\w:  letter(word)

\s:  space


问:
How to format as Text using Text-To-Columns
This code works using text to columns to separate column A into as many columns as I need, but I cannot figure out a way to make it do this with all columns outputted into text format.

```<code>Sub TxT_to_Columns()
    ActiveWorkbook.ActiveSheet.Range("A:A").TextToColumns _
    Destination:=Range("A1"), _
    DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, _
    ConsecutiveDelimiter:=False, _
    Tab:=False, _
    Semicolon:=False, _
    Comma:=False, _
    Space:=False, _
    Other:=True, _
    OtherChar:="|"
End Sub
</code>```

How can I do the same thing but output all columns to text format?

Thank you,

答:
You use FieldInfo:

```<code>FieldInfo:=Array(Array(1, 2), Array(2, 2), Array(3, 2)),
</code>```

FieldInfo uses an array of arrays: Array(Array(Column,Type),...)

You can get the types from here:

https://learn.microsoft.com/en-us/office/vba/api/excel.xlcolumndatatype

If you know you want to do all the columns then you can pre fill an variant arr variable:

```<code>Sub TxT_to_Columns()
    Dim arr(1 To 10) As Variant

    arr(1) = Array(1, 2)
    arr(2) = Array(2, 2)
    arr(3) = Array(3, 2)
    arr(4) = Array(4, 2)
    arr(5) = Array(5, 2)
    arr(6) = Array(6, 2)
    arr(7) = Array(7, 2)
    arr(8) = Array(8, 2)
    arr(9) = Array(9, 2)
    arr(10) = Array(10, 2)

    ActiveWorkbook.ActiveSheet.Range("A:A").TextToColumns _
        Destination:=ActiveWorkbook.ActiveSheet.Range("A1"), _
        DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, _
        ConsecutiveDelimiter:=False, _
        Tab:=True, _
        Semicolon:=False, _
        Comma:=False, _
        Space:=False, _
        Other:=True, _
        OtherChar:="|", _
        FieldInfo:=arr
End Sub
</code>```

Body:
This code works using text to columns to separate column A into as many columns as I need, but I cannot figure out a way to make it do this with all columns outputted into text format.

Sub TxT_to_Columns()
    ActiveWorkbook.ActiveSheet.Range("A:A").TextToColumns _
    Destination:=Range("A1"), _
    DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, _
    ConsecutiveDelimiter:=False, _
    Tab:=False, _
    Semicolon:=False, _
    Comma:=False, _
    Space:=False, _
    Other:=True, _
    OtherChar:="|"
End Sub

How can I do the same thing but output all columns to text format?

Thank you,

Body:
You use FieldInfo:

FieldInfo:=Array(Array(1, 2), Array(2, 2), Array(3, 2)),

FieldInfo uses an array of arrays: Array(Array(Column,Type),...)

You can get the types from here:

https://learn.microsoft.com/en-us/office/vba/api/excel.xlcolumndatatype

If you know you want to do all the columns then you can pre fill an variant arr variable:

Sub TxT_to_Columns()
    Dim arr(1 To 10) As Variant

    arr(1) = Array(1, 2)
    arr(2) = Array(2, 2)
    arr(3) = Array(3, 2)
    arr(4) = Array(4, 2)
    arr(5) = Array(5, 2)
    arr(6) = Array(6, 2)
    arr(7) = Array(7, 2)
    arr(8) = Array(8, 2)
    arr(9) = Array(9, 2)
    arr(10) = Array(10, 2)

    ActiveWorkbook.ActiveSheet.Range("A:A").TextToColumns _
        Destination:=ActiveWorkbook.ActiveSheet.Range("A1"), _
        DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, _
        ConsecutiveDelimiter:=False, _
        Tab:=True, _
        Semicolon:=False, _
        Comma:=False, _
        Space:=False, _
        Other:=True, _
        OtherChar:="|", _
        FieldInfo:=arr
End Sub


问:
What picture size to use in Android layouts
I have an ImageView in Android with a foto in it. That view should always have the same proportions no matter which device it is displayed on. In my example the width of the ImageView is 427 dp and the height is 250 dp. I choose this special width to make the picture cover the whole width of the layout in Android studio. Now my question is, how should I modify the raw pictures taken from my camera (or whatever device/tool) such that it fits to the desired proportions? I mean, the raw picture does not have the desired proportions. This is why I extracted an ereas out of the picture with the desired proportions. I could specify the pixels for that in the tool I use (IrfanView). The proportions shoudld be multiples of 427 and 250, meaning that the following options are possible (427, 250) (2 * 427,2 *  250) (3 * 427, 3 *  250) etc. Now I do not know what size to choose. The ImageView might need different proportions depending on the device it is displayed on. Does someone have a good advice how to do that. Here you see a screenshot of the ImageView

Update: As nobody has answered so far, I would like to ask you again, how I should decide about the size of pictures in Android given that the app would run on different devices with different screen sizes. What is your way of deciding about that?

I'd be happy for every comment

Update 2: Can nobody help me with that? This should be a common problem. I mean you create an app for different devices and you need a picture for that app. What size should the picture have.

Why does nobody answer? Is the question itself unclear? If so please tell me.

答:
try this i think you need two define two dimen files. one for normal phone and one for tablet. One size define in all dimen files. if you load in mobile normal fonts which you define for mobile will be load, if tab then tab font size.

How to define dimens.xml for every different screen size in android?


问:
CONCAT columns with Laravel 5 eloquent
Consider me as laravel beginner

The goal is: I have two colums, now I need the id to be prefixed with the component name of same row in the table.

For Example (Working)... I have Mysql like

```<code>SELECT CONCAT(components.name," ", components.id) AS ID
FROM   `components`
</code>```

And output is

ID

```<code>|TestComp 40  |
 -------------
|component 41 |
 -------------
|test 42      |
</code>```

I need the same in laravel eloquent way, as here Component is Model name. So i tried something like

```<code>$comp=Component::select("CONCAT('name','id') AS ID")->get()
</code>```

but it doesn't work.

I think because the  syntax is wrong.

Kindly help me with the correct syntax. Using laravel Models.

Note: I made the above query, referring this as which available on internet.

```<code>User::select(DB::raw('CONCAT(last_name, first_name) AS full_name'))
</code>```

答:
Scrubbing the Data: Before using Laravel and now, when developing in other languages, I would use CONCAT() on a regular basis.  The answers here work to a degree but there still isn't an elegant way to use CONCAT() in Laravel/Eloquent/Query Builder
 that I have found.

However, I have found that concatenating the cols AFTER returning the results works well for me and is usually very fast - Scrubbing the data - ( unless you have a huge result which should probably be "chunked" anyway for performance purposes ).

```<code>foreach($resultsArray AS $row){
    $row['fullname'] = trim($row['firstname']).' '.trim($row['lastname']);
}
</code>```

This is a tradeoff of course but, personally, I find it to be much more manageable and doesn't limit my use of Eloquent as intended as well as the Query Builder. ( the above is pseudo code - not tested so tweak as needed )

There are other workarounds as well that don't mess with Eloquent/Query Builder functionality such as creating a concatenated col in the table, in this case full_name - save the full name when the record is inserted/updated. This is not uncommon.

Title: CONCAT columns with Laravel 5 eloquent

Body:
Consider me as laravel beginner

The goal is: I have two colums, now I need the id to be prefixed with the component name of same row in the table.

For Example (Working)... I have Mysql like

SELECT CONCAT(components.name," ", components.id) AS ID
FROM   `components`

And output is

ID

|TestComp 40  |
 -------------
|component 41 |
 -------------
|test 42      |

I need the same in laravel eloquent way, as here Component is Model name. So i tried something like

$comp=Component::select("CONCAT('name','id') AS ID")->get()

but it doesn't work.

I think because the  syntax is wrong.

Kindly help me with the correct syntax. Using laravel Models.

Note: I made the above query, referring this as which available on internet.

User::select(DB::raw('CONCAT(last_name, first_name) AS full_name'))

Body:
Scrubbing the Data: Before using Laravel and now, when developing in other languages, I would use CONCAT() on a regular basis.  The answers here work to a degree but there still isn't an elegant way to use CONCAT() in Laravel/Eloquent/Query Builder
 that I have found.

However, I have found that concatenating the cols AFTER returning the results works well for me and is usually very fast - Scrubbing the data - ( unless you have a huge result which should probably be "chunked" anyway for performance purposes ).

foreach($resultsArray AS $row){
    $row['fullname'] = trim($row['firstname']).' '.trim($row['lastname']);
}

This is a tradeoff of course but, personally, I find it to be much more manageable and doesn't limit my use of Eloquent as intended as well as the Query Builder. ( the above is pseudo code - not tested so tweak as needed )

There are other workarounds as well that don't mess with Eloquent/Query Builder functionality such as creating a concatenated col in the table, in this case full_name - save the full name when the record is inserted/updated. This is not uncommon.


问:
How to override Chrome new tab content with a react component
I am trying to create a React application/Chrome extension which overrides the content of a new tab in Google Chrome. I have used create-react-app and am simply trying to override the content of a new tab with App.js content. The folder structure is straight from the initial create-react-app, which is below.

```<code>    build
    node_modules
    Public
      favicon.ico
      index.html
      logo192.png
      logo512.png
      manifest.json
    src
      App.css
      App.js
      app.test.js
      index.css
      index.js
      logo.svg
    ..
    ..
</code>```

My manifest.json file looks like this.

```<code>    {
      "name": "..",
      "author": "..",
      "version": "1.0.1",
      "manifest_version": 2,
      "description": "..",
      "chrome_url_overrides": {
        "newtab": "index.html"
      }
    }
</code>```

This is what my index.html looks like.

<!DOCTYPE html>

    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />

    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

    <title>React App</title>

    You need to enable JavaScript to run this app.

```

<p>My <code>index.js</code> file looks like this.</p>

<pre class="lang-js prettyprint-override"><code>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

serviceWorker.unregister();
</code>```

I have tried inserting the following but receive an empty page.

```

How would I override the content of a new tab with App.js?

答:
Originally I modified my manifest.json file to the following.

```<code>{
  "name": "..",
  "author": "..",
  "version": "1.0.1",
  "manifest_version": 2,
  "description": "..",
  "chrome_url_overrides": {
    "newtab": "index.html"
  },
  "content_security_policy": "script-src 'self' 'YOUR HASH'; object-src 'self'"
}
</code>```

The YOUR HASH can be found from the console, as highlighted below

However, I went for an alternative approach. I created a .env file in the root directory and placed the following inside of it

```<code>INLINE_RUNTIME_CHUNK=false
</code>```

Body:
I am trying to create a React application/Chrome extension which overrides the content of a new tab in Google Chrome. I have used create-react-app and am simply trying to override the content of a new tab with App.js content. The folder structure is straight from the initial create-react-app, which is below.

    build
    node_modules
    Public
      favicon.ico
      index.html
      logo192.png
      logo512.png
      manifest.json
    src
      App.css
      App.js
      app.test.js
      index.css
      index.js
      logo.svg
    ..
    ..

My manifest.json file looks like this.

    {
      "name": "..",
      "author": "..",
      "version": "1.0.1",
      "manifest_version": 2,
      "description": "..",
      "chrome_url_overrides": {
        "newtab": "index.html"
      }
    }

This is what my index.html looks like.

<!DOCTYPE html>

    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />

    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

    <title>React App</title>

    You need to enable JavaScript to run this app.

My index.js file looks like this.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

serviceWorker.unregister();

I have tried inserting the following but receive an empty page.

How would I override the content of a new tab with App.js?

Body:
Originally I modified my manifest.json file to the following.

{
  "name": "..",
  "author": "..",
  "version": "1.0.1",
  "manifest_version": 2,
  "description": "..",
  "chrome_url_overrides": {
    "newtab": "index.html"
  },
  "content_security_policy": "script-src 'self' 'YOUR HASH'; object-src 'self'"
}

The YOUR HASH can be found from the console, as highlighted below

However, I went for an alternative approach. I created a .env file in the root directory and placed the following inside of it

INLINE_RUNTIME_CHUNK=false


问:
How can I show a loading image before the MVC call has returned the model?
I have an HTML button in the file generateReport.cshtml, that opens a new tab to display the report:

```<code><div>
   <a id="btnPreviewPDF" class="btn" href="#" title="Preview Report" target="_blank">Preview</a>
</div>
</code>```

This kicks off an MVC GET in reportController.cs that creates the model to be used by the html that renders the report:

```<code>[GET("PreviewPdf/{id:int}/{reportDate}")]
        public virtual ActionResult PreviewReport(int id, string reportDate)
        {
            var helper = new ReportHelper(client);
            var model = helper.GenerateViewModelForPreviewReport(id, reportDate);

            return View(model);
        }
</code>```

Then the above model is used in viewReport.cshtml as a model to display the data, for example:

```<code>@model Reports.ReportHelper

<div class="sub-header-text primary-orange text-bold">
   Summary: @Model.ReportDate.ToString("MMMM") @Model.ReportDate.ToString("yyyy")
</div>
</code>```

Waiting for the PreviewReport to return in the GET of reportController.cs can take 30+ seconds to run so I would like to display a loading image/gif on the new tab that's created by clicking the 'Preview' button. Since this GET command is running before the HTML code in viewReport.cshtml I have not been able to figure out a way to do this. I would like to display a loading image on that new tab and prevent the browser from throwing a message thinking that the page is not responding.

答:
In the first response return loading string/image + a script which send an ajax request to load the report, then in response to the ajax request, return the report content.

This way the page will be shown immediately and in the contents, shows a loading, then after a few seconds when the ajax request received the response, the page content will be updated.

Controller

In the controller, check if it's ajax request, return the partial view which contains the report. Otherwise, return the view which just contains loading and the ajax script:

```<code>public ActionResult Report()
{
    if (Request.IsAjaxRequest())
    {
        //Delay just for demo purpose
        System.Threading.Thread.Sleep(5000);
        return PartialView("_Report");
    }
    else
        return View("Report");
}
</code>```

Report.cshtml

Use this view just to show loading and send the ajax request:

```<code>@{ ViewBag.Title = "Report"; }

<div id="content">
    Loading ...
</div>

@section Scripts
{
    <script>
        $(function () {
            $.ajax({
                url: "/Home/Report",
                success: function (data) { $('#content').html(data); },
                error: function () { alert(error); },
                cache: false,
                type: 'GET'
            });
        });
    </script>
}
</code>```

_Report.cshtml

Use this partial view to shows actual report content:

```<code>Actual report content
</code>```

Body:
I have an HTML button in the file generateReport.cshtml, that opens a new tab to display the report:

   Preview

This kicks off an MVC GET in reportController.cs that creates the model to be used by the html that renders the report:

[GET("PreviewPdf/{id:int}/{reportDate}")]
        public virtual ActionResult PreviewReport(int id, string reportDate)
        {
            var helper = new ReportHelper(client);
            var model = helper.GenerateViewModelForPreviewReport(id, reportDate);

            return View(model);
        }

Then the above model is used in viewReport.cshtml as a model to display the data, for example:

@model Reports.ReportHelper

   Summary: @Model.ReportDate.ToString("MMMM") @Model.ReportDate.ToString("yyyy")

Waiting for the PreviewReport to return in the GET of reportController.cs can take 30+ seconds to run so I would like to display a loading image/gif on the new tab that's created by clicking the 'Preview' button. Since this GET command is running before the HTML code in viewReport.cshtml I have not been able to figure out a way to do this. I would like to display a loading image on that new tab and prevent the browser from throwing a message thinking that the page is not responding.

Body:
In the first response return loading string/image + a script which send an ajax request to load the report, then in response to the ajax request, return the report content.

This way the page will be shown immediately and in the contents, shows a loading, then after a few seconds when the ajax request received the response, the page content will be updated.

Controller

In the controller, check if it's ajax request, return the partial view which contains the report. Otherwise, return the view which just contains loading and the ajax script:

public ActionResult Report()
{
    if (Request.IsAjaxRequest())
    {
        //Delay just for demo purpose
        System.Threading.Thread.Sleep(5000);
        return PartialView("_Report");
    }
    else
        return View("Report");
}

Report.cshtml

Use this view just to show loading and send the ajax request:

@{ ViewBag.Title = "Report"; }

<div id="content">
    Loading ...
</div>

@section Scripts
{
    <script>
        $(function () {
            $.ajax({
                url: "/Home/Report",
                success: function (data) { $('#content').html(data); },
                error: function () { alert(error); },
                cache: false,
                type: 'GET'
            });
        });
    </script>
}

_Report.cshtml

Use this partial view to shows actual report content:

Actual report content