问:
node js, how to write/read integers to binary file?
I am new to this, so might be asking a basic question.
I have an array of floats

```<code>[1.3, 2.0, 10, 9.8, ... ] . //let's say length = 10
</code>```

which I want to store in a binary file.
I want to write in the following format

```<code> 10 1.3 2.0 10 9.8, ...
</code>```

so that when i load that file later, I first read the length 10, then read floats 10 times.

I think that saves space and should be faster than just writing/reading it as text.

So far, I found a bit info about binary file in node.js.

```<code>  var fs = require('fs');
  var wstream = fs.createWriteStream('myBinaryFile');
  var buffer = crypto.randomBytes(100);
  wstream.write(buffer);
  wstream.end();
</code>```

where I did not know how I can write my numbers into the buffer and write the buffer to file.

Also, I read some documents that says buffer in node only have integer 0~255, so does that mean, it cannot handle integers larger than 255?

For example, How can I write/read an array

```<code>  [11000, 24535, 92833, 45353, ... ]
</code>```

to/from a binary file.

I think I need a bit guidance, so here I am seeking for help.
Please point out what i should do, thanks!

答:
To be a bit more specific here is an answer to what you are looking to accomplish.</p>

```<code>    const values = [0, 4764, 9243, 13167, 16303, 18461, 19513];

    var wstream = fs.createWriteStream(testDatFile, { encoding: 'binary' });
    wstream.on('finish', function() {
      console.log('file has been written');
    });

    console.log('buffer.from', Buffer.from(Int16Array.from(values).buffer));
    wstream.write(Buffer.from(Int16Array.from(values).buffer));
    wstream.end()
</code>```

Body:
I am new to this, so might be asking a basic question.
I have an array of floats

[1.3, 2.0, 10, 9.8, ... ] . //let's say length = 10

which I want to store in a binary file.
I want to write in the following format

 10 1.3 2.0 10 9.8, ...

so that when i load that file later, I first read the length 10, then read floats 10 times.

I think that saves space and should be faster than just writing/reading it as text.

So far, I found a bit info about binary file in node.js.

  var fs = require('fs');
  var wstream = fs.createWriteStream('myBinaryFile');
  var buffer = crypto.randomBytes(100);
  wstream.write(buffer);
  wstream.end();

where I did not know how I can write my numbers into the buffer and write the buffer to file.

Also, I read some documents that says buffer in node only have integer 0~255, so does that mean, it cannot handle integers larger than 255?

For example, How can I write/read an array

  [11000, 24535, 92833, 45353, ... ]

to/from a binary file.

I think I need a bit guidance, so here I am seeking for help.
Please point out what i should do, thanks!

Body:
To be a bit more specific here is an answer to what you are looking to accomplish.

    const values = [0, 4764, 9243, 13167, 16303, 18461, 19513];

    var wstream = fs.createWriteStream(testDatFile, { encoding: 'binary' });
    wstream.on('finish', function() {
      console.log('file has been written');
    });

    console.log('buffer.from', Buffer.from(Int16Array.from(values).buffer));
    wstream.write(Buffer.from(Int16Array.from(values).buffer));
    wstream.end()


来源: stackexchange

问:
Using JQuery to change CSS value of all divs with same class but only if a contained checkbox is checked
I'm new to this world and finding myself on a very steep learning curve.
I've managed to sort all issues so far by looking through this site but this one has me stumped! I've given it a full day and can't progress so i'm hoping someone can help.

I've 2 roles, student and assessor.

Student completes their work and then the assessor marks it and a checkbox is ticked if the answer is sufficient.

Student then looks at their work and should see a green background to the answer with the checked checkbox, no background to those with unchecked.

At the moment my code is changing the background colour of all divs with the same class regardless of if the checkbox is checked or not.

Any help as to where i'm going wrong would be very much appreciated.

A sample question within a HTML form:

$(document).ready(function() {

  $('.answer').each(function() {
    if ($(this).find('input.cb:checked').prop('checked')) {

      $('.answer').css("background-color", "#a5de76");

    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="text-left">1. Describe the procedures in place when a steward supervises spectator entry.</div>
<p></p>
<div class="answer"><textarea id="U1Q1" name="U1Q1" rows="5" cols="70"><?php echo htmlspecialchars($row['U1Q1'])?></textarea>
  <?php echo '<input class="cb" type="checkbox" name="n" class="hidden" value="v"' . ($row['U1Q1R']==1 ? ' checked="checked"' : '') . '>';?>
  <input style="color:blue" id="textfield" name="U1Q1F" class="textfields" type="text" value="<?php echo htmlspecialchars($row['U1Q1F'])?>" readonly />
</div></code>```

This is how it currently looks on screen (the checkboxes will be hidden once I have the code working:

student page

答:
You just need to use the current context this and change:

```<code>$('.answer').css("background-color", "#a5de76");
</code>```

to

```<code>$(this).css("background-color", "#a5de76");
</code>```

So, that only current checked answer background color is changed.

Full Code:

$(document).ready(function() {
  $('.answer').each(function() {
    if ($(this).find('input.cb').prop('checked')) {
      $(this).css("background-color", "#a5de76");
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="text-left">1. Describe the procedures in place when a steward supervises spectator entry.</div>
<p></p>
<div class="answer">
  <textarea id="U1Q1" name="U1Q1" rows="2" cols="70"></textarea>
  <input class="cb" type="checkbox" name="n" class="hidden" value="v" checked>
  <input style="color:blue" id="textfield" name="U1Q1F" class="textfields" type="text" value="" readonly />
</div>
<div class="answer">
  <textarea id="U1Q1" name="U1Q1" rows="2" cols="70"></textarea>
  <input class="cb" type="checkbox" name="n" class="hidden" value="v">
  <input style="color:blue" id="textfield" name="U1Q1F" class="textfields" type="text" value="" readonly />
</div>
<div class="answer">
  <textarea id="U1Q1" name="U1Q1" rows="2" cols="70"></textarea>
  <input class="cb" type="checkbox" name="n" class="hidden" value="v" checked>
  <input style="color:blue" id="textfield" name="U1Q1F" class="textfields" type="text" value="" readonly />
</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new to this world and finding myself on a very steep learning curve.
I've managed to sort all issues so far by looking through this site but this one has me stumped! I've given it a full day and can't progress so i'm hoping someone can help.

I've 2 roles, student and assessor.

Student completes their work and then the assessor marks it and a checkbox is ticked if the answer is sufficient.

Student then looks at their work and should see a green background to the answer with the checked checkbox, no background to those with unchecked.

At the moment my code is changing the background colour of all divs with the same class regardless of if the checkbox is checked or not.

Any help as to where i'm going wrong would be very much appreciated.

A sample question within a HTML form:

$(document).ready(function() {

  $('.answer').each(function() {
    if ($(this).find('input.cb:checked').prop('checked')) {

      $('.answer').css("background-color", "#a5de76");

    }
  });
});

1. Describe the procedures in place when a steward supervises spectator entry.

<textarea id="U1Q1" name="U1Q1" rows="5" cols="70"><?php echo htmlspecialchars($row['U1Q1'])?></textarea>
  <?php echo '<input class="cb" type="checkbox" name="n" class="hidden" value="v"' . ($row['U1Q1R']==1 ? ' checked="checked"' : '') . '>';?>
  <input style="color:blue" id="textfield" name="U1Q1F" class="textfields" type="text" value="<?php echo htmlspecialchars($row['U1Q1F'])?>" readonly />

This is how it currently looks on screen (the checkboxes will be hidden once I have the code working:

student page

Body:
You just need to use the current context this and change:

$('.answer').css("background-color", "#a5de76");

to

$(this).css("background-color", "#a5de76");

So, that only current checked answer background color is changed.

Full Code:

$(document).ready(function() {
  $('.answer').each(function() {
    if ($(this).find('input.cb').prop('checked')) {
      $(this).css("background-color", "#a5de76");
    }
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="text-left">1. Describe the procedures in place when a steward supervises spectator entry.</div>
<p></p>
<div class="answer">
  <textarea id="U1Q1" name="U1Q1" rows="2" cols="70"></textarea>
  <input class="cb" type="checkbox" name="n" class="hidden" value="v" checked>
  <input style="color:blue" id="textfield" name="U1Q1F" class="textfields" type="text" value="" readonly />
</div>
<div class="answer">
  <textarea id="U1Q1" name="U1Q1" rows="2" cols="70"></textarea>
  <input class="cb" type="checkbox" name="n" class="hidden" value="v">
  <input style="color:blue" id="textfield" name="U1Q1F" class="textfields" type="text" value="" readonly />
</div>
<div class="answer">
  <textarea id="U1Q1" name="U1Q1" rows="2" cols="70"></textarea>
  <input class="cb" type="checkbox" name="n" class="hidden" value="v" checked>
  <input style="color:blue" id="textfield" name="U1Q1F" class="textfields" type="text" value="" readonly />
</div>


问:
How to get path Json in nested Pentaho?
I´m importing a json file that has the following structure (see code) in Pentaho. I have been able to obtain the first data but those that are nested do not know how to obtain it.

I know get label display and isMeasure but i don´t know how to get the next nested, label, display and display_sequence

```<code>Name     Path
label    $.dimension.*..label
display  $.dimension.*..display
Measure  $.dimension.*..isMeasure
Code     $.dimension.*..code
label2   $.dimension.*..code.label ???

{
"copyright": "(c) World Health Organization",
"dataset":
[
],
"attribute":
[
],
"dimension":
[
{
"label": "BLABLA",
"display": "BLELE",
"isMeasure": false,
"code":
[
{
"label": "AAAA",
"display": "CCCCC",
"display_sequence": 10,
"url": "",
"attr":
[
]
},
{
"label": "BBBB",
"display": "DDDD",
"display_sequence": 20,
"url": "",
"attr":
[
]
}
]
}
],
"fact":
[
]
}
</code>```

答:
to get first "label": "BLABLA" path should be $.dimension.*.label this will get only label BLABLA

for display and measure use below path

$.dimension.*.display
$.dimension.*.isMeasure

now get to another two label which is on code array the path should be $.dimension.*.code.*.label this will give you only code array label.

for display and display_sequence use below path

$.dimension.*.code.*.display
$.dimension.*.code.*.display_sequence

Title: How to get path Json in nested Pentaho?

Body:
I´m importing a json file that has the following structure (see code) in Pentaho. I have been able to obtain the first data but those that are nested do not know how to obtain it.

I know get label display and isMeasure but i don´t know how to get the next nested, label, display and display_sequence

Name     Path
label    $.dimension.*..label
display  $.dimension.*..display
Measure  $.dimension.*..isMeasure
Code     $.dimension.*..code
label2   $.dimension.*..code.label ???

{
"copyright": "(c) World Health Organization",
"dataset":
[
],
"attribute":
[
],
"dimension":
[
{
"label": "BLABLA",
"display": "BLELE",
"isMeasure": false,
"code":
[
{
"label": "AAAA",
"display": "CCCCC",
"display_sequence": 10,
"url": "",
"attr":
[
]
},
{
"label": "BBBB",
"display": "DDDD",
"display_sequence": 20,
"url": "",
"attr":
[
]
}
]
}
],
"fact":
[
]
}


问:
Problem with KeyListener and jframe
I've got problem with JFrame and KeyListerner in Tetris game. I've got two frames - one with Start Button and second with Board. In the second frame I want to control shapes from keyboard, but when I click start I can't do that. When I disactivate first frame - everything is ok. I know I have to focus on second frame and I tried do that, but with no effect. Could someone help me?
First frame:

```<code>package tetris;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Tetris implements ActionListener {
public Tetris() {
initComponents();
}
Component contentPane;
JLabel statusbar  = new JLabel(" 0");
JLabel name  = new JLabel("Tetris");
JButton startbut = new JButton("Start");
JFrame window = new JFrame();
JPanel panelStart = new JPanel();
JPanel game = new JPanel();
int nameSize=24;
Font fontName = new Font("Dialog", Font.BOLD, nameSize);
BorderLayout borderLayout = new BorderLayout();
Board board = new Board(this);

public void initComponents() {
    window.setBounds(500,200,200,400);
    window.setTitle("Tetris");
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setVisible(true);

    window.add(panelStart);
    window.add(game);
    panelStart.setLayout (null);
    panelStart.setVisible(true);
    window.setContentPane(panelStart);

    name.setSize(70,25);
    name.setLocation(53,10);
    name.setFont(fontName);
    panelStart.add(name);
    startbut.setSize(70,25);
    startbut.setLocation(50,80);
    panelStart.add(startbut);
    startbut.addActionListener(this);
  }

public void initGame() {

    game.setLayout (borderLayout);
    panelStart.setVisible(false);
    window.remove(panelStart);

    game.setVisible(true);
    window.setContentPane(game);

    game.setFocusable(true);
    statusbar = new JLabel(" 0");
   game.add(statusbar, BorderLayout.SOUTH);
     game.add(board);
   board.start();

 }
 public JLabel getStatusBar() {
   return statusbar;
 }
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == startbut)
{
    initGame();

}
}

}
</code>```

Board code:

```<code>package tetris;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;

import tetris.Shape.Tetrominoes;

public class Board extends JPanel implements ActionListener      {

    final int BoardWidth = 10;
    final int BoardHeight = 22;

    Timer timer;
    boolean isFallingFinished = false;
    boolean isStarted = false;
    boolean isPaused = false;
    int numLinesRemoved = 0;
    int curX = 0;
    int curY = 0;
    JLabel statusbar;
    Shape curPiece;
    Tetrominoes[] board;

    public Board(Tetris parent) {

    //   setFocusable(true);
       curPiece = new Shape();
       timer = new Timer(400, this);
       timer.start();

       statusbar =  parent.getStatusBar();
       board = new Tetrominoes[BoardWidth * BoardHeight];
       KeyListener keyListener = new TAdapter();
       addKeyListener(keyListener);
       repaint();
       clearBoard();

    }

    public void actionPerformed(ActionEvent e) {
        if (isFallingFinished) {
            isFallingFinished = false;
            newPiece();
        } else {
            oneLineDown();
        }
    }

    int squareWidth() { return (int) getSize().getWidth() / BoardWidth; }
    int squareHeight() { return (int) getSize().getHeight() / BoardHeight; }
    Tetrominoes shapeAt(int x, int y) { return board[(y * BoardWidth) + x]; }

    public void start()
    {
        if (isPaused)
            return;

        isStarted = true;
        isFallingFinished = false;
        numLinesRemoved = 0;
        clearBoard();

        newPiece();
        timer.start();
    }

    private void pause()
    {
        if (!isStarted)
            return;

        isPaused = !isPaused;
        if (isPaused) {
            timer.stop();
            statusbar.setText("paused");
        } else {
            timer.start();
            statusbar.setText(String.valueOf(numLinesRemoved));
        }
        repaint();
    }

    public void paint(Graphics g)
    {
        super.paint(g);

        Dimension size = getSize();
        int boardTop = (int) size.getHeight() - BoardHeight * squareHeight();

        for (int i = 0; i < BoardHeight; ++i) {
            for (int j = 0; j < BoardWidth; ++j) {
                Tetrominoes shape = shapeAt(j, BoardHeight - i - 1);
                if (shape != Tetrominoes.NoShape)
                    drawSquare(g, 0 + j * squareWidth(),
                               boardTop + i * squareHeight(), shape);
            }
        }

        if (curPiece.getShape() != Tetrominoes.NoShape) {
            for (int i = 0; i < 4; ++i) {
                int x = curX + curPiece.x(i);
                int y = curY - curPiece.y(i);
                drawSquare(g, 0 + x * squareWidth(),
                           boardTop + (BoardHeight - y - 1) * squareHeight(),
                           curPiece.getShape());
            }
        }
    }

    private void dropDown()
    {
        int newY = curY;
        while (newY > 0) {
            if (!tryMove(curPiece, curX, newY - 1))
                break;
            --newY;
        }
        pieceDropped();
    }

    private void oneLineDown()
    {
        if (!tryMove(curPiece, curX, curY - 1))
            pieceDropped();
    }

    private void clearBoard()
    {
        for (int i = 0; i < BoardHeight * BoardWidth; ++i)
            board[i] = Tetrominoes.NoShape;
    }

    private void pieceDropped()
    {
        for (int i = 0; i < 4; ++i) {
            int x = curX + curPiece.x(i);
            int y = curY - curPiece.y(i);
            board[(y * BoardWidth) + x] = curPiece.getShape();
        }

        removeFullLines();

        if (!isFallingFinished)
            newPiece();
    }

    private void newPiece()
    {
        curPiece.setRandomShape();
        curX = BoardWidth / 2 + 1;
        curY = BoardHeight - 1 + curPiece.minY();

        if (!tryMove(curPiece, curX, curY)) {
            curPiece.setShape(Tetrominoes.NoShape);
            timer.stop();
            isStarted = false;
            statusbar.setText("game over");
        }
    }

    private boolean tryMove(Shape newPiece, int newX, int newY)
    {
        for (int i = 0; i < 4; ++i) {
            int x = newX + newPiece.x(i);
            int y = newY - newPiece.y(i);
            if (x < 0 || x >= BoardWidth || y < 0 || y >= BoardHeight)
                return false;
            if (shapeAt(x, y) != Tetrominoes.NoShape)
                return false;
        }

        curPiece = newPiece;
        curX = newX;
        curY = newY;
        repaint();
        return true;
    }

    private void removeFullLines()
    {
        int numFullLines = 0;

        for (int i = BoardHeight - 1; i >= 0; --i) {
            boolean lineIsFull = true;

            for (int j = 0; j < BoardWidth; ++j) {
                if (shapeAt(j, i) == Tetrominoes.NoShape) {
                    lineIsFull = false;
                    break;
                }
            }

            if (lineIsFull) {
                ++numFullLines;
                for (int k = i; k < BoardHeight - 1; ++k) {
                    for (int j = 0; j < BoardWidth; ++j)
                         board[(k * BoardWidth) + j] = shapeAt(j, k + 1);
                }
            }
        }

        if (numFullLines > 0) {
            numLinesRemoved += numFullLines;
            statusbar.setText(String.valueOf(numLinesRemoved));
            isFallingFinished = true;
            curPiece.setShape(Tetrominoes.NoShape);
            repaint();
        }
     }

    private void drawSquare(Graphics g, int x, int y, Tetrominoes shape)
    {
        Color colors[] = { new Color(0, 0, 0), new Color(204, 102, 102),
            new Color(102, 204, 102), new Color(102, 102, 204),
            new Color(204, 204, 102), new Color(204, 102, 204),
            new Color(102, 204, 204), new Color(218, 170, 0)
        };

        Color color = colors[shape.ordinal()];

        g.setColor(color);
        g.fillRect(x + 1, y + 1, squareWidth() - 2, squareHeight() - 2);

        g.setColor(color.brighter());
        g.drawLine(x, y + squareHeight() - 1, x, y);
        g.drawLine(x, y, x + squareWidth() - 1, y);

        g.setColor(color.darker());
        g.drawLine(x + 1, y + squareHeight() - 1,
                         x + squareWidth() - 1, y + squareHeight() - 1);
        g.drawLine(x + squareWidth() - 1, y + squareHeight() - 1,
                         x + squareWidth() - 1, y + 1);

    }
    public boolean isFocusable() {
        return true;
    }
  public class TAdapter implements KeyListener  {
          public void keyTyped(KeyEvent e) {
          }
         public void keyPressed(KeyEvent e) {
             if (!isStarted || curPiece.getShape() == Tetrominoes.NoShape) {
                 return;
             }

             int keycode = e.getKeyCode();

             if (keycode == 'p' || keycode == 'P') {
                 pause();
                 return;
             }

             if (isPaused)
                 return;

             switch (keycode) {
             case KeyEvent.VK_LEFT:
                 tryMove(curPiece, curX - 1, curY);
                 break;
             case KeyEvent.VK_RIGHT:
                 tryMove(curPiece, curX + 1, curY);
                 break;
             case KeyEvent.VK_DOWN:
                 tryMove(curPiece.rotateRight(), curX, curY);
                 break;
             case KeyEvent.VK_UP:
                 tryMove(curPiece.rotateLeft(), curX, curY);
                 break;
             case KeyEvent.VK_SPACE:
                 dropDown();
                 break;
             case 'd':
                 oneLineDown();
                 break;
             case 'D':
                 oneLineDown();
                 break;
             }

         }
        @Override
        public void keyReleased(KeyEvent arg0) {
            // TODO Auto-generated method stub

        }
     }
}
</code>```

答: Same here, the code is too large to dig. However if you are facing problems in setting the focus try frame.requestFocus();

ContentLicense: CC BY-SA 3.0

Title: Problem with KeyListener and jframe

Body:
I've got problem with JFrame and KeyListerner in Tetris game. I've got two frames - one with Start Button and second with Board. In the second frame I want to control shapes from keyboard, but when I click start I can't do that. When I disactivate first frame - everything is ok. I know I have to focus on second frame and I tried do that, but with no effect. Could someone help me?
First frame:

package tetris;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Tetris implements ActionListener {
public Tetris() {
initComponents();
}
Component contentPane;
JLabel statusbar  = new JLabel(" 0");
JLabel name  = new JLabel("Tetris");
JButton startbut = new JButton("Start");
JFrame window = new JFrame();
JPanel panelStart = new JPanel();
JPanel game = new JPanel();
int nameSize=24;
Font fontName = new Font("Dialog", Font.BOLD, nameSize);
BorderLayout borderLayout = new BorderLayout();
Board board = new Board(this);

public void initComponents() {
    window.setBounds(500,200,200,400);
    window.setTitle("Tetris");
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setVisible(true);

    window.add(panelStart);
    window.add(game);
    panelStart.setLayout (null);
    panelStart.setVisible(true);
    window.setContentPane(panelStart);

    name.setSize(70,25);
    name.setLocation(53,10);
    name.setFont(fontName);
    panelStart.add(name);
    startbut.setSize(70,25);
    startbut.setLocation(50,80);
    panelStart.add(startbut);
    startbut.addActionListener(this);
  }

public void initGame() {

    game.setLayout (borderLayout);
    panelStart.setVisible(false);
    window.remove(panelStart);

    game.setVisible(true);
    window.setContentPane(game);

    game.setFocusable(true);
    statusbar = new JLabel(" 0");
   game.add(statusbar, BorderLayout.SOUTH);
     game.add(board);
   board.start();

 }
 public JLabel getStatusBar() {
   return statusbar;
 }
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == startbut)
{
    initGame();

}
}

}

Board code:

package tetris;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;

import tetris.Shape.Tetrominoes;

public class Board extends JPanel implements ActionListener      {

    final int BoardWidth = 10;
    final int BoardHeight = 22;

    Timer timer;
    boolean isFallingFinished = false;
    boolean isStarted = false;
    boolean isPaused = false;
    int numLinesRemoved = 0;
    int curX = 0;
    int curY = 0;
    JLabel statusbar;
    Shape curPiece;
    Tetrominoes[] board;

    public Board(Tetris parent) {

    //   setFocusable(true);
       curPiece = new Shape();
       timer = new Timer(400, this);
       timer.start();

       statusbar =  parent.getStatusBar();
       board = new Tetrominoes[BoardWidth * BoardHeight];
       KeyListener keyListener = new TAdapter();
       addKeyListener(keyListener);
       repaint();
       clearBoard();

    }

    public void actionPerformed(ActionEvent e) {
        if (isFallingFinished) {
            isFallingFinished = false;
            newPiece();
        } else {
            oneLineDown();
        }
    }

    int squareWidth() { return (int) getSize().getWidth() / BoardWidth; }
    int squareHeight() { return (int) getSize().getHeight() / BoardHeight; }
    Tetrominoes shapeAt(int x, int y) { return board[(y * BoardWidth) + x]; }

    public void start()
    {
        if (isPaused)
            return;

        isStarted = true;
        isFallingFinished = false;
        numLinesRemoved = 0;
        clearBoard();

        newPiece();
        timer.start();
    }

    private void pause()
    {
        if (!isStarted)
            return;

        isPaused = !isPaused;
        if (isPaused) {
            timer.stop();
            statusbar.setText("paused");
        } else {
            timer.start();
            statusbar.setText(String.valueOf(numLinesRemoved));
        }
        repaint();
    }

    public void paint(Graphics g)
    {
        super.paint(g);

        Dimension size = getSize();
        int boardTop = (int) size.getHeight() - BoardHeight * squareHeight();

        for (int i = 0; i < BoardHeight; ++i) {
            for (int j = 0; j < BoardWidth; ++j) {
                Tetrominoes shape = shapeAt(j, BoardHeight - i - 1);
                if (shape != Tetrominoes.NoShape)
                    drawSquare(g, 0 + j * squareWidth(),
                               boardTop + i * squareHeight(), shape);
            }
        }

        if (curPiece.getShape() != Tetrominoes.NoShape) {
            for (int i = 0; i < 4; ++i) {
                int x = curX + curPiece.x(i);
                int y = curY - curPiece.y(i);
                drawSquare(g, 0 + x * squareWidth(),
                           boardTop + (BoardHeight - y - 1) * squareHeight(),
                           curPiece.getShape());
            }
        }
    }

    private void dropDown()
    {
        int newY = curY;
        while (newY > 0) {
            if (!tryMove(curPiece, curX, newY - 1))
                break;
            --newY;
        }
        pieceDropped();
    }

    private void oneLineDown()
    {
        if (!tryMove(curPiece, curX, curY - 1))
            pieceDropped();
    }

    private void clearBoard()
    {
        for (int i = 0; i < BoardHeight * BoardWidth; ++i)
            board[i] = Tetrominoes.NoShape;
    }

    private void pieceDropped()
    {
        for (int i = 0; i < 4; ++i) {
            int x = curX + curPiece.x(i);
            int y = curY - curPiece.y(i);
            board[(y * BoardWidth) + x] = curPiece.getShape();
        }

        removeFullLines();

        if (!isFallingFinished)
            newPiece();
    }

    private void newPiece()
    {
        curPiece.setRandomShape();
        curX = BoardWidth / 2 + 1;
        curY = BoardHeight - 1 + curPiece.minY();

        if (!tryMove(curPiece, curX, curY)) {
            curPiece.setShape(Tetrominoes.NoShape);
            timer.stop();
            isStarted = false;
            statusbar.setText("game over");
        }
    }

    private boolean tryMove(Shape newPiece, int newX, int newY)
    {
        for (int i = 0; i < 4; ++i) {
            int x = newX + newPiece.x(i);
            int y = newY - newPiece.y(i);
            if (x < 0 || x >= BoardWidth || y < 0 || y >= BoardHeight)
                return false;
            if (shapeAt(x, y) != Tetrominoes.NoShape)
                return false;
        }

        curPiece = newPiece;
        curX = newX;
        curY = newY;
        repaint();
        return true;
    }

    private void removeFullLines()
    {
        int numFullLines = 0;

        for (int i = BoardHeight - 1; i >= 0; --i) {
            boolean lineIsFull = true;

            for (int j = 0; j < BoardWidth; ++j) {
                if (shapeAt(j, i) == Tetrominoes.NoShape) {
                    lineIsFull = false;
                    break;
                }
            }

            if (lineIsFull) {
                ++numFullLines;
                for (int k = i; k < BoardHeight - 1; ++k) {
                    for (int j = 0; j < BoardWidth; ++j)
                         board[(k * BoardWidth) + j] = shapeAt(j, k + 1);
                }
            }
        }

        if (numFullLines > 0) {
            numLinesRemoved += numFullLines;
            statusbar.setText(String.valueOf(numLinesRemoved));
            isFallingFinished = true;
            curPiece.setShape(Tetrominoes.NoShape);
            repaint();
        }
     }

    private void drawSquare(Graphics g, int x, int y, Tetrominoes shape)
    {
        Color colors[] = { new Color(0, 0, 0), new Color(204, 102, 102),
            new Color(102, 204, 102), new Color(102, 102, 204),
            new Color(204, 204, 102), new Color(204, 102, 204),
            new Color(102, 204, 204), new Color(218, 170, 0)
        };

        Color color = colors[shape.ordinal()];

        g.setColor(color);
        g.fillRect(x + 1, y + 1, squareWidth() - 2, squareHeight() - 2);

        g.setColor(color.brighter());
        g.drawLine(x, y + squareHeight() - 1, x, y);
        g.drawLine(x, y, x + squareWidth() - 1, y);

        g.setColor(color.darker());
        g.drawLine(x + 1, y + squareHeight() - 1,
                         x + squareWidth() - 1, y + squareHeight() - 1);
        g.drawLine(x + squareWidth() - 1, y + squareHeight() - 1,
                         x + squareWidth() - 1, y + 1);

    }
    public boolean isFocusable() {
        return true;
    }
  public class TAdapter implements KeyListener  {
          public void keyTyped(KeyEvent e) {
          }
         public void keyPressed(KeyEvent e) {
             if (!isStarted || curPiece.getShape() == Tetrominoes.NoShape) {
                 return;
             }

             int keycode = e.getKeyCode();

             if (keycode == 'p' || keycode == 'P') {
                 pause();
                 return;
             }

             if (isPaused)
                 return;

             switch (keycode) {
             case KeyEvent.VK_LEFT:
                 tryMove(curPiece, curX - 1, curY);
                 break;
             case KeyEvent.VK_RIGHT:
                 tryMove(curPiece, curX + 1, curY);
                 break;
             case KeyEvent.VK_DOWN:
                 tryMove(curPiece.rotateRight(), curX, curY);
                 break;
             case KeyEvent.VK_UP:
                 tryMove(curPiece.rotateLeft(), curX, curY);
                 break;
             case KeyEvent.VK_SPACE:
                 dropDown();
                 break;
             case 'd':
                 oneLineDown();
                 break;
             case 'D':
                 oneLineDown();
                 break;
             }

         }
        @Override
        public void keyReleased(KeyEvent arg0) {
            // TODO Auto-generated method stub

        }
     }
}


问:
Date/time output has single quote in front of variable in Google Sheet
I have some code to export some output to a Google Sheet. The command I am using for that is:

row = [timestamp, float(temperature), float(humidity), current_temperature, current_humidity, current_pressure, weather_description]
sheet.insert_row(row, index)
```
<p>The issue is that the timestamp variable is adding a single quote in front of itself when it is inserted into the sheet, but when using <code>print(timestamp)</code>, this quote is not there.</p>
<p><img src="https://i.stack.imgur.com/cYeLR.png" alt="date/time in cell in Google Sheets" /></p>
<p>This makes it difficult because I cannot make any graphs with that quote in front of the output. The commands I am using for time are as follows:</p>
<pre class="lang-py prettyprint-override"><code>now = datetime.now()
timestamp = now.strftime("%m/%d/%Y%l:%M:%S %p")
</code>```

How can I get a timestamp without a single quote in front?

答:
This is usually to indicate that the input is a string. I recommend to just insert the date using datetime.now() in this way google sheets will recognize it as a date rather than a string.

timestamp = datetime.now()
row = [timestamp,float(temperature),float(humidity),current_temperature,current_humidity,current_pressure,weather_description]
sheet.insert_row(row, index)
```

Edit:

If you want a special date format in your sheet, you will need to use google sheets API and format the column accordingly. I recommend using the library gspread is really useful when it comes to google-sheets formatting and easy to use: gspread docs

There is also another a special library to use gspread with pandas, I find it really useful as well: gspread-pandas

Body:
I have some code to export some output to a Google Sheet. The command I am using for that is:

row = [timestamp, float(temperature), float(humidity), current_temperature, current_humidity, current_pressure, weather_description]
sheet.insert_row(row, index)

The issue is that the timestamp variable is adding a single quote in front of itself when it is inserted into the sheet, but when using print(timestamp), this quote is not there.

This makes it difficult because I cannot make any graphs with that quote in front of the output. The commands I am using for time are as follows:

now = datetime.now()
timestamp = now.strftime("%m/%d/%Y%l:%M:%S %p")

How can I get a timestamp without a single quote in front?

Body:
This is usually to indicate that the input is a string. I recommend to just insert the date using datetime.now() in this way google sheets will recognize it as a date rather than a string.

timestamp = datetime.now()
row = [timestamp,float(temperature),float(humidity),current_temperature,current_humidity,current_pressure,weather_description]
sheet.insert_row(row, index)

Edit:

If you want a special date format in your sheet, you will need to use google sheets API and format the column accordingly. I recommend using the library gspread is really useful when it comes to google-sheets formatting and easy to use: gspread docs

There is also another a special library to use gspread with pandas, I find it really useful as well: gspread-pandas


问:
Iterate over set elements
I have turned on the Chrome flag for experimental ECMAscript 6 features, one of which is Set. As I understand, the details of Set are broadly agreed upon by the spec writers.

I create a set a and add the string 'Hello'

```<code>a = Set();
a.add('Hello');
</code>```

but how do I iterate over the elements of a?

```<code>for(let i of a) { console.log(i); }
</code>```

gives "SyntaxError: Illegal let declaration outside extended mode"

```<code>for(var i of a) { console.log(i); }
</code>```

gives "SyntaxError: Unexpected identifier"

```<code>for(var i in a) { console.log(i); }
</code>```

gives Undefined

Is it possible to iterate over of a set in Chrome 26?

答:
There are two methods you can use.
for...of
and  forEach

```<code>let a = new Set();
a.add('Hello');

for(let key of a) console.log(key)

a.forEach(key => console.log(key))
</code>```

Title: Iterate over set elements

Body:
I have turned on the Chrome flag for experimental ECMAscript 6 features, one of which is Set. As I understand, the details of Set are broadly agreed upon by the spec writers.

I create a set a and add the string 'Hello'

a = Set();
a.add('Hello');

but how do I iterate over the elements of a?

for(let i of a) { console.log(i); }

gives "SyntaxError: Illegal let declaration outside extended mode"

for(var i of a) { console.log(i); }

gives "SyntaxError: Unexpected identifier"

for(var i in a) { console.log(i); }

gives Undefined

Is it possible to iterate over of a set in Chrome 26?

Body:
There are two methods you can use.
for...of
and  forEach

let a = new Set();
a.add('Hello');

for(let key of a) console.log(key)

a.forEach(key => console.log(key))


问:
Program in C++ that takes 3 numbers and send them to a function and then calculate the average function of these 3 numbers
Program in C++ that takes 3 numbers and send them to a function and then calculate the average function of these 3 numbers.

I know how to do that without using a function ,for example for any n numbers I have the following program:

```<code>#include<stdio.h>

int main()
{

    int n, i;
    float sum = 0, x;

    printf("Enter number of elements:  ");
    scanf("%d", &n);
    printf("\n\n\nEnter %d elements\n\n", n);
    for(i = 0; i < n; i++)
    {
        scanf("%f", &x);
        sum += x;
    }
    printf("\n\n\nAverage of the entered numbers is =  %f", (sum/n));

    return 0;
}

</code>```

Or this one which do that using arrays:

```<code>#include <iostream>
using namespace std;

int main()
{
    int n, i;
    float num[100], sum=0.0, average;

    cout << "Enter the numbers of data: ";
    cin >> n;

    while (n > 100 || n <= 0)
    {
        cout << "Error! number should in range of (1 to 100)." << endl;
        cout << "Enter the number again: ";
        cin >> n;
    }

    for(i = 0; i < n; ++i)
    {
        cout << i + 1 << ". Enter number: ";
        cin >> num[i];
        sum += num[i];
    }

    average = sum / n;
    cout << "Average = " << average;

    return 0;
}

</code>```

But is it possible to use functions?if yes then how? thank you so much for helping.

答:
how to do that without using a function

Quite simple. Just put your code in a function, let's call it calculateAverage and return the average value from it. What should this function take as input?

The list of numbers (array of numbers)

Total numbers (n)

So let's first get the input from the user and put it into the array, you have already done it:

```<code>    for(int i = 0; i < n; ++i)
    {
        cout << i + 1 << ". Enter number: ";
        cin >> num[i];
    }
</code>```

Now, lets make a small function i.e., calculateAverage():

```<code>int calculateAverage(int numbers[], int total)
{
    int sum = 0; // always initialize your variables
    for(int i = 0; i < total; ++i)
    {
        sum += numbers[i];
    }

    const int average = sum / total; // it is constant and should never change
                                     // so we qualify it as 'const'
    //return this value
    return average
}
</code>```

There are a few important points to note here.

When you pass an array into a function, you will loose size information i.e, how many elements it contains or it can contain. This is because it decays into a pointer. So how do we fix this? There are a couple of ways,

pass the size information in the function, like we passed total

Use an std::vector (when you don't know how many elements the user will enter). std::vector is a dynamic array, it will grow as required. If you know the number of elements beforehand, you can use std::array

A few problems with your code:

using namespace std;

Don't do this. Instead if you want something out of std, for e.g., cout you can do:

```<code>using std::cout
using std::cin
...
</code>```

or you can just write std::cout everytime.

```<code>    int n, i;
    float num[100], sum=0.0, average;
</code>```

Always initialize your variables before you use them. If you don't know the value they should be initialized to, just default initialize using {};

```<code>    int n{}, i{};
    float num[100]{}, sum=0.0, average{};
</code>```

It is not mandatory, but good practice to declare variables on separate lines. This makes your code more readable.

Body:
Program in C++ that takes 3 numbers and send them to a function and then calculate the average function of these 3 numbers.

I know how to do that without using a function ,for example for any n numbers I have the following program:

#include<stdio.h>

int main()
{

    int n, i;
    float sum = 0, x;

    printf("Enter number of elements:  ");
    scanf("%d", &n);
    printf("\n\n\nEnter %d elements\n\n", n);
    for(i = 0; i < n; i++)
    {
        scanf("%f", &x);
        sum += x;
    }
    printf("\n\n\nAverage of the entered numbers is =  %f", (sum/n));

    return 0;
}

Or this one which do that using arrays:

#include <iostream>
using namespace std;

int main()
{
    int n, i;
    float num[100], sum=0.0, average;

    cout << "Enter the numbers of data: ";
    cin >> n;

    while (n > 100 || n <= 0)
    {
        cout << "Error! number should in range of (1 to 100)." << endl;
        cout << "Enter the number again: ";
        cin >> n;
    }

    for(i = 0; i < n; ++i)
    {
        cout << i + 1 << ". Enter number: ";
        cin >> num[i];
        sum += num[i];
    }

    average = sum / n;
    cout << "Average = " << average;

    return 0;
}

But is it possible to use functions?if yes then how? thank you so much for helping.

Body:
how to do that without using a function

Quite simple. Just put your code in a function, let's call it calculateAverage and return the average value from it. What should this function take as input?

The list of numbers (array of numbers)

Total numbers (n)

So let's first get the input from the user and put it into the array, you have already done it:

    for(int i = 0; i < n; ++i)
    {
        cout << i + 1 << ". Enter number: ";
        cin >> num[i];
    }

Now, lets make a small function i.e., calculateAverage():

int calculateAverage(int numbers[], int total)
{
    int sum = 0; // always initialize your variables
    for(int i = 0; i < total; ++i)
    {
        sum += numbers[i];
    }

    const int average = sum / total; // it is constant and should never change
                                     // so we qualify it as 'const'
    //return this value
    return average
}

There are a few important points to note here.

When you pass an array into a function, you will loose size information i.e, how many elements it contains or it can contain. This is because it decays into a pointer. So how do we fix this? There are a couple of ways,

pass the size information in the function, like we passed total

Use an std::vector (when you don't know how many elements the user will enter). std::vector is a dynamic array, it will grow as required. If you know the number of elements beforehand, you can use std::array

A few problems with your code:

using namespace std;

Don't do this. Instead if you want something out of std, for e.g., cout you can do:

using std::cout
using std::cin
...

or you can just write std::cout everytime.

    int n, i;
    float num[100], sum=0.0, average;

Always initialize your variables before you use them. If you don't know the value they should be initialized to, just default initialize using {};

    int n{}, i{};
    float num[100]{}, sum=0.0, average{};

It is not mandatory, but good practice to declare variables on separate lines. This makes your code more readable.


问:
Remote Certificate error in Azure Function App logs
I am having the function app in azure which reads the excel file of a particular column named "LoanNumber" when uploaded to Azure blob Storage and call node API with the following body, whenever an excel file has a column named "LoanNumber"

```<code>{
  status: "success"
}
</code>```

, but when it didn't find the particular column name "LoanNumber" (i.e when function app reading an uploaded file from azure blog storage) it updates the node API with the request body  as

```<code>{
 status: "failed"
}
</code>```

the functionality is working fine when excel file as column name "LoanNumber", When I upload an invalid file it is not working, but when I monitored the logs of Function App. There is an error, which is mentioned below.

The remote certificate is invalid according to the validation procedure.
when I uploaded invalid file

Due to this, the API is not calling

I have no clue about this. Please help me to solve this error.

答:
From the error message, you may check if the SSL certificate is invalid or expired in the TLS/SSL settings of the Azure function app.

For more information, you could read this document---Use a TLS/SSL certificate in your code in Azure App Service

Body:
I am having the function app in azure which reads the excel file of a particular column named "LoanNumber" when uploaded to Azure blob Storage and call node API with the following body, whenever an excel file has a column named "LoanNumber"

{
  status: "success"
}

, but when it didn't find the particular column name "LoanNumber" (i.e when function app reading an uploaded file from azure blog storage) it updates the node API with the request body  as

{
 status: "failed"
}

the functionality is working fine when excel file as column name "LoanNumber", When I upload an invalid file it is not working, but when I monitored the logs of Function App. There is an error, which is mentioned below.

The remote certificate is invalid according to the validation procedure.
when I uploaded invalid file

Due to this, the API is not calling

I have no clue about this. Please help me to solve this error.


问:
Why do we need setRollbackOnly, not just rollback the transaction?
When I use @Transactional in my project, I set timeout to 60 seconds.
But after the process ran more than 60 seconds, the transaction didn't roll back immediately, it just called setRollbackOnly() method to mark the transaction as roll back only and when transaction tried to commit it detected the roll back only mark and roll back.

I am wondering why do we need setRollbackOnly()? Why don't we just call rollback() ?
Is this the design of JTA?

答:
Actually rollback will invoke when something went wrong in current transaction(i.e Some exceptions).
Here you are setting timeout 60 sec manually.

Case 1: If Transaction execute within time, then it commits.

Case 2: If Transaction went wrong due to some exceptions within time, then it will call directly rollback();

Case 3: If transaction not completed within time, it set one flag setRollbackOnly().

After this also transaction will execute, Even transaction successful after 60 sec it won't commit because there is setRollbackOnly() flag.


问:
swift Convert dictionary to jsonString error : Protocol type 'Any' cannot conform to 'Encodable' because only concrete types can conform to protocols
I have a dictionary and I want to convert to jsonstring.

Protocol type 'Any' cannot conform to 'Encodable' because only concrete types can conform to protocols
  How to fix it? Thanks.

```<code>func save(body: [String: Any]) -> Void {

    let encoder = JSONEncoder()
    if let jsonData = try? encoder.encode(body) { //error here.
        if let jsonString = String(data: jsonData, encoding: .utf8) {
            print(jsonString)
        }
    }
}
</code>```

答:
You need to give the body type something that conforms to Codable. To fix this issue create another struct that conforms to Codable and change the type of body variable to it.

Here's an example:

struct Body: Codable {
// all the properties you require can be added here.
}

func save(body: Body) -> Void {

    let encoder = JSONEncoder()
    if let jsonData = try? encoder.encode(body) {
        if let jsonString = String(data: jsonData, encoding: .utf8) {
            print(jsonString)
        }
    }
}
```

<p>Or you can use JSONSerialisation like this:</p>

<pre class="lang-swift prettyprint-override"><code>func save(body: [String: Any]) -> Void {

    if let jsonData = try? JSONSerialization.data(withJSONObject: body, options: .prettyPrinted) {
        if let jsonString = String(data: jsonData, encoding: .utf8) {
            print(jsonString)
        }
    }
}
</code>```

Body:
I have a dictionary and I want to convert to jsonstring.

Protocol type 'Any' cannot conform to 'Encodable' because only concrete types can conform to protocols
  How to fix it? Thanks.

func save(body: [String: Any]) -> Void {

    let encoder = JSONEncoder()
    if let jsonData = try? encoder.encode(body) { //error here.
        if let jsonString = String(data: jsonData, encoding: .utf8) {
            print(jsonString)
        }
    }
}

Body:
You need to give the body type something that conforms to Codable. To fix this issue create another struct that conforms to Codable and change the type of body variable to it.

Here's an example:

struct Body: Codable {
// all the properties you require can be added here.
}

func save(body: Body) -> Void {

    let encoder = JSONEncoder()
    if let jsonData = try? encoder.encode(body) {
        if let jsonString = String(data: jsonData, encoding: .utf8) {
            print(jsonString)
        }
    }
}

Or you can use JSONSerialisation like this:

func save(body: [String: Any]) -> Void {

    if let jsonData = try? JSONSerialization.data(withJSONObject: body, options: .prettyPrinted) {
        if let jsonString = String(data: jsonData, encoding: .utf8) {
            print(jsonString)
        }
    }
}


问:
I keep getting this error in CSS and I don't know why
I keep getting this error in css. This screenshot is on dreamweaver. I have also tried on brackets and codesandbox. Nothing seems to be working.

enter image description here

答:
To answer your question you are using a valid SASS or SCSS with nested classes in a .css file and hence the error is shown. You can use this link to convert SASS to CSS: SassMeister

The equivalent css would be:

```<code>header {
  display: flex;
  height: 140px;
  background-color: #A7ACB1;
}
header nav {
  flex: l;
}
header nav ul {
  list-style: none;
  margin: 0;
  padding: 0;
}
</code>```

Please use "code samples" in the editor to post your questions for the code snippet going forward.

Body:
To answer your question you are using a valid SASS or SCSS with nested classes in a .css file and hence the error is shown. You can use this link to convert SASS to CSS: SassMeister

The equivalent css would be:

header {
  display: flex;
  height: 140px;
  background-color: #A7ACB1;
}
header nav {
  flex: l;
}
header nav ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

Please use "code samples" in the editor to post your questions for the code snippet going forward.


问:
Opposite of SetFocus
MSAccess VBA:
Assume, in an arbitrary form, the focus is set to MyControl on that form.
How to "unset" the focus without giving the focus to another control?

I'm lokking for a code like
MyControl.UnsetFocus

答:
In your circumstance, you probably want to just set focus back to the parent form. This meets the conditions of unsetting focus without giving another control focus, and tabbing or clicking will activate the focus / tab-navigation again from that form.

Here's an example:

```<code>Forms![MyForm].SetFocus
</code>```

Note that per the documentation for SetFocus, if you attempt to SetFocus to a Form with child controls that have Enabled set, this will cause focus to automatically bounce to the first eligible child control per the documentation.

Form.SetFocus method (Access) @ Microsoft Docs

Title: Opposite of SetFocus

Body:
In your circumstance, you probably want to just set focus back to the parent form. This meets the conditions of unsetting focus without giving another control focus, and tabbing or clicking will activate the focus / tab-navigation again from that form.

Here's an example:

Forms![MyForm].SetFocus

Note that per the documentation for SetFocus, if you attempt to SetFocus to a Form with child controls that have Enabled set, this will cause focus to automatically bounce to the first eligible child control per the documentation.

Form.SetFocus method (Access) @ Microsoft Docs


问:
Passing multiple variable to Redux Action creator. What format?
I am pretty new to Redux but I am getting a good hang of it so far.
I am setting up an actions file and I would need to pass two values to payload.

Please let me know if the question has already been asked elsewhere and I missed it.

Thanks!
kramnic

p.s. below is what I have drafted

    export const transferValues = (fromId, toId) => {
      return {
        type: VALUES_TRANSFER,
        payload: { fromId, toId }, //should it be array? not sure about syntax here
      };
    };
```

答:
you can also have an action of type { type: string, fromId: number, toId: number } instead of a single "payload". that's a matther of preference I think. you just need to adapt you reducers accordingly. I personally like the above attempt more because it represents single attributes like I have them in my state as well. so I can do like a one-to-one mapping. for example:

// state
export type SessionState = {
  +id: number,
  +username: string,
  +sessionId: string,
}

// reducer here
[...]
    case SET_USERNAME:
      const setUsernameAction = ((action: any): SetUsernameAction)

      return {
        ...state,
        username: setUsernameAction.username,
        sessionId: setUsernameAction.sessionId,
      }
[...]

// example action
export const setUsername = (username: string, sessionId: string): SetUsernameAction => {
  return { type: SET_USERNAME, username, sessionId }
}

```

but you will certainly never use an array for multiple attributes. you'll lose the named access to properties as well as any chance to type your action. stick with objects, no matther what solution you'll go for.

Body:
you can also have an action of type { type: string, fromId: number, toId: number } instead of a single "payload". that's a matther of preference I think. you just need to adapt you reducers accordingly. I personally like the above attempt more because it represents single attributes like I have them in my state as well. so I can do like a one-to-one mapping. for example:

// state
export type SessionState = {
  +id: number,
  +username: string,
  +sessionId: string,
}

// reducer here
[...]
    case SET_USERNAME:
      const setUsernameAction = ((action: any): SetUsernameAction)

      return {
        ...state,
        username: setUsernameAction.username,
        sessionId: setUsernameAction.sessionId,
      }
[...]

// example action
export const setUsername = (username: string, sessionId: string): SetUsernameAction => {
  return { type: SET_USERNAME, username, sessionId }
}

but you will certainly never use an array for multiple attributes. you'll lose the named access to properties as well as any chance to type your action. stick with objects, no matther what solution you'll go for.


问:
Encoding Error in Json file when copied from Sharepoint to Azure Blob Storage
I have a json file in sharepoint and I am using Logic Apps to get the json file and dump it into blob storage. Further I need to open that json file in Databricks python using this code

```<code>blobstring = blob_service.get_blob_to_bytes(INPUTCONTAINERNAME, INPUTFILEPATH)
myJson = blobstring.decode('utf8')
data = json.loads(myJson)
</code>```

When I try to open json in python it gives me the following error:

```<code>JSONDecodeError: Unexpected UTF-8 BOM (decode using utf-8-sig)
</code>```

After using the "utf-8-sig" as decode I get this error

```<code>JSONDecodeError: Unterminated string starting at: line 1 column 103775708
</code>```

IMPORTANT: When logic app dumps the json from sharepoint on blob, lease state is expired on the blob storage. I downloaded the json from blob and uploaded the same file manually (it made the lease state available) and the python code opened the json perfectly.

I thought it was an issue with lease state so after logic app dumped the json on blob, I made the lease state available with code (so I don't have to download and upload again manually) and tried to open json but received the same errors again.

In my logic app I am using the get file content for getting the file content of the .json file and create blob for creating a blob with the file content.

Can anybody point me in the right direction?

答:
It seems your storage blob has some setting which caused the lease state to expired, the lease state will become "expired" just after acquire the lease. I test it in my logic app(get a file from sharepoint and create blob), its lease state is "available".

And it works fine when I want to get this file in code.

Body:
I have a json file in sharepoint and I am using Logic Apps to get the json file and dump it into blob storage. Further I need to open that json file in Databricks python using this code

blobstring = blob_service.get_blob_to_bytes(INPUTCONTAINERNAME, INPUTFILEPATH)
myJson = blobstring.decode('utf8')
data = json.loads(myJson)

When I try to open json in python it gives me the following error:

JSONDecodeError: Unexpected UTF-8 BOM (decode using utf-8-sig)

After using the "utf-8-sig" as decode I get this error

JSONDecodeError: Unterminated string starting at: line 1 column 103775708

IMPORTANT: When logic app dumps the json from sharepoint on blob, lease state is expired on the blob storage. I downloaded the json from blob and uploaded the same file manually (it made the lease state available) and the python code opened the json perfectly.

I thought it was an issue with lease state so after logic app dumped the json on blob, I made the lease state available with code (so I don't have to download and upload again manually) and tried to open json but received the same errors again.

In my logic app I am using the get file content for getting the file content of the .json file and create blob for creating a blob with the file content.

Can anybody point me in the right direction?


问:
Flutter :how to call function in statelesswidget?
I want to show a list of data with list view and JSON. This code in a file with stateless widget. And this page opened after login. When I try in stateful widget, the code RUN normally. In stateless widget, when I debug it, the code didn't call function getData(). But directly went to

```<code>Widget build(BuildContext context) {
     return new Scaffold( ...
</code>```

Here is complete code :

```<code>class frmClass extends StatelessWidget{
  List<dynamic> dta;
  get setState => null;

  Future<String> getData() async {
      var uri ='https://xxxx.com/class';
      var map = new Map<String, dynamic>();
      map["username"] = "abc";
      map["password"] = "1234";

      http.Response response = await http.post(
        uri,
        body: jsonEncode(map),
      );

      Map<String,dynamic> mp = jsonDecode(utf8.decode(response.bodyBytes));
      this.setState(() {
        dta = mp["data"];
        debugPrint(dta.toString());
      });

    }

  @override
  void initState(){
    this.getData();
  }

  @override
  Widget build(BuildContext context) {

     return new Scaffold(
       appBar: new AppBar(
           backgroundColor:Colors.transparent,
           elevation: 0.0,
           iconTheme: new IconThemeData(color: Color(0xFF18D191))),
       body: new ListView.builder(
           itemCount: dta == null ? 0 : dta.length,
           itemBuilder: (BuildContext context, int index){
             return new Card(
               child: new Text(dta[index]["className"]),
             );
           }
       ),
     );
  }
}
</code>```

How can I fix it?

答:
This is happening because stateless widgets don't have initState that's why the below code will never get called. Stateless widgets are more sort of rendering flat UI with no lifecycle methods if you want to use Stateless widget then pass data in the class constructor and use it where ever you want

```<code> @override
  void initState(){
    this.getData();
  }
</code>```

Body:
I want to show a list of data with list view and JSON. This code in a file with stateless widget. And this page opened after login. When I try in stateful widget, the code RUN normally. In stateless widget, when I debug it, the code didn't call function getData(). But directly went to

Widget build(BuildContext context) {
     return new Scaffold( ...

Here is complete code :

class frmClass extends StatelessWidget{
  List<dynamic> dta;
  get setState => null;

  Future<String> getData() async {
      var uri ='https://xxxx.com/class';
      var map = new Map<String, dynamic>();
      map["username"] = "abc";
      map["password"] = "1234";

      http.Response response = await http.post(
        uri,
        body: jsonEncode(map),
      );

      Map<String,dynamic> mp = jsonDecode(utf8.decode(response.bodyBytes));
      this.setState(() {
        dta = mp["data"];
        debugPrint(dta.toString());
      });

    }

  @override
  void initState(){
    this.getData();
  }

  @override
  Widget build(BuildContext context) {

     return new Scaffold(
       appBar: new AppBar(
           backgroundColor:Colors.transparent,
           elevation: 0.0,
           iconTheme: new IconThemeData(color: Color(0xFF18D191))),
       body: new ListView.builder(
           itemCount: dta == null ? 0 : dta.length,
           itemBuilder: (BuildContext context, int index){
             return new Card(
               child: new Text(dta[index]["className"]),
             );
           }
       ),
     );
  }
}

How can I fix it?

Body:
This is happening because stateless widgets don't have initState that's why the below code will never get called. Stateless widgets are more sort of rendering flat UI with no lifecycle methods if you want to use Stateless widget then pass data in the class constructor and use it where ever you want

 @override
  void initState(){
    this.getData();
  }


问:
Issue running terminal commands through jupyter notebook
I am currently running a jupyter notebook from a github repo. One chunk goes like this:

```<code>for file in os.listdir('data/'):
    path = 'data/' + file

    os.system(f"python OpticalFlowGen.py --type {target} --file {path}")
</code>```

The variables target and path were defined and no errors were raised.

When the OpticalFlowGen.py file is run on the terminal with python OpticalFlowGen.py ---type 'Train' -- file 'data/video.mp4', a popup appears and closes after the video file is processed by openCV and .jpg files will be saved in the system. However, when this command is run on the jupyter notebook, nothing pops up and no files are saved. You can access this .py file from the same repository here.

Currently I have to run manually on the terminal file by file so save all the image output before I can run the notebook without error. However, it will become an issue when I have too many video files, not using the for loop will be too cumbersome. Any idea on how to solve this issue?

答:
In a Jupyter Notebook you don't have to use os.system, instead try to use !:

for file in os.listdir('data/'):
    path = 'data/' + file

    # Use
    # ! - for terminal commands
    # {} - for a variable in the terminal command
    !python OpticalFlowGen.py --type {target} --file {path}
```

Body:
I am currently running a jupyter notebook from a github repo. One chunk goes like this:

for file in os.listdir('data/'):
    path = 'data/' + file

    os.system(f"python OpticalFlowGen.py --type {target} --file {path}")

The variables target and path were defined and no errors were raised.

When the OpticalFlowGen.py file is run on the terminal with python OpticalFlowGen.py ---type 'Train' -- file 'data/video.mp4', a popup appears and closes after the video file is processed by openCV and .jpg files will be saved in the system. However, when this command is run on the jupyter notebook, nothing pops up and no files are saved. You can access this .py file from the same repository here.

Currently I have to run manually on the terminal file by file so save all the image output before I can run the notebook without error. However, it will become an issue when I have too many video files, not using the for loop will be too cumbersome. Any idea on how to solve this issue?


问:
Gracefully stopping an std::thread?
I have a worker std::thread and I want its main loop to check if some other thread tells it to stop looping and exit.

What is a good cross platform way to do this? Does boost provide some event object for it?

Is using just a bool considered thread-safe?

答:
As you mentioned boost, there is boost::thread you can use.

In your case, after starting a thread, you could interrupt it by using the interrupt() method. The receiver thread can check for interrupt requests with the boost::this_thread::interruption_point() method. This will cause the thread to exit if there is an interruption request, otherwise, it will ignore it.

You can check the documentation here:
Boost Thread Documentation

Title: Gracefully stopping an std::thread?


问:
Implementing a barcode scanner in Angular 4
I am trying to implement a barcode scanner using Angular 4, using this plugin - https://github.com/isonet/angular-barcode-scanner.

In my scanner.component.ts page I have;

```<code>    import { Component, OnInit} from '@angular/core';
    import 'angular-barcode-scanner';
...
</code>```

In my app.module.ts file;

```<code>  ....
import { BarcodeScanner} from 'angular-barcode-scanner';

    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        RouterModule.forRoot(routes),
        LoginModule,
        SignupModule,
        DashboardModule,
        ReactiveFormsModule,
        BarcodeScanner
      ],
      providers: [
        DataService,
        TokenService
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
</code>```

And then in my scanner.component.html file;

```<code><barcode-scanner separator-char="separatorChar" trigger-char="triggerChar" scan-callback="scanCallback"
                trigger-callback="triggerCallback"></barcode-scanner>
        </div>
    </div>
</code>```

However, I get the following errors in console

```<code>Uncaught ReferenceError: angular is not defined
    at Object.defineProperty.value (angular-barcode-scanner.js:1)
    at r (angular-barcode-scanner.js:1)
    at Object.defineProperty.value (angular-barcode-scanner.js:1)
    at angular-barcode-scanner.js:1
    at t (angular-barcode-scanner.js:1)
    at Object.<anonymous> (angular-barcode-scanner.js:1)
    at __webpack_require__ (bootstrap 0689b0e…:52)
    at Object.152 (bsElement.routes.ts:9)
    at __webpack_require__ (bootstrap 0689b0e…:52)
    at Object.413 (chart.module.ts:12)
    at __webpack_require__ (bootstrap 0689b0e…:52)
    at Object.153 (chart.component.ts:11)
    at __webpack_require__ (bootstrap 0689b0e…:52)
    at Object.155 (dashboard.component.ts:12)
    at __webpack_require__ (bootstrap 0689b0e…:52)
Object.defineProperty.value @ angular-barcode-scanner.js:1
r @ angular-barcode-scanner.js:1
Object.defineProperty.value @ angular-barcode-scanner.js:1
(anonymous) @ angular-barcode-scanner.js:1
t @ angular-barcode-scanner.js:1
(anonymous) @ angular-barcode-scanner.js:1
__webpack_require__ @ bootstrap 0689b0e…:52
152 @ bsElement.routes.ts:9
__webpack_require__ @ bootstrap 0689b0e…:52
413 @ chart.module.ts:12
__webpack_require__ @ bootstrap 0689b0e…:52
153 @ chart.component.ts:11
__webpack_require__ @ bootstrap 0689b0e…:52
155 @ dashboard.component.ts:12
__webpack_require__ @ bootstrap 0689b0e…:52
405 @ app.module.ts:40
__webpack_require__ @ bootstrap 0689b0e…:52
404 @ main.ts:12
__webpack_require__ @ bootstrap 0689b0e…:52
424 @ table.module.ts:12
__webpack_require__ @ bootstrap 0689b0e…:52
393 @ src async:7
__webpack_require__ @ bootstrap 0689b0e…:52
733 @ main.bundle.js:2545
__webpack_require__ @ bootstrap 0689b0e…:52
webpackJsonpCallback @ bootstrap 0689b0e…:23
(anonymous) @ main.bundle.js:1
bundle.js:19 Uncaught ReferenceError: ng is not defined
    at N (bundle.js:19)
    at VueComponent.ready (bundle.js:15)
    at VueComponent.LN.M._callHook (bundle.js:5)
    at VueComponent.z (bundle.js:5)
    at VueComponent.N (bundle.js:5)
    at VueComponent.M.$emit (bundle.js:5)
    at VueComponent.LN.M._callHook (bundle.js:5)
    at z (bundle.js:5)
    at VueComponent.M.$before (bundle.js:5)
    at CN.transition (bundle.js:6)
    at CN.mountComponent (bundle.js:6)
    at bundle.js:6
    at bundle.js:6
    at N (bundle.js:4)
    at ON.QN.M._resolveComponent (bundle.js:5)
N @ bundle.js:19
ready @ bundle.js:15
LN.M._callHook @ bundle.js:5
z @ bundle.js:5
N @ bundle.js:5
M.$emit @ bundle.js:5
LN.M._callHook @ bundle.js:5
z @ bundle.js:5
M.$before @ bundle.js:5
transition @ bundle.js:6
mountComponent @ bundle.js:6
(anonymous) @ bundle.js:6
(anonymous) @ bundle.js:6
N @ bundle.js:4
QN.M._resolveComponent @ bundle.js:5
resolveComponent @ bundle.js:6
setComponent @ bundle.js:6
bind @ bundle.js:6
CN._bind @ bundle.js:6
Gz @ bundle.js:4
(anonymous) @ bundle.js:4
M._compile @ bundle.js:5
M.$mount @ bundle.js:5
M._init @ bundle.js:4
Y.M._init @ bundle.js:19
ON @ bundle.js:5
(anonymous) @ bundle.js:3
zone.js:155 Uncaught TypeError: Cannot read property 'geAdapter' of undefined
    at WebSocket._ws.onopen (eval at M.exports (bundle.js:3), <anonymous>:97:46)
    at WebSocket.wrapFn [as _onopen] (zone.js:851)
    at ZoneDelegate.invokeTask (zone.js:262)
    at Zone.runTask (zone.js:151)
    at WebSocket.ZoneTask.invoke (zone.js:332)
_ws.onopen @ VM53541:97
wrapFn @ zone.js:851
ZoneDelegate.invokeTask @ zone.js:262
Zone.runTask @ zone.js:151
ZoneTask.invoke @ zone.js:332
</code>```

Any help is appreciated.

答: Chrome has released the Shape Detection API in their version 83 and this includes the Barcode Detector API. So if you are only focused on Chrome users, like in my case, I would suggest the ng-barcode-detector package.</p>

Body:
I am trying to implement a barcode scanner using Angular 4, using this plugin - https://github.com/isonet/angular-barcode-scanner.

In my scanner.component.ts page I have;

    import { Component, OnInit} from '@angular/core';
    import 'angular-barcode-scanner';
...

In my app.module.ts file;

  ....
import { BarcodeScanner} from 'angular-barcode-scanner';

    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        RouterModule.forRoot(routes),
        LoginModule,
        SignupModule,
        DashboardModule,
        ReactiveFormsModule,
        BarcodeScanner
      ],
      providers: [
        DataService,
        TokenService
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

And then in my scanner.component.html file;

<barcode-scanner separator-char="separatorChar" trigger-char="triggerChar" scan-callback="scanCallback"
                trigger-callback="triggerCallback"></barcode-scanner>

However, I get the following errors in console

Uncaught ReferenceError: angular is not defined
    at Object.defineProperty.value (angular-barcode-scanner.js:1)
    at r (angular-barcode-scanner.js:1)
    at Object.defineProperty.value (angular-barcode-scanner.js:1)
    at angular-barcode-scanner.js:1
    at t (angular-barcode-scanner.js:1)
    at Object.<anonymous> (angular-barcode-scanner.js:1)
    at __webpack_require__ (bootstrap 0689b0e…:52)
    at Object.152 (bsElement.routes.ts:9)
    at __webpack_require__ (bootstrap 0689b0e…:52)
    at Object.413 (chart.module.ts:12)
    at __webpack_require__ (bootstrap 0689b0e…:52)
    at Object.153 (chart.component.ts:11)
    at __webpack_require__ (bootstrap 0689b0e…:52)
    at Object.155 (dashboard.component.ts:12)
    at __webpack_require__ (bootstrap 0689b0e…:52)
Object.defineProperty.value @ angular-barcode-scanner.js:1
r @ angular-barcode-scanner.js:1
Object.defineProperty.value @ angular-barcode-scanner.js:1
(anonymous) @ angular-barcode-scanner.js:1
t @ angular-barcode-scanner.js:1
(anonymous) @ angular-barcode-scanner.js:1
__webpack_require__ @ bootstrap 0689b0e…:52
152 @ bsElement.routes.ts:9
__webpack_require__ @ bootstrap 0689b0e…:52
413 @ chart.module.ts:12
__webpack_require__ @ bootstrap 0689b0e…:52
153 @ chart.component.ts:11
__webpack_require__ @ bootstrap 0689b0e…:52
155 @ dashboard.component.ts:12
__webpack_require__ @ bootstrap 0689b0e…:52
405 @ app.module.ts:40
__webpack_require__ @ bootstrap 0689b0e…:52
404 @ main.ts:12
__webpack_require__ @ bootstrap 0689b0e…:52
424 @ table.module.ts:12
__webpack_require__ @ bootstrap 0689b0e…:52
393 @ src async:7
__webpack_require__ @ bootstrap 0689b0e…:52
733 @ main.bundle.js:2545
__webpack_require__ @ bootstrap 0689b0e…:52
webpackJsonpCallback @ bootstrap 0689b0e…:23
(anonymous) @ main.bundle.js:1
bundle.js:19 Uncaught ReferenceError: ng is not defined
    at N (bundle.js:19)
    at VueComponent.ready (bundle.js:15)
    at VueComponent.LN.M._callHook (bundle.js:5)
    at VueComponent.z (bundle.js:5)
    at VueComponent.N (bundle.js:5)
    at VueComponent.M.$emit (bundle.js:5)
    at VueComponent.LN.M._callHook (bundle.js:5)
    at z (bundle.js:5)
    at VueComponent.M.$before (bundle.js:5)
    at CN.transition (bundle.js:6)
    at CN.mountComponent (bundle.js:6)
    at bundle.js:6
    at bundle.js:6
    at N (bundle.js:4)
    at ON.QN.M._resolveComponent (bundle.js:5)
N @ bundle.js:19
ready @ bundle.js:15
LN.M._callHook @ bundle.js:5
z @ bundle.js:5
N @ bundle.js:5
M.$emit @ bundle.js:5
LN.M._callHook @ bundle.js:5
z @ bundle.js:5
M.$before @ bundle.js:5
transition @ bundle.js:6
mountComponent @ bundle.js:6
(anonymous) @ bundle.js:6
(anonymous) @ bundle.js:6
N @ bundle.js:4
QN.M._resolveComponent @ bundle.js:5
resolveComponent @ bundle.js:6
setComponent @ bundle.js:6
bind @ bundle.js:6
CN._bind @ bundle.js:6
Gz @ bundle.js:4
(anonymous) @ bundle.js:4
M._compile @ bundle.js:5
M.$mount @ bundle.js:5
M._init @ bundle.js:4
Y.M._init @ bundle.js:19
ON @ bundle.js:5
(anonymous) @ bundle.js:3
zone.js:155 Uncaught TypeError: Cannot read property 'geAdapter' of undefined
    at WebSocket._ws.onopen (eval at M.exports (bundle.js:3), <anonymous>:97:46)
    at WebSocket.wrapFn [as _onopen] (zone.js:851)
    at ZoneDelegate.invokeTask (zone.js:262)
    at Zone.runTask (zone.js:151)
    at WebSocket.ZoneTask.invoke (zone.js:332)
_ws.onopen @ VM53541:97
wrapFn @ zone.js:851
ZoneDelegate.invokeTask @ zone.js:262
Zone.runTask @ zone.js:151
ZoneTask.invoke @ zone.js:332

Any help is appreciated.


问:
Is it possible update multiple templates from controller in Thymeleaf?
I am using Thymeleaf in a project.

The point is, when controller is called I want to return two templates, one containing the response and another one containing the new data to display. So, update two fragments.

Controller code is as follows:

```<code>@GetMapping("/...")
public String multiTemplate(...){
  // do things

  return "resultsTemplate :: fragment1" && return "responseTemplate :: fragment2" <---- how?

}
</code>```

To be clearer, for example you have a list of objects and you can filter them. When you filter, your backend receives code 200 and the new list, so the front end will show "search successful" and will update the list.

Now with two different calls I can return one thing or another, but I want to know if it is possible to return two templates at the same time.

Thanks.

答:
You should use this one return top fragment from the controller</p>
```<code><div th:fragment=top>
  <div th:fragment=first>
  </div>
  <div th:fragment=second>
  </div>
</div>
</code>```

Body:
I am using Thymeleaf in a project.

The point is, when controller is called I want to return two templates, one containing the response and another one containing the new data to display. So, update two fragments.

Controller code is as follows:

@GetMapping("/...")
public String multiTemplate(...){
  // do things

  return "resultsTemplate :: fragment1" && return "responseTemplate :: fragment2" <---- how?

}

To be clearer, for example you have a list of objects and you can filter them. When you filter, your backend receives code 200 and the new list, so the front end will show "search successful" and will update the list.

Now with two different calls I can return one thing or another, but I want to know if it is possible to return two templates at the same time.

Thanks.

Body:
You should use this one return top fragment from the controller

<div th:fragment=top>
  <div th:fragment=first>
  </div>
  <div th:fragment=second>
  </div>
</div>


问:
Create multiple possible email addresses based on names in Python
Given a dataframe as follows:

```<code>  firstname   lastname                     email_address  \
0      Doug     Watson  douglas.watson@dignityhealth.org
1      Nick   Holekamp    nick.holekamp@rankenjordan.org
2       Rob  Schreiner        rob.schriener@wellstar.org
3    Austin   Phillips       austin.phillips@precmed.com
4     Elise     Geiger               egeiger@puracap.com
5      Paul      Urick       purick@diplomatpharmacy.com
6   Michael   Obringer    michael.obringer@lashgroup.com
7     Craig   Heneghan           cheneghan@west-ward.com
8     Kathy      Hirst       kathleen.hirst@sunovion.com
9    Stefan  Bluemmers   stefan.bluemmers@grunenthal.com

                               companyname
0                           Dignity Health
1  Ranken Jordan Pediatric Bridge Hospital
2                   WellStar Health System
3         Precision Medical Products, Inc.
4                              puracap.com
5              Diplomat Specialty Pharmacy
6                               Lash Group
7                West-Ward Pharmaceuticals
8                 Sunovion Pharmaceuticals
9                         Grünenthal Group
</code>```

How could I create possible email addresses using common email patterns as such: firstlast@example.com, first.last@example.com, f.last@example.com, lastF@example.com, first_last@example.com, firstL@example.com, etc.

```<code>df['email1'] = df.firstname.str.lower() + '.' + df.lastname.str.lower() + '@' + df.companyname.str.replace('\s+', '').str.lower() + '.com'
print(df['email1'])
</code>```

Out:

```<code>0                           doug.watson@dignityhealth.com
1       nick.holekamp@rankenjordanpediatricbridgehospi...  --->problematic
2                  rob.schreiner@wellstarhealthsystem.com
3       austin.phillips@precisionmedicalproducts,inc..com  --->problematic
4                            elise.geiger@puracap.com.com  --->problematic
                              ...
9995              terry.hanley@kempersportsmanagement.com
9996                          christine.marks@geocomp.com
9997                               darryl.rickner@doe.com
9998                     lalit.sharma@lovelylifestyle.com
9999                              parul.dutt@infibeam.com
</code>```

Some of them seems quite problematic, anyone could help to solve this issue? Thanks a lot.

EDITED:

print(df) after applying @Sajith Herath's solution:

Out:

```<code>  firstname  lastname                                        companyname  \
0      Nick  Holekamp  Ranken                                        ...

                                               email
0                       nick.                    ...
</code>```

答:
You can use a method to create permutations of username with different separators and define a max length that simplify the domain using company name as follows

```<code>import pandas as pd
import random

data = {"firstname":["Nick"],"lastname":["Holekamp"],"companyname":["Ranken \
                                        Jordan Pediatric Bridge Hospital"]}
df = pd.DataFrame(data=data)

max_char = 5
emails = []

def simplify_domain(text):
    if len(text)>max_char:
        text = ''.join([c for c in text if c.isupper()])
        return text.lower()
    return text.replace("\s+","").lower()

def username_permutations(first_name,last_name):
  # define separators
  separators = [".", "_", "-"]
  #lower case
  combinations = list(map(lambda x:f"{first_name.lower()}{x} \
                           {last_name.lower()}",separators))

  #append a random number to tail
  n = random.randint(1, 100)
  combinations.extend(list(map(lambda x:f"{x}{n}",combinations)))
  return combinations

for index,row in df.iterrows():
    usernames = username_permutations(row["firstname"],row["lastname"])
    email_permutations = list(map(lambda x: f" \
                    {x}@{simplify_domain(row['companyname'])}.com",usernames))
    emails.append(','.join(email_permutations))

df["email"] = emails
</code>```

Final result will be nick.holekamp@rjpbh.com,nick_holekamp@rjpbh.com,nick-holekamp@rjpbh.com,nick.holekamp66@rjpbh.com,nick_holekamp66@rjpbh.com,nick-holekamp66@rjpbh.com

you can modify simplify_domain method to validate given string such as removing inc or .com values

Body:
Given a dataframe as follows:

  firstname   lastname                     email_address  \
0      Doug     Watson  douglas.watson@dignityhealth.org
1      Nick   Holekamp    nick.holekamp@rankenjordan.org
2       Rob  Schreiner        rob.schriener@wellstar.org
3    Austin   Phillips       austin.phillips@precmed.com
4     Elise     Geiger               egeiger@puracap.com
5      Paul      Urick       purick@diplomatpharmacy.com
6   Michael   Obringer    michael.obringer@lashgroup.com
7     Craig   Heneghan           cheneghan@west-ward.com
8     Kathy      Hirst       kathleen.hirst@sunovion.com
9    Stefan  Bluemmers   stefan.bluemmers@grunenthal.com

                               companyname
0                           Dignity Health
1  Ranken Jordan Pediatric Bridge Hospital
2                   WellStar Health System
3         Precision Medical Products, Inc.
4                              puracap.com
5              Diplomat Specialty Pharmacy
6                               Lash Group
7                West-Ward Pharmaceuticals
8                 Sunovion Pharmaceuticals
9                         Grünenthal Group

How could I create possible email addresses using common email patterns as such: firstlast@example.com, first.last@example.com, f.last@example.com, lastF@example.com, first_last@example.com, firstL@example.com, etc.

df['email1'] = df.firstname.str.lower() + '.' + df.lastname.str.lower() + '@' + df.companyname.str.replace('\s+', '').str.lower() + '.com'
print(df['email1'])

Out:

0                           doug.watson@dignityhealth.com
1       nick.holekamp@rankenjordanpediatricbridgehospi...  --->problematic
2                  rob.schreiner@wellstarhealthsystem.com
3       austin.phillips@precisionmedicalproducts,inc..com  --->problematic
4                            elise.geiger@puracap.com.com  --->problematic
                              ...
9995              terry.hanley@kempersportsmanagement.com
9996                          christine.marks@geocomp.com
9997                               darryl.rickner@doe.com
9998                     lalit.sharma@lovelylifestyle.com
9999                              parul.dutt@infibeam.com

Some of them seems quite problematic, anyone could help to solve this issue? Thanks a lot.

EDITED:

print(df) after applying @Sajith Herath's solution:

Out:

  firstname  lastname                                        companyname  \
0      Nick  Holekamp  Ranken                                        ...

                                               email
0                       nick.                    ...

Body:
You can use a method to create permutations of username with different separators and define a max length that simplify the domain using company name as follows

import pandas as pd
import random

data = {"firstname":["Nick"],"lastname":["Holekamp"],"companyname":["Ranken \
                                        Jordan Pediatric Bridge Hospital"]}
df = pd.DataFrame(data=data)

max_char = 5
emails = []

def simplify_domain(text):
    if len(text)>max_char:
        text = ''.join([c for c in text if c.isupper()])
        return text.lower()
    return text.replace("\s+","").lower()

def username_permutations(first_name,last_name):
  # define separators
  separators = [".", "_", "-"]
  #lower case
  combinations = list(map(lambda x:f"{first_name.lower()}{x} \
                           {last_name.lower()}",separators))

  #append a random number to tail
  n = random.randint(1, 100)
  combinations.extend(list(map(lambda x:f"{x}{n}",combinations)))
  return combinations

for index,row in df.iterrows():
    usernames = username_permutations(row["firstname"],row["lastname"])
    email_permutations = list(map(lambda x: f" \
                    {x}@{simplify_domain(row['companyname'])}.com",usernames))
    emails.append(','.join(email_permutations))

df["email"] = emails

Final result will be nick.holekamp@rjpbh.com,nick_holekamp@rjpbh.com,nick-holekamp@rjpbh.com,nick.holekamp66@rjpbh.com,nick_holekamp66@rjpbh.com,nick-holekamp66@rjpbh.com

you can modify simplify_domain method to validate given string such as removing inc or .com values


问:
Combine records into one?
```<code>CATEGORY     DESC                                       AMOUNT
50200105 Sub Contractor - SLW                             1000
50200205 Sub Contractor - Meal Operator - SLW             0
50200305 Sub Contractor - Garbage - SLW                 2000
</code>```

Result

```<code>CATEGORY                  DESC                            AMOUNT
50200105                Sub Contractor - SLW              3000
</code>```

答:
Lets achieve you output somehow with so many let ;)

let - you are trying to group by results with the last part of value in your column - DESCRIPTION.

Let - you are ok with keeping the MIN value from the CATEGORY column among the group.

Now- try this below query. Just trying to help you somehow :)

```<code>SELECT MIN(CATEGORY) CATEGORY,
'Sub Contractor - '+ TRIM(REVERSE(LEFT(REVERSE(DESCRIPTION), CHARINDEX('-',REVERSE(DESCRIPTION),0)-1))) DESCRIPTION,
SUM(AMOUNT) AMOUNT
FROM your_table
GROUP BY TRIM(REVERSE(LEFT(REVERSE(DESCRIPTION), CHARINDEX('-',REVERSE(DESCRIPTION),0)-1)))
</code>```

Demo Here

Title: Combine records into one?

Body:
CATEGORY     DESC                                       AMOUNT
50200105 Sub Contractor - SLW                             1000
50200205 Sub Contractor - Meal Operator - SLW             0
50200305 Sub Contractor - Garbage - SLW                 2000

Result

CATEGORY                  DESC                            AMOUNT
50200105                Sub Contractor - SLW              3000

Body:
Lets achieve you output somehow with so many let ;)

let - you are trying to group by results with the last part of value in your column - DESCRIPTION.

Let - you are ok with keeping the MIN value from the CATEGORY column among the group.

Now- try this below query. Just trying to help you somehow :)

SELECT MIN(CATEGORY) CATEGORY,
'Sub Contractor - '+ TRIM(REVERSE(LEFT(REVERSE(DESCRIPTION), CHARINDEX('-',REVERSE(DESCRIPTION),0)-1))) DESCRIPTION,
SUM(AMOUNT) AMOUNT
FROM your_table
GROUP BY TRIM(REVERSE(LEFT(REVERSE(DESCRIPTION), CHARINDEX('-',REVERSE(DESCRIPTION),0)-1)))

Demo Here


问:
Date/time output has single quote in front of variable in Google Sheet
I have some code to export some output to a Google Sheet. The command I am using for that is:

row = [timestamp, float(temperature), float(humidity), current_temperature, current_humidity, current_pressure, weather_description]
sheet.insert_row(row, index)
```
<p>The issue is that the timestamp variable is adding a single quote in front of itself when it is inserted into the sheet, but when using <code>print(timestamp)</code>, this quote is not there.</p>
<p><img src="https://i.stack.imgur.com/cYeLR.png" alt="date/time in cell in Google Sheets" /></p>
<p>This makes it difficult because I cannot make any graphs with that quote in front of the output. The commands I am using for time are as follows:</p>
<pre class="lang-py prettyprint-override"><code>now = datetime.now()
timestamp = now.strftime("%m/%d/%Y%l:%M:%S %p")
</code>```

How can I get a timestamp without a single quote in front?

答:
To remove a character from a string, try using the String.split() function:</p>

```<code>timestamp = timestamp.split("'")[1]
</code>```

Body:
I have some code to export some output to a Google Sheet. The command I am using for that is:

row = [timestamp, float(temperature), float(humidity), current_temperature, current_humidity, current_pressure, weather_description]
sheet.insert_row(row, index)

The issue is that the timestamp variable is adding a single quote in front of itself when it is inserted into the sheet, but when using print(timestamp), this quote is not there.

This makes it difficult because I cannot make any graphs with that quote in front of the output. The commands I am using for time are as follows:

now = datetime.now()
timestamp = now.strftime("%m/%d/%Y%l:%M:%S %p")

How can I get a timestamp without a single quote in front?

Body:
To remove a character from a string, try using the String.split() function:

timestamp = timestamp.split("'")[1]


问:
nltk path in azure functions python
I am tring to use nltk in one of my folder but it can't find it

what i try to use:

import nltk
nltk.data.path.append("nltk_data")

in a one of my files

The file tree:

main_azure_folder:

share_code:

text_analysis.py

nltk_data

What is the current way to path it?

Thank you

答:
Please have a look of the below doc if you want to import custom extension in your function, it tells you how to import:

https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-python#import-behavior

For example, if you want to import dog.py file, you can use it like this:

```<code>from . import dog
</code>```

If it is a folder, then the files in the folder in the current trigger folder cannot be used as the source of import(must be level with the trigger), like this:

In this situation, we need to use this(If you want to import something to a folder you created yourself, such as test folder, use this method as well):

```<code>from ..test import cat
</code>```

Title: nltk path in azure functions python

Body:
Please have a look of the below doc if you want to import custom extension in your function, it tells you how to import:

https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-python#import-behavior

For example, if you want to import dog.py file, you can use it like this:

from . import dog

If it is a folder, then the files in the folder in the current trigger folder cannot be used as the source of import(must be level with the trigger), like this:

In this situation, we need to use this(If you want to import something to a folder you created yourself, such as test folder, use this method as well):

from ..test import cat


问:
Pandas - remove the label of the column index
I have a dataframe as follows:

```<code>PLEASE_REMOVE  2013  2014  2015
 THIS_IS_EASY
-------------------------------
          Bob     0     3     4
         Mary     2     3     6
</code>```

The years (2013, 2014, 2015) are the column index labels.
The names (Mary, Bob) are the row index labels.

I have somehow managed to get labels for the row indices and column indices.

Using df.index.names = [''] I can remove the THIS_IS_EASY bit.

How can I remove the PLEASE_REMOVE bit?

Desired output is:

```<code>               2013  2014  2015
 -------------------------------
          Bob     0     3     4
         Mary     2     3     6
</code>```

答:
In Pandas 1.0.3 I have used the following :</p>

```<code>df.rename_axis(None, axis = 1)
</code>```

Body:
I have a dataframe as follows:

PLEASE_REMOVE  2013  2014  2015
 THIS_IS_EASY
-------------------------------
          Bob     0     3     4
         Mary     2     3     6

The years (2013, 2014, 2015) are the column index labels.
The names (Mary, Bob) are the row index labels.

I have somehow managed to get labels for the row indices and column indices.

Using df.index.names = [''] I can remove the THIS_IS_EASY bit.

How can I remove the PLEASE_REMOVE bit?

Desired output is:

               2013  2014  2015
 -------------------------------
          Bob     0     3     4
         Mary     2     3     6

Body:
In Pandas 1.0.3 I have used the following :

df.rename_axis(None, axis = 1)


问:
JAVA_HOME path updated for version 11, java version in the cmd still showing 8
I had recently installed java 11 and set all the necessary paths in the system environment variables.

why does my java -version show the old java installed. Do i need to do something else to get his updated.

答: You need to add %JAVA_HOME%\bin to your path.</p>


问:
how to send Camera video using flash socket
this is my  flash as3 code :

```<code>var cam:Camera;

cam= Camera.getCamera();

var video:Video=new Video(200,200);
video.attachCamera(cam);
addChild(video);
</code>```

use this code , i can see my Camera in this swf file ,

now i want to send/get this video to my friend using flash socket ,

so , i would create a client file and a server file using flash socket ,

how to create this client/server file ,

thanks

答:
Are you sure you want to user flash.net.Socket instead of simple flash.net.NetStream? Why?

I would recommend NetStream, see NetStream.attachCamera()

You can use server publishing (FMS, Wowza, Red5), P2P direct connection or P2P NetGroup (with Adobe Cirrus), or just LAN P2P with NetGroup IP multicast (works without internet connection).

More inspiration on Tom Krcha's blog flashrealtime.com

Body:
this is my  flash as3 code :

var cam:Camera;

cam= Camera.getCamera();

var video:Video=new Video(200,200);
video.attachCamera(cam);
addChild(video);

use this code , i can see my Camera in this swf file ,

now i want to send/get this video to my friend using flash socket ,

so , i would create a client file and a server file using flash socket ,

how to create this client/server file ,

thanks


问:
How to filter the div as we search in search box?
I made a page with 9 cards. The card is with the class name "card". I want to get the card when I type the letters. I want this to be filtered on the basis of p tag that consist "First project", "Second project" and so on for seven more.

function search() {
  let input = document.getElementById('.searchbar').value
  input = input.toLowerCase();
  let x = document.querySelector('.card p');

  for (i = 0; i < x.length; i++) {
    if (!x[i].innerHTML.toLowerCase().includes(input)) {
      x[i].style.display = "none";
    } else {
      x[i].style.display = "list-item";
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main">

  <h3 class="first">Page Heading <span class="span-text">Secondary Text</span></h3>
  <form class='searchbox'>
    <input class="searchbar" type="text" onkeyup="search()" placeholder="Search.." name="search">
  </form>

  <section class="cards">
    <div class="card">
      <div class="card-box">700 x 400</div>
      <p style="color:blue; font-size:1.5rem;">First Project</p>
      <p>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero quod non sed eveniet numquam perferendis.
      </p>
    </div>

    <div class="card">
      <div class="card-box">700 x 400</div>
      <p style="color:blue; font-size:1.5rem;">Second Project</p>
      <p>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero quod non sed eveniet numquam perferendis.
      </p>
    </div>
    //and seven more of same "card" class
</div></code>```

I am not able to filter it when I type in the search box. Kindly guide on what is wrong and what I can do  to display the card that I searched.

答:
```<code>function search() {
   // Get input value
   const input = document.querySelector('.searchbox > .searchbar').value.toLowerCase();
   // Get all cards in page
   const cards = document.querySelectorAll('.cards > .card');
   cards.forEach(card => {
      // Get card title
      const title = card.querySelector('p').innerText.toLowerCase();
      // Hide card if card title does not match
      card.style.display = title.includes(input) ? null : 'none';
   });
}
</code>```

Body:
I made a page with 9 cards. The card is with the class name "card". I want to get the card when I type the letters. I want this to be filtered on the basis of p tag that consist "First project", "Second project" and so on for seven more.

function search() {
  let input = document.getElementById('.searchbar').value
  input = input.toLowerCase();
  let x = document.querySelector('.card p');

  for (i = 0; i < x.length; i++) {
    if (!x[i].innerHTML.toLowerCase().includes(input)) {
      x[i].style.display = "none";
    } else {
      x[i].style.display = "list-item";
    }
  }
}

Page Heading Secondary Text

  <form class='searchbox'>
    <input class="searchbar" type="text" onkeyup="search()" placeholder="Search.." name="search">
  </form>

700 x 400

First Project

        Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero quod non sed eveniet numquam perferendis.

700 x 400

Second Project

        Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero quod non sed eveniet numquam perferendis.

    //and seven more of same "card" class

I am not able to filter it when I type in the search box. Kindly guide on what is wrong and what I can do  to display the card that I searched.