问:
VB.NET Linq query Left outer join left is null
I am trying to use a linq query similar to this in SQL:

```<code>SELECT pos.*, cl.cltyp_level FROM TPSTAFFPOS pos LEFT OUTER JOIN TSTAFFCLTYP cl ON pos.pos_cllvlid = cl.cltyp_id
</code>```

I have tried a few things.

```<code>Dim query = (From pos In TaRRDataSet.TPSTAFFPOS
             Join cl In TaRRDataSet.TSTAFFCLTYP
             On pos.pos_cllvlid Equals cl.cltyp_id
             Where pos.pos_id.Equals(CInt(text))
             Select cl.cltyp_level, pos).Distinct.ToArray
</code>```

I have also tried group join:

```<code>Dim query = (From pos In TaRRDataSet.TPSTAFFPOS
             Group Join cl In TaRRDataSet.TSTAFFCLTYP
             On pos.pos_cllvlid Equals cl.cltyp_id Into cc = Group
             From cl In cc.DefaultIfEmpty()
             Select cl.cltyp_level, pos).Distinct.ToArray
</code>```

The problem is the pos.pos_cllvlid could be null.  The cl table is just a lookup table.  The field in pos can be NULL.  How do i select the pos rows even if the pos.pos_cllvlid is null.  I searched and found the group join, but i still get the value is dbnull.  Here is an example of the data:

TPSTAFFPOS

```<code>| pos_id | pos_name   | pos_cllvlid |
|--------|------------|-------------|
| 1      | Position 1 | 1           |
| 2      | Position 2 | NULL        |
| 3      | Position 3 | 2           |
</code>```

TSTAFFCLTYP

```<code>| cltyp_id | cltype_value |
|----------|--------------|
| 1        | TS           |
| 2        | S            |
| 3        | I            |
</code>```

RESULT

```<code>| pos_id | pos_name   | pos_cllvlid | cltyp_value |
|--------|------------|-------------|-------------|
| 1      | Position 1 | 1           | TS          |
| 2      | Position 2 |             |             |
| 3      | Position 3 | 2           | S           |
</code>```

As you can see in TPSTAFFPOS, the pos_cllvlid can be null.  Everything I try i keep getting the same error, "The value for column 'pos_cllvlid' in table TPSTAFFPOS is dbnull."

答:
Assuming that pos_cllvlid field can hold null value, your final Select statement within Group Join should looks like:

```<code>        Select New With _
        {
            pos.pos_id,  _
            pos.pos_name,  _
            pos.pos_cllvlid,  _
            cl?.cltype_value
        }) _
         .Distinct() _
         .ToArray()
</code>```

or

```<code>        Select pos, cl?.cltype_value) _
         .Distinct() _
         .ToArray()
</code>```

As you can see, i've used ? to prevent NullReferenceException. Left outer join is getting all data on left and when there's no related data returns null (Nothing) on right. So, before you'll try to access data on right, you have to check for null (Nothing).

As MSDN states, a ? operator ...

Tests the value of the left-hand operand for null (Nothing) before
  performing a member access (?.) or index (?()) operation; returns
  Nothing if the left-hand operand evaluates to Nothing. Note that in
  expressions that ordinarily return value types, the null-conditional
  operator returns a Nullable.

For further details, please see: ?. and ?() null-conditional operators (Visual Basic)

Body:
I am trying to use a linq query similar to this in SQL:

SELECT pos.*, cl.cltyp_level FROM TPSTAFFPOS pos LEFT OUTER JOIN TSTAFFCLTYP cl ON pos.pos_cllvlid = cl.cltyp_id

I have tried a few things.

Dim query = (From pos In TaRRDataSet.TPSTAFFPOS
             Join cl In TaRRDataSet.TSTAFFCLTYP
             On pos.pos_cllvlid Equals cl.cltyp_id
             Where pos.pos_id.Equals(CInt(text))
             Select cl.cltyp_level, pos).Distinct.ToArray

I have also tried group join:

Dim query = (From pos In TaRRDataSet.TPSTAFFPOS
             Group Join cl In TaRRDataSet.TSTAFFCLTYP
             On pos.pos_cllvlid Equals cl.cltyp_id Into cc = Group
             From cl In cc.DefaultIfEmpty()
             Select cl.cltyp_level, pos).Distinct.ToArray

The problem is the pos.pos_cllvlid could be null.  The cl table is just a lookup table.  The field in pos can be NULL.  How do i select the pos rows even if the pos.pos_cllvlid is null.  I searched and found the group join, but i still get the value is dbnull.  Here is an example of the data:

TPSTAFFPOS

| pos_id | pos_name   | pos_cllvlid |
|--------|------------|-------------|
| 1      | Position 1 | 1           |
| 2      | Position 2 | NULL        |
| 3      | Position 3 | 2           |

TSTAFFCLTYP

| cltyp_id | cltype_value |
|----------|--------------|
| 1        | TS           |
| 2        | S            |
| 3        | I            |

RESULT

| pos_id | pos_name   | pos_cllvlid | cltyp_value |
|--------|------------|-------------|-------------|
| 1      | Position 1 | 1           | TS          |
| 2      | Position 2 |             |             |
| 3      | Position 3 | 2           | S           |

As you can see in TPSTAFFPOS, the pos_cllvlid can be null.  Everything I try i keep getting the same error, "The value for column 'pos_cllvlid' in table TPSTAFFPOS is dbnull."

Body:
Assuming that pos_cllvlid field can hold null value, your final Select statement within Group Join should looks like:

        Select New With _
        {
            pos.pos_id,  _
            pos.pos_name,  _
            pos.pos_cllvlid,  _
            cl?.cltype_value
        }) _
         .Distinct() _
         .ToArray()

or

        Select pos, cl?.cltype_value) _
         .Distinct() _
         .ToArray()

As you can see, i've used ? to prevent NullReferenceException. Left outer join is getting all data on left and when there's no related data returns null (Nothing) on right. So, before you'll try to access data on right, you have to check for null (Nothing).

As MSDN states, a ? operator ...

Tests the value of the left-hand operand for null (Nothing) before
  performing a member access (?.) or index (?()) operation; returns
  Nothing if the left-hand operand evaluates to Nothing. Note that in
  expressions that ordinarily return value types, the null-conditional
  operator returns a Nullable.

For further details, please see: ?. and ?() null-conditional operators (Visual Basic)


来源: stackexchange

问:
How to prompt iOS user for geoLocation service permission in Ionic
I've created a social media app that uses geoLocation services.  It's an Ionic 4 app with a Firebase backend.  GeoLocation services are working with Android but with iOS it's not prompting users for geoLocation access.

I've been looking but can't find an example of how to prompt users for GeoLocation service permission on Platform ready.

Any example on how to check for location services permissions and then prompt a user for location services permissions would be greatly appreciated.

And I assume this would be added to the app.component.ts file.

答:
You can open your project inside xCode and then click on you project solution then click Info and add the privacy permission “Privacy - Location When In Use Usage Description”

This was taken from the following forum post

https://forum.ionicframework.com/t/geolocation-permissions/145727/3

ContentLicense: CC BY-SA 4.0


问:
LinqDataSource - Can you limit the amount of records returned?
I'd like to use a LinqDataSource control on a page and limit the amount of records returned.  I know if I use code behind I could do something like this:

```<code>IEnumerable<int> values = Enumerable.Range(0, 10);
IEnumerable<int> take3 = values.Take(3);
</code>```

Does anyone know if something like this is possible with a LinqDataSource control?

[Update]

I'm going to use the LinqDataSource with the ListView control, not a GridView or Repeater.  The LinqDataSource wizard does not provide the ability to limit the number of records return.  The Advanced options only allow you to enabled deletes, inserts, and updates.

答:
I had this same issue. The way I got round this was to use the Selecting event on the LinqDataSource and return the result manually.

e.g.

