问:
How to subset data based on a column efficiently (R)
This is my first time posting, so bear with me on the formatting. I am trying to select data based on an another columns data efficiently.

The data set is as follows:

```<code>+------+------+------+------+--+
| Var1 | Var2 | Var3 | Type |  |
+======+======+======+======+==+
|  3.3 |  2.3 |  5.5 |    1 |  |
|  3.4 |  2.0 |  7.5 |    2 |  |
|  2.9 |  1.9 |  6.2 |    1 |  |
|  3.1 |  2.2 |  5.9 |    1 |  |
|  3.3 |  2.1 |  7.1 |    3 |  |
+------+------+------+------+--+
</code>```

In row 1, when Type = 1, I want it to select that rows Var1 and put it in an another column, for Type = 2, Var2, Type = 3, Var3 -- and so on. How would I do this efficiently? I have done it with a for loop, but with a bigger dataset it takes a while to process. Thanks

Essentially put into pseudo code, I was thinking

If df[i, 4] == 1, then
      df[i, 5] == df[i, 1]

Body:
This is my first time posting, so bear with me on the formatting. I am trying to select data based on an another columns data efficiently.

The data set is as follows:

+------+------+------+------+--+
| Var1 | Var2 | Var3 | Type |  |
+======+======+======+======+==+
|  3.3 |  2.3 |  5.5 |    1 |  |
|  3.4 |  2.0 |  7.5 |    2 |  |
|  2.9 |  1.9 |  6.2 |    1 |  |
|  3.1 |  2.2 |  5.9 |    1 |  |
|  3.3 |  2.1 |  7.1 |    3 |  |
+------+------+------+------+--+

In row 1, when Type = 1, I want it to select that rows Var1 and put it in an another column, for Type = 2, Var2, Type = 3, Var3 -- and so on. How would I do this efficiently? I have done it with a for loop, but with a bigger dataset it takes a while to process. Thanks

Essentially put into pseudo code, I was thinking

If df[i, 4] == 1, then
      df[i, 5] == df[i, 1]

Body:
We can do matrix subsetting.

df$new_col <- df[cbind(1:nrow(df), df$Type)]
df
#  Var1 Var2 Var3 Type new_col
#1  3.3  2.3  5.5    1     3.3
#2  3.4  2.0  7.5    2     2.0
#3  2.9  1.9  6.2    1     2.9
#4  3.1  2.2  5.9    1     3.1
#5  3.3  2.1  7.1    3     7.1

data

df <- structure(list(Var1 = c(3.3, 3.4, 2.9, 3.1, 3.3), Var2 = c(2.3,
2, 1.9, 2.2, 2.1), Var3 = c(5.5, 7.5, 6.2, 5.9, 7.1), Type = c(1L,
2L, 1L, 1L, 3L)), class = "data.frame", row.names = c(NA, -5L))


来源: stackexchange

答:
Since you are doing O(N^2) comparison to find the common elements already, you don't need to sort the array before. Just removing the sorting should also work and reduce a good amount of redundant code

Instead of string comparison use JSONObject.similar()

ContentLicense: CC BY-SA 4.0

Title: Compare two json arrays and return common elements java

Body:
I am a newbie to java. I have a JSONArray  like this

String data1 =  "[{\"_index\":\"sales_csv\",\"_source\":{\"Order Date\":\"2016-01-28T18:37:00.000Z\"},\"sort\":[1576653361740],\"_score\":null},{\"_index\":\"sales_csv\",\"_source\":{\"Order Date\":\"2016-01-29T18:35:00.000Z\"},\"sort\":[1576653361740],\"_score\":null},{\"_index\":\"sales_csv\",\"_source\":{\"Order Date\":\"2016-01-30T18:41:00.000Z\"},\"sort\":[1576653361739],\"_score\":null}]";
String data2 = "[ { \"_index\": \"sales_csv\", \"_source\": { \"Order Date\": \"2016-01-28T18:37:00.000Z\" }, \"sort\": [ 1576653361740 ], \"_score\": null }, { \"_index\": \"sales_csv\", \"_source\": { \"Order Date\": \"2016-01-29T18:35:00.000Z\" }, \"sort\": [ 1576653361740 ], \"_score\": null }, { \"_index\": \"sales_csv\", \"_source\": { \"Order Date\": \"2016-01-17T18:35:00.000Z\" }, \"sort\": [ 1576653361736 ], \"_score\": null } ]" ;

JSONArray jsonElement1 = new JSONArray(data1) ;
JSONArray jsonElement2 = new JSONArray(data2) ;

After conversion:

jsonElement1 = [
    {"_index":"sales_csv","_source":{"Order Date":"2016-01-28T18:37:00.000Z"},"sort":[1576653361740],"_score":null},
    {"_index":"sales_csv","_source":{"Order Date":"2016-01-29T18:35:00.000Z"},"sort":[1576653361740],"_score":null},
    {"_index":"sales_csv","_source":{"Order Date":"2016-01-30T18:41:00.000Z"},"sort":[1576653361739],"_score":null}]
jsonElement2 = [
    { "_index": "sales_csv", "_source": { "Order Date": "2016-01-28T18:37:00.000Z" }, "sort": [ 1576653361740 ], "_score": null },
    { "_index": "sales_csv", "_source": { "Order Date": "2016-01-17T18:35:00.000Z" }, "sort": [ 1576653361736 ], "_score": null },
    { "_index": "sales_csv", "_source": { "Order Date": "2016-01-29T18:35:00.000Z" }, "sort": [ 1576653361740 ], "_score": null }, ]

I need to compare both the JSONArray and return the common JSONobjects between both the array and append it to the  new JSONarray output

Required Output:

output = [
    { "_index": "sales_csv", "_source": { "Order Date": "2016-01-28T18:37:00.000Z" }, "sort": [ 1576653361740 ], "_score": null },
    { "_index": "sales_csv", "_source": { "Order Date": "2016-01-29T18:35:00.000Z" }, "sort": [ 1576653361740 ], "_score": null }
     ]

I tried this answer Comparing 2 JSONArray. But it returns either true/ false.

Here's the Code I tried:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.*;

import static java.lang.System.out;

