问:
Drawing Bowling Pins (pyramid) with Recursion in Ada
I know this is pushing the good will of the community by presenting my least elaborate work expecting someone to come and save me but I simply have no choice with nothing to lose. I've gone through packets, files, types, flags and boxes the last few weeks but I haven't covered much of recursion. Especially not drawing with recursion. My exam is in roughly one week and I hope this is ample time to repeat and learn simple recursion tricks like that of drawing bowling pins or other patterns:

```<code>I I I I I
 I I I I
  I I I
   I I
    I
n = 5
</code>```

The problem I have with recursion is that I don't quite get it. How are you supposed to approach a problem like drawing pins like this using recursion?

The closest I've come is

```<code>I I I
I I
I
n = 3
</code>```

and that's using

THIS CODE NOW WORKS

```<code>with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure pyramidchaser is

   subtype X_Type is Integer range 0..30;
   X: X_Type;
   Indent : Integer := 0;

   procedure Numbergrabber (X : out Integer) is
   begin

      Put("Enter a number: ");
      Get(X);
      Skip_Line;
   end Numbergrabber;

   procedure PrintSpaces(I : in Integer) is
   begin
      if I in X_Type then
      Put(" ");
      else
     return;
      end if;

      PrintSpaces(I - 1);
   end Printspaces;

   procedure PrintPins(i, n: in Integer) is
   begin
      if i >= n then
     return;
      end if;

    Put('I');
    Put(' ');

    PrintPins(i + 1, n);
    end Printpins;

   function Pins (X, Indent: in Integer) return Integer is

      Printed : Integer;

   begin

      Printed:= 0;
      if X > 0 then
     PrintSpaces(Indent);
     PrintPins(0, X);
     New_Line;

     Printed := X + Pins(X - 1, Indent + 1);
      end if;
      return Printed;

   end Pins;

   Bowlingpins : Integer;

begin

   Numbergrabber(X);
   Bowlingpins:= Pins(X, Indent);

end pyramidchaser;

</code>```

but with that I throw in a sum I dont really need just to kick off the recursive part which I dont really know why I do except it seems to be needed to be there. I experimented with code from a completely different assignment, thats why it looks the way it does. I know mod 2 will grant me too many new lines but at least it was an approach to finding heights to the pyramid. I understand the real approach is something similar to N+1 as with each step of the growing pyramid a new line is needed, but I dont know how to implement it.

I don't expect anyone to present a complete code but I hope somebody can clue me in on how to think on the way towards finding a solution.

I can still pass the exam without knowing recursion as its typically 2 assignments where one is and one isnt recursion and you need to pass one or the other, but given that I have some time I thought Id give it a chance.

As always, immensely thankful for anyone fighting the good fight!

Seeing this post gathered some attention Id like to expand the pyramid to one a little more complex:

THE PYRAMID PROBLEM 2

hope someone looks at it. I didnt expect so many good answers, I thought why not throw all I have out there.

```<code>Level 1
|=|

Level 2
|===|
||=||
|===|

Level 3

|=====|
||===||
|||=|||
||===||
|=====|

it needs to be figured out recursively. so some way it has to build both upwards and downwards from the center.
</code>```

To clarify Im studying for an exam and surely so are many others whom would be thankful for code to sink their teeth in. Maybe theres an easy way to apply what Tama built in terms of bowling pin lines in pyramid walls?

答:
A variation of this program is to use both head recursion and tail recursion in the same procedure.
The output of such a program is

```<code>Enter the number of rows in the pyramid: 5
I I I I I
 I I I I
  I I I
   I I
    I
    I
   I I
  I I I
 I I I I
I I I I I

N = 5
</code>```

Tail recursion produces the upper triangle and head recursion produces the lower triangle.

Body:
I know this is pushing the good will of the community by presenting my least elaborate work expecting someone to come and save me but I simply have no choice with nothing to lose. I've gone through packets, files, types, flags and boxes the last few weeks but I haven't covered much of recursion. Especially not drawing with recursion. My exam is in roughly one week and I hope this is ample time to repeat and learn simple recursion tricks like that of drawing bowling pins or other patterns:

I I I I I
 I I I I
  I I I
   I I
    I
n = 5

The problem I have with recursion is that I don't quite get it. How are you supposed to approach a problem like drawing pins like this using recursion?

The closest I've come is

I I I
I I
I
n = 3

and that's using

THIS CODE NOW WORKS

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure pyramidchaser is

   subtype X_Type is Integer range 0..30;
   X: X_Type;
   Indent : Integer := 0;

   procedure Numbergrabber (X : out Integer) is
   begin

      Put("Enter a number: ");
      Get(X);
      Skip_Line;
   end Numbergrabber;

   procedure PrintSpaces(I : in Integer) is
   begin
      if I in X_Type then
      Put(" ");
      else
     return;
      end if;

      PrintSpaces(I - 1);
   end Printspaces;

   procedure PrintPins(i, n: in Integer) is
   begin
      if i >= n then
     return;
      end if;

    Put('I');
    Put(' ');

    PrintPins(i + 1, n);
    end Printpins;

   function Pins (X, Indent: in Integer) return Integer is

      Printed : Integer;

   begin

      Printed:= 0;
      if X > 0 then
     PrintSpaces(Indent);
     PrintPins(0, X);
     New_Line;

     Printed := X + Pins(X - 1, Indent + 1);
      end if;
      return Printed;

   end Pins;

   Bowlingpins : Integer;

begin

   Numbergrabber(X);
   Bowlingpins:= Pins(X, Indent);

end pyramidchaser;

but with that I throw in a sum I dont really need just to kick off the recursive part which I dont really know why I do except it seems to be needed to be there. I experimented with code from a completely different assignment, thats why it looks the way it does. I know mod 2 will grant me too many new lines but at least it was an approach to finding heights to the pyramid. I understand the real approach is something similar to N+1 as with each step of the growing pyramid a new line is needed, but I dont know how to implement it.

I don't expect anyone to present a complete code but I hope somebody can clue me in on how to think on the way towards finding a solution.

I can still pass the exam without knowing recursion as its typically 2 assignments where one is and one isnt recursion and you need to pass one or the other, but given that I have some time I thought Id give it a chance.

As always, immensely thankful for anyone fighting the good fight!

Seeing this post gathered some attention Id like to expand the pyramid to one a little more complex:

THE PYRAMID PROBLEM 2

hope someone looks at it. I didnt expect so many good answers, I thought why not throw all I have out there.

Level 1
|=|

Level 2
|===|
||=||
|===|

Level 3

|=====|
||===||
|||=|||
||===||
|=====|

it needs to be figured out recursively. so some way it has to build both upwards and downwards from the center.

To clarify Im studying for an exam and surely so are many others whom would be thankful for code to sink their teeth in. Maybe theres an easy way to apply what Tama built in terms of bowling pin lines in pyramid walls?

Body:
A variation of this program is to use both head recursion and tail recursion in the same procedure.
The output of such a program is

Enter the number of rows in the pyramid: 5
I I I I I
 I I I I
  I I I
   I I
    I
    I
   I I
  I I I
 I I I I
I I I I I

N = 5

Tail recursion produces the upper triangle and head recursion produces the lower triangle.


来源: stackexchange

问:
Using Android NDK for encryption of data passed from normal android app
Is it possible and worth trying to develop some server application using android NDK which will encrypt data (or just use some built in Linux encryption library) passed to it from normal Java based application?

I tried using Cipher library, but it took almost a minute to encrypt 2MB file with AES. And blowfish is not available in Cipher until Android 2.3(?). And I doubt it will be much faster.

I was using blowfish for encryption on Symbian and it was much faster (under 5-10 seconds) so I think in android it is slower because of using Java virtual machine and I'd like to try native app for it.

Have someone done it before?

EDIT: Encrypting in NDK is so much faster. Do it there. There is a similar question with the same answer for AES: AES decryption on Android too slow to be usable. Will NDK be faster? Other ideas?

答: This is not open source but performance point of view Chillkat the best I found.</p>

ContentLicense: CC BY-SA 3.0


问:
ModuleNotFoundError with pytest
I want my tests folder separate to my application code. My project structure is like so

```<code>myproject/
  myproject/
    myproject.py
    moduleone.py
  tests/
    myproject_test.py
</code>```

myproject.py

```<code>from moduleone import ModuleOne

class MyProject(object)
....
</code>```

myproject_test.py

```<code>from myproject.myproject import MyProject
import pytest

...
</code>```

I use myproject.myproject since I use the command

```<code>python -m pytest
</code>```

from the project root directory ./myproject/

However, then the imports within those modules fail with

E   ModuleNotFoundError: No module named 'moduleone'

I am running Python 3.7 and have read that since 3.3, empty __init__ files are no longer needed which means my project becomes an implicit namespace package

However, I have tried adding an __init__.py file in myproject/myproject/ and also tried adding a conftest.py file in myproject/ but  neither works

I have read answers that say to mess with the paths and then upvoted comments in other questions saying not to.

What is the correct way and what am I missing?

EDIT;

Possibly related, I used a requirements.txt to install pytest using pip. Could this be related? And if so, what is the correct way to install pytest in this case?

EDIT 2:

One of the paths in sys.path is /usr/src/app/ which is a docker volume lined to /my/local/path/myproject/.

Should the volume be /my/local/path/myproject/myproject/ instead?

答:
I ran into this issue as well and am using poetry for dependency management and direnv for my project specific environment variables. Please note, I am relatively new to Python so I don't know if this is the correct fix.

Here is my entire .envrc file:

```<code>layout_poetry() {
  if [[ ! -f pyproject.toml ]]; then
    log_error 'No pyproject.toml found.  Use `poetry new` or `poetry init` to create one first.'
    exit 2
  fi

  local VENV=$(poetry env list --full-path | cut -d' ' -f1)
  if [[ -z $VENV || ! -d $VENV/bin ]]; then
    log_error 'No created poetry virtual environment found.  Use `poetry install` to create one first.'
    exit 2
  fi
  VENV=$VENV/bin
  export VIRTUAL_ENV=$(echo "$VENV" | rev | cut -d'/' -f2- | rev)
  export POETRY_ACTIVE=1
  PATH_add "$VENV"
}

layout poetry
export PYTHONDONTWRITEBYTECODE=1
export PYTHONPATH="$PWD/project_name"
</code>```

I don't know if I need to layout poetry because it is supposed to be creating virtual environments for us already but this is what I coworker recommended so I went with it. Layout poetry also didn't work without that function and it didn't like when I added it to my zshenv so I added it here.

For this specific question, the last line is the money maker.

ContentLicense: CC BY-SA 4.0

Title: ModuleNotFoundError with pytest

Body:
I want my tests folder separate to my application code. My project structure is like so

myproject/
  myproject/
    myproject.py
    moduleone.py
  tests/
    myproject_test.py

myproject.py

from moduleone import ModuleOne

class MyProject(object)
....

myproject_test.py

from myproject.myproject import MyProject
import pytest

...

I use myproject.myproject since I use the command

python -m pytest

from the project root directory ./myproject/

However, then the imports within those modules fail with

E   ModuleNotFoundError: No module named 'moduleone'

I am running Python 3.7 and have read that since 3.3, empty __init__ files are no longer needed which means my project becomes an implicit namespace package

However, I have tried adding an __init__.py file in myproject/myproject/ and also tried adding a conftest.py file in myproject/ but  neither works

I have read answers that say to mess with the paths and then upvoted comments in other questions saying not to.

What is the correct way and what am I missing?

EDIT;

Possibly related, I used a requirements.txt to install pytest using pip. Could this be related? And if so, what is the correct way to install pytest in this case?

EDIT 2:

One of the paths in sys.path is /usr/src/app/ which is a docker volume lined to /my/local/path/myproject/.

Should the volume be /my/local/path/myproject/myproject/ instead?

Body:
I ran into this issue as well and am using poetry for dependency management and direnv for my project specific environment variables. Please note, I am relatively new to Python so I don't know if this is the correct fix.

Here is my entire .envrc file:

layout_poetry() {
  if [[ ! -f pyproject.toml ]]; then
    log_error 'No pyproject.toml found.  Use `poetry new` or `poetry init` to create one first.'
    exit 2
  fi

  local VENV=$(poetry env list --full-path | cut -d' ' -f1)
  if [[ -z $VENV || ! -d $VENV/bin ]]; then
    log_error 'No created poetry virtual environment found.  Use `poetry install` to create one first.'
    exit 2
  fi
  VENV=$VENV/bin
  export VIRTUAL_ENV=$(echo "$VENV" | rev | cut -d'/' -f2- | rev)
  export POETRY_ACTIVE=1
  PATH_add "$VENV"
}

layout poetry
export PYTHONDONTWRITEBYTECODE=1
export PYTHONPATH="$PWD/project_name"

I don't know if I need to layout poetry because it is supposed to be creating virtual environments for us already but this is what I coworker recommended so I went with it. Layout poetry also didn't work without that function and it didn't like when I added it to my zshenv so I added it here.

For this specific question, the last line is the money maker.


问:
Why mongodb java driver uses random bytes instead of machine id in ObjectId?
Many people say that ObjectId consist of:

a 4-byte value representing the seconds since the Unix epoch (which will not run out of seconds until the year 2106)

a 3-byte machine identifier (usually derived from the MAC address),

a 2-byte process id, and

a 3-byte counter, starting with a random value.