```<code>protected void lnqRecentOrder_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
    DataClassesDataContext dx = new DataClassesDataContext();
    e.Result = (from o in dx.Orders
                where o.CustomerID == Int32.Parse(Request.QueryString["CustomerID"])
                select o).Take(5);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'd like to use a LinqDataSource control on a page and limit the amount of records returned.  I know if I use code behind I could do something like this:

IEnumerable<int> values = Enumerable.Range(0, 10);
IEnumerable<int> take3 = values.Take(3);

Does anyone know if something like this is possible with a LinqDataSource control?

[Update]

I'm going to use the LinqDataSource with the ListView control, not a GridView or Repeater.  The LinqDataSource wizard does not provide the ability to limit the number of records return.  The Advanced options only allow you to enabled deletes, inserts, and updates.

LastEditorDisplayName: Otto

Body:
I had this same issue. The way I got round this was to use the Selecting event on the LinqDataSource and return the result manually.

e.g.

protected void lnqRecentOrder_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
    DataClassesDataContext dx = new DataClassesDataContext();
    e.Result = (from o in dx.Orders
                where o.CustomerID == Int32.Parse(Request.QueryString["CustomerID"])
                select o).Take(5);
}

OwnerDisplayName: Ollie

ContentLicense: CC BY-SA 2.5


问:
how to convert byte* into jpeg file in VC++
how to convert byte*  into jpeg file in VC++

i am capturing Video samples and writing it as bmp files, but i want to write that video samples into jpeg file using MFC support in ATL COM.

答: Raw image data to JPEG can be acheived by ImageMagick.</p>

OwnerDisplayName: BALA

LastEditorDisplayName: BALA

OwnerDisplayName: Alphaneo


问:
Do unused functions get optimized out?
Compilers these days tend to do a significant amount of optimizations. Do they also remove unused functions from the final output?</p>

答: It depends on the compiler. Visual C++ 9 can do that - unused static functions are removed at compilation phase (there's even a C4505 warning for that), unused functions with external linkage can be removed at link phase depending on linker settings.

Title: Do unused functions get optimized out?


问:
Is a python subprocess allowed to use as many real threads as it can?
So as we know, Python doesn't have real threading because of the GIL (unless you go the Cython route and detach) but i can't seem to find info or documentation on a usecase.

If from my python script i run a Popen with the commands [dotnet test .....] and that code supports the native C# threads and processes and all of that, will my Python subprocess execute as native C# and handle as many threads as the script needs to or is it locked behind 1 process and 1 thread?

答: Any sub-process you launch with Popen will behave as it normally does. Python's threading model won't be inherited by a non-Python process when you launch it from within a Python process.


问:
How to fetch SSM Parameters from two different accounts using AWS CDK
I have a scenario where I'm using CodePipeline to deploy my cdk project from a tools account to several environment accounts.
The way my pipeline is deploying is by running cdk deploy from within a CodeBuild job.

My team has decided to use SSM Parameter Store to store configuration and we ended up with some parameters living in the environment account, for example the VPC_ID (resources/vpc/id) that I can read in deployment time => ssm.StringParameter.valueForStringParameter.

However, other parameters are living in the tools account, such as the Account Ids from my environment accounts (environment/nonprod/account/id) and other Global Config. I'm having trouble fetching those values.

At the moment, the only way I could think of was by using a step to read all those values in a previous step and loaded them into the context values.

Is there a more elegant approach for this problem? I was hoping I could specify in which account to get the SSM values from. Any ideas?

Thank you.

答:
As you already stated there is no native support for that. I am also using CodePipeline in cross-account deployments, so all the automation parameters or product specified parameters are stored in a secured account and CodePipeline deploys the resources using CloudFormation as an action provider. </p>

<p>Cross account resolution of SSM parameters isn't supported, so in the end, I had added an extra step (stage) in my CodePipeline, which is nothing else but a CodeBuild project, which runs a script in a containerized environment and scripts then "syncs" the parameters from the automation account to the destination account. </p>

Body:
As you already stated there is no native support for that. I am also using CodePipeline in cross-account deployments, so all the automation parameters or product specified parameters are stored in a secured account and CodePipeline deploys the resources using CloudFormation as an action provider.

Cross account resolution of SSM parameters isn't supported, so in the end, I had added an extra step (stage) in my CodePipeline, which is nothing else but a CodeBuild project, which runs a script in a containerized environment and scripts then "syncs" the parameters from the automation account to the destination account.


问:
Store non-strings in Hyperledger Fabric 1.4
From what I'm reading, it is only possible to pass string values from the Node SDK to the chaincode via submitTransaction.

However, from the chaincode point of view, there is no issue with creating an asset containing, say, booleans and integers and store them.

Hence my question: is storing non-string attributes considered a bad practice, and if not, what is the best way to implement it? Of course I can send strings that the smart contract will then convert back to bool/ints, but that sounds quite ugly. I also guess that instead of sending ...args I can send a JSON, but again, quite ugly.

答:
Okay, this is from JAVA HLF implementation standpoint. Assuming Node JS and Java have the same capabilities, the 'putState' method takes in either 'byte' or 'String' data types, and putState is the only method as far as I know to put data to ledger. So, you cannot put anything other than String/ byte in my view. So, although it is ugly, I think putting String or bytes to ledger is the only way to put and get data (at least as of HLF 1.4).

All data written to ledger would actually get stored onto 'CouchDB' behind the scenes, so if you write JSON strings to ledger, you can later write 'CouchDB query' and get the data from ledger too (just like how you use SQL to get data from traditional RDBMS).


问:
R Plot: spead out axis labels evenly
I'm currently struggling with finding out, how to spread the axis labels evenly.

Here is the code I'm using:

```<code>plot(1:10, type = "p", xlab = "", ylab = "")
axis(1, at = c(1:10))
axis(2, at = c(1:10))
grid(nx = 10, ny = 10)
</code>```

What I'm trying to achieve is to have the data points in the center of the respective grid box and to have the labels (1-10) to be in the center. How can I achieve this?

Any help or direction would be greatly appreciated, thank you!

答:
I agree with Allan Cameron that when you want that much control it is best to switch tools to something like abline.  But if you really want to use grid, you can do so by explicitly setting the limits of your plot:

```<code>plot(1:10, xlim=c(0.5,10.5), ylim=c(0.5,10.5), xaxs='i', yaxs='i')
grid(nx=10, ny=10)
</code>```

You may want to do this even if using abline since it will make the corner and edge boxes be the same size as the others (and center the points in those boxes).

Title: R Plot: spead out axis labels evenly

Body:
I'm currently struggling with finding out, how to spread the axis labels evenly.

Here is the code I'm using:

plot(1:10, type = "p", xlab = "", ylab = "")
axis(1, at = c(1:10))
axis(2, at = c(1:10))
grid(nx = 10, ny = 10)

What I'm trying to achieve is to have the data points in the center of the respective grid box and to have the labels (1-10) to be in the center. How can I achieve this?

Any help or direction would be greatly appreciated, thank you!

Body:
I agree with Allan Cameron that when you want that much control it is best to switch tools to something like abline.  But if you really want to use grid, you can do so by explicitly setting the limits of your plot:

plot(1:10, xlim=c(0.5,10.5), ylim=c(0.5,10.5), xaxs='i', yaxs='i')
grid(nx=10, ny=10)

You may want to do this even if using abline since it will make the corner and edge boxes be the same size as the others (and center the points in those boxes).


问:
Drag & Drop API and table rows (vanilla JS only)
In my HTML table of one column and n rows, for example:

```<code><table id="my-table">
  <tr>
    <td>How</td>
  </tr>
  <tr>
    <td>Are</td>
  </tr>
  <tr>
    <td>You</td>
  </tr>
</table>
</code>```

I want to make each row draggable and droppable into another one. If you drop one row A into another row B, the HTML content of these respective rows should get exchanged.

To do so, I read through quite some documentations and tutorials, but there appears something o be missing that I just can't figure out. What I did so far is attach the following code into each tag:

draggable="true" ondragstart="dragCell(event)" ondragover="allowDrop(event)" ondrop="dropCell(event)" ondragenter="handleDragEnter(event)" ondragleave="handleDragLeave(event)" ondragend="handleDragEnd(event)"

and my JavaScript is:

```<code>/*##############################################################################
##                            1. Dragstart Handler                            ##
##############################################################################*/

function dragCell(ev) {
  let draggedRow = ev.target.closest("tr");
  let rowNumber = draggedRow.rowIndex;
  let tableId = draggedRow.parentNode.parentNode.getAttribute("id");
  let data = {"id":tableId,"rowNumber":rowNumber};
  let cellsdragged = draggedRow.children;
  let amountOfCells = cellsdragged.length;
  let dataToTransfer = [];
  for (let i = 0; i < amountOfCells; i++) {
    let currentCell = cellsdragged[i];
    dataToTransfer.push(currentCell.outerHTML);
  }
  data["cellContents"] = dataToTransfer;
  data = JSON.stringify(data);
  ev.dataTransfer.setData("text/plain",data);
  document.getElementsByTagName("body")[0].style.cursor = "grabbing";
}

/*##############################################################################
##                             2. Dragover Handler                            ##
##############################################################################*/

function allowDrop(ev) {
  ev.preventDefault();
}

/*##############################################################################
##                               3. Drop Handler                              ##
##############################################################################*/

function dropCell(ev) {
  ev.preventDefault();
  if (ev.stopPropagation) {
    ev.stopPropagation();
  }
  document.getElementsByTagName("body")[0].style.cursor = "default";
  let data = ev.dataTransfer.getData("text/plain");
  data = JSON.parse(data);
  let rowToDrop = ev.target.closest('tr');
  let targetIndex = rowToDrop.rowIndex;
  let targetId = rowToDrop.parentNode.parentNode.getAttribute("id");
  if (data.id == targetId && data.rowNumber != targetIndex) {
    let targetContents = [];
    let cellsForDrop = rowToDrop.children;
    let amountOfCells = cellsForDrop.length;
    for (let i = 0; i < amountOfCells; i++) {
      targetContents
        .push(cellsForDrop[i].outerHTML);
    }
    let draggedRow = document.getElementById(data.id).rows[data.rowNumber];
    let cellsOfDrag = draggedRow.children;
    for (let i = 0; i < amountOfCells; i++) {
      cellsForDrop[i].outerHTML = data.cellContents[i][0];
      cellsOfDrag[i].outerHTML = targetContents[i][0];
    }
  }
}

/*##############################################################################
##                             4. Dragenter Handler                           ##
##############################################################################*/

function handleDragEnter(ev) {
  ev.target.closest('tr').classList.add('ready-for-drop');
}

/*##############################################################################
##                            5. Dragleave Handler                            ##
##############################################################################*/

function handleDragLeave(ev) {
  ev.target.closest('tr').classList.remove('ready-for-drop');
}

/*##############################################################################
##                              6. Dragend Handler                            ##
##############################################################################*/

function handleDragEnd(event) {
  let rows = ev.target.closest("table").rows;
  let amount = rows.length;
  for (let i = 0; i < amount; i++) {
    if (rows[i].classList.contains('ready-for-drop')) {
      rows[i].classList.remove('ready-for-drop')
    }
  }
}
</code>```

When I run this and drag one row into another one, the console provides me with an error concerning ev.target.closest, for the Dragenter, Dragleave and the Dragend Handler functions, always saying ev.target.closest is not a function. Although I use exactly the same syntax in the dragstart handler function, no error is reported in the console on that line. When finishing the drag, the content of the dragged and dropped row both become <.

What am I missing here? Please consider that I don't want to use any jQuery solution, I'd like to stick to vanilla JavaScript. Please also consider that I indeed need the whole outerHTML to be exchanged, because my  tags may contain cell-specific attribute values.

答:
Ok figured out a solution, most important facts:

I used addEventListener instead of HTML inline event listeners inside the HTML tags, as mentioned above, for several reasons (which I won't specify further here)

The hardest troubles I had was with the fact that my dragleave event function fired when I was dragging the dragged element over the child of an element with the dragenter & dragleave listeners bound to it. I read countless articles & posts in this forum about this issue, and none of the proposed solutions seemed to work easily or simply with my very basic HTML table rows and cells, and soon employed functions to stop event propagations etc., which is actually not even necessary, as you'll see in my code. Furthermore I completely ommit the dragleave event listener in my solution, so this may be one of the easier ways to reach what I want, which is why I wanted to share it here for others which may want to do similar stuff as I wanted.

What's different from above for everything to work is:

HTML: I included only draggable="true" class="table-cell" in the td tags

JavaScript: Quite different now, but works perfectly:

```<code>/*##############################################################################
##    1. Define Function which adds all the required event listeners          ##
##############################################################################*/

function addDragEvents(element) {
  element.addEventListener("dragstart",dragCell);
  element.addEventListener("dragover",allowDrop);
  element.addEventListener("drop",dropCell);
  element.addEventListener("dragenter",handleDragEnter);
  element.addEventListener("dragend",handleDragEnd);
}

/*##############################################################################
##    2. Define Function which resets the drag state for the concerned table  ##
##############################################################################*/

