问:
Unknown error writing an array to an element in javascript?
I am looking to add an array to a div. Not working with document.getElementsByClassName('boxed').innerHTML = numList. I am able to write the array to the DOM with document.write(numList).
Here's the whole HTML

```<code><!DOCTYPE html>
<html lang="en">

<head>
<title>Super Lotto</title>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Libre+Franklin" rel="stylesheet">
<link href="lotto-styles.css" rel="stylesheet">
<script>
    do {
        var high = prompt('What\'s the highest number you want to generate','');
        high = parseInt(high, 10);
    } while (isNaN(high));

    do {
        var nums = prompt('How many numbers do you want to generate','');
        nums = parseInt(nums, 10);
    } while (isNaN(nums));

    function rand(highestNum) {
        var randomNumber =
        Math.floor(Math.random() * highestNum) + 1;
        return randomNumber;
    }

    var numList = [];

    for (var i = 0; i < nums; i++) {
        // Go through this loop quantity of times
        numList.unshift(rand(high));
        // add new number to end of array
    };
    numList.toString();
    document.getElementsByClassName('boxed').innerHTML = numList;
</script>
</head>

<body>
<div id="container">
    <header>
        <h1>Lucky Numbers</h1>
    </header>

    <main>
        <div class="boxed"></div>
         <p>Good luck!</p>
    </main>
</div> <!-- Closing container -->
</body>

</html>
</code>```

答:
your problem is that in innerHTML you can't add an array, just a string, to add the numbers you need to do something like numList.join(" ");, I modified your code to do that. another thing I change is that instead of use "boxed" as a class, I use it as an id because getElementsByClassName return an nodeList.

 do {
    var high = prompt('What\'s the highest number you want to generate','');
    high = parseInt(high, 10);
} while (isNaN(high));

do {
    var nums = prompt('How many numbers do you want to generate','');
    nums = parseInt(nums, 10);
} while (isNaN(nums));

function rand(highestNum) {
    var randomNumber =
    Math.floor(Math.random() * highestNum) + 1;
    return randomNumber;
}

var numList = [];

for (var i = 0; i < nums; i++) {
    // Go through this loop quantity of times
    numList.unshift(rand(high));
    // add new number to end of array
};

numList.toString();
document.getElementById('boxed').innerHTML = numList.join(" ");```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
    <header>
        <h1>Lucky Numbers</h1>
    </header>

    <main>
        <div id="boxed"></div>
         <p>Good luck!</p>
    </main>
</div> </code>```

Body:
I am looking to add an array to a div. Not working with document.getElementsByClassName('boxed').innerHTML = numList. I am able to write the array to the DOM with document.write(numList).
Here's the whole HTML

<!DOCTYPE html>

<title>Super Lotto</title>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Libre+Franklin" rel="stylesheet">
<link href="lotto-styles.css" rel="stylesheet">

Lucky Numbers

Good luck!

Body:
your problem is that in innerHTML you can't add an array, just a string, to add the numbers you need to do something like numList.join(" ");, I modified your code to do that. another thing I change is that instead of use "boxed" as a class, I use it as an id because getElementsByClassName return an nodeList.

 do {
    var high = prompt('What\'s the highest number you want to generate','');
    high = parseInt(high, 10);
} while (isNaN(high));

do {
    var nums = prompt('How many numbers do you want to generate','');
    nums = parseInt(nums, 10);
} while (isNaN(nums));

function rand(highestNum) {
    var randomNumber =
    Math.floor(Math.random() * highestNum) + 1;
    return randomNumber;
}

var numList = [];

for (var i = 0; i < nums; i++) {
    // Go through this loop quantity of times
    numList.unshift(rand(high));
    // add new number to end of array
};

numList.toString();
document.getElementById('boxed').innerHTML = numList.join(" ");

<div id="container">
    <header>
        <h1>Lucky Numbers</h1>
    </header>

    <main>
        <div id="boxed"></div>
         <p>Good luck!</p>
    </main>
</div>


来源: stackexchange

问:
Get index of clicked element
So I'm still pretty new at JavaScript, I can do some basic stuff, but a lot of it, not so much. Anyway I am trying to create a gallery that opens a larger slideshow when one of the elements is clicked. The problem I'm running into is I don't know how to find the index of the clicked elements. I've tried Google, and I even looked here and lots of answers to the question, but none of them seem to work for my bit of code.

```<code>    var getThumbs = Array.from(document.querySelectorAll('.retail-thumbnail'));
    for (var i = 0; i < getThumbs.length; i++) {
        getThumbs[i].onclick = function(e) {
            var createSlideshow = document.createElement('div');
            createSlideshow.setAttribute('class', 'retail-slideshow');
            var createClsBtn = document.createElement('div');
            createClsBtn.setAttribute('class', 'close');
            createClsBtn.innerHTML = '×';
            createSlideshow.append(createClsBtn);
            var slides = '';
            const index = getThumbs
            getThumbs.forEach(gall => {
                if (gall.classList.contains('video-thumb')) {
                    gall.childNodes.forEach(source => {
                            source = Array.from(source.src.split('.'));
                            source = source[source.length - 3];
                            slides += '<div class="retail-slide">\n' +
                                      '<iframe src="https://player.vimeo.com/video/' + source + '" width="100%" height="100%" frameborder="0" webkitallowfullscreen mozallowfullscreen></iframe>\n' +
                                      '</div>\n\n'
                    });
                } else {
                    slides += '<img src="' + gall.src + '" class="retail-slide">\n\n'
                }
            });
            slides += '<div id="retail_ss_prev"></div><div id="retail_ss_next"></div>';
            createSlideshow.innerHTML += slides;
            var activeModal = document.querySelector('.modal.active');
            activeModal.append(createSlideshow);
            var activeCls = document.querySelector('.retail-slideshow > .close');
            activeCls.addEventListener('click', function(e) {
                activeCls.parentNode.remove();
            });
        };
    };
};
</code>```

So this is what I have, and it writes everything, but I can't get the index when I click on one of the .retail-thumbnail elements. Any help is greatly appreciated. Preferably in Vanilla JS. I try to stay away from Jquery

答:
Use an anonymous function to pass both the event and the index.

Below is the code that passes the index to the function in your code, in addition to the event.

By using an anonymous function, your are able to create a function that takes the event as an input (e), but also know what the index is (see about closures - the anonymous function knows lexical scope from when it was created).

I used anonymous function and the ES-6 fat arrow function syntax below ()=>{}. You can do it without these, but it will look less clean.

```<code>const clicked = (e,i) =>{
        var createSlideshow = document.createElement('div');
            createSlideshow.setAttribute('class', 'retail-slideshow');
            var createClsBtn = document.createElement('div');
            createClsBtn.setAttribute('class', 'close');
            createClsBtn.innerHTML = '×';
            createSlideshow.append(createClsBtn);
            var slides = '';
            const index = getThumbs
            getThumbs.forEach(gall => {
                if (gall.classList.contains('video-thumb')) {
                    gall.childNodes.forEach(source => {
                            source = Array.from(source.src.split('.'));
                            source = source[source.length - 3];
                            slides += '<div class="retail-slide">\n' +
                                      '<iframe src="https://player.vimeo.com/video/' + source + '" width="100%" height="100%" frameborder="0" webkitallowfullscreen mozallowfullscreen></iframe>\n' +
                                      '</div>\n\n'
                    });
                } else {
                    slides += '<img src="' + gall.src + '" class="retail-slide">\n\n'
                }
            });
            slides += '<div id="retail_ss_prev"></div><div id="retail_ss_next"></div>';
            createSlideshow.innerHTML += slides;
            var activeModal = document.querySelector('.modal.active');
            activeModal.append(createSlideshow);
            var activeCls = document.querySelector('.retail-slideshow > .close');
            activeCls.addEventListener('click', function(e) {
            activeCls.parentNode.remove();
}

var getThumbs = Array.from(document.querySelectorAll('.retail-thumbnail'));
    for (var i = 0; i < getThumbs.length; i++) {
        getThumbs[i].onclick = (e) =>{clicked(e,i);}
        };
    };
};
</code>```

ContentLicense: CC BY-SA 4.0

Title: Get index of clicked element

Body:
So I'm still pretty new at JavaScript, I can do some basic stuff, but a lot of it, not so much. Anyway I am trying to create a gallery that opens a larger slideshow when one of the elements is clicked. The problem I'm running into is I don't know how to find the index of the clicked elements. I've tried Google, and I even looked here and lots of answers to the question, but none of them seem to work for my bit of code.

    var getThumbs = Array.from(document.querySelectorAll('.retail-thumbnail'));
    for (var i = 0; i < getThumbs.length; i++) {
        getThumbs[i].onclick = function(e) {
            var createSlideshow = document.createElement('div');
            createSlideshow.setAttribute('class', 'retail-slideshow');
            var createClsBtn = document.createElement('div');
            createClsBtn.setAttribute('class', 'close');
            createClsBtn.innerHTML = '×';
            createSlideshow.append(createClsBtn);
            var slides = '';
            const index = getThumbs
            getThumbs.forEach(gall => {
                if (gall.classList.contains('video-thumb')) {
                    gall.childNodes.forEach(source => {
                            source = Array.from(source.src.split('.'));
                            source = source[source.length - 3];
                            slides += '
\n' +
                                      '\n' +
                                      '
\n\n'
                    });
                } else {
                    slides += '\n\n'
                }
            });
            slides += '

';
            createSlideshow.innerHTML += slides;
            var activeModal = document.querySelector('.modal.active');
            activeModal.append(createSlideshow);
            var activeCls = document.querySelector('.retail-slideshow > .close');
            activeCls.addEventListener('click', function(e) {
                activeCls.parentNode.remove();
            });
        };
    };
};

So this is what I have, and it writes everything, but I can't get the index when I click on one of the .retail-thumbnail elements. Any help is greatly appreciated. Preferably in Vanilla JS. I try to stay away from Jquery

Body:
Use an anonymous function to pass both the event and the index.

Below is the code that passes the index to the function in your code, in addition to the event.

By using an anonymous function, your are able to create a function that takes the event as an input (e), but also know what the index is (see about closures - the anonymous function knows lexical scope from when it was created).

I used anonymous function and the ES-6 fat arrow function syntax below ()=>{}. You can do it without these, but it will look less clean.

const clicked = (e,i) =>{
        var createSlideshow = document.createElement('div');
            createSlideshow.setAttribute('class', 'retail-slideshow');
            var createClsBtn = document.createElement('div');
            createClsBtn.setAttribute('class', 'close');
            createClsBtn.innerHTML = '&times;';
            createSlideshow.append(createClsBtn);
            var slides = '';
            const index = getThumbs
            getThumbs.forEach(gall => {
                if (gall.classList.contains('video-thumb')) {
                    gall.childNodes.forEach(source => {
                            source = Array.from(source.src.split('.'));
                            source = source[source.length - 3];
                            slides += '<div class="retail-slide">\n' +
                                      '<iframe src="https://player.vimeo.com/video/' + source + '" width="100%" height="100%" frameborder="0" webkitallowfullscreen mozallowfullscreen></iframe>\n' +
                                      '</div>\n\n'
                    });
                } else {
                    slides += '<img src="' + gall.src + '" class="retail-slide">\n\n'
                }
            });
            slides += '<div id="retail_ss_prev"></div><div id="retail_ss_next"></div>';
            createSlideshow.innerHTML += slides;
            var activeModal = document.querySelector('.modal.active');
            activeModal.append(createSlideshow);
            var activeCls = document.querySelector('.retail-slideshow > .close');
            activeCls.addEventListener('click', function(e) {
            activeCls.parentNode.remove();
}

var getThumbs = Array.from(document.querySelectorAll('.retail-thumbnail'));
    for (var i = 0; i < getThumbs.length; i++) {
        getThumbs[i].onclick = (e) =>{clicked(e,i);}
        };
    };
};


