问:
Python and JSON - Interact directly with items
I'm new to the Bose SoundTouch API.

I need to interact with a command that returns a JSON file constructed like that.

```<code>{
  "deviceID": "string",
  "source": "string",
  "ContentItem": {
    "source": "string",
    "type": "string",
    "location": "string",
    "sourceAccount": "string",
    "preset": "string",
    "itemName": {
      "text": "string"
    },
    "offset": 0,
    "isNavigate": true,
    "isPresetable": true
  },
  "track": "string",
  "artist": "string",
  "album": "string",
  "stationName": "string",
  "art": {
    "artImageStatus": "string",
    "url": "string"
  },
  "playStatus": "string",
  "description": "string",
  "stationLocation": "string"
}
</code>```

I would like to extract only "source" and "location" in the ContentItem.

```<code>import json

with open('test.json') as json_file:
    data = json.load(json_file)
    for p in data['ContentItem']:
        print('Source: ' + (p['source']))
        varSource = p['source']
        print('Location: ' + p['location'])
        varLocation = p['location']
        print('Type: ' + p['type'])

        print('')

print(varSource)
print(varLocation)
</code>```

Is there a way to complete this more simply ?

答:
```<code>content = data['ContentItem']
source, location = content['source'], content['location']
</code>```

or

```<code>source = data['ContentItem']['source']
location = data['ContentItem']['location']
</code>```

or

```<code>source, location = data['ContentItem']['source'], data['ContentItem']['location']
</code>```

or

```<code>source, location = (data['ContentItem'][s] for s in ('source', 'location'))
</code>```

or

```<code>from operator import itemgetter
source, location = itemgetter('source', 'location')(data['ContentItem'])
</code>```

Body:
I'm new to the Bose SoundTouch API.

I need to interact with a command that returns a JSON file constructed like that.

{
  "deviceID": "string",
  "source": "string",
  "ContentItem": {
    "source": "string",
    "type": "string",
    "location": "string",
    "sourceAccount": "string",
    "preset": "string",
    "itemName": {
      "text": "string"
    },
    "offset": 0,
    "isNavigate": true,
    "isPresetable": true
  },
  "track": "string",
  "artist": "string",
  "album": "string",
  "stationName": "string",
  "art": {
    "artImageStatus": "string",
    "url": "string"
  },
  "playStatus": "string",
  "description": "string",
  "stationLocation": "string"
}

I would like to extract only "source" and "location" in the ContentItem.

import json

with open('test.json') as json_file:
    data = json.load(json_file)
    for p in data['ContentItem']:
        print('Source: ' + (p['source']))
        varSource = p['source']
        print('Location: ' + p['location'])
        varLocation = p['location']
        print('Type: ' + p['type'])

        print('')

print(varSource)
print(varLocation)

Is there a way to complete this more simply ?

Body:
content = data['ContentItem']
source, location = content['source'], content['location']

or

source = data['ContentItem']['source']
location = data['ContentItem']['location']

or

source, location = data['ContentItem']['source'], data['ContentItem']['location']

or

source, location = (data['ContentItem'][s] for s in ('source', 'location'))

or

from operator import itemgetter
source, location = itemgetter('source', 'location')(data['ContentItem'])


来源: stackexchange

问:
Sitecore Caching for SSL + non-SSL sublayout
I have a little issue with a sublayout outputting data which should differ between SSL and non-SSL requests.

To replicate if you create a sublayout and in code behind render out the URL. If you then add this sublayout to a page through the sitecore interface, eg: presentation>details etc and set caching on and set all caching variable to on. Do you publish etc so the page is now viewable (also behaves the same if your doing it directly calling the the control by sublayout control in code).

