问:
How to order a matrix of object
I'm working on an application that read a file Excel with Apache POI. I put the cells value inside a matrix of String object.

```<code>[title 1][title 2][title 3]
[mark]   [smith]  [34]
[simon]  [black]  [24]
</code>```

I've been ask to allow to order the matrix according to the selected column.
How can I order a matrix of String object?

Thank you

答:
If you have only few columns you can create some comparators with a meaningful name and sort like below:

```<code>    public static void main(String[] args) {
    String[][] matrix = {{"mark","smith","34"},
                         {"simon","black","24"},
                         {"foo","bar","44"}
                        };

    Comparator<String[]> firstNameComparator  = new Comparator<String[]>() {
        @Override
        public int compare(String[] row1, String[] row2) {
            return row1[0].compareTo(row2[0]);
        }
    };
    Comparator<String[]> lastNameComparator  = new Comparator<String[]>() {
        @Override
        public int compare(String[] row1, String[] row2) {
            return row1[1].compareTo(row2[1]);
        }
    };
    Comparator<String[]> ageComparator  = new Comparator<String[]>() {
        @Override
        public int compare(String[] row1, String[] row2) {
            return Integer.compare(Integer.parseInt(row1[2]), Integer.parseInt(row2[2]));
        }
    };
    Arrays.sort(matrix, firstNameComparator);// pass the desired comparator
    for(String[] row:matrix){
        System.out.println(Arrays.toString(row));
    }
}
</code>```

or create a class that extends Comparator and pass the column index:

```<code>public class NewClass5 {
    public static void main(String[] args) {
        String[][] matrix = {{"mark","smith","34"},
                             {"simon","black","24"},
                             {"foo","bar","44"}
                            };

        Arrays.sort(matrix, new CompareByColumn(1));// pass the desired index
        for(String[] row:matrix){
            System.out.println(Arrays.toString(row));
        }
    }
    static class CompareByColumn implements Comparator {
        int columnToSort;
        CompareByColumn(int columnToSort) {
            this.columnToSort = columnToSort;
        }
        public int compare(Object o1, Object o2) {
                String[] row1 = (String[]) o1;
                String[] row2 = (String[]) o2;
                return row1[columnToSort].compareTo(row2[columnToSort]);
        }
    }
}
</code>```

With java 8 and streams you can write it even more compactly:

```<code>String[][] sorted = Arrays.stream(matrix)
                          .sorted((s1,s2)->s1[1].compareTo(s2[1])) // pass the desired index
                          .toArray(String[][]::new);
for(String[] row: sorted){
    System.out.println(Arrays.toString(row));
}
</code>```

EDIT

Since you prefer the stream approach, I have only reworked this one. But you can use it for the other approaches as well. You can check before the comparison if the corresponding column contains numbers and make your comparison in a simple if-else either for numbers or strings.

```<code>    int colIndex  = 2;
    String[][] sorted = Arrays.stream(matrix).sorted((s1,s2)-> {
                            if(s1[colIndex].matches("(\\d+(?:\\.\\d+)?)")){
                                return Double.compare(Double.parseDouble(s1[colIndex]), Double.parseDouble(s2[colIndex]));
                            }
                            else{
                                return s1[2].compareTo(s2[2]);
                            }})
                      .toArray(String[][]::new);

    for(String[] row: sorted){
        System.out.println(Arrays.toString(row));
    }
</code>```

Used this (\d+(?:\.\d+)?) regex to match both integer and floating point numbers.

Title: How to order a matrix of object

Body:
I'm working on an application that read a file Excel with Apache POI. I put the cells value inside a matrix of String object.

[title 1][title 2][title 3]
[mark]   [smith]  [34]
[simon]  [black]  [24]

I've been ask to allow to order the matrix according to the selected column.
How can I order a matrix of String object?

Thank you

Body:
If you have only few columns you can create some comparators with a meaningful name and sort like below:

    public static void main(String[] args) {
    String[][] matrix = {{"mark","smith","34"},
                         {"simon","black","24"},
                         {"foo","bar","44"}
                        };

    Comparator<String[]> firstNameComparator  = new Comparator<String[]>() {
        @Override
        public int compare(String[] row1, String[] row2) {
            return row1[0].compareTo(row2[0]);
        }
    };
    Comparator<String[]> lastNameComparator  = new Comparator<String[]>() {
        @Override
        public int compare(String[] row1, String[] row2) {
            return row1[1].compareTo(row2[1]);
        }
    };
    Comparator<String[]> ageComparator  = new Comparator<String[]>() {
        @Override
        public int compare(String[] row1, String[] row2) {
            return Integer.compare(Integer.parseInt(row1[2]), Integer.parseInt(row2[2]));
        }
    };
    Arrays.sort(matrix, firstNameComparator);// pass the desired comparator
    for(String[] row:matrix){
        System.out.println(Arrays.toString(row));
    }
}

or create a class that extends Comparator and pass the column index:

public class NewClass5 {
    public static void main(String[] args) {
        String[][] matrix = {{"mark","smith","34"},
                             {"simon","black","24"},
                             {"foo","bar","44"}
                            };

        Arrays.sort(matrix, new CompareByColumn(1));// pass the desired index
        for(String[] row:matrix){
            System.out.println(Arrays.toString(row));
        }
    }
    static class CompareByColumn implements Comparator {
        int columnToSort;
        CompareByColumn(int columnToSort) {
            this.columnToSort = columnToSort;
        }
        public int compare(Object o1, Object o2) {
                String[] row1 = (String[]) o1;
                String[] row2 = (String[]) o2;
                return row1[columnToSort].compareTo(row2[columnToSort]);
        }
    }
}

With java 8 and streams you can write it even more compactly:

String[][] sorted = Arrays.stream(matrix)
                          .sorted((s1,s2)->s1[1].compareTo(s2[1])) // pass the desired index
                          .toArray(String[][]::new);
for(String[] row: sorted){
    System.out.println(Arrays.toString(row));
}

EDIT

Since you prefer the stream approach, I have only reworked this one. But you can use it for the other approaches as well. You can check before the comparison if the corresponding column contains numbers and make your comparison in a simple if-else either for numbers or strings.

    int colIndex  = 2;
    String[][] sorted = Arrays.stream(matrix).sorted((s1,s2)-> {
                            if(s1[colIndex].matches("(\\d+(?:\\.\\d+)?)")){
                                return Double.compare(Double.parseDouble(s1[colIndex]), Double.parseDouble(s2[colIndex]));
                            }
                            else{
                                return s1[2].compareTo(s2[2]);
                            }})
                      .toArray(String[][]::new);

    for(String[] row: sorted){
        System.out.println(Arrays.toString(row));
    }

Used this (\d+(?:\.\d+)?) regex to match both integer and floating point numbers.


来源: stackexchange

问:
AVRO, convert record to array
My AVRO schema has a fileObject record but I need to change this to be an array of fileObject.  How can I do this?

```<code>        {
            "name": "file",
            "type": ["null", {
                "type": "record",
                "name": "FileObject",
                "doc": "file object",
                "fields": [{
                        "name": "fileUrl",
                        "type": ["null", "string"],
                        "doc": "url of the file"
                    },
                    {
                        "name": "spId",
                        "type": ["null", "string"],
                        "doc": "space id"
                    },
                    {
                        "name": "contentId",
                        "type": ["null", "string"],
                        "doc": "content id of the file"
                    },
                    {
                        "name": "versionId",
                        "type": ["null", "string"],
                        "doc": "version id of the file"
                    }
                ]
            }]
        },
</code>```

答:
I got this to work</p>

```<code>    {
        "name": "files",
        "type": {
            "type": "array",
            "items":{
                "name": "FileObjects",
                "type": "record",
                "fields":[{
                    "name": "fileUrl",
                    "type": ["null", "string"],
                    "doc": "url of the file"
                },
                {
                    "name": "sId",
                    "type": ["null", "string"],
                    "doc": "sid of the file"
                },
                {
                    "name": "contentId",
                    "type": ["null", "string"],
                    "doc": "content id of the file"
                },
                {
                    "name": "versionId",
                    "type": ["null", "string"],
                    "doc": "version id of the file"
                }]
            }
        },
        "default": []
    }
</code>```

ContentLicense: CC BY-SA 4.0

Title: AVRO, convert record to array

Body:
My AVRO schema has a fileObject record but I need to change this to be an array of fileObject.  How can I do this?

        {
            "name": "file",
            "type": ["null", {
                "type": "record",
                "name": "FileObject",
                "doc": "file object",
                "fields": [{
                        "name": "fileUrl",
                        "type": ["null", "string"],
                        "doc": "url of the file"
                    },
                    {
                        "name": "spId",
                        "type": ["null", "string"],
                        "doc": "space id"
                    },
                    {
                        "name": "contentId",
                        "type": ["null", "string"],
                        "doc": "content id of the file"
                    },
                    {
                        "name": "versionId",
                        "type": ["null", "string"],
                        "doc": "version id of the file"
                    }
                ]
            }]
        },

Body:
I got this to work

    {
        "name": "files",
        "type": {
            "type": "array",
            "items":{
                "name": "FileObjects",
                "type": "record",
                "fields":[{
                    "name": "fileUrl",
                    "type": ["null", "string"],
                    "doc": "url of the file"
                },
                {
                    "name": "sId",
                    "type": ["null", "string"],
                    "doc": "sid of the file"
                },
                {
                    "name": "contentId",
                    "type": ["null", "string"],
                    "doc": "content id of the file"
                },
                {
                    "name": "versionId",
                    "type": ["null", "string"],
                    "doc": "version id of the file"
                }]
            }
        },
        "default": []
    }


问:
How to set blob url in image source
I get a binary file back from the server and would like to show it in the frontend. I convert my binary file to a blob and use the DOM Sanitizer to create a save URL.

The problem is that the image is not found when I used the blob URL for the image source:

Typescript:

const blob = new Blob([response], { type: 'application/octet-stream' });

const fileData = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob));
```

<p><strong>HTML:</strong></p>

<pre class="lang-html prettyprint-override"><code>   <img [src]="fileData">
</code>```

Response from Server

```<code>�PNG

IHDR��91tHiCCPICC ProfileH��WXS��[RIh�H ��R�K   �E�*�I �ĘD�ʢ�k���"��;��(v��P��u�`C�M
����������ϙs�S2��t�yRi.�@�$_����"u`���ǗK�qq���������r�E����=�P���8C ��A|��/��@�z�i�R%���&�T��ԸX�3ԸBe�ρxd�'�@�   �Y�,ȣ}bW�@,@�q _�@  )J�C�7<Y����������C�ri.o��َ�-y���vp�D��xeͰowr�D)1
�nIFL,���T��T�"2Im�����3���U�����pInL�F��)�BWZ(��&j|    �a  �jٔ���)�5��<�*����"'���#r���S�9c�qr��3�9    Qj̦Hĉ��)���@�'�D����I���x��,O>P/�H$��hpe�(1Ró��S�oq�P�N���E�"���kǮ
%I�z�vi~H����47Nc�S��J�Ħ��/�������%���3�y����� p@(``
�����n�K=x@���h4)�  �&�"�DB �Q�
A�Ԫ�. S5[���O �Q �V��$�ђ�P#�!:��r�Gj�5�/Kg��F%FÉ��  ������;��d�՞��FxL�Ih'ܝ,�/���a�pM��֌�AVO<���g�&� #�� �j9�̕������Ǝ�JA)C(���=���=Y�=��C�\3����>>�N�=�{Kl�;���.`G�F�cM�e���?T�h Z�*��#�!OS�I�k�k��'�\��P�~�)��2q�(�ņo~!�+��rwu�@�Q��^3U��y�n�������j`��_u�����$��
Y�Z�+/@:�2��8�z܁�� �� ��I��"��e`�   �P��5�l[�����8  ΂K�*�   ����    ����!BB�1F,[�qG|�@$�F�T$�B$���,@ʐ�H%��E~E!'�Hry�t!���(��P��CG�>(�Bщh:-B�ѥhZ��BГ�%�&ڎ>G{1�iaL�s�|0��a�����b�X
V�5���:֎ucp"��Y�\��x�ǧ��%x%�o�O���Gx��@'��  ~.a!�0�PB('l#$��OS'�-�Hd���iL%fg���Oۈ�^�dLr&�bI<R>������t�t��IzO�"[�����4��<�\N�I>F�F~J��Rl)~�X��2������L�B��Q����j"5�:�ZA����ާ���Ҳ����%֚�U��W��#�4}��C�@SЖҶ�N���^��t;z0=��O_J����?���fh��j��hWi7h_�~�Cѱ�a�L�)�)�ٯsE�[��k������֭�=�{[�W�������Do���g�$};�0}�~���S��a��0�����3�N���� ۠�`�A�A����H�d�B�*ã��L�i��2s�˘������
aY<�~ȵ!    �J���4�h�23�1^a�h��7q2k2�d����C����7�wS���4�t���˦�f�ffR�uf�̺͙������wY0,-��-�[��2d�Y��
�iV���e���r�e�e���U��|�=V���>֙֫�[�{l,l��̴���ݖb�c+�]k{�����]��B�F�g�F�\�"�:��t� ��57��>�9���:�N�N"�*�+Ψ����y�s�0�0�a�a5�n��\�..u.��3�G�?�q��6#�F�qn�WO�\׭�����F��wkv{����w�r��A�������r��H��
#�x2<�x.�l�����%�����N�����c����/�7�w���~^~�~����w������l��(ᨭ�:�x��Y�遛ۃ,�xA5A�����ۂ�����]�!�!���!�8~�Y��XhDhihk�~XRXe��p����ψ'" �Q�+"os͸|n-�g���Y�OGѢ�*�G;Eˢ�ǠcF�Y5�~�m�$�1�rcW�>����wx,ql�ت�O���gƟK`$LNؙ�61$qY�$�$ERK�N����w)�)+S�Ǎ7kܥT�TqjS)-9m[Z����k�wN�P2��D���/L2��;��d�ɼ���  �)�;�?�by5��nFuF��_�.�t �+�O32Wf>�
�Z��%
����q��evd���w9�9�s�sSr�����I�%9��ŞNi�:KK��S�����#��m�#��|�a��pP��xTXPU�~Z���z����ӝ�/���(��������3��|4�=k�ldv��9�s��t΍��cu^μ���_9�͂���f�s�;~����D�DVr{����E�E��=�[��TPz�̵�������?��\�s��̥�˼�mXN\.Y~kEЊ+�V��X5fU�j����o�L^s�|d�ƵԵ����M�l�-_��RTy�*�jO�i���w��m�P��lc�Ə�ě�l���PcWS����`˓��[����K�6�me�>o�lo���t�wm�Nӝ���:E]׮ �����T�R�ysO�^�W���_���/j_�~���lTd,m@�7�4�ۛR���>����|����ۏX�:jxt�1��c�ǋ������>�u��er˽S�N�8=�t뙨3�φ�=u�}�����G.�]8t��b�%�K
�=/��^�
W��4]����6��ص�k'��^?{�{��͘�m��nݹ=�v���gws������{s��>�}P���aͿ���ݫ���G�'<����x����O��O�OʟZ<�}���HWx��?����\�����/���_8�8�w�ߗ{��t���������oF�i��}�6�m߻����w|��p�c�ǧ}�>�>U|v���%������~)O�Sm08��L^m��
�*�?�W��T��Ϧ*�V�U�@=�)����.rûr��P���y�����O<������ ���gY�����[a�w81U}�T
�
6+�M#�\������ꯈ  pHYs%%IR$��iTXtXML:com.adobe.xmp<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="XMP Core 5.4.0">
   <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
      <rdf:Description rdf:about=""
            xmlns:exif="http://ns.adobe.com/exif/1.0/">
         <exif:PixelXDimension>202</exif:PixelXDimension>
         <exif:PixelYDimension>188</exif:PixelYDimension>
      </rdf:Description>
   </rdf:RDF>
