问:
How to set yAxis min/max in Highcharts synchronized chart with JSON
I am working with the synchronised chart of Highchart. Pretty cool. However, I would like to »dictate« the min and max values for the yAxis. I added these two parameters into the JSON file, but they are not being accepted unfortunately.

JSON file:

```<code>    "unit": "km/h",
    "type": "line",
    "min": -2,
    "max": 16,
</code>```

yAxis definition:

```<code>     yAxis: {
        title: {
           text: null
        },
        min: dataset.min,
        max: dataset.max
     },
</code>```

but that doesn't work. Any idea why? Here is the original graphic I am working with. Here is a fiddle.

答:
In Highcharts API we can read:

max: number, null

...

If the endOnTick option is true, the max value might be rounded up. (...)

As a solution disable startOnTick and endOnTick options or use tickPositioner function to calculate and set tick postion manually, for example:

```<code>            yAxis: {
                ...,
                tickPositioner: function(){
                    var ticks = [],
                    step = (dataset.max - dataset.min) / 4;

                  for (var i = dataset.min; i <= dataset.max; i += step) {
                    ticks.push(i);
                  }

                  return ticks;
                }
            }
</code>```

Live demo: https://jsfiddle.net/BlackLabel/ev5hz0pk/

API Reference:

https://api.highcharts.com/highcharts/yAxis.max

https://api.highcharts.com/highcharts/yAxis.tickPositioner

Body:
I am working with the synchronised chart of Highchart. Pretty cool. However, I would like to »dictate« the min and max values for the yAxis. I added these two parameters into the JSON file, but they are not being accepted unfortunately.

JSON file:

    "unit": "km/h",
    "type": "line",
    "min": -2,
    "max": 16,

yAxis definition:

     yAxis: {
        title: {
           text: null
        },
        min: dataset.min,
        max: dataset.max
     },

but that doesn't work. Any idea why? Here is the original graphic I am working with. Here is a fiddle.

Body:
In Highcharts API we can read:

max: number, null

...

If the endOnTick option is true, the max value might be rounded up. (...)

As a solution disable startOnTick and endOnTick options or use tickPositioner function to calculate and set tick postion manually, for example:

            yAxis: {
                ...,
                tickPositioner: function(){
                    var ticks = [],
                    step = (dataset.max - dataset.min) / 4;

                  for (var i = dataset.min; i <= dataset.max; i += step) {
                    ticks.push(i);
                  }

                  return ticks;
                }
            }

Live demo: https://jsfiddle.net/BlackLabel/ev5hz0pk/

API Reference:

https://api.highcharts.com/highcharts/yAxis.max

https://api.highcharts.com/highcharts/yAxis.tickPositioner


来源: stackexchange

问:
Apache poi add label in excel chart
```<code>public class LineChart {

    public static void main(String[] args) throws IOException {
        try (XSSFWorkbook wb = new XSSFWorkbook()) {
            XSSFSheet sheet = wb.createSheet("linechart");
            final int NUM_OF_ROWS = 3;
            final int NUM_OF_COLUMNS = 10;

            // Create a row and put some cells in it. Rows are 0 based.
            Row row;
            Cell cell;
            for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) {
                row = sheet.createRow((short) rowIndex);
                for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) {
                    cell = row.createCell((short) colIndex);
                    cell.setCellValue(colIndex * (rowIndex + 1.0));
                }
            }

            XSSFDrawing drawing = sheet.createDrawingPatriarch();
            XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15);

            XSSFChart chart = drawing.createChart(anchor);
            XDDFChartLegend legend = chart.getOrAddLegend();
            legend.setPosition(LegendPosition.BOTTOM);

            // Use a category axis for the bottom axis.
            XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
            //bottomAxis.setTitle("x"); // https://stackoverflow.com/questions/32010765
            XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT);
            //leftAxis.setTitle("f(x)");
            leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);

            XDDFDataSource<Double> xs = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1));
            XDDFNumericalDataSource<Double> ys1 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1));
            XDDFNumericalDataSource<Double> ys2 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1));

            XDDFLineChartData data = (XDDFLineChartData) chart.createData(ChartTypes.LINE, bottomAxis, leftAxis);
            XDDFLineChartData.Series series1 = (XDDFLineChartData.Series) data.addSeries(xs, ys1);
            series1.setTitle("2x", null); // https://stackoverflow.com/questions/21855842
            series1.setSmooth(false); // https://stackoverflow.com/questions/29014848
            series1.setMarkerStyle(MarkerStyle.DOT); // https://stackoverflow.com/questions/39636138
            series1.setShowLeaderLines(true);
            XDDFLineChartData.Series series2 = (XDDFLineChartData.Series) data.addSeries(xs, ys2);
            series2.setTitle("3x", null);
            //series2.setSmooth(true);
            //series2.setMarkerSize((short) 6);
            //series2.setMarkerStyle(MarkerStyle.NONE); // https://stackoverflow.com/questions/39636138
            series2.setShowLeaderLines(false);

            chart.plot(data);

            // if your series have missing values like https://stackoverflow.com/questions/29014848
            // chart.displayBlanksAs(DisplayBlanks.GAP);

            // https://stackoverflow.com/questions/24676460
            solidLineSeries(data, 0, PresetColor.CHARTREUSE);
            solidLineSeries(data, 1, PresetColor.BLACK);

            // Write the output to a file
            try (FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx")) {
                wb.write(fileOut);
            }
        }
    }
    //CTPresetLineDashProperties
    private static void solidLineSeries(XDDFChartData data, int index, PresetColor color) {
        XDDFSolidFillProperties fill = new XDDFSolidFillProperties(XDDFColor.from(color));
        XDDFLineProperties line = new XDDFLineProperties();
        //line.setPresetDash(new XDDFPresetLineDash(PresetLineDash.DOT));
        line.setFillProperties(fill);
        XDDFChartData.Series series = data.getSeries().get(index);
        XDDFShapeProperties properties = series.getShapeProperties();
        if (properties == null) {
            properties = new XDDFShapeProperties();
        }
        properties.setLineProperties(line);
        series.setShapeProperties(properties);
    }
}
</code>```

This is an example from:
http://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/xssf/usermodel/examples/LineChart.java

And I use poi version is 4.1.1.

when I use series1.setShowLeaderLines(true) or series2.setShowLeaderLines(false)
it will show label as picture 1, and contains Series Name, Category Name, Value and Legend Key,
also label position is Right.

Is it possible to change it picture 2 which just contain Value and label position is Center?
Thank you

current view   what I want

答:
The problem is that XDDF is not complete yet. The XDDFLineChartData.Series.setShowLeaderLines sets default data lables if not present.

As of current Excel versions default data lables means including value, legend key, category name and series name. So all this is shown.

XDDFLineChartData.Series lacks methods for customizing the data labels except of the leader lines. So this needs to be done using the low level ooxml-schemas classes and methods.

In your case:

```<code>...
            series1.setShowLeaderLines(true); // this sets default data lables
            // customizing data labels
            int seriesNr = 0;
            //chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(seriesNr).getDLbls()
            // .addNewSpPr().addNewSolidFill().addNewSrgbClr().setVal(new byte[]{(byte)255,(byte)255,0});
            chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(seriesNr).getDLbls()
             .addNewDLblPos().setVal(org.openxmlformats.schemas.drawingml.x2006.chart.STDLblPos.CTR);
            chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(seriesNr).getDLbls().addNewShowVal().setVal(true);
            chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(seriesNr).getDLbls().addNewShowLegendKey().setVal(false);
            chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(seriesNr).getDLbls().addNewShowCatName().setVal(false);
            chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(seriesNr).getDLbls().addNewShowSerName().setVal(false);
...
</code>```

ContentLicense: CC BY-SA 4.0

Title: Apache poi add label in excel chart

Body:
public class LineChart {

    public static void main(String[] args) throws IOException {
        try (XSSFWorkbook wb = new XSSFWorkbook()) {
            XSSFSheet sheet = wb.createSheet("linechart");
            final int NUM_OF_ROWS = 3;
            final int NUM_OF_COLUMNS = 10;

            // Create a row and put some cells in it. Rows are 0 based.
            Row row;
            Cell cell;
            for (int rowIndex = 0; rowIndex < NUM_OF_ROWS; rowIndex++) {
                row = sheet.createRow((short) rowIndex);
                for (int colIndex = 0; colIndex < NUM_OF_COLUMNS; colIndex++) {
                    cell = row.createCell((short) colIndex);
                    cell.setCellValue(colIndex * (rowIndex + 1.0));
                }
            }

            XSSFDrawing drawing = sheet.createDrawingPatriarch();
            XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15);

            XSSFChart chart = drawing.createChart(anchor);
            XDDFChartLegend legend = chart.getOrAddLegend();
            legend.setPosition(LegendPosition.BOTTOM);

            // Use a category axis for the bottom axis.
            XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
            //bottomAxis.setTitle("x"); // https://stackoverflow.com/questions/32010765
            XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT);
            //leftAxis.setTitle("f(x)");
            leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);

            XDDFDataSource<Double> xs = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(0, 0, 0, NUM_OF_COLUMNS - 1));
            XDDFNumericalDataSource<Double> ys1 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(1, 1, 0, NUM_OF_COLUMNS - 1));
            XDDFNumericalDataSource<Double> ys2 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(2, 2, 0, NUM_OF_COLUMNS - 1));

            XDDFLineChartData data = (XDDFLineChartData) chart.createData(ChartTypes.LINE, bottomAxis, leftAxis);
            XDDFLineChartData.Series series1 = (XDDFLineChartData.Series) data.addSeries(xs, ys1);
            series1.setTitle("2x", null); // https://stackoverflow.com/questions/21855842
            series1.setSmooth(false); // https://stackoverflow.com/questions/29014848
            series1.setMarkerStyle(MarkerStyle.DOT); // https://stackoverflow.com/questions/39636138
            series1.setShowLeaderLines(true);
            XDDFLineChartData.Series series2 = (XDDFLineChartData.Series) data.addSeries(xs, ys2);
            series2.setTitle("3x", null);
            //series2.setSmooth(true);
            //series2.setMarkerSize((short) 6);
            //series2.setMarkerStyle(MarkerStyle.NONE); // https://stackoverflow.com/questions/39636138
            series2.setShowLeaderLines(false);

            chart.plot(data);

            // if your series have missing values like https://stackoverflow.com/questions/29014848
            // chart.displayBlanksAs(DisplayBlanks.GAP);

            // https://stackoverflow.com/questions/24676460
            solidLineSeries(data, 0, PresetColor.CHARTREUSE);
            solidLineSeries(data, 1, PresetColor.BLACK);

            // Write the output to a file
            try (FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx")) {
                wb.write(fileOut);
            }
        }
    }
    //CTPresetLineDashProperties
    private static void solidLineSeries(XDDFChartData data, int index, PresetColor color) {
        XDDFSolidFillProperties fill = new XDDFSolidFillProperties(XDDFColor.from(color));
        XDDFLineProperties line = new XDDFLineProperties();
        //line.setPresetDash(new XDDFPresetLineDash(PresetLineDash.DOT));
        line.setFillProperties(fill);
        XDDFChartData.Series series = data.getSeries().get(index);
        XDDFShapeProperties properties = series.getShapeProperties();
        if (properties == null) {
            properties = new XDDFShapeProperties();
        }
        properties.setLineProperties(line);
        series.setShapeProperties(properties);
    }
}