If you execute this page in non-ssl mode (http://URL) you will get a URL such as; http://URL...
Then if you execute this page in ssl mode (https://URL) your output will still be http://URL...

So does anyone know of a way to get this so we an cache both instances.

Regards,
Chris

答:
I think I see your issue -- you are outputting absolute URLs for your images, and based on whether or not SSL is used on the first request, the SSL URL of your images may or may not be included in the cached output.

My first suggestion is to disable absolute URLs, if possible. Is there a reason you need them?

My backup would be to point you at the renderingControls configuration in Web.config. If we're talking about sublayouts here, you could potentially subclass sublayout, and create a new factory for sublayout rendering. When you subclass sublayout, override its GetCacheKey method to add a flag if the request is ssl...

//if request is ssl
return base.GetCacheKey()+"#ssl";

Fair warning that I've never done this, just making an educated suggestion based on available Sitecore config and APIs.

Good luck.

ContentLicense: CC BY-SA 3.0


问:
How to query date with a column name in SQL?
how do I query just the date and not the time from the stored data?
I have tried the following:

```<code>select FirstName, dob from table1 where rno='123';
</code>```

What I require is dob returns just the date along with a column name, so I can use the value later in a c# .net project. Also, is it possible to change the format of the date? How do I customize it to DD-MM-YYYY or YYYY-MM-DD?

答:
Look at DATE_FORMAT

So try

```<code>select FirstName, DATE_FORMAT(dob, '%d-%m-%Y') as dob from table1 where rno='123';
</code>```

ContentLicense: CC BY-SA 4.0

Body:
how do I query just the date and not the time from the stored data?
I have tried the following:

select FirstName, dob from table1 where rno='123';

What I require is dob returns just the date along with a column name, so I can use the value later in a c# .net project. Also, is it possible to change the format of the date? How do I customize it to DD-MM-YYYY or YYYY-MM-DD?

Body:
Look at DATE_FORMAT

So try

select FirstName, DATE_FORMAT(dob, '%d-%m-%Y') as dob from table1 where rno='123';


问:
replace several matches of a substring with their indexes
assuming that you have a string with multiple occurrences of the same substring what would be the best one-liner to replace the matches with their another substring which contains the index of the math as well? As an example, let's say you have the following string: This is a test. and we want to replace all the occurrences of is with X and their index to have something like: ThX-0 X-1 a test.

Any ideas on this?

答:
Perl to the rescue!

```<code>echo 'This is a test.' | perl -pe 's/is/"X-" . $c++/ge'
</code>```

-p reads the input line by line, runs the code on it and outputs the processed line.

s///g runs a substitution globally, i.e. on all the positions where it's possible

/e interprets the replacement part as code and runs it. The code here uses the concatenation operator . on the string X- and the value of $c, increasing it by one at the same time.

Body:
Perl to the rescue!

echo 'This is a test.' | perl -pe 's/is/"X-" . $c++/ge'

-p reads the input line by line, runs the code on it and outputs the processed line.

s///g runs a substitution globally, i.e. on all the positions where it's possible

/e interprets the replacement part as code and runs it. The code here uses the concatenation operator . on the string X- and the value of $c, increasing it by one at the same time.


问:
Can't compile C program on a Mac after upgrade to Mojave
I have used the gcc command on the terminal to compile C programs but all of a sudden, after an update to my Mac's OS (to macOS 10.14 Mojave, and XCode 10.0), I started receiving the message:

```<code>test.c:8:10: fatal error: stdio.h: No such file or directory
#include <stdio.h>
         ^~~~~~~~~
compilation terminated.
</code>```

I already have gcc installed as I can find it in /usr/local/bin and there really is a gcc in there. I tried running the same file on my other iMac and it worked without any issue.

I tried running xcode-select --install and it already was installed, hence it didn't fix the issue I'm having now. I'm guessing that the path is messed up as it doesn't seem like it can find gcc after I started copying and pasting some commands from other resources to solve this issue.

Would like some help on this.

答:
I tried almost all the posted solutions and nothing worked for me. I use Mojave OS (10.14.6) and what finally worked for me (after removing and re-installing Xcode and CLTs and SDK headers):

Install Clang v8 from https://cran.r-project.org/bin/macosx/tools/

Modify the following lines from ~/.R/Makevars file

```<code>CC=/usr/local/opt/llvm/bin/clang -fopenmp
CXX=/usr/local/opt/llvm/bin/clang++
</code>```

with

```<code>CC=/usr/local/clang8/bin/clang -fopenmp
CXX=/usr/local/clang8/bin/clang++
</code>```

Now R packages that rely on C compilers install successfully

Body:
I have used the gcc command on the terminal to compile C programs but all of a sudden, after an update to my Mac's OS (to macOS 10.14 Mojave, and XCode 10.0), I started receiving the message:

test.c:8:10: fatal error: stdio.h: No such file or directory
#include <stdio.h>
         ^~~~~~~~~
compilation terminated.

I already have gcc installed as I can find it in /usr/local/bin and there really is a gcc in there. I tried running the same file on my other iMac and it worked without any issue.

I tried running xcode-select --install and it already was installed, hence it didn't fix the issue I'm having now. I'm guessing that the path is messed up as it doesn't seem like it can find gcc after I started copying and pasting some commands from other resources to solve this issue.

Would like some help on this.

Body:
I tried almost all the posted solutions and nothing worked for me. I use Mojave OS (10.14.6) and what finally worked for me (after removing and re-installing Xcode and CLTs and SDK headers):

Install Clang v8 from https://cran.r-project.org/bin/macosx/tools/

Modify the following lines from ~/.R/Makevars file

CC=/usr/local/opt/llvm/bin/clang -fopenmp
CXX=/usr/local/opt/llvm/bin/clang++

with

CC=/usr/local/clang8/bin/clang -fopenmp
CXX=/usr/local/clang8/bin/clang++

Now R packages that rely on C compilers install successfully


问:
How to Export HTML Table to PDF
I have a small form in HTML that I'm exporting to excel. I would like to be able to keep the same format that shows in excel but in a PDF. I've tried many different ways but still have not been able to successfully export to a PDF.          Please check out my jsfiddle. Thanks!

https://jsfiddle.net/jphuizar/dcv3mg21/

var tablesToExcel = (function() {
  var uri = 'data:application/vnd.ms-excel;base64,',
    tmplWorkbookXML = '<?xml version="1.0"?><?mso-application progid="Excel.Sheet"?><Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">' +
    '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"><Author>Axel Richter</Author><Created>{created}</Created></DocumentProperties>' +
    '' +
    '' +
    '</Styles>' +
    '{worksheets}</Workbook>',
    tmplWorksheetXML = '<Worksheet ss:Name="{nameWS}">
{rows}
</Worksheet>',
    tmplCellXML = '<Cell{attributeStyleID}{attributeFormula}><Data ss:Type="{nameType}">{data}</Data></Cell>',
    base64 = function(s) {
      return window.btoa(unescape(encodeURIComponent(s)))
    },
    format = function(s, c) {
      return s.replace(/{(\w+)}/g, function(m, p) {
        return c[p];
      })
    }
  return function(tables, wsnames, wbname, appname) {

    var ctx = "";
    var workbookXML = "";
    var worksheetsXML = "";
    var rowsXML = "";

    /*

    for (var j = 0; j < column.length; j++)
      //goes through <select> tags
      {const select = column[j].querySelector('select');

      */

    for (var i = 0; i < tables.length; i++) {
      if (!tables[i].nodeType) tables[i] = document.getElementById(tables[i]);
      for (var j = 0; j < tables[i].rows.length; j++) {
        rowsXML += '<Row>'
        for (var k = 0; k < tables[i].rows[j].cells.length; k++) {
          var dataType = tables[i].rows[j].cells[k].getAttribute("data-type");
          var dataStyle = tables[i].rows[j].cells[k].getAttribute("data-style");
          var dataValue = tables[i].rows[j].cells[k].getAttribute("data-value");
          var select = tables[i].rows[j].cells[k].getElementsByTagName("select")[0];
          dataValue = (dataValue) ? dataValue : (select ? select.options[select.selectedIndex].value : tables[i].rows[j].cells[k].innerHTML);
          dataValue = (dataValue) ? dataValue : tables[i].rows[j].cells[k].innerHTML;
          var dataFormula = tables[i].rows[j].cells[k].getAttribute("data-formula");
          dataFormula = (dataFormula) ? dataFormula : (appname == 'Calc' && dataType == 'DateTime') ? dataValue : null;
          ctx = {
            attributeStyleID: (dataStyle == 'Currency' || dataStyle == 'Date') ? ' ss:StyleID="' + dataStyle + '"' : '',
            nameType: (dataType == 'Number' || dataType == 'DateTime' || dataType == 'Boolean' || dataType == 'Error') ? dataType : 'String',
            data: (dataFormula) ? '' : dataValue,
            attributeFormula: (dataFormula) ? ' ss:Formula="' + dataFormula + '"' : ''
          };
          rowsXML += format(tmplCellXML, ctx);
        }

        rowsXML += '</Row>'
      }
      ctx = {
        rows: rowsXML,
        nameWS: wsnames[i] || 'Sheet' + i
      };
      worksheetsXML += format(tmplWorksheetXML, ctx);
      rowsXML = "";
    }

    ctx = {
      created: (new Date()).getTime(),
      worksheets: worksheetsXML
    };
    workbookXML = format(tmplWorkbookXML, ctx);

    console.log(workbookXML);

    var link = document.createElement("A");
    link.href = uri + base64(workbookXML);
    link.download = wbname || 'Workbook.xls';
    link.target = '_blank';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
  var rows = document.querySelectorAll("table tr");
})();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- 1 -->
<table id="table1">
  <p>Table 1</p>
  <hr>
  <tr>
    <td>Question 1:</td>
    <td>
      <select>
        <option value="0">0</option>
        <option value="1">1</option>
      </select>
    </td>
  </tr>
  <tr>
    <td>Question 2:</td>
    <td>
      <select>
        <option value="0">0</option>
        <option value="1">1</option>
      </select>
    </td>
  </tr>
</table>

<!-- 2 -->
<p>Table 2</p>
<hr>
<table id="table2">
  <tr>
    <td>Question 3:</td>
    <td>
      <select>
        <option value="0">0</option>
        <option value="1">1</option>
      </select>
    </td>
  </tr>
  <tr>
    <td>Question 4:</td>
    <td>
      <select>
        <option value="0">0</option>
        <option value="1">1</option>
      </select>
    </td>
  </tr>
</table>

<!-- 3 -->
<p>Table 3</p>
<hr>
<table id="table3">
  <tr>
    <td>Question 5:</td>
    <td>
      <select>
        <option value="0">0</option>
        <option value="1">1</option>
      </select>
    </td>
  </tr>
  <tr>
    <td>Question 6:</td>
    <td>
      <select>
        <option value="0">0</option>
        <option value="1">1</option>
      </select>
    </td>
  </tr>
</table>
<button onclick="tablesToExcel(['table1','table2','table3'], ['Summary','SectionA', 'SectionB'], 'TestBook.xls', 'Excel')">Export to Excel</button></code>```

答:
use this code

```<code><html>
<head>
    <title>Convert Table to PDF using JavaScript</title>
    <style>
        table
        {
            width: 300px;
            font: 17px Calibri;
        }
        table, th, td
        {
            border: solid 1px #DDD;
            border-collapse: collapse;
            padding: 2px 3px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div id="tab">
        <table>
            <tr>
                <th>Name</th>
                    <th>Age</th>
                        <th>Job</th>
            </tr>
            <tr>
                <td>Brian</td>
                    <td>41</td>
                        <td>Blogger</td>
            </tr>
            <tr>
                <td>Matt</td>
                    <td>25</td>
                        <td>Programmer</td>
            </tr>
            <tr>
                <td>Arun</td>
                    <td>39</td>
                        <td>Writter</td>
            </tr>
        </table>
    </div>

    <p>
        <input type="button" value="Create PDF"
            id="btPrint" onclick="createPDF()" />
    </p>
</body>
<script>
    function createPDF() {
        var sTable = document.getElementById('tab').innerHTML;

        var style = "<style>";
        style = style + "table {width: 100%;font: 17px Calibri;}";
        style = style + "table, th, td {border: solid 1px #DDD; border-collapse: collapse;";
        style = style + "padding: 2px 3px;text-align: center;}";
        style = style + "</style>";

        // CREATE A WINDOW OBJECT.
        var win = window.open('', '', 'height=700,width=700');

        win.document.write('<html><head>');
        win.document.write('<title>Profile</title>');   // <title> FOR PDF HEADER.
        win.document.write(style);          // ADD STYLE INSIDE THE HEAD TAG.
        win.document.write('</head>');
        win.document.write('<body>');
        win.document.write(sTable);         // THE TABLE CONTENTS INSIDE THE BODY TAG.
        win.document.write('</body></html>');

        win.document.close();   // CLOSE THE CURRENT WINDOW.

        win.print();    // PRINT THE CONTENTS.
    }
</script>
</html>

</code>```

Reference

Title: How to Export HTML Table to PDF

Body:
I have a small form in HTML that I'm exporting to excel. I would like to be able to keep the same format that shows in excel but in a PDF. I've tried many different ways but still have not been able to successfully export to a PDF.          Please check out my jsfiddle. Thanks!

https://jsfiddle.net/jphuizar/dcv3mg21/

var tablesToExcel = (function() {
  var uri = 'data:application/vnd.ms-excel;base64,',
    tmplWorkbookXML = '<?xml version="1.0"?><?mso-application progid="Excel.Sheet"?><Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">' +
    '<DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"><Author>Axel Richter</Author><Created>{created}</Created></DocumentProperties>' +
    '' +
    '' +
    '</Styles>' +
    '{worksheets}</Workbook>',
    tmplWorksheetXML = '<Worksheet ss:Name="{nameWS}">
{rows}
</Worksheet>',
    tmplCellXML = '<Cell{attributeStyleID}{attributeFormula}><Data ss:Type="{nameType}">{data}</Data></Cell>',
    base64 = function(s) {
      return window.btoa(unescape(encodeURIComponent(s)))
    },
    format = function(s, c) {
      return s.replace(/{(\w+)}/g, function(m, p) {
        return c[p];
      })
    }
  return function(tables, wsnames, wbname, appname) {

    var ctx = "";
    var workbookXML = "";
    var worksheetsXML = "";
    var rowsXML = "";

    /*

    for (var j = 0; j < column.length; j++)
      //goes through <select> tags
      {const select = column[j].querySelector('select');

      */

    for (var i = 0; i < tables.length; i++) {
      if (!tables[i].nodeType) tables[i] = document.getElementById(tables[i]);
      for (var j = 0; j < tables[i].rows.length; j++) {
        rowsXML += '<Row>'
        for (var k = 0; k < tables[i].rows[j].cells.length; k++) {
          var dataType = tables[i].rows[j].cells[k].getAttribute("data-type");
          var dataStyle = tables[i].rows[j].cells[k].getAttribute("data-style");
          var dataValue = tables[i].rows[j].cells[k].getAttribute("data-value");
          var select = tables[i].rows[j].cells[k].getElementsByTagName("select")[0];
          dataValue = (dataValue) ? dataValue : (select ? select.options[select.selectedIndex].value : tables[i].rows[j].cells[k].innerHTML);
          dataValue = (dataValue) ? dataValue : tables[i].rows[j].cells[k].innerHTML;
          var dataFormula = tables[i].rows[j].cells[k].getAttribute("data-formula");
          dataFormula = (dataFormula) ? dataFormula : (appname == 'Calc' && dataType == 'DateTime') ? dataValue : null;
          ctx = {
            attributeStyleID: (dataStyle == 'Currency' || dataStyle == 'Date') ? ' ss:StyleID="' + dataStyle + '"' : '',
            nameType: (dataType == 'Number' || dataType == 'DateTime' || dataType == 'Boolean' || dataType == 'Error') ? dataType : 'String',
            data: (dataFormula) ? '' : dataValue,
            attributeFormula: (dataFormula) ? ' ss:Formula="' + dataFormula + '"' : ''
          };
          rowsXML += format(tmplCellXML, ctx);
        }

        rowsXML += '</Row>'
      }
      ctx = {
        rows: rowsXML,
        nameWS: wsnames[i] || 'Sheet' + i
      };
      worksheetsXML += format(tmplWorksheetXML, ctx);
      rowsXML = "";
    }

    ctx = {
      created: (new Date()).getTime(),
      worksheets: worksheetsXML
    };
    workbookXML = format(tmplWorkbookXML, ctx);

    console.log(workbookXML);

    var link = document.createElement("A");
    link.href = uri + base64(workbookXML);
    link.download = wbname || 'Workbook.xls';
    link.target = '_blank';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
  var rows = document.querySelectorAll("table tr");
})();

Table 1

    Question 1:

      <select>
        <option value="0">0</option>
        <option value="1">1</option>
      </select>

    Question 2:

      <select>
        <option value="0">0</option>
        <option value="1">1</option>
      </select>

Table 2

    Question 3:

      <select>
        <option value="0">0</option>
        <option value="1">1</option>
      </select>

    Question 4:

      <select>
        <option value="0">0</option>
        <option value="1">1</option>
      </select>

Table 3

    Question 5:

      <select>
        <option value="0">0</option>
        <option value="1">1</option>
      </select>

    Question 6:

      <select>
        <option value="0">0</option>
        <option value="1">1</option>
      </select>

<button onclick="tablesToExcel(['table1','table2','table3'], ['Summary','SectionA', 'SectionB'], 'TestBook.xls', 'Excel')">Export to Excel</button>

Body:
use this code

<html>
<head>
    <title>Convert Table to PDF using JavaScript</title>
    <style>
        table
        {
            width: 300px;
            font: 17px Calibri;
        }
        table, th, td
        {
            border: solid 1px #DDD;
            border-collapse: collapse;
            padding: 2px 3px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div id="tab">
        <table>
            <tr>
                <th>Name</th>
                    <th>Age</th>
                        <th>Job</th>
            </tr>
            <tr>
                <td>Brian</td>
                    <td>41</td>
                        <td>Blogger</td>
            </tr>
            <tr>
                <td>Matt</td>
                    <td>25</td>
                        <td>Programmer</td>
            </tr>
            <tr>
                <td>Arun</td>
                    <td>39</td>
                        <td>Writter</td>
            </tr>
        </table>
    </div>

    <p>
        <input type="button" value="Create PDF"
            id="btPrint" onclick="createPDF()" />
    </p>
</body>
<script>
    function createPDF() {
        var sTable = document.getElementById('tab').innerHTML;

        var style = "<style>";
        style = style + "table {width: 100%;font: 17px Calibri;}";
        style = style + "table, th, td {border: solid 1px #DDD; border-collapse: collapse;";
        style = style + "padding: 2px 3px;text-align: center;}";
        style = style + "</style>";

        // CREATE A WINDOW OBJECT.
        var win = window.open('', '', 'height=700,width=700');

        win.document.write('<html><head>');
        win.document.write('<title>Profile</title>');   // <title> FOR PDF HEADER.
        win.document.write(style);          // ADD STYLE INSIDE THE HEAD TAG.
        win.document.write('</head>');
        win.document.write('<body>');
        win.document.write(sTable);         // THE TABLE CONTENTS INSIDE THE BODY TAG.
        win.document.write('</body></html>');

        win.document.close();   // CLOSE THE CURRENT WINDOW.

        win.print();    // PRINT THE CONTENTS.
    }
</script>
</html>

Reference


问:
SQL does not show me the time (hour by day)
SQL does not show me the time, I have a business day table, and I need that for each business day it shows me a time range from 9 to 19 hours to then show the number of transactions per hour, for each day of the month.

I can not generate stored procedure only query can be performed not to alter the database by company policy

I have a query like that.

SELECT
    TO_CHAR(cd.days, 'yyyymmdd') AS fechaTransaccion,
    NVL(SUM(data.numTransacionExitosa),0)       AS numTransacionExitosa,
    NVL(SUM(data.numTransactionPendiente),0)    AS numTransactionPendiente
FROM
    calendardays cd
LEFT JOIN
    data
ON
    cd.days = data.settledate
WHERE
    cd.DAYs BETWEEN ADD_MONTHS(TRUNC(to_date(20200201, 'yyyymmdd'), 'MM'),-1) AND ADD_MONTHS(LAST_DAY(TRUNC(to_date(20200201, 'yyyymmdd'))),-1)
and substr(SETTLEDATE, 10, 2) between 9 and 19
GROUP BY
    cd.days,  substr(SETTLEDATE, 10, 2)
ORDER BY
    cd.days
```

i need show like this

答:
Hard to understand/answer without seeing your data, but if you need to extract hour from date, follow the below example:

select extract(hour from cast(sysdate as timestamp)) hour from dual;

Body:
SQL does not show me the time, I have a business day table, and I need that for each business day it shows me a time range from 9 to 19 hours to then show the number of transactions per hour, for each day of the month.

I can not generate stored procedure only query can be performed not to alter the database by company policy

I have a query like that.

SELECT
    TO_CHAR(cd.days, 'yyyymmdd') AS fechaTransaccion,
    NVL(SUM(data.numTransacionExitosa),0)       AS numTransacionExitosa,
    NVL(SUM(data.numTransactionPendiente),0)    AS numTransactionPendiente
FROM
    calendardays cd
LEFT JOIN
    data
ON
    cd.days = data.settledate
WHERE
    cd.DAYs BETWEEN ADD_MONTHS(TRUNC(to_date(20200201, 'yyyymmdd'), 'MM'),-1) AND ADD_MONTHS(LAST_DAY(TRUNC(to_date(20200201, 'yyyymmdd'))),-1)
and substr(SETTLEDATE, 10, 2) between 9 and 19
GROUP BY
    cd.days,  substr(SETTLEDATE, 10, 2)
ORDER BY
    cd.days

i need show like this


问:
Changing User DSN ODBC Setting in REG is not changing in ODBC administration
Well I guess you could say it is.. not really sure.

Anyway I'll do my best to explain.

We are updating a server and need to update the an ODBC setting it connects to so they match. In the past I have just changed the REG setting on my pc and exported it then pushed it out with a .bat file.

The issue here is that the setting does not show under

```<code>Computer\HKEY_CURRENT_USER\Software\ODBC\ODBC.IN
or
Computer\HKEY_CURRENT_USER\Software\ODBC\ODBC.INI\ODBC Data Sources
</code>```

Well it kinda does..

In ODBC Data Source Administration we have a User DNS named 'Metafile'. When you go to configure it the first screen it says "which SQL Server do you want to connect to?". I need to update this.

The only other configuration is that we change the defualt database which ideally wouldn't be affected with this change. It is currently set to "Metaviewer_SQL".

Now back to the REG editor.

Under "Computer\HKEY_CURRENT_USER\Software\ODBC\ODBC.INI" there is a key for Metaviewer_SQL with a value for Server that also points to the old server. If I manually change that to the new one, export Metaviewer_SQL.reg and run that it will only change the Key in the REG editor not the ODBC setting in ODBC administration just called 'Metafile'.

How do I update this ODBC setting so that the Default Database AND the "Which SQL server do you want to connect to" are both updated? I am able to update the default database but not the other one which will break when that server goes offline.

I hope that all makes sense,  I can answer any questions or post screen shots if necessary, thanks!

答:
Export the whole Metafile registry key (the dsn name appears as a registry key under ODBC.INI)
example:

```<code>[HKEY_CURRENT_USER\Software\ODBC\ODBC.INI\Metafile]
"Driver"="C:\\Windows\\system32\\SQLSRV32.dll or any other odbc driver"
"Server"="sql server name goes here"
"Database"="database name goes here"
"LastUser"="sqluser goes here does it really matter?"
"Trusted_Connection"="Yes"
</code>```

If  you execute this registry file, it will apply/change all values.
If you would like to change only the server and the database then remove all other values from the reg file. The following will change only the dsn server&db, all other values in the registry remain intact.

```<code>[HKEY_CURRENT_USER\Software\ODBC\ODBC.INI\Metafile ]
"Server"="new sql server name goes here"
"Database"="new database name goes here"
</code>```

Changes are reflected in odbcad32 immediately.

Body:
Well I guess you could say it is.. not really sure.

Anyway I'll do my best to explain.

We are updating a server and need to update the an ODBC setting it connects to so they match. In the past I have just changed the REG setting on my pc and exported it then pushed it out with a .bat file.

The issue here is that the setting does not show under

Computer\HKEY_CURRENT_USER\Software\ODBC\ODBC.IN
or
Computer\HKEY_CURRENT_USER\Software\ODBC\ODBC.INI\ODBC Data Sources

Well it kinda does..

In ODBC Data Source Administration we have a User DNS named 'Metafile'. When you go to configure it the first screen it says "which SQL Server do you want to connect to?". I need to update this.

The only other configuration is that we change the defualt database which ideally wouldn't be affected with this change. It is currently set to "Metaviewer_SQL".

Now back to the REG editor.

Under "Computer\HKEY_CURRENT_USER\Software\ODBC\ODBC.INI" there is a key for Metaviewer_SQL with a value for Server that also points to the old server. If I manually change that to the new one, export Metaviewer_SQL.reg and run that it will only change the Key in the REG editor not the ODBC setting in ODBC administration just called 'Metafile'.

How do I update this ODBC setting so that the Default Database AND the "Which SQL server do you want to connect to" are both updated? I am able to update the default database but not the other one which will break when that server goes offline.

I hope that all makes sense,  I can answer any questions or post screen shots if necessary, thanks!

Body:
Export the whole Metafile registry key (the dsn name appears as a registry key under ODBC.INI)
example:

[HKEY_CURRENT_USER\Software\ODBC\ODBC.INI\Metafile]
"Driver"="C:\\Windows\\system32\\SQLSRV32.dll or any other odbc driver"
"Server"="sql server name goes here"
"Database"="database name goes here"
"LastUser"="sqluser goes here does it really matter?"
"Trusted_Connection"="Yes"

If  you execute this registry file, it will apply/change all values.
If you would like to change only the server and the database then remove all other values from the reg file. The following will change only the dsn server&db, all other values in the registry remain intact.

[HKEY_CURRENT_USER\Software\ODBC\ODBC.INI\Metafile ]
"Server"="new sql server name goes here"
"Database"="new database name goes here"

Changes are reflected in odbcad32 immediately.


问:
How to concatenate char and string on iPhone?
I want to add some marks to separate some strings.
How to add a char to a string?

e.g. add '\x01' to "Hello", add '\x02' before "World" and add '\x03' after "World".

So I can create a string "\x01 Hello \x02 World \x03" which has some separate marks.

答:
If you want to modify a string, you have to use NSMutableString instead of NSString. There is no such need if you want to create a string from scratch.

For instance, you may want to use +stringWithFormat: method:

```<code>NSString * myString = [NSString stringWithFormat:@"%c %@ %c %@ %c",
                                                 0x01,
                                                 @"Hello",
                                                 0x02,
                                                 @"World",
                                                 0x03];
</code>```

OwnerDisplayName: iphony

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: andynormancx

Body:
If you want to modify a string, you have to use NSMutableString instead of NSString. There is no such need if you want to create a string from scratch.

For instance, you may want to use +stringWithFormat: method:

NSString * myString = [NSString stringWithFormat:@"%c %@ %c %@ %c",
                                                 0x01,
                                                 @"Hello",
                                                 0x02,
                                                 @"World",
                                                 0x03];

OwnerDisplayName: mouviciel


问:
Stopping a runaway Lua subprocess
I have embedded Lua in an Objective-C application using LuaObjCBridge. I need to know how to stop the Lua process if it taking too much time (infinite loop?).

Would running it in a separate thread help?

答:
For OS-level restrictions like kaizer.se mentions, one good approach for running Lua stand-alone on *nix systems is to use ulimit -t 1 to restrict the Lua process to one second of CPU time. This is the approach the CGI script that powers the live demo on Lua.org uses.

For an application like the one you described, using your environment's thread facilities is the best option.

Title: Stopping a runaway Lua subprocess


问:
I want to get a single database SQL string
I got a little problem with this:

```<code>readonly LoginMandant logon = new LoginMandant();
string query = "SELECT Name FROM tMandant WHERE Id_Mandant = " + userDetails.Id_Mandant + ";";

Session["MandantName"] = logon.Database.SqlQuery<string>(query).SingleOrDefaultAsync();
</code>```

and it returns:

```<code>System.Threading.Tasks.Task`1[System.String]
</code>```

But why? I wanted a single string like "test" in there.

答:
Async will require you to await.

```<code>Session["MandantName"] = await logon.Database.SqlQuery<string>(query).SingleOrDefaultAsync();
</code>```

However, the calling method also has to be an async (and its caller call await, and so on). I highly recommend this, however, if you are really short on time, you could do the SingleOrDefaultAsync().Result or simply call the SingleOrDefault(), however, it will block the execution until the database query completes.

IMPORTANT: Avoid string concatenation for the query string. You are risking SQL injection.

Body:
I got a little problem with this:

readonly LoginMandant logon = new LoginMandant();
string query = "SELECT Name FROM tMandant WHERE Id_Mandant = " + userDetails.Id_Mandant + ";";

Session["MandantName"] = logon.Database.SqlQuery<string>(query).SingleOrDefaultAsync();

and it returns:

System.Threading.Tasks.Task`1[System.String]

But why? I wanted a single string like "test" in there.

Body:
Async will require you to await.

Session["MandantName"] = await logon.Database.SqlQuery<string>(query).SingleOrDefaultAsync();

However, the calling method also has to be an async (and its caller call await, and so on). I highly recommend this, however, if you are really short on time, you could do the SingleOrDefaultAsync().Result or simply call the SingleOrDefault(), however, it will block the execution until the database query completes.

IMPORTANT: Avoid string concatenation for the query string. You are risking SQL injection.


问:
'@react-navigation/stack' has stopped working with error - unable to resolve module
I have been successfully using React Navigation Stack (V5) for about a week now and today my app will not build as the error - unable to resolve module is now shown.

Error Message

The module is installed as shown in my package.json file -

```<code>{
  "scripts": {
    "postinstall": "jetify",
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "web": "expo start --web",
    "start": "react-native start",
    "test": "jest"
  },
  "dependencies": {
    "@react-native-community/masked-view": "^0.1.6",
    "expo": "~36.0.0",
    "expo-linear-gradient": "^8.0.0",
    "react": "~16.9.0",
    "react-dom": "~16.9.0",
    "react-native": "~0.61.4",
    "react-native-fontawesome": "^7.0.0",
    "react-native-gesture-handler": "^1.5.6",
    "react-native-keyboard-aware-scroll-view": "^0.9.1",
    "react-native-reanimated": "^1.7.0",
    "react-native-safe-area-context": "^0.7.2",
    "react-native-screens": "^2.0.0-beta.2",
    "react-native-unimodules": "~0.7.0",
    "react-native-web": "~0.11.7",
    "react-navigation": "^4.0.10",
    "react-navigation-stack": "^1.10.3"
  },
  "devDependencies": {
    "@babel/core": "~7.6.0",
    "babel-jest": "~24.9.0",
    "jest": "~24.9.0",
    "jetifier": "~1.6.4",
    "metro-react-native-babel-preset": "~0.56.0",
    "react-test-renderer": "~16.9.0"
  },
  "jest": {
    "preset": "react-native"
  },
  "private": true
}
</code>```

I have tried the following steps to try resolve the issue -

Deleted node_modules

Cleared yarn and npm cache

Ran npm install to install dependencies again

Cleared expo cache

Deleted and re-downoaded expo app on iOS device

Also tried installing the react navigation stack package again

Still receiving the same error message.

Would MASSIVELY appreciate any ideas.. currently losing my head over this :|

答:
You don't have @react-navigation/stack or any @react-navigation/xxx packages in your package.json. You have react-navigation-xxx packages which are for v4.

Follow the getting started guide to set it up properly https://reactnavigation.org/docs/en/getting-started.html

Body:
I have been successfully using React Navigation Stack (V5) for about a week now and today my app will not build as the error - unable to resolve module is now shown.

Error Message

The module is installed as shown in my package.json file -

{
  "scripts": {
    "postinstall": "jetify",
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "web": "expo start --web",
    "start": "react-native start",
    "test": "jest"
  },
  "dependencies": {
    "@react-native-community/masked-view": "^0.1.6",
    "expo": "~36.0.0",
    "expo-linear-gradient": "^8.0.0",
    "react": "~16.9.0",
    "react-dom": "~16.9.0",
    "react-native": "~0.61.4",
    "react-native-fontawesome": "^7.0.0",
    "react-native-gesture-handler": "^1.5.6",
    "react-native-keyboard-aware-scroll-view": "^0.9.1",
    "react-native-reanimated": "^1.7.0",
    "react-native-safe-area-context": "^0.7.2",
    "react-native-screens": "^2.0.0-beta.2",
    "react-native-unimodules": "~0.7.0",
    "react-native-web": "~0.11.7",
    "react-navigation": "^4.0.10",
    "react-navigation-stack": "^1.10.3"
  },
  "devDependencies": {
    "@babel/core": "~7.6.0",
    "babel-jest": "~24.9.0",
    "jest": "~24.9.0",
    "jetifier": "~1.6.4",
    "metro-react-native-babel-preset": "~0.56.0",
    "react-test-renderer": "~16.9.0"
  },
  "jest": {
    "preset": "react-native"
  },
  "private": true
}

I have tried the following steps to try resolve the issue -

Deleted node_modules

Cleared yarn and npm cache

Ran npm install to install dependencies again

Cleared expo cache

Deleted and re-downoaded expo app on iOS device

Also tried installing the react navigation stack package again

Still receiving the same error message.

Would MASSIVELY appreciate any ideas.. currently losing my head over this :|


问:
How to get the exact child element with corresponding parent only from multilevel embedded MongoDB document using C#
Trying to get exact child document with it's corresponding parent document from embedded MongoDB document using C#  but query return all the child and corresponding parent and others . how to set parameter to
get the exact match with Filter and findOptions. My expected result will be Channel 1 -> Episode 1 & it's Child Track which id is given .
Here is my code:

```<code>// Class
namespace CrudWithMultilvelNestedDoc
{
    public class Channel
    {
        [BsonId]
        [BsonRepresentation(BsonType.String)]
        public string Id { get; set; }
        public string Name { get; set; }
        public Episode[] Episodes { get; set; }
    }

    public class Episode
    {
        [BsonId]
        [BsonRepresentation(BsonType.String)]
        public string Id { get; set; }
        public string Name { get; set; }
        public Track[] Tracks { get; set; }
    }

    public class Track
    {
        [BsonId]
        [BsonRepresentation(BsonType.String)]
        public string Id { get; set; }
        public string Name { get; set; }
        public Like[] Likes { get; set; }
    }

    public class Like
    {
        [BsonId]
        [BsonRepresentation(BsonType.String)]
        public string Id { get; set; }
        public string Name { get; set; }
    }
}

//Code
var chanelId = "5e4606e6ae7b090688671416";
var episodeId = "5e46071d385a672b0cea0f86";
var trackId = "5e460dbe2bc5e70c9cfeac21";

var filter = Builders<Channel>.Filter.And(
             Builders<Channel>.Filter.Where(x => x.Id == chanelId),
             Builders<Channel>.Filter.Eq("Episodes._id", episodeId),
             Builders<Channel>.Filter.Eq("Episodes.Tracks._id", trackId));
var result = collection.Find(filter).ToList();

// Data
{"_id":"5e4606e6ae7b090688671416","Name":"Channel 1","Episodes":[{"_id":"5e46071d385a672b0cea0f86","Name":"Episode 1","Tracks":[{"_id":"5e460dbe2bc5e70c9cfeac21","Name":"Trak 1","Likes":[{"_id":"5e4635d41f949d43a8194790","Name":"Like 1"},{"_id":"5e464e1ccfa17a25181234f6","Name":"Like 2"},{"_id":"5e464e94776dc808383326d5","Name":"Like 3"}]},{"_id":"5e4612d60747a2121870c815","Name":"Trak 2","Likes":[]}]},{"_id":"5e460851d29c1b3df4d27b7d","Name":"Episode 2","Tracks":[{"_id":"5e460e307ca6843758ce814e","Name":"Trak 1","Likes":[{"_id":"5e4686aa2813d41fa428b621","Name":"Like 1"}]}]}]}
</code>```

答:
here's a lambda version of mickl's answer and also with the channel info retained:

var result = collection.AsQueryable()
               .Where(c => c.Id == "5e4606e6ae7b090688671416")
               .SelectMany(c => c.Episodes,
                           (c, e) => new
                           {
                               cid = c.Id,
                               cname = c.Name,
                               eid = e.Id,
                               ename = e.Name,
                               etracks = (Track[])e.Tracks.Where(t => t.Id == "5e460dbe2bc5e70c9cfeac21")
                           })
               .Where(x => x.etracks.Any())
               .Select(x => new Channel
               {
                   ID = x.cid,
                   Name = x.cname,
                   Episodes = new Episode[] {
                       new Episode {
                           Id = x.eid,
                           Name = x.ename,
                           Tracks = x.etracks } }
               })
               .ToList();
```

Body:
Trying to get exact child document with it's corresponding parent document from embedded MongoDB document using C#  but query return all the child and corresponding parent and others . how to set parameter to
get the exact match with Filter and findOptions. My expected result will be Channel 1 -> Episode 1 & it's Child Track which id is given .
Here is my code:

// Class
namespace CrudWithMultilvelNestedDoc
{
    public class Channel
    {
        [BsonId]
        [BsonRepresentation(BsonType.String)]
        public string Id { get; set; }
        public string Name { get; set; }
        public Episode[] Episodes { get; set; }
    }

    public class Episode
    {
        [BsonId]
        [BsonRepresentation(BsonType.String)]
        public string Id { get; set; }
        public string Name { get; set; }
        public Track[] Tracks { get; set; }
    }

    public class Track
    {
        [BsonId]
        [BsonRepresentation(BsonType.String)]
        public string Id { get; set; }
        public string Name { get; set; }
        public Like[] Likes { get; set; }
    }

    public class Like
    {
        [BsonId]
        [BsonRepresentation(BsonType.String)]
        public string Id { get; set; }
        public string Name { get; set; }
    }
}

//Code
var chanelId = "5e4606e6ae7b090688671416";
var episodeId = "5e46071d385a672b0cea0f86";
var trackId = "5e460dbe2bc5e70c9cfeac21";

var filter = Builders<Channel>.Filter.And(
             Builders<Channel>.Filter.Where(x => x.Id == chanelId),
             Builders<Channel>.Filter.Eq("Episodes._id", episodeId),
             Builders<Channel>.Filter.Eq("Episodes.Tracks._id", trackId));
var result = collection.Find(filter).ToList();

// Data
{"_id":"5e4606e6ae7b090688671416","Name":"Channel 1","Episodes":[{"_id":"5e46071d385a672b0cea0f86","Name":"Episode 1","Tracks":[{"_id":"5e460dbe2bc5e70c9cfeac21","Name":"Trak 1","Likes":[{"_id":"5e4635d41f949d43a8194790","Name":"Like 1"},{"_id":"5e464e1ccfa17a25181234f6","Name":"Like 2"},{"_id":"5e464e94776dc808383326d5","Name":"Like 3"}]},{"_id":"5e4612d60747a2121870c815","Name":"Trak 2","Likes":[]}]},{"_id":"5e460851d29c1b3df4d27b7d","Name":"Episode 2","Tracks":[{"_id":"5e460e307ca6843758ce814e","Name":"Trak 1","Likes":[{"_id":"5e4686aa2813d41fa428b621","Name":"Like 1"}]}]}]}


问:
How to specify what actually happens when Yes/No is clicked with ctypes MessageBoxW?
```<code>def addnewunit(title, text, style):
    ctypes.windll.user32.MessageBoxW(0, text, title, style)
</code>```

Ive seen a lot of people show this code, however nobody has ever specified how to actually make the Yes/No work. Theyre buttons, and they are there, however how does one specify what actually happens when you click either or?

答:
You set the answer as equal to the command, like so:

```<code>import ctypes
answer = ctypes.windll.user32.MessageBoxW(0, "Message", "Title", 4)
</code>```

Then you can just use

print(answer)

to see what number is the outcome of the user's choice.

Then use an "If" statement based on what the answer number is to make it do what you want.

Body:
def addnewunit(title, text, style):
    ctypes.windll.user32.MessageBoxW(0, text, title, style)

Ive seen a lot of people show this code, however nobody has ever specified how to actually make the Yes/No work. Theyre buttons, and they are there, however how does one specify what actually happens when you click either or?

Body:
You set the answer as equal to the command, like so:

import ctypes
answer = ctypes.windll.user32.MessageBoxW(0, "Message", "Title", 4)

Then you can just use

print(answer)

to see what number is the outcome of the user's choice.

Then use an "If" statement based on what the answer number is to make it do what you want.


问:
php is variable an array or object
Trying to figure out how to do the equivalent of something I did in javascript but in php. But I'm not sure of the operators to do it. In javascript I wanted to see if a particular parameter being passed was either an object or array.. and if not then was it a string/int and what I did was something like

```<code>if (str instanceof Array || str instanceof Object)
{
   //code
}
else
{
   //code
}
</code>```

anyone know of the equivalent to this for php?

答:
I came across this question while looking for is_countable. Maybe it's of some use to somebody.
https://www.php.net/manual/en/function.is-countable.php

Title: php is variable an array or object

Body:
Trying to figure out how to do the equivalent of something I did in javascript but in php. But I'm not sure of the operators to do it. In javascript I wanted to see if a particular parameter being passed was either an object or array.. and if not then was it a string/int and what I did was something like

if (str instanceof Array || str instanceof Object)
{
   //code
}
else
{
   //code
}

anyone know of the equivalent to this for php?


问:
Returning Channels Golang
I'm trying with Go channels and confused with below function example from go blog:

```<code>func gen(nums []int) <-chan int {
    out := make(chan int)
    go func() {
        for _, n := range nums {
            out <- n
        }
        close(out)
    }()
    fmt.Println("return statement is called ")
    return out
}
</code>```

Main :

```<code>func main() {
    c := make(chan int)
    c = gen([]int{2, 3, 4, 5})

    // Consume the output.
    // Print 2,3,4,5
    fmt.Println(<-c)
    fmt.Println(<-c)
    fmt.Println(<-c)
    fmt.Println(<-c)
}
</code>```

Complete Code: http://play.golang.org/p/Qh30wzo4m0

My Doubts:

My understanding was, once return is called the function will be terminated and the channel inside that function has no more life.

The return statement is called only once. But the content of the out channel is read many times. In this case what is the actual flow of execution?

(I'm new to concurrent programming.)

答:
I think this is what you want: https://play.golang.org/p/WSBUPPyQiY6</p>

```<code>package main

import (
    "fmt"
    "sync"
    "time"
)

func read() (elemChan chan int) {
    elemChan = make(chan int)
    go func() {
        for k := 0; k < 1000; k++ {
            elemChan <- k
        }
        close(elemChan)
    }()
    return
}

func main() {
    fmt.Println("Hello, playground")
    elemChan := read()
    wg := sync.WaitGroup{}
    for k := 0; k < 2; k++ {
        wg.Add(1)
        go func(k int) {
            for {
                e, more := <-elemChan
                if !more {
                    wg.Done()
                    return
                }
                fmt.Printf("goroutine #%d: %d\n", k, e)
                time.Sleep(1000 * time.Nanosecond)
            }
        }(k)
    }
    wg.Wait()
}
</code>```

Title: Returning Channels Golang

Body:
I'm trying with Go channels and confused with below function example from go blog:

func gen(nums []int) <-chan int {
    out := make(chan int)
    go func() {
        for _, n := range nums {
            out <- n
        }
        close(out)
    }()
    fmt.Println("return statement is called ")
    return out
}

Main :

func main() {
    c := make(chan int)
    c = gen([]int{2, 3, 4, 5})

    // Consume the output.
    // Print 2,3,4,5
    fmt.Println(<-c)
    fmt.Println(<-c)
    fmt.Println(<-c)
    fmt.Println(<-c)
}

Complete Code: http://play.golang.org/p/Qh30wzo4m0

My Doubts:

My understanding was, once return is called the function will be terminated and the channel inside that function has no more life.

The return statement is called only once. But the content of the out channel is read many times. In this case what is the actual flow of execution?

(I'm new to concurrent programming.)

Body:
I think this is what you want: https://play.golang.org/p/WSBUPPyQiY6

package main

import (
    "fmt"
    "sync"
    "time"
)

func read() (elemChan chan int) {
    elemChan = make(chan int)
    go func() {
        for k := 0; k < 1000; k++ {
            elemChan <- k
        }
        close(elemChan)
    }()
    return
}

func main() {
    fmt.Println("Hello, playground")
    elemChan := read()
    wg := sync.WaitGroup{}
    for k := 0; k < 2; k++ {
        wg.Add(1)
        go func(k int) {
            for {
                e, more := <-elemChan
                if !more {
                    wg.Done()
                    return
                }
                fmt.Printf("goroutine #%d: %d\n", k, e)
                time.Sleep(1000 * time.Nanosecond)
            }
        }(k)
    }
    wg.Wait()
}


问:
How can I update this state without mutating the array?
I want to know how to not mutate state in the following scenario:

I'm using React Hooks. I have a TodoList that lists TodoItems. TodoItems can be clicked to run a function called toggle which toggles their completed property.

```<code>import React, { useState } from "react";
import TodoItem from "./TodoItem";

export default function TodoList() {
  const [todos, setTodos] = useState([
    { text: "Example", completed: false }
  ]);

  const toggle = index => {
    const newTodos = [...todos];
    newTodos[index].completed = !newTodos[index].completed; // Mutating state?
    setTodos(newTodos);
  };

  return (
    <>
      {todos.map((item, index) => (
        <TodoItem key={index} index={index} todo={item} toggle={toggle} />
      ))}
    </>
  );
}
</code>```

I was told that this was mutating state:

You create a copy of the todos array, but you still mutate an item inside the array:

newTodos[index].completed = !newTodos[index].completed;
```

  <p>Spreading the array only creates a shallow copy of the array, but the original todo object is not copied and thus mutated.</p>
</blockquote>

<p>So, what is the correct way to handle this without mutating state? I've tried passing in a <code>prevTodos</code> param, but then the state doesn't update:</p>

```const toggle = index => {
  setTodos(prevTodos => {
    prevTodos[index].completed = !prevTodos[index].completed;
    return prevTodos;
  });
};
```

<p><strong>Update:</strong> I've taken a look at the posts you've all recommended. This is a solution, although I'm wondering if there's a cleaner way to express it:</p>

```const toggle = index => {
  setTodos(
    todos.map((todo, i) =>
      i === index ? { ...todo, completed: !todo.completed } : todo
    )
  );
};
```

Update 2: Thanks everyone. I posted the solution below. StackOverflow won't let me accept it for 2 days, but I'll do it then. The accepted answer on the suggested post suggests the use of a third-party library, and it doesn't use React Hooks, so I don't consider this question a duplicate.

答:
```<code>const toggle = (index) => {
  const oldTodo = todos[index];
  setTodos(oldState => {
   oldState.splice(index, 1, {...oldTodo, checked: !oldTodo.checked})

   return oldState
})
}
</code>```

Body:
I want to know how to not mutate state in the following scenario:

I'm using React Hooks. I have a TodoList that lists TodoItems. TodoItems can be clicked to run a function called toggle which toggles their completed property.

import React, { useState } from "react";
import TodoItem from "./TodoItem";

export default function TodoList() {
  const [todos, setTodos] = useState([
    { text: "Example", completed: false }
  ]);

  const toggle = index => {
    const newTodos = [...todos];
    newTodos[index].completed = !newTodos[index].completed; // Mutating state?
    setTodos(newTodos);
  };

  return (
    <>
      {todos.map((item, index) => (
        <TodoItem key={index} index={index} todo={item} toggle={toggle} />
      ))}
    </>
  );
}

I was told that this was mutating state:

You create a copy of the todos array, but you still mutate an item inside the array:

newTodos[index].completed = !newTodos[index].completed;

Spreading the array only creates a shallow copy of the array, but the original todo object is not copied and thus mutated.

So, what is the correct way to handle this without mutating state? I've tried passing in a prevTodos param, but then the state doesn't update:

const toggle = index => {
  setTodos(prevTodos => {
    prevTodos[index].completed = !prevTodos[index].completed;
    return prevTodos;
  });
};

Update: I've taken a look at the posts you've all recommended. This is a solution, although I'm wondering if there's a cleaner way to express it:

const toggle = index => {
  setTodos(
    todos.map((todo, i) =>
      i === index ? { ...todo, completed: !todo.completed } : todo
    )
  );
};

Update 2: Thanks everyone. I posted the solution below. StackOverflow won't let me accept it for 2 days, but I'll do it then. The accepted answer on the suggested post suggests the use of a third-party library, and it doesn't use React Hooks, so I don't consider this question a duplicate.


问:
Animating a button background to reflect time left?
I am working on a android project where the user can scan a RFID tag. The tag expires after a certain amount of seconds to clear up the system before another tag comes in, basically to avoid processing the same tag twice by mistake. To visualise this timeout I want the background of the button where the tags ID is displayed to be animated. Basically I want the entire button to be filled with color when the tag has just been scanned and slowly scale down to the middle as time processes.

What I have found so far:
I found this answer where they talk about the properties api. I could see this working with a gradient but unfortunately the documentation on gradients is sparce and it looks like it wouldnt be that easy to do that with.

I also thought that maybe you could achieve this by somehow layering another view of the same size below the button and scaling that. But honestly I think this would be quite difficult to do consistently, especially with resizing the view while the timer processes and configuration changes. Then again, I am not really that experienced with android and use linear and grid layouts for almost everything since they are the easiest to understand.

All I would really need is some way to essentially "scale" the background by a value (the ratio between total time and time left) towards the middle like I have demonstrated here. Or a way to essentially have a hard color gradient where the white portions of the gradient move towards the middle as the time processes.

Last solution I thought could maybe work is to have a animated vector drawable and manipulate the objectanimator associated with it to force it to play at the right speed. However, this solution is probably pretty messy, thought I haven't tried it (yet)

Does anyone have a clean solution to this problem?

Note: i am using java for this project. I did not include code snippets because I didn't think they were needed. If you need some snippets please simply ask and I will provide. My minSdkVersion is 25 since the target device for the job has android 7.1 and cannot be updated to a newer version.

答:
Here’s a sample layout with two progress bars and a textview over them:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent">

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:progressBackgroundTint="@color/transparent"
        android:rotation="180"
        android:scaleY="4"
        app:layout_constraintBottom_toBottomOf="@id/textView2"
        app:layout_constraintEnd_toStartOf="@+id/progressBar2"
        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@id/textView2"
        tools:progress="100" />

    <ProgressBar
        android:id="@+id/progressBar2"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:progressBackgroundTint="@color/transparent"
        android:scaleY="4"
        app:layout_constraintBottom_toBottomOf="@id/textView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/progressBar"
        app:layout_constraintTop_toTopOf="@id/textView2"
        tools:progress="100" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="24dp"
        android:text="TextView"
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

These are the results you get by setting the progress to 100, 50 and 1:

100:

50:

1:

If you add a custom drawable as your background you can make the progress bar fill the space accordingly and also make its colour red.

Note that the grey lines in the photos are from my design tab in Android Studio and aren't visible other than when debugging.

UPDATE: Here's the animation code that makes the progress bars reset from 100% to 0% in 5 seconds.

ProgressBar pb = findViewById(R.id.progressBar);
        ProgressBar pb2 = findViewById(R.id.progressBar2);

```<code>    ObjectAnimator animation = ObjectAnimator.ofInt(pb, "progress", 0, 100);
    animation.setDuration(5000);
    animation.setInterpolator(new DecelerateInterpolator());
    animation.addListener(new Animator.AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animator) { }

        @Override
        public void onAnimationEnd(Animator animator) {
            //do something when the countdown is complete
        }

        @Override
        public void onAnimationCancel(Animator animator) { }

        @Override
        public void onAnimationRepeat(Animator animator) { }
    });
    animation.start();

    AnimatorSet set = new AnimatorSet();
    set.playTogether(ObjectAnimator.ofInt(pb, "progress", 100, 0),
            ObjectAnimator.ofInt(pb2, "progress", 100, 0));
    set.setDuration(5000);
    set.start();
</code>```

Body:
Here’s a sample layout with two progress bars and a textview over them:

    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent">

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:progressBackgroundTint="@color/transparent"
        android:rotation="180"
        android:scaleY="4"
        app:layout_constraintBottom_toBottomOf="@id/textView2"
        app:layout_constraintEnd_toStartOf="@+id/progressBar2"
        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@id/textView2"
        tools:progress="100" />

    <ProgressBar
        android:id="@+id/progressBar2"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:progressBackgroundTint="@color/transparent"
        android:scaleY="4"
        app:layout_constraintBottom_toBottomOf="@id/textView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/progressBar"
        app:layout_constraintTop_toTopOf="@id/textView2"
        tools:progress="100" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="24dp"
        android:text="TextView"
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

These are the results you get by setting the progress to 100, 50 and 1:

100:

50:

1:

If you add a custom drawable as your background you can make the progress bar fill the space accordingly and also make its colour red.

Note that the grey lines in the photos are from my design tab in Android Studio and aren't visible other than when debugging.

UPDATE: Here's the animation code that makes the progress bars reset from 100% to 0% in 5 seconds.

ProgressBar pb = findViewById(R.id.progressBar);
        ProgressBar pb2 = findViewById(R.id.progressBar2);

    ObjectAnimator animation = ObjectAnimator.ofInt(pb, "progress", 0, 100);
    animation.setDuration(5000);
    animation.setInterpolator(new DecelerateInterpolator());
    animation.addListener(new Animator.AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animator) { }

        @Override
        public void onAnimationEnd(Animator animator) {
            //do something when the countdown is complete
        }

        @Override
        public void onAnimationCancel(Animator animator) { }

        @Override
        public void onAnimationRepeat(Animator animator) { }
    });
    animation.start();

    AnimatorSet set = new AnimatorSet();
    set.playTogether(ObjectAnimator.ofInt(pb, "progress", 100, 0),
            ObjectAnimator.ofInt(pb2, "progress", 100, 0));
    set.setDuration(5000);
    set.start();


问:
How to remove whitespace from a expression using a function with const char* pointer
I am working with a small piece of code and want to remove all the whitespaces from a simple expression. I am taking char array expression and passing it to an function with const char* pointer,but i am not able to remove the whitespace. here is what i tried, but didn't get desired output.

```<code>#include <iostream>

using namespace std;

void evaluate(const char *expression){

if (*expression == '\0') cout<<"Invalid"<<endl;

while(*expression){
    if(*expression == ' '){
        *expression++ ;
    }
    expression++;
 }

cout<<expression;

}

int main()
{
    char expr[] = "1 + 2 * 3";
    evaluate(expr);
    return 0;
}
</code>```

It will be great if someone can help me with this.
Thanks in advance.

答:
If I understand your intent is simply to output the expression without spaces when calling  evaluate(), you can simplify things by outputting each character that is not a space with:

```<code>#include <iostream>

using namespace std;

void evaluate (const char *expression) {

    if (!*expression) {
        cout << "Invalid\n";
        return;
    }

    while (*expression) {
        if (*expression != ' ')
            cout << (char)*expression;
        expression++;
    }
    cout << '\n';
}

int main() {

    char expr[] = "1 + 2 * 3";

    evaluate(expr);
}
</code>```

Example Use/Output

```<code>$ ./bin/rmws_const_char
1+2*3
</code>```

Body:
I am working with a small piece of code and want to remove all the whitespaces from a simple expression. I am taking char array expression and passing it to an function with const char* pointer,but i am not able to remove the whitespace. here is what i tried, but didn't get desired output.

#include <iostream>

using namespace std;

void evaluate(const char *expression){

if (*expression == '\0') cout<<"Invalid"<<endl;

while(*expression){
    if(*expression == ' '){
        *expression++ ;
    }
    expression++;
 }

cout<<expression;

}

int main()
{
    char expr[] = "1 + 2 * 3";
    evaluate(expr);
    return 0;
}

It will be great if someone can help me with this.
Thanks in advance.

Body:
If I understand your intent is simply to output the expression without spaces when calling  evaluate(), you can simplify things by outputting each character that is not a space with:

#include <iostream>

using namespace std;

void evaluate (const char *expression) {

    if (!*expression) {
        cout << "Invalid\n";
        return;
    }

    while (*expression) {
        if (*expression != ' ')
            cout << (char)*expression;
        expression++;
    }
    cout << '\n';
}

int main() {

    char expr[] = "1 + 2 * 3";

    evaluate(expr);
}

Example Use/Output

$ ./bin/rmws_const_char
1+2*3


问:
global variable won't update from function within AJAX success

OK, so I cannot seem to be able to change the global variable of systemPath after it goes through the ajax.It will work inside of ajax, but I need that updated variable outside of ajax. basically I'm trying to create an array of paths from xml and use them to locate other xml files that I can generate a table from.

Does anyone know what's going on here? Does ajax run before the variable is set and that is why I get an array length of 0 after the ajax?

```<code>    var systemPath = new Array();
var techDigestArr = new Array();
var addToArray = function(thisarray, toPush){
    thisarray.push(toPush);
}

$.ajax({
    url: fullPath+"technical/systems/systems.xml",
    dataType: ($.browser.msie) ? "text" : "xml",
    success: function(data){
                            var xml;
                            if (typeof data == "string") {
                               xml = new ActiveXObject("Microsoft.XMLDOM");
                               xml.async = false;
                               xml.loadXML(data);
                            } else {
                               xml = data;
                            }
                            $(xml).find("system").each(function(){
                                var urlString = fullPath + "technical/system_" + $(this).attr("id") + "/" + $(this).attr("id") + "tech-digest.xml <br />";
                                //alert(urlString);
                            $("#td-articles").append(systemPath.length + urlString);
                                addToArray(systemPath,urlString);
                                //systemPath.push(urlString);
                            });
                        $("#msg-output").append("total - " +systemPath.length);//Returns 48

                    },//END SUCCSESS
    error: function(){
        alert("Sorry - ");
        history.go(-1);
    }
});//END AJAX CALL
    $(document).ready(function(){
        //$("#msg-output").append("total - " + systemPath.length); Returns 0
    });
</code>```

答:
The ajax is ran asynchronously. Things execute in this order in your code.

stuff before $.ajax()

$.ajax() initiates an ajax call (while waiting for the response it continues to run the rest of the code)

stuff after $.ajax()

success callback

Note that depending on how fast the call is 3 and 4 might occur in reverse order (not the case here)

So when $(document).ready() is executed the ajax call might not have returned yet, so the code in the success callback didn't have a chance to execute. If you are lucky and have a fast connection than maybe the response will come before document ready, but it's unlikely.

Just so you can see that the global variable gets updated you can set a timeout:

```<code>$(document).ready(function(){
  setTimeout(function(){
    $("#msg-output").append("total - " + systemPath.length);
    //if the delay set below is more than the time between the ajax request and the server response than this will print the correct value
  },2000);
});
</code>```

Body:
OK, so I cannot seem to be able to change the global variable of systemPath after it goes through the ajax.It will work inside of ajax, but I need that updated variable outside of ajax. basically I'm trying to create an array of paths from xml and use them to locate other xml files that I can generate a table from.

Does anyone know what's going on here? Does ajax run before the variable is set and that is why I get an array length of 0 after the ajax?

    var systemPath = new Array();
var techDigestArr = new Array();
var addToArray = function(thisarray, toPush){
    thisarray.push(toPush);
}

$.ajax({
    url: fullPath+"technical/systems/systems.xml",
    dataType: ($.browser.msie) ? "text" : "xml",
    success: function(data){
                            var xml;
                            if (typeof data == "string") {
                               xml = new ActiveXObject("Microsoft.XMLDOM");
                               xml.async = false;
                               xml.loadXML(data);
                            } else {
                               xml = data;
                            }
                            $(xml).find("system").each(function(){
                                var urlString = fullPath + "technical/system_" + $(this).attr("id") + "/" + $(this).attr("id") + "tech-digest.xml
";
                                //alert(urlString);
                            $("#td-articles").append(systemPath.length + urlString);
                                addToArray(systemPath,urlString);
                                //systemPath.push(urlString);
                            });
                        $("#msg-output").append("total - " +systemPath.length);//Returns 48

                    },//END SUCCSESS
    error: function(){
        alert("Sorry - ");
        history.go(-1);
    }
});//END AJAX CALL
    $(document).ready(function(){
        //$("#msg-output").append("total - " + systemPath.length); Returns 0
    });

Body:
The ajax is ran asynchronously. Things execute in this order in your code.

stuff before $.ajax()

$.ajax() initiates an ajax call (while waiting for the response it continues to run the rest of the code)

stuff after $.ajax()

success callback

Note that depending on how fast the call is 3 and 4 might occur in reverse order (not the case here)

So when $(document).ready() is executed the ajax call might not have returned yet, so the code in the success callback didn't have a chance to execute. If you are lucky and have a fast connection than maybe the response will come before document ready, but it's unlikely.

Just so you can see that the global variable gets updated you can set a timeout:

$(document).ready(function(){
  setTimeout(function(){
    $("#msg-output").append("total - " + systemPath.length);
    //if the delay set below is more than the time between the ajax request and the server response than this will print the correct value
  },2000);
});


问:
How to output the result of a chain of commands for a given input with bash
In reference to this question I still struggle the following single-liner to work

```<code>kubectl get ns | while read -r line; do  echo `$line | grep Term | cut -d' ' -f1`; done
</code>```

I would expect to print out the result of $line | grep Term | cut -d' ' -f1 however it prints out an empty line (echo) and then executes the result of $line | grep Term | cut -d' ' -f1

```<code>bash: NAME: command not found

bash: cert-manager: command not found

bash: configmap-4262: command not found

bash: configmap-4430: command not found

</code>```

Same results with a slightly different approach:

```<code>kubectl get ns | while read -r line; do ns=`$line | grep Term | cut -d' ' -f1`; echo $ns; done
</code>```

What I actually want to achieve is to use the result of $line | grep Term | cut -d' as an input of a shell script e.g.

```<code>do ns=`$line | grep Term | cut -d' ' -f1`; ./delete-kube-ns.sh $ns;
</code>```

or

```<code>$line | grep Term | cut -d' ' -f1` | xargs ./delete-kube-ns.sh
</code>```

答:
Ger rid of the backticks. It's trying to execute the output of kubectl as a shell command. You want to echo $line, not the result of executing it as a command.

```<code>kubectl get ns | while read -r line; do
    echo "$line" | grep Term | cut -d' ' -f1
done
</code>```

There doesn't really seem to be a need to use while read at all, just pipe kubectl to grep

```<code>kubectl get ns | grep Term | cut -d' ' -f1
</code>```

Body:
In reference to this question I still struggle the following single-liner to work

kubectl get ns | while read -r line; do  echo `$line | grep Term | cut -d' ' -f1`; done

I would expect to print out the result of $line | grep Term | cut -d' ' -f1 however it prints out an empty line (echo) and then executes the result of $line | grep Term | cut -d' ' -f1

bash: NAME: command not found

bash: cert-manager: command not found

bash: configmap-4262: command not found

bash: configmap-4430: command not found

Same results with a slightly different approach:

kubectl get ns | while read -r line; do ns=`$line | grep Term | cut -d' ' -f1`; echo $ns; done

What I actually want to achieve is to use the result of $line | grep Term | cut -d' as an input of a shell script e.g.

do ns=`$line | grep Term | cut -d' ' -f1`; ./delete-kube-ns.sh $ns;

or

$line | grep Term | cut -d' ' -f1` | xargs ./delete-kube-ns.sh

Body:
Ger rid of the backticks. It's trying to execute the output of kubectl as a shell command. You want to echo $line, not the result of executing it as a command.

kubectl get ns | while read -r line; do
    echo "$line" | grep Term | cut -d' ' -f1
done

There doesn't really seem to be a need to use while read at all, just pipe kubectl to grep

kubectl get ns | grep Term | cut -d' ' -f1


问:
Python ruamel.yaml - preserving single quote in value while dumping yaml
I am trying to dump the dictionary into yaml and facing the following issue.

```<code>connection = dict()
connection['authentication']= 'Username Password'
connection['dbname']= '{{client}}_DB'

ruamel.yaml.round_trip_dump(connection, sys.stdout)

</code>```

What i got :

```<code>  connection:
    authentication: Username Password
    dbname: '{{client}}_DB'
</code>```

We can see that single quote are removed from authentication but not from dbname.

What i expected:

```<code>  connection:
    authentication: 'Username Password'
    dbname: '{{client}}_DB'
</code>```

Complete example from terminal

```<code>>>> import sys
>>> import ruamel.yaml
>>> connection = dict()
>>> connection['authentication']= 'Username Password'
>>> connection['dbname']= '{{client}}_DB'
>>> ruamel.yaml.round_trip_dump(connection, sys.stdout)
authentication: Username Password
dbname: '{{client}}_DB'
>>> print(connection)
{'authentication': 'Username Password', 'dbname': '{{client}}_DB'}
>>>

</code>```

yaml is printed without single quote. My requirement is to have single quote around the value

答:
Quotes here just mean you input string. If you want add single quotes to 'Username Password' just use double quotes:</p>

```<code>connection['authentication'] = "'Username Password'"
</code>```

Body:
I am trying to dump the dictionary into yaml and facing the following issue.

connection = dict()
connection['authentication']= 'Username Password'
connection['dbname']= '{{client}}_DB'

ruamel.yaml.round_trip_dump(connection, sys.stdout)

What i got :

  connection:
    authentication: Username Password
    dbname: '{{client}}_DB'

We can see that single quote are removed from authentication but not from dbname.

What i expected:

  connection:
    authentication: 'Username Password'
    dbname: '{{client}}_DB'

Complete example from terminal

>>> import sys
>>> import ruamel.yaml
>>> connection = dict()
>>> connection['authentication']= 'Username Password'
>>> connection['dbname']= '{{client}}_DB'
>>> ruamel.yaml.round_trip_dump(connection, sys.stdout)
authentication: Username Password
dbname: '{{client}}_DB'
>>> print(connection)
{'authentication': 'Username Password', 'dbname': '{{client}}_DB'}
>>>

yaml is printed without single quote. My requirement is to have single quote around the value

Body:
Quotes here just mean you input string. If you want add single quotes to 'Username Password' just use double quotes:

connection['authentication'] = "'Username Password'"


问:
SSPI: user principle name WCF client
I am trying to access a wcf client.  I know people are getting information out of it right now, so I know it works.  My problem is I can't seem to get past it.  The service is a mutual certific service.  I have the appropriate certs in my personal stores on my local machine.  Even with that, I get the following exception:

```<code> A call to SSPI failed, see inner exception
</code>```

Searching deep into the exception and I see this:

```<code>Message : The target principal name is incorrect
</code>```

How can I resolve this?  Do I need to impersonate the user the app pool is running under?  Do I need to add an Identity\ServicePrincipleName or Identity\UserPrincipleName?  Has anyone run into an issue similar to this?

答:
For future reference for others, I experienced this issue but the existing answers didn't help.

My issue was with the userPrincipalName being used for a service reference.

I had recently re-registered the service reference in order update it but it had overwritten the specified userPrincipalName in the log files with my email address:

```<code><endpoint address="net.pipe://localhost/XXXX"
  binding="netNamedPipeBinding" bindingConfiguration="NetNamedPipeBinding_IXXX"
  contract="XXXServiceReference.IXXX"
  name="NetNamedPipeBinding_IXXXX">
  <identity>
    <userPrincipalName value="my@emailaddress.com" />
  </identity>
</endpoint>
</code>```

To rectify the issue, I simply changed the userPrincipalName to localhost, which it what it was previously:

```<code><userPrincipalName value="localhost" />
</code>```

Title: SSPI: user principle name WCF client

Body:
I am trying to access a wcf client.  I know people are getting information out of it right now, so I know it works.  My problem is I can't seem to get past it.  The service is a mutual certific service.  I have the appropriate certs in my personal stores on my local machine.  Even with that, I get the following exception:

 A call to SSPI failed, see inner exception

Searching deep into the exception and I see this:

Message : The target principal name is incorrect

How can I resolve this?  Do I need to impersonate the user the app pool is running under?  Do I need to add an Identity\ServicePrincipleName or Identity\UserPrincipleName?  Has anyone run into an issue similar to this?

Body:
For future reference for others, I experienced this issue but the existing answers didn't help.

My issue was with the userPrincipalName being used for a service reference.

I had recently re-registered the service reference in order update it but it had overwritten the specified userPrincipalName in the log files with my email address:

<endpoint address="net.pipe://localhost/XXXX"
  binding="netNamedPipeBinding" bindingConfiguration="NetNamedPipeBinding_IXXX"
  contract="XXXServiceReference.IXXX"
  name="NetNamedPipeBinding_IXXXX">
  <identity>
    <userPrincipalName value="my@emailaddress.com" />
  </identity>
</endpoint>

To rectify the issue, I simply changed the userPrincipalName to localhost, which it what it was previously:

<userPrincipalName value="localhost" />


问:
setTimeout js and voice channel discordjs
First of All I'm sorry for my bad English.
I'm working on a discord music bot, I wanna add a feature to make the bot stay for 30seconds before it disconnect from the voice channel (when idle = all music ended nothing to play more)

```<code>async function play(guild, song) {
    const serverQueue = queue.get(guild.id);
    if (!song) {
        setTimeout(function() {serverQueue.voiceChannel.leave();}, 30000);
        queue.delete(guild.id);
        return;
    }
    console.log(serverQueue.songs);
    const dispatcher = serverQueue.connection.playOpusStream(await ytdl(song.url))
        .on('end', reason => {
            console.log(reason)
            serverQueue.songs.shift()
            play(guild, serverQueue.songs[0])
        })
        .on('error', error => console.error(error));
    serverQueue.textChannel.send(`\`\`\`Start playing : ${song.title}\`\`\``);
}
</code>```

but i want to make it disconnect immediately from the voice channel and End everything, when "stop" command used

```<code>else if (command === 'play') {

    const voiceChannel = message.member.voiceChannel;
    ...
}
else if (command === 'stop') {
    if (!message.member.voiceChannel) return message.channel.send("you are not in a voice channel")
    if (!serverQueue) return message.channel.send("nothing to stop!")
    serverQueue.songs = []
    serverQueue.connection.dispatcher.end();

    serverQueue.voiceChannel.leave();

    return undefined;
}
else if (command === 'next') {
    if (!message.member.voiceChannel) return message.channel.send("you are not in a voice channel")
    if (!serverQueue) return message.channel.send("nothing!")
    serverQueue.connection.dispatcher.end();
    message.channel.send("```Next music!```");
    return undefined;
}
</code>```

When it end from playing a piece of music it wait 30 seconds, and disconnect, Ok!
BUT The problem is : if anyone used 'play' command when waiting for that 30s, it play his music track but it cut everything after 30s (even if the second track didn't end)

.

答:
You will want to assign the setTimeout to a variable. Then use the clearTimeout function when you play again. To cancel the serverQueue.voiceChannel.leave().

The docs explain how to use it here

Body:
First of All I'm sorry for my bad English.
I'm working on a discord music bot, I wanna add a feature to make the bot stay for 30seconds before it disconnect from the voice channel (when idle = all music ended nothing to play more)

async function play(guild, song) {
    const serverQueue = queue.get(guild.id);
    if (!song) {
        setTimeout(function() {serverQueue.voiceChannel.leave();}, 30000);
        queue.delete(guild.id);
        return;
    }
    console.log(serverQueue.songs);
    const dispatcher = serverQueue.connection.playOpusStream(await ytdl(song.url))
        .on('end', reason => {
            console.log(reason)
            serverQueue.songs.shift()
            play(guild, serverQueue.songs[0])
        })
        .on('error', error => console.error(error));
    serverQueue.textChannel.send(`\`\`\`Start playing : ${song.title}\`\`\``);
}