function resetDragState(e) {
  let data = e.dataTransfer.getData("text/plain");
  data = JSON.parse(data);
  let rows = document.getElementById(data.id).rows;
  for (let row of rows) {
    if (row.classList.contains('ready-for-drop')) {
      row.classList.remove('ready-for-drop');
    }
    let cells = row.cells;
    for (let cell of cells) {
      cell.style.cursor="pointer";
    }
  }
}

/*##############################################################################
##    3. Add Required Event listeners to all table cells                      ##
##############################################################################*/

let cells = document.getElementsByClassName('table-cell');
for (let cell of cells) {
  addDragEvents(cell);
}

/*##############################################################################
##                            4. Dragstart Handler                            ##
##############################################################################*/

// This function is created to define the action of a drag (which data will be
// taken for transfer to the HTML element into which the dragged element's
// content will be dropped)

function dragCell(e) {
  // Change the cursor to a grabbing hand on dragstart
  let cells = document.getElementsByClassName('table-cell');
  for (let cell of cells) {
    cell.style.cursor="grabbing";
  }
  // Three pieces of information must be transferred for the drag & drop to work
  // properly: the table id of the table having the row being dragged (to assure
  // that D&D only works among rows of the same table), the row index of the row
  // being dragged (to know which row needs to be replaced via the drop
  // function), and finally the content of the row being dragged
  let draggedRow = e.target.closest("tr");
  // Get the row index of that row
  let rowNumber = draggedRow.rowIndex;
  // Get the id name of the table having that row
  let tableId = draggedRow.parentNode.parentNode.getAttribute("id");
  // Initiate JSON object which will be transferred to the drop row
  let data = {"id":tableId,"rowNumber":rowNumber};
  // Append all the cells as second element onto this same object
  let cellsdragged = draggedRow.children;
  let amountOfCells = cellsdragged.length;
  let dataToTransfer = [];
  for (let i = 0; i < amountOfCells; i++) {
    let currentCell = cellsdragged[i];
    dataToTransfer.push(currentCell.outerHTML);
  }
  data["cellContents"] = dataToTransfer;
  data = JSON.stringify(data);
  e.dataTransfer.setData("text/plain",data);
}

/*##############################################################################
##                             5. Dragover Handler                            ##
##############################################################################*/

// This function is used to allow for drops into the corresponding HTML elements
// (the default behavior doesn't allow this)
function allowDrop(e) {
  e.preventDefault();
}

/*##############################################################################
##                               6. Drop Handler                              ##
##############################################################################*/

function dropCell(e) {
  // First, prevent default behavior once again
  e.preventDefault();
  // Second, access data coming from dragged element (which is the index of the
  // row from which data is being dragged)
  let data = e.dataTransfer.getData("text/plain");
  data = JSON.parse(data);
  // Next, get the index of the row into which content shall be dropped
  let rowToDrop = e.target.closest('tr');
  let targetIndex = rowToDrop.rowIndex;
  // Next, get the id of the table of that retrieved row
  let targetId = rowToDrop.parentNode.parentNode.getAttribute("id");
  // Next, only proceed if the dragged row comes from the same table as the
  // target row, and if the dragged and the target rows are two different rows
  if (data.id == targetId && data.rowNumber != targetIndex) {
    // Store the contents of the target row in the same array structure as the
    // one coming from the dragged row
    let targetContents = [];
    // Exchange the contents of the two rows
    let cellsForDrop = rowToDrop.children;
    let amountOfCells = cellsForDrop.length;
    for (let i = 0; i < amountOfCells; i++) {
      targetContents
        .push(cellsForDrop[i].outerHTML);
    }
    // Exchange the contents of the two rows
    let draggedRow = document.getElementById(data.id).rows[data.rowNumber];
    let cellsOfDrag = draggedRow.children;
    for (let i = 0; i < amountOfCells; i++) {
      // Replace the content of the row into which the drag is being dropped
      // with the content of the dragged row
      cellsForDrop[i].outerHTML = data.cellContents[i];
      // Replacement of the outerHTML deletes all bound event listeners, so:
      addDragEvents(cellsForDrop[i]);
      // And now, replace the content of the dragged row with the content of the
      // target row. Then, do the same for the value.
      cellsOfDrag[i].outerHTML = targetContents[i];
      addDragEvents(cellsOfDrag[i]);
    }
    resetDragState(e);
  }
}

/*##############################################################################
##                             7. Dragenter Handler                           ##
##############################################################################*/

// When dragging over the text node of a table cell (the text in a table cell),
// while previously being over the table cell element, the dragleave event gets
// fired, which stops the highlighting of the currently dragged cell. To avoid
// this problem and any coding around to fight it, everything has been
// programmed with the dragenter event handler only; no more dragleave needed

// For the dragenter event, e.target corresponds to the element into which the
// drag enters. This fact has been used to program the code as follows:

var previousRow = null;

function handleDragEnter(e) {
  // Assure that dragenter code is only executed when entering an element (and
  // for example not when entering a text node)
  if (e.target.nodeType === 1) {
    // Get the currently entered row
    let currentRow = this.closest('tr');
    // Check if the currently entered row is different from the row entered via
    // the last drag
    if (previousRow !== null) {
      if (currentRow !== previousRow) {
        // If so, remove the class responsible for highlighting it via CSS from
        // it
        previousRow.className = "";
      }
    }
    // Each time an HTML element is entered, add the class responsible for
    // highlighting it via CSS onto its containing row (or onto itself, if row)
    currentRow.className = "ready-for-drop";
    // To know which row has been the last one entered when this function will
    // be called again, assign the previousRow variable of the global scope onto
    // the currentRow from this function run
    previousRow = currentRow;
  }
}

/*##############################################################################
##                              8. Dragend Handler                            ##
##############################################################################*/

// This function is required for cases where the dragged has been dropped on a
// non-valid drop target.