This is an example from:
http://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/xssf/usermodel/examples/LineChart.java

And I use poi version is 4.1.1.

when I use series1.setShowLeaderLines(true) or series2.setShowLeaderLines(false)
it will show label as picture 1, and contains Series Name, Category Name, Value and Legend Key,
also label position is Right.

Is it possible to change it picture 2 which just contain Value and label position is Center?
Thank you

current view   what I want

Body:
The problem is that XDDF is not complete yet. The XDDFLineChartData.Series.setShowLeaderLines sets default data lables if not present.

As of current Excel versions default data lables means including value, legend key, category name and series name. So all this is shown.

XDDFLineChartData.Series lacks methods for customizing the data labels except of the leader lines. So this needs to be done using the low level ooxml-schemas classes and methods.

In your case:

...
            series1.setShowLeaderLines(true); // this sets default data lables
            // customizing data labels
            int seriesNr = 0;
            //chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(seriesNr).getDLbls()
            // .addNewSpPr().addNewSolidFill().addNewSrgbClr().setVal(new byte[]{(byte)255,(byte)255,0});
            chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(seriesNr).getDLbls()
             .addNewDLblPos().setVal(org.openxmlformats.schemas.drawingml.x2006.chart.STDLblPos.CTR);
            chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(seriesNr).getDLbls().addNewShowVal().setVal(true);
            chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(seriesNr).getDLbls().addNewShowLegendKey().setVal(false);
            chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(seriesNr).getDLbls().addNewShowCatName().setVal(false);
            chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(seriesNr).getDLbls().addNewShowSerName().setVal(false);
...


问:
How To Return The Right of An Either
I have a value of this type:

List[Either[Error, Files]]
```

<p>and I have a function which checks if there are any errors like this:</p>

<pre class="lang-scala prettyprint-override"><code>  private def process(result: List[Either[Error, Files]]): Either[Error, List[Files]] = {
    if(result.exists(p => p.isLeft)){
      Left(Error("some downloads failed"))
    }else{
      Right(
      Right(
        result.collect {
          case Right(value) => value
        }
      )

    }

  }
</code>```

Is this the best way to return the List of files if there are no errors in result?

答:
You can use foldLeft in this case, to collect either all errors or all files. I don't know how Error looks like, but suppose it is simple case class with message string inside:

```<code>case class Error(message: String) {
  def append(message: Error): Error = copy(message = message + s"; ${message.message}")
}

def process(result: List[Either[Error, Files]]): Either[Error, List[Files]] = {
  val init: Either[Error, List[Files]] = Right(Nil)
  result.foldLeft(init) {
    case (Left(allErrors), Left(currentError)) => Left(allErrors.append(currentError))
    case (Left(allErrors), Right(_)) => Left(allErrors)
    case (Right(_), Left(currentError)) => Left(currentError)
    case (Right(allFiles), Right(currentFile)) => Right(currentFile :: allFiles)
  }
}
</code>```

Hope this helps!

Title: How To Return The Right of An Either

Body:
I have a value of this type:

List[Either[Error, Files]]

