问:
Real-time retrieval of selected range in spreadsheet using GAS
I have a apps script UI modal dialog with textbox and pick button. When I press pick button and select the range of cells in sheets, then it has to copy sheet range address location identified by sheet(0) or sheet(1). Any thoughts? </p>

答:
Cut or Copy and Paste

This is a cut and paste or copy and paste that use a modeless dialog so that you can make the selection even when the dialog is active.

```<code>function onOpen()
{
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('My Tools')
        .addItem('Copy or Cut', 'copyFromToSetupUi')
        .addItem('Display Properties','dispProperties')
        .addItem('Clear Ranges','clearCopyProperties')
        .addToUi();
}

function dispProperties()
{
  var copyProperties = PropertiesService.getDocumentProperties();
  var srcShtNameStr = copyProperties.getProperty('SourceSheetName');
  var srcShtRangeStr = copyProperties.getProperty('SourceSheetRange');
  var desShtNameStr = copyProperties.getProperty('DestinationSheetName');
  var desShtRangeStr = copyProperties.getProperty('DestinationSheetRange');
  var title = 'Copy From To Sheets Properties';
  var msg = 'Source Sheet Name = ' + srcShtNameStr + '<br />';
  msg += 'Source Sheet Range = ' + srcShtRangeStr + '<br />';
  msg += 'Destination Sheet Range = ' + desShtNameStr + '<br />';
  msg += 'Destination Sheet Range = ' + desShtRangeStr + '<br />';
  msg += '<input type="button" value="Exit" onClick="google.script.host.close();" />';
  dispStatus(title,msg);
}

function copyFromToSheets()
{
  var copyProperties = PropertiesService.getDocumentProperties();
  var srcRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(copyProperties.getProperty('SourceSheetName')).getRange(copyProperties.getProperty('SourceSheetRange'));
  var srcA = srcRange.getValues();
  srcRange.setBackground('#ffffff');
  var desRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(copyProperties.getProperty('DestinationSheetName')).getRange(copyProperties.getProperty('DestinationSheetRange'));
  desRange.setValues(srcA);
  desRange.setBackground('#ffffff');
}

function cutnpasteFromToSheets()
{
  var copyProperties = PropertiesService.getDocumentProperties();
  var srcRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(copyProperties.getProperty('SourceSheetName')).getRange(copyProperties.getProperty('SourceSheetRange'));
  var srcA = srcRange.getValues();
  srcRange.clearContent();
  srcRange.setBackground('#ffffff');
  var desRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(copyProperties.getProperty('DestinationSheetName')).getRange(copyProperties.getProperty('DestinationSheetRange'));
  desRange.setValues(srcA);
  desRange.setBackground('#ffffff');
}

function setCopySource()
{
  var srcShtName = SpreadsheetApp.getActiveSheet().getName();
  var srcShtRange = SpreadsheetApp.getActiveRange();
  var copyProperties = PropertiesService.getDocumentProperties();
  copyProperties.setProperty('SourceSheetRange', srcShtRange.getA1Notation());
  copyProperties.setProperty('SourceSheetName', srcShtName);
  srcShtRange.setBackground('#d9caa9');
}

function setCopyDestination()
{
  var desShtName = SpreadsheetApp.getActiveSheet().getName();
  var desShtRange = SpreadsheetApp.getActiveRange();
  var copyProperties = PropertiesService.getDocumentProperties();
  copyProperties.setProperty('DestinationSheetRange',desShtRange.getA1Notation());
  copyProperties.setProperty('DestinationSheetName', desShtName);
  desShtRange.setBackground('#c4df87');
}

function clearCopyProperties()
{
  var copyProperties = PropertiesService.getDocumentProperties();
  var srcShtNameStr = copyProperties.getProperty('SourceSheetName');
  var srcShtRangeStr = copyProperties.getProperty('SourceSheetRange');
  var desShtNameStr = copyProperties.getProperty('DestinationSheetName');
  var desShtRangeStr = copyProperties.getProperty('DestinationSheetRange');
  if(srcShtNameStr && srcShtRangeStr)
  {
    var srcShtRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(srcShtNameStr).getRange(srcShtRangeStr);
    srcShtRange.setBackground('#ffffff');
  }
  else
  {
    SpreadsheetApp.getUi().alert('At least one of the Source String Properties is undefined in clearCopyProperties so background color cannot be reset.');
  }
  if(desShtNameStr && desShtRangeStr)
  {
    var desShtRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(desShtNameStr).getRange(desShtRangeStr);
    desShtRange.setBackground('#ffffff');
  }
  else
  {
    SpreadsheetApp.getUi().alert('At least one of the Destination String Properties is undefined in clearCopyProperties so background color cannot be reset.');
  }
  copyProperties.setProperty('SourceSheetName', '');
  copyProperties.setProperty('SourceSheetRange', '');
  copyProperties.setProperty('DestinationSheetName', '');
  copyProperties.setProperty('DestinationSheetRange', '');
}

function copyFromToSetupUi()
{
  var copyProperties = PropertiesService.getDocumentProperties();
  var srcShtNameStr = copyProperties.getProperty('SourceSheetName');
  var srcShtRangeStr = copyProperties.getProperty('SourceSheetRange');
  var desShtNameStr = copyProperties.getProperty('DestinationSheetName');
  var desShtRangeStr = copyProperties.getProperty('DestinationSheetRange');
  var title='No Title';
  var msg = 'No Text';
  if(!srcShtNameStr || !srcShtRangeStr )  //if !src
  {
    title = 'Select Source Range';
    msg = '<p>Please select input range from <strong>Source Sheet.</strong> and then press "Source Range Selected" button below.</p>\
    <br /><input type="button" value="Source Range Selected" onclick="google.script.run.copyFromToSetupHelper(1);google.script.host.close();" />';
    msg += '<script>console.log(\'flag1\');</script>';
    dispStatus(title, msg);
  }
  if ((srcShtNameStr && srcShtRangeStr) && (!desShtNameStr || !desShtRangeStr)) //if src and !des
  {
      var srcShtRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(srcShtNameStr).getRange(srcShtRangeStr);
      title = 'Select Destination Range';
      msg = '<p>Please select a destination range which is ' + srcShtRange.getNumRows() + ' rows by ' + srcShtRange.getNumColumns() + ' columns.</p>';
      msg += '<br /><input type="button" value="Destination Range Selected" onclick="google.script.run.copyFromToSetupHelper(2);google.script.host.close();" />';
      msg += '<br />Input Range: ' + srcShtRangeStr + '<br /><input type="button" value="Clear Ranges and Start Over" onClick="google.script.run.clearCopyProperties();google.script.host.close(); />';
      dispStatus(title, msg);
  }
  if((srcShtNameStr && srcShtRangeStr) && (desShtNameStr && desShtRangeStr))//if src and des
  {
    var srcShtRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(srcShtNameStr).getRange(srcShtRangeStr);
    var desShtRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(desShtNameStr).getRange(desShtRangeStr);
    if((desShtRange.getWidth()===srcShtRange.getWidth()) && (desShtRange.getHeight()===srcShtRange.getHeight()))
    {
      title= 'Displaying Source and Destination Ranges';
      msg = '<br />Source Sheet/Range: ' + srcShtNameStr + '/' + srcShtRangeStr + '<br />Destination Sheet/Range: ' + desShtNameStr + '/' + desShtRangeStr + '<br />';
      msg += '<br /><input type="button" value="Perform Copy" onclick="google.script.run.copyFromToSheets();google.script.host.close();" />';
      msg += '<br /><input type="button" value="Perform Cut & Paste" onclick="google.script.run.cutnpasteFromToSheets();google.script.host.close();" />';
      msg += '<br /><input type="button" value="Keep both Ranges Defined" onclick="google.script.host.close();" />';
      msg += '<br /><input type="button" value="Clear Ranges and Start Over" onclick="google.script.run.clearCopyProperties();google.script.host.close();" />';
      dispStatus(title,msg);
    }
    else
    {
      var srcShtRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(srcShtNameStr).getRange(srcShtRangeStr);
      var desShtRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(desShtNameStr).getRange(desShtRangeStr);
      var newdesShtRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(desShtNameStr).getRange(desShtRange.getRow(), desShtRange.getColumn(), srcShtRange.getNumRows(), srcShtRange.getNumColumns());
      desShtRange.setBackground('white');
      newdesShtRange.setBackground('#c4df87');
      copyProperties.setProperty('DestinationSheetRange', newdesShtRange.getA1Notation());
      title = 'Destination Range Adjusted';

      msg = 'Source Range and Destination Range Dimension did not Match. So it was assumed that the upper left corner of the Destination Range is correct';
      msg += 'and that the Sheet Selections were correct. The Destination Range was modified to have the same dimensions as the Source Range. ';
      msg += '<br />Source Sheet/Range: ' + srcShtNameStr + '/' + srcShtRangeStr + '<br />Destination Sheet/Range: ' + desShtNameStr + '/' + newdesShtRange.getA1Notation() + '<br />';
      msg += '<br /><input type="button" value="Perform Copy" onclick="google.script.run.copyFromToSheets();google.script.host.close();" />';
      msg += '<br /><input type="button" value="Perform Cut & Paste" onclick="google.script.run.cutnpasteFromToSheets();google.script.host.close();" />';
      msg += '<br /><input type="button" value="Keep both Ranges Defined" onclick="google.script.host.close();" />';
      msg += '<br /><input type="button" value="Clear Ranges and Start Over" onclick="google.script.run.clearCopyProperties();;google.script.host.close(); />';
      dispStatus(title,msg);

    }

  }
}

function copyFromToSetupHelper(mode)
{
  var mode = (typeof(mode) !== 'undefined')? mode : 0;
  switch(mode)
  {
    case 1:
      setCopySource();
      copyFromToSetupUi();
      break;
    case 2:
      setCopyDestination();
      copyFromToSetupUi();
      break;
    default:
      clearCopyProperties();
  }
}
</code>```

Here's the the dispStatus dialog.