function handleDragEnd(e) {
  resetDragState(e);
}
</code>```

I left the comments inside, as I struggeled a lot searching online (and without success) how to use the Drag & Drop API as simply as possible to make rows / cells of HTML tables drag- & droppable, so I hope this answer will help out others!

Body:
In my HTML table of one column and n rows, for example:

    How

    Are

    You

I want to make each row draggable and droppable into another one. If you drop one row A into another row B, the HTML content of these respective rows should get exchanged.

To do so, I read through quite some documentations and tutorials, but there appears something o be missing that I just can't figure out. What I did so far is attach the following code into each tag:

draggable="true" ondragstart="dragCell(event)" ondragover="allowDrop(event)" ondrop="dropCell(event)" ondragenter="handleDragEnter(event)" ondragleave="handleDragLeave(event)" ondragend="handleDragEnd(event)"

and my JavaScript is:

/*##############################################################################
##                            1. Dragstart Handler                            ##
##############################################################################*/

function dragCell(ev) {
  let draggedRow = ev.target.closest("tr");
  let rowNumber = draggedRow.rowIndex;
  let tableId = draggedRow.parentNode.parentNode.getAttribute("id");
  let data = {"id":tableId,"rowNumber":rowNumber};
  let cellsdragged = draggedRow.children;
  let amountOfCells = cellsdragged.length;
  let dataToTransfer = [];
  for (let i = 0; i < amountOfCells; i++) {
    let currentCell = cellsdragged[i];
    dataToTransfer.push(currentCell.outerHTML);
  }
  data["cellContents"] = dataToTransfer;
  data = JSON.stringify(data);
  ev.dataTransfer.setData("text/plain",data);
  document.getElementsByTagName("body")[0].style.cursor = "grabbing";
}

/*##############################################################################
##                             2. Dragover Handler                            ##
##############################################################################*/

function allowDrop(ev) {
  ev.preventDefault();
}

/*##############################################################################
##                               3. Drop Handler                              ##
##############################################################################*/

function dropCell(ev) {
  ev.preventDefault();
  if (ev.stopPropagation) {
    ev.stopPropagation();
  }
  document.getElementsByTagName("body")[0].style.cursor = "default";
  let data = ev.dataTransfer.getData("text/plain");
  data = JSON.parse(data);
  let rowToDrop = ev.target.closest('tr');
  let targetIndex = rowToDrop.rowIndex;
  let targetId = rowToDrop.parentNode.parentNode.getAttribute("id");
  if (data.id == targetId && data.rowNumber != targetIndex) {
    let targetContents = [];
    let cellsForDrop = rowToDrop.children;
    let amountOfCells = cellsForDrop.length;
    for (let i = 0; i < amountOfCells; i++) {
      targetContents
        .push(cellsForDrop[i].outerHTML);
    }
    let draggedRow = document.getElementById(data.id).rows[data.rowNumber];
    let cellsOfDrag = draggedRow.children;
    for (let i = 0; i < amountOfCells; i++) {
      cellsForDrop[i].outerHTML = data.cellContents[i][0];
      cellsOfDrag[i].outerHTML = targetContents[i][0];
    }
  }
}

/*##############################################################################
##                             4. Dragenter Handler                           ##
##############################################################################*/

function handleDragEnter(ev) {
  ev.target.closest('tr').classList.add('ready-for-drop');
}

/*##############################################################################
##                            5. Dragleave Handler                            ##
##############################################################################*/

function handleDragLeave(ev) {
  ev.target.closest('tr').classList.remove('ready-for-drop');
}

/*##############################################################################
##                              6. Dragend Handler                            ##
##############################################################################*/

function handleDragEnd(event) {
  let rows = ev.target.closest("table").rows;
  let amount = rows.length;
  for (let i = 0; i < amount; i++) {
    if (rows[i].classList.contains('ready-for-drop')) {
      rows[i].classList.remove('ready-for-drop')
    }
  }
}

When I run this and drag one row into another one, the console provides me with an error concerning ev.target.closest, for the Dragenter, Dragleave and the Dragend Handler functions, always saying ev.target.closest is not a function. Although I use exactly the same syntax in the dragstart handler function, no error is reported in the console on that line. When finishing the drag, the content of the dragged and dropped row both become <.

What am I missing here? Please consider that I don't want to use any jQuery solution, I'd like to stick to vanilla JavaScript. Please also consider that I indeed need the whole outerHTML to be exchanged, because my  tags may contain cell-specific attribute values.

Body:
Ok figured out a solution, most important facts:

I used addEventListener instead of HTML inline event listeners inside the HTML tags, as mentioned above, for several reasons (which I won't specify further here)

The hardest troubles I had was with the fact that my dragleave event function fired when I was dragging the dragged element over the child of an element with the dragenter & dragleave listeners bound to it. I read countless articles & posts in this forum about this issue, and none of the proposed solutions seemed to work easily or simply with my very basic HTML table rows and cells, and soon employed functions to stop event propagations etc., which is actually not even necessary, as you'll see in my code. Furthermore I completely ommit the dragleave event listener in my solution, so this may be one of the easier ways to reach what I want, which is why I wanted to share it here for others which may want to do similar stuff as I wanted.

What's different from above for everything to work is:

HTML: I included only draggable="true" class="table-cell" in the td tags

JavaScript: Quite different now, but works perfectly:

/*##############################################################################
##    1. Define Function which adds all the required event listeners          ##
##############################################################################*/

function addDragEvents(element) {
  element.addEventListener("dragstart",dragCell);
  element.addEventListener("dragover",allowDrop);
  element.addEventListener("drop",dropCell);
  element.addEventListener("dragenter",handleDragEnter);
  element.addEventListener("dragend",handleDragEnd);
}

/*##############################################################################
##    2. Define Function which resets the drag state for the concerned table  ##
##############################################################################*/

function resetDragState(e) {
  let data = e.dataTransfer.getData("text/plain");
  data = JSON.parse(data);
  let rows = document.getElementById(data.id).rows;
  for (let row of rows) {
    if (row.classList.contains('ready-for-drop')) {
      row.classList.remove('ready-for-drop');
    }
    let cells = row.cells;
    for (let cell of cells) {
      cell.style.cursor="pointer";
    }
  }
}

/*##############################################################################
##    3. Add Required Event listeners to all table cells                      ##
##############################################################################*/

let cells = document.getElementsByClassName('table-cell');
for (let cell of cells) {
  addDragEvents(cell);
}

/*##############################################################################
##                            4. Dragstart Handler                            ##
##############################################################################*/

// This function is created to define the action of a drag (which data will be
// taken for transfer to the HTML element into which the dragged element's
// content will be dropped)

function dragCell(e) {
  // Change the cursor to a grabbing hand on dragstart
  let cells = document.getElementsByClassName('table-cell');
  for (let cell of cells) {
    cell.style.cursor="grabbing";
  }
  // Three pieces of information must be transferred for the drag & drop to work
  // properly: the table id of the table having the row being dragged (to assure
  // that D&D only works among rows of the same table), the row index of the row
  // being dragged (to know which row needs to be replaced via the drop
  // function), and finally the content of the row being dragged
  let draggedRow = e.target.closest("tr");
  // Get the row index of that row
  let rowNumber = draggedRow.rowIndex;
  // Get the id name of the table having that row
  let tableId = draggedRow.parentNode.parentNode.getAttribute("id");
  // Initiate JSON object which will be transferred to the drop row
  let data = {"id":tableId,"rowNumber":rowNumber};
  // Append all the cells as second element onto this same object
  let cellsdragged = draggedRow.children;
  let amountOfCells = cellsdragged.length;
  let dataToTransfer = [];
  for (let i = 0; i < amountOfCells; i++) {
    let currentCell = cellsdragged[i];
    dataToTransfer.push(currentCell.outerHTML);
  }
  data["cellContents"] = dataToTransfer;
  data = JSON.stringify(data);
  e.dataTransfer.setData("text/plain",data);
}

/*##############################################################################
##                             5. Dragover Handler                            ##
##############################################################################*/

// This function is used to allow for drops into the corresponding HTML elements
// (the default behavior doesn't allow this)
function allowDrop(e) {
  e.preventDefault();
}

/*##############################################################################
##                               6. Drop Handler                              ##
##############################################################################*/

function dropCell(e) {
  // First, prevent default behavior once again
  e.preventDefault();
  // Second, access data coming from dragged element (which is the index of the
  // row from which data is being dragged)
  let data = e.dataTransfer.getData("text/plain");
  data = JSON.parse(data);
  // Next, get the index of the row into which content shall be dropped
  let rowToDrop = e.target.closest('tr');
  let targetIndex = rowToDrop.rowIndex;
  // Next, get the id of the table of that retrieved row
  let targetId = rowToDrop.parentNode.parentNode.getAttribute("id");
  // Next, only proceed if the dragged row comes from the same table as the
  // target row, and if the dragged and the target rows are two different rows
  if (data.id == targetId && data.rowNumber != targetIndex) {
    // Store the contents of the target row in the same array structure as the
    // one coming from the dragged row
    let targetContents = [];
    // Exchange the contents of the two rows
    let cellsForDrop = rowToDrop.children;
    let amountOfCells = cellsForDrop.length;
    for (let i = 0; i < amountOfCells; i++) {
      targetContents
        .push(cellsForDrop[i].outerHTML);
    }
    // Exchange the contents of the two rows
    let draggedRow = document.getElementById(data.id).rows[data.rowNumber];
    let cellsOfDrag = draggedRow.children;
    for (let i = 0; i < amountOfCells; i++) {
      // Replace the content of the row into which the drag is being dropped
      // with the content of the dragged row
      cellsForDrop[i].outerHTML = data.cellContents[i];
      // Replacement of the outerHTML deletes all bound event listeners, so:
      addDragEvents(cellsForDrop[i]);
      // And now, replace the content of the dragged row with the content of the
      // target row. Then, do the same for the value.
      cellsOfDrag[i].outerHTML = targetContents[i];
      addDragEvents(cellsOfDrag[i]);
    }
    resetDragState(e);
  }
}

/*##############################################################################
##                             7. Dragenter Handler                           ##
##############################################################################*/

// When dragging over the text node of a table cell (the text in a table cell),
// while previously being over the table cell element, the dragleave event gets
// fired, which stops the highlighting of the currently dragged cell. To avoid
// this problem and any coding around to fight it, everything has been
// programmed with the dragenter event handler only; no more dragleave needed

// For the dragenter event, e.target corresponds to the element into which the
// drag enters. This fact has been used to program the code as follows:

var previousRow = null;

function handleDragEnter(e) {
  // Assure that dragenter code is only executed when entering an element (and
  // for example not when entering a text node)
  if (e.target.nodeType === 1) {
    // Get the currently entered row
    let currentRow = this.closest('tr');
    // Check if the currently entered row is different from the row entered via
    // the last drag
    if (previousRow !== null) {
      if (currentRow !== previousRow) {
        // If so, remove the class responsible for highlighting it via CSS from
        // it
        previousRow.className = "";
      }
    }
    // Each time an HTML element is entered, add the class responsible for
    // highlighting it via CSS onto its containing row (or onto itself, if row)
    currentRow.className = "ready-for-drop";
    // To know which row has been the last one entered when this function will
    // be called again, assign the previousRow variable of the global scope onto
    // the currentRow from this function run
    previousRow = currentRow;
  }
}

/*##############################################################################
##                              8. Dragend Handler                            ##
##############################################################################*/

// This function is required for cases where the dragged has been dropped on a
// non-valid drop target.

function handleDragEnd(e) {
  resetDragState(e);
}

I left the comments inside, as I struggeled a lot searching online (and without success) how to use the Drag & Drop API as simply as possible to make rows / cells of HTML tables drag- & droppable, so I hope this answer will help out others!


问:
How do I use arrow functions in React
I'm working on a node and react project where when i try to use an arrow function, it brings the error that the function is not defined. I've tried following every tutorial I can get but I'm not able to solve this. Here is my code;

```<code>import React from 'react';
import './App.css';
import {BrowserRouter as Router, Link} from 'react-router-dom';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state={apiResponse:""}
  }

  callAPI(){
    fetch("http://localhost:9000/testAPI")
    .then(res=> res.text())
    .then(res=> this.setState({apiResponse: res}));
  }

  componentWillMount(){
    this.callAPI();
  }

  Trial = ()=>{
    return(
      <div>this is my div</div>
    );
  }

render(){
  return (
    <div className="App">
      <p>{this.state.apiResponse}</p>

      <Trial />

    </div>
  );
}
}

export default App;
</code>```

and the error message i'm getting is:

```<code>./src/App.js
  Line 33:8:  'Trial' is not defined  react/jsx-no-undef

Search for the keywords to learn more about each error.
This error occurred during the build time and cannot be dismissed
</code>```

any assistance will be highly appreciated

答:
If you want to create a new component your code will be much clearer if you move it before the class.

Also the standard place to call api is componentDidMount. So react will render the page with empty data very quickly, then it calls the async functions.

```<code>import React from 'react';
import './App.css';
import {BrowserRouter as Router, Link} from 'react-router-dom';

const Trial = ()=>{
    return(
      <div>this is my div</div>
    );
  }

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state={apiResponse:""}
  }

  callAPI(){
    fetch("http://localhost:9000/testAPI")
    .then(res=> res.text())
    .then(res=> this.setState({apiResponse: res}));
  }

  componentDidMount(){
    this.callAPI();
  }

render(){
  return (
    <div className="App">
      <p>{this.state.apiResponse}</p>

      <Trial />

    </div>
  );
}
}