and I have a function which checks if there are any errors like this:

  private def process(result: List[Either[Error, Files]]): Either[Error, List[Files]] = {
    if(result.exists(p => p.isLeft)){
      Left(Error("some downloads failed"))
    }else{
      Right(
      Right(
        result.collect {
          case Right(value) => value
        }
      )

    }

  }

Is this the best way to return the List of files if there are no errors in result?

Body:
You can use foldLeft in this case, to collect either all errors or all files. I don't know how Error looks like, but suppose it is simple case class with message string inside:

case class Error(message: String) {
  def append(message: Error): Error = copy(message = message + s"; ${message.message}")
}

def process(result: List[Either[Error, Files]]): Either[Error, List[Files]] = {
  val init: Either[Error, List[Files]] = Right(Nil)
  result.foldLeft(init) {
    case (Left(allErrors), Left(currentError)) => Left(allErrors.append(currentError))
    case (Left(allErrors), Right(_)) => Left(allErrors)
    case (Right(_), Left(currentError)) => Left(currentError)
    case (Right(allFiles), Right(currentFile)) => Right(currentFile :: allFiles)
  }
}

Hope this helps!


问:
bootstrap 4 img-fluid does not change image height
Responsive Images in Bootstrap 4, with class .img-fluid are resized disproportionally. They keep it's height even width is shrinking down correctly. That is deforming whole image. Is there any way how to make it as smooth as it was in Bootstrap 3 with class .img-responsive? Thanks

```<code><div class="col-sm-6">
    <img class="img-fluid" src="/assets/blogs/14853991244821.jpg" alt="">
</div>
</code>```

By the way it is same in Bootstrap 4 documentation (https://v4-alpha.getbootstrap.com/content/images/) where sample svg image keeps height 250 pixels regardless of it's width.

答:
We have an (asp.net core 2.2) app (public portal) with Bootstrap 4.x, whereby the customer can upload his own images and use the img-fluid on various views (with different sizes) in flex.

The images are scaled (resized) automatically by the upload to the size how the images are showed to the end users ("query view").

On the editing view, we have to show the images with correct aspect ratio but smaller.

The end user view is optimized to show the images in landscape ( 1 ) format, but the customer also is able to upload images in portrait ( 2 ) format (the images then have to be scaled to a given height) what is not a problem on the end user view, as the images are scaled automatically correctly by the upload, but in the (smaller) editing view, it definitely is a problem...

Per default, the .img-fluid class applies max-width: 100%; and height: auto; to the image:
In my case (I set the width), this leads to a scale of a portrait image to the full width ( 2 ) , what shows the image

way to high ( 3 ).

I want to scale the height to to a given height ( 4 )  (in the example it is 185 Pixel).

Principally, I would be able to overwrite the max-height to the img-fluid to have the needed hight:

```<code> img-fluid {
  max-height: 185px;
}
</code>```

But this would be a really bad idea, as it would affect all images on all views.

The only solution, that works for my case is:

to overwrite the max-height to 100%:

```<code>.img-fluid {
  max-height: 100%;
}
</code>```

and set the height to the container control explicitly to the needed height:

```<code><div id="WirUeberUnsFotoUpload" style="height:185px">
   <div> --- Noch kein Foto  hochgeladen --- </div>
</div>
</code>```

Note: The Text to the div „ --- Noch kein Foto  hochgeladen --- „ is replaced by the uploaded image via JQuery at runtime.

This leads to the wanted result ( 5 ) :

This way, the image ( 5 )  is scaled correct to the needed height ( 4 ) and don’t affect the other views.

Note: Both, to set the height to the container and to set max-height: 100% is needed.

ContentLicense: CC BY-SA 3.0

Body:
Responsive Images in Bootstrap 4, with class .img-fluid are resized disproportionally. They keep it's height even width is shrinking down correctly. That is deforming whole image. Is there any way how to make it as smooth as it was in Bootstrap 3 with class .img-responsive? Thanks

By the way it is same in Bootstrap 4 documentation (https://v4-alpha.getbootstrap.com/content/images/) where sample svg image keeps height 250 pixels regardless of it's width.

Body:
We have an (asp.net core 2.2) app (public portal) with Bootstrap 4.x, whereby the customer can upload his own images and use the img-fluid on various views (with different sizes) in flex.

The images are scaled (resized) automatically by the upload to the size how the images are showed to the end users ("query view").

On the editing view, we have to show the images with correct aspect ratio but smaller.

The end user view is optimized to show the images in landscape ( 1 ) format, but the customer also is able to upload images in portrait ( 2 ) format (the images then have to be scaled to a given height) what is not a problem on the end user view, as the images are scaled automatically correctly by the upload, but in the (smaller) editing view, it definitely is a problem...

Per default, the .img-fluid class applies max-width: 100%; and height: auto; to the image:
In my case (I set the width), this leads to a scale of a portrait image to the full width ( 2 ) , what shows the image

way to high ( 3 ).

I want to scale the height to to a given height ( 4 )  (in the example it is 185 Pixel).

Principally, I would be able to overwrite the max-height to the img-fluid to have the needed hight:

 img-fluid {
  max-height: 185px;
}

But this would be a really bad idea, as it would affect all images on all views.

The only solution, that works for my case is:

to overwrite the max-height to 100%:

.img-fluid {
  max-height: 100%;
}

and set the height to the container control explicitly to the needed height:

<div id="WirUeberUnsFotoUpload" style="height:185px">
   <div> --- Noch kein Foto  hochgeladen --- </div>
</div>

Note: The Text to the div „ --- Noch kein Foto  hochgeladen --- „ is replaced by the uploaded image via JQuery at runtime.

This leads to the wanted result ( 5 ) :

This way, the image ( 5 )  is scaled correct to the needed height ( 4 ) and don’t affect the other views.

Note: Both, to set the height to the container and to set max-height: 100% is needed.


问:
Datatables Responsive in a flexbox hierarchy overflow in recent browsers

The problem

We use Datatables Responsive to display a table within a Bootstrap cell. It works fine. At least, we thought so, but lately discovered that, in later browsers, the table largely overflows the screen.

About the overflow: some columns are collapsed, but clearly not enough. We have some older versions of the code where columns are hidden when we drop below a threshold point (which is far after it should be). This is no longer the case but we had some radical changes (in both stylesheets and JavaScript) that code comparison flew out of the window.

To be precise:

Works fine

Chrome 47

IE11

Overflows

Chrome 52

Chromium 54

Firefox ESR 47 & 52

We are in a corporate environment so we have limited choice in the browsers we have and this is all I can test.

The configuration

The datatables is set this way:

HMTL

```<code><div id="some-ancestor-with-flexbox-styling">
    <div class="row">
        <div class="col-xs-12">
            <table id="my-table" style="width: 100%"></table>
        </div>
    </div>
</div>
</code>```

JavaScript

```<code>$table.DataTable({
    language: {emptyTable: this.i18n.no_data},
    data: content,
    columns: columns,
    responsive: true
});
</code>```

(I'm sorry, I cannot easily reproduce a case)

What I've tried

Go back to the basics

I removed as much as the options as I could from the configuration and see if the default Datatables configuration was better (spoiler alert: it was not). I also tried deactivating responsive but overflow still occurs.

I also moved the table as close to top-level as I could but that did not change anything.

We also wrote our own stylesheet but adding the original one doesn't change anything.

Tinker

After browsing all the possibly relevant solutions I saw on SO (div.table-responsive doesn't work and I already have the viewport <meta/>), I browsed the Datatables API and tinkered with some options we hadn't set yet (autoWidth, for instance).

I noticed no interesting change.

Listening

I added some listeners on Datatables events. Whether Responsive works or not, column-sizing is fired. In more modern browsers however, responsive-resize is not.

Check Chrome's changelog

I tried but only found a list of security fixes. Which is not what I need.

What next?

I've got no clue about how to solve this. Even if I don't get a solution, a new investigation lead would be great!

[Edit 2017-10-06] Clues

I'm still investigating, but moving the table around in the DOM, I found which element was the first to show problems. It had a display: flex; flex: 1 0 auto; style. Removing it fixed the problem.

I must now investigate with the full DOM tree but I'm afraid this is related to flexbox. This post on Datatables' forum seems to support this, but the proposed solution (add overflow: hidden to the table's parent) doesn't do the trick for me. Going on with my search.

答: Add overflow: hidden to the closest flex element in the DOM hierarchy it should solve the issue

Body:
The problem

We use Datatables Responsive to display a table within a Bootstrap cell. It works fine. At least, we thought so, but lately discovered that, in later browsers, the table largely overflows the screen.

About the overflow: some columns are collapsed, but clearly not enough. We have some older versions of the code where columns are hidden when we drop below a threshold point (which is far after it should be). This is no longer the case but we had some radical changes (in both stylesheets and JavaScript) that code comparison flew out of the window.

To be precise:

Works fine

Chrome 47

IE11

Overflows

Chrome 52

Chromium 54

Firefox ESR 47 & 52

We are in a corporate environment so we have limited choice in the browsers we have and this is all I can test.

The configuration

The datatables is set this way:

HMTL

JavaScript

$table.DataTable({
    language: {emptyTable: this.i18n.no_data},
    data: content,
    columns: columns,
    responsive: true
});

(I'm sorry, I cannot easily reproduce a case)

What I've tried

Go back to the basics

I removed as much as the options as I could from the configuration and see if the default Datatables configuration was better (spoiler alert: it was not). I also tried deactivating responsive but overflow still occurs.

I also moved the table as close to top-level as I could but that did not change anything.

We also wrote our own stylesheet but adding the original one doesn't change anything.

Tinker

After browsing all the possibly relevant solutions I saw on SO (div.table-responsive doesn't work and I already have the viewport <meta/>), I browsed the Datatables API and tinkered with some options we hadn't set yet (autoWidth, for instance).

I noticed no interesting change.

Listening

I added some listeners on Datatables events. Whether Responsive works or not, column-sizing is fired. In more modern browsers however, responsive-resize is not.

Check Chrome's changelog

I tried but only found a list of security fixes. Which is not what I need.

What next?

I've got no clue about how to solve this. Even if I don't get a solution, a new investigation lead would be great!

[Edit 2017-10-06] Clues

I'm still investigating, but moving the table around in the DOM, I found which element was the first to show problems. It had a display: flex; flex: 1 0 auto; style. Removing it fixed the problem.

I must now investigate with the full DOM tree but I'm afraid this is related to flexbox. This post on Datatables' forum seems to support this, but the proposed solution (add overflow: hidden to the table's parent) doesn't do the trick for me. Going on with my search.


问:
liquibase does not generate table DATABASECHANGELOG
I'm new to liquibase and I want to use it on an database in production.
It's a small application, but instead of creating schema by hand I would like to use something more professional like liquibase.

What I plan to do is to make a changelog between the current schema in production and the new schema ready for the new application. I've followed many tutorials but there is still something missing. The output changelog.xml always imports all the schema and doesn't make the difference with the existing. I saw that liquibase had to create the table DATABASECHANGELOG but I couldn't see them on my computer.

What I did :

dump of the current db in production and import on dev computer

from core project added liquibase.properties and launched the following command : mvn clean resources:resources liquibase:generateChangeLog

this generated a master.xml with all the schema, but didn't create the tables DATABASECHANGELOG in DB (the table DATABASECHANGELOGLOCK was created when commenting outputChangeLogFile, and the LOCKED value is 0)

created manually the DATABASECHANGELOG from http://www.liquibase.org/databases.html

rerun the command mvn liquibase:generateChangeLog. Still nothing

pom.xml :

```<code><dependencies>
    ...
    <dependency>
        <groupId>org.liquibase</groupId>
        <artifactId>liquibase-core</artifactId>
        <version>3.5.3</version>
    </dependency>
    <dependency>
        <groupId>org.yaml</groupId>
        <artifactId>snakeyaml</artifactId>
        <version>1.17</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.6</version>
    </dependency>
</dependencies>

 <!-- edited build after 1st comment. Still got the problem -->
<build>
    <plugins>
        <plugin>
            <groupId>org.liquibase</groupId>
            <artifactId>liquibase-maven-plugin</artifactId>
            <version>${liquibase.version}</version>
            <configuration>
                <promptOnNonLocalDatabase>true</promptOnNonLocalDatabase>
                <changeLogFile>${project.build.directory}/classes/changelog/db.changelog-master.xml</changeLogFile>
                <propertyFile>src/main/resources/liquibase.properties</propertyFile>
            </configuration>
        </plugin>
    </plugins>
</build>

<!--- old section build, left for history purpose --->
<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.liquibase</groupId>
                <artifactId>liquibase-maven-plugin</artifactId>
                <version>${liquibase.version}</version>
                <configuration>
                    <promptOnNonLocalDatabase>true</promptOnNonLocalDatabase>
                    <changeLogFile>${project.build.directory}/classes/changelog/db.changelog-master.xml</changeLogFile>
                    <propertyFile>src/main/resources/liquibase.properties</propertyFile>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
</build>
</code>```

liquibase.properties :

```<code>url=jdbc:mysql://localhost:3306/my_db
username=user
password=pass
driver=com.mysql.jdbc.Driver
outputChangeLogFile=src/main/resources/liquibase/master.xml
</code>```

NB : commenting outputChangeLogFile made liquibase create the table DATABASECHANGELOGLOCK, but only this one.

maven output :

```<code>[INFO] ------------------------------------------------------------------------
[INFO] Building -CORE 0.0.2
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- liquibase-maven-plugin:3.5.3:generateChangeLog (default-cli) @ EDI-CORE ---
[INFO] ------------------------------------------------------------------------
[INFO] Parsing Liquibase Properties File
[INFO]   File: src/main/resources/liquibase.properties
[INFO]   'classpath' in properties file is not being used by this task.
[INFO] ------------------------------------------------------------------------
[INFO] Executing on Database: jdbc:mysql://localhost:3306/my_db
[INFO] Generating Change Log from database root@localhost @ jdbc:mysql://localhost:3306/my_db (Default Schema: edi)
INFO 17/01/17 15:01: liquibase: src\main\resources\liquibase\master.xml exists, appending
WARNING 17/01/17 15:01: liquibase: MySQL does not support a timestamp precision of '19' - resetting to the maximum of '6'
WARNING 17/01/17 15:01: liquibase: MySQL does not support a timestamp precision of '19' - resetting to the maximum of '6'
WARNING 17/01/17 15:01: liquibase: MySQL does not support a timestamp precision of '19' - resetting to the maximum of '6'
[INFO] Output written to Change Log file, src/main/resources/liquibase/master.xml
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
</code>```

答:
It does not support a timestamp precision of '19' is about your Data Type in MySQL

MySQL does not  support your Data Type column for your Entity.

Body:
I'm new to liquibase and I want to use it on an database in production.
It's a small application, but instead of creating schema by hand I would like to use something more professional like liquibase.

What I plan to do is to make a changelog between the current schema in production and the new schema ready for the new application. I've followed many tutorials but there is still something missing. The output changelog.xml always imports all the schema and doesn't make the difference with the existing. I saw that liquibase had to create the table DATABASECHANGELOG but I couldn't see them on my computer.

What I did :

dump of the current db in production and import on dev computer

from core project added liquibase.properties and launched the following command : mvn clean resources:resources liquibase:generateChangeLog

this generated a master.xml with all the schema, but didn't create the tables DATABASECHANGELOG in DB (the table DATABASECHANGELOGLOCK was created when commenting outputChangeLogFile, and the LOCKED value is 0)

created manually the DATABASECHANGELOG from http://www.liquibase.org/databases.html

rerun the command mvn liquibase:generateChangeLog. Still nothing

pom.xml :

<dependencies>
    ...
    <dependency>
        <groupId>org.liquibase</groupId>
        <artifactId>liquibase-core</artifactId>
        <version>3.5.3</version>
    </dependency>
    <dependency>
        <groupId>org.yaml</groupId>
        <artifactId>snakeyaml</artifactId>
        <version>1.17</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.6</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.liquibase</groupId>
            <artifactId>liquibase-maven-plugin</artifactId>
            <version>${liquibase.version}</version>
            <configuration>
                <promptOnNonLocalDatabase>true</promptOnNonLocalDatabase>
                <changeLogFile>${project.build.directory}/classes/changelog/db.changelog-master.xml</changeLogFile>
                <propertyFile>src/main/resources/liquibase.properties</propertyFile>
            </configuration>
        </plugin>
    </plugins>
</build>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.liquibase</groupId>
                <artifactId>liquibase-maven-plugin</artifactId>
                <version>${liquibase.version}</version>
                <configuration>
                    <promptOnNonLocalDatabase>true</promptOnNonLocalDatabase>
                    <changeLogFile>${project.build.directory}/classes/changelog/db.changelog-master.xml</changeLogFile>
                    <propertyFile>src/main/resources/liquibase.properties</propertyFile>
                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
</build>

liquibase.properties :

url=jdbc:mysql://localhost:3306/my_db
username=user
password=pass
driver=com.mysql.jdbc.Driver
outputChangeLogFile=src/main/resources/liquibase/master.xml

NB : commenting outputChangeLogFile made liquibase create the table DATABASECHANGELOGLOCK, but only this one.

maven output :

[INFO] ------------------------------------------------------------------------
[INFO] Building -CORE 0.0.2
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- liquibase-maven-plugin:3.5.3:generateChangeLog (default-cli) @ EDI-CORE ---
[INFO] ------------------------------------------------------------------------
[INFO] Parsing Liquibase Properties File
[INFO]   File: src/main/resources/liquibase.properties
[INFO]   'classpath' in properties file is not being used by this task.
[INFO] ------------------------------------------------------------------------
[INFO] Executing on Database: jdbc:mysql://localhost:3306/my_db
[INFO] Generating Change Log from database root@localhost @ jdbc:mysql://localhost:3306/my_db (Default Schema: edi)
INFO 17/01/17 15:01: liquibase: src\main\resources\liquibase\master.xml exists, appending
WARNING 17/01/17 15:01: liquibase: MySQL does not support a timestamp precision of '19' - resetting to the maximum of '6'
WARNING 17/01/17 15:01: liquibase: MySQL does not support a timestamp precision of '19' - resetting to the maximum of '6'
WARNING 17/01/17 15:01: liquibase: MySQL does not support a timestamp precision of '19' - resetting to the maximum of '6'
[INFO] Output written to Change Log file, src/main/resources/liquibase/master.xml
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------


问:
Arabic letters aren't showing correctly in the plot
I used all the correct encoding and the software does work but the letters in Arabic aren't connected (most Arabic letters are connected when written next to each other)

This is how the plot shows the image

I used the python Pandas module using the bar chart function

答:
The only way I could get around this is to take all the Arabic words in the pandas column that I need to plot and reshape it with arabic_reshaper, append them to a list and have this list as my x axis:

# reshaping the arabic words to show correctly on matplotlib

import arabic_reshaper
import matplotlib.pyplot as plt
from bidi.algorithm import get_display

x = [ ]

for item in df.column_name.values:
    x.append(get_display(arabic_reshaper.reshape(item)))
```

Of course you need to install the arabic_reshaper and the bidi.algorithm packages first

Body:
The only way I could get around this is to take all the Arabic words in the pandas column that I need to plot and reshape it with arabic_reshaper, append them to a list and have this list as my x axis:

# reshaping the arabic words to show correctly on matplotlib

import arabic_reshaper
import matplotlib.pyplot as plt
from bidi.algorithm import get_display

x = [ ]

for item in df.column_name.values:
    x.append(get_display(arabic_reshaper.reshape(item)))

Of course you need to install the arabic_reshaper and the bidi.algorithm packages first


问:
distanceTo() integer overflow?
This is my method to determine the distance between two points:

```<code>
    // Euclidean distance between this point and that point
    public int distanceTo(Point that) {
        int distanceX = this.x - that.x;
        int distanceY = this.y - that.y;
        return (int) Math.sqrt(distanceX * distanceX + distanceY * distanceY);
    }

</code>```

Is it possible that an integer overflow occurs, and if so, how can I prevent it?

EDIT:

答:
To prevent incorrect result from overflow, use the Math "exact" methods:

Math.addExact(int x, int y)1

Math.subtractExact(int x, int y)1

Math.multiplyExact(int x, int y)1

Math.incrementExact(int a)1

Math.decrementExact(int a)1

Math.negateExact(int a)1

Math.toIntExact(long value)

1) Or the long variant.

The methods will throw an ArithmeticException if overflow would have occurred.

```<code>public int distanceTo(Point that) throws ArithmeticException {
    int distanceX = Math.subtractExact(this.x, that.x);
    int distanceY = Math.subtractExact(this.y, that.y);
    return (int) Math.sqrt(Math.addExact(Math.multiplyExact(distanceX, distanceX),
                                         Math.multiplyExact(distanceY, distanceY)));
}
</code>```

Of course it might be prudent to use long math to minimize the probability of overflow.

```<code>public int distanceTo(Point that) {
    long distanceX = Math.subtractExact((long) this.x, (long) that.x);
    long distanceY = Math.subtractExact((long) this.y, (long) that.y);
    long sumOfSquares = Math.addExact(Math.multiplyExact(distanceX, distanceX),
                                      Math.multiplyExact(distanceY, distanceY));
    return Math.toIntExact((long) Math.sqrt(sumOfSquares));
}
</code>```

There might be a small loss of precision when sumOfSquares is widened to a double, but the effect would likely be lost when decimals are discarded during cast to long.

Title: distanceTo() integer overflow?

Body:
This is my method to determine the distance between two points:

    // Euclidean distance between this point and that point
    public int distanceTo(Point that) {
        int distanceX = this.x - that.x;
        int distanceY = this.y - that.y;
        return (int) Math.sqrt(distanceX * distanceX + distanceY * distanceY);
    }

Is it possible that an integer overflow occurs, and if so, how can I prevent it?

EDIT:

Body:
To prevent incorrect result from overflow, use the Math "exact" methods:

Math.addExact(int x, int y)1

Math.subtractExact(int x, int y)1

Math.multiplyExact(int x, int y)1

Math.incrementExact(int a)1

Math.decrementExact(int a)1

Math.negateExact(int a)1

Math.toIntExact(long value)

1) Or the long variant.

The methods will throw an ArithmeticException if overflow would have occurred.

public int distanceTo(Point that) throws ArithmeticException {
    int distanceX = Math.subtractExact(this.x, that.x);
    int distanceY = Math.subtractExact(this.y, that.y);
    return (int) Math.sqrt(Math.addExact(Math.multiplyExact(distanceX, distanceX),
                                         Math.multiplyExact(distanceY, distanceY)));
}

Of course it might be prudent to use long math to minimize the probability of overflow.

public int distanceTo(Point that) {
    long distanceX = Math.subtractExact((long) this.x, (long) that.x);
    long distanceY = Math.subtractExact((long) this.y, (long) that.y);
    long sumOfSquares = Math.addExact(Math.multiplyExact(distanceX, distanceX),
                                      Math.multiplyExact(distanceY, distanceY));
    return Math.toIntExact((long) Math.sqrt(sumOfSquares));
}

There might be a small loss of precision when sumOfSquares is widened to a double, but the effect would likely be lost when decimals are discarded during cast to long.


问:
Technologies required to develop something like bitlocker
My idea is to build a full volume encryption as a project.
I know C# and web technologies like HTML CSS JS and angular.
I want to build something like
BitLocker and https://www.diskcryptor.org/ , Can anyone guide what should be my first step, I have searched a lot on the web did not found any good starting point.</p>

答:
You can not do that in C# such sort of tools require kernel drivers which are usually written in C or C++

What you could do though would be to use the dcapi.dll from diskcryptor.org and implement only an own modern looking C# based GUI frontent.
This way you have full control over how the application looks and feals to the user yet don't have to mess around with drivers and boot-loaders.

IMHO that is a decent compromise.


问:
How to use
 tag as variable
Anyone knows how to make br tag as variable?
I want to output a txt file that has textbox value.
I want to set a specific counts of break lines. Like 100 times.

Example.
Hello
Earth

Output
Hello
(line break 100times)
Earth

答:
You can declare

```<code>const new_line = "<br>";
</code>```

And then use ES6 String.prototype.repeat:

```<code>const content = "Hello" + new_line.repeat(100) + "Earth";
document.querySelector(".your-class").innerHTML = content;
</code>```

Another way is to create custom function with recursion for this. For example:

```<code>function repeatString(string, times) {
  if (times < 0) {
    return "";
  } else if (times === 1) {
    return string;
  } else {
    return string + repeatString(string, times - 1);
  }
</code>```

And repeatString(new_line, 3) will return result wanted.

Title: How to use <br> tag as variable

Body:
You can declare

const new_line = "<br>";

And then use ES6 String.prototype.repeat:

const content = "Hello" + new_line.repeat(100) + "Earth";
document.querySelector(".your-class").innerHTML = content;

Another way is to create custom function with recursion for this. For example:

function repeatString(string, times) {
  if (times < 0) {
    return "";
  } else if (times === 1) {
    return string;
  } else {
    return string + repeatString(string, times - 1);
  }

And repeatString(new_line, 3) will return result wanted.


问:
Sequences in SAS Tables
I'm looking to add a sequence column to my sas dataset, but according to ids and transaction dates. To illustrate, below is the table I'm referring to:

```<code>ID   |   TXN_DT    |
01   |  01JAN2020  |
01   |  01JAN2020  |
01   |  02JAN2020  |
01   |  03JAN2020  |
02   |  01JAN2020  |
02   |  02JAN2020  |
02   |  02JAN2020  |
02   |  03JAN2020  |
02   |  03JAN2020  |
</code>```

and I want to add a sequence like so:

```<code>ID   |   TXN_DT    |   SEQ  |
01   |  01JAN2020  |    1   |
01   |  01JAN2020  |    1   |
01   |  02JAN2020  |    2   |
01   |  03JAN2020  |    3   |
02   |  01JAN2020  |    1   |
02   |  02JAN2020  |    2   |
02   |  02JAN2020  |    2   |
02   |  03JAN2020  |    3   |
02   |  03JAN2020  |    3   |
</code>```

I'm trying to run the following code, but it seems to jump a row up and not copying the previous' row's value, and instead skips to 2 rows above.

```<code>data want;
set have;
by id;
if first.id then seq=1;
else seq+1;
if txn_dt=lag(txn_dt) then seq = lag(seq);
keep id seq txn_dt;
run;
</code>```

any help? Thanks in advance!

答:
For completeness, here is a hash solution that does not depend on the order of your data.</p>

```<code>data have;
input ID $ TXN_DT :date9.;
infile datalines dlm='|';
format TXN_DT date9.;
datalines;
01|01JAN2020
01|01JAN2020
01|02JAN2020
01|03JAN2020
02|01JAN2020
02|02JAN2020
02|02JAN2020
02|03JAN2020
02|03JAN2020
;

data want(drop=rc);
   if _N_ = 1 then do;
      dcl hash h1 ();
      h1.definekey ('ID', 'TXN_DT');
      h1.definedata ('SEQ');
      h1.definedone ();
      dcl hash h2 ();
      h2.definekey ('ID');
      h2.definedata ('SEQ');
      h2.definedone ();

      do until (lr);
         set have end=lr;

         if h2.find() = 0 then do;
            if h1.check() ne 0 then seq + 1;
         end;
         else seq = 1;

         h1.ref();
         h2.replace();
      end;
   end;

   set have;
   rc = h1.find();
run;
</code>```

Title: Sequences in SAS Tables

Body:
I'm looking to add a sequence column to my sas dataset, but according to ids and transaction dates. To illustrate, below is the table I'm referring to:

ID   |   TXN_DT    |
01   |  01JAN2020  |
01   |  01JAN2020  |
01   |  02JAN2020  |
01   |  03JAN2020  |
02   |  01JAN2020  |
02   |  02JAN2020  |
02   |  02JAN2020  |
02   |  03JAN2020  |
02   |  03JAN2020  |

and I want to add a sequence like so:

ID   |   TXN_DT    |   SEQ  |
01   |  01JAN2020  |    1   |
01   |  01JAN2020  |    1   |
01   |  02JAN2020  |    2   |
01   |  03JAN2020  |    3   |
02   |  01JAN2020  |    1   |
02   |  02JAN2020  |    2   |
02   |  02JAN2020  |    2   |
02   |  03JAN2020  |    3   |
02   |  03JAN2020  |    3   |

I'm trying to run the following code, but it seems to jump a row up and not copying the previous' row's value, and instead skips to 2 rows above.

data want;
set have;
by id;
if first.id then seq=1;
else seq+1;
if txn_dt=lag(txn_dt) then seq = lag(seq);
keep id seq txn_dt;
run;

any help? Thanks in advance!

Body:
For completeness, here is a hash solution that does not depend on the order of your data.

data have;
input ID $ TXN_DT :date9.;
infile datalines dlm='|';
format TXN_DT date9.;
datalines;
01|01JAN2020
01|01JAN2020
01|02JAN2020
01|03JAN2020
02|01JAN2020
02|02JAN2020
02|02JAN2020
02|03JAN2020
02|03JAN2020
;

data want(drop=rc);
   if _N_ = 1 then do;
      dcl hash h1 ();
      h1.definekey ('ID', 'TXN_DT');
      h1.definedata ('SEQ');
      h1.definedone ();
      dcl hash h2 ();
      h2.definekey ('ID');
      h2.definedata ('SEQ');
      h2.definedone ();

      do until (lr);
         set have end=lr;

         if h2.find() = 0 then do;
            if h1.check() ne 0 then seq + 1;
         end;
         else seq = 1;

         h1.ref();
         h2.replace();
      end;
   end;

   set have;
   rc = h1.find();
run;


问:
Groupby upon multiple columns, then append
i am trying to count the number of occurrences of the same packet in my dataframe, a packet is the same if it has these matching fields:

```<code>['SourceIP', 'SourcePort', 'DestinationIP', 'DestinationPort', 'Protocol']
</code>```

I want to make a new column in my dataframe with the occurrence values and have this column be called 'PerSec'

I have tried to implement the solution to this problem found here Pandas create new column with count from groupby

However when I run:

```<code>df['PerSec'] = df.groupby(['SourceIP', 'SourcePort', 'DestinationIP', 'DestinationPort', 'Protocol']['SourceIP', 'SourcePort', 'DestinationIP', 'DestinationPort', 'Protocol'].transform('PerSec'))
with pd.option_context('display.max_rows', None, 'display.max_columns', None):
    print(df)
</code>```

I receive this error:

TypeError: list indices must be integers or slices, not tuple

Does this mean the groupby method will only work upon one column?

答:
Groupby method can be extended to multiple columns. It will group in the given order of columns

in you case

```<code>df.groupby(['SourceIP', 'SourcePort', 'DestinationIP', 'DestinationPort', 'Protocol'])
</code>```

will return a grouped dataframe in which if SourceIP equals it groups by SourcePort and so on.

Body:
i am trying to count the number of occurrences of the same packet in my dataframe, a packet is the same if it has these matching fields:

['SourceIP', 'SourcePort', 'DestinationIP', 'DestinationPort', 'Protocol']

I want to make a new column in my dataframe with the occurrence values and have this column be called 'PerSec'

I have tried to implement the solution to this problem found here Pandas create new column with count from groupby

However when I run:

df['PerSec'] = df.groupby(['SourceIP', 'SourcePort', 'DestinationIP', 'DestinationPort', 'Protocol']['SourceIP', 'SourcePort', 'DestinationIP', 'DestinationPort', 'Protocol'].transform('PerSec'))
with pd.option_context('display.max_rows', None, 'display.max_columns', None):
    print(df)

I receive this error:

TypeError: list indices must be integers or slices, not tuple

Does this mean the groupby method will only work upon one column?

Body:
Groupby method can be extended to multiple columns. It will group in the given order of columns

in you case

df.groupby(['SourceIP', 'SourcePort', 'DestinationIP', 'DestinationPort', 'Protocol'])

will return a grouped dataframe in which if SourceIP equals it groups by SourcePort and so on.


问:
Why am I getting 502 errors on my ALB end points, targeted at EKS hosted services
I am building a service in EKS that has two deployments, two services (NodePort) , and a single ingress.

I am using the aws-alb-ingress-controller.

When I run kubectl port-forward POD 8080:80  It does show me my working pods.

When I look at the generated endpoints by the alb I get 502 errors.

When I look at the Registered Targets of the target group I am seeing the message, Health checks failed with these codes: [502]

Here is my complete yaml.

```<code>---
#Example game deployment and service
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: "example-game"
  namespace: "example-app"
spec:
  replicas: 5
  template:
    metadata:
      labels:
        app: "example-game"
    spec:
      containers:
      - image: alexwhen/docker-2048
        imagePullPolicy: Always
        name: "example-game"
        ports:
        - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: "service-example-game"
  namespace: "example-app"
spec:
  ports:
    - port: 80
      targetPort: 80
      protocol: TCP
  type: NodePort
  selector:
    app: "example-app"

#Example nginxdemo Deployment and Service
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: "example-nginxdemo"
  namespace: "example-app"
spec:
  replicas: 5
  template:
    metadata:
      labels:
        app: "example-nginxdemo"
    spec:
      containers:
      - image: nginxdemos/hello
        imagePullPolicy: Always
        name: "example-nginxdemo"
        ports:
        - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: "service-example-nginxdemo"
  namespace: "example-app"
spec:
  ports:
    - port: 80
      targetPort: 80
      protocol: TCP
  type: NodePort
  selector:
    app: "example-app"
---

#Shared ALB ingress
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: "example-ingress"
  namespace: "example-app"
  annotations:
    kubernetes.io/ingress.class: alb
    alb.ingress.kubernetes.io/healthcheck-protocol: HTTP
    Alb.ingress.kubernetes.io/healthcheck-port: traffic-port
    alb.ingress.kubernetes.io/healthcheck-path: /

#   alb.ingress.kubernetes.io/scheme: internal
#   alb.ingress.kubernetes.io/load-balancer-attributes: routing.http2.enabled=true

  labels:
    app: example-app
spec:
  rules:
    - http:
        paths:
          - path: /game/*
            backend:
              serviceName: "service-example-game"
              servicePort: 80
          - path: /nginxdemo/*
            backend:
              serviceName: "service-example-nginxdemo"
              servicePort: 80
</code>```

答:
I don't know why but it turns out that the label given to to ingress has to be unique.

When I changed the label from 'example-app' to 'example-app-ingress' it just started working.

Body:
I am building a service in EKS that has two deployments, two services (NodePort) , and a single ingress.

I am using the aws-alb-ingress-controller.

When I run kubectl port-forward POD 8080:80  It does show me my working pods.

When I look at the generated endpoints by the alb I get 502 errors.

When I look at the Registered Targets of the target group I am seeing the message, Health checks failed with these codes: [502]

Here is my complete yaml.

---
#Example game deployment and service
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: "example-game"
  namespace: "example-app"
spec:
  replicas: 5
  template:
    metadata:
      labels:
        app: "example-game"
    spec:
      containers:
      - image: alexwhen/docker-2048
        imagePullPolicy: Always
        name: "example-game"
        ports:
        - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: "service-example-game"
  namespace: "example-app"
spec:
  ports:
    - port: 80
      targetPort: 80
      protocol: TCP
  type: NodePort
  selector:
    app: "example-app"

#Example nginxdemo Deployment and Service
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: "example-nginxdemo"
  namespace: "example-app"
spec:
  replicas: 5
  template:
    metadata:
      labels:
        app: "example-nginxdemo"
    spec:
      containers:
      - image: nginxdemos/hello
        imagePullPolicy: Always
        name: "example-nginxdemo"
        ports:
        - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: "service-example-nginxdemo"
  namespace: "example-app"
spec:
  ports:
    - port: 80
      targetPort: 80
      protocol: TCP
  type: NodePort
  selector:
    app: "example-app"
---

#Shared ALB ingress
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: "example-ingress"
  namespace: "example-app"
  annotations:
    kubernetes.io/ingress.class: alb
    alb.ingress.kubernetes.io/healthcheck-protocol: HTTP
    Alb.ingress.kubernetes.io/healthcheck-port: traffic-port
    alb.ingress.kubernetes.io/healthcheck-path: /

#   alb.ingress.kubernetes.io/scheme: internal
#   alb.ingress.kubernetes.io/load-balancer-attributes: routing.http2.enabled=true

  labels:
    app: example-app
spec:
  rules:
    - http:
        paths:
          - path: /game/*
            backend:
              serviceName: "service-example-game"
              servicePort: 80
          - path: /nginxdemo/*
            backend:
              serviceName: "service-example-nginxdemo"
              servicePort: 80


问:
Vue.js: To Get Environment Variables in js File
I have created .env file to set environment variables as shown below:

Inside which I have given below mentioned code.

```<code>VUE_APP_BASEURL="https://qa-apps-nodejs.Dtech.com:9000/"
PORT=8080
</code>```

I have written below code in my js file and executed npm install dotenv:

```<code>require('dotenv').config();
console.log(process.env.VUE_APP_BASEURL);
</code>```

With the above code, I need to get https://qa-apps-nodejs.Dtech.com:9000/ in console. But instead I'm getting:

undefined

答:
No need to install "dotenv" simply place .env file in the root of your project (at the same level of your package.json file) and Vue CLI will handle the reset. Side note; as of Vue CLI 3 only variables that start with VUE_APP_ will be loaded. make sure also to rerun npm run serve again to restart your server.

for more details: visit docs

Body:
I have created .env file to set environment variables as shown below:

Inside which I have given below mentioned code.

VUE_APP_BASEURL="https://qa-apps-nodejs.Dtech.com:9000/"
PORT=8080

I have written below code in my js file and executed npm install dotenv:

require('dotenv').config();
console.log(process.env.VUE_APP_BASEURL);

With the above code, I need to get https://qa-apps-nodejs.Dtech.com:9000/ in console. But instead I'm getting:

undefined


问:
Display laravel retrun result in html table using jquery- Ajax
In Laravel Blade I have a script for searching

```<code> <script type="text/javascript">
    $.ajax({
        type: "POST",
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
        url: "{{ URL::asset('upload-panel/search')}}",
        data: dataString,
        dataType:"JSON",
        cache: false,
        success: function(result) {
        var FinalResult=result.CallDetails
        num_rows = result.length;
        console.log(result)

        },error:function(x,e) {
            setTimeout(function() {searchPhoneCalls();}, 2000);
        }
    })
</script>
</code>```

search function in controller returns is below

return  json_encode($users);

In console am getting the result as an array like below

```<code>0: {Short_name: "GO120762", Date: "21-01-2020"}
1: {Short_name: "GO120764", Date: "21-01-2020"}
2: {Short_name: "GO120766", Date: "21-01-2020"}
</code>```

I want to display those result in a HTML  table  like below

```<code>+----------+------------+
| Name     | Date       |
+----------+------------+
| GO120762 | 21-01-2020 |
+----------+------------+
| GO120764 | 21-01-2020 |
+----------+------------+
| GO120766 | 21-01-2020 |
+----------+------------+

</code>```

答:
Try like this</p>

```<code>success: function(result) {
 var tableSearch = $('#table-search');
 tableSearch.html('');

 $.each(result, function(index, value){
    tableSearch.append('<tr><td>'+value.Short_name+'</td><td>'+value.Date+'</td></tr>');
});
}
</code>```

Body:
In Laravel Blade I have a script for searching

search function in controller returns is below

return  json_encode($users);

In console am getting the result as an array like below

0: {Short_name: "GO120762", Date: "21-01-2020"}
1: {Short_name: "GO120764", Date: "21-01-2020"}
2: {Short_name: "GO120766", Date: "21-01-2020"}

I want to display those result in a HTML  table  like below

+----------+------------+
| Name     | Date       |
+----------+------------+
| GO120762 | 21-01-2020 |
+----------+------------+
| GO120764 | 21-01-2020 |
+----------+------------+
| GO120766 | 21-01-2020 |
+----------+------------+

Body:
Try like this

success: function(result) {
 var tableSearch = $('#table-search');
 tableSearch.html('');

 $.each(result, function(index, value){
    tableSearch.append('<tr><td>'+value.Short_name+'</td><td>'+value.Date+'</td></tr>');
});
}


问:
Sapien Powershell Form Close button event
To whom it may concern,

It's my first week using Sapien powershell studio, I'm very new this technology sorry in advance if I come across asking something very easy to do.

I'm creating a GUI form I want to disable the red x and put close button on the form but I can't seem to get the close button to work please see code I used below.

  $buttonClose_Click={

$formADSubmissionForm.Close = $true

答:
You need to add the eval function "()". Try this

```<code>$formADSubmissionForm.Close()
</code>```

Body:
You need to add the eval function "()". Try this

$formADSubmissionForm.Close()


答:
It should be like this </p>

```<code>df['PerSec'] = df.groupby([['SourceIP', 'SourcePort', 'DestinationIP', 'DestinationPort', 'Protocol']])['SourceIP', 'SourcePort', 'DestinationIP', 'DestinationPort', 'Protocol'].transform('PerSec')
</code>```

Title: Groupby upon multiple columns, then append

Body:
It should be like this

df['PerSec'] = df.groupby([['SourceIP', 'SourcePort', 'DestinationIP', 'DestinationPort', 'Protocol']])['SourceIP', 'SourcePort', 'DestinationIP', 'DestinationPort', 'Protocol'].transform('PerSec')


问:
Cloud Identity and Cloud Endpoints, Is there any way to bar certain users within a role/group from making POST/GET Requests to an endpoint
For example, let's say user A needs to have GET permissions but no POST permissions to a certain endpoint. Is there any way to:

Make roles where a certain user can't make certain types of requests
to an endpoint?

Make sure that endpoint follows those rules?

答:
Regarding your first question, Cloud IAM roles are meant to control the access level of user accounts to the services and products that exist within your project. The IAM roles for Cloud Endpoints allow to restrict which users can enable your API but they don't offer such fine-grained permissions to control how users, that are indeed allowed to call, can interact with particular routes of your API.

Now, it is possible to restrict access to particular API methods, I describe below two approaches:

Using Auth0 and checking user-authorization programmatically: When a user allowed to reach the endpoint makes a request it's identity is passed to the handling code under the header X-Endpoint-API-UserInfo. You might then check who's the caller in order to negate an answer. This would require some database communication to check the restricted users or the questionable naive approach of hardcoding the users. This approach is solid from security point of view since Cloud IAP would block unauthorized users to reach the API and then you can further restrict access scopes as needed. The only downside of this method is that it creates some latency.  See here for documentation and links to code samples in several languages.

API keys: API keys provide a way of allowing/restricting access to individual methods as long as you can differentiate the endpoints routes. For instance you might allow some keys to call yourendpoint/route/method1 but restrict yourendpoint/route/method2. There are several drawbacks with this, the first is that API keys are meant to identify project/application/website/IP rather than individual users which isn't exactly what you're asking about. The second is that they're less secure than authentication and once your API key is exposed almost anybody can use it which can incur in unexpected charges to your billing account. Nonetheless I wanted to mention it for the sake of completeness as it might be useful in other situations. See here for an overview of API keys.

Overall I would suggest using Auth0 with programmatic authentication.


问:
How to make a local string variable in Lisp?
I am trying to make a local string variable and build the string with variables.

```<code>(setq string-label (make-array 0 :element-type `character
                                 :fill-pointer 0
                                 :adjustable t))
(loop while (and (char/= char #\Space)
                 (char/= char #\()
                 (char/= char #\Newline))
      do
         (vector-push-extend char string-label)
         (setq char (read-char fstream nil)))
</code>```

I am getting an error:

```<code>*** - SETQ: variable STRING_LABEL has no value
</code>```

答:
I assume that the code you are running is different than the code you've given, as there's no reference to string_label in that code.

However there are enough other problems with the code you've shown to make it worth fixing.  These are essentially

you should not bind variables, let alone local variables, by assigning to them, and in fact doing so is not legal in CL – instead you should use a binding form like let (in the code below I'm using loop to do the binding for me);

you are using char before it is bound (and even then, it's not actually bound since you just use setq);

the termination condition for reading the label is not right – if you hit EOF you'll get an error since char will then be nil.

Additionally there's some unclarity in your code: when you hit one of the 'stopper' characters, do you want to leave that as the next character to be read?  My version assumes that you do.  This has implications for successive calls to the function, of course: you need to skip forward over stoppers.

So, here is a cleaned-up version of your code, presented as a function.  This also makes the list of 'stopper' characters an argument to the function, and uses member to know when to stop (member uses eql by default, and eql is the same as char= on characters, so this is fine).

```<code>(defun read-string-label (fstream &key (stoppers '(#\Space #\( #\Newline)))
  (loop with string-label = (make-array 0 :element-type 'character
                                        :fill-pointer 0
                                        :adjustable t)
        for char =  (read-char fstream nil)
        while (and char (not (member char stoppers)))
        do (vector-push-extend char string-label)
        finally (progn
                  (when char
                    ;; push the stopper character back into the stream
                    ;; so it's the next thing we read
                    (unread-char char fstream))
                  (return string-label))))
</code>```

Body:
I am trying to make a local string variable and build the string with variables.

(setq string-label (make-array 0 :element-type `character
                                 :fill-pointer 0
                                 :adjustable t))
(loop while (and (char/= char #\Space)
                 (char/= char #\()
                 (char/= char #\Newline))
      do
         (vector-push-extend char string-label)
         (setq char (read-char fstream nil)))

I am getting an error:

*** - SETQ: variable STRING_LABEL has no value

Body:
I assume that the code you are running is different than the code you've given, as there's no reference to string_label in that code.

However there are enough other problems with the code you've shown to make it worth fixing.  These are essentially

you should not bind variables, let alone local variables, by assigning to them, and in fact doing so is not legal in CL – instead you should use a binding form like let (in the code below I'm using loop to do the binding for me);

you are using char before it is bound (and even then, it's not actually bound since you just use setq);

the termination condition for reading the label is not right – if you hit EOF you'll get an error since char will then be nil.

Additionally there's some unclarity in your code: when you hit one of the 'stopper' characters, do you want to leave that as the next character to be read?  My version assumes that you do.  This has implications for successive calls to the function, of course: you need to skip forward over stoppers.

So, here is a cleaned-up version of your code, presented as a function.  This also makes the list of 'stopper' characters an argument to the function, and uses member to know when to stop (member uses eql by default, and eql is the same as char= on characters, so this is fine).

(defun read-string-label (fstream &key (stoppers '(#\Space #\( #\Newline)))
  (loop with string-label = (make-array 0 :element-type 'character
                                        :fill-pointer 0
                                        :adjustable t)
        for char =  (read-char fstream nil)
        while (and char (not (member char stoppers)))
        do (vector-push-extend char string-label)
        finally (progn
                  (when char
                    ;; push the stopper character back into the stream
                    ;; so it's the next thing we read
                    (unread-char char fstream))
                  (return string-label))))


问:
How do I pass data from method _callLogs to body and print it?
I'm new to using flutter framework and I want to pass call logs to my app so I can print them. How do I do that?</p>

```<code>class _QuoteListState extends State<QuoteList> {

   Future<bool>_callLogs() async {
     Iterable<CallLogEntry> entries = await CallLog.get();

   }

 @override
 Widget build(BuildContext context) {
   return Scaffold(
     backgroundColor: Colors.grey[200],
     appBar: AppBar(
       title: Text('Calls Log'),
       centerTitle: true,
       backgroundColor: Colors.purple,
     ),
     body: ListView.builder(
       itemCount: entries.length,
       itemBuilder: (context, index){

       }
     )
   );
</code>```

答:
you have to fetch data from async function and set to local variables so it is good to call setState inside the _callLogs as and make your widget stateful and write as below

```<code>   import 'package:call_log/call_log.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: LogsList(),
  ));
}

class LogsList extends StatefulWidget {
  @override
  _LogsListState createState() => _LogsListState();
}

class _LogsListState extends State<LogsList> {
  @override
  void initState() {
    super.initState();
    _callLogs();
  }

  Future<void> _callLogs() async {
    Iterable<CallLogEntry> entries = await CallLog.get();
    List _data = entries.map((data) => data).toList();
    setState(() {
      _entries = _data;
    });
  }

  List<CallLogEntry> _entries = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[200],
      appBar: AppBar(
        title: Text('Calls Log'),
        centerTitle: true,
        backgroundColor: Colors.purple,
      ),
      body: ListView.builder(
          itemCount: _entries.length,
          itemBuilder: (context, i) {
            final CallLogEntry callLogEntry = _entries[i];

            return ListTile(
              title: Text(callLogEntry.formattedNumber),
              subtitle: Text(callLogEntry.duration.toString()),
            );
          }),
    );
  }
}
</code>```

make sure to add this to your project Android Manifest:

Body:
I'm new to using flutter framework and I want to pass call logs to my app so I can print them. How do I do that?

class _QuoteListState extends State<QuoteList> {

   Future<bool>_callLogs() async {
     Iterable<CallLogEntry> entries = await CallLog.get();

   }

 @override
 Widget build(BuildContext context) {
   return Scaffold(
     backgroundColor: Colors.grey[200],
     appBar: AppBar(
       title: Text('Calls Log'),
       centerTitle: true,
       backgroundColor: Colors.purple,
     ),
     body: ListView.builder(
       itemCount: entries.length,
       itemBuilder: (context, index){

       }
     )
   );

Body:
you have to fetch data from async function and set to local variables so it is good to call setState inside the _callLogs as and make your widget stateful and write as below

   import 'package:call_log/call_log.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    home: LogsList(),
  ));
}

class LogsList extends StatefulWidget {
  @override
  _LogsListState createState() => _LogsListState();
}

class _LogsListState extends State<LogsList> {
  @override
  void initState() {
    super.initState();
    _callLogs();
  }

  Future<void> _callLogs() async {
    Iterable<CallLogEntry> entries = await CallLog.get();
    List _data = entries.map((data) => data).toList();
    setState(() {
      _entries = _data;
    });
  }

  List<CallLogEntry> _entries = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[200],
      appBar: AppBar(
        title: Text('Calls Log'),
        centerTitle: true,
        backgroundColor: Colors.purple,
      ),
      body: ListView.builder(
          itemCount: _entries.length,
          itemBuilder: (context, i) {
            final CallLogEntry callLogEntry = _entries[i];

            return ListTile(
              title: Text(callLogEntry.formattedNumber),
              subtitle: Text(callLogEntry.duration.toString()),
            );
          }),
    );
  }
}

make sure to add this to your project Android Manifest:


问:
Spring security - Enable HTTPS - client gets 403 unauthorized
I'm trying to create a demo app using spring security, I need to protect my Rest API with SSL certificate.
These are the steps I did to create the example:
1- Generated a JKS file using keytool command:

```<code>keytool -genkey -keyalg RSA -alias tomcat -keystore selfsigned.jks -validity 365 -keysize 2048
</code>```

2- Converted the resulted jks to pkcs12 format:

```<code>keytool -genkey -keyalg RSA -alias tomcat -keystore selfsigned.jks -validity 365 -keysize 2048
</code>```

3- Created a server-side application as follow:

```<code>@EnableWebSecurity
public class X509AuthenticationServer extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .x509()
                .subjectPrincipalRegex("OU=My self signed certificate");
    }

}

@Controller
@RequestMapping("/get")
public class UserController {
    @PostMapping(value = "/user")
    public String user(@RequestBody UserInfo userInfo) {

        return "Welcome: " + userInfo.getUsername();
    }
}

server.ssl.key-store=/Users/mymacuser/devhome/certpoc/selfsigned.jks
server.ssl.key-store-password=marwan
server.ssl.key-alias=tomcat
server.ssl.key-password=marwan
server.ssl.enabled=true
server.port=8443
spring.security.user.name=Admin
spring.security.user.password=admin
spring.security.require-ssl=true
</code>```

4- Created a client-side application as following:

```<code>@Configuration
public class BeanConfig {

    @Bean("httpsClient")
    public RestTemplate getSSLRestTemplate() throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
        char[] storePassword = "marwan".toCharArray();
        File keyStore =  new File("/Users/mymacuser/devhome/certpoc/selfsigned.jks");

        SSLContext sslContext = new SSLContextBuilder()
                .loadTrustMaterial(keyStore, storePassword)
                .loadKeyMaterial(keyStore, storePassword, storePassword)
                .build();

        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

        CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client);
        RestTemplate restTemplate = new RestTemplate(factory);
        // restTemplate.setMessageConverters(List.of(new Jaxb2RootElementHttpMessageConverter()));
        return restTemplate;
    }

@RestController
@RequestMapping("/get")
public class ClientController {

    @Autowired
    @Qualifier("httpsClient")
    private RestTemplate httpsClient;

    @RequestMapping("/user")
    public String getUserFromServer() throws URISyntaxException {

        ResponseEntity<String> s = httpsClient.exchange("https://localhost:8443/get/user", HttpMethod.POST, new HttpEntity<UserInfo>(new UserInfo("marwan")), String.class);
        return s.getBody();

    }
}
</code>```

As you can notice, My client-side is a (MITM) man in the middle service that I call from a POSTMAN or curl request.

When I invoke my request to the MITM service, I get as a response:

```<code>{
    "timestamp": "2020-02-17T09:16:20.399+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "403 : [{\"timestamp\":\"2020-02-17T09:16:20.325+0000\",\"status\":403,\"error\":\"Forbidden\",\"message\":\"Forbidden\",\"path\":\"/get/user\"}]",
    "path": "/get/user"
}
</code>```

I tried printing the network logs for both MITM and server-side, and both show they are exchanging the correct certificate

答:
Ok,
So I solved this issue, And here is the solution in case someone is interested:
In TLS there are two different stores:
KeyStore - Used to store keys to be used to seld identification against the other peer
TrustStore - User to tore keys of trusted peers
For server-side authentication, it's needed to specify the trust store as well and to include the client cert.
Also, it's needed to add the following property to the application.properties file:

```<code>server.ssl.client-auth=need
</code>```

So the application.proprties should include:

```<code>server.ssl.trust-store=file:/Users/mymacuser/devhome/certpoc/trust.jks
server.ssl.trust-store-type=JKS
server.ssl.trust-store-password=marwan
server.ssl.client-auth=need
</code>```

Body:
I'm trying to create a demo app using spring security, I need to protect my Rest API with SSL certificate.
These are the steps I did to create the example:
1- Generated a JKS file using keytool command:

keytool -genkey -keyalg RSA -alias tomcat -keystore selfsigned.jks -validity 365 -keysize 2048

2- Converted the resulted jks to pkcs12 format:

keytool -genkey -keyalg RSA -alias tomcat -keystore selfsigned.jks -validity 365 -keysize 2048

3- Created a server-side application as follow:

@EnableWebSecurity
public class X509AuthenticationServer extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .x509()
                .subjectPrincipalRegex("OU=My self signed certificate");
    }

}

@Controller
@RequestMapping("/get")
public class UserController {
    @PostMapping(value = "/user")
    public String user(@RequestBody UserInfo userInfo) {

        return "Welcome: " + userInfo.getUsername();
    }
}

server.ssl.key-store=/Users/mymacuser/devhome/certpoc/selfsigned.jks
server.ssl.key-store-password=marwan
server.ssl.key-alias=tomcat
server.ssl.key-password=marwan
server.ssl.enabled=true
server.port=8443
spring.security.user.name=Admin
spring.security.user.password=admin
spring.security.require-ssl=true

4- Created a client-side application as following:

@Configuration
public class BeanConfig {

    @Bean("httpsClient")
    public RestTemplate getSSLRestTemplate() throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
        char[] storePassword = "marwan".toCharArray();
        File keyStore =  new File("/Users/mymacuser/devhome/certpoc/selfsigned.jks");

        SSLContext sslContext = new SSLContextBuilder()
                .loadTrustMaterial(keyStore, storePassword)
                .loadKeyMaterial(keyStore, storePassword, storePassword)
                .build();

        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

        CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client);
        RestTemplate restTemplate = new RestTemplate(factory);
        // restTemplate.setMessageConverters(List.of(new Jaxb2RootElementHttpMessageConverter()));
        return restTemplate;
    }

@RestController
@RequestMapping("/get")
public class ClientController {

    @Autowired
    @Qualifier("httpsClient")
    private RestTemplate httpsClient;

    @RequestMapping("/user")
    public String getUserFromServer() throws URISyntaxException {

        ResponseEntity<String> s = httpsClient.exchange("https://localhost:8443/get/user", HttpMethod.POST, new HttpEntity<UserInfo>(new UserInfo("marwan")), String.class);
        return s.getBody();

    }
}

As you can notice, My client-side is a (MITM) man in the middle service that I call from a POSTMAN or curl request.

When I invoke my request to the MITM service, I get as a response:

{
    "timestamp": "2020-02-17T09:16:20.399+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "403 : [{\"timestamp\":\"2020-02-17T09:16:20.325+0000\",\"status\":403,\"error\":\"Forbidden\",\"message\":\"Forbidden\",\"path\":\"/get/user\"}]",
    "path": "/get/user"
}

I tried printing the network logs for both MITM and server-side, and both show they are exchanging the correct certificate

Body:
Ok,
So I solved this issue, And here is the solution in case someone is interested:
In TLS there are two different stores:
KeyStore - Used to store keys to be used to seld identification against the other peer
TrustStore - User to tore keys of trusted peers
For server-side authentication, it's needed to specify the trust store as well and to include the client cert.
Also, it's needed to add the following property to the application.properties file:

server.ssl.client-auth=need

So the application.proprties should include:

server.ssl.trust-store=file:/Users/mymacuser/devhome/certpoc/trust.jks
server.ssl.trust-store-type=JKS
server.ssl.trust-store-password=marwan
server.ssl.client-auth=need


问:
Regex start with exactly two alphabetic characters and than followed by any digits
I'm trying to create a very simple regex that accepts strings:

starts with two [A-Za-z] characters

ends with any number of digits

my code is:

Regex.IsMatch("AA00000000000", $"^[A-Za-z]{2}[0-9]*$")
```

but it returns False. Where am I wrong? I've already tested the same regex with the same input on regexstorm.net and it works.

答: Regex.IsMatch method return boolean value. Please, try with this way. You can also try with using "$"</p>

Body:
I'm trying to create a very simple regex that accepts strings:

starts with two [A-Za-z] characters

ends with any number of digits

my code is:

Regex.IsMatch("AA00000000000", $"^[A-Za-z]{2}[0-9]*$")

but it returns False. Where am I wrong? I've already tested the same regex with the same input on regexstorm.net and it works.


问:
MySQL JOIN: Only return rows where all values from right table are NULL
I have two MySQL tables like this:

```<code>orders:
+----------+------+
| order_id | name |
+----------+------+
| 1        | Mary |
| 2        | John |
| 3        | Anne |
+----------+------+

order_details:
+----------+----------------+
| order_id | shipped        |
+----------+----------------+
| 1        | null           |
| 1        | null           |
| 1        | SHIPPED-123ABC |
| 2        | null           |
| 2        | null           |
| 3        | SHIPPED-XYZ    |
| 3        | SHIPPED-XYZ    |
| 3        | null           |
+----------+----------------+
</code>```

Now I want to join the order_details-table to the orders-table but only show the entries that only  have NULL shipped values in the order_details table. So in this example only order_id #2 would get returned.

So the result would be:

```<code>+----------+------+---------+
| order_id | name | shipped |
+----------+------+---------+
| 2        | John | null    |
+----------+------+---------+
</code>```

Thank you!

答:
If you want orders that have at least one row in order_details, then use aggregation:

```<code>select o.*
from (select od.order_id
      from order_details
      group by od.order_id
      having count(shipped) = 0
     ) od join
     orders o
     on od.order_id = o.order_id;
</code>```

If you want all such orders, even those with no rows in order_details, then use not exists:

```<code>select o.*
from orders o
where not exists (select 1
                  from order_details od
                  where od.order_id = o.order_id and
                        od.shipping is not null
                 );
</code>```

Body:
I have two MySQL tables like this:

orders:
+----------+------+
| order_id | name |
+----------+------+
| 1        | Mary |
| 2        | John |
| 3        | Anne |
+----------+------+

order_details:
+----------+----------------+
| order_id | shipped        |
+----------+----------------+
| 1        | null           |
| 1        | null           |
| 1        | SHIPPED-123ABC |
| 2        | null           |
| 2        | null           |
| 3        | SHIPPED-XYZ    |
| 3        | SHIPPED-XYZ    |
| 3        | null           |
+----------+----------------+

Now I want to join the order_details-table to the orders-table but only show the entries that only  have NULL shipped values in the order_details table. So in this example only order_id #2 would get returned.

So the result would be:

+----------+------+---------+
| order_id | name | shipped |
+----------+------+---------+
| 2        | John | null    |
+----------+------+---------+

Thank you!

Body:
If you want orders that have at least one row in order_details, then use aggregation:

select o.*
from (select od.order_id
      from order_details
      group by od.order_id
      having count(shipped) = 0
     ) od join
     orders o
     on od.order_id = o.order_id;

If you want all such orders, even those with no rows in order_details, then use not exists:

select o.*
from orders o
where not exists (select 1
                  from order_details od
                  where od.order_id = o.order_id and
                        od.shipping is not null
                 );


问:
Listings days and hours in a 2D list using python
I want to list all dates and hours between 2 given inout datetimes using dateutil library.

Example:
input: date_from= 02/16/2020:00:00:00, date_to = 02/17/2020:00:00:00

I want to have a list with the below structure

```<code>02/16/2020, 02/16/2020:00:00:00

02/16/2020, 02/16/2020:01:00:00

02/16/2020, 02/16/2020:02:00:00

... till hour 23

02/17/2020, 02/17/2020:00:00:00

02/17/2020, 02/17/2020:01:00:00

02/17/2020, 02/17/2020:02:00:00

.... till hour 23
</code>```

I tried the below code and it seems the logic need to be changed.

```<code>days = [[], []]
for day in rrule.rrule(rrule.DAILY, dtstart=date_from, until=date_to):
    for hour in rrule.rrule(rrule.HOURLY, dtstart=date_from, until=date_to):
        days.append(str(day))
</code>```

Body:
I want to list all dates and hours between 2 given inout datetimes using dateutil library.

Example:
input: date_from= 02/16/2020:00:00:00, date_to = 02/17/2020:00:00:00

I want to have a list with the below structure

02/16/2020, 02/16/2020:00:00:00

02/16/2020, 02/16/2020:01:00:00

02/16/2020, 02/16/2020:02:00:00

... till hour 23

02/17/2020, 02/17/2020:00:00:00

02/17/2020, 02/17/2020:01:00:00

02/17/2020, 02/17/2020:02:00:00

.... till hour 23

I tried the below code and it seems the logic need to be changed.

days = [[], []]
for day in rrule.rrule(rrule.DAILY, dtstart=date_from, until=date_to):
    for hour in rrule.rrule(rrule.HOURLY, dtstart=date_from, until=date_to):
        days.append(str(day))

Body:
from datetime import datetime as dt
from datetime import timedelta

date_from= '02/16/2020 00:00:00'
date_to = '02/17/2020 00:00:00'

date_from = dt.strptime(date_from, '%m/%d/%Y %H:%M:%S')
date_to = dt.strptime(date_to, '%m/%d/%Y %H:%M:%S')
new_date = date_from
while new_date < date_to:
    print(new_date)
    new_date = new_date + timedelta(minutes=60)

output:

2020-02-16 00:00:00
2020-02-16 01:00:00
2020-02-16 02:00:00
2020-02-16 03:00:00
2020-02-16 04:00:00
2020-02-16 05:00:00
2020-02-16 06:00:00
2020-02-16 07:00:00
2020-02-16 08:00:00
2020-02-16 09:00:00
2020-02-16 10:00:00
2020-02-16 11:00:00
2020-02-16 12:00:00
2020-02-16 13:00:00
2020-02-16 14:00:00
2020-02-16 15:00:00
2020-02-16 16:00:00
2020-02-16 17:00:00
2020-02-16 18:00:00
2020-02-16 19:00:00
2020-02-16 20:00:00
2020-02-16 21:00:00
2020-02-16 22:00:00
2020-02-16 23:00:00


问:
Searching For Existing Values in Array
I have been trying to search for an existing value in an array like below

```<code>var values = []
values.push(localStorage.getItem('items'));

console.log(values);

if (values.includes(2)) {
  alert('Already Exists.');
}
</code>```

When i console the array values i have output as ["1,2,3,4,5,6"] so the code treats the array as having just one index which is index[0] which makes the search quite challenging for me.

My challenge is how to find the value 2 in the array values ?

答:
firstly get the values from local storage store it in a variable, split it using the split
function, then check if the number is inside the array, alert the message if it returns true</p>

```<code>var values  =localStorage.getItem('items')
    var spliter = values.split(',')
    console.log(spliter);

    if (spliter.includes('2') == true) {
      alert('Already Exists.');
    }
</code>```

Title: Searching For Existing Values in Array

Body:
I have been trying to search for an existing value in an array like below

var values = []
values.push(localStorage.getItem('items'));

console.log(values);

if (values.includes(2)) {
  alert('Already Exists.');
}

When i console the array values i have output as ["1,2,3,4,5,6"] so the code treats the array as having just one index which is index[0] which makes the search quite challenging for me.

My challenge is how to find the value 2 in the array values ?

Body:
firstly get the values from local storage store it in a variable, split it using the split
function, then check if the number is inside the array, alert the message if it returns true

var values  =localStorage.getItem('items')
    var spliter = values.split(',')
    console.log(spliter);

    if (spliter.includes('2') == true) {
      alert('Already Exists.');
    }


问:
Unable to target button to separate behaviour using :not()
I have a HTML5 application which has a table (ID is #myTable in the remainder of this question). The table is populated by an ajax request.

Following the ajax response a single row of the table looks like this:

```<code><tr>
    <td>ID 001</td>
    <td>Foo</td>
    <td>Bar</td>
    <td>Baz</td>
    <td><a href="/fge?id=001" class="btn-fge">Find group entries</a></td>
</tr>
</code>```

The anchor in the last column isn't present on every row. It only appears for certain rows. If the anchor doesn't appear an empty row is rendered: 	.

Prior to this anchor being added I'd written a function which toggles expanding/collapsing each row. Upon expansion an additional ajax request was made to present further data. The behaviour was such that the user could click anywhere inside the row.

```<code>$('#myTable tbody').on('click', 'td', function (e) {
    var tr = $(this).closest('tr');

    // Code to expand/collapse tr
    // ...

    // Ajax request for additional row data
    // ...
}
</code>```

This all worked without any problems.

However, I want to segregate the behaviour such that the code above doesn't fire if the user has clicked the anchor. Conversely if they click anywhere inside the row other than the anchor it should fire.

I've read Check if clicked element doesn't have a specific class and attempted to target .btn-fge using a :not() condition as follows.

```<code>$('#myTable tbody').on('click', 'td:not(.btn-fge)', function (e) {

}
</code>```

This doesn't work (although I believe this might be because .btn-fge isn't a class on the  but rather an anchor inside it?). The collapsing/expanding row behaviour still fires followed by the browser redirecting to the href value. In the example given the behaviour is:

Click .btn-fge.

The row is expanded (or if it was already expanded it is collapsed).

The browser follows the href on .btn-fge so in this case redirects to /fge?id=001.

I want (1) followed by (3) to occur, but not (2) when clicking .btn-fge.

I've tried logging console.log($(this)); followed by e.preventDefault(). It doesn't matter whereabouts inside the row I click - whether it's on the button or not - it gives the same output as follows.

How can I target this such that the button behaviour is different to clicking other places inside the row?

I'm using jquery version 3.2.1 and would prefer a jquery solution but a vanilla JavaScript one would also be acceptable.

Edit - I've made a fiddle here https://jsfiddle.net/adrq0nhz/ and if you click anywhere inside the table it will console log "this is still firing" which is effectively the issue of the anchor having no separate behavior. Note: the .btn-fge class is on the anchor, not the , and this cannot be changed.

答:
You can make use of jQuery's .find() method</p>

```<code>$('#myTable tbody').on('click', 'td', function (e) {

    // proceed only if a child does not exist with class .btn-fge
    if(!$(this).find('.btn-fge').length){

        // non-anchor td clicked
    }
}
</code>```

Body:
I have a HTML5 application which has a table (ID is #myTable in the remainder of this question). The table is populated by an ajax request.

Following the ajax response a single row of the table looks like this:

    ID 001
    Foo
    Bar
    Baz
    Find group entries

The anchor in the last column isn't present on every row. It only appears for certain rows. If the anchor doesn't appear an empty row is rendered: 	.

Prior to this anchor being added I'd written a function which toggles expanding/collapsing each row. Upon expansion an additional ajax request was made to present further data. The behaviour was such that the user could click anywhere inside the row.

$('#myTable tbody').on('click', 'td', function (e) {
    var tr = $(this).closest('tr');

    // Code to expand/collapse tr
    // ...

    // Ajax request for additional row data
    // ...
}

This all worked without any problems.

However, I want to segregate the behaviour such that the code above doesn't fire if the user has clicked the anchor. Conversely if they click anywhere inside the row other than the anchor it should fire.

I've read Check if clicked element doesn't have a specific class and attempted to target .btn-fge using a :not() condition as follows.

$('#myTable tbody').on('click', 'td:not(.btn-fge)', function (e) {

}

This doesn't work (although I believe this might be because .btn-fge isn't a class on the  but rather an anchor inside it?). The collapsing/expanding row behaviour still fires followed by the browser redirecting to the href value. In the example given the behaviour is:

Click .btn-fge.

The row is expanded (or if it was already expanded it is collapsed).

The browser follows the href on .btn-fge so in this case redirects to /fge?id=001.

I want (1) followed by (3) to occur, but not (2) when clicking .btn-fge.

I've tried logging console.log($(this)); followed by e.preventDefault(). It doesn't matter whereabouts inside the row I click - whether it's on the button or not - it gives the same output as follows.

How can I target this such that the button behaviour is different to clicking other places inside the row?

I'm using jquery version 3.2.1 and would prefer a jquery solution but a vanilla JavaScript one would also be acceptable.

Edit - I've made a fiddle here https://jsfiddle.net/adrq0nhz/ and if you click anywhere inside the table it will console log "this is still firing" which is effectively the issue of the anchor having no separate behavior. Note: the .btn-fge class is on the anchor, not the , and this cannot be changed.

Body:
You can make use of jQuery's .find() method

$('#myTable tbody').on('click', 'td', function (e) {

    // proceed only if a child does not exist with class .btn-fge
    if(!$(this).find('.btn-fge').length){

        // non-anchor td clicked
    }
}