public class home {
    public static JSONArray sortJsonArray(JSONArray inputUnSort, JSONArray outputSort) throws JsonProcessingException {
        for (int i = 0; i < inputUnSort.length(); i++) {
            ObjectMapper om = new ObjectMapper();
            om.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
            Map<String, Object> map = null;
            try {
                map = om.readValue(inputUnSort.getJSONObject(i).toString(), HashMap.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String jsonstr = om.writeValueAsString(map);
            JSONObject json = new JSONObject(jsonstr);
            outputSort.put(json);
        }
        return outputSort;
    }
    public static JSONArray compareJsonArray(JSONArray jsonElement1, JSONArray jsonElement2) throws JsonProcessingException {
//        Sorting
        JSONArray jsonElement1sort = new JSONArray() ;
        JSONArray jsonElement2sort = new JSONArray();
        jsonElement1sort = sortJsonArray( jsonElement1,  jsonElement1sort);
        jsonElement2sort = sortJsonArray( jsonElement2,  jsonElement2sort);
        JSONArray outputJSONelement = new JSONArray();
        for (int i = 0; i < jsonElement1sort.length(); i++){
            for (int j = 0; j < jsonElement2sort.length(); j++) {
                if (jsonElement1sort.getJSONObject(i).toString().equals(jsonElement2sort.getJSONObject(j).toString())){
                    outputJSONelement.put(jsonElement1sort.getJSONObject(i));
                }
            }
        }
        return  outputJSONelement;
    }
    public static void main(String[] args) throws JsonProcessingException {
        String data1 =  "[{\"_index\":\"sales_csv\",\"_source\":{\"Order Date\":\"2016-01-28T18:37:00.000Z\"},\"sort\":[1576653361740],\"_score\":null},{\"_index\":\"sales_csv\",\"_source\":{\"Order Date\":\"2016-01-29T18:35:00.000Z\"},\"sort\":[1576653361740],\"_score\":null},{\"_index\":\"sales_csv\",\"_source\":{\"Order Date\":\"2016-01-30T18:41:00.000Z\"},\"sort\":[1576653361739],\"_score\":null}]";
        String data2 = "[ { \"_index\": \"sales_csv\", \"_source\": { \"Order Date\": \"2016-01-28T18:37:00.000Z\" }, \"sort\": [ 1576653361740 ], \"_score\": null }, { \"_index\": \"sales_csv\", \"_source\": { \"Order Date\": \"2016-01-29T18:35:00.000Z\" }, \"sort\": [ 1576653361740 ], \"_score\": null }, { \"_index\": \"sales_csv\", \"_source\": { \"Order Date\": \"2016-01-17T18:35:00.000Z\" }, \"sort\": [ 1576653361736 ], \"_score\": null } ]" ;
        JSONArray jsonElement1 = new JSONArray(data1) ;
        JSONArray jsonElement2 = new JSONArray(data2) ;
        out.println(jsonElement1);
        out.println(jsonElement2);
        out.println(compareJsonArray(jsonElement1, jsonElement2));
    }
}

The above code looks huge.
Any shortest way to achieve this


问:
How to insert a map into a popover - bootstrap
I need to have a popover which can present a map inside its body. I did this basic example:

```<code>    <!DOCTYPE html>
<html>

<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin="" />
  <script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js" integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==" crossorigin=""></script>

  <link rel="stylesheet" href="css/style.css">
  <script src="script/script.js"></script>
</head>

<body>
  <div class="container">
    <h3>Popover Example</h3>
    <a href="#" data-toggle="popover">Toggle popover</a>
  </div>

  <script>
    let script = `
    <script>
    var map = L.map('map').setView([51.505, -0.09], 13);

    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'}).addTo(map);

    L.marker([51.5, -0.09]).addTo(map)
    .bindPopup('A pretty CSS3 popup.<br> Easily customizable.')
    .openPopup();
    <\/script>`;

    console.log(script);
    $(document).ready(function() {
      $('[data-toggle="popover"]').popover({
        title: 'A nice map inside a popover!',
        content: "<div id='map' style='background: gray;'></div>" + script,
        html: true
      });

    });
  </script>
</body>

</html>
</code>```

It sends html content which contains a div and script for the leaflet map. It doesn't work.
I am not sure this approach would work out and maybe you know a better way to have a map once a table cell or any other element is clicked.

答:
You cannot append script tags directly on the content prop of the popover method. To make this, you will need listen to some event triggered after the popover is rendered, like shown.bs.popover:

```<code>$('[data-toggle="popover"]').on('shown.bs.popover', () => {});
</code>```

Inside, you'll be able to call Leaflet and create the map instance. I attach a CodePen with the concept (I applied some CSS to make adjustments on the popover layout to show the map correctly) https://codepen.io/geekzolanos-dev/pen/gOpwRrR

Body:
I need to have a popover which can present a map inside its body. I did this basic example:

    <!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin="" />

  <link rel="stylesheet" href="css/style.css">

Popover Example

    Toggle popover

It sends html content which contains a div and script for the leaflet map. It doesn't work.
I am not sure this approach would work out and maybe you know a better way to have a map once a table cell or any other element is clicked.

Body:
You cannot append script tags directly on the content prop of the popover method. To make this, you will need listen to some event triggered after the popover is rendered, like shown.bs.popover:

$('[data-toggle="popover"]').on('shown.bs.popover', () => {});

Inside, you'll be able to call Leaflet and create the map instance. I attach a CodePen with the concept (I applied some CSS to make adjustments on the popover layout to show the map correctly) https://codepen.io/geekzolanos-dev/pen/gOpwRrR


问:
How to adapt PATH variable in Makefile.am?
In the file Makefile.am a am using somehting like this:

```<code>PATH := $(PWD)/.tools/bin:$(PATH)
</code>```

When running configure.ac I get this error:

```<code>Makefile.am:3: warning: ':='-style assignments are not portable
</code>```

I using the assignment operator = would cause a recursive problem.

So I wonder how to adapt PATH variable in Makefile.am without having this problem?

答:
If I really needed to change the shell's PATH inside a rule, I would set a shell variable PATH there, not a make variable PATH:

```<code>foo.h: foo.src
        PATH="$${PATH}:$$(pwd)/.tools/bin"; \
        my-tool foo.src > foo.h
</code>```

However, if I need my-tool from that directory, why not call my-tool with the proper path in the first place?

```<code>foo.h: foo.src .tools/bin/my-tool
        ./.tools/bin/my-tool foo.src > foo.h
</code>```

Body:
In the file Makefile.am a am using somehting like this:

PATH := $(PWD)/.tools/bin:$(PATH)

When running configure.ac I get this error:

Makefile.am:3: warning: ':='-style assignments are not portable

I using the assignment operator = would cause a recursive problem.

So I wonder how to adapt PATH variable in Makefile.am without having this problem?

Body:
If I really needed to change the shell's PATH inside a rule, I would set a shell variable PATH there, not a make variable PATH:

foo.h: foo.src
        PATH="$${PATH}:$$(pwd)/.tools/bin"; \
        my-tool foo.src > foo.h

However, if I need my-tool from that directory, why not call my-tool with the proper path in the first place?

foo.h: foo.src .tools/bin/my-tool
        ./.tools/bin/my-tool foo.src > foo.h


问:
How do I make a string bold in a console window?
So I'm trying to find a simple code that makes my code get printed in bold. When I searched the internet all of them were so complicated that it wasn't even worth it. Is there any easier way to make a string or just a Console.WriteLine(" "); bold? </p>

```<code>Console.Write("Type in the number of people to create: ");
int time = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nGenerating " + time + " people please stand by...");
System.Threading.Thread.Sleep(3000);
Console.Clear();
</code>```

答:
Fonts and Styles are not available on a per-word basis.(@Atreyagaurav)

But You Can Set Console.ForegroundColor

```<code>Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("This Is A Test Txt"); // Print Text In Red Color
Console.ResetColor();
</code>```

Or Alternatively, You Can Change cmd Font Setting

Body:
So I'm trying to find a simple code that makes my code get printed in bold. When I searched the internet all of them were so complicated that it wasn't even worth it. Is there any easier way to make a string or just a Console.WriteLine(" "); bold?

Console.Write("Type in the number of people to create: ");
int time = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nGenerating " + time + " people please stand by...");
System.Threading.Thread.Sleep(3000);
Console.Clear();

Body:
Fonts and Styles are not available on a per-word basis.(@Atreyagaurav)

But You Can Set Console.ForegroundColor

Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("This Is A Test Txt"); // Print Text In Red Color
Console.ResetColor();

Or Alternatively, You Can Change cmd Font Setting


问:
Catch up text from voice Interactive Canvas?
I am designing a web screen with Interactive Canvas. I want to capture the text from the voice of the user speaking in the input box. It's similar to conv.input.raw in functions / index.js but I don't know what to do in public / index.html

答:
Once you have text in conv.input.raw in functions / index.js you need to pass it to website using interactiveCanvas api.

```<code>conv.ask(new HtmlResponse({
  data: {
    userEnteredData: conv.input.raw
  }
}));
</code>```

And from website you will get it in callback of interactive canvas

```<code>interactiveCanvas.ready({
   onUpdate(data) {
       console.log('user entered text = ', data.userEnteredData);
       document.getElementById("textBox").value = data.userEnteredData;
   }
});
</code>```

Body:
Once you have text in conv.input.raw in functions / index.js you need to pass it to website using interactiveCanvas api.

conv.ask(new HtmlResponse({
  data: {
    userEnteredData: conv.input.raw
  }
}));

And from website you will get it in callback of interactive canvas

interactiveCanvas.ready({
   onUpdate(data) {
       console.log('user entered text = ', data.userEnteredData);
       document.getElementById("textBox").value = data.userEnteredData;
   }
});


问:
python opens text file with a space between every character
Whenever I try to open a .csv file with the python command
fread = open('input.csv', 'r')
it always opens the file with spaces between every single character.  I'm guessing it's something wrong with the text file because I can open other text files with the same command and they are loaded correctly.  Does anyone know why a text file would load like this in python?

Thanks.

Update

Ok, I got it with the help of Jarret Hardie's post

this is the code that I used to convert the file to ascii

```<code>fread = open('input.csv', 'rb').read()
mytext = fread.decode('utf-16')
mytext = mytext.encode('ascii', 'ignore')
fwrite = open('input-ascii.csv', 'wb')
fwrite.write(mytext)
</code>```

Thanks!

答:
It did never ocurred to me, but as truppo said, it must be something wrong with the file.

Try to open the file in Excel/BrOffice Calc and Save As the file as Csv again.

If the problem persists, try a subset of the data: fist 10/last 10/intermediate 10 lines of the file.

ContentLicense: CC BY-SA 2.5

Body:
Whenever I try to open a .csv file with the python command
fread = open('input.csv', 'r')
it always opens the file with spaces between every single character.  I'm guessing it's something wrong with the text file because I can open other text files with the same command and they are loaded correctly.  Does anyone know why a text file would load like this in python?

Thanks.

Update

Ok, I got it with the help of Jarret Hardie's post

this is the code that I used to convert the file to ascii

fread = open('input.csv', 'rb').read()
mytext = fread.decode('utf-16')
mytext = mytext.encode('ascii', 'ignore')
fwrite = open('input-ascii.csv', 'wb')
fwrite.write(mytext)

Thanks!

LastEditorDisplayName: ΤΖΩΤΖΙΟΥ

OwnerDisplayName: Luiz Damim


问:
Session attribute access and converting to int?
I have stored user id in Session using following command in Servlet:

```<code>HttpSession session = request.getSession();
session.setAttribute("user", user.getId());
</code>```

Now, I want to access that user id from another Servlet:

```<code>HttpSession session = request.getSession(false);
int userid = (int) session.getAttribute("user"); // This is not working

OR

User user = new User();
user.setId(session.getAttribute("user")); This ain't possible (Object != int)
</code>```

Question:

How can I cast to int and send the id to DAO for SELECT statement

答:
```<code>Integer userid = Integer.parseInt(session.getAttribute("user"));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have stored user id in Session using following command in Servlet:

HttpSession session = request.getSession();
session.setAttribute("user", user.getId());

Now, I want to access that user id from another Servlet:

HttpSession session = request.getSession(false);
int userid = (int) session.getAttribute("user"); // This is not working

OR

User user = new User();
user.setId(session.getAttribute("user")); This ain't possible (Object != int)

Question:

How can I cast to int and send the id to DAO for SELECT statement


问:
Store Excel file along within flask app and make it readable when deployed on heroku
My flask app reads an locally stored excel file and it is running perfect on local machine.

When I deploy the same app on heroku it is throws exception-

```<code>FileNotFoundError: [Errno 2] No such file or directory: 'C:/QuestionBank_v5.xlsx'
</code>```

Which is valid as heroku deployment cannot read from my local machine.

Is there a way to store this file along with flask app files and make it readable when deployed on heroku?

答:
Yes, you can store the file in the same directory as the Flask app file and use os.path to get the app's current directory and append the file name to it.</p>

```<code>import os

# Current directory for Flask app
APP_ROOT = os.path.dirname(os.path.abspath(__file__))

# Current directory for Flask app + file name
# Use this file_path variable in your code to refer to your file
file_path = os.path.join(APP_ROOT, 'QuestionBank_v5.xlsx')

print(file_path)
</code>```

Body:
My flask app reads an locally stored excel file and it is running perfect on local machine.

When I deploy the same app on heroku it is throws exception-

FileNotFoundError: [Errno 2] No such file or directory: 'C:/QuestionBank_v5.xlsx'

Which is valid as heroku deployment cannot read from my local machine.

Is there a way to store this file along with flask app files and make it readable when deployed on heroku?

Body:
Yes, you can store the file in the same directory as the Flask app file and use os.path to get the app's current directory and append the file name to it.

import os

# Current directory for Flask app
APP_ROOT = os.path.dirname(os.path.abspath(__file__))

# Current directory for Flask app + file name
# Use this file_path variable in your code to refer to your file
file_path = os.path.join(APP_ROOT, 'QuestionBank_v5.xlsx')

print(file_path)


问:
MDX linkmember equivalent in DAX
Is there any equivalent of linkmemeber from MDX to DAX?

I am trying to migrate the following script from MDX to DAX

```<code>   with

member TauxdetransformationQuartileRegion  as ([Measures].[Taux_de_transformation_Region],[Bon Envoi].[Bon Envoi].&[True])
member Annees as [Date Creation].[Année].currentmember.name
select  {

        [Measures].[Tx_Real_Meilleur_Region]
        ,TauxdetransformationQuartileRegion

      } on 0

FROM ( select strtoset(@Region) on 0 from test)

 WHERE (
 linkmember(strtotuple(@DateFin),[Mois Publication].[Mois de publication])
 ,{strtotuple(@DateDebut):strtotuple(@DateFin)}
 ,[Perimetre Ebusiness].[Périmètre E-Business].&[O]
 ,{[MER_Publication].[Detail Type Visiteur].&[Prospect],[MER_Publication].[Detail Type Visiteur].&[Client direct]}
 ,( - { [Origine_Marketing].[Entree Parcours].&[SiteAgent] } )

)
</code>```

答:
MDX query parameters are typically strings with member unique names ("[Dim].[Attr].&[Key]") which you must convert to a member with StrToMember(@Param). And if you need to switch hierarchies you the use LinkMember.

DAX parameters are just the values. So the parameter will work against any dimension. Thus LinkMember isn’t needed.

Here is an article about DAX parameters. For Date type parameters I forget if you just say 'Date'[Date] = @DateParam or if you have to say 'Date'[Date] = DATEVALUE(@DateParam). My recollection is that it depends on whether the parameter is Date type (use the first approach) or String type (use the DATEVALUE approach).

Title: MDX linkmember equivalent in DAX

Body:
Is there any equivalent of linkmemeber from MDX to DAX?

I am trying to migrate the following script from MDX to DAX

   with

member TauxdetransformationQuartileRegion  as ([Measures].[Taux_de_transformation_Region],[Bon Envoi].[Bon Envoi].&[True])
member Annees as [Date Creation].[Année].currentmember.name
select  {

        [Measures].[Tx_Real_Meilleur_Region]
        ,TauxdetransformationQuartileRegion

      } on 0

FROM ( select strtoset(@Region) on 0 from test)

 WHERE (
 linkmember(strtotuple(@DateFin),[Mois Publication].[Mois de publication])
 ,{strtotuple(@DateDebut):strtotuple(@DateFin)}
 ,[Perimetre Ebusiness].[Périmètre E-Business].&[O]
 ,{[MER_Publication].[Detail Type Visiteur].&[Prospect],[MER_Publication].[Detail Type Visiteur].&[Client direct]}
 ,( - { [Origine_Marketing].[Entree Parcours].&[SiteAgent] } )

)


问:
Azure DevOps run build on branch creation
My pipeline looks like:

```<code>trigger:
  branches:
    include:
    - release-*

jobs:
- job: release
  condition: contains(variables['Build.SourceBranch'], 'refs/heads/release-')
  pool:
    vmImage: 'windows-latest'
  steps:
  - bash: |
      echo "RELEASE"
    displayName: 'release_task1'
</code>```

How can I make it executed automatically when new release-.. branch is created?

答:
How can I make it executed automatically when new release-.. branch is created?

This is a limitation of YAML trigger.

If the yaml file is not present in the new create branch, the build will not be triggered.

That is reason why it does not execute automatically when creating a new release ... branch.

To resolve this issue, we need to create the yaml file in the basic branch, like release-basic, then we create a new branch based on the branch release-basic. Now the build will be executed automatically.

Hope this helps.

Body:
My pipeline looks like:

trigger:
  branches:
    include:
    - release-*

jobs:
- job: release
  condition: contains(variables['Build.SourceBranch'], 'refs/heads/release-')
  pool:
    vmImage: 'windows-latest'
  steps:
  - bash: |
      echo "RELEASE"
    displayName: 'release_task1'

How can I make it executed automatically when new release-.. branch is created?


问:
How to Solve App has Stopped in react native
after yarn or npm react-native-screens my app wont debug, it says unfortunatelly, App has stopped.

and when i did

```<code>react-native link react-native-screens
</code>```

it says

npm\react-native.ps1 cannot be loaded because running scripts is
  disabled on this system.

My RN vers.

react-native-cli: 2.0.1

react-native: 0.61.5

答:
Since you are using React Native Version 0.60 > you don't need to link packages using command react-native link. Do not do that :) React will automatically link packages

This is a powershell security policy, to fix it run the following

```<code>PS C:\> Set-ExecutionPolicy RemoteSigned
</code>```

The stricter the policy, the more secure your system becomes.

You can change RemoteSigned to other options like: Restricted, AllSigned, RemoteSigned, Unrestricted

Source

Body:
after yarn or npm react-native-screens my app wont debug, it says unfortunatelly, App has stopped.

and when i did

react-native link react-native-screens

it says

npm\react-native.ps1 cannot be loaded because running scripts is
  disabled on this system.

My RN vers.

react-native-cli: 2.0.1

react-native: 0.61.5

Body:
Since you are using React Native Version 0.60 > you don't need to link packages using command react-native link. Do not do that :) React will automatically link packages

This is a powershell security policy, to fix it run the following

PS C:\> Set-ExecutionPolicy RemoteSigned

The stricter the policy, the more secure your system becomes.

You can change RemoteSigned to other options like: Restricted, AllSigned, RemoteSigned, Unrestricted

Source


问:
LayoutInflater fails to inflate layout with reference to class
I try to inflate Layout which contain class.
I create inflater instance with:

```<code> LayoutInflater inflate =(LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRelLayout = (RelativeLayout) inflate.inflate(
                    R.layout.app_layout, null);
</code>```

My app_layout.xml layout is:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:panel="http://schemas.android.com/apk/res/com.alpha"
            android:id="@+id/layoutMain"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:gravity="top|right">
</code>```

        .
        .
        .

Inflation fails with exception: java.lang.RuntimeException: Your Panel must have a child View whose id attribute is 'R.id.panelHandle'

Thanks for help

答:
I have tried following code, It's working perfect, Please provide full source code so I can identify the error.

Test.java

```<code> LayoutInflater inflate =(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
     RelativeLayout mRelLayout = (RelativeLayout) inflate.inflate(
                         R.layout.app_layout, null);
</code>```

app_layout.xml

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:panel="http://schemas.android.com/apk/res/com.alpha"
            android:id="@+id/layoutMain"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:gravity="top|right" />
</code>```

Body:
I try to inflate Layout which contain class.
I create inflater instance with:

 LayoutInflater inflate =(LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRelLayout = (RelativeLayout) inflate.inflate(
                    R.layout.app_layout, null);

My app_layout.xml layout is:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:panel="http://schemas.android.com/apk/res/com.alpha"
            android:id="@+id/layoutMain"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:gravity="top|right">

        .
        .
        .

Inflation fails with exception: java.lang.RuntimeException: Your Panel must have a child View whose id attribute is 'R.id.panelHandle'

Thanks for help

Body:
I have tried following code, It's working perfect, Please provide full source code so I can identify the error.

Test.java

 LayoutInflater inflate =(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
     RelativeLayout mRelLayout = (RelativeLayout) inflate.inflate(
                         R.layout.app_layout, null);

app_layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:panel="http://schemas.android.com/apk/res/com.alpha"
            android:id="@+id/layoutMain"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:gravity="top|right" />


问:
is there a way (or conditional statement in Clojure) to go through all different conditions even if one of the conditions is false?
I would like to evaluate all the conditions in this block but i can't find any conditional statement that does this without pulling out when one condition is false. If there's a way outside using conditional statements please let me know also.

Kindly help. Tnx.

```<code>(when
     ;;when "number" is found in 'a' execute the nextline
      (clojure.string/includes? (.toString a) "number")
        (println (hash-map :num {:test 'number?, :data (flatten num)}))
     ;;when "vector" is found in 'b' execute the nextline
      (clojure.string/includes? (.toString b) "vector")
        (println (hash-map :vec {:test 'vector?, :data vec}))
     ;;when "string" is found in 'c' execute the nextline
      (clojure.string/includes? (.toString c) "symbol")
        (println (hash-map :sym {:test 'symbol?, :data (flatten sym)}) )
     )
</code>```

答:
If you look at https://clojuredocs.org/clojure.core/when you can see that when only takes 1 expression and 1 body, which means that only the first check you write will be used as expression and the rest is part of the body.

I am not really sure what you are trying to achieve in your example, but if you want to match with multiple criteria, you can wrap in an or.

```<code>(def a 120)
(when (or (= a 120) (= a 1)) (println "a is 120 or 1"))
</code>```

If you want some kind of keep trying mechanism, then case, cond or condp could be solutions. You can look them up on ClojureDocs

Body:
I would like to evaluate all the conditions in this block but i can't find any conditional statement that does this without pulling out when one condition is false. If there's a way outside using conditional statements please let me know also.

Kindly help. Tnx.

(when
     ;;when "number" is found in 'a' execute the nextline
      (clojure.string/includes? (.toString a) "number")
        (println (hash-map :num {:test 'number?, :data (flatten num)}))
     ;;when "vector" is found in 'b' execute the nextline
      (clojure.string/includes? (.toString b) "vector")
        (println (hash-map :vec {:test 'vector?, :data vec}))
     ;;when "string" is found in 'c' execute the nextline
      (clojure.string/includes? (.toString c) "symbol")
        (println (hash-map :sym {:test 'symbol?, :data (flatten sym)}) )
     )

Body:
If you look at https://clojuredocs.org/clojure.core/when you can see that when only takes 1 expression and 1 body, which means that only the first check you write will be used as expression and the rest is part of the body.

I am not really sure what you are trying to achieve in your example, but if you want to match with multiple criteria, you can wrap in an or.

(def a 120)
(when (or (= a 120) (= a 1)) (println "a is 120 or 1"))

If you want some kind of keep trying mechanism, then case, cond or condp could be solutions. You can look them up on ClojureDocs


问:
How to override the css of common html(ex: header html page) file included in another html file in angular 6
We are using header and footer as common in our code but in one page we need to add one css property for the common footer.

```<code><app-footer>
  <footer class="mobile-footer">
    <div class="container"></div>
  </footer>
</app-footer>
</code>```

so how can we override css of mobile-footer class from footer in another html page ex: customer page.

We have included the css file of footer in customer page in place of style urls also.

I have tried like accessing footer >.mobile-footer to override but it is not working. Can you please suggest solutions for this ?

答:
You page has unique body id. You can apply styles to descendant element using your body id.

reference: descendant-selector-css-selector

Example:

```<code>body#body-id footer>.mobile-footer{ ...}
</code>```

use !important if needed.

Body:
We are using header and footer as common in our code but in one page we need to add one css property for the common footer.

<app-footer>

</app-footer>

so how can we override css of mobile-footer class from footer in another html page ex: customer page.

We have included the css file of footer in customer page in place of style urls also.

I have tried like accessing footer >.mobile-footer to override but it is not working. Can you please suggest solutions for this ?

Body:
You page has unique body id. You can apply styles to descendant element using your body id.

reference: descendant-selector-css-selector

Example:

body#body-id footer>.mobile-footer{ ...}

use !important if needed.


答:
We can use seq to create sequence starting from 0 with steps of 0.05 with length as number of rows in each group.

```<code>library(dplyr)

df %>%
  group_by(`activity label`, `subject-id`) %>%
  mutate(timestamp = seq(0, by = 0.05, length.out = n()))
</code>```

n() gives number of rows, since our data is grouped here it gives number of rows in each group.

Title: How to rewrite a column based off of two different groups

Body:
If I have a data frame that has many rows like this:

 subject-id activity label    timestamp          x         y          z
1       1600              A 2.522077e+14 -0.3647613  8.793503  1.0550842
2       1600              A 2.522077e+14 -0.8797302  9.768784  1.0169983
3       1600              A 2.522078e+14  2.0014954 11.109070   2.619156
4       1600              A 2.522078e+14  0.4506226 12.651642 0.18455505
5       1600              A 2.522079e+14 -2.1643524 13.928436 -4.4224854
6       1600              A 2.522079e+14 -4.3327790 13.361191 -0.7188721
.
.
.
  subject-id activity label    timestamp           x          y          z
991      1600             B 2.519876e+14  1.37554930 15.3750460  2.9716187
992      1600             B 2.519877e+14 -3.93443300 17.5387880  2.1100159
993      1600             B 2.519877e+14 -0.08773804 12.7915650 -1.4541016
994      1600             B 2.519878e+14  2.03874200  3.0771484 -1.0537262
995      1600             B 2.519878e+14 -2.55847170 -2.7386780 -2.0985107
996      1600             B 2.519879e+14 -1.35530090  0.3884125 -0.6598511
.
.
.
  subject-id activity label timestamp          x         y           z
24551       1601              A  12865.64  4.7034090  9.127296  0.06404489
24552       1601              A  12865.68  5.3546320 15.635334 -0.62907650
24553       1601              A  12865.72  6.3997010 12.926893  0.45010993
24554       1601              A  12865.76 10.5320930 13.207614 -1.02471830
24555       1601              A  12865.80 16.1297360  2.683301  1.14263270
24556       1601              A  12865.84  0.3932476  6.549937 -3.78224020

How can I set the time equal to zero by group "subject-id" and "activity label" and then increments 0.05 to the rest of the group as I move down the rows. Like this:

  subject-id activity label    timestamp          x         y          z
1       1600              A            0 -0.3647613  8.793503  1.0550842
2       1600              A          .05 -0.8797302  9.768784  1.0169983
3       1600              A          .10  2.0014954 11.109070   2.619156
4       1600              A          .15  0.4506226 12.651642 0.18455505
.
.
.
  subject-id activity label    timestamp           x          y          z
991      1600             B            0  1.37554930 15.3750460  2.9716187
992      1600             B          .05 -3.93443300 17.5387880  2.1100159
993      1600             B          .10 -0.08773804 12.7915650 -1.4541016
.
.
.
  subject-id activity label timestamp          x         y           z
24551       1601              A         0  4.7034090  9.127296  0.06404489
24552       1601              A       .05  5.3546320 15.635334 -0.62907650
24553       1601              A       .10  6.3997010 12.926893  0.45010993

I have been trying to use the dplyr function because I tend to be unsuccessful with loops in the long run. I have tried the following but I can't figure out what the argument for mutate should be:

test <- as.data.frame(df %>% group_by(`activity label`, `subject-id`) %>% mutate(timestamp = ???))

Should I not be using mutate()? Should I use do()?

Body:
We can use seq to create sequence starting from 0 with steps of 0.05 with length as number of rows in each group.

library(dplyr)

df %>%
  group_by(`activity label`, `subject-id`) %>%
  mutate(timestamp = seq(0, by = 0.05, length.out = n()))

n() gives number of rows, since our data is grouped here it gives number of rows in each group.


答:
Java has Integer wrapper class , you can store int value in an Object of Integer

```<code>//setting
Integer intObj = new Integer(intVal);
session.setAttribute("key",intObj);
//fetching
Integer intObj = (Integer) session.getAttribute("key");
</code>```

Title: Session attribute access and converting to int?

Body:
Java has Integer wrapper class , you can store int value in an Object of Integer

//setting
Integer intObj = new Integer(intVal);
session.setAttribute("key",intObj);
//fetching
Integer intObj = (Integer) session.getAttribute("key");


问:
How to give Write Permission to public in Github Folder?
My project is deployed in a server. Server is pulling from Github. I want, users can upload images in one folder in Github which is deployed in server. It is showing "Permission Denied".
How to give write access to that folder in github ?

I am using CloudWays PHP project. Deployed via Github.

答:
You need to change the permission of the directory and enable others to create files inside.

```<code>sudo chmod -R 777 /yourfolderpath
</code>```

This command will change the permission of the directory recursively and enable all other users to create/modify and delete files and directories inside.

Body:
You need to change the permission of the directory and enable others to create files inside.

sudo chmod -R 777 /yourfolderpath

This command will change the permission of the directory recursively and enable all other users to create/modify and delete files and directories inside.


问:
Grails functional test Geb page object module not working No signature of method
This is the page object.

```<code>package myapp.pages
import geb.Page

class LoginPage extends Page {
    static url = "http://localhost:8080/login/auth"
    //static at = {title.contains("Login")}
    static at = {
        waitFor {title.contains("Login")} // Add waitFor here to verify on page
    }
    static content = {
        loginForm { $( 'form') }
        usernameField { $('form').userName }
        passwordField { $('form').password }
        submitButton { $('input#submit' )}
    }

    void  loginSubmit(String email, String password) {
        usernameField = "email@something.com"
        assert $('form').username == "email@something.com"
        passwordField = "secret"
        assert $('form').password == "secret"
        submitButton.click()
    }
}
</code>```

And this is the LoginSpec test file

```<code>package myapp.login

import geb.spock.GebSpec
import grails.testing.mixin.integration.Integration
import grails.transaction.*
import myapp.pages.LoginPage

@Integration
@Rollback
class LoginSpec extends GebSpec {

    def setup() {
    }

    def cleanup() {
    }

    void "user successfully logs in, is redirected to homepage"() {
        given:
        to LoginPage

        when:
        LoginPage.loginSubmit("email@something.com", "secret")

        then:
        title.contains("Dashboard")
    }
}
</code>```

When i run this test, I get the following error:

```<code>groovy.lang.MissingMethodException: No signature of method: static myapp.pages.LoginPage.loginSubmit() is applicable for argument types: (java.lang.String, java.lang.String) values: [email@something.com.com, secret]
</code>```

I basically get the same error when I hardcode the username and password into the login page loginsubmit function. The selectors are fine, when I use the same selectors directly in the LoginSpec test to set the username and password, the test passes. The issue only occurs when I try to use the page object.

答:
Instead of this:

```<code>    when:
    LoginPage.loginSubmit("email@something.com", "secret")
</code>```

Use this:

```<code>    when:
    loginSubmit("email@something.com", "secret")
</code>```

The issue isn't really a Geb one.  The JVM doesn't allow you to invoke an instance method on a class reference as the context necessary to carry out that invocation wouldn't exist.  loginSubmit is an instance method, not a static method.

I hope that helps.

Body:
This is the page object.

package myapp.pages
import geb.Page

class LoginPage extends Page {
    static url = "http://localhost:8080/login/auth"
    //static at = {title.contains("Login")}
    static at = {
        waitFor {title.contains("Login")} // Add waitFor here to verify on page
    }
    static content = {
        loginForm { $( 'form') }
        usernameField { $('form').userName }
        passwordField { $('form').password }
        submitButton { $('input#submit' )}
    }

    void  loginSubmit(String email, String password) {
        usernameField = "email@something.com"
        assert $('form').username == "email@something.com"
        passwordField = "secret"
        assert $('form').password == "secret"
        submitButton.click()
    }
}

And this is the LoginSpec test file

package myapp.login

import geb.spock.GebSpec
import grails.testing.mixin.integration.Integration
import grails.transaction.*
import myapp.pages.LoginPage

@Integration
@Rollback
class LoginSpec extends GebSpec {

    def setup() {
    }

    def cleanup() {
    }

    void "user successfully logs in, is redirected to homepage"() {
        given:
        to LoginPage

        when:
        LoginPage.loginSubmit("email@something.com", "secret")

        then:
        title.contains("Dashboard")
    }
}

When i run this test, I get the following error:

groovy.lang.MissingMethodException: No signature of method: static myapp.pages.LoginPage.loginSubmit() is applicable for argument types: (java.lang.String, java.lang.String) values: [email@something.com.com, secret]

I basically get the same error when I hardcode the username and password into the login page loginsubmit function. The selectors are fine, when I use the same selectors directly in the LoginSpec test to set the username and password, the test passes. The issue only occurs when I try to use the page object.

Body:
Instead of this:

    when:
    LoginPage.loginSubmit("email@something.com", "secret")

Use this:

    when:
    loginSubmit("email@something.com", "secret")

The issue isn't really a Geb one.  The JVM doesn't allow you to invoke an instance method on a class reference as the context necessary to carry out that invocation wouldn't exist.  loginSubmit is an instance method, not a static method.

I hope that helps.


问:
Calculating the speed of routines?
What would be the best and most accurate way to determine how long it took to process a routine, such as a procedure of function?

I ask because I am currently trying to optimize a few functions in my Application, when i test the changes it is hard to determine just by looking at it if there was any improvements at all. So if I could return an accurate or near accurate time it took to process a routine, I then have a more clear idea of how well, if any changes to the code have been made.

I considered using GetTickCount, but I am unsure if this would be anything near accurate?

It would be useful to have a resuable function/procedure to calculate the time of a routine, and use it something like this:

```<code>// < prepare for calcuation of code
...
ExecuteSomeCode; // < code to test
...
// < stop calcuating code and return time it took to process
</code>```

I look forward to hearing some suggestions.

Thanks.

Craig.

答:
From Delphi 6 upwards you can use the x86 Timestamp counter.

This counts CPU cycles, on a 1 Ghz processor, each count takes one nanosecond.

Can't get more accurate than that.

```<code>function RDTSC: Int64; assembler;
asm
  // RDTSC can be executed out of order, so the pipeline needs to be flushed
  // to prevent RDTSC from executing before your code is finished.
  // Flush the pipeline
  XOR eax, eax
  PUSH EBX
  CPUID
  POP EBX
  RDTSC  //Get the CPU's time stamp counter.
end;
</code>```

On x64 the following code is more accurate, because it does not suffer from the delay of CPUID.

```<code>  rdtscp        // On x64 we can use the serializing version of RDTSC
  push rbx      // Serialize the code after, to avoid OoO sneaking in
  push rax      // subsequent instructions prior to executing RDTSCP.
  push rdx      // See: http://www.intel.de/content/dam/www/public/us/en/documents/white-papers/ia-32-ia-64-benchmark-code-execution-paper.pdf
  xor eax,eax
  cpuid
  pop rdx
  pop rax
  pop rbx
  shl rdx,32
  or rax,rdx
</code>```

Use the above code to get the timestamp before and after executing your code.

Most accurate method possible and easy as pie.

Note that you need to run a test at least 10 times to get a good result, on the first pass the cache will be cold, and random harddisk reads and interrupts can throw off your timings.

Because this thing is so accurate it can give you the wrong idea if you only time the first run.

Why you should not use QueryPerformanceCounter()

QueryPerformanceCounter() gives the same amount of time if the CPU slows down, it compensates for CPU thottling. Whilst RDTSC will give you the same amount of cycles if your CPU slows down due to overheating or whatnot.

So if your CPU starts running hot and needs to throttle down, QueryPerformanceCounter() will say that your routine is taking more time (which is misleading) and RDTSC will say that it takes the same amount of cycles (which is accurate).

This is what you want because you're interested in the amount of CPU-cycles your code uses, not the wall-clock time.

From the lastest intel docs: http://software.intel.com/en-us/articles/measure-code-sections-using-the-enhanced-timer/?wapkw=%28rdtsc%29

Using the Processor Clocks

This timer is very accurate. On a system with a 3GHz processor, this timer can measure events that last less than one nanosecond. [...] If the frequency changes while the targeted code is running, the final reading will be redundant since the initial and final readings were not taken using the same clock frequency. The number of clock ticks that occurred during this time will be accurate, but the elapsed time will be an unknown.

When not to use RDTSC

RDTSC is useful for basic timing. If you're timing multithreaded code on a single CPU machine, RDTSC will work fine. If you have multiple CPU's the startcount may come from one CPU and the endcount from another.

So don't use RDTSC to time multithreaded code on a multi-CPU machine. On a single CPU machine it works fine, or single threaded code on a multi-CPU machine it is also fine.

Also remember that RDTSC counts CPU cycles. If there is something that takes time but doesn't use the CPU, like disk-IO or network than RDTSC is not a good tool.

But the documentation says RDTSC is not accurate on modern CPU's

RDTSC is not a tool for keeping track of time, it's a tool for keeping track of CPU-cycles.

For that it is the only tool that is accurate. Routines that keep track of time are not accurate on modern CPU's because the CPU-clock is not absolute like it used to be.

Title: Calculating the speed of routines?

Body:
What would be the best and most accurate way to determine how long it took to process a routine, such as a procedure of function?

I ask because I am currently trying to optimize a few functions in my Application, when i test the changes it is hard to determine just by looking at it if there was any improvements at all. So if I could return an accurate or near accurate time it took to process a routine, I then have a more clear idea of how well, if any changes to the code have been made.

I considered using GetTickCount, but I am unsure if this would be anything near accurate?

It would be useful to have a resuable function/procedure to calculate the time of a routine, and use it something like this:

// < prepare for calcuation of code
...
ExecuteSomeCode; // < code to test
...
// < stop calcuating code and return time it took to process

I look forward to hearing some suggestions.

Thanks.

Craig.

Body:
From Delphi 6 upwards you can use the x86 Timestamp counter.

This counts CPU cycles, on a 1 Ghz processor, each count takes one nanosecond.

Can't get more accurate than that.

function RDTSC: Int64; assembler;
asm
  // RDTSC can be executed out of order, so the pipeline needs to be flushed
  // to prevent RDTSC from executing before your code is finished.
  // Flush the pipeline
  XOR eax, eax
  PUSH EBX
  CPUID
  POP EBX
  RDTSC  //Get the CPU's time stamp counter.
end;

On x64 the following code is more accurate, because it does not suffer from the delay of CPUID.

  rdtscp        // On x64 we can use the serializing version of RDTSC
  push rbx      // Serialize the code after, to avoid OoO sneaking in
  push rax      // subsequent instructions prior to executing RDTSCP.
  push rdx      // See: http://www.intel.de/content/dam/www/public/us/en/documents/white-papers/ia-32-ia-64-benchmark-code-execution-paper.pdf
  xor eax,eax
  cpuid
  pop rdx
  pop rax
  pop rbx
  shl rdx,32
  or rax,rdx

Use the above code to get the timestamp before and after executing your code.

Most accurate method possible and easy as pie.

Note that you need to run a test at least 10 times to get a good result, on the first pass the cache will be cold, and random harddisk reads and interrupts can throw off your timings.

Because this thing is so accurate it can give you the wrong idea if you only time the first run.

Why you should not use QueryPerformanceCounter()

QueryPerformanceCounter() gives the same amount of time if the CPU slows down, it compensates for CPU thottling. Whilst RDTSC will give you the same amount of cycles if your CPU slows down due to overheating or whatnot.

So if your CPU starts running hot and needs to throttle down, QueryPerformanceCounter() will say that your routine is taking more time (which is misleading) and RDTSC will say that it takes the same amount of cycles (which is accurate).

This is what you want because you're interested in the amount of CPU-cycles your code uses, not the wall-clock time.

From the lastest intel docs: http://software.intel.com/en-us/articles/measure-code-sections-using-the-enhanced-timer/?wapkw=%28rdtsc%29

Using the Processor Clocks

This timer is very accurate. On a system with a 3GHz processor, this timer can measure events that last less than one nanosecond. [...] If the frequency changes while the targeted code is running, the final reading will be redundant since the initial and final readings were not taken using the same clock frequency. The number of clock ticks that occurred during this time will be accurate, but the elapsed time will be an unknown.

When not to use RDTSC

RDTSC is useful for basic timing. If you're timing multithreaded code on a single CPU machine, RDTSC will work fine. If you have multiple CPU's the startcount may come from one CPU and the endcount from another.

So don't use RDTSC to time multithreaded code on a multi-CPU machine. On a single CPU machine it works fine, or single threaded code on a multi-CPU machine it is also fine.

Also remember that RDTSC counts CPU cycles. If there is something that takes time but doesn't use the CPU, like disk-IO or network than RDTSC is not a good tool.

But the documentation says RDTSC is not accurate on modern CPU's

RDTSC is not a tool for keeping track of time, it's a tool for keeping track of CPU-cycles.

For that it is the only tool that is accurate. Routines that keep track of time are not accurate on modern CPU's because the CPU-clock is not absolute like it used to be.


问:
Downloading file through rest api spring boot and with multiple NULL
I have a rest controller which is downloading a CSV File from classpath.

```<code>@GetMapping("/template/download")
    public ResponseEntity<byte[]> downloadCsv() throws IOException {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set( HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=template.csv" );
        return ResponseEntity.status(HttpStatus.OK).headers(httpHeaders).body(csvUtil.downloadCsvTemplate());
    }
</code>```

Below is my downloadCsvTemplate() code

```<code>public byte[] downloadCsvTemplate() throws IOException {
        File resource = new ClassPathResource("templates/template.csv").getFile();
        return util.convertFileToByteArray(resource);
    }
</code>```

```<code>public byte[] convertFileToByteArray(File file) throws IOException {
        byte[] bytes = new byte[1024];

        try(FileInputStream fis = new FileInputStream(file);) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            for (int readNum; (readNum = fis.read(bytes)) != -1;) {
                bos.write(bytes, 0, readNum);
            }
        }

        return bytes;
    }
</code>```

When I try to hit the API I am able to download the file with content but I am getting some additional contents like below-

Any idea on how to get only the below content:

```<code>email,password,firstName
abc@abc.com,ABC@123,Test
</code>```

Appreciate the help.

答:
The reason why you are seeing raw data in the response is that CSV is nothing but a comma-delimited string. Try to add content-type.</p>

```<code>@GetMapping("/template/download")
public ResponseEntity<byte[]> downloadCsv() throws IOException {
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.set( HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=template.csv" );
    return ResponseEntity.status(HttpStatus.OK).contentType(MediaType.parseMediaType("text/csv")).headers(httpHeaders).body(csvUtil.downloadCsvTemplate());
}
</code>```

Body:
I have a rest controller which is downloading a CSV File from classpath.

@GetMapping("/template/download")
    public ResponseEntity<byte[]> downloadCsv() throws IOException {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set( HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=template.csv" );
        return ResponseEntity.status(HttpStatus.OK).headers(httpHeaders).body(csvUtil.downloadCsvTemplate());
    }

Below is my downloadCsvTemplate() code

public byte[] downloadCsvTemplate() throws IOException {
        File resource = new ClassPathResource("templates/template.csv").getFile();
        return util.convertFileToByteArray(resource);
    }

public byte[] convertFileToByteArray(File file) throws IOException {
        byte[] bytes = new byte[1024];

        try(FileInputStream fis = new FileInputStream(file);) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            for (int readNum; (readNum = fis.read(bytes)) != -1;) {
                bos.write(bytes, 0, readNum);
            }
        }

        return bytes;
    }

When I try to hit the API I am able to download the file with content but I am getting some additional contents like below-

Any idea on how to get only the below content:

email,password,firstName
abc@abc.com,ABC@123,Test

Appreciate the help.

Body:
The reason why you are seeing raw data in the response is that CSV is nothing but a comma-delimited string. Try to add content-type.

@GetMapping("/template/download")
public ResponseEntity<byte[]> downloadCsv() throws IOException {
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.set( HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=template.csv" );
    return ResponseEntity.status(HttpStatus.OK).contentType(MediaType.parseMediaType("text/csv")).headers(httpHeaders).body(csvUtil.downloadCsvTemplate());
}


问:
Map Discriminator Column to class Property Entity Framework Core 2.2.0
I am failing to generate Migration for Entity Framework Core (v. 2.2.0)

I have a class "Question" which is inherited by class "MultipleChoiceQuestion" & "MatchColumns". I am trying to build a TPH (Table per Hierarchy) inheritance using Entity Framework Core. My base class (Question) has a property "QuestionType" to distinguish between child classes. The "QuestionType" property is an Enum. I don't want EF to generate a Discriminator column but use the property "QuestionType" as Discriminator column.

To create a proper migration, I am using the following code in dbcontext class:

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Question>(b => b.HasDiscriminator(x => x.QuestionType).HasValue<MultipleChoiceQuestion>(QuestionType.MultipleChoiceQuestion).HasValue<MatchColumns>(QuestionType.MatchColumns));

    modelBuilder.Entity<Question>().Property(p => p.QuestionType).HasMaxLength(100).HasColumnName("QuestionType");
}
</code>```

But when I run "Add-Migration" I get the following error:

The entity type 'Question' is part of a hierarchy, but does not have a discriminator value configured.

Can't figure out why the configuring code is failing. I looked at the following documentation from Microsoft:
https://learn.microsoft.com/en-us/ef/core/modeling/inheritance#discriminator-configuration

Any pointers why the configuration is incomplete/breaking?

TIA.

答: Either Question should be abstract. Or it should be one of the possible record types, with a discriminator value.

Body:
I am failing to generate Migration for Entity Framework Core (v. 2.2.0)

I have a class "Question" which is inherited by class "MultipleChoiceQuestion" & "MatchColumns". I am trying to build a TPH (Table per Hierarchy) inheritance using Entity Framework Core. My base class (Question) has a property "QuestionType" to distinguish between child classes. The "QuestionType" property is an Enum. I don't want EF to generate a Discriminator column but use the property "QuestionType" as Discriminator column.

To create a proper migration, I am using the following code in dbcontext class:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Question>(b => b.HasDiscriminator(x => x.QuestionType).HasValue<MultipleChoiceQuestion>(QuestionType.MultipleChoiceQuestion).HasValue<MatchColumns>(QuestionType.MatchColumns));

    modelBuilder.Entity<Question>().Property(p => p.QuestionType).HasMaxLength(100).HasColumnName("QuestionType");
}

But when I run "Add-Migration" I get the following error:

The entity type 'Question' is part of a hierarchy, but does not have a discriminator value configured.

Can't figure out why the configuring code is failing. I looked at the following documentation from Microsoft:
https://learn.microsoft.com/en-us/ef/core/modeling/inheritance#discriminator-configuration

Any pointers why the configuration is incomplete/breaking?

TIA.


问:
Spring HATEOAS HalResourcesSerializer No default constructor found
I'm creating a Spring REST app using Spring Boot 2, Spring Data REST, Spring HATEOAS.

I created this controller:

```<code>@Api(tags = "City Entity")
@RepositoryRestController
@RequestMapping(path = "/api/v1")
@PreAuthorize("isAuthenticated()")
public class CityController {

    @Autowired
    private LocalValidatorFactoryBean validator;

    @Autowired
    private PagedBeanResourceAssembler<City> pagedBeanResourceAssembler;

    @Autowired
    private CityService cityService;

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.addValidators(validator);
    }

    @GetMapping(path = "/cities/search/autocomplete")
    public ResponseEntity<?> autocomplete(@RequestParam(name = "city") String city, @RequestParam(name = "country", required = false) String country, Pageable pageable, Locale locale) {
        return new ResponseEntity<>(pagedBeanResourceAssembler.toResource(cityService.autocomplete(city, country, pageable)), HttpStatus.OK);
    }

}
</code>```

The service method is:

```<code>@Transactional(readOnly = true)
    public Page<City> autocomplete(String text, String country, Pageable pageable) {
        //my logic
        return elasticSearchManager.search(ElasticSearchUtil.getIndexName(City.class), null, City.class, filters, null, pageable);
    }
</code>```

As you can see City bean is not stored in the DB. In fact the bean is:

```<code>public class City implements Persistable<Long> {

    private Long id;

    @NotBlank
    private String name;

    private String district;

    private String region;

    private String zipCode;

    @NotNull
    @Size(min = 2, max = 2)
    private String country;
}
</code>```

and finally this is my PagedBeanResourceAssembler:

```<code>@Component
public class PagedBeanResourceAssembler<T> implements ResourceAssembler<Page<T>, PagedResources<T>> {

    @Autowired
    private EntityLinks entityLinks;

    @Override
    public PagedResources<T> toResource(Page<T> page) {
        PagedResources<T> pagedResources = new PagedResources<T>(page.getContent(), asPageMetadata(page));
        return pagedResources;
    }

   private PagedResources.PageMetadata asPageMetadata(Page<?> page) {
        Assert.notNull(page, "Page must not be null!");
        return new PagedResources.PageMetadata(page.getSize(), page.getNumber(), page.getTotalElements(), page.getTotalPages());
    }
}
</code>```

When I make a http call I see a WARNING message in the console:

```<code>08/02/2019 11:09:35,526  WARN http-nio-8082-exec-1 RepositoryRestMvcConfiguration$ResourceSupportHttpMessageConverter:205 - Failed to evaluate Jackson serialization for type [class org.springframework.hateoas.PagedResources]: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.hateoas.hal.Jackson2HalModule$HalResourcesSerializer': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.hateoas.hal.Jackson2HalModule$HalResourcesSerializer]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.hateoas.hal.Jackson2HalModule$HalResourcesSerializer.<init>()
08/02/2019 11:09:35,527  WARN http-nio-8082-exec-1 MappingJackson2HttpMessageConverter:205 - Failed to evaluate Jackson serialization for type [class org.springframework.hateoas.PagedResources]: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.hateoas.hal.Jackson2HalModule$HalResourcesSerializer': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.hateoas.hal.Jackson2HalModule$HalResourcesSerializer]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.hateoas.hal.Jackson2HalModule$HalResourcesSerializer.<init>()
</code>```

Not using a PagedResources the error goes away. I don't understand where I'm doing something wrong. I got that HalResourcesSerializer has not a default constructor, but I don't use it directly and I don't understand either why with Entity persisted in the db a controller such this works fine.
How can I fix this problem continuing to use a PagedResource?

======== UPDATE ==========

I add my configuration to give a more detailed view:

CustomConfiguration:

```<code>@Configuration
@EnableRetry
@EnableTransactionManagement
@EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
public class CustomConfiguration {
    public static CustomConfiguration INSTANCE;

    @PostConstruct
    public void init() {
        INSTANCE = this;
    }

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean
    public static SpringSecurityAuditorAware springSecurityAuditorAware() {
        return new SpringSecurityAuditorAware();
    }

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasenames("classpath:/i18n/messages");
        // messageSource.setDefaultEncoding("UTF-8");
        // set to true only for debugging
        messageSource.setUseCodeAsDefaultMessage(false);
        messageSource.setCacheSeconds((int) TimeUnit.HOURS.toSeconds(1));
        messageSource.setFallbackToSystemLocale(false);
        return messageSource;
    }

    @Bean
    public MessageSourceAccessor messageSourceAccessor() {
        return new MessageSourceAccessor(messageSource());
    }

    /**
     * Enable Spring bean validation https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#validation
     *
     * @return
     */
    @Bean
    public LocalValidatorFactoryBean validator() {
        LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
        factoryBean.setValidationMessageSource(messageSource());
        return factoryBean;
    }

    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
        methodValidationPostProcessor.setValidator(validator());
        return methodValidationPostProcessor;
    }

    /**
     * Utility class from Google to work with phone numbers {@link https://github.com/googlei18n/libphonenumber}
     *
     * @return
     */
    @Bean
    public PhoneNumberUtil phoneNumberUtil() {
        return PhoneNumberUtil.getInstance();
    }

    /**
     * To enable SpEL expressions
     *
     * @return
     */
    @Bean
    public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
        return new SecurityEvaluationContextExtension();
    }

    /**
     * Define the specific storage manager to use (disk, S3, etc)
     *
     * @return
     */
    @Bean
    public StorageManager storageManager() {
        return new S3StorageManager();
    }

    /**
     * GRACEFUL SHUTDOWN
     */
    @Bean
    public GracefulShutdown gracefulShutdown() {
        return new GracefulShutdown();
    }

    @Bean
    public ConfigurableServletWebServerFactory webServerFactory(final GracefulShutdown gracefulShutdown) {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
        factory.addConnectorCustomizers(gracefulShutdown);
        return factory;
    }

}
</code>```

GlobalRepositoryRestConfigurer:

```<code>@Configuration
public class GlobalRepositoryRestConfigurer implements RepositoryRestConfigurer {
    private Logger log = LogManager.getLogger();

    @Autowired(required = false)
    private Jackson2ObjectMapperBuilder objectMapperBuilder;

    @Autowired
    private Validator validator;

    @Value("${cors.mapping}")
    private String corsMapping;

    @Value("#{'${cors.allowed.headers}'.split(',')}")
    private String[] corsAllowedHeaders;

    @Value("#{'${cors.exposed.headers}'.split(',')}")
    private String[] corsExposedHeaders;

    @Value("#{'${cors.allowed.methods}'.split(',')}")
    private String[] corsAllowedMethod;

    @Value("#{'${cors.allowed.origins}'.split(',')}")
    private String[] corsAllowedOrigins;

    @Value("${cors.max.age}")
    private int corsMaxAge;

    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
        config.getCorsRegistry().addMapping(corsMapping).exposedHeaders(corsExposedHeaders).allowedOrigins(corsAllowedOrigins)
                .allowedHeaders(corsAllowedHeaders).allowedMethods(corsAllowedMethod).maxAge(corsMaxAge);

    }

    @Override
    public void configureConversionService(ConfigurableConversionService conversionService) {

    }

    /**
     * ValidationException serialiazer
     *
     * @return
     */
    @Bean
    public ValidationExceptionSerializer validationExceptionSerializer() {
        return new ValidationExceptionSerializer();
    }

    @Bean
    public CustomValidationExceptionSerializer customValidationExceptionSerializer() {
        return new CustomValidationExceptionSerializer();
    }

    @Bean
    public ConstraintViolationExceptionSerializer constraintViolationExceptionSerializer() {
        return new ConstraintViolationExceptionSerializer();
    }

    /**
     * Customize Object Mapper
     */
    @Override
    public void configureJacksonObjectMapper(ObjectMapper objectMapper) {
        if (this.objectMapperBuilder != null) {
            /**
             * Custom serializer for ConstraintViolationException
             * (https://jira.spring.io/browse/DATAREST-593)
             */
            try {
                SimpleModule constraintExceptionModule = new SimpleModule();
                constraintExceptionModule.addSerializer(ConstraintViolationException.class, constraintViolationExceptionSerializer());

                constraintExceptionModule.addSerializer(ValidationException.class, validationExceptionSerializer());
                constraintExceptionModule.addSerializer(cloud.optix.server.exceptions.ValidationException.class, customValidationExceptionSerializer());
                objectMapper.registerModule(constraintExceptionModule);
                this.objectMapperBuilder.configure(objectMapper);
            } catch (Exception e) {
                log.error("", e);
            }
        }
    }

    @Override
    public void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener validatingListener) {
        validatingListener.addValidator("beforeCreate", validator);
        validatingListener.addValidator("beforeSave", validator);
    }

    @Override
    public void configureExceptionHandlerExceptionResolver(ExceptionHandlerExceptionResolver exceptionResolver) {

    }

    /**
     * Adding converter to donwload files in{@link org.springframework.web.bind.annotation.RestController}
     *
     * @param messageConverters
     */
    @Override
    public void configureHttpMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
        // super.configureHttpMessageConverters(messageConverters);
        messageConverters.add(new ResourceHttpMessageConverter());
    }
}
</code>```

WebMvcConfiguration:

```<code>@Configuration
// Enable entity links for Spring HATEOAS
@EnableHypermediaSupport(type = {HypermediaType.HAL})
public class WebMvcConfiguration implements WebMvcConfigurer {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private TenantRestClient tenantRestClient;

    @Value("${cors.mapping}")
    private String corsMapping;

    @Value("#{'${cors.allowed.headers}'.split(',')}")
    private String[] corsAllowedHeaders;

    @Value("#{'${cors.exposed.headers}'.split(',')}")
    private String[] corsExposedHeaders;

    @Value("#{'${cors.allowed.methods}'.split(',')}")
    private String[] corsAllowedMethod;

    @Value("#{'${cors.allowed.origins}'.split(',')}")
    private String[] corsAllowedOrigins;

    @Value("${cors.max.age}")
    private int corsMaxAge;

    @Autowired
    public WebMvcConfiguration() {
    }

    @Bean
    public LocaleResolver localeResolver() {
        return new SmartLocaleResolver();
    }

    public class SmartLocaleResolver extends CookieLocaleResolver {
        @Override
        public Locale resolveLocale(HttpServletRequest request) {
            String acceptLanguage = request.getHeader("Accept-Language");
            if (acceptLanguage == null || acceptLanguage.trim().isEmpty()) {
                return super.determineDefaultLocale(request);
            }
            return request.getLocale();
        }
    }

    /**
     * Custom exception in WEB MVC
     *
     * @return
     */
    @Bean
    public CustomErrorAttributes myCustomErrorAttributes() {
        return new CustomErrorAttributes();
    }

    /**
     * Global CORS security configuration
     *
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping(corsMapping).exposedHeaders(corsExposedHeaders).allowedOrigins(corsAllowedOrigins).allowedHeaders(corsAllowedHeaders)
                .allowedMethods(corsAllowedMethod).maxAge(corsMaxAge);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new TenantInterceptor());
    }

}
</code>```

答:
You will get same error when you use RepresentationModelAssembler<Object, PersistentEntityResource> resourceAssembler as parameter to your controller method. When you use PersistentEntityResourceAssembler resourceAssembler, spring will create right instance for you.

I suggest you to try to examine class hierarchy of PagedBeanResourceAssembler class and find some more specific class/implementation.

Body:
I'm creating a Spring REST app using Spring Boot 2, Spring Data REST, Spring HATEOAS.

I created this controller:

@Api(tags = "City Entity")
@RepositoryRestController
@RequestMapping(path = "/api/v1")
@PreAuthorize("isAuthenticated()")
public class CityController {

    @Autowired
    private LocalValidatorFactoryBean validator;

    @Autowired
    private PagedBeanResourceAssembler<City> pagedBeanResourceAssembler;

    @Autowired
    private CityService cityService;

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.addValidators(validator);
    }

    @GetMapping(path = "/cities/search/autocomplete")
    public ResponseEntity<?> autocomplete(@RequestParam(name = "city") String city, @RequestParam(name = "country", required = false) String country, Pageable pageable, Locale locale) {
        return new ResponseEntity<>(pagedBeanResourceAssembler.toResource(cityService.autocomplete(city, country, pageable)), HttpStatus.OK);
    }

}

The service method is:

@Transactional(readOnly = true)
    public Page<City> autocomplete(String text, String country, Pageable pageable) {
        //my logic
        return elasticSearchManager.search(ElasticSearchUtil.getIndexName(City.class), null, City.class, filters, null, pageable);
    }

As you can see City bean is not stored in the DB. In fact the bean is:

public class City implements Persistable<Long> {

    private Long id;

    @NotBlank
    private String name;

    private String district;

    private String region;

    private String zipCode;

    @NotNull
    @Size(min = 2, max = 2)
    private String country;
}

and finally this is my PagedBeanResourceAssembler:

@Component
public class PagedBeanResourceAssembler<T> implements ResourceAssembler<Page<T>, PagedResources<T>> {

    @Autowired
    private EntityLinks entityLinks;

    @Override
    public PagedResources<T> toResource(Page<T> page) {
        PagedResources<T> pagedResources = new PagedResources<T>(page.getContent(), asPageMetadata(page));
        return pagedResources;
    }

   private PagedResources.PageMetadata asPageMetadata(Page<?> page) {
        Assert.notNull(page, "Page must not be null!");
        return new PagedResources.PageMetadata(page.getSize(), page.getNumber(), page.getTotalElements(), page.getTotalPages());
    }
}

When I make a http call I see a WARNING message in the console:

08/02/2019 11:09:35,526  WARN http-nio-8082-exec-1 RepositoryRestMvcConfiguration$ResourceSupportHttpMessageConverter:205 - Failed to evaluate Jackson serialization for type [class org.springframework.hateoas.PagedResources]: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.hateoas.hal.Jackson2HalModule$HalResourcesSerializer': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.hateoas.hal.Jackson2HalModule$HalResourcesSerializer]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.hateoas.hal.Jackson2HalModule$HalResourcesSerializer.<init>()
08/02/2019 11:09:35,527  WARN http-nio-8082-exec-1 MappingJackson2HttpMessageConverter:205 - Failed to evaluate Jackson serialization for type [class org.springframework.hateoas.PagedResources]: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.hateoas.hal.Jackson2HalModule$HalResourcesSerializer': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.hateoas.hal.Jackson2HalModule$HalResourcesSerializer]: No default constructor found; nested exception is java.lang.NoSuchMethodException: org.springframework.hateoas.hal.Jackson2HalModule$HalResourcesSerializer.<init>()

Not using a PagedResources the error goes away. I don't understand where I'm doing something wrong. I got that HalResourcesSerializer has not a default constructor, but I don't use it directly and I don't understand either why with Entity persisted in the db a controller such this works fine.
How can I fix this problem continuing to use a PagedResource?

======== UPDATE ==========

I add my configuration to give a more detailed view:

CustomConfiguration:

@Configuration
@EnableRetry
@EnableTransactionManagement
@EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
public class CustomConfiguration {
    public static CustomConfiguration INSTANCE;

    @PostConstruct
    public void init() {
        INSTANCE = this;
    }

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Bean
    public static SpringSecurityAuditorAware springSecurityAuditorAware() {
        return new SpringSecurityAuditorAware();
    }

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasenames("classpath:/i18n/messages");
        // messageSource.setDefaultEncoding("UTF-8");
        // set to true only for debugging
        messageSource.setUseCodeAsDefaultMessage(false);
        messageSource.setCacheSeconds((int) TimeUnit.HOURS.toSeconds(1));
        messageSource.setFallbackToSystemLocale(false);
        return messageSource;
    }

    @Bean
    public MessageSourceAccessor messageSourceAccessor() {
        return new MessageSourceAccessor(messageSource());
    }

    /**
     * Enable Spring bean validation https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#validation
     *
     * @return
     */
    @Bean
    public LocalValidatorFactoryBean validator() {
        LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
        factoryBean.setValidationMessageSource(messageSource());
        return factoryBean;
    }

    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        MethodValidationPostProcessor methodValidationPostProcessor = new MethodValidationPostProcessor();
        methodValidationPostProcessor.setValidator(validator());
        return methodValidationPostProcessor;
    }

    /**
     * Utility class from Google to work with phone numbers {@link https://github.com/googlei18n/libphonenumber}
     *
     * @return
     */
    @Bean
    public PhoneNumberUtil phoneNumberUtil() {
        return PhoneNumberUtil.getInstance();
    }

    /**
     * To enable SpEL expressions
     *
     * @return
     */
    @Bean
    public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
        return new SecurityEvaluationContextExtension();
    }

    /**
     * Define the specific storage manager to use (disk, S3, etc)
     *
     * @return
     */
    @Bean
    public StorageManager storageManager() {
        return new S3StorageManager();
    }

    /**
     * GRACEFUL SHUTDOWN
     */
    @Bean
    public GracefulShutdown gracefulShutdown() {
        return new GracefulShutdown();
    }

    @Bean
    public ConfigurableServletWebServerFactory webServerFactory(final GracefulShutdown gracefulShutdown) {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
        factory.addConnectorCustomizers(gracefulShutdown);
        return factory;
    }

}

GlobalRepositoryRestConfigurer:

@Configuration
public class GlobalRepositoryRestConfigurer implements RepositoryRestConfigurer {
    private Logger log = LogManager.getLogger();

    @Autowired(required = false)
    private Jackson2ObjectMapperBuilder objectMapperBuilder;

    @Autowired
    private Validator validator;

    @Value("${cors.mapping}")
    private String corsMapping;

    @Value("#{'${cors.allowed.headers}'.split(',')}")
    private String[] corsAllowedHeaders;

    @Value("#{'${cors.exposed.headers}'.split(',')}")
    private String[] corsExposedHeaders;

    @Value("#{'${cors.allowed.methods}'.split(',')}")
    private String[] corsAllowedMethod;

    @Value("#{'${cors.allowed.origins}'.split(',')}")
    private String[] corsAllowedOrigins;

    @Value("${cors.max.age}")
    private int corsMaxAge;

    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
        config.getCorsRegistry().addMapping(corsMapping).exposedHeaders(corsExposedHeaders).allowedOrigins(corsAllowedOrigins)
                .allowedHeaders(corsAllowedHeaders).allowedMethods(corsAllowedMethod).maxAge(corsMaxAge);

    }

    @Override
    public void configureConversionService(ConfigurableConversionService conversionService) {

    }

    /**
     * ValidationException serialiazer
     *
     * @return
     */
    @Bean
    public ValidationExceptionSerializer validationExceptionSerializer() {
        return new ValidationExceptionSerializer();
    }

    @Bean
    public CustomValidationExceptionSerializer customValidationExceptionSerializer() {
        return new CustomValidationExceptionSerializer();
    }

    @Bean
    public ConstraintViolationExceptionSerializer constraintViolationExceptionSerializer() {
        return new ConstraintViolationExceptionSerializer();
    }

    /**
     * Customize Object Mapper
     */
    @Override
    public void configureJacksonObjectMapper(ObjectMapper objectMapper) {
        if (this.objectMapperBuilder != null) {
            /**
             * Custom serializer for ConstraintViolationException
             * (https://jira.spring.io/browse/DATAREST-593)
             */
            try {
                SimpleModule constraintExceptionModule = new SimpleModule();
                constraintExceptionModule.addSerializer(ConstraintViolationException.class, constraintViolationExceptionSerializer());

                constraintExceptionModule.addSerializer(ValidationException.class, validationExceptionSerializer());
                constraintExceptionModule.addSerializer(cloud.optix.server.exceptions.ValidationException.class, customValidationExceptionSerializer());
                objectMapper.registerModule(constraintExceptionModule);
                this.objectMapperBuilder.configure(objectMapper);
            } catch (Exception e) {
                log.error("", e);
            }
        }
    }

    @Override
    public void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener validatingListener) {
        validatingListener.addValidator("beforeCreate", validator);
        validatingListener.addValidator("beforeSave", validator);
    }

    @Override
    public void configureExceptionHandlerExceptionResolver(ExceptionHandlerExceptionResolver exceptionResolver) {

    }

    /**
     * Adding converter to donwload files in{@link org.springframework.web.bind.annotation.RestController}
     *
     * @param messageConverters
     */
    @Override
    public void configureHttpMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
        // super.configureHttpMessageConverters(messageConverters);
        messageConverters.add(new ResourceHttpMessageConverter());
    }
}

WebMvcConfiguration:

@Configuration
// Enable entity links for Spring HATEOAS
@EnableHypermediaSupport(type = {HypermediaType.HAL})
public class WebMvcConfiguration implements WebMvcConfigurer {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private TenantRestClient tenantRestClient;

    @Value("${cors.mapping}")
    private String corsMapping;

    @Value("#{'${cors.allowed.headers}'.split(',')}")
    private String[] corsAllowedHeaders;

    @Value("#{'${cors.exposed.headers}'.split(',')}")
    private String[] corsExposedHeaders;

    @Value("#{'${cors.allowed.methods}'.split(',')}")
    private String[] corsAllowedMethod;

    @Value("#{'${cors.allowed.origins}'.split(',')}")
    private String[] corsAllowedOrigins;

    @Value("${cors.max.age}")
    private int corsMaxAge;

    @Autowired
    public WebMvcConfiguration() {
    }

    @Bean
    public LocaleResolver localeResolver() {
        return new SmartLocaleResolver();
    }

    public class SmartLocaleResolver extends CookieLocaleResolver {
        @Override
        public Locale resolveLocale(HttpServletRequest request) {
            String acceptLanguage = request.getHeader("Accept-Language");
            if (acceptLanguage == null || acceptLanguage.trim().isEmpty()) {
                return super.determineDefaultLocale(request);
            }
            return request.getLocale();
        }
    }

    /**
     * Custom exception in WEB MVC
     *
     * @return
     */
    @Bean
    public CustomErrorAttributes myCustomErrorAttributes() {
        return new CustomErrorAttributes();
    }

    /**
     * Global CORS security configuration
     *
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping(corsMapping).exposedHeaders(corsExposedHeaders).allowedOrigins(corsAllowedOrigins).allowedHeaders(corsAllowedHeaders)
                .allowedMethods(corsAllowedMethod).maxAge(corsMaxAge);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new TenantInterceptor());
    }

}


问:
How to set shadow border of a custom button?
I am a newvie in qt.I made a hexagon shape button through paint now i have to set its border which reflecting shadow view.
I tried it with drawing lines on the surrounding the button but it is not reflect shadow view.If the pen style can set to groove then it is possible to draw the lines with groove style than my purpose will solve.
Any suggestion is highly appriciated.
Thanks in advance.</p>

答:
For simple styling of UI elements look at

QML/QtQuick http://doc.qt.nokia.com/4.7/qtquick.html

and Qt Stylesheets http://doc.qt.nokia.com/latest/stylesheet.html.

Coming back to your question, Assuming you are drawing by overloading the PaintEvent function , have you looked at QPainter::setPen(Qt::PenStyle) http://doc.qt.nokia.com/latest/qpainter.html#setPen-3

```<code>QPainter painter;
painter.setPen(Qt::DashLine);
</code>```

It is also possible to define a custom pen style using Qt::CustomDashLine

Body:
For simple styling of UI elements look at

QML/QtQuick http://doc.qt.nokia.com/4.7/qtquick.html

and Qt Stylesheets http://doc.qt.nokia.com/latest/stylesheet.html.

Coming back to your question, Assuming you are drawing by overloading the PaintEvent function , have you looked at QPainter::setPen(Qt::PenStyle) http://doc.qt.nokia.com/latest/qpainter.html#setPen-3

QPainter painter;
painter.setPen(Qt::DashLine);

It is also possible to define a custom pen style using Qt::CustomDashLine


问:
How to migrate from SQLite database to Room about "String" field?
I am trying to migrate a database from SQLite to Room in Android.

But I got an error:

Migration didn't properly handle:
  staff_message(db.entity.StaffMessage).
       Expected:
      TableInfo{message=Column{name='message', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0,
  defaultValue='null'}}
       Found:
      TableInfo{message=Column{name='message', type='String', affinity='1', notNull=true, primaryKeyPosition=0,
  defaultValue='null'}}

Origin table was written like:

```<code>db.execSQL("CREATE TABLE IF NOT EXISTS staff_message( " +
                    "message String NOT NULL");");
</code>```

And new table scheme is like:

```<code>@Entity(tableName = "staff_message")
data class StaffMessage(
        @ColumnInfo(name = "message") val message: String
)
</code>```

The only difference is the type.

String VS. TEXT

How can I migrate this table to the Room?

答:
There is no data type in SQLite like String. You have to use TEXT

```<code>db.execSQL("CREATE TABLE IF NOT EXISTS staff_message( " + "message TEXT NOT NULL");");
</code>```

Body:
I am trying to migrate a database from SQLite to Room in Android.

But I got an error:

Migration didn't properly handle:
  staff_message(db.entity.StaffMessage).
       Expected:
      TableInfo{message=Column{name='message', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0,
  defaultValue='null'}}
       Found:
      TableInfo{message=Column{name='message', type='String', affinity='1', notNull=true, primaryKeyPosition=0,
  defaultValue='null'}}

Origin table was written like:

db.execSQL("CREATE TABLE IF NOT EXISTS staff_message( " +
                    "message String NOT NULL");");

And new table scheme is like:

@Entity(tableName = "staff_message")
data class StaffMessage(
        @ColumnInfo(name = "message") val message: String
)

The only difference is the type.

String VS. TEXT

How can I migrate this table to the Room?

Body:
There is no data type in SQLite like String. You have to use TEXT

db.execSQL("CREATE TABLE IF NOT EXISTS staff_message( " + "message TEXT NOT NULL");");