but i want to make it disconnect immediately from the voice channel and End everything, when "stop" command used

else if (command === 'play') {

    const voiceChannel = message.member.voiceChannel;
    ...
}
else if (command === 'stop') {
    if (!message.member.voiceChannel) return message.channel.send("you are not in a voice channel")
    if (!serverQueue) return message.channel.send("nothing to stop!")
    serverQueue.songs = []
    serverQueue.connection.dispatcher.end();

    serverQueue.voiceChannel.leave();

    return undefined;
}
else if (command === 'next') {
    if (!message.member.voiceChannel) return message.channel.send("you are not in a voice channel")
    if (!serverQueue) return message.channel.send("nothing!")
    serverQueue.connection.dispatcher.end();
    message.channel.send("```Next music!```");
    return undefined;
}

When it end from playing a piece of music it wait 30 seconds, and disconnect, Ok!
BUT The problem is : if anyone used 'play' command when waiting for that 30s, it play his music track but it cut everything after 30s (even if the second track didn't end)

.


问:
C# Load/Unload plugins
Is there anyway to have ClassLibrary plugins which can be loaded/unloaded. The only way I have found is using an AppDomain but that defeats the purpose as the plugin cannot use the hosts API.</p>

答:
When you say "the plugin cannot use the hosts API," do you mean that you need your plugins to access their host's code?  If so, that sounds like you're wanting a circular dependency, which is not allowed whether your code is dynamically loadable/unloadable or not.  If the plugin needs access to the host's API, you should extract an interface out of that API and place it in a shared library that both plugins and the host app can access:

```<code>Plugin -> PluginLib <- Host
</code>```

The host can then inject its API object into a property/constructor of the plugin so that the plugin can then invoke the API methods.  Ideally, your plugin libraries should have no dependencies on the host library.  Using an AppDomain for dynamic loading/unloading should be fine once your dependency problems are solved.

Title: C# Load/Unload plugins

Body:
When you say "the plugin cannot use the hosts API," do you mean that you need your plugins to access their host's code?  If so, that sounds like you're wanting a circular dependency, which is not allowed whether your code is dynamically loadable/unloadable or not.  If the plugin needs access to the host's API, you should extract an interface out of that API and place it in a shared library that both plugins and the host app can access:

Plugin -> PluginLib <- Host

The host can then inject its API object into a property/constructor of the plugin so that the plugin can then invoke the API methods.  Ideally, your plugin libraries should have no dependencies on the host library.  Using an AppDomain for dynamic loading/unloading should be fine once your dependency problems are solved.


问:
Use local docker image without registry setup in k8s
I've set up single node kubernetes  according to official tutorial.

In addition to official documentation I've set-up single node cluster:

```<code>kubectl taint nodes --all node-role.kubernetes.io/master-
</code>```

Disabled eviction limit:

```<code>cat << EOF >> /var/lib/kubelet/config.yaml
evictionHard:
  imagefs.available: 1%
  memory.available: 100Mi
  nodefs.available: 1%
  nodefs.inodesFree: 1%
EOF

systemctl daemon-reload
systemctl restart kubelet
</code>```

And set systemd driver for Docker:

```<code>cat << EOF > /etc/docker/daemon.json
{
  "exec-opts": ["native.cgroupdriver=systemd"],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m"
  },
  "storage-driver": "overlay2"
}
EOF

systemctl daemon-reload
systemctl restart docker
</code>```

I've tried following:

```<code>docker build -t localhost:5000/my-image .
kubectl run -it --rm --restart=Always --image=localhost:5000/my-image my-image
</code>```

But in pod logs I see ImagePullBackOff. If I setup local repository and I do docker push localhost:5000/my-image after I build image, then everything is working.

Is it is possible to use local images (which are already available after issuing docker images) without needing to setting up local repository, pushing to this repository and then pulling from it?

答:
mario's answer is correct. Would be complete with the command though. So, you want to create your deployment as follows:

```<code>kubectl run -it --rm --restart Always DEPLOYMENT_NAME --image my-image --image-pull-policy IfNotPresent COMMAND
</code>```

Note: if you'd have more than one node, you would need to ensure on all of them you have an image with that name, as a repo doesn't exist, and it will fail.

Body:
I've set up single node kubernetes  according to official tutorial.

In addition to official documentation I've set-up single node cluster:

kubectl taint nodes --all node-role.kubernetes.io/master-

Disabled eviction limit:

cat << EOF >> /var/lib/kubelet/config.yaml
evictionHard:
  imagefs.available: 1%
  memory.available: 100Mi
  nodefs.available: 1%
  nodefs.inodesFree: 1%
EOF

systemctl daemon-reload
systemctl restart kubelet

And set systemd driver for Docker:

cat << EOF > /etc/docker/daemon.json
{
  "exec-opts": ["native.cgroupdriver=systemd"],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m"
  },
  "storage-driver": "overlay2"
}
EOF