```<code>function dispStatus(title,html,width,height)
{
  var title = typeof(title) !== 'undefined' ? title : 'No Title Provided';
  var width = typeof(width) !== 'undefined' ? width : 400;
  var height = typeof(height) !== 'undefined' ? height : 300;
  var html = typeof(html) !== 'undefined' ? html : '<p>No html provided.</p>';
  var htmlOutput = HtmlService
     .createHtmlOutput(html)
     .setWidth(width)
     .setHeight(height);
 SpreadsheetApp.getUi().showModelessDialog(htmlOutput, title);
}
</code>```

Body:
Cut or Copy and Paste

This is a cut and paste or copy and paste that use a modeless dialog so that you can make the selection even when the dialog is active.

function onOpen()
{
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('My Tools')
        .addItem('Copy or Cut', 'copyFromToSetupUi')
        .addItem('Display Properties','dispProperties')
        .addItem('Clear Ranges','clearCopyProperties')
        .addToUi();
}

function dispProperties()
{
  var copyProperties = PropertiesService.getDocumentProperties();
  var srcShtNameStr = copyProperties.getProperty('SourceSheetName');
  var srcShtRangeStr = copyProperties.getProperty('SourceSheetRange');
  var desShtNameStr = copyProperties.getProperty('DestinationSheetName');
  var desShtRangeStr = copyProperties.getProperty('DestinationSheetRange');
  var title = 'Copy From To Sheets Properties';
  var msg = 'Source Sheet Name = ' + srcShtNameStr + '<br />';
  msg += 'Source Sheet Range = ' + srcShtRangeStr + '<br />';
  msg += 'Destination Sheet Range = ' + desShtNameStr + '<br />';
  msg += 'Destination Sheet Range = ' + desShtRangeStr + '<br />';
  msg += '<input type="button" value="Exit" onClick="google.script.host.close();" />';
  dispStatus(title,msg);
}

function copyFromToSheets()
{
  var copyProperties = PropertiesService.getDocumentProperties();
  var srcRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(copyProperties.getProperty('SourceSheetName')).getRange(copyProperties.getProperty('SourceSheetRange'));
  var srcA = srcRange.getValues();
  srcRange.setBackground('#ffffff');
  var desRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(copyProperties.getProperty('DestinationSheetName')).getRange(copyProperties.getProperty('DestinationSheetRange'));
  desRange.setValues(srcA);
  desRange.setBackground('#ffffff');
}

function cutnpasteFromToSheets()
{
  var copyProperties = PropertiesService.getDocumentProperties();
  var srcRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(copyProperties.getProperty('SourceSheetName')).getRange(copyProperties.getProperty('SourceSheetRange'));
  var srcA = srcRange.getValues();
  srcRange.clearContent();
  srcRange.setBackground('#ffffff');
  var desRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(copyProperties.getProperty('DestinationSheetName')).getRange(copyProperties.getProperty('DestinationSheetRange'));
  desRange.setValues(srcA);
  desRange.setBackground('#ffffff');
}

function setCopySource()
{
  var srcShtName = SpreadsheetApp.getActiveSheet().getName();
  var srcShtRange = SpreadsheetApp.getActiveRange();
  var copyProperties = PropertiesService.getDocumentProperties();
  copyProperties.setProperty('SourceSheetRange', srcShtRange.getA1Notation());
  copyProperties.setProperty('SourceSheetName', srcShtName);
  srcShtRange.setBackground('#d9caa9');
}

function setCopyDestination()
{
  var desShtName = SpreadsheetApp.getActiveSheet().getName();
  var desShtRange = SpreadsheetApp.getActiveRange();
  var copyProperties = PropertiesService.getDocumentProperties();
  copyProperties.setProperty('DestinationSheetRange',desShtRange.getA1Notation());
  copyProperties.setProperty('DestinationSheetName', desShtName);
  desShtRange.setBackground('#c4df87');
}

function clearCopyProperties()
{
  var copyProperties = PropertiesService.getDocumentProperties();
  var srcShtNameStr = copyProperties.getProperty('SourceSheetName');
  var srcShtRangeStr = copyProperties.getProperty('SourceSheetRange');
  var desShtNameStr = copyProperties.getProperty('DestinationSheetName');
  var desShtRangeStr = copyProperties.getProperty('DestinationSheetRange');
  if(srcShtNameStr && srcShtRangeStr)
  {
    var srcShtRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(srcShtNameStr).getRange(srcShtRangeStr);
    srcShtRange.setBackground('#ffffff');
  }
  else
  {
    SpreadsheetApp.getUi().alert('At least one of the Source String Properties is undefined in clearCopyProperties so background color cannot be reset.');
  }
  if(desShtNameStr && desShtRangeStr)
  {
    var desShtRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(desShtNameStr).getRange(desShtRangeStr);
    desShtRange.setBackground('#ffffff');
  }
  else
  {
    SpreadsheetApp.getUi().alert('At least one of the Destination String Properties is undefined in clearCopyProperties so background color cannot be reset.');
  }
  copyProperties.setProperty('SourceSheetName', '');
  copyProperties.setProperty('SourceSheetRange', '');
  copyProperties.setProperty('DestinationSheetName', '');
  copyProperties.setProperty('DestinationSheetRange', '');
}

function copyFromToSetupUi()
{
  var copyProperties = PropertiesService.getDocumentProperties();
  var srcShtNameStr = copyProperties.getProperty('SourceSheetName');
  var srcShtRangeStr = copyProperties.getProperty('SourceSheetRange');
  var desShtNameStr = copyProperties.getProperty('DestinationSheetName');
  var desShtRangeStr = copyProperties.getProperty('DestinationSheetRange');
  var title='No Title';
  var msg = 'No Text';
  if(!srcShtNameStr || !srcShtRangeStr )  //if !src
  {
    title = 'Select Source Range';
    msg = '<p>Please select input range from <strong>Source Sheet.</strong> and then press "Source Range Selected" button below.</p>\
    <br /><input type="button" value="Source Range Selected" onclick="google.script.run.copyFromToSetupHelper(1);google.script.host.close();" />';
    msg += '<script>console.log(\'flag1\');</script>';
    dispStatus(title, msg);
  }
  if ((srcShtNameStr && srcShtRangeStr) && (!desShtNameStr || !desShtRangeStr)) //if src and !des
  {
      var srcShtRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(srcShtNameStr).getRange(srcShtRangeStr);
      title = 'Select Destination Range';
      msg = '<p>Please select a destination range which is ' + srcShtRange.getNumRows() + ' rows by ' + srcShtRange.getNumColumns() + ' columns.</p>';
      msg += '<br /><input type="button" value="Destination Range Selected" onclick="google.script.run.copyFromToSetupHelper(2);google.script.host.close();" />';
      msg += '<br />Input Range: ' + srcShtRangeStr + '<br /><input type="button" value="Clear Ranges and Start Over" onClick="google.script.run.clearCopyProperties();google.script.host.close(); />';
      dispStatus(title, msg);
  }
  if((srcShtNameStr && srcShtRangeStr) && (desShtNameStr && desShtRangeStr))//if src and des
  {
    var srcShtRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(srcShtNameStr).getRange(srcShtRangeStr);
    var desShtRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(desShtNameStr).getRange(desShtRangeStr);
    if((desShtRange.getWidth()===srcShtRange.getWidth()) && (desShtRange.getHeight()===srcShtRange.getHeight()))
    {
      title= 'Displaying Source and Destination Ranges';
      msg = '<br />Source Sheet/Range: ' + srcShtNameStr + '/' + srcShtRangeStr + '<br />Destination Sheet/Range: ' + desShtNameStr + '/' + desShtRangeStr + '<br />';
      msg += '<br /><input type="button" value="Perform Copy" onclick="google.script.run.copyFromToSheets();google.script.host.close();" />';
      msg += '<br /><input type="button" value="Perform Cut & Paste" onclick="google.script.run.cutnpasteFromToSheets();google.script.host.close();" />';
      msg += '<br /><input type="button" value="Keep both Ranges Defined" onclick="google.script.host.close();" />';
      msg += '<br /><input type="button" value="Clear Ranges and Start Over" onclick="google.script.run.clearCopyProperties();google.script.host.close();" />';
      dispStatus(title,msg);
    }
    else
    {
      var srcShtRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(srcShtNameStr).getRange(srcShtRangeStr);
      var desShtRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(desShtNameStr).getRange(desShtRangeStr);
      var newdesShtRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(desShtNameStr).getRange(desShtRange.getRow(), desShtRange.getColumn(), srcShtRange.getNumRows(), srcShtRange.getNumColumns());
      desShtRange.setBackground('white');
      newdesShtRange.setBackground('#c4df87');
      copyProperties.setProperty('DestinationSheetRange', newdesShtRange.getA1Notation());
      title = 'Destination Range Adjusted';

      msg = 'Source Range and Destination Range Dimension did not Match. So it was assumed that the upper left corner of the Destination Range is correct';
      msg += 'and that the Sheet Selections were correct. The Destination Range was modified to have the same dimensions as the Source Range. ';
      msg += '<br />Source Sheet/Range: ' + srcShtNameStr + '/' + srcShtRangeStr + '<br />Destination Sheet/Range: ' + desShtNameStr + '/' + newdesShtRange.getA1Notation() + '<br />';
      msg += '<br /><input type="button" value="Perform Copy" onclick="google.script.run.copyFromToSheets();google.script.host.close();" />';
      msg += '<br /><input type="button" value="Perform Cut & Paste" onclick="google.script.run.cutnpasteFromToSheets();google.script.host.close();" />';
      msg += '<br /><input type="button" value="Keep both Ranges Defined" onclick="google.script.host.close();" />';
      msg += '<br /><input type="button" value="Clear Ranges and Start Over" onclick="google.script.run.clearCopyProperties();;google.script.host.close(); />';
      dispStatus(title,msg);

    }

  }
}

function copyFromToSetupHelper(mode)
{
  var mode = (typeof(mode) !== 'undefined')? mode : 0;
  switch(mode)
  {
    case 1:
      setCopySource();
      copyFromToSetupUi();
      break;
    case 2:
      setCopyDestination();
      copyFromToSetupUi();
      break;
    default:
      clearCopyProperties();
  }
}