And if the objectId contains all these elements then it's guaranteed that all ids are unique across the cluster. But the docs say that there're no machine and process ids and the objectId contains just a random value (https://docs.mongodb.com/manual/reference/method/ObjectId)

I looked in the java mongo driver ObjectId generation and found the evidence:

```<code>SecureRandom secureRandom = new SecureRandom();
RANDOM_VALUE1 = secureRandom.nextInt(0x01000000);
RANDOM_VALUE2 = (short) secureRandom.nextInt(0x00008000);

// ...

private ObjectId(final int timestamp, final int counter, final boolean checkCounter) {
    this(timestamp, RANDOM_VALUE1, RANDOM_VALUE2, counter, checkCounter);
}
</code>```

So, it's possible (ok, the probability is really low, but still) that two machines generate the same random numbers and all the consequently generated ids will have clashes very probably. Why such decision has been made? Is it still perfectly unique, but I don't understand something?
Thanks!

Edit: Well, the purpose of the question is: should I implement the retrieving of MAC address and processId and generate ObjectId by myself or leave random 5 bytes number, because there's no difference?

答:
Why mongodb java driver uses random bytes instead of machine id in ObjectId?

This behavior is mandated by the ObjectId specification.

The same document provides the rationale:

Random Value: Originally, this field consisted of the Machine ID and Process ID fields. There were numerous divergences between drivers due to implementation choices, and the Machine ID field traditionally used the MD5 hashing algorithm which can't be used on FIPS compliant machines. In order to allow for a similar behaviour among all drivers and the MongoDB Server, these two fields have been collated together into a single 5-byte random value, unique to a machine and process.

You should not need to implement ObjectId generation, as all MongoDB drivers necessarily need to provide this functionality.

Body:
Many people say that ObjectId consist of:

a 4-byte value representing the seconds since the Unix epoch (which will not run out of seconds until the year 2106)

a 3-byte machine identifier (usually derived from the MAC address),

a 2-byte process id, and

a 3-byte counter, starting with a random value.

And if the objectId contains all these elements then it's guaranteed that all ids are unique across the cluster. But the docs say that there're no machine and process ids and the objectId contains just a random value (https://docs.mongodb.com/manual/reference/method/ObjectId)

I looked in the java mongo driver ObjectId generation and found the evidence:

SecureRandom secureRandom = new SecureRandom();
RANDOM_VALUE1 = secureRandom.nextInt(0x01000000);
RANDOM_VALUE2 = (short) secureRandom.nextInt(0x00008000);

// ...

private ObjectId(final int timestamp, final int counter, final boolean checkCounter) {
    this(timestamp, RANDOM_VALUE1, RANDOM_VALUE2, counter, checkCounter);
}

So, it's possible (ok, the probability is really low, but still) that two machines generate the same random numbers and all the consequently generated ids will have clashes very probably. Why such decision has been made? Is it still perfectly unique, but I don't understand something?
Thanks!

Edit: Well, the purpose of the question is: should I implement the retrieving of MAC address and processId and generate ObjectId by myself or leave random 5 bytes number, because there's no difference?


问:
Issue in QLineEdit with title()?
In my Programme. use two QLineEdit. First one is normal and second one is titled Line edit. First one/normal QLineEidt  works smoothly,   But In second textbox(QLineEdit), I cannot insert a text at begging or any where at a time.

for example : I entered a text "Python". Now I add "Hello" to begging of the text ("Hello Python"). If I try to type "Hello", I can insert only one word at a time, (press home key, type word "H",after that cursor jumps to end, once again we move cursor to second position and enter a word "O", Once we enter word "O" cursor jumps to end of the text and so on). I want to type(insert) a text at a stretch.

How to OverCome?

```<code>import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QFont

class Lineedit_title(QWidget):
    def __init__(self):
        super().__init__()

        self.setGeometry(100,100,500,500)

        self.textbox1 = QLineEdit(self)
        self.textbox1.setGeometry(50,50,200,50)
        self.textbox1.setFont(QFont("Caliber", 15, QFont.Bold))

        self.textbox2 = QLineEdit(self)
        self.textbox2.setGeometry(50,140,200,50)
        self.textbox2.setFont(QFont("Caliber",15,QFont.Bold))
        self.textbox2.textChanged.connect(self.textbox_textchange)

    def textbox_textchange(self,txt):
        self.textbox2.setText(txt.title())

def main():
    app = QApplication(sys.argv)
    win = Lineedit_title()
    win.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()
</code>```

答:
The problem is that when you use setText() the cursor position is set at the end of the text, in this case the cursor position must be saved and restored before and after setText(), respectively:

```<code>def textbox_textchange(self, txt):
    <b>position = self.textbox2.cursorPosition()</b>
    self.textbox2.setText(txt.title())
    <b>self.textbox2.setCursorPosition(position)</b></code>```

A more elegant solution is to use a custom validator:

```<code>import sys
from PyQt5.QtWidgets import QApplication, QLineEdit, QWidget
from PyQt5.QtGui import QFont, QValidator

class TitleValidator(QValidator):
    def validate(self, text, pos):
        return QValidator.Acceptable, text.title(), pos

class Lineedit_title(QWidget):
    def __init__(self):
        super().__init__()

        self.setGeometry(100, 100, 500, 500)

        self.textbox1 = QLineEdit(self)
        self.textbox1.setGeometry(50, 50, 200, 50)
        self.textbox1.setFont(QFont("Caliber", 15, QFont.Bold))

        self.textbox2 = QLineEdit(self)
        self.textbox2.setGeometry(50, 140, 200, 50)
        self.textbox2.setFont(QFont("Caliber", 15, QFont.Bold))

        validator = TitleValidator(self.textbox2)
        self.textbox2.setValidator(validator)

def main():
    app = QApplication(sys.argv)
    win = Lineedit_title()
    win.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()
</code>```

Title: Issue in QLineEdit with title()?

Body:
In my Programme. use two QLineEdit. First one is normal and second one is titled Line edit. First one/normal QLineEidt  works smoothly,   But In second textbox(QLineEdit), I cannot insert a text at begging or any where at a time.

for example : I entered a text "Python". Now I add "Hello" to begging of the text ("Hello Python"). If I try to type "Hello", I can insert only one word at a time, (press home key, type word "H",after that cursor jumps to end, once again we move cursor to second position and enter a word "O", Once we enter word "O" cursor jumps to end of the text and so on). I want to type(insert) a text at a stretch.

How to OverCome?

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QFont

class Lineedit_title(QWidget):
    def __init__(self):
        super().__init__()

        self.setGeometry(100,100,500,500)

        self.textbox1 = QLineEdit(self)
        self.textbox1.setGeometry(50,50,200,50)
        self.textbox1.setFont(QFont("Caliber", 15, QFont.Bold))

        self.textbox2 = QLineEdit(self)
        self.textbox2.setGeometry(50,140,200,50)
        self.textbox2.setFont(QFont("Caliber",15,QFont.Bold))
        self.textbox2.textChanged.connect(self.textbox_textchange)

    def textbox_textchange(self,txt):
        self.textbox2.setText(txt.title())

def main():
    app = QApplication(sys.argv)
    win = Lineedit_title()
    win.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

Body:
The problem is that when you use setText() the cursor position is set at the end of the text, in this case the cursor position must be saved and restored before and after setText(), respectively:

def textbox_textchange(self, txt):
    position = self.textbox2.cursorPosition()
    self.textbox2.setText(txt.title())
    self.textbox2.setCursorPosition(position)

A more elegant solution is to use a custom validator:

import sys
from PyQt5.QtWidgets import QApplication, QLineEdit, QWidget
from PyQt5.QtGui import QFont, QValidator

class TitleValidator(QValidator):
    def validate(self, text, pos):
        return QValidator.Acceptable, text.title(), pos

class Lineedit_title(QWidget):
    def __init__(self):
        super().__init__()

        self.setGeometry(100, 100, 500, 500)

        self.textbox1 = QLineEdit(self)
        self.textbox1.setGeometry(50, 50, 200, 50)
        self.textbox1.setFont(QFont("Caliber", 15, QFont.Bold))

        self.textbox2 = QLineEdit(self)
        self.textbox2.setGeometry(50, 140, 200, 50)
        self.textbox2.setFont(QFont("Caliber", 15, QFont.Bold))

        validator = TitleValidator(self.textbox2)
        self.textbox2.setValidator(validator)

def main():
    app = QApplication(sys.argv)
    win = Lineedit_title()
    win.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()


问:
Get nested inner content value of each div using jQuery
I am trying to get selected values of all the radio buttons and if one is not selected, then null value.
Here is my HTML code:

```<code><div class="question m-2">
    <div class="question-title">Question 1</div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="a" name="q-1">Option a
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="b" name="q-1">Option b
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="c" name="q-1">Option c
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="d" name="q-1">Option d
        </label>
    </div>
</div>
<div class="question m-2">
    <div class="question-title">Question 2</div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="a" name="q-2">Option a
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="b" name="q-2">Option b
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="c" name="q-2">Option c
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="d" name="q-2">Option d
        </label>
    </div>
</div>
<div class="question m-2">
    <div class="question-title">Question 3</div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="a" name="q-3">Option a
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="b" name="q-3">Option b
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="c" name="q-3">Option c
        </label>
    </div>
    <div class="form-check">
        <label class="form-check-label">
            <input type="radio" class="form-check-input" value="d" name="q-3">Option d
        </label>
    </div>
</div>
</code>```

I want to store all the answers of each question, if selected then the selected value, if not selected, then null value. Can anyone help me with jQuery code?

答:
You can get it with javascript as well

const questions = document.querySelectorAll('.question');
const answers = Array.from(questions).map(e => e.querySelector('input.form-
      check - input: checked ').value);```
</div>
</div>
</p>

<p>In JQuery</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const answers = $('.question input.form-check-input:checked').val();</code>```

Body:
I am trying to get selected values of all the radio buttons and if one is not selected, then null value.
Here is my HTML code:

Question 1

            <input type="radio" class="form-check-input" value="a" name="q-1">Option a

            <input type="radio" class="form-check-input" value="b" name="q-1">Option b

            <input type="radio" class="form-check-input" value="c" name="q-1">Option c

            <input type="radio" class="form-check-input" value="d" name="q-1">Option d

Question 2

            <input type="radio" class="form-check-input" value="a" name="q-2">Option a

            <input type="radio" class="form-check-input" value="b" name="q-2">Option b

            <input type="radio" class="form-check-input" value="c" name="q-2">Option c

            <input type="radio" class="form-check-input" value="d" name="q-2">Option d

Question 3

            <input type="radio" class="form-check-input" value="a" name="q-3">Option a

            <input type="radio" class="form-check-input" value="b" name="q-3">Option b

            <input type="radio" class="form-check-input" value="c" name="q-3">Option c

            <input type="radio" class="form-check-input" value="d" name="q-3">Option d

I want to store all the answers of each question, if selected then the selected value, if not selected, then null value. Can anyone help me with jQuery code?

Body:
You can get it with javascript as well

const questions = document.querySelectorAll('.question');
const answers = Array.from(questions).map(e => e.querySelector('input.form-
      check - input: checked ').value);

In JQuery

const answers = $('.question input.form-check-input:checked').val();


问:
Is it possible to upload file via $.ajax(options) or xhr.send(file) only?
I'm using file api and xhr2 spec. I created an uploader (backed by flash for older browsers) that was using FormData and $.ajax(options) where the FormData object with File was part of options.data object. Everything was working.

Now I decided to remove FormData because of weak browser support. And I can't figure a way to upload the file other than

```<code>var xhr = new XMLHttpRequest();
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.send(file);
</code>```

Which doesn't return Promise that I can use in the recursion function.

My code is like this :

```<code>   startUpload: function() {
        var that = this;
        that.recurseSend(that.queue);
    },

    _initProgressListener: function (options, file) {
        var that = this;
        var xhr = $.ajaxSettings.xhr();
        options.contentType = 'multipart/form-data';
        options.processData = false;
        options.type = 'POST';
        // WHAT TO DO HERE TO avoid FormData???? What ever I put into options.data - fails

        /* THIS WOULD WORK
        var formData = new FormData();
        formData.append('file', file);
        options.data = formData;
        */

        if (xhr.upload && xhr.upload.addEventListener) {
            xhr.upload.addEventListener('progress', function (e) {
                that._onProgress(e, file);
            }, false);
            options.xhr = function () {
                return xhr;
            };
        }
    },

    recurseSend: function (queue) {
        var file = queue.pop();
        if(file != undefined) {
            var that = this;
            var options = that.options;
            that._initProgressListener(options, file);

            var send = function() {
                jqXHR = ($.ajax(options)).done(function(result, textStatus, jqXHR) {
                        that._onDone(result, textStatus, jqXHR, file);
                        queue.stats['successful_uploads']++;
                    }).fail(function(jqXHR, textStatus, errorThrown) {
                        that._onFail(jqXHR, textStatus, errorThrown, file);
                        queue.stats['upload_errors']++;
                    }).always(function(result, textStatus, jqXHR) {
                        that._onAlways(result, textStatus, jqXHR, file);
                        queue.stats['files_queued']--;
                        that.recurseSend(queue);
                    });
                    return jqXHR;
            };

            this._beforeSend(file);
            return send();
        }
    },
</code>```

To make it short, $.ajax(options) resolves into xhr.send(formData) if options.data = FormData but how do I make it resolve into xhr.send(file) ?

EDITED: I was playing with it and if I set options.data = file;  then $.ajax(options) executes xhr.send(theFile); but with error Error: INVALID_STATE_ERR: DOM Exception 11

and the request is sent as POST multipart/form-data request, but without the multipart body with file in it

And if I put it into  options.data = {file: file};  it is serialized no matter if processData property is set to true or not.

答:
I my self have used valums ajax uploader. You can get it from here:
http://valums.com/ajax-upload/. It works pretty nicely. I don't know the exact implementation details, but here's a very short description:

"This plugin uses XHR for uploading multiple files with progress-bar in FF3.6+, Safari4+, Chrome and falls back to hidden iframe based upload in other browsers, providing good user experience everywhere."

So it sounds like its very close to what you want. Here's another bit of info describing the way it works from the servers point of view (from server/readme.txt):

For IE6-8, Opera, older versions of other browsers you get the file as
you normally do with regular form-base uploads.

For browsers which upload file with progress bar, you will need to get the raw
post data and write it to the file.

So it requires special handling on the server side. Luckily it comes with several reference server side implementations (perl, php and java) so that shouldn't be too much of hassle. Happy ajax uploading :)

Body:
I'm using file api and xhr2 spec. I created an uploader (backed by flash for older browsers) that was using FormData and $.ajax(options) where the FormData object with File was part of options.data object. Everything was working.

Now I decided to remove FormData because of weak browser support. And I can't figure a way to upload the file other than

var xhr = new XMLHttpRequest();
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.send(file);

Which doesn't return Promise that I can use in the recursion function.

My code is like this :

   startUpload: function() {
        var that = this;
        that.recurseSend(that.queue);
    },

    _initProgressListener: function (options, file) {
        var that = this;
        var xhr = $.ajaxSettings.xhr();
        options.contentType = 'multipart/form-data';
        options.processData = false;
        options.type = 'POST';
        // WHAT TO DO HERE TO avoid FormData???? What ever I put into options.data - fails

        /* THIS WOULD WORK
        var formData = new FormData();
        formData.append('file', file);
        options.data = formData;
        */

        if (xhr.upload && xhr.upload.addEventListener) {
            xhr.upload.addEventListener('progress', function (e) {
                that._onProgress(e, file);
            }, false);
            options.xhr = function () {
                return xhr;
            };
        }
    },

    recurseSend: function (queue) {
        var file = queue.pop();
        if(file != undefined) {
            var that = this;
            var options = that.options;
            that._initProgressListener(options, file);

            var send = function() {
                jqXHR = ($.ajax(options)).done(function(result, textStatus, jqXHR) {
                        that._onDone(result, textStatus, jqXHR, file);
                        queue.stats['successful_uploads']++;
                    }).fail(function(jqXHR, textStatus, errorThrown) {
                        that._onFail(jqXHR, textStatus, errorThrown, file);
                        queue.stats['upload_errors']++;
                    }).always(function(result, textStatus, jqXHR) {
                        that._onAlways(result, textStatus, jqXHR, file);
                        queue.stats['files_queued']--;
                        that.recurseSend(queue);
                    });
                    return jqXHR;
            };

            this._beforeSend(file);
            return send();
        }
    },

To make it short, $.ajax(options) resolves into xhr.send(formData) if options.data = FormData but how do I make it resolve into xhr.send(file) ?

EDITED: I was playing with it and if I set options.data = file;  then $.ajax(options) executes xhr.send(theFile); but with error Error: INVALID_STATE_ERR: DOM Exception 11

and the request is sent as POST multipart/form-data request, but without the multipart body with file in it

And if I put it into  options.data = {file: file};  it is serialized no matter if processData property is set to true or not.


问:
Why can't I run phpinfo() in my docker container?
I am trying to get a connection between my php-fpm docker container and an RDS Postregsql. I found that I was getting an error in my php application "call to undefined function pg_connect()". So I thought that maybe the issue was that I didn't have pgsql driver enabled in my php.ini. So I tried to enable it, by first adding a line to my Dockerfile, rebuilding the image, then I brought down the container and brought it up again. But I am getting the same error "call to undefined function pg_connect(). So I'd like to run phpinfo() in the container to see if the pgsql driver is loaded. I tried to run it by using docker exec 4822 /bin/bash to open a cli to the container, but the host cli just comes back with a $. How can I run phpinfo() in the container so I can figure out why $DB2 = $this->load->database('postgres', TRUE) is failing with the above error? I am using Codeigniter and here is the connection array:

```<code>enter code here

enter code here
</code>```

Sorry I can't get the format going. Anyway, here is the dsn
'dsn' => 'jdbc:postgresql://imagesdatabase.cwymdn16cxes.us-east-1.rds.amazonaws.com:5432/postgres'

答:
Follow this https://www.php.net/manual/en/features.commandline.interactive.php

This will help you, how to use interactive command line PHP.

If DockerImage is based on PHP or has PHP installed in docker container then you can use this feature. What you need to do in docker terminal is run following command

```<code>$ php -a
Interactive shell

php > echo 5+8;
13
</code>```

Body:
I am trying to get a connection between my php-fpm docker container and an RDS Postregsql. I found that I was getting an error in my php application "call to undefined function pg_connect()". So I thought that maybe the issue was that I didn't have pgsql driver enabled in my php.ini. So I tried to enable it, by first adding a line to my Dockerfile, rebuilding the image, then I brought down the container and brought it up again. But I am getting the same error "call to undefined function pg_connect(). So I'd like to run phpinfo() in the container to see if the pgsql driver is loaded. I tried to run it by using docker exec 4822 /bin/bash to open a cli to the container, but the host cli just comes back with a $. How can I run phpinfo() in the container so I can figure out why $DB2 = $this->load->database('postgres', TRUE) is failing with the above error? I am using Codeigniter and here is the connection array:

enter code here

enter code here

Sorry I can't get the format going. Anyway, here is the dsn
'dsn' => 'jdbc:postgresql://imagesdatabase.cwymdn16cxes.us-east-1.rds.amazonaws.com:5432/postgres'

Body:
Follow this https://www.php.net/manual/en/features.commandline.interactive.php

This will help you, how to use interactive command line PHP.

If DockerImage is based on PHP or has PHP installed in docker container then you can use this feature. What you need to do in docker terminal is run following command

$ php -a
Interactive shell

php > echo 5+8;
13


问:
Why isn't the answer to the "Egg Drop" Problem "no. of floors" or 2?
I've been attempting the "Egg Drop" Dynamic Programming problem however I'm really confused as to why the answer makes sense.

The problem is usually phrased like the follwoing (longer definitions here, here and here among many other places):

You have a number of floors you can drop an egg from. From some floors the egg will be fine when it hits the ground and from others it will break.

Given a certain number of eggs and a certain number of floors what is the minimum number of drops needed to find the threshold floor (the first floor where the egg will break

Apparently the answer to this a of search of the problem space that enumerates out all possibilites and finds the worst case scenario.

This is definitely a case of me not understanding the question, but why is this the answer? To my mind the answer is one of two things:

If you have 1 egg then it's however many floors you have as you potentially need to drop it from all of the floors (starting from 1). The first one it breaks at is the 'threshold' and this would confirm an answer for you because you know for a fact that every floor beneath it is 'safe'

If you have n eggs then isn't the answer 2: you drop it and it breaks, then you drop it on the floor below and it doesn't.

Obviously the n eggs answer requires you to get lucky with both drops, but the question is asking for the minimum number of drops needed to find the threshold i.e. the smallest possible number of drops needed to find the answer and confirm it. If you happened to go down this golden path then isn't that answer 2?

As I said, I'm clearly misunderstanding something about the question here - would someone be able to help?

Thanks!

答:
You are indeed misinterpreting the question. When it says:

what is the minimum number of drops needed to find the threshold floor

It means that you must design an optimal strategy that you will apply. The strategy must define from which floor you will do the next drop, based on whether the previous drop broke the egg or not. So it is like a binary decision tree which you follow. Depending on the feedback you get from dropping eggs, you will move in a different direction in that decision tree.

Now you must find the worst case for your strategy: what would be the threshold floor that would take the most drops to find with that strategy?

There are a multitude of strategies. Some of these will need more drops in their worst case scenario, than others. Your job is to find the strategy that minimises the number of drops it needs for its worst case, and to return that number.

Note that what constitutes a worst case for one scenario, might not be a worst case for another. Every strategy has its own worst case.

Be aware: the strategy must never allow you to get into a situations where you have no more eggs left, and still do not know with certainty which is the threshold floor.


问:
How do you post as a bot with a different avatar image and name?
There is a discord bot called Unbelivaboat. It has a command called !suggest <your suggestion>. When someone suggests something, the bot copies their message and posts it on a different channel. However, nickname and the avatar image is changed (see picture below). How did the bot do this?

When you click on the profile you get this only:

答:
The bots avatar can be canged using following code,

```<code>import discord
client = discord.Client()

token = 'TOKEN HERE'
pfp_path = "path/to/file.png"

fp = open(pfp_path, 'rb')
pfp = fp.read()

@client.event
async def on_ready():
    await client.edit_profile(password=None, avatar=pfp)

client.run(token)
</code>```

If you want a user to change the picture of a bot, you can give them the option to add their own path (for the picture), like here

```<code>import discord
from discord.exe import commands
bot = commands.Bot(command_prefix=';')

@bot.command()
   async def profile(ctx, path):
   token = 'TOKEN HERE'
   pfp_path = "path"

   fp = open(pfp_path, 'rb')
   pfp = fp.read()

@client.event
async def on_ready():
    await client.edit_profile(password=None, avatar=pfp)

client.run(token)
</code>```

With this setup, a user can run the command ;profile https://vlands.net/underconstruction.png and it will apply the picture that is located at this adress.

Body:
The bots avatar can be canged using following code,

import discord
client = discord.Client()

token = 'TOKEN HERE'
pfp_path = "path/to/file.png"

fp = open(pfp_path, 'rb')
pfp = fp.read()

@client.event
async def on_ready():
    await client.edit_profile(password=None, avatar=pfp)

client.run(token)

If you want a user to change the picture of a bot, you can give them the option to add their own path (for the picture), like here

import discord
from discord.exe import commands
bot = commands.Bot(command_prefix=';')

@bot.command()
   async def profile(ctx, path):
   token = 'TOKEN HERE'
   pfp_path = "path"

   fp = open(pfp_path, 'rb')
   pfp = fp.read()

@client.event
async def on_ready():
    await client.edit_profile(password=None, avatar=pfp)

client.run(token)

With this setup, a user can run the command ;profile https://vlands.net/underconstruction.png and it will apply the picture that is located at this adress.


问:
Best data store solution for small mathematical data but fast and with aggregate functions
I'm looking for a data storage solution for a project with these requirements:

The application creates dynamically
a containter/table in the store.

For a small period of time (two
weeks for example) that
table/container gets a huge amount
of inserts in parallel. Last read
have to be immediately available.

The data inserted is very small, 4
to 6 numeric columns.

Small query/filtering support is
required, but no joins or cross
queries.

Is needed to execute some aggregate
functions like "Count", "Sum",
"Max", "Min" and "Avg".

Basically, I need something like Windows Azure Table Storage but with aggregate functions.

What would you recommend?

答:
MongoDB is also a good choice. It supports group (aggregate) queries on single-node installation. If you need to scale you can create sharded cluster and use map/reduce for aggregation needs - but Mongo map/reduce performance isn't top level when comapring to other solutions.

If you need big performance in map/reduce you can take look at Hadoop


问:
(Python) manually copy/paste data from pandas table without copying the index
I've been looking around but could not find an similar post, so I thought I'd give it a go.
I wrote an pandas program that sucessfully displays the resulting dataframe in pandas table format in a tkinter textbox. the aim is that the user can select the data ancopy/paste it into an (existing)excel sheet. when doing this, the index is always copied as well. I was wondering if one could programmatically select the complete table except the index?
I know that one can save to excel or other with index=false, but I could not find a kind of df.select....index=false. I hope my explanation is more or less clear ;-)
Thanks a lot
screenshot</p>

答:
I finally found it.
Instead of using something like self.mytable.copy('columns') to select everything and then switch to Excel and paste it, I use this line of code which does exactly what I need :

```<code>df.to_clipboard(sep="\t", index=False)
</code>```

The sep="\t" makes it split up amongst columns in Excel.

Hopefully someone can use this at some stage.

Body:
I finally found it.
Instead of using something like self.mytable.copy('columns') to select everything and then switch to Excel and paste it, I use this line of code which does exactly what I need :

df.to_clipboard(sep="\t", index=False)

The sep="\t" makes it split up amongst columns in Excel.

Hopefully someone can use this at some stage.


问:
How to decrement items in array Incrementally based on the given quantity in Javascript
I have this sample array of objects

```<code>   mangoes:[
      { quantity:5},
      { quantity:8},
      { quantity:13},
      { quantity:4}
    ]
</code>```

When I remove x mangoes, that x should be subtracted from the first element in the array, and if that x exceed the first element then it should reduce the remained quantity in the second item in the array...and so forth.

This is to say, I need the quantity to be reduced starting from the first one in the array down to the second if it exceed, to the third etc..

For example, If I buy 2 mangoes, It should minus 2 in the first array element and the resulting mangoes array should be

```<code>   mangoes:[
      { quantity:3},
      { quantity:8},
      { quantity:13},
      { quantity:4}
    ]
</code>```

On the other hand, If I would have bought 7 mangoes, it should reduce all 5 from first array element and then remove 2 mangoes from the second element...and hence the final array would be like this below

```<code>   mangoes:[
      { quantity:0},
      { quantity:6},
      { quantity:13},
      { quantity:4}
    ]
</code>```

By Using Javascript, how can I achieve this?

WHAT I HAVE TRIED

I have tried like this below, It works only for the first element(case) when the x is less, but for other case it doesn't work;

```<code>var x = 2
var done = false

mangoes.forEach(function (item,i) {

  if(mangoes[i].quantity>=x && !done){
    item.quantity = mangoes[i].quantity - x
    done = true
  }

})
</code>```

答:
You can take a closure inside map and generate the desired result.

var mangoes=[ { quantity:5},{ quantity:8},{ quantity:13},{ quantity:4}];
var toReduce = 5;

var result = mangoes.map((num=>({quantity})=>(r = Math.min(quantity,num),num=num-r,({quantity:quantity-r})))(toReduce));

console.log(result);```

Body:
I have this sample array of objects

   mangoes:[
      { quantity:5},
      { quantity:8},
      { quantity:13},
      { quantity:4}
    ]

When I remove x mangoes, that x should be subtracted from the first element in the array, and if that x exceed the first element then it should reduce the remained quantity in the second item in the array...and so forth.

This is to say, I need the quantity to be reduced starting from the first one in the array down to the second if it exceed, to the third etc..

For example, If I buy 2 mangoes, It should minus 2 in the first array element and the resulting mangoes array should be

   mangoes:[
      { quantity:3},
      { quantity:8},
      { quantity:13},
      { quantity:4}
    ]

On the other hand, If I would have bought 7 mangoes, it should reduce all 5 from first array element and then remove 2 mangoes from the second element...and hence the final array would be like this below

   mangoes:[
      { quantity:0},
      { quantity:6},
      { quantity:13},
      { quantity:4}
    ]

By Using Javascript, how can I achieve this?

WHAT I HAVE TRIED

I have tried like this below, It works only for the first element(case) when the x is less, but for other case it doesn't work;

var x = 2
var done = false

mangoes.forEach(function (item,i) {

  if(mangoes[i].quantity>=x && !done){
    item.quantity = mangoes[i].quantity - x
    done = true
  }

})


问:
speechSynthesis.pause() should return true but returning false
When I play and pause and play again it does not play because

speechSynthesis.pause() does not make speechSynthesis.paused true which should make it true.

I've checked the docs it says

The paused read-only property of the SpeechSynthesis interface is a Boolean that returns true if the SpeechSynthesis object is in a paused state, or false if not.

meaning the line speechSynthesis.pause() didnt set it to true

Sample below:

const playButton = document.getElementById("play-button");
const pauseButton = document.getElementById("pause-button");
const stopButton = document.getElementById("stop-button");
const textInput = document.getElementById("text");
const speedInput = document.getElementById("speed");
const status = document.getElementById("status");
let currentCharacter;
const utterance = new SpeechSynthesisUtterance();

utterance.addEventListener("end", () => {
  textInput.disabled = false;
})
utterance.addEventListener("bounary", e => {
  currentCharacter = e.charIndex;
})

playButton.addEventListener("click", () => {
  playText(textInput.value);
})
pauseButton.addEventListener("click", pauseText);
stopButton.addEventListener("click", stopText);
speedInput.addEventListener("input", () => {
  stopText();
  playText(utterance.text.substring(currentCharacter))
})

function playText(text) {
  if (speechSynthesis.paused && speechSynthesis.speaking) {
    status.innerHTML = "resumed";
    return speechSynthesis.resume()
  }
  status.innerHTML = "played";
  if (speechSynthesis.speaking) return
  utterance.text = text;
  utterance.rate = speedInput.value || 1;
  textInput.disabled = true;
  speechSynthesis.speak(utterance);
}

function pauseText() {
  if (speechSynthesis.speaking) {
    status.innerHTML = "paused";
    speechSynthesis.pause() //
  }
}

function stopText() {
  status.innerHTML = "stopped";
  speechSynthesis.resume()
  speechSynthesis.cancel()
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  width: 90%;
  margin: 0 auto;
  margin-top: 1rem;
}

#text {
  width: 100%;
  height: 50vh;
}</code>```

<textarea name="text" id="text"></textarea>
Speed
<input type="number" name="speed" id="speed" min=".5" max="3" step=".5" value="1">
<button id="play-button">Play</button>
<button id="pause-button">Pause</button>
<button id="stop-button">Stop</button>
```

答:
You can use this code to see the statuses upon clicking Play, Pause and Stop. The statues are then updated when the relevent event is triggered. I.e. when you click Play the statuses are shown once upon clicking and again upon the onstart event being fired.

You'll see that there is a difference between these two for example when you click Pause the paused flag is false until the onpause event is triggered a moment later.

Given that chrome has problems and there are timing issues I suggest that you keep it simple and have start, pause, resume and cancel buttons with their own functions.

const showStatus = (btn) => {
  const statuses = document.createTextNode(`
    ${btn}:
    Pending: ${speechSynthesis.pending},
    Speaking: ${speechSynthesis.speaking},
    Paused: ${speechSynthesis.paused}`);
  const p = document.createElement('p');
  p.appendChild(statuses);
  data.insertBefore(p, data.firstElementChild);
};

play.addEventListener("click", (e) => {
  const u = new SpeechSynthesisUtterance(
    "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15"
  );
  speechSynthesis.speak(u);
  showStatus(e.target.innerText);
  u.onstart = () => showStatus('On start');
  u.onpause = () => showStatus('On pause');
  u.onresume = () => showStatus('On resume');
  u.onend = () => showStatus('On end');
  u.onerror = (err) => showStatus('On error ' + err);
});

pause.addEventListener("click", (e) => {
  speechSynthesis.pause();
  showStatus(e.target.innerText);
});

resume.addEventListener("click", (e) => {
  speechSynthesis.resume();
  showStatus(e.target.innerText);
});

ssCancel.addEventListener('click', (e) => {
  speechSynthesis.cancel();
  showStatus(e.target.innerText);
});

showStatus('Upon load');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="play">Play</button>
<button id="pause">Pause</button>
<button id="resume">Resume</button>
<button id="ssCancel">Cancel</button>

<div id="data"></div></code>```

Body:
When I play and pause and play again it does not play because

speechSynthesis.pause() does not make speechSynthesis.paused true which should make it true.

I've checked the docs it says

The paused read-only property of the SpeechSynthesis interface is a Boolean that returns true if the SpeechSynthesis object is in a paused state, or false if not.

meaning the line speechSynthesis.pause() didnt set it to true

Sample below:

const playButton = document.getElementById("play-button");
const pauseButton = document.getElementById("pause-button");
const stopButton = document.getElementById("stop-button");
const textInput = document.getElementById("text");
const speedInput = document.getElementById("speed");
const status = document.getElementById("status");
let currentCharacter;
const utterance = new SpeechSynthesisUtterance();

utterance.addEventListener("end", () => {
  textInput.disabled = false;
})
utterance.addEventListener("bounary", e => {
  currentCharacter = e.charIndex;
})

playButton.addEventListener("click", () => {
  playText(textInput.value);
})
pauseButton.addEventListener("click", pauseText);
stopButton.addEventListener("click", stopText);
speedInput.addEventListener("input", () => {
  stopText();
  playText(utterance.text.substring(currentCharacter))
})

function playText(text) {
  if (speechSynthesis.paused && speechSynthesis.speaking) {
    status.innerHTML = "resumed";
    return speechSynthesis.resume()
  }
  status.innerHTML = "played";
  if (speechSynthesis.speaking) return
  utterance.text = text;
  utterance.rate = speedInput.value || 1;
  textInput.disabled = true;
  speechSynthesis.speak(utterance);
}

function pauseText() {
  if (speechSynthesis.speaking) {
    status.innerHTML = "paused";
    speechSynthesis.pause() //
  }
}

function stopText() {
  status.innerHTML = "stopped";
  speechSynthesis.resume()
  speechSynthesis.cancel()
}

body {
  width: 90%;
  margin: 0 auto;
  margin-top: 1rem;
}

#text {
  width: 100%;
  height: 50vh;
}

<textarea name="text" id="text"></textarea>
Speed
<input type="number" name="speed" id="speed" min=".5" max="3" step=".5" value="1">
<button id="play-button">Play</button>
<button id="pause-button">Pause</button>
<button id="stop-button">Stop</button>

Body:
You can use this code to see the statuses upon clicking Play, Pause and Stop. The statues are then updated when the relevent event is triggered. I.e. when you click Play the statuses are shown once upon clicking and again upon the onstart event being fired.

You'll see that there is a difference between these two for example when you click Pause the paused flag is false until the onpause event is triggered a moment later.

Given that chrome has problems and there are timing issues I suggest that you keep it simple and have start, pause, resume and cancel buttons with their own functions.

const showStatus = (btn) => {
  const statuses = document.createTextNode(`
    ${btn}:
    Pending: ${speechSynthesis.pending},
    Speaking: ${speechSynthesis.speaking},
    Paused: ${speechSynthesis.paused}`);
  const p = document.createElement('p');
  p.appendChild(statuses);
  data.insertBefore(p, data.firstElementChild);
};

play.addEventListener("click", (e) => {
  const u = new SpeechSynthesisUtterance(
    "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15"
  );
  speechSynthesis.speak(u);
  showStatus(e.target.innerText);
  u.onstart = () => showStatus('On start');
  u.onpause = () => showStatus('On pause');
  u.onresume = () => showStatus('On resume');
  u.onend = () => showStatus('On end');
  u.onerror = (err) => showStatus('On error ' + err);
});

pause.addEventListener("click", (e) => {
  speechSynthesis.pause();
  showStatus(e.target.innerText);
});

resume.addEventListener("click", (e) => {
  speechSynthesis.resume();
  showStatus(e.target.innerText);
});

ssCancel.addEventListener('click', (e) => {
  speechSynthesis.cancel();
  showStatus(e.target.innerText);
});

showStatus('Upon load');

<button id="play">Play</button>
<button id="pause">Pause</button>
<button id="resume">Resume</button>
<button id="ssCancel">Cancel</button>

<div id="data"></div>


问:
Setting a maximum width on a ViewGroup
How do I set the maximum width of a ViewGroup? I am using a Theme.Dialog activity, however, this does not look so good when resized to bigger screens, it's also sort of lightweight and I don't want it taking up the whole screen.

I tried this suggestion to no avail. Also, there is no android:maxWidth property like some views.

Is there a way to restrict the root LinearLayout so that it is only (for example) 640 dip? I am willing to change to another ViewGroup for this.

Any suggestions?

答:
One option which is what I did is to extend LinearLayout and override the onMeasure function. For example:

```<code>public class BoundedLinearLayout extends LinearLayout {

    private final int mBoundedWidth;

    private final int mBoundedHeight;

    public BoundedLinearLayout(Context context) {
        super(context);
        mBoundedWidth = 0;
        mBoundedHeight = 0;
    }

    public BoundedLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BoundedView);
        mBoundedWidth = a.getDimensionPixelSize(R.styleable.BoundedView_bounded_width, 0);
        mBoundedHeight = a.getDimensionPixelSize(R.styleable.BoundedView_bounded_height, 0);
        a.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // Adjust width as necessary
        int measuredWidth = MeasureSpec.getSize(widthMeasureSpec);
        if(mBoundedWidth > 0 && mBoundedWidth < measuredWidth) {
            int measureMode = MeasureSpec.getMode(widthMeasureSpec);
            widthMeasureSpec = MeasureSpec.makeMeasureSpec(mBoundedWidth, measureMode);
        }
        // Adjust height as necessary
        int measuredHeight = MeasureSpec.getSize(heightMeasureSpec);
        if(mBoundedHeight > 0 && mBoundedHeight < measuredHeight) {
            int measureMode = MeasureSpec.getMode(heightMeasureSpec);
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(mBoundedHeight, measureMode);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}
</code>```

Then you XML would use the custom class:

```<code><com.yourpackage.BoundedLinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:bounded_width="900dp">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
    />
</com.youpackage.BoundedLinearLayout>
</code>```

And the attr.xml file entry

```<code><declare-styleable name="BoundedView">
    <attr name="bounded_width" format="dimension" />
    <attr name="bounded_height" format="dimension" />
</declare-styleable>
</code>```

EDIT: This is the actual code I am using now. This is still not complete but works in most cases.

Title: Setting a maximum width on a ViewGroup

Body:
One option which is what I did is to extend LinearLayout and override the onMeasure function. For example:

public class BoundedLinearLayout extends LinearLayout {

    private final int mBoundedWidth;

    private final int mBoundedHeight;

    public BoundedLinearLayout(Context context) {
        super(context);
        mBoundedWidth = 0;
        mBoundedHeight = 0;
    }

    public BoundedLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BoundedView);
        mBoundedWidth = a.getDimensionPixelSize(R.styleable.BoundedView_bounded_width, 0);
        mBoundedHeight = a.getDimensionPixelSize(R.styleable.BoundedView_bounded_height, 0);
        a.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // Adjust width as necessary
        int measuredWidth = MeasureSpec.getSize(widthMeasureSpec);
        if(mBoundedWidth > 0 && mBoundedWidth < measuredWidth) {
            int measureMode = MeasureSpec.getMode(widthMeasureSpec);
            widthMeasureSpec = MeasureSpec.makeMeasureSpec(mBoundedWidth, measureMode);
        }
        // Adjust height as necessary
        int measuredHeight = MeasureSpec.getSize(heightMeasureSpec);
        if(mBoundedHeight > 0 && mBoundedHeight < measuredHeight) {
            int measureMode = MeasureSpec.getMode(heightMeasureSpec);
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(mBoundedHeight, measureMode);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

Then you XML would use the custom class:

<com.yourpackage.BoundedLinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:bounded_width="900dp">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
    />
</com.youpackage.BoundedLinearLayout>

And the attr.xml file entry

<declare-styleable name="BoundedView">
    <attr name="bounded_width" format="dimension" />
    <attr name="bounded_height" format="dimension" />
</declare-styleable>

EDIT: This is the actual code I am using now. This is still not complete but works in most cases.


问:
Create Object into Object Javascript
I have the follow code and I want to achive the same result inside a for loop.

Is there a way to make it?

```<code>function makeNode(){
    let node = {value: 0, next :{} };
    let randon_number = Math.floor(Math.random() * (100 -1)) + 1;
    node.value = randon_number;
    node.next = {};
    return node;
}
function nodeList (){
    let node = makeNode();
    node.next = makeNode();
    node.next.next = makeNode();
    node.next.next.next = makeNode();
    node.next.next.next.next = makeNode();
    return node;
}
</code>```

Output:

{"value":45,"next":{"value":32,"next":{"value":52,"next":{"value":89,"next":{"value":32,"next":{}}}}}}

答:
Using for loop

function makeNode() {
  return {
    value: Math.floor(Math.random() * (100 - 1)) + 1,
    next: {}
  };
}

function makeNodeList(length) {
  let nodeList = makeNode()
  let currentNode = nodeList
  for (let i = 1; i < length; i++) {
    currentNode.next = makeNode()
    currentNode = currentNode.next
  }
  return nodeList
}
console.log(makeNodeList(5))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}</code>```

Using recursion

function makeNodeList(length) {
 if(length==0)return {};
 return {
    value: Math.floor(Math.random() * (100 - 1)) + 1,
    next: makeNodeList(length-1)
  };

}
console.log(makeNodeList(5))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}</code>```

Title: Create Object into Object Javascript

Body:
I have the follow code and I want to achive the same result inside a for loop.

Is there a way to make it?

function makeNode(){
    let node = {value: 0, next :{} };
    let randon_number = Math.floor(Math.random() * (100 -1)) + 1;
    node.value = randon_number;
    node.next = {};
    return node;
}
function nodeList (){
    let node = makeNode();
    node.next = makeNode();
    node.next.next = makeNode();
    node.next.next.next = makeNode();
    node.next.next.next.next = makeNode();
    return node;
}

Output:

{"value":45,"next":{"value":32,"next":{"value":52,"next":{"value":89,"next":{"value":32,"next":{}}}}}}

Body:
Using for loop

function makeNode() {
  return {
    value: Math.floor(Math.random() * (100 - 1)) + 1,
    next: {}
  };
}

function makeNodeList(length) {
  let nodeList = makeNode()
  let currentNode = nodeList
  for (let i = 1; i < length; i++) {
    currentNode.next = makeNode()
    currentNode = currentNode.next
  }
  return nodeList
}
console.log(makeNodeList(5))

.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}

Using recursion

function makeNodeList(length) {
 if(length==0)return {};
 return {
    value: Math.floor(Math.random() * (100 - 1)) + 1,
    next: makeNodeList(length-1)
  };

}
console.log(makeNodeList(5))

.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}


问:
How to get a class to print out multiple parameters (__str__ function question)
I'm creating a class that prints out its contents using the str() function. However, I can only seem to be able to get it to print out one of the parameters? When I ask it to return self.num as well as self.word it throws an error.

Would anyone be able to help me on this?

```<code>class Test:
    def __init__ (self, word, num):
        self.word = word
        self.num = num

    def __str__(self):
        return self.word, self.num

a = Test('Word', '10')
print(a)
</code>```

答:
The __str__ method is expected to return a single string. To show several variables, concatenate (via + if they are strings) or format them (via f-string literals, format string templates, or printf %-formatting) into a single string.

```<code>class Test:
    def __init__ (self, word, num):
        self.word = word
        self.num = num

    def __str__(self):
        # f-string literal - ``{...}`` are replacement fields
        return f'{self.word} => {self.num}'

a = Test('Word', '10')
print(a)  # Word => 10
</code>```

Body:
I'm creating a class that prints out its contents using the str() function. However, I can only seem to be able to get it to print out one of the parameters? When I ask it to return self.num as well as self.word it throws an error.

Would anyone be able to help me on this?

class Test:
    def __init__ (self, word, num):
        self.word = word
        self.num = num

    def __str__(self):
        return self.word, self.num

a = Test('Word', '10')
print(a)

Body:
The __str__ method is expected to return a single string. To show several variables, concatenate (via + if they are strings) or format them (via f-string literals, format string templates, or printf %-formatting) into a single string.

class Test:
    def __init__ (self, word, num):
        self.word = word
        self.num = num

    def __str__(self):
        # f-string literal - ``{...}`` are replacement fields
        return f'{self.word} => {self.num}'

a = Test('Word', '10')
print(a)  # Word => 10


问:
Excel VBA (sub or function not defined error)
I am working on the following code in VBA excel and i get the compile error "sub or function not defined"
The code is meant to copy the cells and paste their transpose at a certain offset.
Any help would be highly appreciated.

Code

```<code>Sub copy_paste()
ActiveCells.Copy
Offset(-1, 1).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=True
Offset(3, -1).Select
Range(Selection, Selection.End(xlToRight)).Select
Application.CutCopyMode = False
Selection.Copy
Offset(-2, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=True
Offset(1, 0).Select
Range(Selection, Selection.End(xlToRight)).Select
Application.CutCopyMode = False
Selection.ClearContents

End Sub
</code>```

Thanking in advance, here is the code along with the error:

答:
Use offset in vba like this : Range("A1").Offset(1, 1).Select .

in your code you used offset without refrence range address

Body:
I am working on the following code in VBA excel and i get the compile error "sub or function not defined"
The code is meant to copy the cells and paste their transpose at a certain offset.
Any help would be highly appreciated.

Code

Sub copy_paste()
ActiveCells.Copy
Offset(-1, 1).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=True
Offset(3, -1).Select
Range(Selection, Selection.End(xlToRight)).Select
Application.CutCopyMode = False
Selection.Copy
Offset(-2, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=True
Offset(1, 0).Select
Range(Selection, Selection.End(xlToRight)).Select
Application.CutCopyMode = False
Selection.ClearContents

End Sub

Thanking in advance, here is the code along with the error:


问:
Converting more columns into different types
I have a dataset that looks like as follows:

```<code>date           time_h     Checked     Verified
2018-03-10    21:10     TRUE         TRUE
2018-03-19    03:20     FALSE        TRUE
2018-04-04    12:03     TBC          FALSE
...
</code>```

I have been trying to convert the strings to the following formats:

date and time_h to date and time objects;

Checked and Verified to boolean values.

After putting all text in lower case, I have tried as follows:

```<code>bool = {'true': True, 'false': False}

df['Checked']=df['Checked'].map(bool)
df['Verified']=df['Verified'].map(bool)

df['date']= pd.to_datetime(df['date']).dt.date
df['time_h']= pd.to_datetime(df['time_h']).dt.strftime('%H:%M')
</code>```

However, when I check using dtypes, the outputs show all the columns as objects (so no change has been applied).
Where am I doing wrong? How could I also include the TBC in the TRUE boolean value (saying TBC = TRUE)?

Edit:

An example of nan in my code within column time_h is NaN (string format, as it comes from a csv file).
After replacing 'NaN' value using

```<code>df['time_h'] = df['time_h'].replace('NaN', np.nan)
</code>```

I get:

```<code><bound method Series.isnull of 0      nan
1      nan
2      nan
3      nan
</code>```

but when I use

```<code>t = df['time_h'].str.split(':', expand=True).astype(int)
df['time_h'] = pd.to_timedelta(t[0], unit='h', errors='coerce') + pd.to_timedelta(t[1], unit='m', errors='coerce')
</code>```

I get the following error:

```<code>ValueError: invalid literal for int() with base 10: 'nan'
</code>```

答:
For converting to bool columns, you can use np.where:

```<code>In [707]: import numpy as np

In [704]: df.Checked = df['Checked'].astype(str).replace({'(?i)True|TBC': True, '(?i)False|nan': False}, regex=True)
In [704]: df.Verified = df['Verified'].astype(str).replace({'(?i)True|TBC': True, '(?i)False|nan': False}, regex=True)

In [706]: df.dtypes
Out[706]:
date                object
time                object
Checked               bool
Verified              bool
</code>```

For date column, use pd.to_datetime:

```<code>df['date']= pd.to_datetime(df['date'])

In [706]: df.dtypes
Out[706]:
date        datetime64[ns]
time                object
Checked               bool
Verified              bool
</code>```

For time column, you can use pd.to_timedelta:

```<code>In [714]: t = df['time'].str.split(':', expand=True).astype(int)
In [716]: df['time'] = pd.to_timedelta(t[0], unit='h', errors='coerce') + pd.to_timedelta(t[1], unit='m', errors='coerce')

In [717]: df.dtypes
Out[717]:
date         datetime64[ns]
time        timedelta64[ns]
Checked                bool
Verified               bool
</code>```

Body:
I have a dataset that looks like as follows:

date           time_h     Checked     Verified
2018-03-10    21:10     TRUE         TRUE
2018-03-19    03:20     FALSE        TRUE
2018-04-04    12:03     TBC          FALSE
...

I have been trying to convert the strings to the following formats:

date and time_h to date and time objects;

Checked and Verified to boolean values.

After putting all text in lower case, I have tried as follows:

bool = {'true': True, 'false': False}

df['Checked']=df['Checked'].map(bool)
df['Verified']=df['Verified'].map(bool)

df['date']= pd.to_datetime(df['date']).dt.date
df['time_h']= pd.to_datetime(df['time_h']).dt.strftime('%H:%M')

However, when I check using dtypes, the outputs show all the columns as objects (so no change has been applied).
Where am I doing wrong? How could I also include the TBC in the TRUE boolean value (saying TBC = TRUE)?

Edit:

An example of nan in my code within column time_h is NaN (string format, as it comes from a csv file).
After replacing 'NaN' value using

df['time_h'] = df['time_h'].replace('NaN', np.nan)

I get:

<bound method Series.isnull of 0      nan
1      nan
2      nan
3      nan

but when I use

t = df['time_h'].str.split(':', expand=True).astype(int)
df['time_h'] = pd.to_timedelta(t[0], unit='h', errors='coerce') + pd.to_timedelta(t[1], unit='m', errors='coerce')

I get the following error:

ValueError: invalid literal for int() with base 10: 'nan'

Body:
For converting to bool columns, you can use np.where:

In [707]: import numpy as np

In [704]: df.Checked = df['Checked'].astype(str).replace({'(?i)True|TBC': True, '(?i)False|nan': False}, regex=True)
In [704]: df.Verified = df['Verified'].astype(str).replace({'(?i)True|TBC': True, '(?i)False|nan': False}, regex=True)

In [706]: df.dtypes
Out[706]:
date                object
time                object
Checked               bool
Verified              bool

For date column, use pd.to_datetime:

df['date']= pd.to_datetime(df['date'])

In [706]: df.dtypes
Out[706]:
date        datetime64[ns]
time                object
Checked               bool
Verified              bool

For time column, you can use pd.to_timedelta:

In [714]: t = df['time'].str.split(':', expand=True).astype(int)
In [716]: df['time'] = pd.to_timedelta(t[0], unit='h', errors='coerce') + pd.to_timedelta(t[1], unit='m', errors='coerce')

In [717]: df.dtypes
Out[717]:
date         datetime64[ns]
time        timedelta64[ns]
Checked                bool
Verified               bool


问:
C#: how to handle floats properly
In my code i write the following line:

```<code>return ((value / 120) * 1440).ToString();
</code>```

Now this returns me 0 when the value in value is less than Zero because it treats the result of (value / 120) as an integer where as i need C# to treat this result as float is there any way to achieve this?

Example:
If Value = 80

Then,
This function returns me 0 whereas i want this function to return me 960

答:
or this: </p>

```<code>float value = 80;
Console.WriteLine( ((value / 120) * 1440).ToString() );
</code>```

Title: C#: how to handle floats properly

Body:
In my code i write the following line:

return ((value / 120) * 1440).ToString();

Now this returns me 0 when the value in value is less than Zero because it treats the result of (value / 120) as an integer where as i need C# to treat this result as float is there any way to achieve this?

Example:
If Value = 80

Then,
This function returns me 0 whereas i want this function to return me 960

Body:
or this:

float value = 80;
Console.WriteLine( ((value / 120) * 1440).ToString() );


Title: I have sample dataframe with null values, i want the null values to be shifted to the right side columnsvalues

Body:
Sample Input Dataframe:

+---+---+----+----+----+
|  A|  B|   C|   D|   E|
+---+---+----+----+----+
|  1|  2|   3|   4|   5|
|  6|  7|null|   8|   9|
| 10| 11|  12|null|null|
+---+---+----+----+----+

Expected output dataframe:

+---+---+----+----+----+
|  A|  B|   C|   D|   E|
+---+---+----+----+----+
|  1|  2|   3|   4|   5|
|  6|  7|   8|   9|null|
| 10| 11|  12|null|null|
+---+---+----+----+----+

Body:
Try this:

var df = List(("1","2","3","4","5"),("6","7",null,"8","9"),("10","11","12",null,null),(null,"13",null,"14",null)).toDF("A","B","C","D","E")
df.show

+----+---+----+----+----+
|   A|  B|   C|   D|   E|
+----+---+----+----+----+
|   1|  2|   3|   4|   5|
|   6|  7|null|   8|   9|
|  10| 11|  12|null|null|
|null| 13|null|  14|null|
+----+---+----+----+----+

val cols = df.columns.size
df = df.withColumn("ct",split(concat_ws("-",df.columns.map(x=>col(x)):_*),"-"))
df.select((0 until cols).map(r => df.col("ct").getItem(r)): _*).toDF((0 until cols).map(r=>df.columns(r)):_*).show

+---+---+----+----+----+
|  A|  B|   C|   D|   E|
+---+---+----+----+----+
|  1|  2|   3|   4|   5|
|  6|  7|   8|   9|null|
| 10| 11|  12|null|null|
| 13| 14|null|null|null|
+---+---+----+----+----+


问:
Bootstrap 4 issue with div content of different sizes

I am stuck with the following issue, as per the below script, where the data in a div is not always the same size, which results in the div NOT taking the entire horizontal space allocated by the use of the col-6 class, from one row to the next:

```<code> <div  class="card-body " >
  <div class="row comments_container" id="comments_container">
      <?php foreach ($comments AS $comment){?>
          <div class="callout <?php echo $comment['comment_callout'];?>">
              <div class="row">
                  <div class="col-3"><?php echo '<span class="text-bold">De: </span>'.$comment['comment_author'];?></div>
                  <div class="offset-6 col-3">Envoyé le: <?php echo $comment['comment_date'];?></div>
              </div>
              <div class="row">
                  <div class="offset-3 col-6 border-primary border-left">
                      <?php
                      if (!empty($comment['comment_parent_author'])){echo 'En réponse à '.$comment['comment_author'].'.<br/>';}
                      echo '<span class="text-xs">'.$comment['comment_content'].'</span>';
                      ?>
                  </div>
                  <div class="col-3"></div>
              </div>
              <div class="row justify-content-center border-top mt-2 pt-2 border-thick border-primary w-100">
                  <div class="col-1">Approuver</div>
                  <div class="col-1">Répondre</div>
                  <div class="col-1">Indésirable</div>
                  <div class="col-1">Corbeille</div>
              </div>
          </div>
      <?php } ?>
  </div>
</div>
</code>```

As you can see also from the below adjoined screenshot, when the $comment['comment_content'] data is not the same size, or smaller, it results in the div containing the smallest data not 'respecting' the col-6 class, eg. only taking the smallest data field's size

答:
Your classes are not formatted very well try this :

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" />

De:John john

Envoyé le : 31 mai 2020

    Commentaire

Approuver

Répondre

Indésirable

Corbeille

```

Body:
I am stuck with the following issue, as per the below script, where the data in a div is not always the same size, which results in the div NOT taking the entire horizontal space allocated by the use of the col-6 class, from one row to the next:

      <?php foreach ($comments AS $comment){?>
          <div class="callout <?php echo $comment['comment_callout'];?>">

<?php echo 'De: '.$comment['comment_author'];?>

Envoyé le: <?php echo $comment['comment_date'];?>

                      <?php
                      if (!empty($comment['comment_parent_author'])){echo 'En réponse à '.$comment['comment_author'].'.
';}
                      echo ''.$comment['comment_content'].'';
                      ?>

Approuver

Répondre

Indésirable

Corbeille

      <?php } ?>

As you can see also from the below adjoined screenshot, when the $comment['comment_content'] data is not the same size, or smaller, it results in the div containing the smallest data not 'respecting' the col-6 class, eg. only taking the smallest data field's size

Body:
Your classes are not formatted very well try this :

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" />

<div class="container card-body">
  <div class="row comments_container" id="comments_container">
    <div class="col-3"><span class="text-bold">De:John john</span></div>
    <div class="offset-6 col-3">Envoyé le : 31 mai 2020 </div>
  </div>
  <div class="offset-3 col-6 border-primary border-left">
    <span class="text-xs">Commentaire</span>
  </div>
  <div class="row justify-content-center border-top mt-2 pt-2 border-thick border-primary w-100">
    <div class="p-1">Approuver</div>
    <div class="p-1">Répondre</div>
    <div class="p-1">Indésirable</div>
    <div class="p-1">Corbeille</div>
  </div>
</div>


问:
Elegant tuple manipulation suggestions
I am working with images and pixel positions represented by tuples. I want to check if pixels are next to each other and came up with a working solution. I'm sure there is a more elegant solution than mine. Here is the function I have:

```<code>def test_neighbors(tup1, tup2):
    neighbors = lambda a, b: [(a + 1, b), (a - 1, b), (a, b + 1), (a, b - 1)]
    list1 = neighbors(tup1[0], tup1[1])
    list2 = neighbors(tup2[0], tup2[1])
    for item in list1:
        if item in list2:
            return True
    return False
</code>```

Again, this code works perfectly, so if this isn't a proper question I am sorry. Thanks in advance for the suggestions!

答:
You can use:</p>

```<code>def func(tup1, tup2):
    return abs(sum(a[:2]) - sum(b[:2])) == 1
</code>```

Title: Elegant tuple manipulation suggestions

Body:
I am working with images and pixel positions represented by tuples. I want to check if pixels are next to each other and came up with a working solution. I'm sure there is a more elegant solution than mine. Here is the function I have:

def test_neighbors(tup1, tup2):
    neighbors = lambda a, b: [(a + 1, b), (a - 1, b), (a, b + 1), (a, b - 1)]
    list1 = neighbors(tup1[0], tup1[1])
    list2 = neighbors(tup2[0], tup2[1])
    for item in list1:
        if item in list2:
            return True
    return False

Again, this code works perfectly, so if this isn't a proper question I am sorry. Thanks in advance for the suggestions!

Body:
You can use:

def func(tup1, tup2):
    return abs(sum(a[:2]) - sum(b[:2])) == 1


问:
How to Force Phalcon to pick view from another module instead of defined?
Currently I am loading all users on URL/Route /admin/config/users which is picking this view ( private/apps/Admin/Views/user/users.volt ) from Admin module.

Now I have set a flag for custom layout. So if custom layout is enabled I want the phalcon to pick view from AdminExtension module i.e ( private/apps/Admin/Extension/Views/user/users.volt )

How can I achive this? I want both views. Because private/apps/Admin/Views/user/users.volt is default view for listing all users. However private/apps/Admin/Extension/Views/user/users.volt is customised view for client where a lot of design changes are done.

Here is how dispatcher code looks like:

```<code>/**
 * @param Dispatcher $dispatcher
 */
public function afterExecuteRoute(Dispatcher $dispatcher) {

    // Check if Json response is required
    if ($this->_isJsonResponse) {
         //if body
    } else {

        if(CxSettingCustomLayout::loadFromDb()->isCustomLayout()) {
            //pick custom view here" `private/apps/Admin/Extension/Views/user/users.volt`
        }

        // Build current module configuration settings section name
        $moduleConfigName = 'app_' . $this->dispatcher->getModuleName();
        // Include assets configuration file where assets collections are defined
        if(file_exists($this->config[ $moduleConfigName ]['assetsFile']))
            include $this->config[ $moduleConfigName ]['assetsFile'];

        // Set a view variable with the current language code
        $this->view->setVar('current_language_code', $this->CxTranslation->getLanguage()->getCode());
    }
}
</code>```

答:
As @num8er said already, try to use setViewsDir. I'm using Phalcons Simple view class in the following way

```<code>use Phalcon\Mvc\View\Simple;

$view = new Simple();
$view->setViewsDir(BASE_PATH . '/app/views/');
echo $view->render('admin/users');
</code>```

Body:
Currently I am loading all users on URL/Route /admin/config/users which is picking this view ( private/apps/Admin/Views/user/users.volt ) from Admin module.

Now I have set a flag for custom layout. So if custom layout is enabled I want the phalcon to pick view from AdminExtension module i.e ( private/apps/Admin/Extension/Views/user/users.volt )

How can I achive this? I want both views. Because private/apps/Admin/Views/user/users.volt is default view for listing all users. However private/apps/Admin/Extension/Views/user/users.volt is customised view for client where a lot of design changes are done.

Here is how dispatcher code looks like:

/**
 * @param Dispatcher $dispatcher
 */
public function afterExecuteRoute(Dispatcher $dispatcher) {

    // Check if Json response is required
    if ($this->_isJsonResponse) {
         //if body
    } else {

        if(CxSettingCustomLayout::loadFromDb()->isCustomLayout()) {
            //pick custom view here" `private/apps/Admin/Extension/Views/user/users.volt`
        }

        // Build current module configuration settings section name
        $moduleConfigName = 'app_' . $this->dispatcher->getModuleName();
        // Include assets configuration file where assets collections are defined
        if(file_exists($this->config[ $moduleConfigName ]['assetsFile']))
            include $this->config[ $moduleConfigName ]['assetsFile'];

        // Set a view variable with the current language code
        $this->view->setVar('current_language_code', $this->CxTranslation->getLanguage()->getCode());
    }
}

Body:
As @num8er said already, try to use setViewsDir. I'm using Phalcons Simple view class in the following way

use Phalcon\Mvc\View\Simple;

$view = new Simple();
$view->setViewsDir(BASE_PATH . '/app/views/');
echo $view->render('admin/users');