问:
Emailing Google Sheet as PDF
I have this script that emails me a PDF of the Google Spreadsheet. I only want it to email me the first 'Tab' and if possible as a single PDF vice a zip file.

Wondered if anyone could help. Also one of the 'Tabs' are hidden, so I don't know if that has an impact.  He is a link to the sample sheet.

The code is shown below:

```<code>/* Send Spreadsheet in an email as PDF, automatically */
function emailSpreadsheetAsPDF() {

// Send the PDF of the spreadsheet to this email address
  var email = "xxxxx@gmail.com";

  // Get the currently active spreadsheet URL (link)
  // Or use SpreadsheetApp.openByUrl("<<SPREADSHEET URL>>");
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  // Subject of email message
  var subject = "Sample Sheet " + ss.getName();

  // Email Body can  be HTML too with your logo image - see ctrlq.org/html-mail
  var body = "Install the <a href='http://www.labnol.org/email-sheet'>Email Spreadsheet add-on</a> for one-click conversion.";

  // Base URL
  var url = "https://docs.google.com/spreadsheets/d/SS_ID/export?".replace("SS_ID", ss.getId());

  /* Specify PDF export parameters
  From: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579
  */

  var url_ext = 'exportFormat=pdf&format=pdf'        // export as pdf / csv / xls / xlsx
  + '&size=letter'                       // paper size legal / letter / A4
  + '&portrait=false'                    // orientation, false for landscape
  + '&fitw=true&source=labnol'           // fit to page width, false for actual size
  + '&sheetnames=false&printtitle=false' // hide optional headers and footers
  + '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
  + '&fzr=false'                         // do not repeat row headers (frozen rows) on each page
  + '&gid=';                             // the sheet's Id

  var token = ScriptApp.getOAuthToken();
  var sheets = ss.getSheets();

  //make an empty array to hold your fetched blobs
  var blobs = [];

  for (var i=0; i<sheets.length; i++) {

    // Convert individual worksheets to PDF
    var response = UrlFetchApp.fetch(url + url_ext + sheets[i].getSheetId(), {
      headers: {
        'Authorization': 'Bearer ' +  token
      }
    });

    //convert the response to a blob and store in our array
    blobs[i] = response.getBlob().setName(sheets[i].getName() + '.pdf');

  }

  //create new blob that is a zip file containing our blob array
  var zipBlob = Utilities.zip(blobs).setName(ss.getName() + '.zip');

  //optional: save the file to the root folder of Google Drive
  DriveApp.createFile(zipBlob);

  // Define the scope
  Logger.log("Storage Space used: " + DriveApp.getStorageUsed());

  // If allowed to send emails, send the email with the PDF attachment
  if (MailApp.getRemainingDailyQuota() > 0)
    GmailApp.sendEmail(email, subject, body, {
      htmlBody: body,
      attachments:[zipBlob]
    });
}

//**************************************************************************
//                                 Revised Code
//**************************************************************************

/* Send Spreadsheet in an email as PDF, automatically */
function emailSpreadsheetAsPDF() {

// Send the PDF of the spreadsheet to this email address
  var email = "xxxxx@gmail.com";

  // Get the currently active spreadsheet URL (link)
  // Or use SpreadsheetApp.openByUrl("<<SPREADSHEET URL>>");
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  // Subject of email message
  var subject = "PDF generated from spreadsheet " + ss.getName();

  // Email Body can  be HTML too with your logo image - see ctrlq.org/html-mail
  var body = "Install the <a href='http://www.labnol.org/email-sheet'>Email Spreadsheet add-on</a> for one-click conversion.";

  // Base URL
  var url = "https://docs.google.com/spreadsheets/d/SS_ID/export?".replace("SS_ID", ss.getId());

  /* Specify PDF export parameters
  From: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579
  */

  var url_ext = 'exportFormat=pdf&format=pdf'        // export as pdf / csv / xls / xlsx
  + '&size=letter'                       // paper size legal / letter / A4
  + '&portrait=false'                    // orientation, false for landscape
  + '&fitw=true&source=labnol'           // fit to page width, false for actual size
  + '&sheetnames=false&printtitle=false' // hide optional headers and footers
  + '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
  + '&fzr=false'                         // do not repeat row headers (frozen rows) on each page
  + '&gid=';                             // the sheet's Id

  var token = ScriptApp.getOAuthToken();
  var sheets = ss.getSheets();

  //make an empty array to hold your fetched blobs
  var blobs = [];

  //for (var i=0; i<sheets.length; i++) {
  for (var i=0; i<1; i++) {
    // Convert individual worksheets to PDF
    var response = UrlFetchApp.fetch(url + url_ext + sheets[i].getSheetId(), {
      headers: {
        'Authorization': 'Bearer ' +  token
      }
    });

    //convert the response to a blob and store in our array
   // blobs[i] = response.getBlob().setName(sheets[i].getName() + '.pdf');

  }

  //create new blob that is a zip file containing our blob array
 // var zipBlob = Utilities.zip(blobs).setName(ss.getName() + '.zip');

  //optional: save the file to the root folder of Google Drive
  //DriveApp.createFile(zipBlob);

  // Define the scope
  Logger.log("Storage Space used: " + DriveApp.getStorageUsed());

  // If allowed to send emails, send the email with the PDF attachment
  if (MailApp.getRemainingDailyQuota() > 0)
    GmailApp.sendEmail(email, subject, body, {
      htmlBody: body,
      //attachments:[zipBlob]
    });
}
</code>```

Kind Regards
Al

答:
In your code, you are getting both sheets as blobs and zipping them??