export default App;
</code>```

This is an example: https://codesandbox.io/s/hopeful-hellman-g4tc3

Title: How do I use arrow functions in React

Body:
I'm working on a node and react project where when i try to use an arrow function, it brings the error that the function is not defined. I've tried following every tutorial I can get but I'm not able to solve this. Here is my code;

import React from 'react';
import './App.css';
import {BrowserRouter as Router, Link} from 'react-router-dom';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state={apiResponse:""}
  }

  callAPI(){
    fetch("http://localhost:9000/testAPI")
    .then(res=> res.text())
    .then(res=> this.setState({apiResponse: res}));
  }

  componentWillMount(){
    this.callAPI();
  }

  Trial = ()=>{
    return(

this is my div

    );
  }

render(){
  return (

{this.state.apiResponse}

      <Trial />

  );
}
}

export default App;

and the error message i'm getting is:

./src/App.js
  Line 33:8:  'Trial' is not defined  react/jsx-no-undef

Search for the keywords to learn more about each error.
This error occurred during the build time and cannot be dismissed

any assistance will be highly appreciated

Body:
If you want to create a new component your code will be much clearer if you move it before the class.

Also the standard place to call api is componentDidMount. So react will render the page with empty data very quickly, then it calls the async functions.

import React from 'react';
import './App.css';
import {BrowserRouter as Router, Link} from 'react-router-dom';

const Trial = ()=>{
    return(
      <div>this is my div</div>
    );
  }

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state={apiResponse:""}
  }

  callAPI(){
    fetch("http://localhost:9000/testAPI")
    .then(res=> res.text())
    .then(res=> this.setState({apiResponse: res}));
  }

  componentDidMount(){
    this.callAPI();
  }

render(){
  return (
    <div className="App">
      <p>{this.state.apiResponse}</p>

      <Trial />

    </div>
  );
}
}

export default App;

This is an example: https://codesandbox.io/s/hopeful-hellman-g4tc3


问:
How can I get class files from Maven dependency into the target\classes folder
Is there any sort of Maven plugin that allows me to copy the class files for a dependency into the target\classes folder for my project? Currently I have to manually open the jar file that has the dependencies extract the package that I need to copy over and then copy it into the target\class folder for my project.

I need a way to do those ideally within the pom.xml file but I haven't been able to find a solution that works. Any help would be appreciated, Thanks.

答:
Use the maven-dependency-plugin. Here is an example of how you can extract the content of a dependency JAR:</p>

```<code>    <project>
       [...]
       <build>
         <plugins>
           <plugin>
             <groupId>org.apache.maven.plugins</groupId>
             <artifactId>maven-dependency-plugin</artifactId>
             <version>3.1.2</version>
             <executions>
               <execution>
                 <id>unpack</id>
                 <phase>package</phase>
                 <goals>
                   <goal>unpack</goal>
                 </goals>
                 <configuration>
                   <artifactItems>
                     <artifactItem>
                       <groupId>junit</groupId>
                       <artifactId>junit</artifactId>
                       <version>3.8.1</version>
                       <type>jar</type>
                       <overWrite>false</overWrite>
                       <outputDirectory>${project.build.directory}/alternateLocation</outputDirectory>
                       <destFileName>optional-new-name.jar</destFileName>
                       <includes>**/*.class,**/*.xml</includes>
                       <excludes>**/*test.class</excludes>
                     </artifactItem>
                   </artifactItems>
                   <includes>**/*.java</includes>
                   <excludes>**/*.properties</excludes>
                   <outputDirectory>${project.build.directory}/wars</outputDirectory>
                   <overWriteReleases>false</overWriteReleases>
                   <overWriteSnapshots>true</overWriteSnapshots>
                 </configuration>
               </execution>
             </executions>
           </plugin>
         </plugins>
       </build>
       [...]
     </project>
</code>```

Body:
Use the maven-dependency-plugin. Here is an example of how you can extract the content of a dependency JAR:

    <project>
       [...]
       <build>
         <plugins>
           <plugin>
             <groupId>org.apache.maven.plugins</groupId>
             <artifactId>maven-dependency-plugin</artifactId>
             <version>3.1.2</version>
             <executions>
               <execution>
                 <id>unpack</id>
                 <phase>package</phase>
                 <goals>
                   <goal>unpack</goal>
                 </goals>
                 <configuration>
                   <artifactItems>
                     <artifactItem>
                       <groupId>junit</groupId>
                       <artifactId>junit</artifactId>
                       <version>3.8.1</version>
                       <type>jar</type>
                       <overWrite>false</overWrite>
                       <outputDirectory>${project.build.directory}/alternateLocation</outputDirectory>
                       <destFileName>optional-new-name.jar</destFileName>
                       <includes>**/*.class,**/*.xml</includes>
                       <excludes>**/*test.class</excludes>
                     </artifactItem>
                   </artifactItems>
                   <includes>**/*.java</includes>
                   <excludes>**/*.properties</excludes>
                   <outputDirectory>${project.build.directory}/wars</outputDirectory>
                   <overWriteReleases>false</overWriteReleases>
                   <overWriteSnapshots>true</overWriteSnapshots>
                 </configuration>
               </execution>
             </executions>
           </plugin>
         </plugins>
       </build>
       [...]
     </project>


问:
Outlook SMTP Oauth Send - Authentication Unsuccessful
I have been trying to implement email functionality in a legacy app using the Legacy Mail API to add OAuth support after getting a token through the Device Code Flow starting with the Microsoft Sample Project.

Along that route I have added SMTP.Send and many other API permissions to find the missing piece. (Including { "User.Read", "User.ReadBasic.All", "SMTP.Send", "offline_access", "Mail.Send" } in fear of missing one)

I have been testing with the MailKit library to build a proof of concept.

So far I have the following Code Snippet that fails after trying to authenticate.

```<code>public void SendSmtpMessageAsync(string id, string accessToken)
{
    var message = new MimeMessage();
    message.From.Add(new MailboxAddress("From Name", "From Address@Example.com"));
    message.To.Add(new MailboxAddress("To Name", "To Address@Example.com"));
    message.Subject = "How you doin'?";

    message.Body = new TextPart("plain")
    {
        Text = @"Test Email Content"
    };

    using (var client = new SmtpClient(new ProtocolLogger(Console.OpenStandardOutput())))
    {
        try
        {
            client.Connect("smtp.office365.com", 587, SecureSocketOptions.StartTls);

            var oauth2 = new SaslMechanismOAuth2(id, accessToken);

            var temp = client.AuthenticationMechanisms;
            client.Authenticate(oauth2);

            client.Send(message);
            client.Disconnect(true);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }
}
</code>```

MailKit Log

I have enabled logging and gotten a log that shows the client connecting than sending the token to authenticate but the authentication failing.

```<code>Connected to smtp://smtp.office365.com:587/?starttls=always
S: 220 MW3PR05CA0003.outlook.office365.com Microsoft ESMTP MAIL Service ready at Mon, 25 May 2020 21:31:07 +0000
C: EHLO [192.168.0.7]
S: 250-MW3PR05CA0003.outlook.office365.com Hello [<<My IP>>]
S: 250-SIZE 157286400
S: 250-PIPELINING
S: 250-DSN
S: 250-ENHANCEDSTATUSCODES
S: 250-STARTTLS
S: 250-8BITMIME
S: 250-BINARYMIME
S: 250-CHUNKING
S: 250 SMTPUTF8
C: STARTTLS
S: 220 2.0.0 SMTP server ready
C: EHLO [192.168.0.7]
S: 250-MW3PR05CA0003.outlook.office365.com Hello [<<My IP>>]
S: 250-SIZE 157286400
S: 250-PIPELINING
S: 250-DSN
S: 250-ENHANCEDSTATUSCODES
S: 250-AUTH LOGIN XOAUTH2
S: 250-8BITMIME
S: 250-BINARYMIME
S: 250-CHUNKING
S: 250 SMTPUTF8
C: AUTH XOAUTH2 <<Token omitted but I have confirmed that it is Base64 encoded and
in the format of base64("user=" + userName + "^Aauth=Bearer " + accessToken + "^A^A")>>
S: 535 5.7.3 Authentication unsuccessful [MW3PR05CA0003.namprd05.prod.outlook.com]
MailKit.Security.AuthenticationException: 535: 5.7.3 Authentication unsuccessful
[MW3PR05CA0003.namprd05.prod.outlook.com]
</code>```

Any direction or resources would be appreciated since most existing posts are from pre-2020 when Legacy SMTP support was added. Additionally, if you see any misunderstanding let me know so I can do some additional reading.

答: I had a similar problem, which was cause by my misconfiguration of Microsoft 365.   Please see MailKit unsuccessful SMTP OAuth with Microsoft 365 server for details.  Hope this helps.</p>

Body:
I have been trying to implement email functionality in a legacy app using the Legacy Mail API to add OAuth support after getting a token through the Device Code Flow starting with the Microsoft Sample Project.

Along that route I have added SMTP.Send and many other API permissions to find the missing piece. (Including { "User.Read", "User.ReadBasic.All", "SMTP.Send", "offline_access", "Mail.Send" } in fear of missing one)

I have been testing with the MailKit library to build a proof of concept.

So far I have the following Code Snippet that fails after trying to authenticate.