systemctl daemon-reload
systemctl restart docker

I've tried following:

docker build -t localhost:5000/my-image .
kubectl run -it --rm --restart=Always --image=localhost:5000/my-image my-image

But in pod logs I see ImagePullBackOff. If I setup local repository and I do docker push localhost:5000/my-image after I build image, then everything is working.

Is it is possible to use local images (which are already available after issuing docker images) without needing to setting up local repository, pushing to this repository and then pulling from it?

Body:
mario's answer is correct. Would be complete with the command though. So, you want to create your deployment as follows:

kubectl run -it --rm --restart Always DEPLOYMENT_NAME --image my-image --image-pull-policy IfNotPresent COMMAND

Note: if you'd have more than one node, you would need to ensure on all of them you have an image with that name, as a repo doesn't exist, and it will fail.


问:
UIButton not highlighting or running code when clicked
I'm setting up 26 buttons, adding them as subviews to a letterButtonLabel, and appending them to an letterButtons array.

```<code>for row in 0..<6 {
            for column in 0..<5 {
                if row == 5 && column > 0 { continue }

                let letterButton = UIButton(type: .system)
                letterButton.titleLabel?.font = UIFont.systemFont(ofSize: 36)
                letterButton.setTitle("O", for: .normal)
                letterButton.addTarget(self, action: #selector(letterTapped), for: .touchUpInside)

                let frame = CGRect(x: width * column, y: height * row, width: width, height: height)
                letterButton.frame = frame

                letterButtonLabel.addSubview(letterButton)

                letterButtons.append(letterButton)
            }
        }
</code>```