答:
When you get elements by class names (source: https://developer.mozilla.org/fr/docs/Web/API/Document/getElementsByClassName), you receive an array,so you have to precise which element of the array you want, I think [0] in your case.
It's better to work with an ID if you only have one place to put the result, like this:

    do {
        var high = prompt('What\'s the highest number you want to generate','');
        high = parseInt(high, 10);
    } while (isNaN(high));

    do {
        var nums = prompt('How many numbers do you want to generate','');
        nums = parseInt(nums, 10);
    } while (isNaN(nums));

    function rand(highestNum) {
        var randomNumber =
        Math.floor(Math.random() * highestNum) + 1;
        return randomNumber;
    }

    var numList = [];

    for (var i = 0; i < nums; i++) {
        // Go through this loop quantity of times
        numList.unshift(rand(high));
        // add new number to end of array
        console.log(numList)
    };
    numList.toString();
    document.getElementById('boxed').innerHTML = numList;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
<title>Super Lotto</title>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Libre+Franklin" rel="stylesheet">
<link href="lotto-styles.css" rel="stylesheet">

</head>

<body>
<div id="container">
    <header>
        <h1>Lucky Numbers</h1>
    </header>

    <main>
        <div id="boxed"></div>
         <p>Good luck!</p>
    </main>
</div> <!-- Closing container -->
</body>

</html></code>```

Title: Unknown error writing an array to an element in javascript?

Body:
When you get elements by class names (source: https://developer.mozilla.org/fr/docs/Web/API/Document/getElementsByClassName), you receive an array,so you have to precise which element of the array you want, I think [0] in your case.
It's better to work with an ID if you only have one place to put the result, like this:

    do {
        var high = prompt('What\'s the highest number you want to generate','');
        high = parseInt(high, 10);
    } while (isNaN(high));

    do {
        var nums = prompt('How many numbers do you want to generate','');
        nums = parseInt(nums, 10);
    } while (isNaN(nums));

    function rand(highestNum) {
        var randomNumber =
        Math.floor(Math.random() * highestNum) + 1;
        return randomNumber;
    }

    var numList = [];

    for (var i = 0; i < nums; i++) {
        // Go through this loop quantity of times
        numList.unshift(rand(high));
        // add new number to end of array
        console.log(numList)
    };
    numList.toString();
    document.getElementById('boxed').innerHTML = numList;

<!DOCTYPE html>
<html lang="en">

<head>
<title>Super Lotto</title>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Libre+Franklin" rel="stylesheet">
<link href="lotto-styles.css" rel="stylesheet">

</head>

<body>
<div id="container">
    <header>
        <h1>Lucky Numbers</h1>
    </header>

    <main>
        <div id="boxed"></div>
         <p>Good luck!</p>
    </main>
</div> <!-- Closing container -->
</body>

</html>


问:
T-SQL - compare strings char by char
I need to compare two strings character by character using T-SQL. Let's assume i have twor strings like these:

```<code>123456789
212456789
</code>```

Every time the character DO NOT match, I would like to increase the variable @Diff +=1. In this case the first three characters differ. So the @Diff = 3 (0 would be default value).

Thank you for all suggestions.

答:
The below query compares, shows the different characters and bring you the count of differences

```<code>Declare @char1 nvarchar(1), @char2 nvarchar(1), @i int = 1, @max int
Declare @string1 nvarchar(max) = '123456789'
        , @string2 nvarchar(max) = '212456789'
Declare @diff_table table (pos int , string1 nvarchar(50) , string2 nvarchar(50), Status nvarchar(50))
Set @max = (select case when len(@String1+'x')-1 > len(@string2+'x')-1 then len(@String1+'x')-1 else len(@string2+'x')-1 end)
while @i < @max +1

        BEGIN
        Select @char1 = SUBSTRING(@string1,@i,1), @char2 = SUBSTRING(@string2,@i,1)
        INSERT INTO @diff_table values
        (
            @i,
            case when UNICODE(@char1) is null then '' else concat(@char1,' - (',UNICODE(@char1),')') end,
            case when UNICODE(@char2) is null then '' else concat(@char2,' - (',UNICODE(@char2),')') end,
            case when ISNULL(UNICODE(@char1),0) <> isnull(UNICODE(@char2),0) then 'CHECK' else 'OK' END
        )
        set @i+=1
        END

Select * from @diff_table
Declare @diff int = (Select count(*) from @diff_table where Status = 'Check')
Select @diff 'Difference'
</code>```

The output will be like this:

ContentLicense: CC BY-SA 3.0

Title: T-SQL - compare strings char by char

Body:
I need to compare two strings character by character using T-SQL. Let's assume i have twor strings like these:

123456789
212456789

Every time the character DO NOT match, I would like to increase the variable @Diff +=1. In this case the first three characters differ. So the @Diff = 3 (0 would be default value).

Thank you for all suggestions.

Body:
The below query compares, shows the different characters and bring you the count of differences

Declare @char1 nvarchar(1), @char2 nvarchar(1), @i int = 1, @max int
Declare @string1 nvarchar(max) = '123456789'
        , @string2 nvarchar(max) = '212456789'
Declare @diff_table table (pos int , string1 nvarchar(50) , string2 nvarchar(50), Status nvarchar(50))
Set @max = (select case when len(@String1+'x')-1 > len(@string2+'x')-1 then len(@String1+'x')-1 else len(@string2+'x')-1 end)
while @i < @max +1

        BEGIN
        Select @char1 = SUBSTRING(@string1,@i,1), @char2 = SUBSTRING(@string2,@i,1)
        INSERT INTO @diff_table values
        (
            @i,
            case when UNICODE(@char1) is null then '' else concat(@char1,' - (',UNICODE(@char1),')') end,
            case when UNICODE(@char2) is null then '' else concat(@char2,' - (',UNICODE(@char2),')') end,
            case when ISNULL(UNICODE(@char1),0) <> isnull(UNICODE(@char2),0) then 'CHECK' else 'OK' END
        )
        set @i+=1
        END

Select * from @diff_table
Declare @diff int = (Select count(*) from @diff_table where Status = 'Check')
Select @diff 'Difference'

The output will be like this:


问:
Downloading audio from web that has been modified with wavesurfer.js
I have created a multitrack web player using wavesurfer.js which can adjust the levels and panning of the different tracks.

What I want to do is export the mixed tracks with new levels and panning as a single .wav file.

I've done a bit of research into this and alot of people are pointing to https://github.com/mattdiamond/Recorderjs but development stopped on this over 4 years ago and from what I've found it seems to have a load of issues.

Just initializing it like so var rec = new Recorder(spectrum); I get an error saying Cannot read property 'createScriptProcessor' of undefined at new Recorder And a quick search shows that is deprecated, see https://developer.mozilla.org/en-US/docs/Web/API/BaseAudioContext/createScriptProcessor.

Although I have a multitrack player if I can figure out how to export a single track with the levels and panning I could go from there. Is there any other way of exporting web audio with just the web audio API or can anybody point me to any other js libraries like this that might work?

答:
Assuming you have PCM audio, you can add a RIFF/WAV header to it, create a Blob from that, and then set blob as an Object URL on the a.href attribute.  StackOverflow blocks the download here, but you run it locally to test.  Hope this helps!

// fetch stereo PCM Float 32 little-endian file
const url = 'https://batman.dev/static/61881209/triangle-stereo-float.pcm'

const ctx = new AudioContext()
const elStatus = document.querySelector('#status')
const elButton = document.querySelector('#download')

init().catch(showError)

async function init() {
  // get raw/PCM buffer (you will presumably already have your own)
  const buffer = await (await fetch(url)).arrayBuffer()

  // get WAV file bytes and audio params of your audio source
  const wavBytes = getWavBytes(buffer, {
    isFloat: true,       // floating point or 16-bit integer (WebAudio API decodes to Float32Array)
    numChannels: 2,
    sampleRate: 44100,
  })

  // add the button
  elButton.href = URL.createObjectURL(
    new Blob([wavBytes], { type: 'audio/wav' })
  )
  elButton.setAttribute('download', 'my-audio.wav') // name file
  status('')
  elButton.hidden = false
}

function status(msg) {
  elStatus.innerText = msg
}

function showError(e) {
  console.error(e)
  status(`ERROR: ${e}`)
}

// Returns Uint8Array of WAV bytes
function getWavBytes(buffer, options) {
  const type = options.isFloat ? Float32Array : Uint16Array
  const numFrames = buffer.byteLength / type.BYTES_PER_ELEMENT

  const headerBytes = getWavHeader(Object.assign({}, options, { numFrames }))
  const wavBytes = new Uint8Array(headerBytes.length + buffer.byteLength);

  // prepend header, then add pcmBytes
  wavBytes.set(headerBytes, 0)
  wavBytes.set(new Uint8Array(buffer), headerBytes.length)

  return wavBytes
}

// adapted from https://gist.github.com/also/900023
// returns Uint8Array of WAV header bytes
function getWavHeader(options) {
  const numFrames =      options.numFrames
  const numChannels =    options.numChannels || 2
  const sampleRate =     options.sampleRate || 44100
  const bytesPerSample = options.isFloat? 4 : 2
  const format =         options.isFloat? 3 : 1

  const blockAlign = numChannels * bytesPerSample
  const byteRate = sampleRate * blockAlign
  const dataSize = numFrames * blockAlign

  const buffer = new ArrayBuffer(44)
  const dv = new DataView(buffer)

  let p = 0

  function writeString(s) {
    for (let i = 0; i < s.length; i++) {
      dv.setUint8(p + i, s.charCodeAt(i))
    }
    p += s.length
  }

  function writeUint32(d) {
    dv.setUint32(p, d, true)
    p += 4
  }

  function writeUint16(d) {
    dv.setUint16(p, d, true)
    p += 2
  }

  writeString('RIFF')              // ChunkID
  writeUint32(dataSize + 36)       // ChunkSize
  writeString('WAVE')              // Format
  writeString('fmt ')              // Subchunk1ID
  writeUint32(16)                  // Subchunk1Size
  writeUint16(format)              // AudioFormat
  writeUint16(numChannels)         // NumChannels
  writeUint32(sampleRate)          // SampleRate
  writeUint32(byteRate)            // ByteRate
  writeUint16(blockAlign)          // BlockAlign
  writeUint16(bytesPerSample * 8)  // BitsPerSample
  writeString('data')              // Subchunk2ID
  writeUint32(dataSize)            // Subchunk2Size

  return new Uint8Array(buffer)
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  padding: 2rem;
  font-family: sans-serif;
  text-align: center;
}
#download {
  padding: 1em 2em;
  color: #fff;
  background: #4c8bf5;
  text-decoration: none;
}</code>```

Loading...

⬇ Download```

Body:
Assuming you have PCM audio, you can add a RIFF/WAV header to it, create a Blob from that, and then set blob as an Object URL on the a.href attribute.  StackOverflow blocks the download here, but you run it locally to test.  Hope this helps!

// fetch stereo PCM Float 32 little-endian file
const url = 'https://batman.dev/static/61881209/triangle-stereo-float.pcm'

const ctx = new AudioContext()
const elStatus = document.querySelector('#status')
const elButton = document.querySelector('#download')

init().catch(showError)

async function init() {
  // get raw/PCM buffer (you will presumably already have your own)
  const buffer = await (await fetch(url)).arrayBuffer()

  // get WAV file bytes and audio params of your audio source
  const wavBytes = getWavBytes(buffer, {
    isFloat: true,       // floating point or 16-bit integer (WebAudio API decodes to Float32Array)
    numChannels: 2,
    sampleRate: 44100,
  })

  // add the button
  elButton.href = URL.createObjectURL(
    new Blob([wavBytes], { type: 'audio/wav' })
  )
  elButton.setAttribute('download', 'my-audio.wav') // name file
  status('')
  elButton.hidden = false
}

function status(msg) {
  elStatus.innerText = msg
}

function showError(e) {
  console.error(e)
  status(`ERROR: ${e}`)
}

// Returns Uint8Array of WAV bytes
function getWavBytes(buffer, options) {
  const type = options.isFloat ? Float32Array : Uint16Array
  const numFrames = buffer.byteLength / type.BYTES_PER_ELEMENT

  const headerBytes = getWavHeader(Object.assign({}, options, { numFrames }))
  const wavBytes = new Uint8Array(headerBytes.length + buffer.byteLength);

  // prepend header, then add pcmBytes
  wavBytes.set(headerBytes, 0)
  wavBytes.set(new Uint8Array(buffer), headerBytes.length)

  return wavBytes
}

// adapted from https://gist.github.com/also/900023
// returns Uint8Array of WAV header bytes
function getWavHeader(options) {
  const numFrames =      options.numFrames
  const numChannels =    options.numChannels || 2
  const sampleRate =     options.sampleRate || 44100
  const bytesPerSample = options.isFloat? 4 : 2
  const format =         options.isFloat? 3 : 1

  const blockAlign = numChannels * bytesPerSample
  const byteRate = sampleRate * blockAlign
  const dataSize = numFrames * blockAlign

  const buffer = new ArrayBuffer(44)
  const dv = new DataView(buffer)

  let p = 0

  function writeString(s) {
    for (let i = 0; i < s.length; i++) {
      dv.setUint8(p + i, s.charCodeAt(i))
    }
    p += s.length
  }

  function writeUint32(d) {
    dv.setUint32(p, d, true)
    p += 4
  }

  function writeUint16(d) {
    dv.setUint16(p, d, true)
    p += 2
  }

  writeString('RIFF')              // ChunkID
  writeUint32(dataSize + 36)       // ChunkSize
  writeString('WAVE')              // Format
  writeString('fmt ')              // Subchunk1ID
  writeUint32(16)                  // Subchunk1Size
  writeUint16(format)              // AudioFormat
  writeUint16(numChannels)         // NumChannels
  writeUint32(sampleRate)          // SampleRate
  writeUint32(byteRate)            // ByteRate
  writeUint16(blockAlign)          // BlockAlign
  writeUint16(bytesPerSample * 8)  // BitsPerSample
  writeString('data')              // Subchunk2ID
  writeUint32(dataSize)            // Subchunk2Size

  return new Uint8Array(buffer)
}

body {
  padding: 2rem;
  font-family: sans-serif;
  text-align: center;
}
#download {
  padding: 1em 2em;
  color: #fff;
  background: #4c8bf5;
  text-decoration: none;
}

<div id="status">Loading...</div>
<a hidden id="download">⬇ Download</a>


问:
Problem changing icon in Delphi 2007
I've been working with a program someone else has made and I wanted to change the icon.

The icon I have is 256x256. I used http://converticon.com/ to create the icon (from a bmp I think). I used the icon in Inno Setup to create an installer and it worked fine

So I go to Options -> Application and attempt to load it. However, Delphi 2007 gives me an error 'The parameter is incorrect.' with this info: http://i.stack.imgur.com/vRCgs.png

When I do the same thing in Delphi XE, it works and loads the icon and changes it on compile. I can't use XE right now because the program uses a math parser that has a problem with unicode (thats something to fix for later haha)

So, what I did was open the project in XE, change the icon, save it, delete the dproj and open it in 2007. This works, compiles and displays the correct icon, but when I go to the project options, it gives me the same 'The parameter is incorrect' error.

The workaround isn't a big deal, but I shouldn't need to do it. Does anyone know why I can't change the icon in Delphi 2007?

Edit: I just used that same converticon site to convert the 256x256 icon to 192x192 and smaller and now it works perfectly. Thanks for the answers

答:
The "icon" file is actually a collection of images, at different resolution and using different encodings. When I'm creating my icons I'm making sure they don't actually contain the 256x256 PNG-encoded version because development tools built before Windows Vista don't understand that. And that includes your Delphi 2007 and my Delphi 7. I also remove the alpha-encoded 256x256 icon because it simply makes the file needlessly large.

You've got two fixes possible:

Find an ICO editor and remove all of the larger formats until your Delphi accepts the icon. I personally never seen the 256x256 used in the real world, they'd take up huge amounts of space on user's Desktop or in Windows Explorer.

Use a dummy icon and replace the icon resource in the generated exe after Delphi is done with it. This way you can keep all of the larger image formats, including the 256x256 PNG image.

Edit to correct an error

If possible, always include the 256x256 image, Windows scales that down for everything above 64x64.

I always assumed Windows Explorer would show an image that's based on the closest matching image size available in the ICO. That is, if a 128x128 image is necessary, Windows would use the 128x128 image if available, or scale down the 256x256 image if that's available, or scale up the 96x96 image. Apparently that's not so. I've just made a test icon consisting of several image formats, including 32, 48, 72, 96, 128 and 256 consisting of simple blobs of color (using the flood-fill tool). In Windows Explorer I cycled throw the various Display Modes, and it became apparent that starting with "Large Icon" (and that's not very large) Windows will scale down the 256x256 icon, and if that's not available, use the 48x48 icon, unscaled! The result is truly ugly and unexpected. The 72x72, 96x96 and 128x128 icons were simply ignored.

Thank you David for pointing this out.

Title: Problem changing icon in Delphi 2007


问:
Firebase saves data as List and sometimes as Map object
I am saving data with key as numeric values, where keys are questions attempted by user. It may be continuous if user has attempted all the questions eg. keys may be 0,1,2,3... this is saved by Firebase as Array (as in image)

JSON is

```<code>"parthgupta48@gmail,com": {
  "attemptedQuestions": [
    {
      "answer": "533",
      "status": "wrong",
      "submissionTime": 1487796702453
    },
    {
      "answer": "9",
      "score": 10,
      "status": "correct",
      "submissionTime": 1487878744867
    },
    {
      "answer": "4",
      "status": "wrong",
      "submissionTime": 1487956858227
    },
    {
      "answer": "3",
      "status": "wrong",
      "submissionTime": 1488056247303
    },
    null,
    {
      "answer": "25",
      "score": 16,
      "status": "correct",
      "submissionTime": 1488212417465
    },
    {
      "answer": "3",
      "status": "wrong",
      "submissionTime": 1488380348815
    },
    null,
    null,
    null,
    {
      "answer": "50",
      "score": 11,
      "status": "correct",
      "submissionTime": 1488648738615
    }
  ],
</code>```

When keys are discontinuous eg 0,9,15... this happen when when user has attempted only certain questions then Firebase saves this as map (as in image)

JSON is

```<code>"priyanshu96,goyal@gmail,com" : {
      "attemptedQuestions" : {
        "0" : {
          "answer" : "667",
          "status" : "wrong",
          "submissionTime" : 1487773682189
        },
        "10" : {
          "answer" : "50",
          "submissionTime" : 1488646361162
        }
      },
</code>```

This is my code I used to retrieve data in Android.

```<code>try {
       mCurrentUser = child.getValue(UserObject.class);
    } catch (Exception e) {

       Utils.makeToast("Some Error Occurred ",LoginActivity.this);

   }
</code>```

userObject class

```<code>public class UserObject implements Serializable {

private String name;
private String uid;
private String email;
private String photoUrl;
private String contact;//bekaar
private long credits;
public Map<String,AttemptedByUserObject> attemptedQuestions;

public void setAttemptedQuestions(Map<String, AttemptedByUserObject> attemptedQuestions) {
    this.attemptedQuestions = attemptedQuestions;
}

public Map<String, AttemptedByUserObject> getAttemptedQuestions() {
    return attemptedQuestions;
}

public long getCredits() {
    return credits;
}

public void setCredits(long credits) {
    this.credits = credits;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getUid() {
    return uid;
}

public void setUid(String uid) {
    this.uid = uid;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPhotoUrl() {
    return photoUrl;
}

public void setPhotoUrl(String photoUrl) {
    this.photoUrl = photoUrl;
}

public String getContact() {
    return contact;
}

public void setContact(String contact) {
    this.contact = contact;
}}
</code>```

But problem is attemptedQuestions needs to be list when data is saves as list and it need to be Map when data is saved as Map.

How can I solve this problem?

答:
When the information is saved with consecutive keys starting from Zero (I.e. 0, 1, 2, etc.) you will get back a list, in my case I was starting from One so for some reason it got me back a list starting with a null element. When keys are discontinuous a Map will be returned. After understanding this I ended up patching it with a type check, and because of the null in the list cases I remove the first element.

```<code>when (it) {
    is Map<*, *> -> doSomething(it.values.toList() as List<HashMap<String, Any>>)
    is List<*> -> doSomething((it.subList(1,it.size)) as List<HashMap<String, Any>>)
    is Any -> return
}
</code>```

In the example doSomething only takes List<Hashmap<String, Any>> arguments, but the variable it can be either a Map or a List.

Body:
I am saving data with key as numeric values, where keys are questions attempted by user. It may be continuous if user has attempted all the questions eg. keys may be 0,1,2,3... this is saved by Firebase as Array (as in image)

JSON is

"parthgupta48@gmail,com": {
  "attemptedQuestions": [
    {
      "answer": "533",
      "status": "wrong",
      "submissionTime": 1487796702453
    },
    {
      "answer": "9",
      "score": 10,
      "status": "correct",
      "submissionTime": 1487878744867
    },
    {
      "answer": "4",
      "status": "wrong",
      "submissionTime": 1487956858227
    },
    {
      "answer": "3",
      "status": "wrong",
      "submissionTime": 1488056247303
    },
    null,
    {
      "answer": "25",
      "score": 16,
      "status": "correct",
      "submissionTime": 1488212417465
    },
    {
      "answer": "3",
      "status": "wrong",
      "submissionTime": 1488380348815
    },
    null,
    null,
    null,
    {
      "answer": "50",
      "score": 11,
      "status": "correct",
      "submissionTime": 1488648738615
    }
  ],

When keys are discontinuous eg 0,9,15... this happen when when user has attempted only certain questions then Firebase saves this as map (as in image)

JSON is

"priyanshu96,goyal@gmail,com" : {
      "attemptedQuestions" : {
        "0" : {
          "answer" : "667",
          "status" : "wrong",
          "submissionTime" : 1487773682189
        },
        "10" : {
          "answer" : "50",
          "submissionTime" : 1488646361162
        }
      },

This is my code I used to retrieve data in Android.

try {
       mCurrentUser = child.getValue(UserObject.class);
    } catch (Exception e) {

       Utils.makeToast("Some Error Occurred ",LoginActivity.this);

   }

userObject class

public class UserObject implements Serializable {

private String name;
private String uid;
private String email;
private String photoUrl;
private String contact;//bekaar
private long credits;
public Map<String,AttemptedByUserObject> attemptedQuestions;

public void setAttemptedQuestions(Map<String, AttemptedByUserObject> attemptedQuestions) {
    this.attemptedQuestions = attemptedQuestions;
}

public Map<String, AttemptedByUserObject> getAttemptedQuestions() {
    return attemptedQuestions;
}

public long getCredits() {
    return credits;
}

public void setCredits(long credits) {
    this.credits = credits;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getUid() {
    return uid;
}

public void setUid(String uid) {
    this.uid = uid;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPhotoUrl() {
    return photoUrl;
}

public void setPhotoUrl(String photoUrl) {
    this.photoUrl = photoUrl;
}

public String getContact() {
    return contact;
}

public void setContact(String contact) {
    this.contact = contact;
}}

But problem is attemptedQuestions needs to be list when data is saves as list and it need to be Map when data is saved as Map.

How can I solve this problem?

Body:
When the information is saved with consecutive keys starting from Zero (I.e. 0, 1, 2, etc.) you will get back a list, in my case I was starting from One so for some reason it got me back a list starting with a null element. When keys are discontinuous a Map will be returned. After understanding this I ended up patching it with a type check, and because of the null in the list cases I remove the first element.

when (it) {
    is Map<*, *> -> doSomething(it.values.toList() as List<HashMap<String, Any>>)
    is List<*> -> doSomething((it.subList(1,it.size)) as List<HashMap<String, Any>>)
    is Any -> return
}

In the example doSomething only takes List<Hashmap<String, Any>> arguments, but the variable it can be either a Map or a List.


答:
for (var i=0; i<5; i++){
  var abc = function(){

    alert(i) //You can very well access i here
  }

 abc();

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

<p>You can pretty much access <code>i</code> inside <code>getThumbs[i].onclick</code> without having to write extra lines of codes.</p>

```for (var i = 0; i < getThumbs.length; i++) {
        getThumbs[i].onclick = function(e) {
            var createSlideshow = document.createElement('div');
            var index = i //You can access i due to the lexical scope
}
```

Title: Get index of clicked element

Body:
for (var i=0; i<5; i++){
  var abc = function(){

    alert(i) //You can very well access i here
  }

 abc();

}

You can pretty much access i inside getThumbs[i].onclick without having to write extra lines of codes.

for (var i = 0; i < getThumbs.length; i++) {
        getThumbs[i].onclick = function(e) {
            var createSlideshow = document.createElement('div');
            var index = i //You can access i due to the lexical scope
}


问:
How to set variable using pipe and awk in GDB?
I would like to store the executable name of the current inferior in a variable. I way to obtain the executable name in the gdb CLI is the following:

```<code> pipe info inferiors | awk '{ if ($1 == "*") { print $4} }'
</code>```

But I am unable to store the output of this expression in a variable. The expression uses single and double quotes, which makes gdb complain if it is combined with set and eval.

```<code>(gdb) set $exec="pipe info inferiors | awk '{ if ($1 == "*") { print $4} }'"
Argument to arithmetic operation not a number or boolean.
(gdb) eval "!echo %s", "pipe info inferiors | awk '{ if ($1 == "*") { print $4} }'"
Argument to arithmetic operation not a number or boolean.
</code>```

Then, how can I store the executable name in a variable? My goal is to pass the executable name to the file command to reload the executable when Autotools are used (see using libtool e gdb).

答:
Although @EmployedRussian's answer is the most appropriated solution for the use case presented in the question, I think that the question of how to use pipe and awk to set a variable has not been answered yet. This could be done using python and splitting the pipe in two parts:

```<code>python res = gdb.execute('info inferiors', to_string=True);
python gdb.execute ('set $exec = "' + str(res.strip().split()[6]) + '"');
</code>```

If a awk like command is preferred, try with the tools provided by python, for instance, convert res to a pandas DataFrame.

Note that, this approach could be catastrophic as has been seen here with the column selection issue.

Body:
I would like to store the executable name of the current inferior in a variable. I way to obtain the executable name in the gdb CLI is the following:

 pipe info inferiors | awk '{ if ($1 == "*") { print $4} }'

But I am unable to store the output of this expression in a variable. The expression uses single and double quotes, which makes gdb complain if it is combined with set and eval.

(gdb) set $exec="pipe info inferiors | awk '{ if ($1 == "*") { print $4} }'"
Argument to arithmetic operation not a number or boolean.
(gdb) eval "!echo %s", "pipe info inferiors | awk '{ if ($1 == "*") { print $4} }'"
Argument to arithmetic operation not a number or boolean.

Then, how can I store the executable name in a variable? My goal is to pass the executable name to the file command to reload the executable when Autotools are used (see using libtool e gdb).

Body:
Although @EmployedRussian's answer is the most appropriated solution for the use case presented in the question, I think that the question of how to use pipe and awk to set a variable has not been answered yet. This could be done using python and splitting the pipe in two parts:

python res = gdb.execute('info inferiors', to_string=True);
python gdb.execute ('set $exec = "' + str(res.strip().split()[6]) + '"');

If a awk like command is preferred, try with the tools provided by python, for instance, convert res to a pandas DataFrame.

Note that, this approach could be catastrophic as has been seen here with the column selection issue.


问:
Chrome Android not using all codec options in SDP offer
When I run RTCRtpSender.getCapabilities("video").codecs; on Chrome Android it includes H264. However, I run var offer = RTCPeerConnection.createOffer() and look at offer.sdp it will only sometimes include H264 in the offer. This is causing me issues with an application that requires H264 - it works inconsistently as a result of rejecting those offers that don't include H264, and I don't know how to force the SDP offer to include it. How do I make sure createOffer includes all available codecs? I would prefer not to have to do any manual editing of the SDP.

答:
I've been facing the same problem. As Pedro Vergara commented, it looks like a bug introduced in recent versions of Chrome Android. For now, I did a simple workaround by keep calling RTCRtpSender.getCapabilities('video') until it lists the expected H.264 codec support, before any attempt to create the SDP offer. Something like this:

```<code>console.log('Waiting for H.264 codec support');
checkH264(20);

function checkH264(count) {
  if (count > 0) {
    console.log('Getting video codec capabilities');
    let capabilities = JSON.stringify(RTCRtpSender.getCapabilities('video').codecs);
    console.log(capabilities);
    if (capabilities.toLowerCase().includes('video/h264')) {
      console.log('H.264 support found. Ready to proceed now! =)');
      // Proceed to SDP offer creation...
    } else {
      setTimeout(checkH264, 1000, count - 1);
    }
  } else {
    console.warn('H.264 support not found');
    // Proceed with caution. SDP offer may not contain H.264...
  }
}
</code>```

Notice that the code above gives some time for Chrome to make H.264 available, by using setTimeout(). Just calling RTCRtpSender.getCapabilities('video') twice or more without really waiting may not work.

Body:
I've been facing the same problem. As Pedro Vergara commented, it looks like a bug introduced in recent versions of Chrome Android. For now, I did a simple workaround by keep calling RTCRtpSender.getCapabilities('video') until it lists the expected H.264 codec support, before any attempt to create the SDP offer. Something like this:

console.log('Waiting for H.264 codec support');
checkH264(20);

function checkH264(count) {
  if (count > 0) {
    console.log('Getting video codec capabilities');
    let capabilities = JSON.stringify(RTCRtpSender.getCapabilities('video').codecs);
    console.log(capabilities);
    if (capabilities.toLowerCase().includes('video/h264')) {
      console.log('H.264 support found. Ready to proceed now! =)');
      // Proceed to SDP offer creation...
    } else {
      setTimeout(checkH264, 1000, count - 1);
    }
  } else {
    console.warn('H.264 support not found');
    // Proceed with caution. SDP offer may not contain H.264...
  }
}

Notice that the code above gives some time for Chrome to make H.264 available, by using setTimeout(). Just calling RTCRtpSender.getCapabilities('video') twice or more without really waiting may not work.


问:
API request returning NULL on HEROKU, but working locally Discord.js Node.js
I'm working on a Discord BOT using Node.js

I'm trying to get an image using a public API with no key needed, it's working locally but when I deploy it on Heroku, it doesn't work.

I need to know if Heroku is limiting the API requests and I should upgrade my "free" plan or I'm missing something.

Error message when trying to call the API :

2020-06-02T22:37:20.973482+00:00 app[worker.1]: Mister Secret is online !
2020-06-02T22:37:47.205353+00:00 app[worker.1]: rpstorydiscord just joined the server.
2020-06-02T22:37:49.831240+00:00 app[worker.1]: Error: Server responded with 403
2020-06-02T22:37:49.831256+00:00 app[worker.1]:     at /app/node_modules/canvas/lib/image.js:56:28
2020-06-02T22:37:49.831257+00:00 app[worker.1]:     at /app/node_modules/simple-get/index.js:89:7
2020-06-02T22:37:49.831258+00:00 app[worker.1]:     at PassThrough.<anonymous> (/app/node_modules/simple-concat/index.js:7:13)
2020-06-02T22:37:49.831258+00:00 app[worker.1]:     at Object.onceWrapper (events.js:421:28)
2020-06-02T22:37:49.831258+00:00 app[worker.1]:     at PassThrough.emit (events.js:315:20)
2020-06-02T22:37:49.831259+00:00 app[worker.1]:     at endReadableNT (_stream_readable.js:1221:12)
2020-06-02T22:37:49.831259+00:00 app[worker.1]:     at processTicksAndRejections (internal/process/task_queues.js:84:21)

The API request looks like this :

https://api.habbocity.me/avatar_image.php?user=PSEUDO&headonly=0&direction=3&head_direction=3&size=l

Thank you for your help.

答:
Your API call was blocked with a site-wide CAPTCHA from the web host Cloudflare. Any call to that domain is blocked with the CAPTCHA, unless you get a token from their "privacy-pass" extension/plug-in. </p>

<p>It worked on localhost because you already have such a token downloaded. </p>

Body:
Your API call was blocked with a site-wide CAPTCHA from the web host Cloudflare. Any call to that domain is blocked with the CAPTCHA, unless you get a token from their "privacy-pass" extension/plug-in.

It worked on localhost because you already have such a token downloaded.


问:
Turning off Bluetooth Adapter not calling onConnectionStateChange Android 8.1.0
Turning off the bluetooth in Android system settings gives us the BluetoothGattCallback.onConnectionStateChange() call in Android < 27 (Oreo). However when I try it on my Pixel or Nexus 5X (Android 8.1.0) I don't get that callback. Is there some change to the bluetooth code where we don't get notified of BluetoothProfile.STATE_DISCONNECTED with the bluetooth setting change. I notice the device gets disconnected. Also when turning off the BLE device that callback gets called. Any insight is appreciated!

Filed as an issue here Google Issue

答:
I guess this is kind of expected, or at least this has always been the behaviour. When Bluetooth is turned off (or dies for some reason), the Bluetooth daemon process quits. But it's the same process that also sends out your GATT callbacks. If the process is terminated, it can't send any callbacks.

Use https://developer.android.com/reference/android/bluetooth/BluetoothAdapter#ACTION_STATE_CHANGED instead to detect when Bluetooth is turned off, and at that time you should just go and close all BluetoothGatt objects.


问:
Why do changes to an array 'B' in JavaScript spread to an array 'A' (which was used to define 'B' but thereafter never directly modified)?
I created a constant named 'alphabet' and assigned it to an array containing the first 5 letters of the alphabet. I then wanted to have a function that would add a number to each character in the array, to enumerate them. But, I didn't want the values in the original 'alphabet' array to be modified, so I created a 'temp' variable within my enumerating function and only made changes to that. However, any changes I made to 'temp' spread over to 'alphabet'. I don't understand why and I'd like to prevent that from happening.

Here's my code: (also available on CodePen)

```<code>const alphabet = ["a", "b", "c", "d", "e"];

function alphaPosition(seq) {
  //'temp' gets 'seq' to avoid making changes directly on the provided argument.
  let temp = seq;
  //adds indexes to each element in the 'temp' array:
  for (let i = 1; i <= temp.length; i++) {
    temp[i - 1] = temp[i - 1] + i;
  }
  return temp;
}

console.log(
  "Step 1. 'alphabet' array before running the 'alphaPosition' function:"
);
console.log(alphabet);
console.log(
  "Step 2. This is the final value of 'temp' in 'alphaPosition' after running the function. An index has been added to every element in the array, as expected:"
);
console.log(alphaPosition(alphabet));
console.log(
  "Step 3. Here's the 'alphabet' array after running 'alphaPosition'. Indexes have also been added to every element, despite not modifying the function argument directly:"
);
console.log(alphabet);
</code>```

Output:

```<code>/*
-> Step 1. 'alphabet' array before running the 'alphaPosition' function:
-> ["a", "b", "c", "d", "e"]
-> Step 2. This is the final value of 'temp' in 'alphaPosition' after running the function. An index has been added to every element in the array, as expected:
-> ["a1", "b2", "c3", "d4", "e5"]
-> Step 3. Here's the 'alphabet' array after running 'alphaPosition'. Indexes have also been added to every element, despite not modifying the function argument directly:
-> ["a1", "b2", "c3", "d4", "e5"]
*/
</code>```

Why do changes to 'temp' spread to 'alphabet'? I would expect that, since I defined 'alphabet' as a constant, it shouldn't even be possible to modify it. Also, I never make changes to it in my function. I only use it to define 'temp'. Is there any way to prevent these spreads from happening?

I experimented doing something similar with a numeric const instead of an array, and everything worked as intended:

```<code>const number = 10;

function numChange(n) {
  //'virtualN' gets 'n' to avoid making changes directly on the provided argument.
  let virtualN = n;
  //modify 'virtualN' multiple times to emulate what was done to the 'temp' array in the alphaPosition function.
  for (let i = 1; i <= 5; i++) {
    virtualN = "iteration" + i;
  }
  return virtualN;
}

console.log(
  "Step 1. See the value of 'number' before running the numChange function:"
);
console.log(number);
console.log(
  "Step 2. This is the final value of 'virtualN' in 'numChange(number)' after running the function. As expected, it's been modified from its initual value by the 'for' loop:"
);
console.log(numChange(number));
console.log(
  "Step 3. Finally, we can see the value of 'number' is still the same as before running the numChange function. As expected, only the value of virtualN changed while the argument 'n' suffered no modifications:"
);
console.log(number);
</code>```

Output:

```<code>/*
-> Step 1. See the value of 'number' before running the numChange function:
-> 10
-> Step 2. This is the final value of 'virtualN' in 'numChange(number)' after running the function. As expected, it's been modified from its initual value by the 'for' loop:
-> iteration5
-> Step 3. Finally, we can see the value of 'number' is still the same as before running the numChange function. As expected, only the value of virtualN changed while the argument 'n' suffered no modifications:
-> 10
*/
</code>```

Why does using an intermediary variable to avoid making changes to the original work for numbers and not for arrays?

I'd be extremely grateful for any help or clarification on this. I've added my code to this CodePen in case you'd like to tweak it or experiment more with it.
Thank you in advance for any help.

答:
This seems to be a duplicate of this.
and the underlying answer is here.

I explain why below:

It would seem that for Strings and numbers, javascript is pass by value, and objects such as arrays is pass by reference.

What this means is that in your first example; the function is taking a reference to the original array, and when you do let temp = seq, temp is actually just a pointer to the original object passed in. In this case that is alphabet so when you modify temp; it is actually modifying alphabet.

Pass by value just sends to the function the value, so the original variable stays the same as in your number example.

In order to get your intended outcome you would want to make a Deep Copy of your array like let temp = deepCopy(seq).

Use of const I think may just be syntax for the user to know not to modify it and some editors will not let you remodify const in the code, but in this case its happening in a roundabout way.

Body:
I created a constant named 'alphabet' and assigned it to an array containing the first 5 letters of the alphabet. I then wanted to have a function that would add a number to each character in the array, to enumerate them. But, I didn't want the values in the original 'alphabet' array to be modified, so I created a 'temp' variable within my enumerating function and only made changes to that. However, any changes I made to 'temp' spread over to 'alphabet'. I don't understand why and I'd like to prevent that from happening.

Here's my code: (also available on CodePen)

const alphabet = ["a", "b", "c", "d", "e"];

function alphaPosition(seq) {
  //'temp' gets 'seq' to avoid making changes directly on the provided argument.
  let temp = seq;
  //adds indexes to each element in the 'temp' array:
  for (let i = 1; i <= temp.length; i++) {
    temp[i - 1] = temp[i - 1] + i;
  }
  return temp;
}

console.log(
  "Step 1. 'alphabet' array before running the 'alphaPosition' function:"
);
console.log(alphabet);
console.log(
  "Step 2. This is the final value of 'temp' in 'alphaPosition' after running the function. An index has been added to every element in the array, as expected:"
);
console.log(alphaPosition(alphabet));
console.log(
  "Step 3. Here's the 'alphabet' array after running 'alphaPosition'. Indexes have also been added to every element, despite not modifying the function argument directly:"
);
console.log(alphabet);

Output:

/*
-> Step 1. 'alphabet' array before running the 'alphaPosition' function:
-> ["a", "b", "c", "d", "e"]
-> Step 2. This is the final value of 'temp' in 'alphaPosition' after running the function. An index has been added to every element in the array, as expected:
-> ["a1", "b2", "c3", "d4", "e5"]
-> Step 3. Here's the 'alphabet' array after running 'alphaPosition'. Indexes have also been added to every element, despite not modifying the function argument directly:
-> ["a1", "b2", "c3", "d4", "e5"]
*/

Why do changes to 'temp' spread to 'alphabet'? I would expect that, since I defined 'alphabet' as a constant, it shouldn't even be possible to modify it. Also, I never make changes to it in my function. I only use it to define 'temp'. Is there any way to prevent these spreads from happening?

I experimented doing something similar with a numeric const instead of an array, and everything worked as intended:

const number = 10;

function numChange(n) {
  //'virtualN' gets 'n' to avoid making changes directly on the provided argument.
  let virtualN = n;
  //modify 'virtualN' multiple times to emulate what was done to the 'temp' array in the alphaPosition function.
  for (let i = 1; i <= 5; i++) {
    virtualN = "iteration" + i;
  }
  return virtualN;
}

console.log(
  "Step 1. See the value of 'number' before running the numChange function:"
);
console.log(number);
console.log(
  "Step 2. This is the final value of 'virtualN' in 'numChange(number)' after running the function. As expected, it's been modified from its initual value by the 'for' loop:"
);
console.log(numChange(number));
console.log(
  "Step 3. Finally, we can see the value of 'number' is still the same as before running the numChange function. As expected, only the value of virtualN changed while the argument 'n' suffered no modifications:"
);
console.log(number);

Output:

/*
-> Step 1. See the value of 'number' before running the numChange function:
-> 10
-> Step 2. This is the final value of 'virtualN' in 'numChange(number)' after running the function. As expected, it's been modified from its initual value by the 'for' loop:
-> iteration5
-> Step 3. Finally, we can see the value of 'number' is still the same as before running the numChange function. As expected, only the value of virtualN changed while the argument 'n' suffered no modifications:
-> 10
*/

Why does using an intermediary variable to avoid making changes to the original work for numbers and not for arrays?

I'd be extremely grateful for any help or clarification on this. I've added my code to this CodePen in case you'd like to tweak it or experiment more with it.
Thank you in advance for any help.


问:
How to get a value passed throuhgt url to a class Create View in django?
Salutations good people of stack overflow,
I read the docs and I been duckduckgoing this and I can't find and answer. I am pretty new to Django so if my approach is totally wrong please let me know. ^^

I am using Django 3.0 and I want to get a Primay Key of a model for a Post into a create view for a Comment Model with a foreign Key Post field, so that each Comment knows to which Post it belong in a one to many relationship. To accomplish I am defining the template as:

```<code><a href="{% url 'comment_new' post.pk  %}">
   <p class="text-center">Write a Comment</p>
</a>
</code>```

In my urls.py I have:

```<code>urlpatterns = [
        path('<int:post>/new', CommentCreateView.as_view(), name='comment_new'),
        ]
</code>```

and in my views.py I have:

```<code>class CommentCreateView(LoginRequiredMixin, CreateView):
    model = Comment
    template_name = 'Comment_new.html'
    fields = ('writing',)
    login_url = 'login'

    def get_object(self, **kwargs ):
        return models.objects.get(id=self.kwargs['post'])

    def form_valid(self, form):
        ''' Set the user which send the request as the form 'creator' '''
        form.instance.user = self.request.user

        return super().form_valid(form)

</code>```

I'm trying to access the post int by overwriting get_object with return models.objects.get(id=self.kwargs['post'])
, and the setting it to the comment model field in the form_valid with form.instance.post = self.post as I did with the users. But it does not seem to work any help I much appreciated. Thank you.

答:
view.py

```<code>def create_view(request, pk):
    data = {}
    data['myModel'] = MyModel.objects.get(pk=pk)
    return render(request, 'my_template.html', data)
</code>```

my_template.html

```<code><a href="{% url 'comment_new' myModel.id  %}">
   <p class="text-center">Write a Comment</p>
</a>
</code>```

urls.py

```<code>urlpatterns = [
    path('create/', create_view, name = 'url_create'),
]
</code>```

Body:
Salutations good people of stack overflow,
I read the docs and I been duckduckgoing this and I can't find and answer. I am pretty new to Django so if my approach is totally wrong please let me know. ^^

I am using Django 3.0 and I want to get a Primay Key of a model for a Post into a create view for a Comment Model with a foreign Key Post field, so that each Comment knows to which Post it belong in a one to many relationship. To accomplish I am defining the template as:

Write a Comment

In my urls.py I have:

urlpatterns = [
        path('<int:post>/new', CommentCreateView.as_view(), name='comment_new'),
        ]

and in my views.py I have:

class CommentCreateView(LoginRequiredMixin, CreateView):
    model = Comment
    template_name = 'Comment_new.html'
    fields = ('writing',)
    login_url = 'login'

    def get_object(self, **kwargs ):
        return models.objects.get(id=self.kwargs['post'])

    def form_valid(self, form):
        ''' Set the user which send the request as the form 'creator' '''
        form.instance.user = self.request.user

        return super().form_valid(form)

I'm trying to access the post int by overwriting get_object with return models.objects.get(id=self.kwargs['post'])
, and the setting it to the comment model field in the form_valid with form.instance.post = self.post as I did with the users. But it does not seem to work any help I much appreciated. Thank you.

Body:
view.py

def create_view(request, pk):
    data = {}
    data['myModel'] = MyModel.objects.get(pk=pk)
    return render(request, 'my_template.html', data)

my_template.html

<a href="{% url 'comment_new' myModel.id  %}">
   <p class="text-center">Write a Comment</p>
</a>

urls.py

urlpatterns = [
    path('create/', create_view, name = 'url_create'),
]


问:
Overriding a publically aliased method via private inheritance
I have a class heirarchy where there is one base type Base with a list of implementations and another base class, AnotherBase, that is almost like Base but a little different. To express this in the language I used private inheritance on the second base class (so there is no as-is relationship between implementations of the latter with the former).

Let's say this is the code (https://wandbox.org/permlink/2e2EG0eKmcLiyvgt)

```<code>#include <iostream>

using std::cout;
using std::endl;

class Base {
public:
    virtual ~Base() = default;
    virtual void foo() = 0;
};

class Impl : public Base {
public:
    void foo() {
        cout << "Impl::foo()" << endl;
    }
};

class AnotherBase : private Base {
public:
    using Base::foo;

    // other virtual methods
};

class Derived : public AnotherBase {
public:
    explicit Derived(std::unique_ptr<Base> base) : base_{std::move(base)} {}

    void foo() override {
        base_->foo();
    }

private:
    std::unique_ptr<Base> base_;
};

int main() {
    auto impl = std::make_unique<Impl>();
    std::make_unique<Derived>(std::move(impl))->foo();
}
</code>```

When I try to compile the above code, I get the following error

```<code>prog.cc:27:38: error: 'Base' is a private member of 'Base'
</code>```

What is the best way to express the above idea if this does not work? Also why does it not work?

答:
On these two lines within the declaration of Derived, Base is resolved as the the privately-inherited Base type since it is in scope -- even though it is private:

```<code>explicit Derived(std::unique_ptr<Base> base) : base_{std::move(base)} {}
// ...
std::unique_ptr<Base> base_;
</code>```

C++ does not ignore in-scope names that refer to things the current scope doesn't have access to.  It seems logical that the compiler would look in an outer scope for a Base that it does have access to, but this is not what happens.  The compiler simply stops at the closest Base it sees without regard for any access modifiers.

This can be trivially fixed by referring to the Base type through the top-level namespace prefix :::

```<code>explicit Derived(std::unique_ptr<::Base> base) : base_{std::move(base)} {}
// ...
std::unique_ptr<::Base> base_;
</code>```

Both refer to the same type, but Derived does not have access to the inherited Base name, while it does have access to the global Base name.

You could also fix this issue by redefining what Base means within Derived. At the top of the Derived declaration, you can add:

```<code>protected:
    using Base = ::Base;
</code>```

This hides the inherited Base name behind a type alias that Derived does have access to.

Body:
I have a class heirarchy where there is one base type Base with a list of implementations and another base class, AnotherBase, that is almost like Base but a little different. To express this in the language I used private inheritance on the second base class (so there is no as-is relationship between implementations of the latter with the former).

Let's say this is the code (https://wandbox.org/permlink/2e2EG0eKmcLiyvgt)

#include <iostream>

using std::cout;
using std::endl;

class Base {
public:
    virtual ~Base() = default;
    virtual void foo() = 0;
};

class Impl : public Base {
public:
    void foo() {
        cout << "Impl::foo()" << endl;
    }
};

class AnotherBase : private Base {
public:
    using Base::foo;

    // other virtual methods
};

class Derived : public AnotherBase {
public:
    explicit Derived(std::unique_ptr<Base> base) : base_{std::move(base)} {}

    void foo() override {
        base_->foo();
    }

private:
    std::unique_ptr<Base> base_;
};

int main() {
    auto impl = std::make_unique<Impl>();
    std::make_unique<Derived>(std::move(impl))->foo();
}

When I try to compile the above code, I get the following error

prog.cc:27:38: error: 'Base' is a private member of 'Base'

What is the best way to express the above idea if this does not work? Also why does it not work?

Body:
On these two lines within the declaration of Derived, Base is resolved as the the privately-inherited Base type since it is in scope -- even though it is private:

explicit Derived(std::unique_ptr<Base> base) : base_{std::move(base)} {}
// ...
std::unique_ptr<Base> base_;

C++ does not ignore in-scope names that refer to things the current scope doesn't have access to.  It seems logical that the compiler would look in an outer scope for a Base that it does have access to, but this is not what happens.  The compiler simply stops at the closest Base it sees without regard for any access modifiers.

This can be trivially fixed by referring to the Base type through the top-level namespace prefix :::

explicit Derived(std::unique_ptr<::Base> base) : base_{std::move(base)} {}
// ...
std::unique_ptr<::Base> base_;

Both refer to the same type, but Derived does not have access to the inherited Base name, while it does have access to the global Base name.

You could also fix this issue by redefining what Base means within Derived. At the top of the Derived declaration, you can add:

protected:
    using Base = ::Base;

This hides the inherited Base name behind a type alias that Derived does have access to.


问:
Replace elements in an Nx3x2 numpy array with elements located in an Mx2 numpy array
I have the following xy numpy array which represents the locations of the vertices of some triangles:

```<code>array([[[ 0.30539728, 49.82845203],
        [ 0.67235022, 49.95042185],
        [ 0.268982  , 49.95195348]],
       [[ 0.268982  , 49.95195348],
        [ 0.67235022, 49.95042185],
        [ 0.27000135, 50.16334035]],
       ...
       [[ 1.00647459, 50.25958169],
        [ 0.79479121, 50.3010079 ],
        [ 0.67235022, 49.95042185]],
       [[ 0.79479121, 50.3010079 ],
        [ 0.6886783 , 50.25867683],
        [ 0.67235022, 49.95042185]]])
</code>```

Here, it's an array of shape (10, 3, 2) but it could as well be (5, 3, 2) or (18, 3, 2), you name it. In any case it's of shape (N, 3, 2).
I have another numpy array to_replace of shape (4, 2) but it could as well be (6, 2) or (7, 2), but always of shape (M, 2):

```<code>array([[ 1.08267406, 49.88690993],
       [ 1.1028248 , 50.01440407],
       [ 0.74114309, 49.73183549],
       [ 1.08267406, 49.88690993]])
</code>```

It represents the locations of pairs of coordinates that can be found in my first array. Note that each of these pairs is present at least once in xy but could be present more than once.
Finally, I have a third array replace_by of which shape (8,) (or of shape (M*2) based on the indication above) and which values are meant to replace exactly those contained in to_replace in my first xy array. It looks like this:

```<code>array([ 0.87751214, 49.91866589,  0.88758751, 49.98241296,  0.70674665, 49.84112867,  0.87751214, 49.91866589])
</code>```

So basically all pairs [1.08267406, 49.88690993] in xy should be replaced by [0.87751214, 49.91866589] for example.

My current code looks like this but it works only if to_replace and replace_by are strictly of shape (2, 2).

```<code>indices = (xy == to_replace[:, None][:, None])[0]
xy[indices] = replace_by
</code>```

I already looked at a number of answers and actually got inspired by some of them but I still can't get it to work.

Body:
I have the following xy numpy array which represents the locations of the vertices of some triangles:

array([[[ 0.30539728, 49.82845203],
        [ 0.67235022, 49.95042185],
        [ 0.268982  , 49.95195348]],
       [[ 0.268982  , 49.95195348],
        [ 0.67235022, 49.95042185],
        [ 0.27000135, 50.16334035]],
       ...
       [[ 1.00647459, 50.25958169],
        [ 0.79479121, 50.3010079 ],
        [ 0.67235022, 49.95042185]],
       [[ 0.79479121, 50.3010079 ],
        [ 0.6886783 , 50.25867683],
        [ 0.67235022, 49.95042185]]])

Here, it's an array of shape (10, 3, 2) but it could as well be (5, 3, 2) or (18, 3, 2), you name it. In any case it's of shape (N, 3, 2).
I have another numpy array to_replace of shape (4, 2) but it could as well be (6, 2) or (7, 2), but always of shape (M, 2):

array([[ 1.08267406, 49.88690993],
       [ 1.1028248 , 50.01440407],
       [ 0.74114309, 49.73183549],
       [ 1.08267406, 49.88690993]])

It represents the locations of pairs of coordinates that can be found in my first array. Note that each of these pairs is present at least once in xy but could be present more than once.
Finally, I have a third array replace_by of which shape (8,) (or of shape (M*2) based on the indication above) and which values are meant to replace exactly those contained in to_replace in my first xy array. It looks like this:

array([ 0.87751214, 49.91866589,  0.88758751, 49.98241296,  0.70674665, 49.84112867,  0.87751214, 49.91866589])

So basically all pairs [1.08267406, 49.88690993] in xy should be replaced by [0.87751214, 49.91866589] for example.

My current code looks like this but it works only if to_replace and replace_by are strictly of shape (2, 2).

indices = (xy == to_replace[:, None][:, None])[0]
xy[indices] = replace_by

I already looked at a number of answers and actually got inspired by some of them but I still can't get it to work.

Body:
You can use numpy.isclose to compare rows and then use .all(axis=2) to find where all last rows are the same. Numpy will broadcast each row to fit xy shape.

import numpy as np
xy = np.array([[[ 0.30539728, 49.82845203],
        [ 0.67235022, 49.95042185],
        [ 0.268982  , 49.95195348]],
       [[ 0.268982  , 49.95195348],
        [ 0.67235022, 49.95042185],
        [ 0.27000135, 50.16334035]],
       [[ 1.00647459, 50.25958169],
        [ 0.79479121, 50.3010079 ],
        [ 0.67235022, 49.95042185]],
       [[ 0.79479121, 50.3010079 ],
        [ 0.6886783 , 50.25867683],
        [ 0.67235022, 49.95042185]]])
xy_start = xy.copy()

to_replace = np.array([[ 1.08267406, 49.88690993],
       [ 1.1028248 , 50.01440407],
       # [ 0.74114309, 49.73183549],
       [ 0.6886783 , 50.25867683],
       [ 1.08267406, 49.88690993]])

replace_by = np.array([ 0.87751214, 49.91866589,  0.88758751, 49.98241296,  0.70674665, 49.84112867,  0.87751214, 49.91866589])
replace_by_reshaped = replace_by.reshape(-1, 2)

for i, row in enumerate(to_replace):
    xy[np.isclose(xy, row).all(axis=2)] = replace_by_reshaped[i]
print(xy_start)
# [[[ 0.30539728 49.82845203]
#   [ 0.67235022 49.95042185]
#   [ 0.268982   49.95195348]]

#  [[ 0.268982   49.95195348]
#   [ 0.67235022 49.95042185]
#   [ 0.27000135 50.16334035]]

#  [[ 1.00647459 50.25958169]
#   [ 0.79479121 50.3010079 ]
#   [ 0.67235022 49.95042185]]

#  [[ 0.79479121 50.3010079 ]
#   [ 0.6886783  50.25867683]
#   [ 0.67235022 49.95042185]]]
print(xy)
# [[[ 0.30539728 49.82845203]
#   [ 0.67235022 49.95042185]
#   [ 0.268982   49.95195348]]

#  [[ 0.268982   49.95195348]
#   [ 0.67235022 49.95042185]
#   [ 0.27000135 50.16334035]]

#  [[ 1.00647459 50.25958169]
#   [ 0.79479121 50.3010079 ]
#   [ 0.67235022 49.95042185]]

#  [[ 0.79479121 50.3010079 ]
#   [ 0.70674665 49.84112867]
#   [ 0.67235022 49.95042185]]]

EDIT

.all(axis=2) shrink axis=2 to True if all values along axis=2 are True and False else. I think little 2d example made it clear what is happening here.

>>> import numpy as np
>>> a = np.array([[0, 1], [0, 2], [3, 4]])
>>> a
array([[0, 1],
       [0, 2],
       [3, 4]])
>>> np.isclose(a, [0, 1])
array([[ True,  True],
       [ True, False],
       [False, False]])
>>> np.isclose(a, [0, 1]).all(axis=1)
array([ True, False, False])
>>> a[np.isclose(a, [0, 1]).all(axis=1)]
array([[0, 1]])
>>> a[np.isclose(a, [0, 1]).all(axis=1)] = [12, 14]
>>> a
array([[12, 14],
       [ 0,  2],
       [ 3,  4]])


问:
bit data type returns -1
I am working on a web application in Visual Studio 2010. I am writing and reading to a database table using SQL Server 2008.

I have a database table, myTable with a column myColumn of datatype bit. I write to this column on the web app like so:

```<code>UPDATE myTable
SET myColumn = 1
</code>```

This works fine, and using SQL Server Management Studio I can see the column gets updated to TRUE as I would expect.

In another part of my web app I query the table like so:

```<code>sqlCmd.CommandText = "SELECT myColumn FROM myTable"

sqlRdr = sqlCmd.ExecuteReader()

While sqlRdr.Read
      myColumn = sqlRdr(0)
End While
</code>```

When I run this query, myColumn gets set to -1. How does this happen? According to Microsoft Documentation a bit is

An integer data type that can take a value of 1, 0, or NULL.

and

The string values TRUE and FALSE can be converted to bit values: TRUE is converted to 1 and FALSE is converted to 0.

I do not understand how I am getting myColumn = -1 from this query.

答:
When you get the data for a bit column, you are actually getting a 32-bit number, not just a single bit. In that 32-bit number, either EVERY bit is set to 1 or every bit is set to 0. The value 11111111 11111111 11111111 11111111 when converted to an Integer using two's complement is -1, because the first bit is the sign bit.

The problem is that you should not be using Integer in your VB code. The ONLY time you should be using 1 or 0 to represent this data is literal values in SQL code. In your VB code, you should be using Boolean to represent this data because that what the data is. 1 represents True and 0 represents False and you will see that if you view the data in SQL Server Management Studio.

That means that here:

sqlCmd.CommandText = "SELECT myColumn FROM myTable"

sqlRdr = sqlCmd.ExecuteReader()

While sqlRdr.Read
      myColumn = sqlRdr(0)
End While
```

<p>that <code>myColumn</code> variable should be type <code>Boolean</code>. That code should not compile at all anyway because it requires <code>Option Strict Off</code> and you should pretty much always have <code>Option Strict On</code>. You should not be assigning the <code>Object</code> reference you get from the data reader to a variable of type <code>Integer</code> or <code>Boolean</code>. You should use the data reader to get the data as it's actual type. If you really were getting an <code>Integer</code>:</p>

<pre class="lang-vb prettyprint-override"><code>myColumn = sqlRdr.GetInt32(0)
</code>```

but, as you will doing it properly and using Boolean:

myColumn = sqlRdr.GetBoolean(0)
```

<p>If you ever wanted to save data then you would generally be using parameters, e.g.</p>

<pre class="lang-vb prettyprint-override"><code>sqlCmd.CommandText = "UPDATE myTable SET myColumn = @myColumn"
sqlCmd.Parameters.Add("@myColumn", SqlDbType.Bit).Value = True
sqlCmd.ExecuteNonQuery()
</code>```

Title: bit data type returns -1

Body:
I am working on a web application in Visual Studio 2010. I am writing and reading to a database table using SQL Server 2008.

I have a database table, myTable with a column myColumn of datatype bit. I write to this column on the web app like so:

UPDATE myTable
SET myColumn = 1

This works fine, and using SQL Server Management Studio I can see the column gets updated to TRUE as I would expect.

In another part of my web app I query the table like so:

sqlCmd.CommandText = "SELECT myColumn FROM myTable"

sqlRdr = sqlCmd.ExecuteReader()

While sqlRdr.Read
      myColumn = sqlRdr(0)
End While

When I run this query, myColumn gets set to -1. How does this happen? According to Microsoft Documentation a bit is

An integer data type that can take a value of 1, 0, or NULL.

and

The string values TRUE and FALSE can be converted to bit values: TRUE is converted to 1 and FALSE is converted to 0.

I do not understand how I am getting myColumn = -1 from this query.

Body:
When you get the data for a bit column, you are actually getting a 32-bit number, not just a single bit. In that 32-bit number, either EVERY bit is set to 1 or every bit is set to 0. The value 11111111 11111111 11111111 11111111 when converted to an Integer using two's complement is -1, because the first bit is the sign bit.

The problem is that you should not be using Integer in your VB code. The ONLY time you should be using 1 or 0 to represent this data is literal values in SQL code. In your VB code, you should be using Boolean to represent this data because that what the data is. 1 represents True and 0 represents False and you will see that if you view the data in SQL Server Management Studio.

That means that here:

sqlCmd.CommandText = "SELECT myColumn FROM myTable"

sqlRdr = sqlCmd.ExecuteReader()

While sqlRdr.Read
      myColumn = sqlRdr(0)
End While

that myColumn variable should be type Boolean. That code should not compile at all anyway because it requires Option Strict Off and you should pretty much always have Option Strict On. You should not be assigning the Object reference you get from the data reader to a variable of type Integer or Boolean. You should use the data reader to get the data as it's actual type. If you really were getting an Integer:

myColumn = sqlRdr.GetInt32(0)

but, as you will doing it properly and using Boolean:

myColumn = sqlRdr.GetBoolean(0)

If you ever wanted to save data then you would generally be using parameters, e.g.

sqlCmd.CommandText = "UPDATE myTable SET myColumn = @myColumn"
sqlCmd.Parameters.Add("@myColumn", SqlDbType.Bit).Value = True
sqlCmd.ExecuteNonQuery()


问:
factor many mutated variables in one fell swoop
If I have 20 variables I've already recoded, why can't I pipe the mutate() into as_factor()? I don't get an error but it just doesn't do any leveling.

I can do it one by one
df$Ethnicity %<>% as_factor()

but I can't do:

```<code>df %<>%
     mutate(
      Gender = case_when(
      Q4 == 1 ~ "Male",
      Q4 == 2 ~ "Female",
      TRUE ~ as.character("Other")),

      Education = case_when(
        Education_n %in% c(1:4) ~ "Low",
        Education_n %in% c(5:8) ~ "Medium",
        Education_n %in% c(9:11) ~ "High",
        TRUE ~ NA_character_)) %>%
as_factor()
</code>```

I've tried it as_factor(.) too, to no avail. Do I really have to manually wrap every case_when in factor()? I have twenty variables, I'd like to avoid a solution that requires writing each one out into a purr:: function or repeating wrapping factor() twenty times.

答:
If you don't want to convert each column to factor you can use across to turn range of columns to factor.

```<code>df %<>%
   mutate(
     Gender = case_when(
            Q4 == 1 ~ "Male",
            Q4 == 2 ~ "Female",
            TRUE ~ as.character("Other")),

     Education = case_when(
        Education_n %in% c(1:4) ~ "Low",
        Education_n %in% c(5:8) ~ "Medium",
        Education_n %in% c(9:11) ~ "High",
        TRUE ~ NA_character_)) %>%
    mutate(across(Gender:Education, as_factor))
</code>```

If you have an older version of dplyr use mutate_at :

```<code>mutate_at(vars(Gender:Education), as_factor)
</code>```

Body:
If I have 20 variables I've already recoded, why can't I pipe the mutate() into as_factor()? I don't get an error but it just doesn't do any leveling.

I can do it one by one
df$Ethnicity %<>% as_factor()

but I can't do:

df %<>%
     mutate(
      Gender = case_when(
      Q4 == 1 ~ "Male",
      Q4 == 2 ~ "Female",
      TRUE ~ as.character("Other")),

      Education = case_when(
        Education_n %in% c(1:4) ~ "Low",
        Education_n %in% c(5:8) ~ "Medium",
        Education_n %in% c(9:11) ~ "High",
        TRUE ~ NA_character_)) %>%
as_factor()

I've tried it as_factor(.) too, to no avail. Do I really have to manually wrap every case_when in factor()? I have twenty variables, I'd like to avoid a solution that requires writing each one out into a purr:: function or repeating wrapping factor() twenty times.

Body:
If you don't want to convert each column to factor you can use across to turn range of columns to factor.

df %<>%
   mutate(
     Gender = case_when(
            Q4 == 1 ~ "Male",
            Q4 == 2 ~ "Female",
            TRUE ~ as.character("Other")),

     Education = case_when(
        Education_n %in% c(1:4) ~ "Low",
        Education_n %in% c(5:8) ~ "Medium",
        Education_n %in% c(9:11) ~ "High",
        TRUE ~ NA_character_)) %>%
    mutate(across(Gender:Education, as_factor))

If you have an older version of dplyr use mutate_at :

mutate_at(vars(Gender:Education), as_factor)


问:
Is SproutCore suitable for mobile app development?
by using it with something like PhoneGap, ...</p>

答: Yes. See for example SproutCore and PhoneGap.</p>


问:
Dynamically adding to a image search in html
I am trying to add profile pictures for an NHL stats website I am currently working on and I wondering how to dynamically change the link address for an image search. here is my script to append it to the body at this time. I do not know how to join the link plus the player id ({{p1_ID}}) and add the .png at the end</p>

```<code><script>
var imgPath = 'https://nhl.bamcontent.com/images/headshots/current/168x168/';
var image = document.createElement('img');
var player_ID = document.getElementById("p1");
image.src =  imgPath + player_ID + '.png';
document.body.appendChild(image);
</script>
<p id="p1">{{p1_ID}}</p>
</code>```

答:
Is there any reason why you can't implement the following (or something along these lines):

```<code><p id="p1">{{p1_ID}}</p>
<img src="https://nhl.bamcontent.com/images/headshots/current/168x168/{{p1_ID}}.png" />
</code>```

I don't know what templating engine you're using so that may not work, but if you provide more detail it would help.

Body:
I am trying to add profile pictures for an NHL stats website I am currently working on and I wondering how to dynamically change the link address for an image search. here is my script to append it to the body at this time. I do not know how to join the link plus the player id ({{p1_ID}}) and add the .png at the end

{{p1_ID}}

Body:
Is there any reason why you can't implement the following (or something along these lines):

<p id="p1">{{p1_ID}}</p>
<img src="https://nhl.bamcontent.com/images/headshots/current/168x168/{{p1_ID}}.png" />

I don't know what templating engine you're using so that may not work, but if you provide more detail it would help.


问:
Run Api code after killed the App iOS flutter -Background fatch- plugins
after run the simulate Background fetch I see That in the log.
I tested using. real device iPhone 8 - iOS 13.4.1
I waited two days nothing happened.

The log:

```<code>2020-05-29 18:05:53.515643+0300 Runner[372:40553] [TSBackgroundFetch scheduleProcessingTask]
2020-05-29 18:05:53.523393+0300 Runner[372:40553] [TSBackgroundFetch finish] flutter_background_fetch (2 of 2)
-[BackgroundTaskManager startPreventSuspendTimer:] BG time remaining: 20 | Total tasks: 1
2020-05-29 18:05:54.032876+0300 Runner[372:40857] -[BackgroundTaskManager startPreventSuspendTimer:] BG time remaining: 20 | Total tasks: 1
-[TSLocationManager onSuspend:] enabled? 1)
</code>```

答:
If the user kills your app, nothing further will happen in the background.  I take "kill" to mean a hard, force quit.  Merely hitting the Home button sends your app to the background.

Can't you just send you a note when the appDelegate receives a "applicationWillTerminate" or a "applicationWillResignActive"?

Body:
after run the simulate Background fetch I see That in the log.
I tested using. real device iPhone 8 - iOS 13.4.1
I waited two days nothing happened.

The log:

2020-05-29 18:05:53.515643+0300 Runner[372:40553] [TSBackgroundFetch scheduleProcessingTask]
2020-05-29 18:05:53.523393+0300 Runner[372:40553] [TSBackgroundFetch finish] flutter_background_fetch (2 of 2)
-[BackgroundTaskManager startPreventSuspendTimer:] BG time remaining: 20 | Total tasks: 1
2020-05-29 18:05:54.032876+0300 Runner[372:40857] -[BackgroundTaskManager startPreventSuspendTimer:] BG time remaining: 20 | Total tasks: 1
-[TSLocationManager onSuspend:] enabled? 1)


问:
Is there a way to go to specific line or command in python?
I am going through book automate boring stuff with python and trying to solve the practical problems.
In this project I need to define collatz() function and print results as seen in code until it gets 1.
So basically i need to input only one number and program should return numbers until it returns 1.
Program works fine but i have one question if i can make it better :D .

My question is after using try: and except: is there a way to not end process when typing string in input function but to get message below 'You must enter number' and get back to inputing new number or string and executing while loop normally. Code works fine just wondering if this is possible and if so how?

```<code>def collatz(number):
    if number % 2 == 0:
        print(number // 2)
        return number // 2
    else:
        print(3 * number + 1)
        return 3 * number + 1

try:
    yourNumber = int(input('Enter number: '))
    while True:
        yourNumber = collatz(yourNumber)
        if yourNumber == 1:
            break

except ValueError:
    print('You must enter a number')
</code>```

答:
Put the try/except inside a loop, such that on the except the loop will continue but on a success it will break:

```<code>while True:
    try:
        yourNumber = int(input('Enter number: '))
    except ValueError:
        print('You must enter a number')
    else:
        break

while yourNumber != 1:
    yourNumber = collatz(yourNumber)
</code>```

Body:
I am going through book automate boring stuff with python and trying to solve the practical problems.
In this project I need to define collatz() function and print results as seen in code until it gets 1.
So basically i need to input only one number and program should return numbers until it returns 1.
Program works fine but i have one question if i can make it better :D .

My question is after using try: and except: is there a way to not end process when typing string in input function but to get message below 'You must enter number' and get back to inputing new number or string and executing while loop normally. Code works fine just wondering if this is possible and if so how?

def collatz(number):
    if number % 2 == 0:
        print(number // 2)
        return number // 2
    else:
        print(3 * number + 1)
        return 3 * number + 1

try:
    yourNumber = int(input('Enter number: '))
    while True:
        yourNumber = collatz(yourNumber)
        if yourNumber == 1:
            break

except ValueError:
    print('You must enter a number')

Body:
Put the try/except inside a loop, such that on the except the loop will continue but on a success it will break:

while True:
    try:
        yourNumber = int(input('Enter number: '))
    except ValueError:
        print('You must enter a number')
    else:
        break

while yourNumber != 1:
    yourNumber = collatz(yourNumber)


问:
Docusign "Could Not load file or Assembly Restsharp" Error
I'm using Docusign in my (.netcore 3.1) project and I'm also using another nuget package which relies on minio.
Both seem to rely on Restsharp.

When I try to run my app I'm getting this error:

```<code>System.IO.FileLoadException: 'Could not load file or assembly 'RestSharp, Version=106.3.1.0, Culture=neutral, PublicKeyToken=598062e77f915f75'. The located assembly's manifest definition does not match the assembly reference. (0x80131040)'
</code>```

Docusign Version: 4.4.1

This is a screenshot of the dependencies as viewed from visual studio:

I've tried adding this binding redirect in App.Config:

```<code><configuration>
  <runtime>
    <dependentAssembly>
      <assemblyIdentity name="RestSharp" publicKeyToken="598062e77f915f75" culture="neutral" />
      <bindingRedirect oldVersion="0.0.0.0-106.3.1.0" newVersion="106.10.1" />
    </dependentAssembly>
  </runtime>
</configuration>
</code>```

This has had no impact whatsoever. Please can you help me. Any help very much appreciated! :)

答:
The 4.4.1 version of the C# SDK depends on the specific version of RestSharp.dll, it must use version 106.3.1.0. A later version would not work.
This is a known issue and would probably only get fixed in version 4.5.0, and I don't know when that version would be released at this time.
The only workaround is to find restsharp.dll version 106.3.1.0 and add it as a reference or put it in the same folder so that it can be loaded (was going to say put it in the GAC but you're using .NET Core).

Revision: actually, if you want to build your own version of DocuSign.eSign.dll, you can go to https://github.com/docusign/docusign-csharp-client and build the code yourself.

Body:
I'm using Docusign in my (.netcore 3.1) project and I'm also using another nuget package which relies on minio.
Both seem to rely on Restsharp.

When I try to run my app I'm getting this error:

System.IO.FileLoadException: 'Could not load file or assembly 'RestSharp, Version=106.3.1.0, Culture=neutral, PublicKeyToken=598062e77f915f75'. The located assembly's manifest definition does not match the assembly reference. (0x80131040)'

Docusign Version: 4.4.1

This is a screenshot of the dependencies as viewed from visual studio:

I've tried adding this binding redirect in App.Config:

<configuration>
  <runtime>
    <dependentAssembly>
      <assemblyIdentity name="RestSharp" publicKeyToken="598062e77f915f75" culture="neutral" />
      <bindingRedirect oldVersion="0.0.0.0-106.3.1.0" newVersion="106.10.1" />
    </dependentAssembly>
  </runtime>
</configuration>

This has had no impact whatsoever. Please can you help me. Any help very much appreciated! :)


问:
LinkButton in DataGrid, to trigger Multiple UpdatePanels
I have a datagrid which lists products and their market share - (dgProd).  That datagrid is in a DIV to provide scrolling.

Clicking on one of the product names shows two more div/datagrid combinations - one with a summary (dgSummary) and one with with the detail records (dgDetail).

The postback of the dgProd provides the information for dgSummary and dgDetail to know what product to show.  But the postback loses the location in dgProd.

I've tried putting dgSummary and dgDetail into UpdatePanels but I'm still getting the full postback.  I considered changing the product name LinkButton to run some javascript instead of the traditional postback, but then I don't see how the server will get the appropriate product to show in the other 2 grids.

Any recommendations?

答:
You could do this with jQuery.

Create a new ASP Page that contains your product detail and Product Summary

In the new ASp Page, Load the Summary Grid into a Div with id="Summary", Load the Detail into a Div with id="Detail"

Then, call your new Page with a jQuery.ajax(); call..

You can then load each of the "content" divs into placeholder divs in your main page using the #Summary, or #Detail method...

This is a good article to get you started and does demonstrate partial loading of remote content..

HTH.
Dave


问:
Determine if first & last characters in a string are vowels and return true if they match
This function is continually returning false. Anything i'm missing here?</p>

```<code>function regexVar() {
    var re = ""

    var last = re.length - 1
    var first = re[0]

    var match = (first === last) ? "true" : "false"

    if(match && (first == "a" ||
                first == 'e' ||
                first == 'i' ||
                first == 'o' ||
                first ==  'u')){
                console.log(true)
            } else {
                console.log(false)
            }
}
</code>```

答: You have set first to the first letter of the string but last is the index of the last letter, not the last letter itself. That means first will never === last. So match is always false.

Body:
This function is continually returning false. Anything i'm missing here?

function regexVar() {
    var re = ""

    var last = re.length - 1
    var first = re[0]

    var match = (first === last) ? "true" : "false"

    if(match && (first == "a" ||
                first == 'e' ||
                first == 'i' ||
                first == 'o' ||
                first ==  'u')){
                console.log(true)
            } else {
                console.log(false)
            }
}


问:
How do install pywin32 on MAC OS
i get the following error

ERROR: Could not find a version that satisfies the requirement pywin32 (from versions: none)
ERROR: No matching distribution found for pywin32
WARNING: You are using pip version 20.1; however, version 20.1.1 is available.
You should consider upgrading via the '/Users/abc/Documents/Python /pycharmtest2/venv/bin/python -m pip install --upgrade pip' command.

答: pywin32 is a wrapper for Windows API calls, so you can't use it on MacOS </p>

Title: How do install pywin32 on MAC OS


问:
Last record per transaction
I am trying to select the last record per sales order.

My query is simple in SQL Server management.

```<code>SELECT *
FROM DOCSTATUS
</code>```

The problem is that this database has tens of thousands of records, as it tracks all SO steps.

```<code>ID    SO    SL      Status        Reason      Attach    Name   Name       Systemdate
22  951581  3     Processed       Customer      NULL    NULL    BW  2016-12-05 13:33:27.857
23  951581  3     Submitted       Customer      NULL    NULL    BW  2016-17-05 13:33:27.997
24  947318  1        Hold         Customer      NULL    NULL    bw  2016-12-05 13:54:27.173
25  947318  1   Invoices Submit   Customer      NULL    NULL    bw  2016-13-05 13:54:27.300
26  947318  1        Ship         Customer      NULL    NULL    bw  2016-14-05 13:54:27.440
</code>```

I would to see the most recent record per the SO

```<code> ID    SO    SL       Status          Reason      Attach    Name   Name       Systemdate
 23  951581  4       Submitted        Customer      NULL    NULL    BW  2016-17-05 13:33:27.997
 26  947318  1         Ship           Customer      NULL    NULL    bw  2016-14-05 13:54:27.440
</code>```

答:
An efficient method with the right index is a correlated subquery:

```<code>select t.*
from t
where t.systemdate = (select max(t2.systemdate) from t t2 where t2.so = t.so);
</code>```

The index is on (so, systemdate).

Title: Last record per transaction

Body:
I am trying to select the last record per sales order.

My query is simple in SQL Server management.

SELECT *
FROM DOCSTATUS

The problem is that this database has tens of thousands of records, as it tracks all SO steps.

ID    SO    SL      Status        Reason      Attach    Name   Name       Systemdate
22  951581  3     Processed       Customer      NULL    NULL    BW  2016-12-05 13:33:27.857
23  951581  3     Submitted       Customer      NULL    NULL    BW  2016-17-05 13:33:27.997
24  947318  1        Hold         Customer      NULL    NULL    bw  2016-12-05 13:54:27.173
25  947318  1   Invoices Submit   Customer      NULL    NULL    bw  2016-13-05 13:54:27.300
26  947318  1        Ship         Customer      NULL    NULL    bw  2016-14-05 13:54:27.440

I would to see the most recent record per the SO

 ID    SO    SL       Status          Reason      Attach    Name   Name       Systemdate
 23  951581  4       Submitted        Customer      NULL    NULL    BW  2016-17-05 13:33:27.997
 26  947318  1         Ship           Customer      NULL    NULL    bw  2016-14-05 13:54:27.440

Body:
An efficient method with the right index is a correlated subquery:

select t.*
from t
where t.systemdate = (select max(t2.systemdate) from t t2 where t2.so = t.so);

The index is on (so, systemdate).