public void SendSmtpMessageAsync(string id, string accessToken)
{
    var message = new MimeMessage();
    message.From.Add(new MailboxAddress("From Name", "From Address@Example.com"));
    message.To.Add(new MailboxAddress("To Name", "To Address@Example.com"));
    message.Subject = "How you doin'?";

    message.Body = new TextPart("plain")
    {
        Text = @"Test Email Content"
    };

    using (var client = new SmtpClient(new ProtocolLogger(Console.OpenStandardOutput())))
    {
        try
        {
            client.Connect("smtp.office365.com", 587, SecureSocketOptions.StartTls);

            var oauth2 = new SaslMechanismOAuth2(id, accessToken);

            var temp = client.AuthenticationMechanisms;
            client.Authenticate(oauth2);

            client.Send(message);
            client.Disconnect(true);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }
}

MailKit Log

I have enabled logging and gotten a log that shows the client connecting than sending the token to authenticate but the authentication failing.

Connected to smtp://smtp.office365.com:587/?starttls=always
S: 220 MW3PR05CA0003.outlook.office365.com Microsoft ESMTP MAIL Service ready at Mon, 25 May 2020 21:31:07 +0000
C: EHLO [192.168.0.7]
S: 250-MW3PR05CA0003.outlook.office365.com Hello [<<My IP>>]
S: 250-SIZE 157286400
S: 250-PIPELINING
S: 250-DSN
S: 250-ENHANCEDSTATUSCODES
S: 250-STARTTLS
S: 250-8BITMIME
S: 250-BINARYMIME
S: 250-CHUNKING
S: 250 SMTPUTF8
C: STARTTLS
S: 220 2.0.0 SMTP server ready
C: EHLO [192.168.0.7]
S: 250-MW3PR05CA0003.outlook.office365.com Hello [<<My IP>>]
S: 250-SIZE 157286400
S: 250-PIPELINING
S: 250-DSN
S: 250-ENHANCEDSTATUSCODES
S: 250-AUTH LOGIN XOAUTH2
S: 250-8BITMIME
S: 250-BINARYMIME
S: 250-CHUNKING
S: 250 SMTPUTF8
C: AUTH XOAUTH2 <<Token omitted but I have confirmed that it is Base64 encoded and
in the format of base64("user=" + userName + "^Aauth=Bearer " + accessToken + "^A^A")>>
S: 535 5.7.3 Authentication unsuccessful [MW3PR05CA0003.namprd05.prod.outlook.com]
MailKit.Security.AuthenticationException: 535: 5.7.3 Authentication unsuccessful
[MW3PR05CA0003.namprd05.prod.outlook.com]

Any direction or resources would be appreciated since most existing posts are from pre-2020 when Legacy SMTP support was added. Additionally, if you see any misunderstanding let me know so I can do some additional reading.


问:
Problem with Git Repository in Xcode 4
In my iPhone app, I am using the in-built Git repository of Xcode 4 so that all the team members can work on the same project.

Now the problem is that even after I commit my changes to the repository, It still shows modified (M) symbol in front of the committed file.

What could be wrong?

I want to ensure that once I commit the changes it should not show "M" for that file.

Is there any setting which I have to do to make it work fine?

What can be done?

答: The built-in Git repository is a local repository only. How do you share that with your team? If you hooked that repository to GitHub, for example, you will experience problems as the implementation is not 100% reliable. I would use the command line in this case and git add/commit/push the changes. There are discussions and tutorials in the GitHub Blog.</p>

Title: Problem with Git Repository in Xcode 4


问:
Retrieving from a database table a value only if the record does not contain duplicates
I have a table with the following three values without any other constraints imposed via Schema

```<code>id_a
id_b
id_c
</code>```

so, there could be more than one row with the same id_b

Now, I want to write a query, that will give me only the rows where id_b is unique and matches a given value.

something like:

```<code>select * where id_b = ? and (id_b is unique)
</code>```

I know it is simple, but my brain in not working as it should, so any help pls.

答:
This query:

```<code>select id_b
from tablename
group by id_b
having count(*) = 1
</code>```

returns all the id_bs that you want, so use it with the operator IN:

```<code>select *
from tablename
where id_b in (
  select id_b
  from tablename
  group by id_b
  having count(*) = 1
)
</code>```

Body:
I have a table with the following three values without any other constraints imposed via Schema

id_a
id_b
id_c

so, there could be more than one row with the same id_b

Now, I want to write a query, that will give me only the rows where id_b is unique and matches a given value.

something like:

select * where id_b = ? and (id_b is unique)

I know it is simple, but my brain in not working as it should, so any help pls.

Body:
This query:

select id_b
from tablename
group by id_b
having count(*) = 1

returns all the id_bs that you want, so use it with the operator IN:

select *
from tablename
where id_b in (
  select id_b
  from tablename
  group by id_b
  having count(*) = 1
)


问:
Python :How to iterate over a list that has numbers as it's contents
I am trying to itereate over an integer list. Unfortunately, I am getting an error in this line.

```<code>odd_numbers = []
    for i in  range(1, 21, 2):
        odd_numbers.append(i)
    for odd in len(odd_numbers):
        print(odd_numbers[odd])
</code>```

How do I iterate over these integers using a for loop?

答:
Just avoid the len() in the second for loop. You have to iterate over the list, not over the length of this list (Which is an integer and leads to your error message). The following code runs.</p>

```<code>odd_numbers = []
for i in  range(1, 21, 2):
    odd_numbers.append(i)
for odd in odd_numbers:
    print(odd)
</code>```

Body:
I am trying to itereate over an integer list. Unfortunately, I am getting an error in this line.

odd_numbers = []
    for i in  range(1, 21, 2):
        odd_numbers.append(i)
    for odd in len(odd_numbers):
        print(odd_numbers[odd])

How do I iterate over these integers using a for loop?

Body:
Just avoid the len() in the second for loop. You have to iterate over the list, not over the length of this list (Which is an integer and leads to your error message). The following code runs.

odd_numbers = []
for i in  range(1, 21, 2):
    odd_numbers.append(i)
for odd in odd_numbers:
    print(odd)


问:
Python making multiple zip objects will overwrite the first one
I was working on a project when I came into this really weird bug, and I have managed to cut it down to this:

```<code>xr = zip(range(0, 5), range(0, 5))
yr = zip(range(3, 4), range(0, 1))

print(list(xr), list(yr))
print(list(xr))
</code>```

The expected output would be this:

```<code>[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] [(3, 0)]
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
</code>```

Because I don't change xr or yr after I set them. I am just printing them as a list to the shell. But, when I actually run it, I get this output:

```<code>[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] [(3, 0)]
[]
</code>```

I have absolutely no clue why. I have been using python for about a week, and maybe this is supposed to happen, but I would appreciate it if someone told me what's going on here. Thanks!

My python version is Python 3.8.3

答:
The zip function creates an iterator object, which can only be consumed once. This post explains why you cannot iterate over data twice.

This document explains the iterator class.

Body:
I was working on a project when I came into this really weird bug, and I have managed to cut it down to this:

xr = zip(range(0, 5), range(0, 5))
yr = zip(range(3, 4), range(0, 1))

print(list(xr), list(yr))
print(list(xr))

The expected output would be this:

[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] [(3, 0)]
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

Because I don't change xr or yr after I set them. I am just printing them as a list to the shell. But, when I actually run it, I get this output:

[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] [(3, 0)]
[]

I have absolutely no clue why. I have been using python for about a week, and maybe this is supposed to happen, but I would appreciate it if someone told me what's going on here. Thanks!

My python version is Python 3.8.3


问:
MQTT.js and Webpack - "WS is not a constructor"
I am trying to bundle one of our microservices which is using MQTT.js and I am struggling with really strange issue.

It is working fine without bundling, so ws is available in node_modules.

Stuff which I think matters:

error:

```<code>    TypeError: WS is not a constructor
        at WebSocketStream (dist/index.js:159329:16)
        at createWebSocket (dist/index.js:147450:10)
        at Object.buildBuilderBrowser (dist/index.js:147476:10)
        at MqttClient.wrapper [as streamBuilder] (dist/index.js:147937:36)
        at MqttClient._setupStream (dist/index.js:146471:22)
        at new MqttClient (dist/index.js:146452:8)
        at Function.connect (dist/index.js:147940:10)

</code>```

webpack config:

const path = require('path');
const nodeExternals = require('webpack-node-externals');

const { NODE_ENV = 'production' } = process.env;

module.exports = {
  entry: { index: './src/index.ts' },
  mode: NODE_ENV,
  target: 'node',
  watch: NODE_ENV === 'development',
  externals: [nodeExternals()],
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js',
  },
  resolve: {
    extensions: ['.ts', '.js'],
  },
  node: {
    __dirname: false,
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: [{ loader: 'ts-loader', options: { transpileOnly: true } }],
      },
      {
        test: /(\.md|\.map)$/,
        loader: 'null-loader',
      },
    ],
  },
};
```

<p>Function where it happens:</p>

<pre class="lang-js prettyprint-override"><code>createMqttClient(): MqttClient {
    return mqtt.connect(this.mqttOptions.url, { ...this.mqttOptions.options });
  }
</code>```

The url is like: ssl://url-to-our-mqtt

Can anybody help please?

答:
I experienced the same with Amazon aws-iot-device-sdk-js and Microsoft azure-iot-device-mqtt which both include mqtt.

The initial issue is the build error:

```<code>ERROR in ./node_modules/mqtt/mqtt.js Module parse failed: Unexpected character '#' (1:0)
</code>```

This error is caused by the package mqtt. Three files (mqtt.js, pub.js and sub.js) contain a shebang line

```<code>#!/usr/bin/env node
</code>```

The solution using module replacement suggested some places

```<code>plugins: [
   new webpack.NormalModuleReplacementPlugin(/^mqtt$/, "mqtt/dist/mqtt.js"),
 ],
</code>```

unfortunately changes the build error with the run time error

```<code>TypeError: WS is not a constructor
</code>```

As mentioned in other answers, webpack can be configured (https://webpack.js.org/concepts/loaders/)  to use the shebang loader (https://www.npmjs.com/package/shebang-loader)

TL;DR

Install shebang-loader

```<code>npm install shebang-loader --save
</code>```

In webpack.config.js use the loader

```<code>module.exports = {
...
    module: {
        rules: [
            {
                test:
                    [
                        /.*mqtt\.js$/,
                        /.*sub\.js$/,
                        /.*pub\.js$/
                    ],
                use: 'shebang-loader'
            }
        ]
    }
}
</code>```

Body:
I am trying to bundle one of our microservices which is using MQTT.js and I am struggling with really strange issue.

It is working fine without bundling, so ws is available in node_modules.

Stuff which I think matters:

error:

    TypeError: WS is not a constructor
        at WebSocketStream (dist/index.js:159329:16)
        at createWebSocket (dist/index.js:147450:10)
        at Object.buildBuilderBrowser (dist/index.js:147476:10)
        at MqttClient.wrapper [as streamBuilder] (dist/index.js:147937:36)
        at MqttClient._setupStream (dist/index.js:146471:22)
        at new MqttClient (dist/index.js:146452:8)
        at Function.connect (dist/index.js:147940:10)

webpack config:

const path = require('path');
const nodeExternals = require('webpack-node-externals');

const { NODE_ENV = 'production' } = process.env;

module.exports = {
  entry: { index: './src/index.ts' },
  mode: NODE_ENV,
  target: 'node',
  watch: NODE_ENV === 'development',
  externals: [nodeExternals()],
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js',
  },
  resolve: {
    extensions: ['.ts', '.js'],
  },
  node: {
    __dirname: false,
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: [{ loader: 'ts-loader', options: { transpileOnly: true } }],
      },
      {
        test: /(\.md|\.map)$/,
        loader: 'null-loader',
      },
    ],
  },
};

Function where it happens:

createMqttClient(): MqttClient {
    return mqtt.connect(this.mqttOptions.url, { ...this.mqttOptions.options });
  }

The url is like: ssl://url-to-our-mqtt

Can anybody help please?

Body:
I experienced the same with Amazon aws-iot-device-sdk-js and Microsoft azure-iot-device-mqtt which both include mqtt.

The initial issue is the build error:

ERROR in ./node_modules/mqtt/mqtt.js Module parse failed: Unexpected character '#' (1:0)

This error is caused by the package mqtt. Three files (mqtt.js, pub.js and sub.js) contain a shebang line

#!/usr/bin/env node

The solution using module replacement suggested some places

plugins: [
   new webpack.NormalModuleReplacementPlugin(/^mqtt$/, "mqtt/dist/mqtt.js"),
 ],

unfortunately changes the build error with the run time error

TypeError: WS is not a constructor