Afterwards, I assign a letter to each button using the letterButtons array.

```<code>var index = 0

        for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" {
             letterButtons[index].setTitle("\(letter)", for: .normal)
             index += 1
        }
</code>```

I then manually add layout constraints.

Here is the functionality for each button:

```<code>@objc func letterTapped(_ sender: UIButton) {
        // check the letter and react
        sender.isHidden = true

        guard let word = currentWord else { return }
        guard var charactersArray = currentWordField.text?.components(separatedBy: "") else { return }
        guard let originalCurrentWordField = currentWordField.text else { return }

        for (index, letter) in word.enumerated() {
            let strLetter = String(letter)

            if strLetter == sender.titleLabel?.text {
                 charactersArray[index] = strLetter
            }
        }

        currentWordField.text = charactersArray.joined()

        if currentWordField.text == originalCurrentWordField {
            livesLeft -= 1
        }

        if wordBank.contains(word) {
            // you got it! reset letters
            level += 1

            let ac = UIAlertController(title: "Good job!", message: nil, preferredStyle: .alert)

            let action = UIAlertAction(title: "Continue", style: .default, handler: resetForNextLevel)
            ac.addAction(action)

            present(ac, animated: true)
        }

        if livesLeft == 0 {
            let ac = UIAlertController(title: "Game Over", message: nil, preferredStyle: .alert)

            let action = UIAlertAction(title: "Restart", style: .default, handler: resetForNextLevel)

            ac.addAction(action)
            present(ac, animated: true)
        }
    }

</code>```