Here's the the dispStatus dialog.

function dispStatus(title,html,width,height)
{
  var title = typeof(title) !== 'undefined' ? title : 'No Title Provided';
  var width = typeof(width) !== 'undefined' ? width : 400;
  var height = typeof(height) !== 'undefined' ? height : 300;
  var html = typeof(html) !== 'undefined' ? html : '<p>No html provided.</p>';
  var htmlOutput = HtmlService
     .createHtmlOutput(html)
     .setWidth(width)
     .setHeight(height);
 SpreadsheetApp.getUi().showModelessDialog(htmlOutput, title);
}


来源: stackexchange

问:
JQuery Ajax gives error on sending multiple data

name = "name1";
uname = "username";
pass = "password";
$.ajax({
  type: 'POST',
  url: "url",
  data: {
    name: name,
    username: uname,
    password: pass
  },
  success: function(data, textStatus, jqXHR) {
    alert(data);
  },
  error: function(jqXHR, textStatus, errorThrown) {
    alert("Error");
  }

});
```

This code gives an error while running :

Uncaught TypeError: Illegal invocation

But if I change the number of parameters at data to 1, it runs fine.
I tried to specify datatype, but to no avail

答: I think your data is array and not text. Try checking it again, I ran into a same issue some time ago.</p>

ContentLicense: CC BY-SA 3.0

Body:
name = "name1";
uname = "username";
pass = "password";
$.ajax({
  type: 'POST',
  url: "url",
  data: {
    name: name,
    username: uname,
    password: pass
  },
  success: function(data, textStatus, jqXHR) {
    alert(data);
  },
  error: function(jqXHR, textStatus, errorThrown) {
    alert("Error");
  }

});

This code gives an error while running :

Uncaught TypeError: Illegal invocation

But if I change the number of parameters at data to 1, it runs fine.
I tried to specify datatype, but to no avail


问:
How to convert this query to doctrine DQL
```<code>SELECT apntoken,deviceid,created
FROM `distribution_mobiletokens` as dm
WHERE userid='20'
and not exists (
    select 1
    from `distribution_mobiletokens`
    where userid = '20'
    and deviceid = dm.deviceid
    and created > dm.created
    )
</code>```

What this query does is selects all mobiletokens where the user id is equal to 20 and the deviceid is the same but chooses the newest apntoken for the device.

My database looks like below.

For more information on this query, I got this answer from another question I asked here(How to group by in SQL by largest date (Order By a Group By))

Things I've Tried

```<code>$mobiletokens = $em->createQueryBuilder()
          ->select('u.id,company.id as companyid,user.id as userid,u.apntoken')
          ->from('AppBundle:MobileTokens', 'u')
          ->leftJoin('u.companyId', 'company')
          ->leftJoin('u.userId', 'user')
          ->where('u.status = 1 and user.id = :userid')
          ->setParameter('userid',(int)$jsondata['userid'])
          ->groupby('u.apntoken')
          ->getQuery()
          ->getResult();

       //@JA - Get the list of all the apn tokens we need to send the message to.
       foreach($mobiletokens as $tokenobject){
           $deviceTokens[] = $tokenobject["apntoken"];
           echo $tokenobject["apntoken"]."\n";
       }

        die();