As mentioned in other answers, webpack can be configured (https://webpack.js.org/concepts/loaders/)  to use the shebang loader (https://www.npmjs.com/package/shebang-loader)

TL;DR

Install shebang-loader

npm install shebang-loader --save

In webpack.config.js use the loader

module.exports = {
...
    module: {
        rules: [
            {
                test:
                    [
                        /.*mqtt\.js$/,
                        /.*sub\.js$/,
                        /.*pub\.js$/
                    ],
                use: 'shebang-loader'
            }
        ]
    }
}


问:
Angular 8 - Multiple HTTP calls in a for loop
There is a list of unlimited cars in backend.
Each car has an id (unique id) and a name (car model name).

I have the list of car IDs, example:

const carIds = ['abc','xyz'];
```

<p>and I need to fetch respective car names for the above car Ids.
I tried the below code, but its not working at all, what is that I'm missing ?</p>

<pre class="lang-js prettyprint-override"><code>const carIds = ['abc','xyz']; // unique ids
const carsList = [];
for (const carId of carIds) {
  this.api.getCar(carId).pipe(
    map(response => {
      carsList.push({
        name: response.name,
        id: carId
      });
    })
  );
}
console.log(carsList); // When I run this, its printing nothing.
</code>```

Expected Output:

carsList = [{
 id: 'abc',
 name: 'benz'
},{
 id: 'xyz',
 name: 'mercede'
}]
```

Thanks in advance.

答:
```<code>const carsList = [];

for await (const carId of carIds) {
  const car = await this.api.getCar(carId);
  car && carsList.push({
        name: car.name,
        id: carId
      });
}

</code>```

Try this code. Happy to help :)

Body:
There is a list of unlimited cars in backend.
Each car has an id (unique id) and a name (car model name).

I have the list of car IDs, example:

const carIds = ['abc','xyz'];

and I need to fetch respective car names for the above car Ids.
I tried the below code, but its not working at all, what is that I'm missing ?

const carIds = ['abc','xyz']; // unique ids
const carsList = [];
for (const carId of carIds) {
  this.api.getCar(carId).pipe(
    map(response => {
      carsList.push({
        name: response.name,
        id: carId
      });
    })
  );
}
console.log(carsList); // When I run this, its printing nothing.

Expected Output:

carsList = [{
 id: 'abc',
 name: 'benz'
},{
 id: 'xyz',
 name: 'mercede'
}]

Thanks in advance.

Body:
const carsList = [];

for await (const carId of carIds) {
  const car = await this.api.getCar(carId);
  car && carsList.push({
        name: car.name,
        id: carId
      });
}

Try this code. Happy to help :)


问:
Jmeter - Compare/assert multiple data: Data from JSON against data from DB
For the purpose of my task i need to compare Data from JSON against data from DB, but i have few doubts how to build the scenario. My scenario is like:

1 Perform DB query

Which returns dynamic set like:

```<code>url secret
https://test1.com/  1234
https://test2.com/  1234
https://test3.com/  1234
</code>```

Based on this dynamic set, i drive my Loop controller to loop. Here from every single call, different JSON is produced like:

```<code>[
{
    "adminLink": "",
    "BTCAmount": 0,
    "lastName": "test",
    "amount": 1,
    "clientId": "e1d4ab18517711eaa84cfa163eb75a2c",
    "foundingSourceName": "test",
    "secretId": "2938663415",
    "txId": "",
    "mcTxId": "1079249234",
    "paymentAddress": "",
    "result": "transaction timed out",
    "firstName": "test",
    "phoneNumber": "",
    "currency": "USD",
    "refoundAmount": 0,
    "approveTime": 1582543463,
    "email": "",
    "status": 1,
    "timestamp": 1581938595
},
{
    "adminLink": "",
    "BTCAmount": 0,
    "lastName": "test",
    "amount": 550,
    "clientId": "ffe22f34742311eab73f06ed6719cf46",
    "foundingSourceName": "test",
    "secretId": "3096308675",
    "txId": "",
    "mcTxId": "1101155492",
    "paymentAddress": "",
    "result": "transaction timed out",
    "firstName": "test",
    "phoneNumber": "",
    "currency": "USD",
    "refoundAmount": 0,
    "approveTime": 1586355699,
    "email": "",
    "status": 1,
    "timestamp": 1585750862
}
]
</code>```

2 From this dynamic json, i can extract: mcTxId with:

3.
For every single mcTxId , i need to perform JDBC query using:

```<code>select *
FROM affiliate_transaction
WHERE affiliate_id = 1  and mctxid = '${mcTxId_1}'
</code>```

Which result to:

I managed to solve up to Loop Controller, and extract every single mcTxId, but i am stuck to nested looping logic, and assert each data.

How can i compare/assert every single clientId & approveTime between API call(json) and DB query, where their data set is always dynamic?

Any help is highly appreciated.
Apologies for the long post

答:
Change your query to select client_id
FROM affiliate_transaction
WHERE affiliate_id = 1  and mctxid = '${mcTxId_1}' and store it into a JMeter Variable like client_id_from_db

Use JSON Extractor to get the client ID from the API  and store it into a JMeter Variable like client_id_from_api

Once done you should be able to compare 2 JMeter Variables using Response Assertion

Body:
For the purpose of my task i need to compare Data from JSON against data from DB, but i have few doubts how to build the scenario. My scenario is like:

1 Perform DB query

Which returns dynamic set like:

url secret
https://test1.com/  1234
https://test2.com/  1234
https://test3.com/  1234

Based on this dynamic set, i drive my Loop controller to loop. Here from every single call, different JSON is produced like:

[
{
    "adminLink": "",
    "BTCAmount": 0,
    "lastName": "test",
    "amount": 1,
    "clientId": "e1d4ab18517711eaa84cfa163eb75a2c",
    "foundingSourceName": "test",
    "secretId": "2938663415",
    "txId": "",
    "mcTxId": "1079249234",
    "paymentAddress": "",
    "result": "transaction timed out",
    "firstName": "test",
    "phoneNumber": "",
    "currency": "USD",
    "refoundAmount": 0,
    "approveTime": 1582543463,
    "email": "",
    "status": 1,
    "timestamp": 1581938595
},
{
    "adminLink": "",
    "BTCAmount": 0,
    "lastName": "test",
    "amount": 550,
    "clientId": "ffe22f34742311eab73f06ed6719cf46",
    "foundingSourceName": "test",
    "secretId": "3096308675",
    "txId": "",
    "mcTxId": "1101155492",
    "paymentAddress": "",
    "result": "transaction timed out",
    "firstName": "test",
    "phoneNumber": "",
    "currency": "USD",
    "refoundAmount": 0,
    "approveTime": 1586355699,
    "email": "",
    "status": 1,
    "timestamp": 1585750862
}
]

2 From this dynamic json, i can extract: mcTxId with:

3.
For every single mcTxId , i need to perform JDBC query using:

select *
FROM affiliate_transaction
WHERE affiliate_id = 1  and mctxid = '${mcTxId_1}'

Which result to:

I managed to solve up to Loop Controller, and extract every single mcTxId, but i am stuck to nested looping logic, and assert each data.

How can i compare/assert every single clientId & approveTime between API call(json) and DB query, where their data set is always dynamic?

Any help is highly appreciated.
Apologies for the long post


问:
Plotly express line chart - get default colors (how to color lines as specified by a dictionary object?)
I have a data frame of a multivariate time series, for which I've created a interactive plotly express plot. I'm adding vertical lines at particular locations specified by a dictionary, each line associated to one of the time series, and wish to set the line color to agree with that of the corresponding variable. In essence, in the picture below, each vertical segment can be identified with one of Fp1 or Fp2 and I want to color it as red or black accordingly:

First I plot the data frame, where X is my time series matrix, plotly.express has been imported as px, pandas imported as pd, and channels=['Fp1','Fp2']:

```<code>df=pd.DataFrame(X,columns=channels)
df['id'] = df.index
df = pd.melt(df, id_vars='id', value_vars=df.columns[:-1])
fig = px.line(df, x='id', y='value', color='variable',labels = {'id':'time (20K~100 sec)',
'value':'millivolts','variable':'channel'},title='Patient')
</code>```

Subsequent calculations yield a dictionary, HFOs, where each key corresponds is one of my two channels, and each value is a list of times, e.g. something of the form

```<code>HFOs={'Fp1':[500,....,10500],'Fp2':[800,...11000]}
</code>```

I then created my lines and added them to the figure:

```<code>for channel,times in HFOs.items():
    for t in times:
        fig.add_shape(type='line',yref="y",xref="x",
        x0=t,y0=df['value'].min()*1.2,x1=t,y1=df['value'].max()*1.2,line=dict(color='black',
        width=.25))
        fig.add_trace(go.Scatter(x=[t],y=
        [df['value'].max()*1.5],mode='text',showlegend=False))
fig.show()
</code>```

This creates the image shown above. How do I modify
     line=dict(color='black',width=.25)
to change the color to what I want? I wish for the vertical lines at times [500,....,10500]to be blue and times [800,...11000] to be red. (Of course, in the future, there will be many more channels.)

I tried replacing 'black' with 'variable" but that, not surprisingly, just resulted in an error message. I feel there must be a very simple way to achieve my goal.

答:
Cool question. There might be a better solution, but here's the one I found. Replace the code that creates the vertical lines with the following:

```<code># fetch the colors of the traces from the figure.
colors = [trace.line["color"] for trace in fig.data]

for inx, (channel,times) in enumerate(HFOs.items()):
    for t in times:
        fig.add_shape(type='line',yref="y",xref="x",
        x0=t,y0=df['value'].min()*1.2,x1=t,y1=df['value'].max()*2,
                      line=dict(color=colors[inx], width=3))
fig.show()
</code>```

The resulting figure looks as follows (Random data, made the vertical lines wider
for visibility):

An alternative way to get the list of default colors is to use

px.colors.qualitative.Plotly, which produces a list of 10 hex color codes. My understanding is that these colors would be used for the first 10 series, and then used again for traces 11-20, etc.

Body:
I have a data frame of a multivariate time series, for which I've created a interactive plotly express plot. I'm adding vertical lines at particular locations specified by a dictionary, each line associated to one of the time series, and wish to set the line color to agree with that of the corresponding variable. In essence, in the picture below, each vertical segment can be identified with one of Fp1 or Fp2 and I want to color it as red or black accordingly:

First I plot the data frame, where X is my time series matrix, plotly.express has been imported as px, pandas imported as pd, and channels=['Fp1','Fp2']:

df=pd.DataFrame(X,columns=channels)
df['id'] = df.index
df = pd.melt(df, id_vars='id', value_vars=df.columns[:-1])
fig = px.line(df, x='id', y='value', color='variable',labels = {'id':'time (20K~100 sec)',
'value':'millivolts','variable':'channel'},title='Patient')

Subsequent calculations yield a dictionary, HFOs, where each key corresponds is one of my two channels, and each value is a list of times, e.g. something of the form

HFOs={'Fp1':[500,....,10500],'Fp2':[800,...11000]}

I then created my lines and added them to the figure:

for channel,times in HFOs.items():
    for t in times:
        fig.add_shape(type='line',yref="y",xref="x",
        x0=t,y0=df['value'].min()*1.2,x1=t,y1=df['value'].max()*1.2,line=dict(color='black',
        width=.25))
        fig.add_trace(go.Scatter(x=[t],y=
        [df['value'].max()*1.5],mode='text',showlegend=False))
fig.show()

This creates the image shown above. How do I modify
     line=dict(color='black',width=.25)
to change the color to what I want? I wish for the vertical lines at times [500,....,10500]to be blue and times [800,...11000] to be red. (Of course, in the future, there will be many more channels.)

I tried replacing 'black' with 'variable" but that, not surprisingly, just resulted in an error message. I feel there must be a very simple way to achieve my goal.

Body:
Cool question. There might be a better solution, but here's the one I found. Replace the code that creates the vertical lines with the following:

# fetch the colors of the traces from the figure.
colors = [trace.line["color"] for trace in fig.data]

for inx, (channel,times) in enumerate(HFOs.items()):
    for t in times:
        fig.add_shape(type='line',yref="y",xref="x",
        x0=t,y0=df['value'].min()*1.2,x1=t,y1=df['value'].max()*2,
                      line=dict(color=colors[inx], width=3))
fig.show()

The resulting figure looks as follows (Random data, made the vertical lines wider
for visibility):

An alternative way to get the list of default colors is to use

px.colors.qualitative.Plotly, which produces a list of 10 hex color codes. My understanding is that these colors would be used for the first 10 series, and then used again for traces 11-20, etc.


问:
Get date from dataset
```<code> df <- read.csv('https://raw.githubusercontent.com/ulklc/covid19-
 timeseries/master/countryReport/raw/rawReport.csv')
 df$countryName = as.character(df$countryName)
</code>```

I processed the dataset.

How can I find the countries that report the most patients, death and recovery in one day?

Examples:

1 June 2020 the country that reported the most deaths, 1 june the country that reported the case and 1 June the country that reported the most recoved

答:
The below code uses the dplyr R package to create a data frame called records that contains the data you desire.  Make sure you have dplyr installed by running install.package("dplyr") in R or RStudio.

```<code>## call the dplyr library
library(dplyr)
## read in your data to R
df <- read.csv ('https://raw.githubusercontent.com/ulklc/covid19-timeseries/master/countryReport/raw/rawReport.csv', stringsAsFactors = FALSE)
## set the date you wish to query max records for
set.date <- "2020-06-01"
## copy the data to preserve the original
df1 <- df
## filter the records to only those that match the specified date
df1 <- filter(df1, as.Date(date, "%Y/%m/%d") == as.Date(set.date))
## determine which country had the most confirmed on the specified day
max.confirmed <- df1[which.max(df1$confirmed),]
## format the record to identify it as the record with most confirmed
max.confirmed$confirmed <- paste0("**",max.confirmed$confirmed,"**")
## determine which country had the most deaths on the specified day
max.deaths <- df1[which.max(df1$death),]
## format the record to identify it as the record with most deaths
max.deaths$death <- paste0("**",max.deaths$death,"**")
## determine which country had the most recovered on the specified day
max.recovered <- df1[which.max(df1$recovered),]
## format the record to identify it as the record with most recovered
max.recovered$recovered <- paste0("**",max.recovered$recovered,"**")
## create the reocrds data frame to contain your max records
records <- rbind(max.confirmed, max.deaths, max.recovered)
</code>```

You can update the date you wish to select by by changing "2020-06-01" to the date you desire to query max death and recovered for.  Make sure to use the "YYYY-MM-DD" format.

Alternatively, instead of manually updating the code, you can use the readline() function to ask the user to input the date they would like to query max data for.

ADDED (based on comments)
If you want to use today's data (or if today's data is not available the most recent data) you can use the code below:

```<code>## call the dplyr library
library(dplyr)
## read the data into R
df <- read.csv ('https://raw.githubusercontent.com/ulklc/covid19-timeseries/master/countryReport/raw/rawReport.csv', stringsAsFactors = FALSE)
## determine the max date contained within the data
max.date <- df[which.max(as.Date(df$day)),"day"]
## copy the data to preserve original
df1 <- df
## filter the data to only entries from the max day
df1 <- filter(df1, as.Date(date, "%Y/%m/%d") == as.Date(max.date))
## determine the entry with the most deaths
max.deaths <- df1[which.max(df1$death),]
## format the number of deaths as given in the example
max.deaths$death <- paste0("**",max.deaths$death,"**")
## determine the entry with the most recovered
max.recovered <- df1[which.max(df1$recovered),]
## format the number recovered to match the format of the example
max.recovered$recovered <- paste0("**",max.recovered$recovered,"**")
## create a data frame containing our max death and max recovered entries
max.records <- rbind(max.deaths, max.recovered)
## attach a column with the max date which corresponds to the date of the entries selected
max.records$date <- max.date
## organize the data as shown in the example
max.records <- select(max.records, c("day","countryName","death","recovered"))
</code>```

I hope this helps!

Title: Get date from dataset

Body:
 df <- read.csv('https://raw.githubusercontent.com/ulklc/covid19-
 timeseries/master/countryReport/raw/rawReport.csv')
 df$countryName = as.character(df$countryName)

I processed the dataset.

How can I find the countries that report the most patients, death and recovery in one day?

Examples:

1 June 2020 the country that reported the most deaths, 1 june the country that reported the case and 1 June the country that reported the most recoved

Body:
The below code uses the dplyr R package to create a data frame called records that contains the data you desire.  Make sure you have dplyr installed by running install.package("dplyr") in R or RStudio.

## call the dplyr library
library(dplyr)
## read in your data to R
df <- read.csv ('https://raw.githubusercontent.com/ulklc/covid19-timeseries/master/countryReport/raw/rawReport.csv', stringsAsFactors = FALSE)
## set the date you wish to query max records for
set.date <- "2020-06-01"
## copy the data to preserve the original
df1 <- df
## filter the records to only those that match the specified date
df1 <- filter(df1, as.Date(date, "%Y/%m/%d") == as.Date(set.date))
## determine which country had the most confirmed on the specified day
max.confirmed <- df1[which.max(df1$confirmed),]
## format the record to identify it as the record with most confirmed
max.confirmed$confirmed <- paste0("**",max.confirmed$confirmed,"**")
## determine which country had the most deaths on the specified day
max.deaths <- df1[which.max(df1$death),]
## format the record to identify it as the record with most deaths
max.deaths$death <- paste0("**",max.deaths$death,"**")
## determine which country had the most recovered on the specified day
max.recovered <- df1[which.max(df1$recovered),]
## format the record to identify it as the record with most recovered
max.recovered$recovered <- paste0("**",max.recovered$recovered,"**")
## create the reocrds data frame to contain your max records
records <- rbind(max.confirmed, max.deaths, max.recovered)

You can update the date you wish to select by by changing "2020-06-01" to the date you desire to query max death and recovered for.  Make sure to use the "YYYY-MM-DD" format.

Alternatively, instead of manually updating the code, you can use the readline() function to ask the user to input the date they would like to query max data for.

ADDED (based on comments)
If you want to use today's data (or if today's data is not available the most recent data) you can use the code below:

## call the dplyr library
library(dplyr)
## read the data into R
df <- read.csv ('https://raw.githubusercontent.com/ulklc/covid19-timeseries/master/countryReport/raw/rawReport.csv', stringsAsFactors = FALSE)
## determine the max date contained within the data
max.date <- df[which.max(as.Date(df$day)),"day"]
## copy the data to preserve original
df1 <- df
## filter the data to only entries from the max day
df1 <- filter(df1, as.Date(date, "%Y/%m/%d") == as.Date(max.date))
## determine the entry with the most deaths
max.deaths <- df1[which.max(df1$death),]
## format the number of deaths as given in the example
max.deaths$death <- paste0("**",max.deaths$death,"**")
## determine the entry with the most recovered
max.recovered <- df1[which.max(df1$recovered),]
## format the number recovered to match the format of the example
max.recovered$recovered <- paste0("**",max.recovered$recovered,"**")
## create a data frame containing our max death and max recovered entries
max.records <- rbind(max.deaths, max.recovered)
## attach a column with the max date which corresponds to the date of the entries selected
max.records$date <- max.date
## organize the data as shown in the example
max.records <- select(max.records, c("day","countryName","death","recovered"))

I hope this helps!


问:
Backspacing in C# window forms
So i'm making a self grading aptitude test that is done except for, if I backspace the entire field of a textbox to be empty is errors out and closes, not upon pressing but upon clearing all the characters. I've been reading some documentation and have had a hard time finding a proper way to implement some way to handle this error. the message after crashing is: This exception was originally thrown at this call stack:

```<code>private void AA3_TextChanged(object sender, EventArgs e)
        {
            int A3 = Int32.Parse(AA3.Text);
            if (A3 == 14200)
            {

                percent +=1;
                exp.Text = percent.ToString();

            }
        }
</code>```

the code inside is just a counter for the grade at the end, but i am lost why some backspace is okay but not a clear field. Sorry if this is poorly worded.

答:
You have to either use Int32.TryParse or validate the text before parsing.

```<code>if(string.IsNullOrEmpty("string")) return;
</code>```

Or

```<code>Int32.TryParse("331", out int value);
</code>```

Title: Backspacing in C# window forms

Body:
So i'm making a self grading aptitude test that is done except for, if I backspace the entire field of a textbox to be empty is errors out and closes, not upon pressing but upon clearing all the characters. I've been reading some documentation and have had a hard time finding a proper way to implement some way to handle this error. the message after crashing is: This exception was originally thrown at this call stack:

private void AA3_TextChanged(object sender, EventArgs e)
        {
            int A3 = Int32.Parse(AA3.Text);
            if (A3 == 14200)
            {

                percent +=1;
                exp.Text = percent.ToString();

            }
        }

the code inside is just a counter for the grade at the end, but i am lost why some backspace is okay but not a clear field. Sorry if this is poorly worded.

Body:
You have to either use Int32.TryParse or validate the text before parsing.

if(string.IsNullOrEmpty("string")) return;

Or

Int32.TryParse("331", out int value);