(adding all just in case)

My button doesn't highlight or click. Is there anything here that might explain the problem? I'm curious about common mistakes.

答:
UILabel has by default userInteractionEnabled = false.
Setting this to true should fix your problem

Body:
I'm setting up 26 buttons, adding them as subviews to a letterButtonLabel, and appending them to an letterButtons array.

for row in 0..<6 {
            for column in 0..<5 {
                if row == 5 && column > 0 { continue }

                let letterButton = UIButton(type: .system)
                letterButton.titleLabel?.font = UIFont.systemFont(ofSize: 36)
                letterButton.setTitle("O", for: .normal)
                letterButton.addTarget(self, action: #selector(letterTapped), for: .touchUpInside)

                let frame = CGRect(x: width * column, y: height * row, width: width, height: height)
                letterButton.frame = frame

                letterButtonLabel.addSubview(letterButton)

                letterButtons.append(letterButton)
            }
        }

Afterwards, I assign a letter to each button using the letterButtons array.

var index = 0

        for letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" {
             letterButtons[index].setTitle("\(letter)", for: .normal)
             index += 1
        }

I then manually add layout constraints.

Here is the functionality for each button:

@objc func letterTapped(_ sender: UIButton) {
        // check the letter and react
        sender.isHidden = true

        guard let word = currentWord else { return }
        guard var charactersArray = currentWordField.text?.components(separatedBy: "") else { return }
        guard let originalCurrentWordField = currentWordField.text else { return }

        for (index, letter) in word.enumerated() {
            let strLetter = String(letter)

            if strLetter == sender.titleLabel?.text {
                 charactersArray[index] = strLetter
            }
        }

        currentWordField.text = charactersArray.joined()

        if currentWordField.text == originalCurrentWordField {
            livesLeft -= 1
        }

        if wordBank.contains(word) {
            // you got it! reset letters
            level += 1

            let ac = UIAlertController(title: "Good job!", message: nil, preferredStyle: .alert)

            let action = UIAlertAction(title: "Continue", style: .default, handler: resetForNextLevel)
            ac.addAction(action)

            present(ac, animated: true)
        }

        if livesLeft == 0 {
            let ac = UIAlertController(title: "Game Over", message: nil, preferredStyle: .alert)

            let action = UIAlertAction(title: "Restart", style: .default, handler: resetForNextLevel)

            ac.addAction(action)
            present(ac, animated: true)
        }
    }