</code>```

This gives me the incorrect response of

```<code>63416A61F2FD47CC7B579CAEACB002CB00FACC3786A8991F329BB41B1208C4BA
9B25BBCC3F3D2232934D86A7BC72967A5546B250281FB750FFE645C8EB105AF6
latestone
</code>```

Any help here is appreciated!

Other Information

Data with SELECT * FROM

Data after using the SQL I provided up top.

答:
I did this for now as a temporary fix, not sure if this is best answer though.</p>

```<code>$em = $this->em;

       $connection = $em->getConnection();
       $statement = $connection->prepare("
            SELECT apntoken,deviceid,created
            FROM `distribution_mobiletokens` as dm
            WHERE userid=:userid
            and not exists (
                select 1
                from `distribution_mobiletokens`
                where userid = :userid
                and deviceid = dm.deviceid
                and created > dm.created
            )");
       $statement->bindValue('userid', $jsondata['userid']);
       $statement->execute();

       $mobiletokens = $statement->fetchAll();

       //@JA - Get the list of all the apn tokens we need to send the message to.
       foreach($mobiletokens as $tokenobject){
           $deviceTokens[] = $tokenobject["apntoken"];
           echo $tokenobject["apntoken"]."\n";
       }
</code>```

Body:
SELECT apntoken,deviceid,created
FROM `distribution_mobiletokens` as dm
WHERE userid='20'
and not exists (
    select 1
    from `distribution_mobiletokens`
    where userid = '20'
    and deviceid = dm.deviceid
    and created > dm.created
    )

What this query does is selects all mobiletokens where the user id is equal to 20 and the deviceid is the same but chooses the newest apntoken for the device.

My database looks like below.

For more information on this query, I got this answer from another question I asked here(How to group by in SQL by largest date (Order By a Group By))

Things I've Tried

$mobiletokens = $em->createQueryBuilder()
          ->select('u.id,company.id as companyid,user.id as userid,u.apntoken')
          ->from('AppBundle:MobileTokens', 'u')
          ->leftJoin('u.companyId', 'company')
          ->leftJoin('u.userId', 'user')
          ->where('u.status = 1 and user.id = :userid')
          ->setParameter('userid',(int)$jsondata['userid'])
          ->groupby('u.apntoken')
          ->getQuery()
          ->getResult();

       //@JA - Get the list of all the apn tokens we need to send the message to.
       foreach($mobiletokens as $tokenobject){
           $deviceTokens[] = $tokenobject["apntoken"];
           echo $tokenobject["apntoken"]."\n";
       }

        die();

This gives me the incorrect response of

63416A61F2FD47CC7B579CAEACB002CB00FACC3786A8991F329BB41B1208C4BA
9B25BBCC3F3D2232934D86A7BC72967A5546B250281FB750FFE645C8EB105AF6
latestone

Any help here is appreciated!

Other Information

Data with SELECT * FROM

Data after using the SQL I provided up top.

Body:
I did this for now as a temporary fix, not sure if this is best answer though.

$em = $this->em;

       $connection = $em->getConnection();
       $statement = $connection->prepare("
            SELECT apntoken,deviceid,created
            FROM `distribution_mobiletokens` as dm
            WHERE userid=:userid
            and not exists (
                select 1
                from `distribution_mobiletokens`
                where userid = :userid
                and deviceid = dm.deviceid
                and created > dm.created
            )");
       $statement->bindValue('userid', $jsondata['userid']);
       $statement->execute();

       $mobiletokens = $statement->fetchAll();

       //@JA - Get the list of all the apn tokens we need to send the message to.
       foreach($mobiletokens as $tokenobject){
           $deviceTokens[] = $tokenobject["apntoken"];
           echo $tokenobject["apntoken"]."\n";
       }


问:
Highlight all possible circles ( Bubble sheet choices ) in opencv
I am working on automatically correcting a bubble-sheet tests that are scanned.
Currently, I can extract the solutions part of the sheet and fix its rotation.

So I have this image.

The output image with detected contours

Running the following code yields in the output image

```<code>def get_answers(image):
    display_normal("Just image",image)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blurry = cv2.GaussianBlur(gray, (3, 3), 1)
    thresh = cv2.threshold(blurry, 225, 255,
                       cv2.THRESH_BINARY_INV)[1]

    display_normal("Binary", thresh)
    # find contours in the thresholded image, then initialize
    # the list of contours that correspond to questions
    cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
                        cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[1]

    questionCnts = []

    # loop over the contours
    for c in cnts:
        # compute the bounding box of the contour, then use the
        # bounding box to derive the aspect ratio
        (x, y, w, h) = cv2.boundingRect(c)
        ar = w / float(h)

        # in order to label the contour as a question, region
        # should be sufficiently wide, sufficiently tall, and
        # have an aspect ratio approximately equal to 1
        if w >= 18 and h >= 18 and 0.9 <= ar and ar <= 1.2:
            questionCnts.append(c)

    cv2.drawContours(image, questionCnts, -1, (255, 0, 0), 1)
    display_normal("Image with contours",image.copy())
    if(questionCnts < 45*4):
        raise Exception("Didn't found all possible answers")
</code>```

Here is the problem : I convert the input image to binary and try to find contours that looks like a circle, but I can't find the whole possible 45*4 choices.. I fail to detect some of these circles..

So is there any better idea/algorithm to do this specific task ?

答:
You could have tried using adaptive threshold:

```<code>adapt_thresh = cv2.adaptiveThreshold(equ, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
cv2.imshow('adapt_thresh.jpg', adapt_thresh)
</code>```

(I resized the original image to keep it smaller)

UPDATE:

Another approach that I just performed.......

I equalized the gray scale image using histogram equalization:

```<code>equalized_img =  cv2.equalizeHist(gray)
cv2.imshow('Equalized Image.jpg', equalized_img )
</code>```

I then obtained the median of the equalized image using np.median(equalized_img) and applied a binary threshold by selecting all pixel values below [0.6 * median]

```<code>ret, thresh = cv2.threshold(equalized_img, lower, 255, 1)
cv2.imwrite("Final Image.jpg", thresh)
</code>```

Now you can go ahead and find your desired contours on this image.

Hope it helps  .. :)

Body:
I am working on automatically correcting a bubble-sheet tests that are scanned.
Currently, I can extract the solutions part of the sheet and fix its rotation.

So I have this image.

The output image with detected contours

Running the following code yields in the output image

def get_answers(image):
    display_normal("Just image",image)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blurry = cv2.GaussianBlur(gray, (3, 3), 1)
    thresh = cv2.threshold(blurry, 225, 255,
                       cv2.THRESH_BINARY_INV)[1]

    display_normal("Binary", thresh)
    # find contours in the thresholded image, then initialize
    # the list of contours that correspond to questions
    cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
                        cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[1]

    questionCnts = []

    # loop over the contours
    for c in cnts:
        # compute the bounding box of the contour, then use the
        # bounding box to derive the aspect ratio
        (x, y, w, h) = cv2.boundingRect(c)
        ar = w / float(h)

        # in order to label the contour as a question, region
        # should be sufficiently wide, sufficiently tall, and
        # have an aspect ratio approximately equal to 1
        if w >= 18 and h >= 18 and 0.9 <= ar and ar <= 1.2:
            questionCnts.append(c)

    cv2.drawContours(image, questionCnts, -1, (255, 0, 0), 1)
    display_normal("Image with contours",image.copy())
    if(questionCnts < 45*4):
        raise Exception("Didn't found all possible answers")

Here is the problem : I convert the input image to binary and try to find contours that looks like a circle, but I can't find the whole possible 45*4 choices.. I fail to detect some of these circles..

So is there any better idea/algorithm to do this specific task ?

Body:
You could have tried using adaptive threshold:

adapt_thresh = cv2.adaptiveThreshold(equ, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
cv2.imshow('adapt_thresh.jpg', adapt_thresh)

(I resized the original image to keep it smaller)

UPDATE:

Another approach that I just performed.......

I equalized the gray scale image using histogram equalization:

equalized_img =  cv2.equalizeHist(gray)
cv2.imshow('Equalized Image.jpg', equalized_img )

I then obtained the median of the equalized image using np.median(equalized_img) and applied a binary threshold by selecting all pixel values below [0.6 * median]

ret, thresh = cv2.threshold(equalized_img, lower, 255, 1)
cv2.imwrite("Final Image.jpg", thresh)

Now you can go ahead and find your desired contours on this image.

Hope it helps  .. :)


问:
method doesn't override from its superclass- swift
```<code>override func tableView(_ tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell( withIdentifier: "ChecklistItem", for: indexPath as IndexPath)
    return cell }
</code>```

There's an error saying: method doesn't override from its superclass. I've deleted the "override"  but still not working.
These are the source code from a book and it is said this is right syntax. So I want to know why I had this error?

答:
For swift 3</p>

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell( withIdentifier: "ChecklistItem", for: indexPath)
    return cell
}
</code>```

Body:
override func tableView(_ tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cell = tableView.dequeueReusableCell( withIdentifier: "ChecklistItem", for: indexPath as IndexPath)
    return cell }

There's an error saying: method doesn't override from its superclass. I've deleted the "override"  but still not working.
These are the source code from a book and it is said this is right syntax. So I want to know why I had this error?

Body:
For swift 3

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell( withIdentifier: "ChecklistItem", for: indexPath)
    return cell
}


问:
Why can't I covert my .ui file to .py?
I created a GUI in QT Designer and am trying to convert it from a .ui to a .py file. I have looked at other questions on here, but none have been helpful. I was able to do this without a problem not long ago, but now I am receiving this error:

RuntimeError: the sip module implements API v12.0 but the PyQt5.QtCore
  module requires API v12.1

I don't know what to do. If someone could please help it would be greatly appreciated.

I have tried to update sip and PyQt5 and neither have helped me. I have even uninstalled PyQt5 and reinstalled it.

答:
You can use pyuic4 for Qt4 and pyuic5 for Qt5

For sip, do this:

```<code>pip uninstall sip
pip install sip
</code>```

You can see the post The sip module implements API v11.0 to v11.2 but the PyQt5.QtCore module requires API v11.3

Title: Why can't I covert my .ui file to .py?

Body:
You can use pyuic4 for Qt4 and pyuic5 for Qt5

For sip, do this:

pip uninstall sip
pip install sip

You can see the post The sip module implements API v11.0 to v11.2 but the PyQt5.QtCore module requires API v11.3


问:
500 internal server error when sending % sign through post request glassfish
I have web service hosted on glassfish server. which basically translates English world to Hindi word.
suppose I post a request like close I get निकट in response but when I post a request something like 100 % off I get
The remote server returned an error: (500) Internal Server Error as a response

My glassfish server failed to handle % sign.
what should I do to overcome this error? screenshot

答:
Use %25 for % because the percent ("%") character serves as the indicator for percent-encoded octets in Glasfish, it must be percent-encoded as "%25" for that octet to be used as data within a URI. For more information, refer link below :

http://urlencoder.urlencode.in/url/decoder/character-encoding-glassfish-url-encode


问:
javascript - how to use a text box input in a for loop
I am trying to write a solution for a javascript application that takes a number input & depending on that number is how many times it runs a specific function. I am using a text box for input field & a button to process the number of times the user wants the function to run. It is for a game of dice game. User enters how many games he wants to play and clicks button to run the roll_dice function that many times. I'm not sure if I am going the right way with using a for loop to take users numeric input and loop through its value until it ends for example</p>

```<code>function games() {
        var num = document.getElementById("inp").vale;
        var i;

        for (i = 0; i < num; i++) {
            roll_dice();
        }
}
</code>```

答:
```<code>**<label>Game:</label><input type="text" id="input" value="0" />
<button id="btn">Submit</button>
  <script>
 document.getElementById("btn").addEventListener("click",function(){
  var inputVal=document.getElementById("input").value*1;
  rollDice(inputVal);
});

 function rollDice(dice){
</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

Game:<input type="text" id="input" value="0" />
<button id="btn">Submit</button>

```
</div>
</div>
</p>

```  for(var i =0;i<dice;i++){
    var x = Math.random()*100;
    console.log(x);}
}
 </script>**
```

Body:
I am trying to write a solution for a javascript application that takes a number input & depending on that number is how many times it runs a specific function. I am using a text box for input field & a button to process the number of times the user wants the function to run. It is for a game of dice game. User enters how many games he wants to play and clicks button to run the roll_dice function that many times. I'm not sure if I am going the right way with using a for loop to take users numeric input and loop through its value until it ends for example

function games() {
        var num = document.getElementById("inp").vale;
        var i;

        for (i = 0; i < num; i++) {
            roll_dice();
        }
}

Body:
**<label>Game:</label><input type="text" id="input" value="0" />
<button id="btn">Submit</button>
  <script>
 document.getElementById("btn").addEventListener("click",function(){
  var inputVal=document.getElementById("input").value*1;
  rollDice(inputVal);
});

 function rollDice(dice){

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<label>Game:</label><input type="text" id="input" value="0" />
<button id="btn">Submit</button>
  <script>
 document.getElementById("btn").addEventListener("click",function(){
  var inputVal=document.getElementById("input").value*1;
  rollDice(inputVal);

});

 function rollDice(dice){
  for(var i =0;i<dice;i++){
    var x = Math.random()*100;
    console.log(x);}
}
 </script>
</body>
</html>

  for(var i =0;i<dice;i++){
    var x = Math.random()*100;
    console.log(x);}
}
 </script>**


问:
Translating SAX exceptions
I have some Java code that validates XML against an XSD. I am using a modified version of the Error Handler found here: http://www.ibm.com/developerworks/xml/library/x-javaxmlvalidapi.html to catch and log ALL exceptions while validating.

The errors are very terse, they look something like this:

```<code>http://www.w3.org/TR/xml-schema-1#cvc-complex-type.2.4.a?s:cID&{"http://www.myschema.com/schema":txn}
</code>```

Other messages such as

```<code>http://www.w3.org/TR/xml-schema-1#cvc-complex-type.2.4.a?s:attributes&{"http://www.myschema.com/schema":sequence}
</code>```

are even more cryptic.

Is there an easy way to get a clear and intelligible message out of SAX explaining what went wrong here? I think in the first error it was expecting txn and instead found the element cID. BUT... I don't know all the possible errors that might be generated by SAX so I'd rather not try to manually create a translation table.

The eventual users of this output are mostly non-technical so I need to be able generate simple and clear messages such as "element txn was out of sequence".

If it helps, here's the code (more or less) that's used for validation:

```<code>Source schema1 = new StreamSource(new File("resources/schema1.xsd"));
Source schema2 = new StreamSource(new File("resources/schema2.xsd"));
Source[] sources = {schema1,schema2};
validator = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(sources).newValidator();
ErrorHandler lenient = new ForgivingErrorHandler();
validator.setErrorHandler(lenient);
</code>```

Elsewhere...

```<code>StreamSource xmlSource = new StreamSource(new StringReader(XMLData) );
try
{
    validator.validate(xmlSource);
}
catch (SAXException e)
{
    logger.error("XML Validation Error: ",e);
}
</code>```

答:
Well, it seems I had to add xsi:schemaLocation="http://www.mycompany.com/schema resources/schema1.xsd " to the XML document, because s:http://www.mycompany.com/schema is the default namespace: xmlns="s:http://www.mycompany.com/schema". Of course, I don't have access to modify the tool that generates the XML, so the following ugly hack was necessary:

```<code>xmlDataStr = xmlDataStr.replace("<rootNode ", "<rootNode xsi:schemaLocation=\"http://www.mycompany.com/schema resources/schema1.xsd \" ");
</code>```

...of course now I'm getting double validation errors! A clear and intelligible one such as:

```
cvc-complex-type.2.4.a: Invalid content was found starting with element 's:cID'. One of '{"http://www.mycompany.ca/schema":tdr}' is expected.
```

Immediately followed by:

```
http://www.w3.org/TR/xml-schema-1#cvc-complex-type.2.4.a?s:cID&{"http://www.mycompany.com/schema":tdr}
```

The double-error is annoying but at least the first one is usable...

ContentLicense: CC BY-SA 2.5

Title: Translating SAX exceptions

Body:
I have some Java code that validates XML against an XSD. I am using a modified version of the Error Handler found here: http://www.ibm.com/developerworks/xml/library/x-javaxmlvalidapi.html to catch and log ALL exceptions while validating.

The errors are very terse, they look something like this:

http://www.w3.org/TR/xml-schema-1#cvc-complex-type.2.4.a?s:cID&{"http://www.myschema.com/schema":txn}

Other messages such as

http://www.w3.org/TR/xml-schema-1#cvc-complex-type.2.4.a?s:attributes&{"http://www.myschema.com/schema":sequence}

are even more cryptic.

Is there an easy way to get a clear and intelligible message out of SAX explaining what went wrong here? I think in the first error it was expecting txn and instead found the element cID. BUT... I don't know all the possible errors that might be generated by SAX so I'd rather not try to manually create a translation table.

The eventual users of this output are mostly non-technical so I need to be able generate simple and clear messages such as "element txn was out of sequence".

If it helps, here's the code (more or less) that's used for validation:

Source schema1 = new StreamSource(new File("resources/schema1.xsd"));
Source schema2 = new StreamSource(new File("resources/schema2.xsd"));
Source[] sources = {schema1,schema2};
validator = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(sources).newValidator();
ErrorHandler lenient = new ForgivingErrorHandler();
validator.setErrorHandler(lenient);

Elsewhere...

StreamSource xmlSource = new StreamSource(new StringReader(XMLData) );
try
{
    validator.validate(xmlSource);
}
catch (SAXException e)
{
    logger.error("XML Validation Error: ",e);
}

Body:
Well, it seems I had to add xsi:schemaLocation="http://www.mycompany.com/schema resources/schema1.xsd " to the XML document, because s:http://www.mycompany.com/schema is the default namespace: xmlns="s:http://www.mycompany.com/schema". Of course, I don't have access to modify the tool that generates the XML, so the following ugly hack was necessary:

xmlDataStr = xmlDataStr.replace("<rootNode ", "<rootNode xsi:schemaLocation=\"http://www.mycompany.com/schema resources/schema1.xsd \" ");

...of course now I'm getting double validation errors! A clear and intelligible one such as:

cvc-complex-type.2.4.a: Invalid content was found starting with element 's:cID'. One of '{"http://www.mycompany.ca/schema":tdr}' is expected.

Immediately followed by:

http://www.w3.org/TR/xml-schema-1#cvc-complex-type.2.4.a?s:cID&{"http://www.mycompany.com/schema":tdr}

The double-error is annoying but at least the first one is usable...


问:
how to print given array in for each using javascript
I have an array like below.

```<code>[{
  'i_id':'119',
  'name':'Brinjal-250',
  'weight':'250.Gm',
  'qty':'1',
  'price':'5',
  'market':'55',
  'image':'f_control/images/vegetables/Brinjal-PNG-Image-min'
 },
 {
  'i_id':'101',
  'name':'Tomato',
  'weight':'500.Gm',
  'qty':'1',
  'price':'4',
  'market':'44',
  'image':'f_control/images/vegetables/tometo-min.jpg'
}]
</code>```

And i want it to in for each loop using java script, It is possible?
If possible then please guide me in right direction, Thanks.

The demo output

答:
The requirement is not clear. If you want to loop through he array use forEach or conventinal for-loop will also work.

```<code>var myArray=[//json array]
myArray.forEach(function(item,index){
  console.log(item.name) // will seperately log Brinjal-250, & Tomato
})
</code>```

Body:
I have an array like below.

[{
  'i_id':'119',
  'name':'Brinjal-250',
  'weight':'250.Gm',
  'qty':'1',
  'price':'5',
  'market':'55',
  'image':'f_control/images/vegetables/Brinjal-PNG-Image-min'
 },
 {
  'i_id':'101',
  'name':'Tomato',
  'weight':'500.Gm',
  'qty':'1',
  'price':'4',
  'market':'44',
  'image':'f_control/images/vegetables/tometo-min.jpg'
}]

And i want it to in for each loop using java script, It is possible?
If possible then please guide me in right direction, Thanks.

The demo output

Body:
The requirement is not clear. If you want to loop through he array use forEach or conventinal for-loop will also work.

var myArray=[//json array]
myArray.forEach(function(item,index){
  console.log(item.name) // will seperately log Brinjal-250, & Tomato
})


问:
Pandas assignment efficiency
I have a Pandas dataframe where I will be adding a new column (SUGGESTED).
Once new column is added, I'm using the following pattern to update it with a new value based on the value of QUERY column. Example:

```<code>QUERY = 'query'
SUGGESTED = 'suggested'
df[SUGGESTED] = numpy.nan
s_query = 'de'
new_value = 'delaware'
df.loc[(df[QUERY] == s_query), [SUGGESTED]] = new_value
</code>```

Example:

```<code>query suggested
al      alabama
ca      california
de      NaN
</code>```

After:

```<code>query suggested
    al      alabama
    ca      california
    de      delaware
</code>```

It seems to work so far, not sure if there is a more efficient way to do it in Pandas.

答:
I think you can first omit df[SUGGESTED] = numpy.nan in loc and np.where solution, because it add new column:

```<code>QUERY = 'query'
SUGGESTED = 'suggested'
s_query = 'de'
new_value = 'delaware'

#if need update existing column
df[SUGGESTED] = df[SUGGESTED].mask(df[QUERY] == s_query, new_value)
print (df)
  query   suggested
0    al     alabama
1    ca  california
2    de    delaware
</code>```

Solution with loc can be simplify remove () if only one condition and remove [] if only one column:

```<code>#for updating existing column
df.loc[df[QUERY] == s_query, SUGGESTED] = new_value
print (df)
  query   suggested
0    al     alabama
1    ca  california
2    de    delaware

#same for creating new column
df.loc[df[QUERY] == s_query, SUGGESTED] = new_value
print (df)
  query suggested
0    al       NaN
1    ca       NaN
2    de  delaware
</code>```

If need replace by NaN where no match:

```<code>#same for creating and updating existing column
df[SUGGESTED] = np.where(df[QUERY] == s_query, new_value, np.nan)
print (df)
  query suggested
0    al       nan
1    ca       nan
2    de  delaware
</code>```

Title: Pandas assignment efficiency

Body:
I have a Pandas dataframe where I will be adding a new column (SUGGESTED).
Once new column is added, I'm using the following pattern to update it with a new value based on the value of QUERY column. Example:

QUERY = 'query'
SUGGESTED = 'suggested'
df[SUGGESTED] = numpy.nan
s_query = 'de'
new_value = 'delaware'
df.loc[(df[QUERY] == s_query), [SUGGESTED]] = new_value

Example:

query suggested
al      alabama
ca      california
de      NaN

After:

query suggested
    al      alabama
    ca      california
    de      delaware

It seems to work so far, not sure if there is a more efficient way to do it in Pandas.

Body:
I think you can first omit df[SUGGESTED] = numpy.nan in loc and np.where solution, because it add new column:

QUERY = 'query'
SUGGESTED = 'suggested'
s_query = 'de'
new_value = 'delaware'

#if need update existing column
df[SUGGESTED] = df[SUGGESTED].mask(df[QUERY] == s_query, new_value)
print (df)
  query   suggested
0    al     alabama
1    ca  california
2    de    delaware

Solution with loc can be simplify remove () if only one condition and remove [] if only one column:

#for updating existing column
df.loc[df[QUERY] == s_query, SUGGESTED] = new_value
print (df)
  query   suggested
0    al     alabama
1    ca  california
2    de    delaware

#same for creating new column
df.loc[df[QUERY] == s_query, SUGGESTED] = new_value
print (df)
  query suggested
0    al       NaN
1    ca       NaN
2    de  delaware

If need replace by NaN where no match:

#same for creating and updating existing column
df[SUGGESTED] = np.where(df[QUERY] == s_query, new_value, np.nan)
print (df)
  query suggested
0    al       nan
1    ca       nan
2    de  delaware


问:
Javascript: How to convert exif date time data to timestamp?
In javascript, while using exif-js to extract metadata of an image file, I am getting date time format as 2017:03:09 14:49:21.

The value in the DateTimeOriginal property is formatted as YYYY:MMY:DD HH:MM:SS. When I use var d = new Date(2017:03:09 14:49:21), it returns NaN. It's the colons in between the YYYY, MM, and DD which causes problem.

How to solve this problem?

Thanks in advance.

答:
Don't use the built-in parser (i.e. Date constructor or Date.parse) for parsing strings as it's largely implementation dependent and unreliable. If you can trust the date to be valid, then the following will do:

/* Parse date string in YYYY-MM-DD hh:mm:ss format
** separator can be any non-digit character
** e.g. 2017:03:09 14:49:21
*/
function parseDate(s) {
  var b = s.split(/\D/);
  return new Date(b[0],b[1]-1,b[2],b[3],b[4],b[5]);
}

console.log(parseDate('2017:03:09 14:49:21').toString());```

It's fairly easy to add validation to the values. Otherwise, use a library and make sure you specify the format to parse.

Body:
Don't use the built-in parser (i.e. Date constructor or Date.parse) for parsing strings as it's largely implementation dependent and unreliable. If you can trust the date to be valid, then the following will do:

/* Parse date string in YYYY-MM-DD hh:mm:ss format
** separator can be any non-digit character
** e.g. 2017:03:09 14:49:21
*/
function parseDate(s) {
  var b = s.split(/\D/);
  return new Date(b[0],b[1]-1,b[2],b[3],b[4],b[5]);
}

console.log(parseDate('2017:03:09 14:49:21').toString());

It's fairly easy to add validation to the values. Otherwise, use a library and make sure you specify the format to parse.


问:
log4net - any filter for logging only the Nth message?
I have a component that is constantly reading a values from a device.  Currently it updates every {n} seconds and logs a debug message with the value to an instance of ILog.

Every second is too frequent for me, I just don't care and it eats up too much log space.  However, I would certainly be interested in capturing every 10th or 30th message from that component so I can get the general gist of what it is doing.

Does anyone know any way of doing this that does not involve me witting my own ILog implementation?

答:
This is probably too late to help you, but you could implement a filter.  http://www.mail-archive.com/log4net-user%40logging.apache.org/msg02517.html shows how to implement a filter for limiting how often an exception is logged (if exception type is same as last exception type and if less than some specified amount of time has passed).

Here is the actual filter source code from that link:

```<code>public class ExceptionThrottleFilter : FilterSkeleton
{
  private DateTime lastException = DateTime.MinValue;
  private Type exceptionType = typeof(Exception);
  private int threshold = 5; // seconds

  public override void ActivateOptions()
  {
    base.ActivateOptions();
  }

  public override FilterDecision Decide(LoggingEvent loggingEvent)
  {
    if (loggingEvent.ExceptionObject != null &&  loggingEvent.ExceptionObject.GetType) == exceptionType)
    {
      if (loggingEvent.TimeStamp.Subtract(lastException).TotalSeconds > threshold)
      {
        lastException = loggingEvent.TimeStamp;
        return FilterDecision.Accept;
      }
      else
      {
        return FilterDecision.Deny;
      }
    }
    else
    {
      return FilterDecision.Neutral;
    }
  }

  public Type ExceptionType
  {
    get { return exceptionType; }
    set { exceptionType = value; }
  }

  public int Threshold
  {
    get { return threshold; }
    set { threshold = value; }
  }
}
</code>```

It would be configured like this:

```<code><filter type="Company.Project.Logging.ExceptionThrottleFilter">
  <threshold value="2" />
  <exceptionType value="System.ApplicationException" />
</filter>
</code>```

It seems like it would be pretty straightforward to modify it to "throttle" messages that repeat.  Maybe something like this (untested):

```<code>public class DuplicateMessageThrottleFilter : FilterSkeleton
{
  private string lastMessage;

  public override void ActivateOptions()
  {
    base.ActivateOptions();
  }

  public override FilterDecision Decide(LoggingEvent loggingEvent)
  {
    string newMessage;
    if (loggingEvent.MessageObject != null)
    {
      newMessage = loggingEvent.MessageObject.ToString();
    }

    if (newMessage.Equals(lastMessage))
    {
      return FilterDecision.Deny;
    }

    lastMessage = newMessage;
    return FilterDecision.Accept;
  }
}
</code>```

It might be nice to annotate a logged message with how many times it was repeated, but how to do that is not obvious to me:

```<code>Some message.
Some message.
Some message.
Look, a new message.
Some message.
Some message.
Look, a new message.
</code>```

Could generate something like this:

```<code>Some message. (3 times)
Look, a new message.
Some message. (2 times)
Look, a new message.
</code>```

Probably some kind of ForwardingAppender or BufferingForwardingAppender.  It would always be one message behind.  A message comes in.  The "RepeatedMessageAppender" would hold that message.  The  next message comes in.  If it is different than last message, forward last message to the "real" Appender (if "repeated count" is > 0, append the number to the last message before forwarding - this is the part that I am not sure about because I think htat it is not easy to modify the LoggingEvent that is passed to the Appender).  If it is the same as the last message, increment counter and do not forward.  Since the "RepeatedMessageAppender" is one behind, it probably has to be a BufferingForwardingAppender and it must implement Flush.

Maybe you (or someone else) will find this information useful.

Body:
This is probably too late to help you, but you could implement a filter.  http://www.mail-archive.com/log4net-user%40logging.apache.org/msg02517.html shows how to implement a filter for limiting how often an exception is logged (if exception type is same as last exception type and if less than some specified amount of time has passed).

Here is the actual filter source code from that link:

public class ExceptionThrottleFilter : FilterSkeleton
{
  private DateTime lastException = DateTime.MinValue;
  private Type exceptionType = typeof(Exception);
  private int threshold = 5; // seconds

  public override void ActivateOptions()
  {
    base.ActivateOptions();
  }

  public override FilterDecision Decide(LoggingEvent loggingEvent)
  {
    if (loggingEvent.ExceptionObject != null &&  loggingEvent.ExceptionObject.GetType) == exceptionType)
    {
      if (loggingEvent.TimeStamp.Subtract(lastException).TotalSeconds > threshold)
      {
        lastException = loggingEvent.TimeStamp;
        return FilterDecision.Accept;
      }
      else
      {
        return FilterDecision.Deny;
      }
    }
    else
    {
      return FilterDecision.Neutral;
    }
  }

  public Type ExceptionType
  {
    get { return exceptionType; }
    set { exceptionType = value; }
  }

  public int Threshold
  {
    get { return threshold; }
    set { threshold = value; }
  }
}

It would be configured like this:

<filter type="Company.Project.Logging.ExceptionThrottleFilter">
  <threshold value="2" />
  <exceptionType value="System.ApplicationException" />
</filter>

It seems like it would be pretty straightforward to modify it to "throttle" messages that repeat.  Maybe something like this (untested):

public class DuplicateMessageThrottleFilter : FilterSkeleton
{
  private string lastMessage;

  public override void ActivateOptions()
  {
    base.ActivateOptions();
  }

  public override FilterDecision Decide(LoggingEvent loggingEvent)
  {
    string newMessage;
    if (loggingEvent.MessageObject != null)
    {
      newMessage = loggingEvent.MessageObject.ToString();
    }

    if (newMessage.Equals(lastMessage))
    {
      return FilterDecision.Deny;
    }

    lastMessage = newMessage;
    return FilterDecision.Accept;
  }
}

It might be nice to annotate a logged message with how many times it was repeated, but how to do that is not obvious to me:

Some message.
Some message.
Some message.
Look, a new message.
Some message.
Some message.
Look, a new message.

Could generate something like this:

Some message. (3 times)
Look, a new message.
Some message. (2 times)
Look, a new message.

Probably some kind of ForwardingAppender or BufferingForwardingAppender.  It would always be one message behind.  A message comes in.  The "RepeatedMessageAppender" would hold that message.  The  next message comes in.  If it is different than last message, forward last message to the "real" Appender (if "repeated count" is > 0, append the number to the last message before forwarding - this is the part that I am not sure about because I think htat it is not easy to modify the LoggingEvent that is passed to the Appender).  If it is the same as the last message, increment counter and do not forward.  Since the "RepeatedMessageAppender" is one behind, it probably has to be a BufferingForwardingAppender and it must implement Flush.

Maybe you (or someone else) will find this information useful.


问:
Where can I change the Gradle version in an android project?
Each time when I try to open an android project downloaded from Google Android samples, Android Studio would try to download different version of Gradle automatically. This is really frustrating and troublesome to me since the downloading is very slow in China.

I would like to stop the automatic download and appoint the latest version to replace the one in a sample project. Is that possible?

答:
In AS, open the settings dialog ("File" -> "Settings") and select "Build, Execution, Deployment" -> "Gradle". In this dialog you can select "Use local gradle distribution" to use whatever Gradle version you have locally installed on your machine.

This may however break some projects since some plugins require a certain gradle version. The default setup (using the gradle wrapper) takes care of this.

Alternatively, you can also change the gradle version used by the wrapper by modifying it in file gradle/wrapper/gradle-wrapper.properties. The same warning about incompatible versions applies.


答:
If both objects are in the same array, just like below:

```<code>[{'i_id':'119',
'name':'Brinjal-250',
'weight':'250.Gm',
'qty':'1',
'price':'5',
'market':'55',
'image':'f_control/images/vegetables/Brinjal-PNG-Image-min'},
{'i_id':'101',
    'name':'Tomato',
    'weight':'500.Gm',
    'qty':'1',
    'price':'4',
    'market':'44',
    'image':'f_control/images/vegetables/tometo-min.jpg'}]
</code>```

then use:

```<code>arrayName.forEach(function (item, index) {
  console.log(item["name"]);
})
</code>```

or else use:

```<code>for(var key in arrayName) {
   console.log("key: "+key+" Value: "+arrayName[key]["name"]);
}
</code>```

Check out the fiddle : https://jsfiddle.net/NayanaDas/42f3yxho/

Updated Answer:

if you want to make this array [{'i_id':'101'}] [{'i_id':'102'}] like this  [{'i_id':'101'},{'i_id':'102'}] , then use JavaScript Array concat() Method :

```<code>var arr1 = [{'i_id':'101'}];
var arr2 = [{'i_id':'102'}];

var array = arr1.concat(arr2);

console.log(JSON.stringify(array));
</code>```

See the fiddle : https://jsfiddle.net/NayanaDas/eaumhnvw/

Title: how to print given array in for each using javascript

Body:
If both objects are in the same array, just like below:

[{'i_id':'119',
'name':'Brinjal-250',
'weight':'250.Gm',
'qty':'1',
'price':'5',
'market':'55',
'image':'f_control/images/vegetables/Brinjal-PNG-Image-min'},
{'i_id':'101',
    'name':'Tomato',
    'weight':'500.Gm',
    'qty':'1',
    'price':'4',
    'market':'44',
    'image':'f_control/images/vegetables/tometo-min.jpg'}]

then use:

arrayName.forEach(function (item, index) {
  console.log(item["name"]);
})

or else use:

for(var key in arrayName) {
   console.log("key: "+key+" Value: "+arrayName[key]["name"]);
}

Check out the fiddle : https://jsfiddle.net/NayanaDas/42f3yxho/

Updated Answer:

if you want to make this array [{'i_id':'101'}] [{'i_id':'102'}] like this  [{'i_id':'101'},{'i_id':'102'}] , then use JavaScript Array concat() Method :

var arr1 = [{'i_id':'101'}];
var arr2 = [{'i_id':'102'}];

var array = arr1.concat(arr2);

console.log(JSON.stringify(array));

See the fiddle : https://jsfiddle.net/NayanaDas/eaumhnvw/


问:
How to use horizontal recycler view and a linear layout with some child using without definate height?
I have used a recyclerview and Linear layout with some child then i covered the the both in a scroll view then recycler view item is not inflate. as we gave definite height all work fine.

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F1F1F1"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="teastall.com.netpe.MainCode.MainActivity"
    tools:showIn="@layout/app_bar_main">
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    >
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="130dp"
            android:layout_margin="10dp"
            android:background="@color/white">
            <android.support.v7.widget.RecyclerView
                android:id="@+id/recyclerViewMainOffer"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:background="@color/white">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="1"
                    android:orientation="horizontal">
                    <LinearLayout
                        android:id="@+id/ll_mainFindServices"
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="1"
                        android:orientation="horizontal">
                        <ImageView
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_gravity="center"
                            android:layout_margin="10dp"
                            android:layout_weight="1"
                            android:src="@drawable/ic_home_delivery" />
                        <LinearLayout
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_gravity="center_vertical"
                            android:layout_marginLeft="10dp"
                            android:layout_weight="2"
                            android:gravity="center_vertical"
                            android:orientation="vertical">
                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_gravity="center_vertical"
                                android:gravity="center_vertical"
                                android:text="Find Service"
                                android:textColor="@color/black"
                                android:textSize="14sp" />
                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_gravity="center_vertical"
                                android:gravity="center_vertical"
                                android:text="Provided Service"
                                android:textSize="12sp" />
                        </LinearLayout>
                    </LinearLayout>
                    <View
                        android:layout_width="1dp"
                        android:layout_height="match_parent"
                        android:layout_marginBottom="10dp"
                        android:layout_marginTop="10dp"
                        android:background="#111111" />
                    <LinearLayout
                        android:id="@+id/ll_mainExploreMarket"
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="1"
                        android:orientation="horizontal">
                        <ImageView
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_gravity="center"
                            android:layout_margin="10dp"
                            android:layout_weight="1"
                            android:src="@drawable/ic_home_delivery" />
                        <LinearLayout
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_gravity="center_vertical"
                            android:layout_marginLeft="10dp"
                            android:layout_weight="2"
                            android:gravity="center_vertical"
                            android:orientation="vertical">
                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_gravity="center_vertical"
                                android:gravity="center_vertical"
                                android:text="Find Service"
                                android:textColor="@color/black"
                                android:textSize="14sp" />
                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_gravity="center_vertical"
                                android:gravity="center_vertical"
                                android:text="Provided Service"
                                android:textSize="12sp" />
                        </LinearLayout>
                    </LinearLayout>
                </LinearLayout>
                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:layout_marginBottom="10dp"
                    android:layout_marginTop="10dp"
                    android:background="#111111" />
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="1"
                    android:orientation="horizontal">
                    <LinearLayout
                        android:id="@+id/ll_mainAssistivePay"
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="1"
                        android:orientation="horizontal">
                        <ImageView
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_gravity="center"
                            android:layout_margin="10dp"
                            android:layout_weight="1"
                            android:src="@drawable/ic_home_delivery" />
                        <LinearLayout
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_gravity="center_vertical"
                            android:layout_marginLeft="10dp"
                            android:layout_weight="2"
                            android:gravity="center_vertical"
                            android:orientation="vertical">
                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_gravity="center_vertical"
                                android:gravity="center_vertical"
                                android:text="Find Service"
                                android:textColor="@color/black"
                                android:textSize="14sp" />
                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_gravity="center_vertical"
                                android:gravity="center_vertical"
                                android:text="Provided Service"
                                android:textSize="12sp" />
                        </LinearLayout>
                    </LinearLayout>
                    <View
                        android:layout_width="1dp"
                        android:layout_height="match_parent"
                        android:layout_marginBottom="10dp"
                        android:layout_marginTop="10dp"
                        android:background="#111111" />

                    <LinearLayout
                        android:id="@+id/ll_mainDocValut"
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="1"
                        android:orientation="horizontal">
                       <ImageView
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_gravity="center"
                            android:layout_margin="10dp"
                            android:layout_weight="1"
                            android:src="@drawable/ic_home_delivery" />
                        <LinearLayout
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_gravity="center_vertical"
                            android:layout_marginLeft="10dp"
                            android:layout_weight="2"
                            android:gravity="center_vertical"
                            android:orientation="vertical">
                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_gravity="center_vertical"
                                android:gravity="center_vertical"
                                android:text="Find Service"
                                android:textColor="@color/black"
                                android:textSize="14sp" />
                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_gravity="center_vertical"
                                android:gravity="center_vertical"
                                android:text="Provided Service"
                                android:textSize="12sp" />
                        </LinearLayout>
                    </LinearLayout>
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
</LinearLayout>
</ScrollView>
</RelativeLayout>
</code>```

I want to use the these type of layout design but without definite height using layout weight or wrap and match parent attributes only.

答:
you can set orientation of recyclerview horizontaly</p>

```<code>  android:orientation="horizontal"
</code>```

Body:
I have used a recyclerview and Linear layout with some child then i covered the the both in a scroll view then recycler view item is not inflate. as we gave definite height all work fine.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F1F1F1"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="teastall.com.netpe.MainCode.MainActivity"
    tools:showIn="@layout/app_bar_main">
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    >
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="130dp"
            android:layout_margin="10dp"
            android:background="@color/white">
            <android.support.v7.widget.RecyclerView
                android:id="@+id/recyclerViewMainOffer"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:background="@color/white">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="1"
                    android:orientation="horizontal">
                    <LinearLayout
                        android:id="@+id/ll_mainFindServices"
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="1"
                        android:orientation="horizontal">
                        <ImageView
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_gravity="center"
                            android:layout_margin="10dp"
                            android:layout_weight="1"
                            android:src="@drawable/ic_home_delivery" />
                        <LinearLayout
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_gravity="center_vertical"
                            android:layout_marginLeft="10dp"
                            android:layout_weight="2"
                            android:gravity="center_vertical"
                            android:orientation="vertical">
                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_gravity="center_vertical"
                                android:gravity="center_vertical"
                                android:text="Find Service"
                                android:textColor="@color/black"
                                android:textSize="14sp" />
                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_gravity="center_vertical"
                                android:gravity="center_vertical"
                                android:text="Provided Service"
                                android:textSize="12sp" />
                        </LinearLayout>
                    </LinearLayout>
                    <View
                        android:layout_width="1dp"
                        android:layout_height="match_parent"
                        android:layout_marginBottom="10dp"
                        android:layout_marginTop="10dp"
                        android:background="#111111" />
                    <LinearLayout
                        android:id="@+id/ll_mainExploreMarket"
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="1"
                        android:orientation="horizontal">
                        <ImageView
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_gravity="center"
                            android:layout_margin="10dp"
                            android:layout_weight="1"
                            android:src="@drawable/ic_home_delivery" />
                        <LinearLayout
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_gravity="center_vertical"
                            android:layout_marginLeft="10dp"
                            android:layout_weight="2"
                            android:gravity="center_vertical"
                            android:orientation="vertical">
                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_gravity="center_vertical"
                                android:gravity="center_vertical"
                                android:text="Find Service"
                                android:textColor="@color/black"
                                android:textSize="14sp" />
                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_gravity="center_vertical"
                                android:gravity="center_vertical"
                                android:text="Provided Service"
                                android:textSize="12sp" />
                        </LinearLayout>
                    </LinearLayout>
                </LinearLayout>
                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:layout_marginBottom="10dp"
                    android:layout_marginTop="10dp"
                    android:background="#111111" />
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_weight="1"
                    android:orientation="horizontal">
                    <LinearLayout
                        android:id="@+id/ll_mainAssistivePay"
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="1"
                        android:orientation="horizontal">
                        <ImageView
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_gravity="center"
                            android:layout_margin="10dp"
                            android:layout_weight="1"
                            android:src="@drawable/ic_home_delivery" />
                        <LinearLayout
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_gravity="center_vertical"
                            android:layout_marginLeft="10dp"
                            android:layout_weight="2"
                            android:gravity="center_vertical"
                            android:orientation="vertical">
                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_gravity="center_vertical"
                                android:gravity="center_vertical"
                                android:text="Find Service"
                                android:textColor="@color/black"
                                android:textSize="14sp" />
                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_gravity="center_vertical"
                                android:gravity="center_vertical"
                                android:text="Provided Service"
                                android:textSize="12sp" />
                        </LinearLayout>
                    </LinearLayout>
                    <View
                        android:layout_width="1dp"
                        android:layout_height="match_parent"
                        android:layout_marginBottom="10dp"
                        android:layout_marginTop="10dp"
                        android:background="#111111" />

                    <LinearLayout
                        android:id="@+id/ll_mainDocValut"
                        android:layout_width="0dp"
                        android:layout_height="match_parent"
                        android:layout_weight="1"
                        android:orientation="horizontal">
                       <ImageView
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_gravity="center"
                            android:layout_margin="10dp"
                            android:layout_weight="1"
                            android:src="@drawable/ic_home_delivery" />
                        <LinearLayout
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_gravity="center_vertical"
                            android:layout_marginLeft="10dp"
                            android:layout_weight="2"
                            android:gravity="center_vertical"
                            android:orientation="vertical">
                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_gravity="center_vertical"
                                android:gravity="center_vertical"
                                android:text="Find Service"
                                android:textColor="@color/black"
                                android:textSize="14sp" />
                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_gravity="center_vertical"
                                android:gravity="center_vertical"
                                android:text="Provided Service"
                                android:textSize="12sp" />
                        </LinearLayout>
                    </LinearLayout>
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
</LinearLayout>
</ScrollView>
</RelativeLayout>

I want to use the these type of layout design but without definite height using layout weight or wrap and match parent attributes only.

Body:
you can set orientation of recyclerview horizontaly

  android:orientation="horizontal"


问:
How to combine hash in PHP
I would like to ask if how to combine hash codes in PHP?

For example I have some checksums here (just sample checksums):

```<code>checksum1:b62e146dbc34b6f7dd0d7b1dc4e6c93ebc2a0016793e3af701fe4f3eab3299d1
checksum2:dsfhsdf8s6f87e4r34ijtr5i34u5934534534ij5340598348534095834095j34
checksum3:4324298sdfhsdhfsdhf387455hsdfhsdf9358903485jsdfjsdjfsiuf03458345
</code>```

If I have these sample checksums of a file which will be split into 3 parts, I have to combine the first 2 checksums and then combine the last checksum after.

Edit: Combine means if I combine 2 checksums, it will generate new checksum.

I would like to achieve through the code what was stated in here:

Combine the first two hashes and take the binary hash of the result.

$ cat hash1 hash2 > hash12

$ openssl dgst -sha256 -binary hash12 > hash12hash

This is in the command line interface. The binary result was later on converted to hexadecimal.
How is it possible for PHP?

答:
You can use the hash() function, for example as in the following body-less for-loop:

```<code>$checksums = [
    'b62e146dbc34b6f7dd0d7b1dc4e6c93ebc2a0016793e3af701fe4f3eab3299d1',
    'dsfhsdf8s6f87e4r34ijtr5i34u5934534534ij5340598348534095834095j34',
    '4324298sdfhsdhfsdhf387455hsdfhsdf9358903485jsdfjsdjfsiuf03458345'
];

for ($i = 1, $hash = $checksums[0];
     $i < sizeof($checksums);
     $i++, $hash = hash('sha256', $hash.$checksums[$i]));

echo $hash;
</code>```

This will calculate the hash as hash(hash(checksum1 + checksum2) + checksum3)

In your question, you use the -binary flag with the openssl dgst command. You can do the same in PHP by passing a true value as the third parameter in the call to the PHP hash() function, but I don't really see how that is meaningful if you start combining more than two hashes.

Update

In the comments, it was made clear that the actual goal is to calculate a tree hash for use with AWS. The easiest way to to that is to use the TreeHash class from the AWS SDK for PHP.

Title: How to combine hash in PHP

Body:
I would like to ask if how to combine hash codes in PHP?

For example I have some checksums here (just sample checksums):

checksum1:b62e146dbc34b6f7dd0d7b1dc4e6c93ebc2a0016793e3af701fe4f3eab3299d1
checksum2:dsfhsdf8s6f87e4r34ijtr5i34u5934534534ij5340598348534095834095j34
checksum3:4324298sdfhsdhfsdhf387455hsdfhsdf9358903485jsdfjsdjfsiuf03458345

If I have these sample checksums of a file which will be split into 3 parts, I have to combine the first 2 checksums and then combine the last checksum after.

Edit: Combine means if I combine 2 checksums, it will generate new checksum.

I would like to achieve through the code what was stated in here:

Combine the first two hashes and take the binary hash of the result.

$ cat hash1 hash2 > hash12

$ openssl dgst -sha256 -binary hash12 > hash12hash

This is in the command line interface. The binary result was later on converted to hexadecimal.
How is it possible for PHP?

Body:
You can use the hash() function, for example as in the following body-less for-loop:

$checksums = [
    'b62e146dbc34b6f7dd0d7b1dc4e6c93ebc2a0016793e3af701fe4f3eab3299d1',
    'dsfhsdf8s6f87e4r34ijtr5i34u5934534534ij5340598348534095834095j34',
    '4324298sdfhsdhfsdhf387455hsdfhsdf9358903485jsdfjsdjfsiuf03458345'
];

for ($i = 1, $hash = $checksums[0];
     $i < sizeof($checksums);
     $i++, $hash = hash('sha256', $hash.$checksums[$i]));

echo $hash;

This will calculate the hash as hash(hash(checksum1 + checksum2) + checksum3)

In your question, you use the -binary flag with the openssl dgst command. You can do the same in PHP by passing a true value as the third parameter in the call to the PHP hash() function, but I don't really see how that is meaningful if you start combining more than two hashes.

Update

In the comments, it was made clear that the actual goal is to calculate a tree hash for use with AWS. The easiest way to to that is to use the TreeHash class from the AWS SDK for PHP.


问:
Insert into same table avoiding duplicate
```<code>Table enrollments
-----------------

id      classId     userId
--      -------     ------
1         1           1
--      -------     ------
</code>```

after this stats: want to reject inserting whenever again inserting { classId=1, userId=1 }

If user inserts same classId and userId then it should rejects inserting.
I've already tried:

```<code>INSERT INTO enrollments(classId, userId)
    VALUES('{$classId}', '{$userId}')
    WHERE
    NOT EXISTS(SELECT NULL FROM
                enrollments WHERE
                    classId='{$classId}' AND userId='{$userId}')
</code>```

答: if you want avoiding duplicate then make these fileds(classId, userId) UNIQUE key or you want these fileds are not null also then you can make these these fields as PRIMIRY key. </p>

Body:
Table enrollments
-----------------

id      classId     userId
--      -------     ------
1         1           1
--      -------     ------

after this stats: want to reject inserting whenever again inserting { classId=1, userId=1 }

If user inserts same classId and userId then it should rejects inserting.
I've already tried:

INSERT INTO enrollments(classId, userId)
    VALUES('{$classId}', '{$userId}')
    WHERE
    NOT EXISTS(SELECT NULL FROM
                enrollments WHERE
                    classId='{$classId}' AND userId='{$userId}')


问:
I would like to change the login logo Odoo 10
I have this problem, and I don't know how to change the odoo logo from login page, I override update_login function

```<code>update_logo: function(reload) {
        var company = session.company_id;
        var img = session.url('/web/static/src/img/logo2.png' + '?db=' + session.db + (company ? '&company=' + company : ''));
        this.$('.o_sub_menu_logo img').attr('src', '').attr('src', img + (reload ? "#" + Date.now() : ''));
        this.$('.oe_logo_edit').toggleClass('oe_logo_edit_admin', session.is_superuser);
</code>```

but isn't work, please help (Sorry for my english)

答:
I assume you want to change the logo appeared while login into odoo database.

This logo come from res.company I mean Your Company
try to change logo of Company It will reflect in login screen.

To do that goto > settings > Users > Companies > Change Logo image of Company.

Body:
I have this problem, and I don't know how to change the odoo logo from login page, I override update_login function

update_logo: function(reload) {
        var company = session.company_id;
        var img = session.url('/web/static/src/img/logo2.png' + '?db=' + session.db + (company ? '&company=' + company : ''));
        this.$('.o_sub_menu_logo img').attr('src', '').attr('src', img + (reload ? "#" + Date.now() : ''));
        this.$('.oe_logo_edit').toggleClass('oe_logo_edit_admin', session.is_superuser);

but isn't work, please help (Sorry for my english)


问:
Can I use wkhtmltopdf on AWS Lambda
I'm using a AWS Lambda function to merge PDF files stored on S3. In addition to that, I need now to create a PDF file (from HTML and CSS). I was trying to use wkhtmltopdf, but it seems that I would have to install it using apt-get install (which I don`t think I have access on AWS Lambda).

Any ideas on how can I do it?

Any suggestions for wkhtmltopdf replacements?

Thanks!

答:
There are multiple projects on GitHub claiming to run wkhtmltopdf on Lambda. Here are a few.

https://github.com/lubos/aws-lambda-wkhtmltopdf

https://github.com/dimiro1/lambda-wkhtmltopdf

https://github.com/jpaolin/aws-lambda-s3-wkhtmltopdf

ContentLicense: CC BY-SA 4.0

Title: Can I use wkhtmltopdf on AWS Lambda


问:
my Admin Controller in codeigniter have one issue
I have one admin_controller. I am accessing that controller form login. So I set form action login. Again I tried to login I want to change the form action to Admin_controller/login. How can I solve this issue?

```<code> $referrerUrl1 = $_SERVER['REQUEST_URI'];

 if($referrerUrl1=="/MallFinder/admin/" || $referrerUrl1=="MallFinder/admin" ||  $referrerUrl1=="MallFinder/index.php/admin")
 {
    $route['default_controller'] = "Admin_controller";
 }
 else
 {
    $route['default_controller'] = "Welcome";
 }
 $route['404_override'] = '';
 $route['translate_uri_dashes'] = TRUE;
</code>```

答:
For Starters. You can Read Codeigniter 3.x Login with Form Validation -Boiler plate

It has all what you need , form validation, querying database, session etc. But for Security you need to read Codeigniter Security Class and Codeigniter Encryption Library

Body:
I have one admin_controller. I am accessing that controller form login. So I set form action login. Again I tried to login I want to change the form action to Admin_controller/login. How can I solve this issue?

 $referrerUrl1 = $_SERVER['REQUEST_URI'];

 if($referrerUrl1=="/MallFinder/admin/" || $referrerUrl1=="MallFinder/admin" ||  $referrerUrl1=="MallFinder/index.php/admin")
 {
    $route['default_controller'] = "Admin_controller";
 }
 else
 {
    $route['default_controller'] = "Welcome";
 }
 $route['404_override'] = '';
 $route['translate_uri_dashes'] = TRUE;


问:
C#: Interpolated Strings- Visual Studio 2013?
I am looking at this example from the google cloud platform.

https://cloud.google.com/storage/docs/json_api/v1/json-api-dotnet-samples

Specifically:

```<code>public void DownloadStream(string bucketName)
{
    StorageService storage = CreateStorageClient();

    using (var stream = new MemoryStream())
    {
        storage.Objects.Get(bucketName, "my-file.txt").Download(stream);

        var content = Encoding.UTF8.GetString(stream.GetBuffer());

        Console.WriteLine($"Downloaded my-file.txt with content: {content}");
    }
}
</code>```

Console.WriteLine($ keeps giving me an error. I am using Visual Studio 2013 and cant seem to get this to work properly. Instead what i have to do is remove the dollar sign and + content as a variable.

I read this is a new syntax for C# version 6? Am i missing something? - Cant do this on Visual studio 2013?

Thanks for your responses!

I have updated my solution to provide a picture of the error. All it says is ) Expected.

It seems it does not recognize the dollar sign.

答: Visual Studio 2013 does not support interpolated strings. This is a feature from 2015.</p>

Body:
I am looking at this example from the google cloud platform.

https://cloud.google.com/storage/docs/json_api/v1/json-api-dotnet-samples

Specifically:

public void DownloadStream(string bucketName)
{
    StorageService storage = CreateStorageClient();

    using (var stream = new MemoryStream())
    {
        storage.Objects.Get(bucketName, "my-file.txt").Download(stream);

        var content = Encoding.UTF8.GetString(stream.GetBuffer());

        Console.WriteLine($"Downloaded my-file.txt with content: {content}");
    }
}

Console.WriteLine($ keeps giving me an error. I am using Visual Studio 2013 and cant seem to get this to work properly. Instead what i have to do is remove the dollar sign and + content as a variable.

I read this is a new syntax for C# version 6? Am i missing something? - Cant do this on Visual studio 2013?

Thanks for your responses!

I have updated my solution to provide a picture of the error. All it says is ) Expected.

It seems it does not recognize the dollar sign.