</x:xmpmeta>
M�uiDOT^(^^lKgf8IDATx�  �U����l6��  PFPA�)H8b@
CD��J��$�U
TT.��*ZKQ�*<�P,�(��-9� ��9�=fwf��?���9z�gwf���ߵ;����~�������=3��=��M5�h�OAi��T
�5�@
((  ��"�Em@5�@
J%��j@AQP
$Ѐ��@I*�PP�T    4��$P�����@
((  ��"�Em@5�@
J%��j@AQP
$Ѐ��@I*�PP�T    4��$P�����@
((  ��"�Em@5�@
J%��j@AQP
$Ѐ��@I*�PP�T    4��$P�����@
((  ��"�Em@5�@
J%��j@AQP
$Ѐ��@I.�T:�����Y�;űk�*�FPZ#BQPf�����5{�?��&i����ԛP�J|�{|x
<o;�wc~�2��g��/�c��z1��J����7�����J�%P�����whWQ<�   �����mC�
=����ޮ6�vU�,�R�`��m�?����N�"�4�ۡQP�`X��1�����F��S�m�M+0��#�+q$����;�    �bC���#���%��R���9��x��H�f�����@hV�xe5T*}�ހ��&�t��QP�Qê^�~��?�逸��fX������͡5��q-5�UYM�����t0
J�E�gz�a���E��t}e�J���!_>��c&�%�8
�I30
J��������H���\y+��O�,8>�2S��.FA �E41��~��?55ݕ-�a�a>��يO,���YʁQP��d�8I��Y[[4�t����X�t�W�_p"1(�a"F�c�I)0

^u
���;0��Izh�mJe`�t&z�uà��C(˩RX��4M�g5(��
�y?qv���;��{1��O@�Lw�i���L���"ί
j��!0)�.��^�O�En�K;[�HĶ��ȕΆB�ĠԚ~�
xh�m5�M+0��>�6��Lt�gu}A-�ktPm�k

y��&U|��lX
�\ZN�U�����-j=��*iQ���Y�tA�D?J���A�35^�0(�]\�eր҃+��7���Sk�o��2,�����F��(#�E�)(z�f��m���3+@������&�Ui`����o4��q:���)L�A�6ԥ�ޥ�A��=����U�H3������P���W1��w�U
�-�82o�jPde�r��-)�++b�[q��  RguG�Dd�-&��.���e&&�]�z1�N���΃B�=�5�xŬb5�2�Q��V.%�#�.m�2�.�
KW��s�Z#l~�x1�KG���f�<��� ��PA $/#�,]
�ne��o�c��������a�(Bk��}POE�K���#�0�(��0��@��$�3ףbu ���:�����`�r|�a1{�(0C���?L�.����p}(�YnN�#wmz�]���ɮ%�_�7�o#M{//���ϣ�`@�X#`��/�ȹ%��Ȼ��Lz��EKij��+��7%�1��"�7F��J������`�r$Q��כ�y7S�t(�l�iw�l���0�>ڻ�v�
Y�wA\��F+c\1c��zT~��Hi�D
����5�UI�}�d�a8f���?;w�I�Ep5�l{j�R��KӇ+��J=(Y��y���A[z�ϳ.e���Zl�w��N�(o�k�$w<K�A�O&��4��#�����O B���Q�BuA(��
��G`I-(�����Z
�a��B���^�
��л(�HD�-��d�&�a�����0�E�J�ɠl2�Ԃ��m�u_1�<m�J�a�p!{��N��f�Q(�.%0��"�N]���R(��4���:��7
��bi2"�.xp$e�A0؛�k��5en�",uφE<K;`I%(Y�z��w��nû���q�
�7�9b�?
�&4db��b8��QO��%u��78�'us_C�Oὕ�l��F�
�K� ����feRX�~�a�ȍ��&N�������kN_��  ���ؕ
GY�B��2v!tb��_��}LJ@U����@f�$�'�f
(��ٌ~�ט@*v����P<
��)a�����a��K+�ԣ"Db7�%U%�߈s�t�|*����/-���e�I@D"Xd�ቴ
`@��E�Dds힯��}�����h2-�I}��,X�q�ISHD���>�    �$�����Da�ez�]����kK���y���3p�'=/�sH���ʹ��0�T�B�f#F8I�xX��ʶ�mE��K*@�����\�oAz>4�4�2�3w3���M�+����A&����xnd
�0�O(�ޟ��@���P�l3_H��G7"�,&o'�Tǡ�KЋ`&�\507$�+a���`�E�f�J�K��v\*�D �g2)XZ��&���{�A�����|n����4h`g���=�X�A��.��Cf)LG�O��
}�+�R�ۆ��Q�Ɵ�ں���h�s�RX<H�Wq
��B@)b"4p6��J�<�HRڈg�
��D���9TТQ�yP��&�w�H����lt�{�`���}�,�%K�������/�����TW���л>A#�o�8�`]t��N�pH����Q��T����g6�i�F�:u�^��ևv��.���7�@����2�x�����>Xv�x����S���{㚤��V�v�|++�a�p�M6M�A�Y�s.l��5��#��4��&+�4��O8
J�d̦�&�+��~���������k�ŒLƃ�]��?>��@8|y�=�!�'����`0���؛�^�C2r4Ƣ�^�}�+�Q�=����Wq�^�.��E���l���U���g����R�ݫͧ�v�~p�+��w���;��P��N5^����M6̮�E��!�+Y�$I��C0�n��L�]�*9=��4(i��<�� \z��p��rA��l�̏,�k�Y4�8�C�G�2��H<�Xr���3�Л`Q`�!xjoD�X��������&�73+W�w��e�{��G�PI.W����/��-۠X�\�ico�.<�|�
�f3�x��U��;G��GuY@0e���mY�D�&�v��*�3+�X���YP|���ԏء��;�p������ۉQ�z���k`�^n��m�&��D�ɭ��Xgk9@��&L�2�� -�<r�#�ySK�U���o�f�0|���G�uvb���_��f'�`{r���5��~1oҲ�WJp��R��m�L(TCB�X�
Kg���7_xq�]{/��]��R����s-�ei֥ac�Fx�1b���]��8��ɋC!���0�`b/my�b��m|�z�bA���Y�2׿�zw�#u$U(��u[�����#}��a�Ha=>v���!��O�ܵ��xb/��{D������?�[�LW�n|6m���p��㬏.��o�/wpl+���yaK��Ũ�ws���B>�z�˔����p��.7^w�V��e~�k���O�   9�Jw�מ�ő�$Ɲ8�_�n�d��$U����]"��)�0Q�i{3iXl%�l"+Pծ�I&���P[���Sq���m+/�����9[ᗿ~ɍ�$ű�����7����®��e�
�Bll�E���X!{*��@ĥ��-�����D �ꗳ�����w�/�/�W���w��%l��/����ާ��N�?z�~�0��&Yuİ��8���L�\���<��M�z<v\��0(�0���Ð_��I��4nW^q\��#�:=����D������z,a��� �t  .�5.Z
���l��:�?[��I�/'A�xs���⟰��;]�4�]V7'�/l��I6��>�
m2�`K
�%C�$�U��E�����7s��RB�z^B���Ps�#I��0(�����8���x����!,}s�}��v�ūC����x�0�6r6_�a��,�q�%f���N��Fq�T�����&w��%�IDAT�}    ���Y׹˷$���Ӥ�EҔ��@�`-�
��a�ڢ-E
�M�AQ�Zk��"%"Gg��8�ǥ$��N˴j馃4��/߾^��s��r��~�{����s�g;�y��{������<q��FYـG7��^�ǵg?�?���΍,R��s��Zy汿���U�z���0S��J)|q����B�
    n�[٠�^)P�(ͲBKYJ���OR�tO���q�:/��������w�_��勏��/�u���'���v���#��lQ����uI���De~ #��{%~�d��@lV�i%�E���y�"�3��Px��ܴ��X�IFP�k*����#�d�.��C�ӟx����ƅ��屣�AvG�j$p��
d��t$�
�H�?1����'�#T�f�d05��孈�a�:�r��>^~��0
_���k_s{����붫v��/l<�<z��/O^�Y���m�B���_֑����5"(�������y2�3N�f�����?(k+�E�����P�������m��w}u����m�])�s�[?�#���:����7y��:A�
\IOi_+ے�ԉB����h���QAS��况�*�+�k�GP?u�Ly�]�q�kk+�3�����_?�(څ��_R�8��$�Q��g'{�<u�d@0�uDLz�#AǱ��PV0�~OC_�(��1Dr�#P����,�V~CΎ����Ty�]��;��]���˿��^-��g�.O�|��cr�ֈI�l�@Q�&�ˤeG��J��=O~%�19��V�g�~U�cʁ�_)V�s]�:;�Tٿ�|�ï*_���������;�-;ב���9    L`�ք�8��ʷ"�mN�U�Fy��͘l�%乘�k��+�w�FT���~���rD�w�i��-/�/p�8O������W��
f-�9�%0 |j`K~d8q sb@����s�O-����BC�gT�=P�V>S��2�������oz����}�euU�4�0>y��̹/�>1}���ԮK�(���j~�h:̓�Q���۞c��g�z�?j����妵�:FV_��Q����Q�ӯ���<�;����/����e߾�Q����w��7"m]�����b��Q�AY!�z�I@(?x���C�Ӥ�j��(hC����C�o/�+O�ٱU'O�/��������F���������l�'  u~�|��y(vL�|���K
�d0K���k@ʹ+������sK��z�`%u2<�TvPtu(底��}��i�GX�dy��|�����T9{��5����������܏�8}�e�o��D�*ә��g��
DFZP/��e��  '�B�A�+�B)"����W}F  ��_�`9��o�옫����7}�|�sG���_��g>���/<�̿�I�9}o9~���$L�<    <6 ����%��:zh���j���x'(����/�V>����zG^?���/N&د���{����~���|�ho�&��ı����rl4F���t��Np���2�*F�(qc���zJ�ʰ��"��ؗY�<Qz�p
7��-�b<_��q�����^y��}t�ze�/|�
����r���Y���R6���ȑZ����<�M��dF:
(::�%Pj �cN�$}�7?|���5�?}�-���7����?qSN���Sx>9|�'��-�R��S�K5hrh�X�[ʅ0{:����o��r�����֟����ݯ�o{�����n.G����g�3�}}���G�۞s��z���[ݿ�E�ʫ<������S����+����R�B�l(z��p
0&�v����3�����u��L�ߪ<���V��
y?>�x��>{�k�R�=��O�7m�k=F�~��@�!b�'��'�S,��O�9�����|F�[tׯ�o�J��%�}��>_��w?���7����w|e������w���s_^�<�Α�'�(�ޥ�[wM�@ٿ��(o�>��c����-?C��������5���p[[�����������@�䭟���S�i��A����>��N�yͯm��>�|���/���nxƸ�
�(k��gލۮK�\l{�y@���k��ߧ<܋_�������?�?
?;�U^|�寽���_���m8M�z9y������0lv���x���͙�᭟Q�aFM�Xe�<����V?��~��!��_Yy�;�?�:t�z��{�W�������{�A}�My��������?�Jr(�7�9�&@��A�}���(���a�G��������7��X���}嫿ꏔ�}ճ����B�,�0g�_<����-��)�I�$�@iǍ���!Sh{�s�(�+X�Y�o��>��r�̟���@!l��WT<v�'O�MEXE��?��]+�`��r�ڏ���W�e5��=�����WOz�����t����G��:!܆����d����a%�b.)��#��̟� �c��00    �}+������e=��H�8�5��LI�fv�4)Ne+V5)�qҔz1H=�P��3��6iA��w��k'�W�XW
��EZo8~��[֣���s/*O���;6(��A�2q�P���x>�1L    C�*�>�PHz��%0B��;6��*�2�Q�K��<Q�e�bP���>�7��,#��S'�+����P��!P�&&�́Lx/���p�`LJ>��ɟ;8@vwEJ�u���q�ݯ�m��'��]��z�$�I�Hw��)��[�DDW@   ���D0�% .�e��   ش�'��u���3Jw���P��q��w<����O�?���m��L�əѩ�v�\�C��+�Ӄy,Q(��^U6(�����|!R�4*�Щ�>�ו"������_��Ֆe$8r�[�����#F  ^�3����CI�ת
�z
����,I��a��g(�K �Y'J���P
2��
k��,��A]6�2|&y��}J�!H���DB��ۮ�S��L`e<��$�b��I@Lzk� �y�
�U�����;���'G[�����/�����ct�U�-���-��ra&kzV;"�m����@�O3T�"B2J��w�B9��1
�)ٱ^%%��FnQ%o���Q�(tt�
���(�l(�>|
���_J�x���p��J�v��3����J[&}�"�3�Hj  ��"�P0$=!�d�--?S�Vd���Fg�e���/c����D�A���Q�:��,W?����r��wդ�V�lr�p���rY�ZO�!'*�m�喜�)�%(Y�P�A>sv0���z3,;(��l�C��7U�Djg�Ru����co��<    ��ng�|�u��:0xT��a��tܢ $�JP�KA�0PqL_�_������[}�<z��y���6�,Z2�\LK�++�,���49�r�#p�����z+8��{��*�̈́_J[�M~�W�^����4k?�ˎ��tH���s�3�ţY@I�݉B���Ww
�#�Yr|��@��ϔC�~�f��F` ��r����{*C�0����&h��\�E��A��Bڷ�J�*Giٞ:Mh�R�IR�'�5���^t�@���E/ы�e��D����Gq��\H,�+�����'Ͼ�&����&ejG]ؘ�u0���A�(&��Df��a����c���,��f��:ML[�.
֡#���v�ٿ��rþ_l+]�.[�>��r�̟��L�!P��(�C�JKO��^I�٧ �L��0�Mj7�P���l�ӃЇ-�R_ţ�AW-�K��4(!��
K��w7��7�7���������g�Oq�    P3�v䀒�٧ ��L_1�~�佌�)U&N[�O��C�TJ+����c{{8C��Ǡ��SB�j=ppU15_�D���������e{  ��$�q�EM2�IՊ��Q�/�$���O�[�L}�4T�lY�NE�iKI.�9)M�L5g�8��s����Hx}X!�
    ż��_�N��O����W�WT�W�$��$�$N���D��PdbS5�H��*a��%)�"��AȠ�W���{�Q�NSZ�i��8���Eo�,�+��-����;c���n������c�k�·��x��ݢN&��k$�e��&0�� M$5
�h���DY/`$��r݀�Y*���˼e��+�F�IF+ѐ��o�5)�Q>̧s\<����υp�R; 1@���ֱ�V7+�����������$�0����|NBqEs���
��;! �K���v�|����GG")c�d-A�!(����J����[$���%e��N�~�X.�"(Z��T1Lo�_��k�p�Έ@~-��>q.$J`ڊ��mf��
Hp�
�MD)ms�5}D?N�@��1x9�9�.z�%ٱ>�{AĤ�V�������c����A��:��W�,�u��D�o9����s�0�U��D�7�}/!`�п�Ž�xO-m��|��%x?��o  Kc(��3Q�<٧��    N�\E aX��D���CS`�V������B䕂�`H��������߳DL�{�#'����p� a���vAB=e�$ܩ�]v2QEy�۩`KH��H�(<�I&��7    �b=]vP�����\t�()���v�����c���y��y�����Su�Y d�&'I�&��Y�Շ�\�.���V�
P�Z�c5���>��Κe������U@׳����(lq�0���PJ���$����N�g
�ı�I��VjP&O2'e���ٴ��5m�U��Q[�:"F-�{7�l�>�i���Q�~ەϼ͗�f�F��Q'5��ŧ�瀑heީ�%-��0�X�k��o�t� n�>�����ֱ3ߨ?)�˫Q�qM�i���;���� �L%!'�����L��@�$Vp�
�̡��0����6�O���&���<�d��c(\x�]��$t9d6v\�$ʅ�Z�F�p�\�[���ߓ�n��gNy�u����O�k�L� G�I��$�
)�a���6A�9��<�i mR��S�5��ӄ�\aNC�ʎ8Q�r�E�*���h��Řa��X(��7����K��S����3�~�^���Y+�)�4H,::��Lj�(�]�J�
�5O�0�#��F���͉�hh�#�c�1�&�6�Z
s�*wP�4]E�.�Z(�����/����S�!b�S�c���J�^��C�k�)�@��|�:u�����������UY �$��bF�oW��O�,˾�����z2P���7�A�=�:5)0!4W7�f�������<�ͩv̉B�3��XE«����0 �C���A�A)�����gq��NF.}
��(>���p9�Ǆd�a�Sg�N��㟃��)��kˊ�,�_�d0Ť�q�LfȪ�i�-Am�JP`�3�~�(���/ ~�O��
��$t��4M�(�R�e���R��^#I^p�A�P�
!��`���U�ڷn��[�0���4�������Әe�?U�+Z6�A=��>w�-��8n�b>����vz��B9�g)��-z
��2?�c��w�m�N��!8�{4ͭ�0�cϯ��r7AAW���ʎ:Q��LdmP��v�H�.]�%_="P�.qRخ$9��H�tmN��F<ʾ�/�����o"���������Sɺ����[�9<��>�����;���w�~�d8]&f�ek�І"��8y57�h�9"i�S�c63A�o ��'?O/���#���F�r�����`�
9
,Ô�-�5(F�I��d�A�n�t�����$�6����L�<����em�Q�扲���������:�|�Y�i��h��47�S���-���/�g� ��w�\�bp��0��JA�H2�[
��g�0��L5�x���}�K/�bx�5$t��_d�U���G,�?�Kՙ��q'
��y:    ������T�����Ր�B��[�����P�`�T��$�s�0�H��agf�8�ᒔo�Z3���i=�P�Ey��y,f���(����0<��`&��b ����-��I���4g��#��<Aw蟸s� �&sp
,��J��'{����f�vj
P1�.��zN��^qC1������rH])jC�������~�|�@0,�����DDʅ1�$���}u'S�*C��ŞQϼ����E'�r�DpE��^�%_Q����   �wP ��W;���W��0x��m2�S[,T���LA�I1���`M[�j��+Si.Έ���n��������zu똲�">��*�� �&�h���.�T-rR���M���*3ɋ�;(\��S�����Nl�H����E:��v(i+p�Ĝ��QER��6���c�eҭF���l��Tu=�FV5Q�S�"5��&m)�8��.�@|���F�m��  %X�ן$�J�r��Tc���7���t��� �՝�0O�Y�x� v.�cy=!���b��WE�2��{6*X����L�E?Aa8W��
���*g��,��$�&�b�5����M%҇�ʯ�J2
 �4�4%�j�D���S�d$�� �
z<$`�xb��F�w�(�=�?�f,
J��:�$��+��������!iE�z��l��v�˴�i��+zcr5?�4ME了�SȉQ�%<o�hR�x�XCQB��s0�ɪ9--Dt[��^���y��~���@�8��Z��Gal[9�[���!��5tC$Y��;��+9�d�,   Gn1�09"C��
��&�!&K��OA$�3W][M�`V�ce�;��[7����4������Q��X&J>4�![�vRwR��;�ɯ�}20$dH��w�A�E�*�hA�ɮluƀ[#��(͹Y�c��U���@��ʚ����ԣ��4�}7�2Q("QU$�p踫1���p`�m՜/���q�=���/�)�X"�x�Aې��g�����|�HGv
�ܛ��m4y����������
�9��b�Z��>X���U6T�
,N�6��"����ܲ�٦��}���=iǒ���/UTr.�n{�n�=y�0u*a?�i�����$3@d�U��)B�L�N�T�ס�����'2�  �lB�ꊏ:�,�� d��,m
�]��p勁%�ޱ�hA�XV3�F,�
���n��0]0Vl��4McE�����j�/-�2�D�~�\���wI? ��"�ӊl�$�%�Is�z�� H8ݮ
Ԓi�݉�+3K�v�hS�@���4��|G�p!G��)��d1wM��3��u$-�H�^;MuӞ�(6�A��04i:��I���}���y��E��0�y92ӎ�0QtK��J�N�Eck����<�T���ٵ@q�����y���`�i,NtX8����"V��j�Y�   ,ؖ�)*RRϕ�f?/ɔ����1�X_�w�涚k��o��W�b��W��m`   PFB������~�\�Y��Х�"A"�9m:s��
㐉�������D�(|
Nn�����fbknx�E
'Ҷ��P
��l�P�",0Z>�)T��1hr�Ux�m�E�,�B;ZB0-�9�����m�=X��6cF��^�[#5�"%�D��el�Z]��,Վqi�]  ��r��[H�x1  ����6�t<�CxL�6%�d�4 ��"%4��L��iʀ=wP�JB� �b�d�,��˥�r�������x�$@�m��+:��Xt8TdG��k���]:X��4�I��@������S�[�Q�r�B+S�� _&�X���(J��$���(]W{�� |!+l�T���.��Kd���*W)��%XTbq:S��k�Ib���N�
K.b�����M�+��4�L^}=lI\OeNl<��:�,�NS�(�0{PK:�Y�DN~i.OXM��i?��I�p:�h�U&|�8E$1�����@B!0Ԉ�UP�dēC0����ʻL�]�i�`��Ǿ(   `�[�>��p��Uf�.����AN"�hZz���/��$AYh��!�/PR�Z���h�){
�NE�9>��)�b�@P��'"L�SD�Q��� kE�;�B�J(�c�q25�7�+���'�"�j�`IE�?����Oh(����i!C�y�O7���sO��;1�c9pث�L�J`'�δ�fЭ㔜�|����Iϵk�I�չ�a=;u(��V �#{�Dɸgr*���c���=�b���
[,��*�¦���F����L���~{Xe��   ;
H�3�9Ŕ���%��|��m�HAŒ�j}Ψe]�E��Q�͈������y�;{
(ߥ�E�a�[�M��i3��*
b��҇�D���i�ߞq��ii
f/P[SZ�6;�
_�A�e�X��mma-�C;�   �g-���;��#M�p5A"7�ʭ�U�6�ۓ���n̬�U���7�7 �e�20T��

˜�������K(aK�tf��"�(����eC�ū^�4����f�h+d�6H8��;Qj����K�vR[;��DL`�k^'���J
m!�ҠH�p��.Y�;ÕYK�<��=m[d���)�3�֊��gk���'���ǂl)�R���E�_�Ȼ�x�p�,NNnQ$�p��)�+�P-�5[;;��[�ut}�A�+ۀ5m�W,O�%����f>ĜV�m�A��� �x����u��*©�vD��Y�f5�ˋ�xW�ڳ'J�7�±6��3�t��'w�̮H$����Vn�ݓ�ѻb�M�S��3[v����'.�F�<�{�5͔�l.��Ī��Y �S�*ͧj�t�<P��"n� ���YN2r��ޮ��Ϟ���D��t�2�,Q�%���R���AdS����W=j��iMT��Pӎ$Z�^��b��6�d����b�l0�Z�p�����de1�����&��6���^b^����á�D��U�o�_���U�vléS��$tgy�0
]�oq���U�t�`�v=re2-:]�15���A��h��ͻi�o�uV4Ur��İwƬ8?4�獕iz��
Н����3&�D�@�@��"`����M$ �B�;L�IL�u�RS�%��`���D7۰�8G��ʔ��P94(�2�-��7F�е��(�(S`�� ������$1�"+����"E�(�͘>��J��g��=�Ѧ�9kj�Y���hAB�@����xi�����ͪ{��^�Z���V��T���m�
�@�9�?aN�\�v*@r�K�d$6i{�PL�>#ț}�z�ҀрCyO��lfiq^[F�:i?�V6��*  �L�P@K��h�VF�Ye���&�p�������b�>�RfU��N?�L?��fHH��^�0�7G��I�p`��"���x    ���6���f/hz�f&{���If���Tc3:s�6��P�d�@�H\D{Q��<��\��H����������<��?a{�� �����F�@��JIEND�B`�
</code>```

Thanks in advance for your help!!

答:
try this:</p>

```<code> constructor(public _DomSanitizationService: DomSanitizer) {}

 ...

 <img [src]="_DomSanitizationService.bypassSecurityTrustUrl('data:image/png;base64,' + response)">
</code>```

Title: How to set blob url in image source

Body:
I get a binary file back from the server and would like to show it in the frontend. I convert my binary file to a blob and use the DOM Sanitizer to create a save URL.

The problem is that the image is not found when I used the blob URL for the image source:

Typescript:

const blob = new Blob([response], { type: 'application/octet-stream' });

const fileData = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob));

HTML:

Response from Server

�PNG

IHDR��91tHiCCPICC ProfileH��WXS��[RIh�H ��R�K   �E�*�I �ĘD�ʢ�k���"��;��(v��P��u�`C�M
����������ϙs�S2��t�yRi.�@�$_����"u`���ǗK�qq���������r�E����=�P���8C ��A|��/��@�z�i�R%���&�T��ԸX�3ԸBe�ρxd�'�@�   �Y�,ȣ}bW�@,@�q _�@  )J�C�7<Y����������C�ri.o��َ�-y���vp�D��xeͰowr�D)1
�nIFL,���T��T�"2Im�����3���U�����pInL�F��)�BWZ(��&j|    �a  �jٔ���)�5��<�*����"'���#r���S�9c�qr��3�9    Qj̦Hĉ��)���@�'�D����I���x��,O>P/�H$��hpe�(1Ró��S�oq�P�N���E�"���kǮ
%I�z�vi~H����47Nc�S��J�Ħ��/�������%���3�y����� p@(``
�����n�K=x@���h4)�  �&�"�DB �Q�
A�Ԫ�. S5[���O �Q �V��$�ђ�P#�!:��r�Gj�5�/Kg��F%FÉ��  ������;��d�՞��FxL�Ih'ܝ,�/���a�pM��֌�AVO<���g�&� #�� �j9�̕������Ǝ�JA)C(���=���=Y�=��C�\3����>>�N�=�{Kl�;���.`G�F�cM�e���?T�h Z�*��#�!OS�I�k�k��'�\��P�~�)��2q�(�ņo~!�+��rwu�@�Q��^3U��y�n�������j`��_u�����$��
Y�Z�+/@:�2��8�z܁�� �� ��I��"��e`�   �P��5�l[�����8  ΂K�*�   ����    ����!BB�1F,[�qG|�@$�F�T$�B$���,@ʐ�H%��E~E!'�Hry�t!���(��P��CG�>(�Bщh:-B�ѥhZ��BГ�%�&ڎ>G{1�iaL�s�|0��a�����b�X
V�5���:֎ucp"��Y�\��x�ǧ��%x%�o�O���Gx��@'��  ~.a!�0�PB('l#$��OS'�-�Hd���iL%fg���Oۈ�^�dLr&�bI<R>������t�t��IzO�"[�����4��<�\N�I>F�F~J��Rl)~�X��2������L�B��Q����j"5�:�ZA����ާ���Ҳ����%֚�U��W��#�4}��C�@SЖҶ�N���^��t;z0=��O_J����?���fh��j��hWi7h_�~�Cѱ�a�L�)�)�ٯsE�[��k������֭�=�{[�W�������Do���g�$};�0}�~���S��a��0�����3�N���� ۠�`�A�A����H�d�B�*ã��L�i��2s�˘������
aY<�~ȵ!    �J���4�h�23�1^a�h��7q2k2�d����C����7�wS���4�t���˦�f�ffR�uf�̺͙������wY0,-��-�[��2d�Y��
�iV���e���r�e�e���U��|�=V���>֙֫�[�{l,l��̴���ݖb�c+�]k{�����]��B�F�g�F�\�"�:��t� ��57��>�9���:�N�N"�*�+Ψ����y�s�0�0�a�a5�n��\�..u.��3�G�?�q��6#�F�qn�WO�\׭�����F��wkv{����w�r��A�������r��H��
#�x2<�x.�l�����%�����N�����c����/�7�w���~^~�~����w������l��(ᨭ�:�x��Y�遛ۃ,�xA5A�����ۂ�����]�!�!���!�8~�Y��XhDhihk�~XRXe��p����ψ'" �Q�+"os͸|n-�g���Y�OGѢ�*�G;Eˢ�ǠcF�Y5�~�m�$�1�rcW�>����wx,ql�ت�O���gƟK`$LNؙ�61$qY�$�$ERK�N����w)�)+S�Ǎ7kܥT�TqjS)-9m[Z����k�wN�P2��D���/L2��;��d�ɼ���  �)�;�?�by5��nFuF��_�.�t �+�O32Wf>�
�Z��%
����q��evd���w9�9�s�sSr�����I�%9��ŞNi�:KK��S�����#��m�#��|�a��pP��xTXPU�~Z���z����ӝ�/���(��������3��|4�=k�ldv��9�s��t΍��cu^μ���_9�͂���f�s�;~����D�DVr{����E�E��=�[��TPz�̵�������?��\�s��̥�˼�mXN\.Y~kEЊ+�V��X5fU�j����o�L^s�|d�ƵԵ����M�l�-_��RTy�*�jO�i���w��m�P��lc�Ə�ě�l���PcWS����`˓��[����K�6�me�>o�lo���t�wm�Nӝ���:E]׮ �����T�R�ysO�^�W���_���/j_�~���lTd,m@�7�4�ۛR���>����|����ۏX�:jxt�1��c�ǋ������>�u��er˽S�N�8=�t뙨3�φ�=u�}�����G.�]8t��b�%�K
�=/��^�
W��4]����6��ص�k'��^?{�{��͘�m��nݹ=�v���gws������{s��>�}P���aͿ���ݫ���G�'<����x����O��O�OʟZ<�}���HWx��?����\�����/���_8�8�w�ߗ{��t���������oF�i��}�6�m߻����w|��p�c�ǧ}�>�>U|v���%������~)O�Sm08��L^m��
�*�?�W��T��Ϧ*�V�U�@=�)����.rûr��P���y�����O<������ ���gY�����[a�w81U}�T
�
6+�M#�\������ꯈ  pHYs%%IR$��iTXtXML:com.adobe.xmp<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="XMP Core 5.4.0">
   <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
      <rdf:Description rdf:about=""
            xmlns:exif="http://ns.adobe.com/exif/1.0/">
         <exif:PixelXDimension>202</exif:PixelXDimension>
         <exif:PixelYDimension>188</exif:PixelYDimension>
      </rdf:Description>
   </rdf:RDF>
</x:xmpmeta>
M�uiDOT^(^^lKgf8IDATx�  �U����l6��  PFPA�)H8b@
CD��J��$�U
TT.��*ZKQ�*<�P,�(��-9� ��9�=fwf��?���9z�gwf���ߵ;����~�������=3��=��M5�h�OAi��T
�5�@
((  ��"�Em@5�@
J%��j@AQP
$Ѐ��@I*�PP�T    4��$P�����@
((  ��"�Em@5�@
J%��j@AQP
$Ѐ��@I*�PP�T    4��$P�����@
((  ��"�Em@5�@
J%��j@AQP
$Ѐ��@I*�PP�T    4��$P�����@
((  ��"�Em@5�@
J%��j@AQP
$Ѐ��@I.�T:�����Y�;űk�*�FPZ#BQPf�����5{�?��&i����ԛP�J|�{|x
<o;�wc~�2��g��/�c��z1��J����7�����J�%P�����whWQ<�   �����mC�
=����ޮ6�vU�,�R�`��m�?����N�"�4�ۡQP�`X��1�����F��S�m�M+0��#�+q$����;�    �bC���#���%��R���9��x��H�f�����@hV�xe5T*}�ހ��&�t��QP�Qê^�~��?�逸��fX������͡5��q-5�UYM�����t0
J�E�gz�a���E��t}e�J���!_>��c&�%�8
�I30
J��������H���\y+��O�,8>�2S��.FA �E41��~��?55ݕ-�a�a>��يO,���YʁQP��d�8I��Y[[4�t����X�t�W�_p"1(�a"F�c�I)0

^u
���;0��Izh�mJe`�t&z�uà��C(˩RX��4M�g5(��
�y?qv���;��{1��O@�Lw�i���L���"ί
j��!0)�.��^�O�En�K;[�HĶ��ȕΆB�ĠԚ~�
xh�m5�M+0��>�6��Lt�gu}A-�ktPm�k

y��&U|��lX
�\ZN�U�����-j=��*iQ���Y�tA�D?J���A�35^�0(�]\�eր҃+��7���Sk�o��2,�����F��(#�E�)(z�f��m���3+@������&�Ui`����o4��q:���)L�A�6ԥ�ޥ�A��=����U�H3������P���W1��w�U
�-�82o�jPde�r��-)�++b�[q��  RguG�Dd�-&��.���e&&�]�z1�N���΃B�=�5�xŬb5�2�Q��V.%�#�.m�2�.�
KW��s�Z#l~�x1�KG���f�<��� ��PA $/#�,]
�ne��o�c��������a�(Bk��}POE�K���#�0�(��0��@��$�3ףbu ���:�����`�r|�a1{�(0C���?L�.����p}(�YnN�#wmz�]���ɮ%�_�7�o#M{//���ϣ�`@�X#`��/�ȹ%��Ȼ��Lz��EKij��+��7%�1��"�7F��J������`�r$Q��כ�y7S�t(�l�iw�l���0�>ڻ�v�
Y�wA\��F+c\1c��zT~��Hi�D
����5�UI�}�d�a8f���?;w�I�Ep5�l{j�R��KӇ+��J=(Y��y���A[z�ϳ.e���Zl�w��N�(o�k�$w<K�A�O&��4��#�����O B���Q�BuA(��
��G`I-(�����Z
�a��B���^�
��л(�HD�-��d�&�a�����0�E�J�ɠl2�Ԃ��m�u_1�<m�J�a�p!{��N��f�Q(�.%0��"�N]���R(��4���:��7
��bi2"�.xp$e�A0؛�k��5en�",uφE<K;`I%(Y�z��w��nû���q�
�7�9b�?
�&4db��b8��QO��%u��78�'us_C�Oὕ�l��F�
�K� ����feRX�~�a�ȍ��&N�������kN_��  ���ؕ
GY�B��2v!tb��_��}LJ@U����@f�$�'�f
(��ٌ~�ט@*v����P<
��)a�����a��K+�ԣ"Db7�%U%�߈s�t�|*����/-���e�I@D"Xd�ቴ
`@��E�Dds힯��}�����h2-�I}��,X�q�ISHD���>�    �$�����Da�ez�]����kK���y���3p�'=/�sH���ʹ��0�T�B�f#F8I�xX��ʶ�mE��K*@�����\�oAz>4�4�2�3w3���M�+����A&����xnd
�0�O(�ޟ��@���P�l3_H��G7"�,&o'�Tǡ�KЋ`&�\507$�+a���`�E�f�J�K��v\*�D �g2)XZ��&���{�A�����|n����4h`g���=�X�A��.��Cf)LG�O��
}�+�R�ۆ��Q�Ɵ�ں���h�s�RX<H�Wq
��B@)b"4p6��J�<�HRڈg�
��D���9TТQ�yP��&�w�H����lt�{�`���}�,�%K�������/�����TW���л>A#�o�8�`]t��N�pH����Q��T����g6�i�F�:u�^��ևv��.���7�@����2�x�����>Xv�x����S���{㚤��V�v�|++�a�p�M6M�A�Y�s.l��5��#��4��&+�4��O8
J�d̦�&�+��~���������k�ŒLƃ�]��?>��@8|y�=�!�'����`0���؛�^�C2r4Ƣ�^�}�+�Q�=����Wq�^�.��E���l���U���g����R�ݫͧ�v�~p�+��w���;��P��N5^����M6̮�E��!�+Y�$I��C0�n��L�]�*9=��4(i��<�� \z��p��rA��l�̏,�k�Y4�8�C�G�2��H<�Xr���3�Л`Q`�!xjoD�X��������&�73+W�w��e�{��G�PI.W����/��-۠X�\�ico�.<�|�
�f3�x��U��;G��GuY@0e���mY�D�&�v��*�3+�X���YP|���ԏء��;�p������ۉQ�z���k`�^n��m�&��D�ɭ��Xgk9@��&L�2�� -�<r�#�ySK�U���o�f�0|���G�uvb���_��f'�`{r���5��~1oҲ�WJp��R��m�L(TCB�X�
Kg���7_xq�]{/��]��R����s-�ei֥ac�Fx�1b���]��8��ɋC!���0�`b/my�b��m|�z�bA���Y�2׿�zw�#u$U(��u[�����#}��a�Ha=>v���!��O�ܵ��xb/��{D������?�[�LW�n|6m���p��㬏.��o�/wpl+���yaK��Ũ�ws���B>�z�˔����p��.7^w�V��e~�k���O�   9�Jw�מ�ő�$Ɲ8�_�n�d��$U����]"��)�0Q�i{3iXl%�l"+Pծ�I&���P[���Sq���m+/�����9[ᗿ~ɍ�$ű�����7����®��e�
�Bll�E���X!{*��@ĥ��-�����D �ꗳ�����w�/�/�W���w��%l��/����ާ��N�?z�~�0��&Yuİ��8���L�\���<��M�z<v\��0(�0���Ð_��I��4nW^q\��#�:=����D������z,a��� �t  .�5.Z
���l��:�?[��I�/'A�xs���⟰��;]�4�]V7'�/l��I6��>�
m2�`K
�%C�$�U��E�����7s��RB�z^B���Ps�#I��0(�����8���x����!,}s�}��v�ūC����x�0�6r6_�a��,�q�%f���N��Fq�T�����&w��%�IDAT�}    ���Y׹˷$���Ӥ�EҔ��@�`-�
��a�ڢ-E
�M�AQ�Zk��"%"Gg��8�ǥ$��N˴j馃4��/߾^��s��r��~�{����s�g;�y��{������<q��FYـG7��^�ǵg?�?���΍,R��s��Zy汿���U�z���0S��J)|q����B�
    n�[٠�^)P�(ͲBKYJ���OR�tO���q�:/��������w�_��勏��/�u���'���v���#��lQ����uI���De~ #��{%~�d��@lV�i%�E���y�"�3��Px��ܴ��X�IFP�k*����#�d�.��C�ӟx����ƅ��屣�AvG�j$p��
d��t$�
�H�?1����'�#T�f�d05��孈�a�:�r��>^~��0
_���k_s{����붫v��/l<�<z��/O^�Y���m�B���_֑����5"(�������y2�3N�f�����?(k+�E�����P�������m��w}u����m�])�s�[?�#���:����7y��:A�
\IOi_+ے�ԉB����h���QAS��况�*�+�k�GP?u�Ly�]�q�kk+�3�����_?�(څ��_R�8��$�Q��g'{�S��2�������oz����}�euU�4�0>y��̹/�>1}���ԮK�(���j~�h:̓�Q���۞c��g�z�?j����妵�:FV_��Q����Q�ӯ���<�;����/����e߾�Q����w��7"m]�����b��Q�AY!�z�I@(?x���C�Ӥ�j��(hC����C�o/�+O�ٱU'O�/��������F���������l�'  u~�|��y(vL�|���K
�d0K���k@ʹ+������sK��z�`%u2<�TvPtu(底��}��i�GX�dy��|�����T9{��5����������܏�8}�e�o��D�*ә��g��
DFZP/��e��  '�B�A�+�B)"����W}F  ��_�`9��o�옫����7}�|�sG���_��g>���/<�̿�I�9}o9~���$L�<    <6 ����%��:zh���j���x'(����/�V>����zG^?���/N&د���{����~���|�ho�&��ı����rl4F���t��Np���2�*F�(qc���zJ�ʰ��"��ؗY�<Qz�p
7��-�b<_��q�����^y��}t�ze�/|�
����r���Y���R6���ȑZ����<�M��dF:
(::�%Pj �cN�$}�7?|���5�?}�-���7����?qSN���Sx>9|�'��-�R��S�K5hrh�X�[ʅ0{:����o��r�����֟����ݯ�o{�����n.G����g�3�}}���G�۞s��z���[ݿ�E�ʫ<������S����+����R�B�l(z��p
0&�v����3�����u��L�ߪ<���V��
y?>�x��>{�k�R�=��O�7m�k=F�~��@�!b�'��'�S,��O�9�����|F�[tׯ�o�J��%�}��>_��w?���7����w|e������w���s_^�<�Α�'�(�ޥ�[wM�@ٿ��(o�>��c����-?C��������5���p[[�����������@�䭟���S�i��A����>��N�yͯm��>�|���/���nxƸ�
�(k��gލۮK�\l{�y@���k��ߧ<܋_�������?�?
?;�U^|�寽���_���m8M�z9y������0lv���x���͙�᭟Q�aFM�Xe�<����V?��~��!��_Yy�;�?�:t�z��{�W�������{�A}�My��������?�Jr(�7�9�&@��A�}���(���a�G��������7��X���}嫿ꏔ�}ճ����B�,�0g�_<����-��)�I�$�@iǍ���!Sh{�s�(�+X�Y�o��>��r�̟���@!l��WT<v�'O�MEXE��?��]+�`��r�ڏ���W�e5��=�����WOz�����t����G��:!܆����d����a%�b.)��#��̟� �c��00    �}+������e=��H�8�5��LI�fv�4)Ne+V5)�qҔz1H=�P��3��6iA��w��k'�W�XW
��EZo8~��[֣���s/*O���;6(��A�2q�P���x>�1L    C�*�>�PHz��%0B��;6��*�2�Q�K��<Q�e�bP���>�7��,#��S'�+����P��!P�&&�́Lx/���p�`LJ>��ɟ;8@vwEJ�u���q�ݯ�m��'��]��z�$�I�Hw��)��[�DDW@   ���D0�% .�e��   ش�'��u���3Jw���P��q��w<����O�?���m��L�əѩ�v�\�C��+�Ӄy,Q(��^U6(�����|!R�4*�Щ�>�ו"������_��Ֆe$8r�[�����#F  ^�3����CI�ת
�z
����,I��a��g(�K �Y'J���P
2��
k��,��A]6�2|&y��}J�!H���DB��ۮ�S��L`e<��$�b��I@Lzk� �y�
�U�����;���'G[�����/�����ct�U�-���-��ra&kzV;"�m����@�O3T�"B2J��w�B9��1
�)ٱ^%%��FnQ%o���Q�(tt�
���(�l(�>|
���_J�x���p��J�v��3����J[&}�"�3�Hj  ��"�P0$=!�d�--?S�Vd���Fg�e���/c����D�A���Q�:��,W?����r��wդ�V�lr�p���rY�ZO�!'*�m�喜�)�%(Y�P�A>sv0���z3,;(��l�C��7U�Djg�Ru����co��<    ��ng�|�u��:0xT��a��tܢ $�JP�KA�0PqL_�_������[}�<z��y���6�,Z2�\LK�++�,���49�r�#p�����z+8��{��*�̈́_J[�M~�W�^����4k?�ˎ��tH���s�3�ţY@I�݉B���Ww
�#�Yr|��@��ϔC�~�f��F` ��r����{*C�0����&h��\�E��A��Bڷ�J�*Giٞ:Mh�R�IR�'�5���^t�@���E/ы�e��D����Gq��\H,�+�����'Ͼ�&����&ejG]ؘ�u0���A�(&��Df��a����c���,��f��:ML[�.
֡#���v�ٿ��rþ_l+]�.[�>��r�̟��L�!P��(�C�JKO��^I�٧ �L��0�Mj7�P���l�ӃЇ-�R_ţ�AW-�K��4(!��
K��w7��7�7���������g�Oq�    P3�v䀒�٧ ��L_1�~�佌�)U&N[�O��C�TJ+����c{{8C��Ǡ��SB�j=ppU15_�D���������e{  ��$�q�EM2�IՊ��Q�/�$���O�[�L}�4T�lY�NE�iKI.�9)M�L5g�8��s����Hx}X!�
    ż��_�N��O����W�WT�W�$��$�$N���D��PdbS5�H��*a��%)�"��AȠ�W���{�Q�NSZ�i��8���Eo�,�+��-����;c���n������c�k�·��x��ݢN&��k$�e��&0�� M$5
�h���DY/`$��r݀�Y*���˼e��+�F�IF+ѐ��o�5)�Q>̧s\<����υp�R; 1@���ֱ�V7+�����������$�0����|NBqEs���
��;! �K���v�|����GG")c�d-A�!(����J����[$���%e��N�~�X.�"(Z��T1Lo�_��k�p�Έ@~-��>q.$J`ڊ��mf��
Hp�
�MD)ms�5}D?N�@��1x9�9�.z�%ٱ>�{AĤ�V�������c����A��:��W�,�u��D�o9����s�0�U��D�7�}/!`�п�Ž�xO-m��|��%x?��o  Kc(��3Q�<٧��    N�\E aX��D���CS`�V������B䕂�`H��������߳DL�{�#'����p� a���vAB=e�$ܩ�]v2QEy�۩`KH��H�(<�I&��7    �b=]vP�����\t�()���v�����c���y��y�����Su�Y d�&'I�&��Y�Շ�\�.���V�
P�Z�c5���>��Κe������U@׳����(lq�0���PJ���$����N�g
�ı�I��VjP&O2'e���ٴ��5m�U��Q[�:"F-�{7�l�>�i���Q�~ەϼ͗�f�F��Q'5��ŧ�瀑heީ�%-��0�X�k��o�t� n�>�����ֱ3ߨ?)�˫Q�qM�i���;���� �L%!'�����L��@�$Vp�
�̡��0����6�O���&���<�d��c(\x�]��$t9d6v\�$ʅ�Z�F�p�\�[���ߓ�n��gNy�u����O�k�L� G�I��$�
)�a���6A�9��<�i mR��S�5��ӄ�\aNC�ʎ8Q�r�E�*���h��Řa��X(��7����K��S����3�~�^���Y+�)�4H,::��Lj�(�]�J�
�5O�0�#��F���͉�hh�#�c�1�&�6�Z
s�*wP�4]E�.�Z(�����/����S�!b�S�c���J�^��C�k�)�@��|�:u�����������UY �$��bF�oW��O�,˾�����z2P���7�A�=�:5)0!4W7�f�������<�ͩv̉B�3��XE«����0 �C���A�A)�����gq��NF.}
��(>���p9�Ǆd�a�Sg�N��㟃��)��kˊ�,�_�d0Ť�q�LfȪ�i�-Am�JP`�3�~�(���/ ~�O��
��$t��4M�(�R�e���R��^#I^p�A�P�
!��`���U�ڷn��[�0���4�������Әe�?U�+Z6�A=��>w�-��8n�b>����vz��B9�g)��-z
��2?�c��w�m�N��!8�{4ͭ�0�cϯ��r7AAW���ʎ:Q��LdmP��v�H�.]�%_="P�.qRخ$9��H�tmN��F<ʾ�/�����o"���������Sɺ����[�9<��>�����;���w�~�d8]&f�ek�І"��8y57�h�9"i�S�c63A�o ��'?O/���#���F�r�����`�
9
,Ô�-�5(F�I��d�A�n�t�����$�6����L�<����em�Q�扲���������:�|�Y�i��h��47�S���-���/�g� ��w�\�bp��0��JA�H2�[
��g�0��L5�x���}�K/�bx�5$t��_d�U���G,�?�Kՙ��q'
��y:    ������T�����Ր�B��[�����P�`�T��$�s�0�H��agf�8�ᒔo�Z3���i=�P�Ey��y,f���(����0<��`&��b ����-��I���4g��#��<Aw蟸s� �&sp
,��J��'{����f�vj
P1�.��zN��^qC1������rH])jC�������~�|�@0,�����DDʅ1�$���}u'S�*C��ŞQϼ����E'�r�DpE��^�%_Q����   �wP ��W;���W��0x��m2�S[,T���LA�I1���`M[�j��+Si.Έ���n��������zu똲�">��*�� �&�h���.�T-rR���M���*3ɋ�;(\��S�����Nl�H����E:��v(i+p�Ĝ��QER��6���c�eҭF���l��Tu=�FV5Q�S�"5��&m)�8��.�@|���F�m��  %X�ן$�J�r��Tc���7���t��� �՝�0O�Y�x� v.�cy=!���b��WE�2��{6*X����L�E?Aa8W��
���*g��,��$�&�b�5����M%҇�ʯ�J2
 �4�4%�j�D���S�d$�� �
z<$`�xb��F�w�(�=�?�f,
J��:�$��+��������!iE�z��l��v�˴�i��+zcr5?�4ME了�SȉQ�%<o�hR�x�XCQB��s0�ɪ9--Dt[��^���y��~���@�8��Z��Gal[9�[���!��5tC$Y��;��+9�d�,   Gn1�09"C��
��&�!&K��OA$�3W][M�`V�ce�;��[7����4������Q��X&J>4�![�vRwR��;�ɯ�}20$dH��w�A�E�*�hA�ɮluƀ[#��(͹Y�c��U���@��ʚ����ԣ��4�}7�2Q("QU$�p踫1���p`�m՜/���q�=���/�)�X"�x�Aې��g�����|�HGv
�ܛ��m4y����������
�9��b�Z��>X���U6T�
,N�6��"����ܲ�٦��}���=iǒ���/UTr.�n{�n�=y�0u*a?�i�����$3@d�U��)B�L�N�T�ס�����'2�  �lB�ꊏ:�,�� d��,m
�]��p勁%�ޱ�hA�XV3�F,�
���n��0]0Vl��4McE�����j�/-�2�D�~�\���wI? ��"�ӊl�$�%�Is�z�� H8ݮ
Ԓi�݉�+3K�v�hS�@���4��|G�p!G��)��d1wM��3��u$-�H�^;MuӞ�(6�A��04i:��I���}���y��E��0�y92ӎ�0QtK��J�N�Eck����<�T���ٵ@q�����y���`�i,NtX8����"V��j�Y�   ,ؖ�)*RRϕ�f?/ɔ����1�X_�w�涚k��o��W�b��W��m`   PFB������~�\�Y��Х�"A"�9m:s��
㐉�������D�(|
Nn�����fbknx�E
'Ҷ��P
��l�P�",0Z>�)T��1hr�Ux�m�E�,�B;ZB0-�9�����m�=X��6cF��^�[#5�"%�D��el�Z]��,Վqi�]  ��r��[H�x1  ����6�t<�CxL�6%�d�4 ��"%4��L��iʀ=wP�JB� �b�d�,��˥�r�������x�$@�m��+:��Xt8TdG��k���]:X��4�I��@������S�[�Q�r�B+S�� _&�X���(J��$���(]W{�� |!+l�T���.��Kd���*W)��%XTbq:S��k�Ib���N�
K.b�����M�+��4�L^}=lI\OeNl<��:�,�NS�(�0{PK:�Y�DN~i.OXM��i?��I�p:�h�U&|�8E$1�����@B!0Ԉ�UP�dēC0����ʻL�]�i�`��Ǿ(   `�[�>��p��Uf�.����AN"�hZz���/��$AYh��!�/PR�Z���h�){
�NE�9>��)�b�@P��'"L�SD�Q��� kE�;�B�J(�c�q25�7�+���'�"�j�`IE�?����Oh(����i!C�y�O7���sO��;1�c9pث�L�J`'�δ�fЭ㔜�|����Iϵk�I�չ�a=;u(��V �#{�Dɸgr*���c���=�b���
[,��*�¦���F����L���~{Xe��   ;
H�3�9Ŕ���%��|��m�HAŒ�j}Ψe]�E��Q�͈������y�;{
(ߥ�E�a�[�M��i3��*
b��҇�D���i�ߞq��ii
f/P[SZ�6;�
_�A�e�X��mma-�C;�   �g-���;��#M�p5A"7�ʭ�U�6�ۓ���n̬�U���7�7 �e�20T��

˜�������K(aK�tf��"�(����eC�ū^�4����f�h+d�6H8��;Qj����K�vR[;��DL`�k^'���J
m!�ҠH�p��.Y�;ÕYK�<��=m[d���)�3�֊��gk���'���ǂl)�R���E�_�Ȼ�x�p�,NNnQ$�p��)�+�P-�5[;;��[�ut}�A�+ۀ5m�W,O�%����f>ĜV�m�A��� �x����u��*©�vD��Y�f5�ˋ�xW�ڳ'J�7�±6��3�t��'w�̮H$����Vn�ݓ�ѻb�M�S��3[v����'.�F�<�{�5͔�l.��Ī��Y �S�*ͧj�t�<P��"n� ���YN2r��ޮ��Ϟ���D��t�2�,Q�%���R���AdS����W=j��iMT��Pӎ$Z�^��b��6�d����b�l0�Z�p�����de1�����&��6���^b^����á�D��U�o�_���U�vléS��$tgy�0
]�oq���U�t�`�v=re2-:]�15���A��h��ͻi�o�uV4Ur��İwƬ8?4�獕iz��
Н����3&�D�@�@��"`����M$ �B�;L�IL�u�RS�%��`���D7۰�8G��ʔ��P94(�2�-��7F�е��(�(S`�� ������$1�"+����"E�(�͘>��J��g��=�Ѧ�9kj�Y���hAB�@����xi�����ͪ{��^�Z���V��T���m�
�@�9�?aN�\�v*@r�K�d$6i{�PL�>#ț}�z�ҀрCyO��lfiq^[F�:i?�V6��*  �L�P@K��h�VF�Ye���&�p�������b�>�RfU��N?�L?��fHH��^�0�7G��I�p`��"���x    ���6���f/hz�f&{���If���Tc3:s�6��P�d�@�H\D{Q��<��\��H����������<��?a{�� �����F�@��JIEND�B`�

Thanks in advance for your help!!

Body:
try this:

 constructor(public _DomSanitizationService: DomSanitizer) {}

 ...

 <img [src]="_DomSanitizationService.bypassSecurityTrustUrl('data:image/png;base64,' + response)">


问:
Calculate direct dependencies among values of a dataframe in R
A data frame is given and the objective is to calculate the direct dependency value between two columns of the data frame.

```<code>c1  c2   N
a    b   30
a    c   5
a    d   10
c    a   5
b    a   10
</code>```

what we are looking for is that to get the direct dependency relations, for example, for aand b this value is ab - ba = 20.
The final result should be like this:

```<code>c1  c2   N     DepValue
a    b   30    ab - ba = 20
a    c   5     ac - ca = 0
a    d   10    ad- 0 = 10
c    a   5     ca - ac= 0
b    a   10    ba - ab = 20
</code>```

Thank you for your help.

答:
```<code>D <- read.table(header=TRUE, stringsAsFactors = FALSE, text=
"c1  c2   N
a    b   30
a    c   5
a    d   10
c    a   5
b    a   10")

N12 <- D$N
names(N12) <- paste0(D$c1, D$c2)
N21 <- N12[paste0(D$c2, D$c1)]
D$depValue <- D$N - ifelse(is.na(N21), 0, N21)
</code>```

result:

```<code>> D
  c1 c2  N depValue
1  a  b 30       20
2  a  c  5        0
3  a  d 10       10
4  c  a  5        0
5  b  a 10      -20
</code>```

Body:
A data frame is given and the objective is to calculate the direct dependency value between two columns of the data frame.

c1  c2   N
a    b   30
a    c   5
a    d   10
c    a   5
b    a   10

what we are looking for is that to get the direct dependency relations, for example, for aand b this value is ab - ba = 20.
The final result should be like this:

c1  c2   N     DepValue
a    b   30    ab - ba = 20
a    c   5     ac - ca = 0
a    d   10    ad- 0 = 10
c    a   5     ca - ac= 0
b    a   10    ba - ab = 20

Thank you for your help.

Body:
D <- read.table(header=TRUE, stringsAsFactors = FALSE, text=
"c1  c2   N
a    b   30
a    c   5
a    d   10
c    a   5
b    a   10")

N12 <- D$N
names(N12) <- paste0(D$c1, D$c2)
N21 <- N12[paste0(D$c2, D$c1)]
D$depValue <- D$N - ifelse(is.na(N21), 0, N21)

result:

> D
  c1 c2  N depValue
1  a  b 30       20
2  a  c  5        0
3  a  d 10       10
4  c  a  5        0
5  b  a 10      -20


答:
You only need createObjectURL from response

```<code>const blob = URL.createObjectURL(response);

const fileData  = this.sanitizer.bypassSecurityTrustUrl(blob);
</code>```

If response base64 format

```<code> const blob = 'data:image/png;base64,' + response;
  const fileData  = this.sanitizer.bypassSecurityTrustUrl(blob );
</code>```

Title: How to set blob url in image source

Body:
You only need createObjectURL from response

const blob = URL.createObjectURL(response);

const fileData  = this.sanitizer.bypassSecurityTrustUrl(blob);

If response base64 format

 const blob = 'data:image/png;base64,' + response;
  const fileData  = this.sanitizer.bypassSecurityTrustUrl(blob );


问:
Use of defer in Go
What is the use of defer in Go? The language documentation says it is executed when the surrounding function returns. Why not just put the code at end of given function?

答:
There are already good answers here. I would like to mention one more use case.

```<code>func BillCustomer(c *Customer) error {
    c.mutex.Lock()
    defer c.mutex.Unlock()

    if err := c.Bill(); err != nil {
        return err
    }

    if err := c.Notify(); err != nil {
        return err
    }

    // ... do more stuff ...

    return nil
}
</code>```

The defer in this example ensures that no matter how BillCustomer returns, the mutex will be unlocked immediately prior to BillCustomer returning. This is extremely useful because without defer you would have to remember to unlock the mutex in every place that the function could possibly return.

ref.

Title: Use of defer in Go

Body:
There are already good answers here. I would like to mention one more use case.

func BillCustomer(c *Customer) error {
    c.mutex.Lock()
    defer c.mutex.Unlock()

    if err := c.Bill(); err != nil {
        return err
    }

    if err := c.Notify(); err != nil {
        return err
    }

    // ... do more stuff ...

    return nil
}

The defer in this example ensures that no matter how BillCustomer returns, the mutex will be unlocked immediately prior to BillCustomer returning. This is extremely useful because without defer you would have to remember to unlock the mutex in every place that the function could possibly return.

ref.


问:
Extract string value of an ENUM in a Typescript Object
I have an Enum:

```<code>export enum DistanceMeasure {
Miles, Kilometers
</code>```

}

To use in a user object:

```<code>export class User {
... some stuff
MaxTravelDistance:  number;
DistanceMeasure:    DistanceMeasure;
MaxTravelTime:      TimeSpan;
... some more stuff
</code>```

}

So the info comes from the server as 0 (zero) or 1 for the DistanceMeasure and thats fine.
But I need to present the string e.g. "Miles".

In my (Angular/Ionic) app, the output of

```<code>      console.log(user.DistanceMeasure);
</code>```

is '0' (zero).
However I read that to extract the enum string you should use it as an index.
If I do:

```<code>      console.log(user.DistanceMeasure[0]);
</code>```

It comes back as undefined.

Why is that? since the user.DistanceMeasure is of type DistanceMeasure?
Is it no longer an enum ?
Thanks.

答:
If you don't define custom values enum has integer values starting from 0 in the order they are declared.
If you want them to have string values you have to declare them like</p>

```<code>enum DistanceMeasure {
    Miles = 'MILES',
    Kilometers = 'KILOMETERS'
}
</code>```

Body:
I have an Enum:

export enum DistanceMeasure {
Miles, Kilometers

}

To use in a user object:

export class User {
... some stuff
MaxTravelDistance:  number;
DistanceMeasure:    DistanceMeasure;
MaxTravelTime:      TimeSpan;
... some more stuff

}

So the info comes from the server as 0 (zero) or 1 for the DistanceMeasure and thats fine.
But I need to present the string e.g. "Miles".

In my (Angular/Ionic) app, the output of

      console.log(user.DistanceMeasure);

is '0' (zero).
However I read that to extract the enum string you should use it as an index.
If I do:

      console.log(user.DistanceMeasure[0]);

It comes back as undefined.

Why is that? since the user.DistanceMeasure is of type DistanceMeasure?
Is it no longer an enum ?
Thanks.

Body:
If you don't define custom values enum has integer values starting from 0 in the order they are declared.
If you want them to have string values you have to declare them like

enum DistanceMeasure {
    Miles = 'MILES',
    Kilometers = 'KILOMETERS'
}


问:
How to convert numeric to nvarchar in SQL Server?
Consider the following table. I use a trigger to add to the table. In the column of converting the number to the string, it fails.</p>

```<code>CREATE TABLE [dbo].[tblAIAgent]
(
    [AgentCode] [NVARCHAR](10) NOT NULL,
    [NationalCode] [BIGINT] NOT NULL
         CONSTRAINT [DF_tblAIAgent_NationalCode]  DEFAULT ((0)),
    [FirstName] [NVARCHAR](50) NOT NULL
         CONSTRAINT [DF_tblAIAgent_Name] DEFAULT (''),
    [LastName] [NVARCHAR](50) NOT NULL
         CONSTRAINT [DF_tblAIAgent_Family] DEFAULT (''),
    [IsActive] [BIT] NOT NULL
         CONSTRAINT [DF_tblAIAgent_Active] DEFAULT ((1)),
    [Counter] [INT] IDENTITY(1,1) NOT NULL,

    CONSTRAINT [PK_tblAIAgent]
        PRIMARY KEY CLUSTERED
)

ALTER TRIGGER [dbo].[AgentInsert]
ON [dbo].[tblAIAgent]
INSTEAD OF INSERT
AS
BEGIN
    DECLARE @AgentCode NVARCHAR(10)
    DECLARE @NationalCode BIGINT
    DECLARE @FirstName NVARCHAR(50)
    DECLARE @LastName NVARCHAR(50)
    DECLARE @IsActive BIT
    DECLARE @CounterIs INT

    SET @CounterIs = @@IDENTITY

    SELECT
        @AgentCode = AgentCode,
        @NationalCode = NationalCode,
        @FirstName = FirstName,
        @LastName = LastName,
        @IsActive = IsActive
    FROM inserted

    INSERT INTO tblAIAgent (NationalCode, FirstName, LastName, IsActive, AgentCode)
    VALUES (@NationalCode, @FirstName, @LastName, @IsActive, 'Agent_' + CAST(@CounterIs AS NVARCHAR(4)))
END
</code>```

答:
```<code>SELECT CAST([PictureId] AS NVARCHAR(4)) From Category
</code>```

Body:
Consider the following table. I use a trigger to add to the table. In the column of converting the number to the string, it fails.

CREATE TABLE [dbo].[tblAIAgent]
(
    [AgentCode] [NVARCHAR](10) NOT NULL,
    [NationalCode] [BIGINT] NOT NULL
         CONSTRAINT [DF_tblAIAgent_NationalCode]  DEFAULT ((0)),
    [FirstName] [NVARCHAR](50) NOT NULL
         CONSTRAINT [DF_tblAIAgent_Name] DEFAULT (''),
    [LastName] [NVARCHAR](50) NOT NULL
         CONSTRAINT [DF_tblAIAgent_Family] DEFAULT (''),
    [IsActive] [BIT] NOT NULL
         CONSTRAINT [DF_tblAIAgent_Active] DEFAULT ((1)),
    [Counter] [INT] IDENTITY(1,1) NOT NULL,

    CONSTRAINT [PK_tblAIAgent]
        PRIMARY KEY CLUSTERED
)

ALTER TRIGGER [dbo].[AgentInsert]
ON [dbo].[tblAIAgent]
INSTEAD OF INSERT
AS
BEGIN
    DECLARE @AgentCode NVARCHAR(10)
    DECLARE @NationalCode BIGINT
    DECLARE @FirstName NVARCHAR(50)
    DECLARE @LastName NVARCHAR(50)
    DECLARE @IsActive BIT
    DECLARE @CounterIs INT

    SET @CounterIs = @@IDENTITY

    SELECT
        @AgentCode = AgentCode,
        @NationalCode = NationalCode,
        @FirstName = FirstName,
        @LastName = LastName,
        @IsActive = IsActive
    FROM inserted

    INSERT INTO tblAIAgent (NationalCode, FirstName, LastName, IsActive, AgentCode)
    VALUES (@NationalCode, @FirstName, @LastName, @IsActive, 'Agent_' + CAST(@CounterIs AS NVARCHAR(4)))
END


问:
How do I assign values to states once I open my edit form?
I'm trying to create my first simple CRUD front-end app in React. I have some problems with the edit form.

Whenever I display the edit form with fields filled with values of a chosen record, I need to edit each of the field in order to save it back to the database. If I don't change any of the fields values - including the id of a record - or change only one value, I get the error:
[GraphQL error]: Message: could not convert string to float: , Location: undefined, Path: undefined.
I am aware of the fact, that I can add Mutation in Query but then I get problems with refetching the updated list of records in the parent component and still get the error message mentioned above.

```<code>export class EditForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            id: '',
            name: '',
            price: '',
            category: ''
        };
        this.handleInputChange = this.handleInputChange.bind(this);
    }

    handleInputChange = (event) => {
        const target = event.target;
        const value = target.value;
        const name = target.name;

        this.setState({
            [name]: value
        });
    };

    updateSome = async () => {
      const {id, name, price, category} = this.state;
      await this.props.editOne({
          variables: {
              id,
              name,
              price,
              category
          },
          refetchQueries: [{ query: ones }]
      })
    };

    render() {
        return (
            <div>
                <Query query={GET_ONE} variables={{one: Number(this.props.id)}}>
        {({ loading, error, data, networkStatus }) => {
            if (loading) return "Loading...";
            if (error) return `Error! ${error.message}`;
            if (networkStatus === 4) return "Refetching!";
            return (
                <div>
                     {data.ones.map(one => (
                       <Form key={one.id}>
                    <Row>
                        <Col>
                        <Form.Group>
                        <Form.Label>ID</Form.Label>
                            <Form.Control
                                name='id'
                                defaultValue={one.id}
                                onChange={this.handleInputChange}
                                type="text"
                                placeholder="id"
                            />
                        </Form.Group>
                        </Col>
                        <Col>
                        <Form.Group>
                        <Form.Label>Name</Form.Label>
                            <Form.Control
                                name='name'
                                defaultValue={one.name}
                                onChange={this.handleInputChange}
                                type="text"
                                placeholder="name"
                            />
                        </Form.Group>
                        </Col>
                        <Col>
                        <Form.Group>
                            <Form.Label>Price</Form.Label>
                            <Form.Control
                                name='price'
                                defaultValue={one.price}
                                onChange={this.handleInputChange}
                                type="number"
                                step={0.01}
                                placeholder="price"
                            />
                        </Form.Group>
                        </Col>
                        <Col>
                        <Form.Group>
                            <Form.Label>Category</Form.Label>
                            <Query query={twos}>
                                {({loading, error, data}) => {
                                    if (loading) return <Spinner animation="border" role="status">
                                                <span className="sr-only">Loading...</span>
                                            </Spinner>;
                                    if (error) return `Error! ${error.message}`;
                                    return (
                                        <Form.Control name='category'
                                                      defaultValue={one.category.id}
                                                      onChange={this.handleInputChange}
                                                      as="select"
                                                      placeholder="category"
                                        >
                                            {data.twos.map(two => (
                                        <option key={two.id} value={two.id}>{two.category}</option>
                                                ))}
                                    </Form.Control>
                                    );
                                }}
                            </Query>
                        </Form.Group>
                        </Col>
                    </Row>
                    <ButtonToolbar>
                            <Button
                                variant="primary"
                                onClick={() => this.updateSome()}
                            >Update</Button>
                        </ButtonToolbar>
                </Form>
                    ))}
                </div>
            );
        }}
    </Query>
            </div>
        )
    }
}
</code>```

How do I assign initial values of a chosen record to this.state.id, this.state.name and so on, once the Component is displayed? I know how to enter some values to this.state in constructor by hand, but I want to pass the values that are displayed in the form fields to this.state.

答:
You probably know that using setState forces rerender and refetch in <Query/> component. Form component (with state and event handling) should be placed inside <Query/> to avoid that effect - getDerivedStateFromProps() for initial state.

In this case, wthout refactoring it's enough to conditionally setState in render, sth like:

```<code>            <Query query={GET_ONE} variables={{one: Number(this.props.id)}}>
    {({ loading, error, data, networkStatus }) => {
        if (loading) return "Loading...";
        if (error) return `Error! ${error.message}`;
        if (networkStatus === 4) return "Refetching!";

        // one-time flag, it can be undefined/uninitialized
        if (!this.state.initialized) {
          this.setState( {
            initialized: true, // block this block
            id: data.someField,
            name: data.someField,
            price: data.someField,
            category: data.someField
          })
        }

        return (
</code>```

GraphQL error probably refers to a price field, convert types in variables (within this.props.editOne call).

Body:
I'm trying to create my first simple CRUD front-end app in React. I have some problems with the edit form.

Whenever I display the edit form with fields filled with values of a chosen record, I need to edit each of the field in order to save it back to the database. If I don't change any of the fields values - including the id of a record - or change only one value, I get the error:
[GraphQL error]: Message: could not convert string to float: , Location: undefined, Path: undefined.
I am aware of the fact, that I can add Mutation in Query but then I get problems with refetching the updated list of records in the parent component and still get the error message mentioned above.

export class EditForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            id: '',
            name: '',
            price: '',
            category: ''
        };
        this.handleInputChange = this.handleInputChange.bind(this);
    }

    handleInputChange = (event) => {
        const target = event.target;
        const value = target.value;
        const name = target.name;

        this.setState({
            [name]: value
        });
    };

    updateSome = async () => {
      const {id, name, price, category} = this.state;
      await this.props.editOne({
          variables: {
              id,
              name,
              price,
              category
          },
          refetchQueries: [{ query: ones }]
      })
    };

    render() {
        return (

                <Query query={GET_ONE} variables={{one: Number(this.props.id)}}>
        {({ loading, error, data, networkStatus }) => {
            if (loading) return "Loading...";
            if (error) return `Error! ${error.message}`;
            if (networkStatus === 4) return "Refetching!";
            return (

                     {data.ones.map(one => (
                       <Form key={one.id}>
                    <Row>
                        <Col>
                        <Form.Group>
                        <Form.Label>ID</Form.Label>
                            <Form.Control
                                name='id'
                                defaultValue={one.id}
                                onChange={this.handleInputChange}
                                type="text"
                                placeholder="id"
                            />
                        </Form.Group>
                        </Col>
                        <Col>
                        <Form.Group>
                        <Form.Label>Name</Form.Label>
                            <Form.Control
                                name='name'
                                defaultValue={one.name}
                                onChange={this.handleInputChange}
                                type="text"
                                placeholder="name"
                            />
                        </Form.Group>
                        </Col>
                        <Col>
                        <Form.Group>
                            <Form.Label>Price</Form.Label>
                            <Form.Control
                                name='price'
                                defaultValue={one.price}
                                onChange={this.handleInputChange}
                                type="number"
                                step={0.01}
                                placeholder="price"
                            />
                        </Form.Group>
                        </Col>
                        <Col>
                        <Form.Group>
                            <Form.Label>Category</Form.Label>
                            <Query query={twos}>
                                {({loading, error, data}) => {
                                    if (loading) return <Spinner animation="border" role="status">
                                                Loading...
                                            </Spinner>;
                                    if (error) return `Error! ${error.message}`;
                                    return (
                                        <Form.Control name='category'
                                                      defaultValue={one.category.id}
                                                      onChange={this.handleInputChange}
                                                      as="select"
                                                      placeholder="category"
                                        >
                                            {data.twos.map(two => (
                                        <option key={two.id} value={two.id}>{two.category}</option>
                                                ))}
                                    </Form.Control>
                                    );
                                }}
                            </Query>
                        </Form.Group>
                        </Col>
                    </Row>
                    <ButtonToolbar>
                            <Button
                                variant="primary"
                                onClick={() => this.updateSome()}
                            >Update</Button>
                        </ButtonToolbar>
                </Form>
                    ))}

            );
        }}
    </Query>

        )
    }
}

How do I assign initial values of a chosen record to this.state.id, this.state.name and so on, once the Component is displayed? I know how to enter some values to this.state in constructor by hand, but I want to pass the values that are displayed in the form fields to this.state.

Body:
You probably know that using setState forces rerender and refetch in <Query/> component. Form component (with state and event handling) should be placed inside <Query/> to avoid that effect - getDerivedStateFromProps() for initial state.

In this case, wthout refactoring it's enough to conditionally setState in render, sth like:

            <Query query={GET_ONE} variables={{one: Number(this.props.id)}}>
    {({ loading, error, data, networkStatus }) => {
        if (loading) return "Loading...";
        if (error) return `Error! ${error.message}`;
        if (networkStatus === 4) return "Refetching!";

        // one-time flag, it can be undefined/uninitialized
        if (!this.state.initialized) {
          this.setState( {
            initialized: true, // block this block
            id: data.someField,
            name: data.someField,
            price: data.someField,
            category: data.someField
          })
        }

        return (

GraphQL error probably refers to a price field, convert types in variables (within this.props.editOne call).


问:
Simple csv import using concurrency
I try to solve this academic use case: parse a csv file and insert data in database with multithreading.

In Java, I wrote a solution which uses the main thread to read the data into a collection and then run 8 tasks concurrently to insert the data in database. With my 8 core machine, it does the job in almost 60s for a 1 million lines csv file (2 columns: title and price).

Then I try to write equivalent in haskell (with my beginner skills):

{-# LANGUAGE OverloadedStrings #-}

import Data.Text
import qualified Data.Text.IO as TIO
import Text.Parsec
import Text.Parsec.Text (Parser)
import Database.PostgreSQL.Simple
import Data.Int
import Control.Concurrent.Async

line :: Parser (Text,Text)
line = do
  title  <- many $ noneOf ","
  oneOf ","
  price <- many $ digit
  return (pack title,pack price)

file :: Parser [(Text,Text)]
file = line `endBy` newline

parseCsv :: SourceName -> Text -> Either ParseError [(Text,Text)]
parseCsv = parse file

parseCsvF :: FilePath -> IO (Either ParseError [(Text,Text)])
parseCsvF path = fmap (parseCsv path) $ TIO.readFile path

connectDB :: IO Connection
connectDB = connect (ConnectInfo { connectHost="localhost", connectPort=5432, connectUser="parser", connectPassword="parser", connectDatabase="parser"})

insertComic :: Connection -> (Text,Text) -> IO Int64
insertComic conn (title,price) = execute conn "INSERT INTO comics (title, price) VALUES (?,?)" [unpack title , unpack price]

main = do
  conn <- connectDB
  input <- parseCsvF "data.csv"
  let (Right x) = input
      inserts = Prelude.map (insertComic conn) x
      asyncs = Prelude.map async inserts
      waiters = Prelude.map waitForIt asyncs
  sequence waiters

waitForIt :: IO (Async Int64) -> IO Int64
waitForIt x =  x >>= \v -> wait v

```

```ghc -threaded injector.hs -o injector
./injector +RTS -N8
```

unfortunately it is very slow (several minutes...)

I guess I didn't use Async correctly. Could someone give me an example of solution to make this program using multithreading efficiently ?

答:
I put here a solution, probably not the best one but it easily achieve better performance than the java one with far less lines of code and without using specific multithreading mechanisms.

I use resource pool and chunk of 10000 lines for insertions.

```<code>{-# LANGUAGE OverloadedStrings #-}

import Data.Text
import qualified Data.Text.IO as TIO
import Text.Parsec
import Text.Parsec.Text (Parser)
import Database.PostgreSQL.Simple
import Data.Int
import Control.Concurrent.Async
import Data.Pool
import qualified Data.List.Split as Split
import System.CPUTime

line :: Parser (Text,Text)
line = do
  title  <- many $ noneOf ","
  oneOf ","
  price <- many $ digit
  return (pack title,pack price)

file :: Parser [(Text,Text)]
file = line `endBy` newline

parseCsv :: SourceName -> Text -> Either ParseError [(Text,Text)]
parseCsv = parse file

parseCsvF :: FilePath -> IO (Either ParseError [(Text,Text)])
parseCsvF path = fmap (parseCsv path) $ TIO.readFile path

connectionInfo :: ConnectInfo
connectionInfo = ConnectInfo {
  connectHost="localhost",
  connectPort=5432,
  connectUser="parser",
  connectPassword="parser",
  connectDatabase="parser"}

myPool :: IO (Pool Connection)
myPool = createPool (connect connectionInfo) close 1 10 10

insertComic :: Pool Connection -> [(Text , Text)] -> IO Int64
insertComic pool comic = withResource pool (\conn -> insertComic' conn comic)

insertComic' :: Connection -> [(Text,Text)] -> IO Int64
insertComic' conn comics = executeMany conn "INSERT INTO comics (title, price) VALUES (?,?)" comics

main = do
  start <- getCPUTime
  pool <- myPool
  input <- parseCsvF "data.csv"
  let (Right allComics) = input
      chunks =  Split.chunksOf 10000 allComics
      inserts = [ insertComic pool chunk  | chunk <- chunks]
  sequence inserts
  end <- getCPUTime
  putStrLn $ show $ fromIntegral (end-start) / 10^12

</code>```

```<code>ghc -threaded injector.hs -o injector
./injector +RTS -N8
</code>```

Title: Simple csv import using concurrency

Body:
I try to solve this academic use case: parse a csv file and insert data in database with multithreading.

In Java, I wrote a solution which uses the main thread to read the data into a collection and then run 8 tasks concurrently to insert the data in database. With my 8 core machine, it does the job in almost 60s for a 1 million lines csv file (2 columns: title and price).

Then I try to write equivalent in haskell (with my beginner skills):

{-# LANGUAGE OverloadedStrings #-}

import Data.Text
import qualified Data.Text.IO as TIO
import Text.Parsec
import Text.Parsec.Text (Parser)
import Database.PostgreSQL.Simple
import Data.Int
import Control.Concurrent.Async

line :: Parser (Text,Text)
line = do
  title  <- many $ noneOf ","
  oneOf ","
  price <- many $ digit
  return (pack title,pack price)

file :: Parser [(Text,Text)]
file = line `endBy` newline

parseCsv :: SourceName -> Text -> Either ParseError [(Text,Text)]
parseCsv = parse file

parseCsvF :: FilePath -> IO (Either ParseError [(Text,Text)])
parseCsvF path = fmap (parseCsv path) $ TIO.readFile path

connectDB :: IO Connection
connectDB = connect (ConnectInfo { connectHost="localhost", connectPort=5432, connectUser="parser", connectPassword="parser", connectDatabase="parser"})

insertComic :: Connection -> (Text,Text) -> IO Int64
insertComic conn (title,price) = execute conn "INSERT INTO comics (title, price) VALUES (?,?)" [unpack title , unpack price]

main = do
  conn <- connectDB
  input <- parseCsvF "data.csv"
  let (Right x) = input
      inserts = Prelude.map (insertComic conn) x
      asyncs = Prelude.map async inserts
      waiters = Prelude.map waitForIt asyncs
  sequence waiters

waitForIt :: IO (Async Int64) -> IO Int64
waitForIt x =  x >>= \v -> wait v

ghc -threaded injector.hs -o injector
./injector +RTS -N8

unfortunately it is very slow (several minutes...)

I guess I didn't use Async correctly. Could someone give me an example of solution to make this program using multithreading efficiently ?

Body:
I put here a solution, probably not the best one but it easily achieve better performance than the java one with far less lines of code and without using specific multithreading mechanisms.

I use resource pool and chunk of 10000 lines for insertions.

{-# LANGUAGE OverloadedStrings #-}

import Data.Text
import qualified Data.Text.IO as TIO
import Text.Parsec
import Text.Parsec.Text (Parser)
import Database.PostgreSQL.Simple
import Data.Int
import Control.Concurrent.Async
import Data.Pool
import qualified Data.List.Split as Split
import System.CPUTime

line :: Parser (Text,Text)
line = do
  title  <- many $ noneOf ","
  oneOf ","
  price <- many $ digit
  return (pack title,pack price)

file :: Parser [(Text,Text)]
file = line `endBy` newline

parseCsv :: SourceName -> Text -> Either ParseError [(Text,Text)]
parseCsv = parse file

parseCsvF :: FilePath -> IO (Either ParseError [(Text,Text)])
parseCsvF path = fmap (parseCsv path) $ TIO.readFile path

connectionInfo :: ConnectInfo
connectionInfo = ConnectInfo {
  connectHost="localhost",
  connectPort=5432,
  connectUser="parser",
  connectPassword="parser",
  connectDatabase="parser"}

myPool :: IO (Pool Connection)
myPool = createPool (connect connectionInfo) close 1 10 10

insertComic :: Pool Connection -> [(Text , Text)] -> IO Int64
insertComic pool comic = withResource pool (\conn -> insertComic' conn comic)

insertComic' :: Connection -> [(Text,Text)] -> IO Int64
insertComic' conn comics = executeMany conn "INSERT INTO comics (title, price) VALUES (?,?)" comics

main = do
  start <- getCPUTime
  pool <- myPool
  input <- parseCsvF "data.csv"
  let (Right allComics) = input
      chunks =  Split.chunksOf 10000 allComics
      inserts = [ insertComic pool chunk  | chunk <- chunks]
  sequence inserts
  end <- getCPUTime
  putStrLn $ show $ fromIntegral (end-start) / 10^12

ghc -threaded injector.hs -o injector
./injector +RTS -N8


问:
Stop Fluent Validation on first failure
i'm defining a validation for my Request objects.
I would like the validator to stop on the very first failure, not only the one on the same chain.
In the example below, if my TechnicalHeader object is null, i get a NullReference exception when the validation reaches the rule for TechnicalHeader.MCUserid.

In poor words, i would like to do a conditional validation over the last three rules in the code below, according to the result of the first rule

```<code>using System;
using ServiceStack.FluentValidation;
using MyProj.Services.Models;

namespace MyProj.Services.BaseService.Validators
{
    public class BaseValidator<T> : AbstractValidator<T>
        where T : RequestBase
    {
        public BaseValidator()
        {
            RuleSet(ServiceStack.ApplyTo.Put | ServiceStack.ApplyTo.Post,
                () =>
                {
                    this.CascadeMode = CascadeMode.StopOnFirstFailure;
                    RuleFor(x => x.TechnicalHeader).Cascade(CascadeMode.StopOnFirstFailure).NotNull().WithMessage("Header cannot be null");
                    RuleFor(x => x.TechnicalHeader).NotEmpty().WithMessage("Header cannot be null");
                    RuleFor(x => x.TechnicalHeader.Userid).NotEmpty().WithMessage("Userid cannot be null or an empty string");
                    RuleFor(x => x.TechnicalHeader.CabCode).GreaterThan(0).WithMessage("CabCode cannot be or less than 0");
                    RuleFor(x => x.TechnicalHeader.Ndg).NotEmpty().WithMessage("Ndg cannot be null or an empty string");
                }
            );
        }
    }
}
</code>```

答:
Just add SetValidator before running the rules that depend on them, using a Custom condition:

```<code>//if InpatOrderImportValidatorBllNode fail ,the custom method cannot be executed
RuleFor(x => x).Cascade(CascadeMode.StopOnFirstFailure)
               .SetValidator(new InpatOrderImportValidatorBllNode())
               .Custom((input, context) => {
                  context.AddFailure(new ValidationFailure("DrugTypeName", "fail"));
               });
</code>```

ContentLicense: CC BY-SA 3.0

Title: Stop Fluent Validation on first failure

Body:
i'm defining a validation for my Request objects.
I would like the validator to stop on the very first failure, not only the one on the same chain.
In the example below, if my TechnicalHeader object is null, i get a NullReference exception when the validation reaches the rule for TechnicalHeader.MCUserid.

In poor words, i would like to do a conditional validation over the last three rules in the code below, according to the result of the first rule

using System;
using ServiceStack.FluentValidation;
using MyProj.Services.Models;

namespace MyProj.Services.BaseService.Validators
{
    public class BaseValidator<T> : AbstractValidator<T>
        where T : RequestBase
    {
        public BaseValidator()
        {
            RuleSet(ServiceStack.ApplyTo.Put | ServiceStack.ApplyTo.Post,
                () =>
                {
                    this.CascadeMode = CascadeMode.StopOnFirstFailure;
                    RuleFor(x => x.TechnicalHeader).Cascade(CascadeMode.StopOnFirstFailure).NotNull().WithMessage("Header cannot be null");
                    RuleFor(x => x.TechnicalHeader).NotEmpty().WithMessage("Header cannot be null");
                    RuleFor(x => x.TechnicalHeader.Userid).NotEmpty().WithMessage("Userid cannot be null or an empty string");
                    RuleFor(x => x.TechnicalHeader.CabCode).GreaterThan(0).WithMessage("CabCode cannot be or less than 0");
                    RuleFor(x => x.TechnicalHeader.Ndg).NotEmpty().WithMessage("Ndg cannot be null or an empty string");
                }
            );
        }
    }
}

Body:
Just add SetValidator before running the rules that depend on them, using a Custom condition:

//if InpatOrderImportValidatorBllNode fail ,the custom method cannot be executed
RuleFor(x => x).Cascade(CascadeMode.StopOnFirstFailure)
               .SetValidator(new InpatOrderImportValidatorBllNode())
               .Custom((input, context) => {
                  context.AddFailure(new ValidationFailure("DrugTypeName", "fail"));
               });


问:
Getting linux to buffer /dev/random
I need a reasonable supply of high-quality random data for an application I'm writing. Linux provides the /dev/random file for this purpose which is ideal; however, because my server is a single-service virtual machine, it has very limited sources of entropy, meaning /dev/random quickly becomes exhausted.

I've noticed that if I read from /dev/random, I will only get 16 or so random bytes before the device blocks while it waits for more entropy:

```<code>[duke@poopz ~]# hexdump /dev/random
0000000 f4d3 8e1e 447a e0e3 d937 a595 1df9 d6c5
<process blocks...>
</code>```

If I terminate this process, go away for an hour and repeat the command, again only 16 or so bytes of random data are produced.

However - if instead I leave the command running for the same amount of time, much, much more random data are collected. I assume from this that over the course of a given timeperiod, the system produces plenty of entropy, but Linux only utilises it if you are actually reading from /dev/random, and discards it if you are not. If this is the case, my question is:

Is it possible to configure Linux to buffer /dev/random so that reading from it yields much larger bursts of high-quality random data?

It wouldn't be difficult for me to buffer /dev/random as part of my program but I feel doing this at a system level would be more elegant. I also wonder if having Linux buffer its random data in memory would have security implications.

答:
Use /dev/urandom.

A counterpart to /dev/random is
  /dev/urandom ("unlocked"/non-blocking
  random source[4]) which reuses the
  internal pool to produce more
  pseudo-random bits. This means that
  the call will not block, but the
  output may contain less entropy than
  the corresponding read from
  /dev/random. While it is still
  intended as a pseudorandom number
  generator suitable for most
  cryptographic purposes, it is not
  recommended for the generation of
  long-term cryptographic keys.

Title: Getting linux to buffer /dev/random

Body:
I need a reasonable supply of high-quality random data for an application I'm writing. Linux provides the /dev/random file for this purpose which is ideal; however, because my server is a single-service virtual machine, it has very limited sources of entropy, meaning /dev/random quickly becomes exhausted.

I've noticed that if I read from /dev/random, I will only get 16 or so random bytes before the device blocks while it waits for more entropy:

[duke@poopz ~]# hexdump /dev/random
0000000 f4d3 8e1e 447a e0e3 d937 a595 1df9 d6c5
<process blocks...>

If I terminate this process, go away for an hour and repeat the command, again only 16 or so bytes of random data are produced.

However - if instead I leave the command running for the same amount of time, much, much more random data are collected. I assume from this that over the course of a given timeperiod, the system produces plenty of entropy, but Linux only utilises it if you are actually reading from /dev/random, and discards it if you are not. If this is the case, my question is:

Is it possible to configure Linux to buffer /dev/random so that reading from it yields much larger bursts of high-quality random data?

It wouldn't be difficult for me to buffer /dev/random as part of my program but I feel doing this at a system level would be more elegant. I also wonder if having Linux buffer its random data in memory would have security implications.


问:
Python - Average of three values in a while true loop
I'm developing a python script on a raspberry pi with a distance sensor.
My code is working and i can reach the distance but I want to avoid some false positive/negative so I would like to get the average of the last three data.

Here is my code:

while True:
        distance= misura() # GETTING THE REAL DISTANCE IN CM
        print "Distanza : %.2f" % distanza

        avg_distance = <something> # <- HERE I NEED SOMETHING ELEGANT

        if (avg_distance > 30):
            print "NOT PRESENT"
        else:
            print "PRESENT"

        time.sleep(1.5)
```

I would like some function (maybe based on a list?) that returns the average of the last three (or n) distances

IMPORTANT:
I don't want to store ALL the values because this script will run for days and days

答:
You could take advantage of the fact that mutable default arguments are only created once, to store the last three values measured:

```<code>def last_three_average(val, last_three=[]):
    last_three.append(val)
    last_three = last_three[-3:]
    return sum(last_three) / len(last_three)

for idx in range(1, 10, 1):
    print(f'{idx}: {last_three_average(idx)}')
</code>```

output:

```<code>1: 1.0
2: 1.5
3: 2.0
4: 3.0
5: 4.0
6: 5.0
7: 6.0
8: 7.0
9: 8.0
</code>```

Or, using a deque i/o a list:

```<code>from collections import deque

def last_three_average(val, last_three=deque(maxlen=3)):
    last_three.append(val)
    return sum(last_three) / len(last_three)
</code>```

Body:
I'm developing a python script on a raspberry pi with a distance sensor.
My code is working and i can reach the distance but I want to avoid some false positive/negative so I would like to get the average of the last three data.

Here is my code:

while True:
        distance= misura() # GETTING THE REAL DISTANCE IN CM
        print "Distanza : %.2f" % distanza

        avg_distance = <something> # <- HERE I NEED SOMETHING ELEGANT

        if (avg_distance > 30):
            print "NOT PRESENT"
        else:
            print "PRESENT"

        time.sleep(1.5)

I would like some function (maybe based on a list?) that returns the average of the last three (or n) distances

IMPORTANT:
I don't want to store ALL the values because this script will run for days and days

Body:
You could take advantage of the fact that mutable default arguments are only created once, to store the last three values measured:

def last_three_average(val, last_three=[]):
    last_three.append(val)
    last_three = last_three[-3:]
    return sum(last_three) / len(last_three)

for idx in range(1, 10, 1):
    print(f'{idx}: {last_three_average(idx)}')

output:

1: 1.0
2: 1.5
3: 2.0
4: 3.0
5: 4.0
6: 5.0
7: 6.0
8: 7.0
9: 8.0

Or, using a deque i/o a list:

from collections import deque

def last_three_average(val, last_three=deque(maxlen=3)):
    last_three.append(val)
    return sum(last_three) / len(last_three)


问:
Tensorflow, Keras: How to create a trainable variable that only update in specific positions?
For example, y=Ax

where A is an diagonal matrix, with its trainable weights (w1, w2, w3) on the diagonal.

```<code>A = [w1 ... ...
    ...  w2 ...
    ... ... w3]
</code>```

How to create such trainable A in Tensorflow or Keras?

If I try A = tf.Variable(np.eye(3)), the total number of trainable weights would be 3*3=9, not 3. Because I only want to update (w1,w2,w3) that 3 weights.

A trick may be to use A = tf.Variable([1, 1, 1]) * np.eye(3), so that the 3 trainable weights are mapped into the diagonal of A.

My question is:

Would that trick work for my purpose? Would the gradient be correctly calculated?

What if the situation of A is more complicated? E.g. if I want to create:

where the w1, w2, ..., w6 are weights to be updated.

答:
For a more complex case where A needs to be divided in sections where only some parts are trainable and others can have arbitrary values, the easiest thing to do would be to build the individual sections and then concatenate them together.

For example I needed weight matrix A of arbitrary size that (for size 4x4) looks like this (4 distinct sections of 2x2):

```<code>#  [[0.,   0.,   -0.2,    0.],
#   [0.,   0.,   0.,      -0.2],
#   [0.35, 0.,   train,   train],
#   [0.,   0.35, train,   train]]
</code>```

Code to make this:

```<code>n_neurons = 3
zero_quarter = tf.zeros((n_neurons, n_neurons))  # upper left quarter are zeros
neg_diag = tf.diag(tf.ones(n_neurons) * -0.2)  # upper right is negative diag
pos_diag = tf.diag(tf.ones(n_neurons) * 0.35)  # lower left is positive diag
# lower right quarter is trainable randomly initialized vars
train_quarter = tf.get_variable(name='TrainableWeights', shape=[n_neurons, n_neurons])

weights_row0 = tf.concat([zero_quarter, neg_diag], axis=1)
weights_row1 = tf.concat([pos_diag, train_quarter], axis=1)

weights = tf.concat([weights_row0, weights_row1], axis=0)

sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run(weights))
</code>```

And the result is:

```<code>[[ 0.          0.          0.         -0.2         0.          0.        ]
 [ 0.          0.          0.          0.         -0.2         0.        ]
 [ 0.          0.          0.          0.          0.         -0.2       ]
 [ 0.35        0.          0.         -0.61401606  0.39812732  0.72078323]
 [ 0.          0.35        0.         -0.34560132  0.40494204  0.36660933]
 [ 0.          0.          0.35        0.34820676  0.5112138  -0.97605824]]
</code>```

where only the bottom right 3x3 section is trainable.

Body:
For example, y=Ax

where A is an diagonal matrix, with its trainable weights (w1, w2, w3) on the diagonal.

A = [w1 ... ...
    ...  w2 ...
    ... ... w3]

How to create such trainable A in Tensorflow or Keras?

If I try A = tf.Variable(np.eye(3)), the total number of trainable weights would be 3*3=9, not 3. Because I only want to update (w1,w2,w3) that 3 weights.

A trick may be to use A = tf.Variable([1, 1, 1]) * np.eye(3), so that the 3 trainable weights are mapped into the diagonal of A.

My question is:

Would that trick work for my purpose? Would the gradient be correctly calculated?

What if the situation of A is more complicated? E.g. if I want to create:

where the w1, w2, ..., w6 are weights to be updated.

Body:
For a more complex case where A needs to be divided in sections where only some parts are trainable and others can have arbitrary values, the easiest thing to do would be to build the individual sections and then concatenate them together.

For example I needed weight matrix A of arbitrary size that (for size 4x4) looks like this (4 distinct sections of 2x2):

#  [[0.,   0.,   -0.2,    0.],
#   [0.,   0.,   0.,      -0.2],
#   [0.35, 0.,   train,   train],
#   [0.,   0.35, train,   train]]

Code to make this:

n_neurons = 3
zero_quarter = tf.zeros((n_neurons, n_neurons))  # upper left quarter are zeros
neg_diag = tf.diag(tf.ones(n_neurons) * -0.2)  # upper right is negative diag
pos_diag = tf.diag(tf.ones(n_neurons) * 0.35)  # lower left is positive diag
# lower right quarter is trainable randomly initialized vars
train_quarter = tf.get_variable(name='TrainableWeights', shape=[n_neurons, n_neurons])

weights_row0 = tf.concat([zero_quarter, neg_diag], axis=1)
weights_row1 = tf.concat([pos_diag, train_quarter], axis=1)

weights = tf.concat([weights_row0, weights_row1], axis=0)

sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run(weights))

And the result is:

[[ 0.          0.          0.         -0.2         0.          0.        ]
 [ 0.          0.          0.          0.         -0.2         0.        ]
 [ 0.          0.          0.          0.          0.         -0.2       ]
 [ 0.35        0.          0.         -0.61401606  0.39812732  0.72078323]
 [ 0.          0.35        0.         -0.34560132  0.40494204  0.36660933]
 [ 0.          0.          0.35        0.34820676  0.5112138  -0.97605824]]

where only the bottom right 3x3 section is trainable.


问:
Can i use solrj (version - 6.6.3 ) client library against solr server with lower version(5.xx or 4.xx)?
I am currently using following solr dependency in my java project:

```<code>   <dependency>
        <groupId>org.apache.solr</groupId>
        <artifactId>solr-solrj</artifactId>
        <version>6.6.3</version>
        <scope>compile</scope>
    </dependency>
</code>```

And my solr server version is 4.xx , do i need to upgrade my solr server version or it is backward compatible?

答:
There's a major change in how the state for the collections are stored - in earlier Solr versions the cloud state for each collection was stored in one single file on the root in Zookeeper, but this changed later to instead keep the state for each collection in its own state file.

The more recent version of SolrJ probably expects to have per collection state instead of the global state, so if you're using the cloud mode, you should use the same version of SolrJ as you use for Solr.

For using the standard http interface for single cores, there shouldn't be much difference (I don't think the javabin format has changed for example), except for features that are only supported on newer versions of Solr than 4.

But the main question then is; if you're actually managing your dependencies properly with Maven; why not use the SolrJ library that is actually designed for your Solr version, instead of risking any possible incompatibilities in weird edge cases? I'd go with the same version of SolrJ as the version you're using for Solr.

Body:
I am currently using following solr dependency in my java project:

   <dependency>
        <groupId>org.apache.solr</groupId>
        <artifactId>solr-solrj</artifactId>
        <version>6.6.3</version>
        <scope>compile</scope>
    </dependency>

And my solr server version is 4.xx , do i need to upgrade my solr server version or it is backward compatible?


问:
Fortran: Short form for "do loop"
Hey there,
I have a code like that:

```<code>write (filehandle,'(5e14.6)')
     &    (((my_array(i,j,k,1),i=istart,iend,istep),j=jstart,jend,jstep),k=kstart,kend,kstep)
</code>```

is this a short form for a "do-loop"? I couldn't find anything about it on google...
Furthermore, I'm getting an error:

forrtl: severe (71): integer divide by
  zero Image              PC

  Routine            Line        Source
  libpthread.so.0    00007F473F0D892B
  Unknown               Unknown  Unknown
  libguide.so        00007F473F3CC20E
  Unknown               Unknown  Unknown

when executing the program (program is parallelized with OpenMP) about THIS line (removing the line removes the error-msg). What could be the cause about it?
Thanks!

答:
As already answered, that is an implicit do-loop.

Could istep, jstep or kstep by zero?   That might lead to integer divide by zero, as the program tried to compute the number of loop iterations.

Does the program run correctly when you compile without OpenMP?

Title: Fortran: Short form for "do loop"

Body:
Hey there,
I have a code like that:

write (filehandle,'(5e14.6)')
     &    (((my_array(i,j,k,1),i=istart,iend,istep),j=jstart,jend,jstep),k=kstart,kend,kstep)

is this a short form for a "do-loop"? I couldn't find anything about it on google...
Furthermore, I'm getting an error:

forrtl: severe (71): integer divide by
  zero Image              PC

  Routine            Line        Source
  libpthread.so.0    00007F473F0D892B
  Unknown               Unknown  Unknown
  libguide.so        00007F473F3CC20E
  Unknown               Unknown  Unknown

when executing the program (program is parallelized with OpenMP) about THIS line (removing the line removes the error-msg). What could be the cause about it?
Thanks!


答:
Const enums can only use constant enum expressions and unlike regular enums they are completely removed during compilation. Const enum members are inlined at use sites. This is possible since const enums cannot have computed members.

So, from your enum you can create a new variable distanceMeasure to use it like as an array:

```<code>export enum DistanceMeasure {
  Miles, Kilometers
}

const distanceMeasure = [DistanceMeasure.Miles, DistanceMeasure.Kilometers];

console.log(distanceMeasure[0]); // --> Miles
</code>```

Read more about TypeScript Enums at: https://www.typescriptlang.org/docs/handbook/enums.html

Title: Extract string value of an ENUM in a Typescript Object

Body:
Const enums can only use constant enum expressions and unlike regular enums they are completely removed during compilation. Const enum members are inlined at use sites. This is possible since const enums cannot have computed members.

So, from your enum you can create a new variable distanceMeasure to use it like as an array:

export enum DistanceMeasure {
  Miles, Kilometers
}

const distanceMeasure = [DistanceMeasure.Miles, DistanceMeasure.Kilometers];

console.log(distanceMeasure[0]); // --> Miles

Read more about TypeScript Enums at: https://www.typescriptlang.org/docs/handbook/enums.html


问:
Java best practices static final map values
I have a utility class which contains a static final map with some values. I need to access to this map in another class. Should I just declare the map as public, or should I write a getter inside the utility class, and therefore let the map be private?

Both ways work, but what are the best practices?

```<code>public MyUtilityClass {
  public static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      "title", 256,
      "text", 512);

}

public MyAnotherClass {

  public void someMethod() {
    //accessing the map directly
    MAX_LENGTHS.get("title")
  }

}
</code>```

Or

```<code>public MyUtilityClass {
  private static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      "title", 256,
      "text", 512);

  public static final getMaxLengthMap() {return MAX_LENGTHS;}
}

public MyAnotherClass {
  public void someMethod() {
    //accessing the map directly
    getMaxLengthMap().get("title")
  }
}
</code>```

Well, actually the keys are enum values.
Something like :

```<code>private static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      MyEnumClass.TITLE, 256,
      MyEnumClass.TEXT, 512);
</code>```

答:
I have to say that you're probably just better of using an Enum in the first place. As this mapping seems to be always completly static:

```<code>public enum MaxLength {
    TITLE(256),
    TEXT(512);

    public final int value;

    MaxLength(int value) {
        this.value= value;
    }
}
</code>```

No more need for that utility class, you can now just get the value directly:

```<code>int length = MaxLength.TITLE.value;
</code>```

Body:
I have a utility class which contains a static final map with some values. I need to access to this map in another class. Should I just declare the map as public, or should I write a getter inside the utility class, and therefore let the map be private?

Both ways work, but what are the best practices?

public MyUtilityClass {
  public static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      "title", 256,
      "text", 512);

}

public MyAnotherClass {

  public void someMethod() {
    //accessing the map directly
    MAX_LENGTHS.get("title")
  }

}

Or

public MyUtilityClass {
  private static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      "title", 256,
      "text", 512);

  public static final getMaxLengthMap() {return MAX_LENGTHS;}
}

public MyAnotherClass {
  public void someMethod() {
    //accessing the map directly
    getMaxLengthMap().get("title")
  }
}

Well, actually the keys are enum values.
Something like :

private static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      MyEnumClass.TITLE, 256,
      MyEnumClass.TEXT, 512);

Body:
I have to say that you're probably just better of using an Enum in the first place. As this mapping seems to be always completly static:

public enum MaxLength {
    TITLE(256),
    TEXT(512);

    public final int value;

    MaxLength(int value) {
        this.value= value;
    }
}

No more need for that utility class, you can now just get the value directly:

int length = MaxLength.TITLE.value;


问:
How to find the first logical unit in dword in ARM Assembly?
I want to know how I can find the first logical unit(single bit) in a dword with registers R0 and R1, for example, from right to left. How can I achieve the described above?

I have tried iterating through the elements of a dword, but I do not seem to understand what's expected from me correctly. Also tried to shift right and left, with no luck overall.

```<code>MOV R2, R0, LSR #31
loop:
MOVS R0, R0, LSL #2
ADC R2, R2, R0, LSR #31
bne loop
</code>```

I want to use the previously described for finding the current index of the single bit

答:
You can use CLZto count the leading zeros. By subtracting the leading zeros from 31 you can the get the location of the first 1 in a byte.

```<code>CLZ R1, R0
RSB R1, R1, #31
</code>```

R0 contains the DWORD you want to work on.

R1 at the end contains the "first logical unit".

The CLZ instruction counts the number of leading zeros in the value in Rm and returns the result in Rd. The result value is 32 if no bits are set in the source register, and zero if bit 31 is set.

When the S optional suffix is added to RSB the condition flags will be updated and a #0 register can be detected.

Body:
I want to know how I can find the first logical unit(single bit) in a dword with registers R0 and R1, for example, from right to left. How can I achieve the described above?

I have tried iterating through the elements of a dword, but I do not seem to understand what's expected from me correctly. Also tried to shift right and left, with no luck overall.

MOV R2, R0, LSR #31
loop:
MOVS R0, R0, LSL #2
ADC R2, R2, R0, LSR #31
bne loop

I want to use the previously described for finding the current index of the single bit

Body:
You can use CLZto count the leading zeros. By subtracting the leading zeros from 31 you can the get the location of the first 1 in a byte.

CLZ R1, R0
RSB R1, R1, #31

R0 contains the DWORD you want to work on.

R1 at the end contains the "first logical unit".

The CLZ instruction counts the number of leading zeros in the value in Rm and returns the result in Rd. The result value is 32 if no bits are set in the source register, and zero if bit 31 is set.

When the S optional suffix is added to RSB the condition flags will be updated and a #0 register can be detected.