(adding all just in case)

My button doesn't highlight or click. Is there anything here that might explain the problem? I'm curious about common mistakes.


问:
Comparing two sets for equality recursively?
I am pretty new to programming in general and am trying to construct a function that will take as input two sets, which can contain other sets (a (b c) d e (f g (h)), (a b c (d e f)) for example, and returns whether or not they are equal. I am working with scheme if that helps, but am really trying to just visualize how I could do it. Thanks for the help in advance</p>

答:
Some languages have built-in set types, including Racket. So the only issue is to convert a list (which may contain other lists) into nested sets. So something like this: (warning - completely untested code)

```<code>(require racket/set)
(define (recursive-make-set obj)
  (cond
    [(list? obj) (list->set (map recursive-make-set obj))]
    [else obj]))
</code>```

Basically we leave atoms alone, and build a set out of a list using the builtin list->set function on recursively converted elements.

Body:
Some languages have built-in set types, including Racket. So the only issue is to convert a list (which may contain other lists) into nested sets. So something like this: (warning - completely untested code)

(require racket/set)
(define (recursive-make-set obj)
  (cond
    [(list? obj) (list->set (map recursive-make-set obj))]
    [else obj]))

Basically we leave atoms alone, and build a set out of a list using the builtin list->set function on recursively converted elements.