The easiest fix it is to change for (var i=0; i<sheets.length; i++) { to for (var i=0; i<1; i++) { so it only gets the first tab and zips it.

UPDATE Based on comments.

```<code>function emailSpreadsheetAsPDF() {

    var email = ""; // Enter the required email address here

    var ss = SpreadsheetApp.getActiveSpreadsheet();

    var sheet = ss.getSheetByName("**********"); // Enter the name of the sheet here

    var subject = "PDF generated from spreadsheet " + ss.getName();

    var body = "\n Attached is a PDF copy of the sheet " + sheet.getName() + " in the " + ss.getName() + " spreadsheet.";

    // Base URL
    var url = "https://docs.google.com/spreadsheets/d/SS_ID/export?".replace("SS_ID", ss.getId());

    /* Specify PDF export parameters
    From: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579
     */

    var url_ext = 'exportFormat=pdf&format=pdf' // export as pdf / csv / xls / xlsx
         + '&size=letter' // paper size legal / letter / A4
         + '&portrait=false' // orientation, false for landscape
         + '&fitw=true&source=labnol' // fit to page width, false for actual size
         + '&sheetnames=false&printtitle=false' // hide optional headers and footers
         + '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
         + '&fzr=false' // do not repeat row headers (frozen rows) on each page
         + '&gid='; // the sheet's Id

    var token = ScriptApp.getOAuthToken();

    var response = UrlFetchApp.fetch(url + url_ext + sheet.getSheetId(), {
            headers : {
                'Authorization' : 'Bearer ' + token
            }
        }).getBlob().setName(sheet.getName() + ".pdf");

    // Uncomment the line below to save the PDF to the root of your drive.
    //  var newFile = DriveApp.createFile(response).setName(sheet.getName() + ".pdf")

    if (MailApp.getRemainingDailyQuota() > 0)
        GmailApp.sendEmail(email, subject, body, {
            htmlBody : body,
            attachments : [response]
        });
}
</code>```

Title: Emailing Google Sheet as PDF

Body:
I have this script that emails me a PDF of the Google Spreadsheet. I only want it to email me the first 'Tab' and if possible as a single PDF vice a zip file.

Wondered if anyone could help. Also one of the 'Tabs' are hidden, so I don't know if that has an impact.  He is a link to the sample sheet.

The code is shown below:

/* Send Spreadsheet in an email as PDF, automatically */
function emailSpreadsheetAsPDF() {

// Send the PDF of the spreadsheet to this email address
  var email = "xxxxx@gmail.com";

  // Get the currently active spreadsheet URL (link)
  // Or use SpreadsheetApp.openByUrl("<<SPREADSHEET URL>>");
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  // Subject of email message
  var subject = "Sample Sheet " + ss.getName();

  // Email Body can  be HTML too with your logo image - see ctrlq.org/html-mail
  var body = "Install the Email Spreadsheet add-on for one-click conversion.";

  // Base URL
  var url = "https://docs.google.com/spreadsheets/d/SS_ID/export?".replace("SS_ID", ss.getId());

  /* Specify PDF export parameters
  From: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579
  */

  var url_ext = 'exportFormat=pdf&format=pdf'        // export as pdf / csv / xls / xlsx
  + '&size=letter'                       // paper size legal / letter / A4
  + '&portrait=false'                    // orientation, false for landscape
  + '&fitw=true&source=labnol'           // fit to page width, false for actual size
  + '&sheetnames=false&printtitle=false' // hide optional headers and footers
  + '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
  + '&fzr=false'                         // do not repeat row headers (frozen rows) on each page
  + '&gid=';                             // the sheet's Id

  var token = ScriptApp.getOAuthToken();
  var sheets = ss.getSheets();

  //make an empty array to hold your fetched blobs
  var blobs = [];

  for (var i=0; i<sheets.length; i++) {

    // Convert individual worksheets to PDF
    var response = UrlFetchApp.fetch(url + url_ext + sheets[i].getSheetId(), {
      headers: {
        'Authorization': 'Bearer ' +  token
      }
    });

    //convert the response to a blob and store in our array
    blobs[i] = response.getBlob().setName(sheets[i].getName() + '.pdf');

  }

  //create new blob that is a zip file containing our blob array
  var zipBlob = Utilities.zip(blobs).setName(ss.getName() + '.zip');

  //optional: save the file to the root folder of Google Drive
  DriveApp.createFile(zipBlob);

  // Define the scope
  Logger.log("Storage Space used: " + DriveApp.getStorageUsed());

  // If allowed to send emails, send the email with the PDF attachment
  if (MailApp.getRemainingDailyQuota() > 0)
    GmailApp.sendEmail(email, subject, body, {
      htmlBody: body,
      attachments:[zipBlob]
    });
}

//**************************************************************************
//                                 Revised Code
//**************************************************************************

/* Send Spreadsheet in an email as PDF, automatically */
function emailSpreadsheetAsPDF() {

// Send the PDF of the spreadsheet to this email address
  var email = "xxxxx@gmail.com";

  // Get the currently active spreadsheet URL (link)
  // Or use SpreadsheetApp.openByUrl("<<SPREADSHEET URL>>");
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  // Subject of email message
  var subject = "PDF generated from spreadsheet " + ss.getName();

  // Email Body can  be HTML too with your logo image - see ctrlq.org/html-mail
  var body = "Install the Email Spreadsheet add-on for one-click conversion.";

  // Base URL
  var url = "https://docs.google.com/spreadsheets/d/SS_ID/export?".replace("SS_ID", ss.getId());

  /* Specify PDF export parameters
  From: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579
  */

  var url_ext = 'exportFormat=pdf&format=pdf'        // export as pdf / csv / xls / xlsx
  + '&size=letter'                       // paper size legal / letter / A4
  + '&portrait=false'                    // orientation, false for landscape
  + '&fitw=true&source=labnol'           // fit to page width, false for actual size
  + '&sheetnames=false&printtitle=false' // hide optional headers and footers
  + '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
  + '&fzr=false'                         // do not repeat row headers (frozen rows) on each page
  + '&gid=';                             // the sheet's Id

  var token = ScriptApp.getOAuthToken();
  var sheets = ss.getSheets();

  //make an empty array to hold your fetched blobs
  var blobs = [];

  //for (var i=0; i<sheets.length; i++) {
  for (var i=0; i<1; i++) {
    // Convert individual worksheets to PDF
    var response = UrlFetchApp.fetch(url + url_ext + sheets[i].getSheetId(), {
      headers: {
        'Authorization': 'Bearer ' +  token
      }
    });

    //convert the response to a blob and store in our array
   // blobs[i] = response.getBlob().setName(sheets[i].getName() + '.pdf');

  }

  //create new blob that is a zip file containing our blob array
 // var zipBlob = Utilities.zip(blobs).setName(ss.getName() + '.zip');

  //optional: save the file to the root folder of Google Drive
  //DriveApp.createFile(zipBlob);

  // Define the scope
  Logger.log("Storage Space used: " + DriveApp.getStorageUsed());

  // If allowed to send emails, send the email with the PDF attachment
  if (MailApp.getRemainingDailyQuota() > 0)
    GmailApp.sendEmail(email, subject, body, {
      htmlBody: body,
      //attachments:[zipBlob]
    });
}

Kind Regards
Al

Body:
In your code, you are getting both sheets as blobs and zipping them??

The easiest fix it is to change for (var i=0; i<sheets.length; i++) { to for (var i=0; i<1; i++) { so it only gets the first tab and zips it.

UPDATE Based on comments.

function emailSpreadsheetAsPDF() {

    var email = ""; // Enter the required email address here

    var ss = SpreadsheetApp.getActiveSpreadsheet();

    var sheet = ss.getSheetByName("**********"); // Enter the name of the sheet here

    var subject = "PDF generated from spreadsheet " + ss.getName();

    var body = "\n Attached is a PDF copy of the sheet " + sheet.getName() + " in the " + ss.getName() + " spreadsheet.";

    // Base URL
    var url = "https://docs.google.com/spreadsheets/d/SS_ID/export?".replace("SS_ID", ss.getId());

    /* Specify PDF export parameters
    From: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579
     */

    var url_ext = 'exportFormat=pdf&format=pdf' // export as pdf / csv / xls / xlsx
         + '&size=letter' // paper size legal / letter / A4
         + '&portrait=false' // orientation, false for landscape
         + '&fitw=true&source=labnol' // fit to page width, false for actual size
         + '&sheetnames=false&printtitle=false' // hide optional headers and footers
         + '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
         + '&fzr=false' // do not repeat row headers (frozen rows) on each page
         + '&gid='; // the sheet's Id

    var token = ScriptApp.getOAuthToken();

    var response = UrlFetchApp.fetch(url + url_ext + sheet.getSheetId(), {
            headers : {
                'Authorization' : 'Bearer ' + token
            }
        }).getBlob().setName(sheet.getName() + ".pdf");

    // Uncomment the line below to save the PDF to the root of your drive.
    //  var newFile = DriveApp.createFile(response).setName(sheet.getName() + ".pdf")

    if (MailApp.getRemainingDailyQuota() > 0)
        GmailApp.sendEmail(email, subject, body, {
            htmlBody : body,
            attachments : [response]
        });
}


来源: stackexchange

问:
Check if user is close to scrolling to bottom of element
My website has a Bootstrap modal. My end goal is to add infinite scrolling to the modal so that when the user scrolls down to the bottom of the modal, it loads more data from the server and appends the data to the modal.

Here is my code so far. All I have right now is a scroll event on the modal:

http://jsfiddle.net/DTcHh/33247/

Note: The height of the modal on my website can vary. Sometimes it can be just 1 paragraph of text.

My question is, how can I check if the user is close to scrolling to the bottom of the modal?

In more technical terms, how can I check if the bottom of the window is at the same position as the bottom of the modal?

Update

I found that this solution works, however, it seems a bit complicated/long. Any way to shorten it?

http://jsfiddle.net/DTcHh/33271/

HTML:

```<code><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalLong">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModalLong" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
        <p>Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.</p>
        <p>Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.</p>
        <p>Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
</code>```

JS:

```<code>$("#exampleModalLong").on("scroll", function() {
    console.log("scroll");
});
</code>```

答:
```<code>$(document).ready(function(){
    $('#exampleModalLong').on("scroll", function() {
    if(($('#exampleModalLong').hasClass('in') && !$('body').hasClass('scrl'))&&($(window).scrollTop() + $(window).height() > $('.modal-footer > button').offset().top)){
      $('body').addClass('scrl');
      setTimeout(function(){
        alert('foo');
        $('body').removeClass('scrl');
      }, 900);
    }

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

See

ContentLicense: CC BY-SA 3.0

Body:
My website has a Bootstrap modal. My end goal is to add infinite scrolling to the modal so that when the user scrolls down to the bottom of the modal, it loads more data from the server and appends the data to the modal.

Here is my code so far. All I have right now is a scroll event on the modal:

http://jsfiddle.net/DTcHh/33247/

Note: The height of the modal on my website can vary. Sometimes it can be just 1 paragraph of text.

My question is, how can I check if the user is close to scrolling to the bottom of the modal?

In more technical terms, how can I check if the bottom of the window is at the same position as the bottom of the modal?

Update

I found that this solution works, however, it seems a bit complicated/long. Any way to shorten it?

http://jsfiddle.net/DTcHh/33271/

HTML:

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalLong">
  Launch demo modal
</button>

Modal title

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.

Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla.

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

JS:

$("#exampleModalLong").on("scroll", function() {
    console.log("scroll");
});

Body:
$(document).ready(function(){
    $('#exampleModalLong').on("scroll", function() {
    if(($('#exampleModalLong').hasClass('in') && !$('body').hasClass('scrl'))&&($(window).scrollTop() + $(window).height() > $('.modal-footer > button').offset().top)){
      $('body').addClass('scrl');
      setTimeout(function(){
        alert('foo');
        $('body').removeClass('scrl');
      }, 900);
    }

  });
});

See


问:
JavaScript doesn't recognize Turkish characters
I have this code :

```<code>if (term.length > 0) {
  var inputVal = $("#input").val();
  if (inputVal.indexOf("jason") !== -1) {
    results = $.ui.autocomplete.filter(table, term);
  }
}
</code>```

This works. But when I changed "jason" to "jasön" or "jasün" or something else which is a Turkish character, it doesn't work. Is it because the encoding of the js file? I changed the encoding to Unicode (utf-8 with signature) - Codepage 65001 then Turkish ISO 28599 but it didn't work. Can you tell me what I should do? Thanks.

答:
It does recognize Turkish characters, but you are doing an equality check on said string. What you have to understand is that even if ö is only an o with an accent, it's still a different character, thus making your conditional falsy, even if you are not doing a triple equality check.

```<code>'ö' == 'o'  // false
'ö' === 'o' // false
</code>```

What you should do instead is convert the input value into a string without accents, since it's apparently what you were expecting. And this question is exactly what you are looking for, and I would say this answer would be the best one if you have access to ES6 features since it's pretty clean and simple to use

```<code>function convert (str) {
  return str.normalize('NFD').replace(/[\u0300-\u036f]/g, '')
}

if (term.length > 0) {
  var inputVal = convert($('#input').val())
  if (inputVal.indexOf('jason') !== -1) {
    results = $.ui.autocomplete.filter(table, term)
  }
}
</code>```

Otherwise if ES6 is not an option, the top answer should be fine to use, just create a function util that you can reuse anywhere you need to.

Regarding the encoding of the file, you should use utf-8 if dealing with special chars that Turkish does have.

Body:
I have this code :

if (term.length > 0) {
  var inputVal = $("#input").val();
  if (inputVal.indexOf("jason") !== -1) {
    results = $.ui.autocomplete.filter(table, term);
  }
}

This works. But when I changed "jason" to "jasön" or "jasün" or something else which is a Turkish character, it doesn't work. Is it because the encoding of the js file? I changed the encoding to Unicode (utf-8 with signature) - Codepage 65001 then Turkish ISO 28599 but it didn't work. Can you tell me what I should do? Thanks.

Body:
It does recognize Turkish characters, but you are doing an equality check on said string. What you have to understand is that even if ö is only an o with an accent, it's still a different character, thus making your conditional falsy, even if you are not doing a triple equality check.

'ö' == 'o'  // false
'ö' === 'o' // false

What you should do instead is convert the input value into a string without accents, since it's apparently what you were expecting. And this question is exactly what you are looking for, and I would say this answer would be the best one if you have access to ES6 features since it's pretty clean and simple to use

function convert (str) {
  return str.normalize('NFD').replace(/[\u0300-\u036f]/g, '')
}

if (term.length > 0) {
  var inputVal = convert($('#input').val())
  if (inputVal.indexOf('jason') !== -1) {
    results = $.ui.autocomplete.filter(table, term)
  }
}

Otherwise if ES6 is not an option, the top answer should be fine to use, just create a function util that you can reuse anywhere you need to.

Regarding the encoding of the file, you should use utf-8 if dealing with special chars that Turkish does have.


问:
How can I make my error message show to the right of my input button?
I'll try to explain this best as possible with pictures.

Here is my input button (look at the one under "bet"):

I want the error message to appear here:

However, all my attempts end up like this:

How can I do this? I tried multiple things such as span, inline display, etc.

UPDATE:

Posted full front-end code on github.

CSS: https://gist.github.com/xxFlare/41ed6a1cac81bbda48848d55a716c3dd

HTML: https://gist.github.com/xxFlare/300733b8b848aea829fc6b26ac70eda2

答:
Please see below. Changed the display setting for .beterror into inline-block and removed settings for width, height, padding and most of the margin.

.beterror {
  font-family: "smooth";
  background-color: indianred;
  color: white;
  display: inline-block;
  margin-left: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  Bet
  <br>
  <span><input id="userbet" onchange="checkBet()" value="1" type="text" name="bet"><div class="beterror" id="beterror">That is not a valid bet.</div></span>
  <br> Chance
  <br>
  <span><input id="userchance" value="50" type="text" name="chance"><div class="beterror" id="beterror">That is not a good chance.</div></span>
  <br>
  <h3>Payout: 0BTC</h3>
  <button type="button" id="dicebutton" onclick="prepareRoll()" style="vertical-align:middle"><img src="Images/dice.png"> Roll dice!</button>
</form></code>```

Body:
Please see below. Changed the display setting for .beterror into inline-block and removed settings for width, height, padding and most of the margin.

.beterror {
  font-family: "smooth";
  background-color: indianred;
  color: white;
  display: inline-block;
  margin-left: 5px;
}

<form>
  Bet
  <br>
  <span><input id="userbet" onchange="checkBet()" value="1" type="text" name="bet"><div class="beterror" id="beterror">That is not a valid bet.</div></span>
  <br> Chance
  <br>
  <span><input id="userchance" value="50" type="text" name="chance"><div class="beterror" id="beterror">That is not a good chance.</div></span>
  <br>
  <h3>Payout: 0BTC</h3>
  <button type="button" id="dicebutton" onclick="prepareRoll()" style="vertical-align:middle"><img src="Images/dice.png"> Roll dice!</button>
</form>


问:
Trigger on SQLite not working
I have built 2 tables (t_top and t_rest) on a db and the first should contain up to 5 numbers, while the second should contain more. We can only insert number to the t_top using an active trigger that saves 5 numbers to t_top and then if a sixth is inserted, then if it's greater than one in t_top, the sixth is inserted in t_top while the smallest from the 5 existing in it moves to t_rest.

F.e. if we have t_top=[1,3,5,7,9} and t_rest is empty, then if we insert 8 we finally have t_top=[3,5,7,8,9] and t_rest=[1]. That trigger works for me.

However, i've written another trigger, which should move numbers in case of deletion from t_top. If f.e. we delete 5, we should have 1 moved back to t_top.

My trigger is the following, but not working:

```<code>CREATE TRIGGER tracks_less_than_5
AFTER DELETE on t_top
WHEN
5>(SELECT COUNT(*) FROM t_top)
BEGIN
INSERT INTO t_top
SELECT MAX(id) AS max_id FROM t_min
WHERE id = max_id;
DELETE FROM t_min
SELECT MAX(id) AS max_id FROM t_min
WHERE id = max_id;
END
</code>```

I guess something is not right, but cannot figure what it is.

答:
```<code>DELETE FROM t_min
SELECT MAX(id) AS max_id FROM t_min
WHERE id = max_id;
</code>```

-this does not have sense because the syntax of DELETE is DELETE FROM table WHERE ... I guess you wanted something like this:

```<code>DELETE FROM t_min WHERE id=(
SELECT MAX(id) FROM t_min
);
</code>```

Title: Trigger on SQLite not working

Body:
I have built 2 tables (t_top and t_rest) on a db and the first should contain up to 5 numbers, while the second should contain more. We can only insert number to the t_top using an active trigger that saves 5 numbers to t_top and then if a sixth is inserted, then if it's greater than one in t_top, the sixth is inserted in t_top while the smallest from the 5 existing in it moves to t_rest.

F.e. if we have t_top=[1,3,5,7,9} and t_rest is empty, then if we insert 8 we finally have t_top=[3,5,7,8,9] and t_rest=[1]. That trigger works for me.

However, i've written another trigger, which should move numbers in case of deletion from t_top. If f.e. we delete 5, we should have 1 moved back to t_top.

My trigger is the following, but not working:

CREATE TRIGGER tracks_less_than_5
AFTER DELETE on t_top
WHEN
5>(SELECT COUNT(*) FROM t_top)
BEGIN
INSERT INTO t_top
SELECT MAX(id) AS max_id FROM t_min
WHERE id = max_id;
DELETE FROM t_min
SELECT MAX(id) AS max_id FROM t_min
WHERE id = max_id;
END

I guess something is not right, but cannot figure what it is.

Body:
DELETE FROM t_min
SELECT MAX(id) AS max_id FROM t_min
WHERE id = max_id;

-this does not have sense because the syntax of DELETE is DELETE FROM table WHERE ... I guess you wanted something like this:

DELETE FROM t_min WHERE id=(
SELECT MAX(id) FROM t_min
);


问:
How to get the value for Days in this code?
I am trying to show the average temperature for 4 days, the highest and lowest. The code works perfectly to show the average and highest/lowest value of the 4 days. The problem is trying to show in which day it occurred.

I know that I don't need to use arrays for it, I thought it was easy if I used it. So, here's the code. How can I improve it, to get the day of the highest/lowest value insert by the user?

```<code>int high[NUMS], low[NUMS];

int maximum = 40;
int minimum = -40;

int i, day;

float total, average;

printf("---=== IPC Temperature Analyzer ===---\n");

for (i = 0; i < NUMS; ++i) {

    do{
        printf("Enter the high value for day %d: \n", i+1);
        scanf("%d", &high[i]);
        printf("Enter the low value for day %d: \n", i+1);
        scanf("%d", &low[i]);

       if ((high[i] > maximum) || (low[i] < minimum) || (high[i] < low[i])){
                printf ("Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low.\n");
        }

    } while((high[i] > maximum) || (low[i] < minimum) || (high[i] < low[i]));

    if((high[0] < high[i]))
       high[0] = high[i];

    if ((low[0] > low[i]))
       low[0] = low[i];

    total = total + (high[i] + low[i]);

}

 average = (total / (NUMS * 2));

printf("The average (mean) temperature was: %.2f\n", average);
printf("The highest temperature was %d, on day %d\n", high[0], day);
printf("The lowest temperature was %d, on day %d\n", low[0], day);

return 0;
</code>```

答:
The simplest way without changing very much your code is declaring two variables day instead of one:

```<code>int day_low = 0;
int day_high = 0;
</code>```

Then change your if conditions below for these:

```<code>if((high[0] < high[i])) {
   high[0] = high[i];
   day_high = i;
}

if ((low[0] > low[i])) {
   low[0] = low[i];
   day_low = i;
}
</code>```

And finally:

```<code>printf("The highest temperature was %d, on day %d\n", high[0], day_high);
printf("The lowest temperature was %d, on day %d\n", low[0], day_low);
</code>```

Body:
I am trying to show the average temperature for 4 days, the highest and lowest. The code works perfectly to show the average and highest/lowest value of the 4 days. The problem is trying to show in which day it occurred.

I know that I don't need to use arrays for it, I thought it was easy if I used it. So, here's the code. How can I improve it, to get the day of the highest/lowest value insert by the user?

int high[NUMS], low[NUMS];

int maximum = 40;
int minimum = -40;

int i, day;

float total, average;

printf("---=== IPC Temperature Analyzer ===---\n");

for (i = 0; i < NUMS; ++i) {

    do{
        printf("Enter the high value for day %d: \n", i+1);
        scanf("%d", &high[i]);
        printf("Enter the low value for day %d: \n", i+1);
        scanf("%d", &low[i]);

       if ((high[i] > maximum) || (low[i] < minimum) || (high[i] < low[i])){
                printf ("Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low.\n");
        }

    } while((high[i] > maximum) || (low[i] < minimum) || (high[i] < low[i]));

    if((high[0] < high[i]))
       high[0] = high[i];

    if ((low[0] > low[i]))
       low[0] = low[i];

    total = total + (high[i] + low[i]);

}

 average = (total / (NUMS * 2));

printf("The average (mean) temperature was: %.2f\n", average);
printf("The highest temperature was %d, on day %d\n", high[0], day);
printf("The lowest temperature was %d, on day %d\n", low[0], day);

return 0;

Body:
The simplest way without changing very much your code is declaring two variables day instead of one:

int day_low = 0;
int day_high = 0;

Then change your if conditions below for these:

if((high[0] < high[i])) {
   high[0] = high[i];
   day_high = i;
}

if ((low[0] > low[i])) {
   low[0] = low[i];
   day_low = i;
}

And finally:

printf("The highest temperature was %d, on day %d\n", high[0], day_high);
printf("The lowest temperature was %d, on day %d\n", low[0], day_low);


问:
Longest sequence of consecutive letters
Suppose I have a string of lower case letters, e.g.

```<code>'ablccmdnneofffpg'
</code>```

And my aim is to find the longest sequence of the consecutive numbers inside this string which in this case is:

```<code>'abcdefg'
</code>```

The intuitive attempt is to find loop around each letter and obtain the longest sequence starting from that letter. One possible solution is

```<code>longest_length = 0
start = None
current_start = 0
while current_start < len(word) - longest_length:
    current_length = 1
    last_in_sequence = ord(word[current_start])
    for i in range(current_start + 1, len(word)):
        if ord(word[i]) - last_in_sequence == 1:
            current_length += 1
            last_in_sequence = ord(word[i])
    if current_length > longest_length:
        longest_length = current_length
        start = current_start
    while (current_start < len(word) - 1 and
           ord(word[current_start + 1]) - ord(word[current_start]) == 1):
        current_start += 1
    current_start += 1
</code>```

Are there any other ways of solving the problem with fewer lines, or even using some pythonic methods?

答: You are basically asking for the longest increasing subsequence, which is a well-studied problem. Have a look at the pseudo code in Wikipedia.

Title: Longest sequence of consecutive letters

Body:
Suppose I have a string of lower case letters, e.g.

'ablccmdnneofffpg'

And my aim is to find the longest sequence of the consecutive numbers inside this string which in this case is:

'abcdefg'

The intuitive attempt is to find loop around each letter and obtain the longest sequence starting from that letter. One possible solution is

longest_length = 0
start = None
current_start = 0
while current_start < len(word) - longest_length:
    current_length = 1
    last_in_sequence = ord(word[current_start])
    for i in range(current_start + 1, len(word)):
        if ord(word[i]) - last_in_sequence == 1:
            current_length += 1
            last_in_sequence = ord(word[i])
    if current_length > longest_length:
        longest_length = current_length
        start = current_start
    while (current_start < len(word) - 1 and
           ord(word[current_start + 1]) - ord(word[current_start]) == 1):
        current_start += 1
    current_start += 1

Are there any other ways of solving the problem with fewer lines, or even using some pythonic methods?


问:
Failed to provide proxy info to twilio pythonanywhere
I am trying to use Twilio in pythonanywhere and I know I need a proxy to make it work. My code looks like this:

```<code>    class ProxiedTwilioHttpClient(HttpClient):
        """
        General purpose HTTP Client for interacting with the Twilio API
        """
        def request(self, method, url, params=None, data=None, headers=None, auth=None, timeout=None,
                    allow_redirects=False):
        session = Session()
        session.verify = get_cert_file()
        session.proxies = {
                              "https" : "https://52.14.161.178:3128"
                          }

        request = Request(method.upper(), url, params=params, data=data, headers=headers, auth=auth)

        prepped_request = session.prepare_request(request)
        response = session.send(
            prepped_request,
            allow_redirects=allow_redirects,
            timeout=timeout,
        )

        return Response(int(response.status_code), response.content.decode('utf-8'))

def send_sms(phone, content):
    client = Client(api_key, api_secret, account_sid, http_client=ProxiedTwilioHttpClient())
    message = client.messages.create(
        to=phone,
        from_="+19999999999", #of course I use the correct one
        body=content)
    return(message.sid)
</code>```

But then it returns the following error:

```<code>.virtualenvs/sms/local/lib/python2.7/site-packages/requests/adapters.py",
line 502, in send raise ProxyError(e, request=request) requests.exceptions.ProxyError:
HTTPSConnectionPool(host='api.twilio.com', port=443):
Max retries exceeded with url: /2010-04-01/Accounts/XXXXXXXXX/Messages.json (Caused by ProxyError('Cannot connect to proxy.',
NewConnectionError('<urllib3.connection.Verif iedHTTPSConnection object at 0x7fa41a55e090>:
Failed to establish a new connection: [Errno 111] Connection refused',)))
</code>```

I am using the following answer that seems to work for others: https://stackoverflow.com/a/43608637/7298530

How can I solve it?

答:
You're specifying that your code should use a proxy at https://52.14.161.178:3128.  That won't work on PythonAnywhere, you need to use the proxy that the service provides.  To find out what address to use for that, start a Bash console and run

```<code>echo $http_proxy
</code>```

[2018 edit] We now have a specific page on getting twilio to work with the pythonanywhere proxy

Body:
I am trying to use Twilio in pythonanywhere and I know I need a proxy to make it work. My code looks like this:

    class ProxiedTwilioHttpClient(HttpClient):
        """
        General purpose HTTP Client for interacting with the Twilio API
        """
        def request(self, method, url, params=None, data=None, headers=None, auth=None, timeout=None,
                    allow_redirects=False):
        session = Session()
        session.verify = get_cert_file()
        session.proxies = {
                              "https" : "https://52.14.161.178:3128"
                          }

        request = Request(method.upper(), url, params=params, data=data, headers=headers, auth=auth)

        prepped_request = session.prepare_request(request)
        response = session.send(
            prepped_request,
            allow_redirects=allow_redirects,
            timeout=timeout,
        )

        return Response(int(response.status_code), response.content.decode('utf-8'))

def send_sms(phone, content):
    client = Client(api_key, api_secret, account_sid, http_client=ProxiedTwilioHttpClient())
    message = client.messages.create(
        to=phone,
        from_="+19999999999", #of course I use the correct one
        body=content)
    return(message.sid)

But then it returns the following error:

.virtualenvs/sms/local/lib/python2.7/site-packages/requests/adapters.py",
line 502, in send raise ProxyError(e, request=request) requests.exceptions.ProxyError:
HTTPSConnectionPool(host='api.twilio.com', port=443):
Max retries exceeded with url: /2010-04-01/Accounts/XXXXXXXXX/Messages.json (Caused by ProxyError('Cannot connect to proxy.',
NewConnectionError('<urllib3.connection.Verif iedHTTPSConnection object at 0x7fa41a55e090>:
Failed to establish a new connection: [Errno 111] Connection refused',)))

I am using the following answer that seems to work for others: https://stackoverflow.com/a/43608637/7298530

How can I solve it?

Body:
You're specifying that your code should use a proxy at https://52.14.161.178:3128.  That won't work on PythonAnywhere, you need to use the proxy that the service provides.  To find out what address to use for that, start a Bash console and run

echo $http_proxy

[2018 edit] We now have a specific page on getting twilio to work with the pythonanywhere proxy


问:
How to change the grouping of items in a list?
So if I have a list like this:

```<code>x = [0,1,2,3,4,5,6,7,8,9]
</code>```

How do I convert this list into something like this:

```<code>x = [01,23,45,67,89]
</code>```

How can I do that?

I know about the built in zip function,
but I don't want a tuple and I want 2 numbers grouped into 1.

答:
This is much easier to understand and is a one liner:</p>

```<code> # l = list of string of items in list u with index(i) and index(i+1) and i increments by 2
 l = [ str( u[i]) + str( u[i+1]) for i in range( 0, len(u), 2)]
</code>```

Body:
So if I have a list like this:

x = [0,1,2,3,4,5,6,7,8,9]

How do I convert this list into something like this:

x = [01,23,45,67,89]

How can I do that?

I know about the built in zip function,
but I don't want a tuple and I want 2 numbers grouped into 1.

Body:
This is much easier to understand and is a one liner:

 # l = list of string of items in list u with index(i) and index(i+1) and i increments by 2
 l = [ str( u[i]) + str( u[i+1]) for i in range( 0, len(u), 2)]


问:
Cmake searches for opencv library
I have installed Opencv-3.2 and I can see the bin and lib files

```<code>$ ls /share/apps/computer/opencv-3.2.0/built/bin/opencv_
opencv_annotation     opencv_createsamples  opencv_traincascade     opencv_version        opencv_visualisation
$ ls /share/apps/computer/opencv-3.2.0/built/lib/
libopencv_calib3d.so           libopencv_imgcodecs.so.3.2.0   libopencv_stitching.so.3.2
libopencv_calib3d.so.3.2       libopencv_imgproc.so           libopencv_stitching.so.3.2.0
libopencv_calib3d.so.3.2.0     libopencv_imgproc.so.3.2       libopencv_superres.so
libopencv_core.so              libopencv_imgproc.so.3.2.0     libopencv_superres.so.3.2
libopencv_core.so.3.2          libopencv_ml.so                libopencv_superres.so.3.2.0
libopencv_core.so.3.2.0        libopencv_ml.so.3.2            libopencv_videoio.so
libopencv_features2d.so        libopencv_ml.so.3.2.0          libopencv_videoio.so.3.2
libopencv_features2d.so.3.2    libopencv_objdetect.so         libopencv_videoio.so.3.2.0
libopencv_features2d.so.3.2.0  libopencv_objdetect.so.3.2     libopencv_video.so
libopencv_flann.so             libopencv_objdetect.so.3.2.0   libopencv_video.so.3.2
libopencv_flann.so.3.2         libopencv_photo.so             libopencv_video.so.3.2.0
libopencv_flann.so.3.2.0       libopencv_photo.so.3.2         libopencv_videostab.so
libopencv_highgui.so           libopencv_photo.so.3.2.0       libopencv_videostab.so.3.2
libopencv_highgui.so.3.2       libopencv_shape.so             libopencv_videostab.so.3.2.0
libopencv_highgui.so.3.2.0     libopencv_shape.so.3.2         pkgconfig/
libopencv_imgcodecs.so         libopencv_shape.so.3.2.0
libopencv_imgcodecs.so.3.2     libopencv_stitching.so
</code>```

Now, according to the tutorial, I wrote a simple program. Problem is that, cmake gets some errors and seems that it is not able to find the library.

```<code>CMake Error at CMakeLists.txt:3 (find_package):
  By not providing "FindOpenCV.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "OpenCV", but
  CMake did not find one.

  Could not find a package configuration file provided by "OpenCV" with any
  of the following names:

    OpenCVConfig.cmake
    opencv-config.cmake

  Add the installation prefix of "OpenCV" to CMAKE_PREFIX_PATH or set
  "OpenCV_DIR" to a directory containing one of the above files.  If   "OpenCV"
  provides a separate development package or SDK, be sure it has been
  installed.
</code>```

I don't know how to set CMAKE_PREFIX_PATH or OpenCV_DIR. How can I fix that?

The content of CMakeLists.txt is

```<code>cmake_minimum_required(VERSION 2.8)
project( DisplayImage )
find_package( OpenCV REQUIRED )
add_executable( DisplayImage DisplayImage.cpp )
target_link_libraries( DisplayImage ${OpenCV_LIBS} )
</code>```

答:
It depends whether you have OpenCVConfig.cmake script, which comes with your installation of OpenCV (that is, under install directory /share/apps/computer/opencv-3.2.0/built/).

If your installation of OpenCV lacks of OpenCVConfig.cmake script, you need to ship your project with script FindOpenCV.cmake (find and copy it from the net, almost any of them is suitable), and add directory with this script to CMAKE_MODULE_PATH variable:

```<code>list(APPEND CMAKE_MODULE_PATH <directory-with-find-script>)
</code>```

Possible ways to hint CMake about your installation of OpenCV:

If you have OpenCVConfig.cmake script, set OpenCV_DIR variable to directory contained this script:

```<code>cmake -DOpenCV_DIR=/share/apps/computer/opencv-3.2.0/built/<...>
</code>```

Set CMAKE_PREFIX_PATH variable to installation prefix of OpenCV:

```<code>cmake -DCMAKE_PREFIX_PATH=/share/apps/computer/opencv-3.2.0/built
</code>```

This works both with OpenCVConfig.cmake and with FindOpenCV.cmake scripts. See also that question: Hinting Find<name>.cmake Files with a custom directory.

Title: Cmake searches for opencv library

Body:
I have installed Opencv-3.2 and I can see the bin and lib files

$ ls /share/apps/computer/opencv-3.2.0/built/bin/opencv_
opencv_annotation     opencv_createsamples  opencv_traincascade     opencv_version        opencv_visualisation
$ ls /share/apps/computer/opencv-3.2.0/built/lib/
libopencv_calib3d.so           libopencv_imgcodecs.so.3.2.0   libopencv_stitching.so.3.2
libopencv_calib3d.so.3.2       libopencv_imgproc.so           libopencv_stitching.so.3.2.0
libopencv_calib3d.so.3.2.0     libopencv_imgproc.so.3.2       libopencv_superres.so
libopencv_core.so              libopencv_imgproc.so.3.2.0     libopencv_superres.so.3.2
libopencv_core.so.3.2          libopencv_ml.so                libopencv_superres.so.3.2.0
libopencv_core.so.3.2.0        libopencv_ml.so.3.2            libopencv_videoio.so
libopencv_features2d.so        libopencv_ml.so.3.2.0          libopencv_videoio.so.3.2
libopencv_features2d.so.3.2    libopencv_objdetect.so         libopencv_videoio.so.3.2.0
libopencv_features2d.so.3.2.0  libopencv_objdetect.so.3.2     libopencv_video.so
libopencv_flann.so             libopencv_objdetect.so.3.2.0   libopencv_video.so.3.2
libopencv_flann.so.3.2         libopencv_photo.so             libopencv_video.so.3.2.0
libopencv_flann.so.3.2.0       libopencv_photo.so.3.2         libopencv_videostab.so
libopencv_highgui.so           libopencv_photo.so.3.2.0       libopencv_videostab.so.3.2
libopencv_highgui.so.3.2       libopencv_shape.so             libopencv_videostab.so.3.2.0
libopencv_highgui.so.3.2.0     libopencv_shape.so.3.2         pkgconfig/
libopencv_imgcodecs.so         libopencv_shape.so.3.2.0
libopencv_imgcodecs.so.3.2     libopencv_stitching.so

Now, according to the tutorial, I wrote a simple program. Problem is that, cmake gets some errors and seems that it is not able to find the library.

CMake Error at CMakeLists.txt:3 (find_package):
  By not providing "FindOpenCV.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "OpenCV", but
  CMake did not find one.

  Could not find a package configuration file provided by "OpenCV" with any
  of the following names:

    OpenCVConfig.cmake
    opencv-config.cmake

  Add the installation prefix of "OpenCV" to CMAKE_PREFIX_PATH or set
  "OpenCV_DIR" to a directory containing one of the above files.  If   "OpenCV"
  provides a separate development package or SDK, be sure it has been
  installed.

I don't know how to set CMAKE_PREFIX_PATH or OpenCV_DIR. How can I fix that?

The content of CMakeLists.txt is

cmake_minimum_required(VERSION 2.8)
project( DisplayImage )
find_package( OpenCV REQUIRED )
add_executable( DisplayImage DisplayImage.cpp )
target_link_libraries( DisplayImage ${OpenCV_LIBS} )

Body:
It depends whether you have OpenCVConfig.cmake script, which comes with your installation of OpenCV (that is, under install directory /share/apps/computer/opencv-3.2.0/built/).

If your installation of OpenCV lacks of OpenCVConfig.cmake script, you need to ship your project with script FindOpenCV.cmake (find and copy it from the net, almost any of them is suitable), and add directory with this script to CMAKE_MODULE_PATH variable:

list(APPEND CMAKE_MODULE_PATH <directory-with-find-script>)

Possible ways to hint CMake about your installation of OpenCV:

If you have OpenCVConfig.cmake script, set OpenCV_DIR variable to directory contained this script:

cmake -DOpenCV_DIR=/share/apps/computer/opencv-3.2.0/built/<...>

Set CMAKE_PREFIX_PATH variable to installation prefix of OpenCV:

cmake -DCMAKE_PREFIX_PATH=/share/apps/computer/opencv-3.2.0/built

This works both with OpenCVConfig.cmake and with FindOpenCV.cmake scripts. See also that question: Hinting Find<name>.cmake Files with a custom directory.


问:
Why i have a link that sends me to a jsp perfectly the first time but whenever i get to click that link again it display an error
i am working in mvc web application with servlets and jsp with database connection

i have a link in a jsp that send me to a another jsp where I can register
another employee

 Add new employee

in the jsp where it send us we can register a new employee and stored the information in a database , once we click the button register the servlet
bring us back to  the first jsp where the link add new employee is but if i click it again to add another employee it gives me this error

HTTP Status 404 - Not Found

type Status report

messageNot Found

descriptionThe requested resource is not available.

答: I got the answer I was sending from the servlet to the jsp a parameter with a request dispatcher instead of using a response.sendredirect , an for that reason I wasn't really in the jsp I was still in the servlet and that's why the link didn't work again </p>


问:
Why does Math::Cartesian::Product return blessed objects?
I noticed Math::Cartesian::Product returns an array of blessed objects instead of a simple array of arrays.  I couldn't figure out why. I actually need to do some extra work (unbless) to use the results...</p>

答:
I added a cartesian function to List::Gen recently:

cartesian CODE LIST_of_ARRAYREF

cartesian computes the cartesian product of any number of array refs, each which can be any size. returns a generator

```<code>use List::Gen 'cartesian';
my $product = cartesian {$_[0] . $_[1]} [qw/a b/], [1, 2];
print "@$product"; # 'a1 a2 b1 b2'
</code>```

The "generator" returned is a lazy tied array that will generate values when asked for them.  There are also iterative and other accessor methods:

```<code>my $pairs = cartesian {@_} [qw/$ @ %/], ['a'..'z'], [1 .. 3];

while (my @tuple = $pairs->next) {  # $pairs->reset; #$pairs->index = 5; ...
    print @tuple, ', ';
}
# $a1, $a2, $a3, $b1, $b2, $b3, $c1, $c2, $c3, $d1, $d2, $d3, $e1 ...
</code>```

I don't know how large the sets you will be working with are, but the advantage to using the above approach is that the storage requirements for the generator remain O(1)

```<code>my $digits = cartesian {join '' => @_} ([0..9]) x 10;

say for @$digits[10**9 - 3 .. 10**9 + 3];

#   0999999998
#   0999999999
#   1000000000
#   1000000001
#   1000000002
#   1000000003
</code>```

which calculates only 6 elements of the set, and stores nothing.

As you can see from the examples, the return value of cartesian itself is a generator object, but that object's subsequent return values are whatever the coderef passed to cartesian returns.  So if you want array references, it's as simple as: cartesian {\@_} ...

Also, what extra work did you have to do to deal with the blessed reference?  A blessed array is still an array in every sense except for what ref will return.  If you are writing switch logic based on reference type, Scalar::Util's reftype is what you should use.

ContentLicense: CC BY-SA 2.5

Body:
I added a cartesian function to List::Gen recently:

cartesian CODE LIST_of_ARRAYREF

cartesian computes the cartesian product of any number of array refs, each which can be any size. returns a generator

use List::Gen 'cartesian';
my $product = cartesian {$_[0] . $_[1]} [qw/a b/], [1, 2];
print "@$product"; # 'a1 a2 b1 b2'

The "generator" returned is a lazy tied array that will generate values when asked for them.  There are also iterative and other accessor methods:

my $pairs = cartesian {@_} [qw/$ @ %/], ['a'..'z'], [1 .. 3];

while (my @tuple = $pairs->next) {  # $pairs->reset; #$pairs->index = 5; ...
    print @tuple, ', ';
}
# $a1, $a2, $a3, $b1, $b2, $b3, $c1, $c2, $c3, $d1, $d2, $d3, $e1 ...

I don't know how large the sets you will be working with are, but the advantage to using the above approach is that the storage requirements for the generator remain O(1)

my $digits = cartesian {join '' => @_} ([0..9]) x 10;

say for @$digits[10**9 - 3 .. 10**9 + 3];

#   0999999998
#   0999999999
#   1000000000
#   1000000001
#   1000000002
#   1000000003

which calculates only 6 elements of the set, and stores nothing.

As you can see from the examples, the return value of cartesian itself is a generator object, but that object's subsequent return values are whatever the coderef passed to cartesian returns.  So if you want array references, it's as simple as: cartesian {\@_} ...

Also, what extra work did you have to do to deal with the blessed reference?  A blessed array is still an array in every sense except for what ref will return.  If you are writing switch logic based on reference type, Scalar::Util's reftype is what you should use.


问:
How do I increment a value with mysql update query (php)
I have a query that looks like this:

```<code>$sql = "UPDATE tbl SET amt_field='amt_field+1' WHERE username='" .mysql_real_escape_string($_SESSION['username']). "'";
        mysql_select_db('db',$con);
        mysql_query($sql,$con);
</code>```

I want to increment the value as easily as possible.

I have tried:

```<code>"UPDATE tbl SET amt_field='amt_field+1' WHERE

"UPDATE tbl SET amt_field='amt_field' + 1 WHERE

"UPDATE tbl SET amt_field='amt_field++' WHERE
</code>```

I don't get error messages, but the value in my db does not increase either.

答:
Hello did you initialize a new session. Below worked perfectly for me.</p>

```<code>  public static function insert_search($pdo)
  {
    @session_start();
    $ip = $_SERVER['REMOTE_ADDR'];
    $username = $_SESSION['username'];
    //$username = self::username();
    $date = date('Y-m-d');
    //Adding the total searches for the logged in user
    $query = $pdo->query("UPDATE  `users` SET  `total_searches` = `total_searches` +1 WHERE username = '$username'");
  }

/* What you could potentially do is the following.
Make sure if you're doing it the procedural way
you put @session_start(); at the top of the page */

@session_start();
$sql = "UPDATE tbl SET amt_field ='amt_field' +1 WHERE username ='" .mysql_real_escape_string($_SESSION['username']). "'";
        mysql_select_db('db',$con);
        mysql_query($sql,$con);
</code>```

Body:
I have a query that looks like this:

$sql = "UPDATE tbl SET amt_field='amt_field+1' WHERE username='" .mysql_real_escape_string($_SESSION['username']). "'";
        mysql_select_db('db',$con);
        mysql_query($sql,$con);

I want to increment the value as easily as possible.

I have tried:

"UPDATE tbl SET amt_field='amt_field+1' WHERE

"UPDATE tbl SET amt_field='amt_field' + 1 WHERE

"UPDATE tbl SET amt_field='amt_field++' WHERE

I don't get error messages, but the value in my db does not increase either.

Body:
Hello did you initialize a new session. Below worked perfectly for me.

  public static function insert_search($pdo)
  {
    @session_start();
    $ip = $_SERVER['REMOTE_ADDR'];
    $username = $_SESSION['username'];
    //$username = self::username();
    $date = date('Y-m-d');
    //Adding the total searches for the logged in user
    $query = $pdo->query("UPDATE  `users` SET  `total_searches` = `total_searches` +1 WHERE username = '$username'");
  }

/* What you could potentially do is the following.
Make sure if you're doing it the procedural way
you put @session_start(); at the top of the page */

@session_start();
$sql = "UPDATE tbl SET amt_field ='amt_field' +1 WHERE username ='" .mysql_real_escape_string($_SESSION['username']). "'";
        mysql_select_db('db',$con);
        mysql_query($sql,$con);


问:
TeamCity Finish Build Triggers Hierarchy
I am currently attempting to implement finish build triggers and snapshot dependencies to kick off builds anytime a dependency is changed. However, my build configuration is a bit complex. For example, I may have a build configuration that looks like

This Picture.

I would like to have these 3 cases met:

Build D kick off build B and C, then have either B or C kick off build A. Making sure that B and C finish before A is triggered.

If build D is not run and B is run, then only kick off build A.

If build D is not run and C is run, then only kick off build A as well.

In other words, I would like these sequences of builds:

D->(B and C)->A

B->A

C->A

Is there a way to do this?

答:
Almost everything you want to implement is possible just using snapshot dependencies with one small exception - trigger A by either B or C.
There is a rule in snapshot dependencies - The build of this configuration will run after all the dependencies are built. That means we can use AND operation (trigger A by B and C) but not OR (trigger A by B or C).

So to trigger B after D you need to add snapshot dependency on D for B. The same for C.
And similar for other builds.

It's possible to use Kotlin DSL to customize builds triggering and it may help you to implement OR operation. But that is not out of the box feature of TeamCity.

Another workaround is to have 2 copies of A build. One of them will be triggered by B build (it will have snapshot dependency on B) and another by C build (it will have snapshot dependency on C).
To reduce duplication you may extract all A logic into a template. So 2 copies will have just different dependencies but everything else will be defined in the template.

ContentLicense: CC BY-SA 4.0


问:
PHP/MySQL: Hashing common data
I am looking at my current database set up and it consists of a silly amount of user full home addresses in about 7 different tables, all with a varying degree of inconsistent data (due to the way people can type their postcode with/without spaces, for example).

The application in question is not yet live - not far off full completion but still not live, so any change now would be much easier than say 6 months down the line when there's a ridiculous amount of data in the tables.

Would it be worth my while to spend a few hours refactoring the code/database that handles user home addresses and instead of inserting the full one every time, using a hashing algorithm?
This would give us much greater consistency and could obviously be set up in a way that users could share an address hash and so therefore we could even search them by address much easier.

We currently use this method with storing user agents - hash the UA String and store it in its own separate table alongside a Medium Text column for the actual UA string to go, then instead we store the UA Hash in tables that require it (see below), and use SHA1. However, what options are available to me in terms of non-collision based hashing, but you've also seen to execute in the quickest possible time in a small-medium scale production environment?

This means that the two obvious ones, MD5/SHA1 are 100% not happening, and I don't really work with hashes bigger than that unfortunately.
For the record, for the password encryption I use password_hash so don't freak out!

Obviously a user's home address is much more important than a user agent string which is why I'm asking what you'd recommend.

Thanks

答:
For those of you wondering, I went with SHA256.

I didn't realise there's actually a function in openssl to benchmark hashing algorithms, which can be used like: openssl speed alg1 alg2 alg3 etc

Looking at the 64/256 byte results in the table below, although obviously it doesn't perform as quick as MD5/SHA1, I've decided its still quick enough for the production anyway.

I thought I'd post this and let anyone who doesn't know about openssl speed have a go.

```<code>[root@prod-use1a ec2-user]# openssl speed md5 sha1 sha256 sha512
Doing md5 for 3s on 16 size blocks: 9785239 md5's in 3.00s
Doing md5 for 3s on 64 size blocks: 7076501 md5's in 2.99s
Doing md5 for 3s on 256 size blocks: 3832312 md5's in 3.00s
Doing md5 for 3s on 1024 size blocks: 1363911 md5's in 3.00s
Doing md5 for 3s on 8192 size blocks: 194888 md5's in 3.00s
Doing sha1 for 3s on 16 size blocks: 10839355 sha1's in 3.00s
Doing sha1 for 3s on 64 size blocks: 7479305 sha1's in 2.99s
Doing sha1 for 3s on 256 size blocks: 4024302 sha1's in 3.00s
Doing sha1 for 3s on 1024 size blocks: 1478185 sha1's in 3.00s
Doing sha1 for 3s on 8192 size blocks: 227631 sha1's in 3.00s
Doing sha256 for 3s on 16 size blocks: 7984178 sha256's in 3.00s
Doing sha256 for 3s on 64 size blocks: 4370920 sha256's in 3.00s
Doing sha256 for 3s on 256 size blocks: 1904856 sha256's in 3.00s
Doing sha256 for 3s on 1024 size blocks: 589307 sha256's in 3.00s
Doing sha256 for 3s on 8192 size blocks: 77639 sha256's in 2.99s
Doing sha512 for 3s on 16 size blocks: 6481869 sha512's in 3.00s
Doing sha512 for 3s on 64 size blocks: 6479426 sha512's in 3.00s
Doing sha512 for 3s on 256 size blocks: 2425680 sha512's in 3.00s
Doing sha512 for 3s on 1024 size blocks: 869702 sha512's in 3.00s
Doing sha512 for 3s on 8192 size blocks: 120660 sha512's in 3.00s

The 'numbers' are in 1000s of bytes per second processed.
type             16 bytes     64 bytes    256 bytes   1024 bytes   8192 bytes
md5              52187.94k   151470.26k   327023.96k   465548.29k   532174.17k
sha1             57809.89k   160092.15k   343407.10k   504553.81k   621584.38k
sha256           42582.28k    93246.29k   162547.71k   201150.12k   212715.28k
sha512           34569.97k   138227.75k   206991.36k   296858.28k   329482.24k
[root@prod-use1a ec2-user]#
</code>```

Title: PHP/MySQL: Hashing common data

Body:
For those of you wondering, I went with SHA256.

I didn't realise there's actually a function in openssl to benchmark hashing algorithms, which can be used like: openssl speed alg1 alg2 alg3 etc

Looking at the 64/256 byte results in the table below, although obviously it doesn't perform as quick as MD5/SHA1, I've decided its still quick enough for the production anyway.

I thought I'd post this and let anyone who doesn't know about openssl speed have a go.

[root@prod-use1a ec2-user]# openssl speed md5 sha1 sha256 sha512
Doing md5 for 3s on 16 size blocks: 9785239 md5's in 3.00s
Doing md5 for 3s on 64 size blocks: 7076501 md5's in 2.99s
Doing md5 for 3s on 256 size blocks: 3832312 md5's in 3.00s
Doing md5 for 3s on 1024 size blocks: 1363911 md5's in 3.00s
Doing md5 for 3s on 8192 size blocks: 194888 md5's in 3.00s
Doing sha1 for 3s on 16 size blocks: 10839355 sha1's in 3.00s
Doing sha1 for 3s on 64 size blocks: 7479305 sha1's in 2.99s
Doing sha1 for 3s on 256 size blocks: 4024302 sha1's in 3.00s
Doing sha1 for 3s on 1024 size blocks: 1478185 sha1's in 3.00s
Doing sha1 for 3s on 8192 size blocks: 227631 sha1's in 3.00s
Doing sha256 for 3s on 16 size blocks: 7984178 sha256's in 3.00s
Doing sha256 for 3s on 64 size blocks: 4370920 sha256's in 3.00s
Doing sha256 for 3s on 256 size blocks: 1904856 sha256's in 3.00s
Doing sha256 for 3s on 1024 size blocks: 589307 sha256's in 3.00s
Doing sha256 for 3s on 8192 size blocks: 77639 sha256's in 2.99s
Doing sha512 for 3s on 16 size blocks: 6481869 sha512's in 3.00s
Doing sha512 for 3s on 64 size blocks: 6479426 sha512's in 3.00s
Doing sha512 for 3s on 256 size blocks: 2425680 sha512's in 3.00s
Doing sha512 for 3s on 1024 size blocks: 869702 sha512's in 3.00s
Doing sha512 for 3s on 8192 size blocks: 120660 sha512's in 3.00s

The 'numbers' are in 1000s of bytes per second processed.
type             16 bytes     64 bytes    256 bytes   1024 bytes   8192 bytes
md5              52187.94k   151470.26k   327023.96k   465548.29k   532174.17k
sha1             57809.89k   160092.15k   343407.10k   504553.81k   621584.38k
sha256           42582.28k    93246.29k   162547.71k   201150.12k   212715.28k
sha512           34569.97k   138227.75k   206991.36k   296858.28k   329482.24k
[root@prod-use1a ec2-user]#


问:
Images don't display on JFrame
I have been coding a game in Java for a while, and I got stuck on Image handling. I don't know why but it worked in all my previous games. Do I have it right? Thanks for advice!

```<code>public class Game extends JPanel implements ActionListener {
    private static final long serialVersionUID = 1L;

    private Timer gameLoop;
    public static final int WIDTH = 800;
    public static final int HEIGHT = 500;
    public static final Dimension SCREEN_SIZE = new Dimension(WIDTH, HEIGHT);
    public static final int FRAMERATE = 60;
    public static final String TITLE = "MedievalGame";

    public BufferedImage[] images = new BufferedImage[4];

    public int x = 100;
    public int y = 100;
    public int width = 100;
    public int height = 100;

    public Game() {
        this.setPreferredSize(SCREEN_SIZE);
        this.setFocusable(true);

        try {
            images[0] = ImageIO.read(getClass().getResourceAsStream("path"));
        } catch (IOException e) {
            e.printStackTrace()
        }

        gameLoop = new Timer(1000 / FRAMERATE, this);
        gameLoop.start();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(images[0], x, y, width, height, null);
    }

    public void actionPerformed(ActionEvent e) {
        this.repaint();
    }

    public static void main(String[] args) {
        JFrame window = new JFrame(TITLE);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setResizable(false);
        window.add(new Game());
        window.pack();
        window.setLocationRelativeTo(null);
        window.setVisible(true);
    }
}
</code>```

I checked many similar questions, but none solved my problem.

答: I figured out what the problem was. Everything about the code was correct, but the images were somehow broken. I tried using other images, and it worked. Thank you all for your time and help.</p>

Title: Images don't display on JFrame

Body:
I have been coding a game in Java for a while, and I got stuck on Image handling. I don't know why but it worked in all my previous games. Do I have it right? Thanks for advice!

public class Game extends JPanel implements ActionListener {
    private static final long serialVersionUID = 1L;

    private Timer gameLoop;
    public static final int WIDTH = 800;
    public static final int HEIGHT = 500;
    public static final Dimension SCREEN_SIZE = new Dimension(WIDTH, HEIGHT);
    public static final int FRAMERATE = 60;
    public static final String TITLE = "MedievalGame";

    public BufferedImage[] images = new BufferedImage[4];

    public int x = 100;
    public int y = 100;
    public int width = 100;
    public int height = 100;

    public Game() {
        this.setPreferredSize(SCREEN_SIZE);
        this.setFocusable(true);

        try {
            images[0] = ImageIO.read(getClass().getResourceAsStream("path"));
        } catch (IOException e) {
            e.printStackTrace()
        }

        gameLoop = new Timer(1000 / FRAMERATE, this);
        gameLoop.start();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(images[0], x, y, width, height, null);
    }

    public void actionPerformed(ActionEvent e) {
        this.repaint();
    }

    public static void main(String[] args) {
        JFrame window = new JFrame(TITLE);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setResizable(false);
        window.add(new Game());
        window.pack();
        window.setLocationRelativeTo(null);
        window.setVisible(true);
    }
}

I checked many similar questions, but none solved my problem.


问:
C# Permutation of an array of arraylists?
I have an ArrayList[] myList and I am trying to create a list of all the permutations of the values in the arrays.

EXAMPLE: (all values are strings)

```<code>myList[0] = { "1", "5", "3", "9" };
myList[1] = { "2", "3" };
myList[2] = { "93" };
</code>```

The count of myList can be varied so its length is not known beforehand.

I would like to be able to generate a list of all the permutations similar to the following (but with some additional formatting).

```<code>1 2 93
1 3 93
5 2 93
5 3 93
3 2 93
3 3 93
9 2 93
9 3 93
</code>```

Does this make sense of what I am trying to accomplish?  I can't seem to come up with a good method for doing this, (if any).

Edit:

I am not sure if recursion would interfere with my desire to format the output in my own manner. Sorry I did not mention before what my formatting was.

I want to end up building a string[] array of all the combinations that follows the format like below:

for the "1 2 93" permutation

I want the output to be "val0=1;val1=2;val2=93;"

I will experiment with recursion for now. Thank you DrJokepu

答:
Here is a generic recursive function that I wrote (and an overload that may be convenient to call):

```<code>Public Shared Function GetCombinationsFromIEnumerables(ByRef chain() As Object, ByRef IEnumerables As IEnumerable(Of IEnumerable(Of Object))) As List(Of Object())
    Dim Combinations As New List(Of Object())
    If IEnumerables.Any Then
        For Each v In IEnumerables.First
            Combinations.AddRange(GetCombinationsFromIEnumerables(chain.Concat(New Object() {v}).ToArray, IEnumerables.Skip(1)).ToArray)
        Next
    Else
        Combinations.Add(chain)
    End If
    Return Combinations
End Function

Public Shared Function GetCombinationsFromIEnumerables(ByVal ParamArray IEnumerables() As IEnumerable(Of Object)) As List(Of Object())
    Return GetCombinationsFromIEnumerables(chain:=New Object() {}, IEnumerables:=IEnumerables.AsEnumerable)
End Function
</code>```

And the equivalent in C#:

```<code>public static List<object[]> GetCombinationsFromIEnumerables(ref object[] chain, ref IEnumerable<IEnumerable<object>> IEnumerables)
{
List<object[]> Combinations = new List<object[]>();
if (IEnumerables.Any) {
    foreach ( v in IEnumerables.First) {
        Combinations.AddRange(GetCombinationsFromIEnumerables(chain.Concat(new object[] { v }).ToArray, IEnumerables.Skip(1)).ToArray);
    }
} else {
    Combinations.Add(chain);
}
return Combinations;
}

public static List<object[]> GetCombinationsFromIEnumerables(params IEnumerable<object>[] IEnumerables)
{
return GetCombinationsFromIEnumerables(chain = new object[], IEnumerables = IEnumerables.AsEnumerable);
}
</code>```

Easy to use:

```<code>Dim list1 = New String() {"hello", "bonjour", "hallo", "hola"}
Dim list2 = New String() {"Erwin", "Larry", "Bill"}
Dim list3 = New String() {"!", ".."}
Dim result = MyLib.GetCombinationsFromIEnumerables(list1, list2, list3)
For Each r In result
    Debug.Print(String.Join(" "c, r))
Next
</code>```

or in C#:

```<code>object list1 = new string[] {"hello","bonjour","hallo","hola"};
object list2 = new string[] {"Erwin", "Larry", "Bill"};
object list3 = new string[] {"!",".."};
object result = MyLib.GetCombinationsFromIEnumerables(list1, list2, list3);
foreach (r in result) {
Debug.Print(string.Join(' ', r));
}
</code>```

OwnerDisplayName: TaRDy

LastEditorDisplayName: Quintin Robinson

Body:
I have an ArrayList[] myList and I am trying to create a list of all the permutations of the values in the arrays.

EXAMPLE: (all values are strings)

myList[0] = { "1", "5", "3", "9" };
myList[1] = { "2", "3" };
myList[2] = { "93" };

The count of myList can be varied so its length is not known beforehand.

I would like to be able to generate a list of all the permutations similar to the following (but with some additional formatting).

1 2 93
1 3 93
5 2 93
5 3 93
3 2 93
3 3 93
9 2 93
9 3 93

Does this make sense of what I am trying to accomplish?  I can't seem to come up with a good method for doing this, (if any).

Edit:

I am not sure if recursion would interfere with my desire to format the output in my own manner. Sorry I did not mention before what my formatting was.

I want to end up building a string[] array of all the combinations that follows the format like below:

for the "1 2 93" permutation

I want the output to be "val0=1;val1=2;val2=93;"

I will experiment with recursion for now. Thank you DrJokepu

Body:
Here is a generic recursive function that I wrote (and an overload that may be convenient to call):

Public Shared Function GetCombinationsFromIEnumerables(ByRef chain() As Object, ByRef IEnumerables As IEnumerable(Of IEnumerable(Of Object))) As List(Of Object())
    Dim Combinations As New List(Of Object())
    If IEnumerables.Any Then
        For Each v In IEnumerables.First
            Combinations.AddRange(GetCombinationsFromIEnumerables(chain.Concat(New Object() {v}).ToArray, IEnumerables.Skip(1)).ToArray)
        Next
    Else
        Combinations.Add(chain)
    End If
    Return Combinations
End Function

Public Shared Function GetCombinationsFromIEnumerables(ByVal ParamArray IEnumerables() As IEnumerable(Of Object)) As List(Of Object())
    Return GetCombinationsFromIEnumerables(chain:=New Object() {}, IEnumerables:=IEnumerables.AsEnumerable)
End Function

And the equivalent in C#:

public static List<object[]> GetCombinationsFromIEnumerables(ref object[] chain, ref IEnumerable<IEnumerable<object>> IEnumerables)
{
List<object[]> Combinations = new List<object[]>();
if (IEnumerables.Any) {
    foreach ( v in IEnumerables.First) {
        Combinations.AddRange(GetCombinationsFromIEnumerables(chain.Concat(new object[] { v }).ToArray, IEnumerables.Skip(1)).ToArray);
    }
} else {
    Combinations.Add(chain);
}
return Combinations;
}

public static List<object[]> GetCombinationsFromIEnumerables(params IEnumerable<object>[] IEnumerables)
{
return GetCombinationsFromIEnumerables(chain = new object[], IEnumerables = IEnumerables.AsEnumerable);
}

Easy to use:

Dim list1 = New String() {"hello", "bonjour", "hallo", "hola"}
Dim list2 = New String() {"Erwin", "Larry", "Bill"}
Dim list3 = New String() {"!", ".."}
Dim result = MyLib.GetCombinationsFromIEnumerables(list1, list2, list3)
For Each r In result
    Debug.Print(String.Join(" "c, r))
Next

or in C#:

object list1 = new string[] {"hello","bonjour","hallo","hola"};
object list2 = new string[] {"Erwin", "Larry", "Bill"};
object list3 = new string[] {"!",".."};
object result = MyLib.GetCombinationsFromIEnumerables(list1, list2, list3);
foreach (r in result) {
Debug.Print(string.Join(' ', r));
}


问:
How do I create objects with a different number of arguments?
my question is what if I want to create an object that represents a person in a contact list.
The user has to enter a last name, if not, the program won't work.
Besides that the user can enter the first name, the address, phone number and so on, but these aren't necessary.
So how do I tackle these?
I could create a huge amount of constructors with the different parameter combinations, but I don't think that is the right solution.

Can you guys help me out?

答:
You can use different patterns:

JavaBeans (Getters and Setters)

Telescoping constructor (with different number of parameters)

Builder pattern

But non of them will guarantee the user's input you're expecting.

It mostly depends on your UI, and what data may came to you from UI.

If there is possibility that UI can send you nulls, or empty String, you should handle them fro mandatory fields, because it's your business logic, no matter which pattern you're using.

Let's sare you're required to build new Person from the DTOPerson which is came from UI:

```<code>public Person register(Person personDTO) {
    validatePerson(personDTO);
    Person person = new Person(personDTO.getName(), personDTO.getSurname());
    // for not mandatory fields
    person.setAddress(personDTO.getAddress());

    // ...
}

public void validatePerson(Person person) {
    Optional.ofNullable(person.getName()).orElseThrow(() ->
        new IllegalArgumentException("Name is required!")
    );

    Optional.ofNullable(person.getSurname()).orElseThrow(() ->
            new IllegalArgumentException("Surname is required!")
    );
}
</code>```

Body:
You can use different patterns:

JavaBeans (Getters and Setters)

Telescoping constructor (with different number of parameters)

Builder pattern

But non of them will guarantee the user's input you're expecting.

It mostly depends on your UI, and what data may came to you from UI.

If there is possibility that UI can send you nulls, or empty String, you should handle them fro mandatory fields, because it's your business logic, no matter which pattern you're using.

Let's sare you're required to build new Person from the DTOPerson which is came from UI:

public Person register(Person personDTO) {
    validatePerson(personDTO);
    Person person = new Person(personDTO.getName(), personDTO.getSurname());
    // for not mandatory fields
    person.setAddress(personDTO.getAddress());

    // ...
}

public void validatePerson(Person person) {
    Optional.ofNullable(person.getName()).orElseThrow(() ->
        new IllegalArgumentException("Name is required!")
    );

    Optional.ofNullable(person.getSurname()).orElseThrow(() ->
            new IllegalArgumentException("Surname is required!")
    );
}


问:
How to code "a[i]=b[c[i]]" on ARM NEON SIMD Intrinsic function
I'm trying to translating this C/C++ code to SIMD Intrinsic function.

```<code>for(int i=0 ; i < length ; i++)
    A[i] = B[C[i]];
</code>```

I can translate below code (C/C++)

```<code>for(int i=0 ; i < length ; i++)
    A[i] = B[i];
</code>```

to SIMD code (using Intrinsic function)

```<code>for(int i=0 ; i < length-16 ; i+=16) {
    uint8x16_t v0 = vld1q_u8(A+i);
    vst1q_u8(A+i, v0);
}
</code>```

I know that keyword is interleaving to solve this problem. But i can't find solution.

Thanks.

Edit

For more information

```<code>unsigned char A [32] = {0,}; // Output Array
unsigned char B [20] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}; // An array with values to pass to A Array
unsigned int C [32] = {19,15,11,10,5,3,6,4,5,19,10,14,16,14,8,9,10,20,11,1, 0, 3, 5, 19, 20, 11, 13, 9, 30, 31, 7}; // An array with the index information of the B array.
</code>```

Is there any Intrinsic function that can make the following code form?

```<code>int length = 32;
For (int i = 0; i < length-8; i+=8)
{
    Uint8x8_t v_idx = vld1_u8 (C + i);
    Uint8x8_t v = func (A, v_idx); // func (uint8_t, uint32x4_t)
    vst1_u8(C+i, v);
}
</code>```

Will output 20, 16, 12, 11, 6, 4, 7, 5, 6, 6, 20, 11, 15, 17, 15, 9, 10, 11, 21, 12, 2, 1, 4, 6, 20, 21, 12, 14, 10, 31, 32, 8

[Note]

A and B are uint8_t * types because they are images with values between 0 and 255, and C is a uint32_t * type because they are indexed by B index.

答:
It's a bit hard to be sure since you didn't provide a lot of information, but vqtbl1_u8 might be what you're looking for.  It's AArch64-only, though vtbl1_u8 is available on armv7.

A quick example:

```<code>int main (void) {
  uint8_t bp[] = { 1,  1,  2,  3,  5,  8, 13, 21 };
  uint8_t cp[] = { 0,  2,  4,  6,  1,  3,  5,  7 };

  uint8x8_t b = vld1_u8(bp);
  uint8x8_t c = vld1_u8(cp);

  uint8x8_t a = vtbl1_u8(b, c);
  uint8_t ap[8];
  vst1_u8(ap, a);

  for (int x = 0 ; x < 8 ; x++)
    printf("%3u ", ap[x]);
  printf("\n");

  return 0;
}
</code>```

Will output 1   2   5  13   1   3   8  21

Body:
I'm trying to translating this C/C++ code to SIMD Intrinsic function.

for(int i=0 ; i < length ; i++)
    A[i] = B[C[i]];

I can translate below code (C/C++)

for(int i=0 ; i < length ; i++)
    A[i] = B[i];

to SIMD code (using Intrinsic function)

for(int i=0 ; i < length-16 ; i+=16) {
    uint8x16_t v0 = vld1q_u8(A+i);
    vst1q_u8(A+i, v0);
}

I know that keyword is interleaving to solve this problem. But i can't find solution.

Thanks.

Edit

For more information

unsigned char A [32] = {0,}; // Output Array
unsigned char B [20] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}; // An array with values to pass to A Array
unsigned int C [32] = {19,15,11,10,5,3,6,4,5,19,10,14,16,14,8,9,10,20,11,1, 0, 3, 5, 19, 20, 11, 13, 9, 30, 31, 7}; // An array with the index information of the B array.

Is there any Intrinsic function that can make the following code form?

int length = 32;
For (int i = 0; i < length-8; i+=8)
{
    Uint8x8_t v_idx = vld1_u8 (C + i);
    Uint8x8_t v = func (A, v_idx); // func (uint8_t, uint32x4_t)
    vst1_u8(C+i, v);
}

Will output 20, 16, 12, 11, 6, 4, 7, 5, 6, 6, 20, 11, 15, 17, 15, 9, 10, 11, 21, 12, 2, 1, 4, 6, 20, 21, 12, 14, 10, 31, 32, 8

[Note]

A and B are uint8_t * types because they are images with values between 0 and 255, and C is a uint32_t * type because they are indexed by B index.

Body:
It's a bit hard to be sure since you didn't provide a lot of information, but vqtbl1_u8 might be what you're looking for.  It's AArch64-only, though vtbl1_u8 is available on armv7.

A quick example:

int main (void) {
  uint8_t bp[] = { 1,  1,  2,  3,  5,  8, 13, 21 };
  uint8_t cp[] = { 0,  2,  4,  6,  1,  3,  5,  7 };

  uint8x8_t b = vld1_u8(bp);
  uint8x8_t c = vld1_u8(cp);

  uint8x8_t a = vtbl1_u8(b, c);
  uint8_t ap[8];
  vst1_u8(ap, a);

  for (int x = 0 ; x < 8 ; x++)
    printf("%3u ", ap[x]);
  printf("\n");

  return 0;
}

Will output 1   2   5  13   1   3   8  21


答:
A solution would be to use some kind of css grid system, many layout frameworks such as bootstrap implement one. A basic implementation could look like this:

```<code><div class="row">
    <div class="col s3"></div>
    <div class="col s6">Bet</div>
    <div class="col s3"></div>
</div>
<div class="row">
    <div class="col s3"></div>
    <div class="col s6"><input id="userbet" onchange="checkBet()" value="1" type="text" name="bet"></div>
    <div class="col s3"><div class="beterror" id="beterror">That is not a valid bet.</div></div>
</div>
[...more div.row tupels]
</code>```

And as simple grid implementation:

```<code>.row .col.s3 {width: 25%; float:left;}
.row .col.s6 {width: 50%; float:left;}
</code>```

Title: How can I make my error message show to the right of my input button?

Body:
I'll try to explain this best as possible with pictures.

Here is my input button (look at the one under "bet"):

I want the error message to appear here:

However, all my attempts end up like this:

How can I do this? I tried multiple things such as span, inline display, etc.

UPDATE:

Posted full front-end code on github.

CSS: https://gist.github.com/xxFlare/41ed6a1cac81bbda48848d55a716c3dd

HTML: https://gist.github.com/xxFlare/300733b8b848aea829fc6b26ac70eda2

Body:
A solution would be to use some kind of css grid system, many layout frameworks such as bootstrap implement one. A basic implementation could look like this:

<div class="row">
    <div class="col s3"></div>
    <div class="col s6">Bet</div>
    <div class="col s3"></div>
</div>
<div class="row">
    <div class="col s3"></div>
    <div class="col s6"><input id="userbet" onchange="checkBet()" value="1" type="text" name="bet"></div>
    <div class="col s3"><div class="beterror" id="beterror">That is not a valid bet.</div></div>
</div>
[...more div.row tupels]

And as simple grid implementation:

.row .col.s3 {width: 25%; float:left;}
.row .col.s6 {width: 50%; float:left;}


问:
Carriage return without line break on windows
So I have this simple statusbar implementation:

```<code>def status_update(current, top, label="Progress"):
    workdone = current/top
    print("\r{0:s}: [{1:30s}] {2:.1f}%".format(label,'#' * int(workdone * 30), workdone*100), end="", flush=True)
    if workdone == 1:
        print()
</code>```

Works as expected on linux.

On Windows (10, in my case), however, \r apparently creates a new line for each output instead of overwriting the preceding.

How do I stop that? (Preferably in a way that does not break linux compatibility.)

答:
This might not be best way to do this, but works. Just use \b.

```<code>def status_update(current, top, label="Progress"):
    workdone = current/top
    if not hasattr(status_update, "length"):
        status_update.length = 0
    str1="{0:s}: [{1:30s}] {2:.1f}%".format(label,'#' * int(workdone * 30), workdone*100)
    print(('\b'*status_update.length)+str1, end="", flush=True)
    status_update.length=len(str1)
    if workdone == 1:
        print()
</code>```

here I'm backspacing number of characters printed in last call of status_update

Body:
So I have this simple statusbar implementation:

def status_update(current, top, label="Progress"):
    workdone = current/top
    print("\r{0:s}: [{1:30s}] {2:.1f}%".format(label,'#' * int(workdone * 30), workdone*100), end="", flush=True)
    if workdone == 1:
        print()

Works as expected on linux.

On Windows (10, in my case), however, \r apparently creates a new line for each output instead of overwriting the preceding.

How do I stop that? (Preferably in a way that does not break linux compatibility.)

Body:
This might not be best way to do this, but works. Just use \b.

def status_update(current, top, label="Progress"):
    workdone = current/top
    if not hasattr(status_update, "length"):
        status_update.length = 0
    str1="{0:s}: [{1:30s}] {2:.1f}%".format(label,'#' * int(workdone * 30), workdone*100)
    print(('\b'*status_update.length)+str1, end="", flush=True)
    status_update.length=len(str1)
    if workdone == 1:
        print()

here I'm backspacing number of characters printed in last call of status_update


问:
Solving a logic riddle in Prolog
I'm in the "early phase" of learning prolog and came across a logic riddle that seams easy to implement:

Link to the riddle | Link to solution

We are looking for the 10-digit number which satisfies the following conditions:

All digits from 0-9 occur exactly once.

The first 2 digits are divisible by 2.

The first 3 digits are divisible by 3.

...

The first 10 digits are divisible by 10.

I think I would first need to implement the rules to the .pl file right?
The rules from the solution are:

An integer can be divided by 1 without remainder.

An integer is divisible by 2 without remainder, if the last digit is straight.

An integer can be divided by 3 without a remainder if its transverse sum is divisible by 3.

An integer can be divided by 4 without a remainder if the last two digits are divisible by 4.

An integer is divisible by 5 if the last digit is divisible by 5.

An integer is divisible by 6 without a remainder if its transverse sum is divisible by 3 and the last digit by 2.

An integer is divisible by 8 without a remainder if the last three digits are divisible by 8.

An integer is divisible by 9 without a remainder if its transverse sum is divisible by 9.

An integer is divisible by 10 without a remainder if the last digit is a 0.

I read multiple introductions to rules in prolog but still dont get how do it. Can anyone help? Would be great :)

答:
Since you have tagged this with clpfd, I would like to augment the existing answer with additional information about constraints.

Importantly, constraints let you often avoid the generation of all combinations by pruning the search space for you.

We can start by relating a list of digits to the integer described by these digits:

```
digits_integer(Ds0, I) :-
        reverse(Ds0, Ds),
        Ds0 ins 0..9,
        foldl(pow, Ds, 0-0, I-_).

pow(D, I0-P0, I-P) :-
        I #= I0 + D*10^P0,
        P #= P0 + 1.
```

Here are two example queries:

```
?- digits_integer([1,2,3], I).
<b>I = 123.</b>

?- digits_integer(Ds, 302).
<b>Ds = [3, 0, 2] .</b>
```

Next, let us describe that a prefix of length N of the list Ls is divisible by N:

```
n_divisible(Ls, N) :-
        length(Prefix, N),
        append(Prefix, _, Ls),
        digits_integer(Prefix, I),
        I mod N #= 0.
```

The whole solution can thus be described as:

```
solution(Ds) :-
        length(Ds, 10),
        Ds ins 0..9,
        all_distinct(Ds),
        E in 2..10,
        findall(E, indomain(E), Es),
        maplist(n_divisible(Ds), Es).
```

Sample query:

```
?- solution(Ds), label(Ds).
<b>Ds = [3, 8, 1, 6, 5, 4, 7, 2, 9, 0] ;</b>
false.
```

Let us briefly compare the performance of the two solutions:

```
?- time((puzzle(Vs),false)).
% 142,709,119 inferences, 14.865 CPU in <b>14.867</b> seconds
```

vs.:

```
?- time((solution(Ds),label(Ds),false)).
% 19,384,173 inferences, 2.166 CPU in <b>2.166 seconds</b>
```

Thus, the constraint-based approach is several times faster in this concrete case. This is mostly due to the power of constraint propagation, which the solver performs automatically.

Title: Solving a logic riddle in Prolog

Body:
Since you have tagged this with clpfd, I would like to augment the existing answer with additional information about constraints.

Importantly, constraints let you often avoid the generation of all combinations by pruning the search space for you.

We can start by relating a list of digits to the integer described by these digits:

digits_integer(Ds0, I) :-
        reverse(Ds0, Ds),
        Ds0 ins 0..9,
        foldl(pow, Ds, 0-0, I-_).

pow(D, I0-P0, I-P) :-
        I #= I0 + D*10^P0,
        P #= P0 + 1.

Here are two example queries:

?- digits_integer([1,2,3], I).
I = 123.

?- digits_integer(Ds, 302).
Ds = [3, 0, 2] .

Next, let us describe that a prefix of length N of the list Ls is divisible by N:

n_divisible(Ls, N) :-
        length(Prefix, N),
        append(Prefix, _, Ls),
        digits_integer(Prefix, I),
        I mod N #= 0.

The whole solution can thus be described as:

solution(Ds) :-
        length(Ds, 10),
        Ds ins 0..9,
        all_distinct(Ds),
        E in 2..10,
        findall(E, indomain(E), Es),
        maplist(n_divisible(Ds), Es).

Sample query:

?- solution(Ds), label(Ds).
Ds = [3, 8, 1, 6, 5, 4, 7, 2, 9, 0] ;
false.

Let us briefly compare the performance of the two solutions:

?- time((puzzle(Vs),false)).
% 142,709,119 inferences, 14.865 CPU in 14.867 seconds

vs.:

?- time((solution(Ds),label(Ds),false)).
% 19,384,173 inferences, 2.166 CPU in 2.166 seconds

Thus, the constraint-based approach is several times faster in this concrete case. This is mostly due to the power of constraint propagation, which the solver performs automatically.