问:
ggplot2 return an empty plot after rotating x-lables
I got a data for comparing two genomes (column 1 and 2) and their similarity with the index indicating the number of genomes comparisons for the species:

```<code> Genome1               Genome2             % of similarity 1 in 2   % of similarity 2 in 1       Species        index
 1: GCF_001956585.1 GCF_002860635.1                  65.2                  65.0      Actinomyces_naeslundii     1
 2: GCF_001937545.1 GCF_001937675.1                  78.8                  79.1            Actinomyces_oris     1
 3: GCF_001937545.1 GCF_001937725.1                  80.9                  73.5            Actinomyces_oris     2
 4: GCF_001937675.1 GCF_001937725.1                  78.4                  71.1            Actinomyces_oris     3
 5: GCF_001262035.1 GCF_003130125.1                  92.6                  93.5 Aggregatibacter_aphrophilus     1
 6: GCF_001262035.1 GCF_003252995.1                  82.8                  84.3 Aggregatibacter_aphrophilus     2
 7: GCF_003130125.1 GCF_003252995.1                  84.5                  84.8 Aggregatibacter_aphrophilus     3
 8: GCF_001059425.1 GCF_003130095.1                  92.4                  89.3      Aggregatibacter_segnis     1
 9: GCF_001059425.1 GCF_003252685.1                  90.1                  90.1      Aggregatibacter_segnis     2
10: GCF_003130095.1 GCF_003252685.1                  87.0                  89.8      Aggregatibacter_segnis     3
</code>```

I was trying to rotate the x-labels of a geom_points graph.

The label was successfully rotated but the graph was empty (show no data).

```<code>g <- ggplot(data = compareset, aes(x = Species, y =`% of similarity 1 in 2`, col = index))
g + geom_point()
g + theme(axis.text.x = element_text(angle = 90, hjust = 1))
</code>```

答:
The code works for me. See here

Data

```<code>set.seed(1)
myFun <- function(n) {
  a <- do.call(paste0, replicate(5, sample(LETTERS, n, TRUE), FALSE))
  paste0(a, sprintf("%04d", sample(9999, n, TRUE)), sample(LETTERS, n, TRUE))
}

n <- 20
compareset <- data.frame(Species= myFun(n=n), y= rnorm(n), index= factor(rep(c(1,2), n/2)))
</code>```

Your code

```<code>library(ggplot2)

g <- ggplot(data = compareset, aes(x = Species, y = y, col = index))
g <- g + geom_point()
g <- g + theme(axis.text.x = element_text(angle = 90, hjust = 1))
g
</code>```

As Z.Lin points out you didn't save the result of g + geom_point() back to g. This is what I did "automatically" while using your code and it worked. So this is what you should try.

EDIT

Thanks for the data. With reassigning new changes to g it works. Here:

```<code>compareset <- data.frame(similarity= c(65.2, 78.8, 80.9, 78.4, 92.6,
                                       82.8, 84.5, 92.4, 90.1, 87.0),
                         Species= c("Actinomyces_naeslundii1", "Actinomyces_oris1", "Actinomyces_oris2", "Actinomyces_oris3", "Aggregatibacter_aphrophilus1",
                                  "Aggregatibacter_aphrophilus2", "Aggregatibacter_aphrophilus3", "Aggregatibacter_segnis1", "Aggregatibacter_segnis2", "Aggregatibacter_segnis3"),
                         index= c(1,1,2,3,1,2,3,1,2,3))

g <- ggplot(data = compareset, aes(x = Species, y = similarity, col = index))
g <- g + geom_point()
g <- g + theme(axis.text.x = element_text(angle = 90, hjust = 1))
g
</code>```

Body:
I got a data for comparing two genomes (column 1 and 2) and their similarity with the index indicating the number of genomes comparisons for the species:

 Genome1               Genome2             % of similarity 1 in 2   % of similarity 2 in 1       Species        index
 1: GCF_001956585.1 GCF_002860635.1                  65.2                  65.0      Actinomyces_naeslundii     1
 2: GCF_001937545.1 GCF_001937675.1                  78.8                  79.1            Actinomyces_oris     1
 3: GCF_001937545.1 GCF_001937725.1                  80.9                  73.5            Actinomyces_oris     2
 4: GCF_001937675.1 GCF_001937725.1                  78.4                  71.1            Actinomyces_oris     3
 5: GCF_001262035.1 GCF_003130125.1                  92.6                  93.5 Aggregatibacter_aphrophilus     1
 6: GCF_001262035.1 GCF_003252995.1                  82.8                  84.3 Aggregatibacter_aphrophilus     2
 7: GCF_003130125.1 GCF_003252995.1                  84.5                  84.8 Aggregatibacter_aphrophilus     3
 8: GCF_001059425.1 GCF_003130095.1                  92.4                  89.3      Aggregatibacter_segnis     1
 9: GCF_001059425.1 GCF_003252685.1                  90.1                  90.1      Aggregatibacter_segnis     2
10: GCF_003130095.1 GCF_003252685.1                  87.0                  89.8      Aggregatibacter_segnis     3

I was trying to rotate the x-labels of a geom_points graph.

The label was successfully rotated but the graph was empty (show no data).

g <- ggplot(data = compareset, aes(x = Species, y =`% of similarity 1 in 2`, col = index))
g + geom_point()
g + theme(axis.text.x = element_text(angle = 90, hjust = 1))

Body:
The code works for me. See here

Data

set.seed(1)
myFun <- function(n) {
  a <- do.call(paste0, replicate(5, sample(LETTERS, n, TRUE), FALSE))
  paste0(a, sprintf("%04d", sample(9999, n, TRUE)), sample(LETTERS, n, TRUE))
}

n <- 20
compareset <- data.frame(Species= myFun(n=n), y= rnorm(n), index= factor(rep(c(1,2), n/2)))

Your code

library(ggplot2)

g <- ggplot(data = compareset, aes(x = Species, y = y, col = index))
g <- g + geom_point()
g <- g + theme(axis.text.x = element_text(angle = 90, hjust = 1))
g

As Z.Lin points out you didn't save the result of g + geom_point() back to g. This is what I did "automatically" while using your code and it worked. So this is what you should try.

EDIT

Thanks for the data. With reassigning new changes to g it works. Here:

compareset <- data.frame(similarity= c(65.2, 78.8, 80.9, 78.4, 92.6,
                                       82.8, 84.5, 92.4, 90.1, 87.0),
                         Species= c("Actinomyces_naeslundii1", "Actinomyces_oris1", "Actinomyces_oris2", "Actinomyces_oris3", "Aggregatibacter_aphrophilus1",
                                  "Aggregatibacter_aphrophilus2", "Aggregatibacter_aphrophilus3", "Aggregatibacter_segnis1", "Aggregatibacter_segnis2", "Aggregatibacter_segnis3"),
                         index= c(1,1,2,3,1,2,3,1,2,3))

g <- ggplot(data = compareset, aes(x = Species, y = similarity, col = index))
g <- g + geom_point()
g <- g + theme(axis.text.x = element_text(angle = 90, hjust = 1))
g


来源: stackexchange

问:
Spring Data JPA - Many to many query
I have two entities Person and Movie.

```<code>@Entity
public class Person {
..some fields

@ManyToMany(fetch = FetchType.LAZY, mappedBy = "actors")
@OrderBy("id")
private Set<Movie> moviesActor = new TreeSet<>();

}

@Entity
public class Movie {
..fields
@JoinTable(name = "actor_movie",
            joinColumns = { @JoinColumn(name = "movie_id") },
            inverseJoinColumns = { @JoinColumn(name = "actor_id") })
    private Set<Person> actors = new TreeSet<>();
}
</code>```

There is many to many relationship so there is new table actor_movie to keep it. And how can I get every person that has any movie in its set? So what I want is to achieve is get every person that exists in actor_movie table. I tried used Spring data jpa but couldn't find right query.

答:
You can use join  directely :

```<code>@Query("SELECT p FROM Person p  JOIN  p.moviesActor movie");
</code>```

List findPersonHasMovie();

ContentLicense: CC BY-SA 4.0

Title: Spring Data JPA - Many to many query

Body:
I have two entities Person and Movie.

@Entity
public class Person {
..some fields

@ManyToMany(fetch = FetchType.LAZY, mappedBy = "actors")
@OrderBy("id")
private Set<Movie> moviesActor = new TreeSet<>();

}

@Entity
public class Movie {
..fields
@JoinTable(name = "actor_movie",
            joinColumns = { @JoinColumn(name = "movie_id") },
            inverseJoinColumns = { @JoinColumn(name = "actor_id") })
    private Set<Person> actors = new TreeSet<>();
}

There is many to many relationship so there is new table actor_movie to keep it. And how can I get every person that has any movie in its set? So what I want is to achieve is get every person that exists in actor_movie table. I tried used Spring data jpa but couldn't find right query.

Body:
You can use join  directely :

@Query("SELECT p FROM Person p  JOIN  p.moviesActor movie");

List findPersonHasMovie();


问:
How do I prevent handheld devices from opening the keyboard when using a canvas signature pad?
I have a little confirmation window in my app where the user has to enter a name and message, then put their signature. My problem is that when a user enters a name, the focus of the application doesn't do a away the moment someone uses the signature pad, causing the virtual keyboard to pup up the moment the user releases their finger from the touch screen. This focus problem only seems to occur on mobile devices and happens on both android and apple devices.

I've tried using JQuery and Javascript and even Knockout solutions like focus.blur and .focus() but nothing seems to work. It's like clicking on the HTML5 canvas on mobile devices doesn't take away focus.

```<code><div class="row">
    <div class="col-md-6">
        <form-group params="value: NameSignatory, attr: {'data-test-id':'name'}"></form-group>
        <form-group params="value: EmailSignatory, attr: {'data-test-id':'email'}"></form-group>
        <form-group params="value: SignatoryComment, attr: {'data-test-id':'comment'}"></form-group>

        <div> </div>
        <div> </div>
        <div> </div>
    </div>
    <div class="col-md-6">
        <div class="form-group has-feedback" data-bind="validationElement: SignatureJson">
            <label class="large">Put your signature here:</label>
            <em class="help-block" data-bind="validationMessage: SignatureJson"></em>
            <signature-pad-v2 params="json: SignatureJson, imageUrl: ImageFileUrl"></signature-pad-v2>

        </div>
    </div>
</div>
</code>```

Script:

```<code>define([
    "knockout",
    "jquery",
    "szimek-signature-pad",
    "text!./signature-pad-v2.html"
], function (ko, $, SignaturePad, template) {

    return {
        template: template,
        viewModel: {
            createViewModel: function (params, componentInfo) {
                var canvas,
                    signaturePad,
                    clearButton,
                    $element = $(componentInfo.element),
                    imageUrl = params.imageUrl ? params.imageUrl : ko.observable(),
                    json = params.json ? params.json : ko.observable(),
                    variableBorder = params.variableBorder ? params.variableBorder : ko.observable(1)
                    ;

                var callbacks = {
                    regenerateFromJson: function (data) {
                        signaturePad.fromData(data);
                    },
                    regenerateFromDataUrl: function (data) {
                        signaturePad.fromDataURL(data);
                    }
                };

                if (params.context) {
                    params.context(callbacks);
                }

                return {
                    init: function () {
                        console.log('signature-pad-v2 started', $element);
                        canvas = $element.find("canvas").get(0);
                        signaturePad = new SignaturePad(canvas,
                            {
                                minWidth: 1,
                                maxWidth: 2,
                                penColor: "rgb(51,97,155)",
                                backgroundColor: "rgb(255,255,255)",
                                onEnd: function () {
                                    json(signaturePad.toData());
                                    imageUrl(signaturePad.toDataURL());
                                }
                            });

                        document.getElementById("signature-pad-v2").style.border = ko.unwrap(variableBorder) + "px solid #c0c0c0";

                        clearButton = $element.find(".clearButton a");

                        clearButton.bind("click", function (evt) {
                            evt.preventDefault();
                            signaturePad.clear();
                            return true;
                        });

                        if (imageUrl()) {
                            signaturePad.fromDataURL(imageUrl());
                        }
                        else {
                            if (json()) {
                                signaturePad.fromData(json());
                            }
                        }

                        if (params.context) {
                            params.context(callbacks);
                        }

                    }
                };

            }
        }
    };

});
</code>```

When the user puts their signature on a mobile device, focus doesn't get removed from the text fields and the keyboard will pop up once they release their finger. An annoying little inconvenience.

答:
Without a complete example, it is difficult to say what the problem is, but since you are using jQuery try to blur the active element as follows:

```<code>$('canvas').on('mousedown', function (e) {
    document.activeElement.blur();
});
</code>```

Also, if it doesn't work, try to disable the default action by adding e.preventDefault();

Body:
I have a little confirmation window in my app where the user has to enter a name and message, then put their signature. My problem is that when a user enters a name, the focus of the application doesn't do a away the moment someone uses the signature pad, causing the virtual keyboard to pup up the moment the user releases their finger from the touch screen. This focus problem only seems to occur on mobile devices and happens on both android and apple devices.

I've tried using JQuery and Javascript and even Knockout solutions like focus.blur and .focus() but nothing seems to work. It's like clicking on the HTML5 canvas on mobile devices doesn't take away focus.

        <form-group params="value: NameSignatory, attr: {'data-test-id':'name'}"></form-group>
        <form-group params="value: EmailSignatory, attr: {'data-test-id':'email'}"></form-group>
        <form-group params="value: SignatoryComment, attr: {'data-test-id':'comment'}"></form-group>

            Put your signature here:

            <signature-pad-v2 params="json: SignatureJson, imageUrl: ImageFileUrl"></signature-pad-v2>

Script:

define([
    "knockout",
    "jquery",
    "szimek-signature-pad",
    "text!./signature-pad-v2.html"
], function (ko, $, SignaturePad, template) {

    return {
        template: template,
        viewModel: {
            createViewModel: function (params, componentInfo) {
                var canvas,
                    signaturePad,
                    clearButton,
                    $element = $(componentInfo.element),
                    imageUrl = params.imageUrl ? params.imageUrl : ko.observable(),
                    json = params.json ? params.json : ko.observable(),
                    variableBorder = params.variableBorder ? params.variableBorder : ko.observable(1)
                    ;

                var callbacks = {
                    regenerateFromJson: function (data) {
                        signaturePad.fromData(data);
                    },
                    regenerateFromDataUrl: function (data) {
                        signaturePad.fromDataURL(data);
                    }
                };

                if (params.context) {
                    params.context(callbacks);
                }

                return {
                    init: function () {
                        console.log('signature-pad-v2 started', $element);
                        canvas = $element.find("canvas").get(0);
                        signaturePad = new SignaturePad(canvas,
                            {
                                minWidth: 1,
                                maxWidth: 2,
                                penColor: "rgb(51,97,155)",
                                backgroundColor: "rgb(255,255,255)",
                                onEnd: function () {
                                    json(signaturePad.toData());
                                    imageUrl(signaturePad.toDataURL());
                                }
                            });

                        document.getElementById("signature-pad-v2").style.border = ko.unwrap(variableBorder) + "px solid #c0c0c0";

                        clearButton = $element.find(".clearButton a");

                        clearButton.bind("click", function (evt) {
                            evt.preventDefault();
                            signaturePad.clear();
                            return true;
                        });

                        if (imageUrl()) {
                            signaturePad.fromDataURL(imageUrl());
                        }
                        else {
                            if (json()) {
                                signaturePad.fromData(json());
                            }
                        }

                        if (params.context) {
                            params.context(callbacks);
                        }

                    }
                };

            }
        }
    };

});

When the user puts their signature on a mobile device, focus doesn't get removed from the text fields and the keyboard will pop up once they release their finger. An annoying little inconvenience.

Body:
Without a complete example, it is difficult to say what the problem is, but since you are using jQuery try to blur the active element as follows:

$('canvas').on('mousedown', function (e) {
    document.activeElement.blur();
});

Also, if it doesn't work, try to disable the default action by adding e.preventDefault();


问:
Is there a SciPy method to autocrop an image, i. e. trim zeros from a 2d `numpy.ndarray`?
For 1d numpy.ndarray there is numpy.trim_zeros. Which method from numpy or scipy can I use to trim zeros for 2d arrays?

```<code>>>> import numpy as np
>>> a = np.array([[0, 0, 0, 0], [4, 1, 2, 0], [0, 3, 6, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
>>> a
array([[0, 0, 0, 0],
       [4, 1, 2, 0],
       [0, 3, 6, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0]])
</code>```

The result I'd like to get:

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

答:
You can try a list comprehension with some numpy methods:

```<code>>>> np.array([sub[~(sub == 0)].tolist() for sub in a if sub[sub != 0].tolist()])
array([[4, 1, 2], [3, 6]], dtype=object)
>>>
</code>```

Body:
For 1d numpy.ndarray there is numpy.trim_zeros. Which method from numpy or scipy can I use to trim zeros for 2d arrays?

>>> import numpy as np
>>> a = np.array([[0, 0, 0, 0], [4, 1, 2, 0], [0, 3, 6, 0], [0, 0, 0, 0], [0, 0, 0, 0]])
>>> a
array([[0, 0, 0, 0],
       [4, 1, 2, 0],
       [0, 3, 6, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0]])

The result I'd like to get:

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

Body:
You can try a list comprehension with some numpy methods:

>>> np.array([sub[~(sub == 0)].tolist() for sub in a if sub[sub != 0].tolist()])
array([[4, 1, 2], [3, 6]], dtype=object)
>>>


问:
How does c# create an instance of Array abstract class behind the scene for arrays?

I mean what happens when we initialize this syntactic sugar?

```<code>var numbers = new int[] { 1, 2, 3, 4 };
</code>```

答:
As pointed out in comments, you can use Sharplab.io to see the generated IL.

I recommend HOW C# ARRAY INITIALIZERS WORK article to appreciate the details.
In particular:

it allocates a temporary array (to ensure that assignment is atomic)

it calls System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array, valuetype [mscorlib]System.RuntimeFieldHandle)

the value passed in to the above method comes from internal class called containing a private nested struct called __StaticArrayInitTypeSize=16

after the call, the initialized temporary is assigned to numbers variable.

Body:
I mean what happens when we initialize this syntactic sugar?

var numbers = new int[] { 1, 2, 3, 4 };


问:
Spring WebFlux File Upload: Unsupported Media Type 415 with Multipart upload
I'm running into some issues handling a file upload using spring's reactive framework. I think I'm following the docs, but can't get away from this 415 / Unsupported Media Type issue.

My controller looks like below (as per the example here: https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-multipart-forms)

```<code>package com.test.controllers;

import reactor.core.publisher.Flux;

import org.springframework.http.MediaType;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.http.codec.multipart.Part;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @RequestMapping(value = "/upload", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public Flux<String> uploadHandler(@RequestBody Flux<Part> parts) {
        return parts
                .filter(part -> part instanceof FilePart)
                .ofType(FilePart.class)
                .log()
                .flatMap(p -> Flux.just(p.filename()));
    }

}
</code>```

POSTing to this endpoint though, always gives me the same output:

```<code>curl -X POST -F "data=@basic.ppt" http://localhost:8080/upload
---
"Unsupported Media Type","message":"Content type 'multipart/form-data;boundary=------------------------537139718d79303c;charset=UTF-8' not supported"
</code>```

I've attempted to use @RequestPart("data") too, but get a similar Unsupported Media Type error, albeit with the content type of the file.

It seems that Spring is having issues converting these to a Part..? I'm stuck - any help is apprecitated!

答:
Thanks @kojot for your answer, but in this case I discovered the issue was my inclusion of spring-webmvc transiently in addition to spring-webflux. Your solution would likely have worked too, but I wanted to stick with the Controller style so ended up forcibly excluding spring-webmvc from my build.gradle:

```<code>configurations {
    implementation {
        exclude group: 'org.springframework', module: 'spring-webmvc'
    }
}
</code>```

After that it worked as documented.

Body:
I'm running into some issues handling a file upload using spring's reactive framework. I think I'm following the docs, but can't get away from this 415 / Unsupported Media Type issue.

My controller looks like below (as per the example here: https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html#webflux-multipart-forms)

package com.test.controllers;

import reactor.core.publisher.Flux;

import org.springframework.http.MediaType;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.http.codec.multipart.Part;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @RequestMapping(value = "/upload", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public Flux<String> uploadHandler(@RequestBody Flux<Part> parts) {
        return parts
                .filter(part -> part instanceof FilePart)
                .ofType(FilePart.class)
                .log()
                .flatMap(p -> Flux.just(p.filename()));
    }

}

POSTing to this endpoint though, always gives me the same output:

curl -X POST -F "data=@basic.ppt" http://localhost:8080/upload
---
"Unsupported Media Type","message":"Content type 'multipart/form-data;boundary=------------------------537139718d79303c;charset=UTF-8' not supported"

I've attempted to use @RequestPart("data") too, but get a similar Unsupported Media Type error, albeit with the content type of the file.

It seems that Spring is having issues converting these to a Part..? I'm stuck - any help is apprecitated!

Body:
Thanks @kojot for your answer, but in this case I discovered the issue was my inclusion of spring-webmvc transiently in addition to spring-webflux. Your solution would likely have worked too, but I wanted to stick with the Controller style so ended up forcibly excluding spring-webmvc from my build.gradle:

configurations {
    implementation {
        exclude group: 'org.springframework', module: 'spring-webmvc'
    }
}

After that it worked as documented.


问:
Bootstrap modal is not showing while clicking on update button using jquery
I am using jquery to update the data using bootstrap modal its not showing the modal i don't know why

This is my code for the modal

```<code><div id="updateModal" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
            </div>

            <div class="modal-body">
                    <div class="form-group">
                        <input type="text" class="form-control" id="name" name="name" placeholder="Enter name" />
                    </div>
                    <div class="form-group">
                        <input type="text" class="form-control" id="email" name="email" placeholder="Enter email" />
                    </div>
                    <div class="form-group">
                        <input type="text" class="form-control" id="mob" name="mob" placeholder="Enter Mobile" />
                    </div>
                    <div class="form-group">
                        <input type="text" class="form-control" id="city" name="city" placeholder="Enter City" />
                    </div>

                <a href="#" id="save" class="btn btn-success pull-right">Update</a>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
            </div>
        </div>
    </div>
</code>```

This is the jquery code :

```<code>    $(document).ready(function(){
       $(document).on('click','a[data-role=update]',function(){
          var id = $(this).data(id);
           var name = $('#'+id).children('td[data-target=name]').text();
           var email = $('#'+id).children('td[data-target=email]').text();
           var mob = $('#'+id).children('td[data-target=mob]').text();
           var city = $('#'+id).children('td[data-target=city]').text();

           $('#name').val(name);
           $('#email').val(email);
           $('#mob').val(mob);
           $('#city').val(city);
           $('#updateModal').modal('toggle');
       });
    });
</code>```

And this is the code for persons list to be updated :

```<code><div class="table">
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Sr. No.</th>
                <th>Name</th>
                <th>Email</th>
                <th>Mobile</th>
                <th>City</th>
                <th>Action</th>
            </tr>
        </thead>

        <tbody>
            <?php while($row = mysqli_fetch_array($query)): $count++;?>
            <tr id="<?php echo $row['id'];?>">
                <td><?php echo $count;?></td>
                <td data-target="name"><?php echo $row['name'];?></td>
                <td data-target="email"><?php echo $row['email'];?></td>
                <td data-target="mob"><?php echo $row['mob'];?></td>
                <td data-target="city"><?php echo $row['city'];?></td>
                <td><a href="#" class="btn btn-success btn-sm" data-role="update" data-id="<?php echo $row['id'];?>">Update</a></td>
            </tr>
            <?php endwhile;?>
        </tbody>

    </table>
</div>
</code>```

By writing upto this i expect that the modal should pop-up and displays the information in the input fields but while I'm clicking on the update button the modal doesn't pop-ups.

Any help should be appreciated.

答:
In jQuery code,</p>

```<code>var id = $(this).attr('data-id');
console.log(id); // test the data-id in console
</code>```

Body:
I am using jquery to update the data using bootstrap modal its not showing the modal i don't know why

This is my code for the modal

                <button type="button" class="close" data-dismiss="modal">×</button>

                        <input type="text" class="form-control" id="name" name="name" placeholder="Enter name" />

                        <input type="text" class="form-control" id="email" name="email" placeholder="Enter email" />

                        <input type="text" class="form-control" id="mob" name="mob" placeholder="Enter Mobile" />

                        <input type="text" class="form-control" id="city" name="city" placeholder="Enter City" />

                Update

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

This is the jquery code :

    $(document).ready(function(){
       $(document).on('click','a[data-role=update]',function(){
          var id = $(this).data(id);
           var name = $('#'+id).children('td[data-target=name]').text();
           var email = $('#'+id).children('td[data-target=email]').text();
           var mob = $('#'+id).children('td[data-target=mob]').text();
           var city = $('#'+id).children('td[data-target=city]').text();

           $('#name').val(name);
           $('#email').val(email);
           $('#mob').val(mob);
           $('#city').val(city);
           $('#updateModal').modal('toggle');
       });
    });

And this is the code for persons list to be updated :

                Sr. No.
                Name
                Email
                Mobile
                City
                Action

            <?php while($row = mysqli_fetch_array($query)): $count++;?>
            <tr id="<?php echo $row['id'];?>">
                <?php echo $count;?>
                <?php echo $row['name'];?>
                <?php echo $row['email'];?>
                <?php echo $row['mob'];?>
                <?php echo $row['city'];?>
                <a href="#" class="btn btn-success btn-sm" data-role="update" data-id="<?php echo $row['id'];?>">Update

            <?php endwhile;?>

By writing upto this i expect that the modal should pop-up and displays the information in the input fields but while I'm clicking on the update button the modal doesn't pop-ups.

Any help should be appreciated.

Body:
In jQuery code,

var id = $(this).attr('data-id');
console.log(id); // test the data-id in console


问:
async/await running on single thread
I have a console application where in some instances a user interface needs to be presented. This user interface needs to remain responsive as it will contain a loading gif, progress bar, cancel button etc. I have the following sample code:

```<code>class Program
{
    static void Main(string[] args)
    {
        DoWork().GetAwaiter().GetResult();
    }

    private static async Task DoWork()
    {
        TestForm form = new TestForm();
        form.Show();

        string s = await Task.Run(() =>
        {
            System.Threading.Thread.Sleep(5000);
            return "Plop";
        });

        if (s == "Plop")
        {
            form.Close();
        }
    }
}
</code>```

I would expect from the code above for the TestForm to be displayed for approximately 5 seconds before being closed due to the value of the string being "Plop", however all that happens is the Task is run and the if statement is never reached. Furthermore the UI of the TestForm does not remain responsive. What is wrong with this code?

答:
Ok I did mark my first answer to be deleted, since what I put there works for WPF and not for you require, BUT in this one is doing what you asked, I did try it and opens the WinForm then closes after 5 seconds, here is the code:</p>

```<code>static void Main(string[] args)
{
    MethodToRun();
}

private static async void MethodToRun()
{
    var windowToOpen = new TestForm();
    var stringValue = String.Empty;
    Task.Run(new Action(() =>
    {
        Dispatcher.CurrentDispatcher.InvokeAsync(() =>
        {
            windowToOpen.Show();
        }).Wait();
        System.Threading.Thread.Sleep(5000);
        stringValue = "Plop";
        Dispatcher.CurrentDispatcher.InvokeAsync(() =>
        {
            if (String.Equals(stringValue, "Plop"))
            {
                windowToOpen.Close();
            }
        }).Wait();
    })).Wait();
}
</code>```

Title: async/await running on single thread

Body:
I have a console application where in some instances a user interface needs to be presented. This user interface needs to remain responsive as it will contain a loading gif, progress bar, cancel button etc. I have the following sample code:

class Program
{
    static void Main(string[] args)
    {
        DoWork().GetAwaiter().GetResult();
    }

    private static async Task DoWork()
    {
        TestForm form = new TestForm();
        form.Show();

        string s = await Task.Run(() =>
        {
            System.Threading.Thread.Sleep(5000);
            return "Plop";
        });

        if (s == "Plop")
        {
            form.Close();
        }
    }
}

I would expect from the code above for the TestForm to be displayed for approximately 5 seconds before being closed due to the value of the string being "Plop", however all that happens is the Task is run and the if statement is never reached. Furthermore the UI of the TestForm does not remain responsive. What is wrong with this code?

Body:
Ok I did mark my first answer to be deleted, since what I put there works for WPF and not for you require, BUT in this one is doing what you asked, I did try it and opens the WinForm then closes after 5 seconds, here is the code:

static void Main(string[] args)
{
    MethodToRun();
}

private static async void MethodToRun()
{
    var windowToOpen = new TestForm();
    var stringValue = String.Empty;
    Task.Run(new Action(() =>
    {
        Dispatcher.CurrentDispatcher.InvokeAsync(() =>
        {
            windowToOpen.Show();
        }).Wait();
        System.Threading.Thread.Sleep(5000);
        stringValue = "Plop";
        Dispatcher.CurrentDispatcher.InvokeAsync(() =>
        {
            if (String.Equals(stringValue, "Plop"))
            {
                windowToOpen.Close();
            }
        }).Wait();
    })).Wait();
}


问:
Iterate over an Array and push elements to an Object
I have an array object which looks like this

```<code>identificationType: "DL",
identificationDesc: "Test",
referenceNumber: "123456789",
country: "US",
province: "Illinois"
</code>```

I want my data model to look like this

```<code>identificationType: "DL",
identificationDesc: "Test",
referenceNumber: "123456789",
issuedEntity:{
country: "US",
province: "Illinois"
}
</code>```

Initially I assign array of Objects to a variable

```<code>identification: this.model['identificationArray'].
</code>```

IdentificationArray is an array of Object and contains all the details but in a simple json format. I want to be able to somehow manipulate it and insert data by creating an issuedEntity object and then country and province details inside that object.

For that I tried iterating over the array but I am getting error.Can someone help me figure out how to do it.

```<code>myModel.identification.forEach(identificationObj => {
issuedEntity: {
province = identificationObj.issuedEntity.province,
country = identificationObj.issuedEntity.country,
}
}
);
</code>```

答:
I think problem here, we are using = instead of : colon when assigning value to object.

```<code>    myModel.identification.forEach(identificationObj => {
    issuedEntity: {
        province **=** identificationObj.issuedEntity.province,
        country **=** identificationObj.issuedEntity.country,
    }
});
</code>```

It should be like this

```<code>myModel.identification.forEach(identificationObj => {
    issuedEntity: {
        province: identificationObj.issuedEntity.province,
        country: identificationObj.issuedEntity.country,
    }
});
</code>```

Body:
I have an array object which looks like this

identificationType: "DL",
identificationDesc: "Test",
referenceNumber: "123456789",
country: "US",
province: "Illinois"

I want my data model to look like this

identificationType: "DL",
identificationDesc: "Test",
referenceNumber: "123456789",
issuedEntity:{
country: "US",
province: "Illinois"
}

Initially I assign array of Objects to a variable

identification: this.model['identificationArray'].

IdentificationArray is an array of Object and contains all the details but in a simple json format. I want to be able to somehow manipulate it and insert data by creating an issuedEntity object and then country and province details inside that object.

For that I tried iterating over the array but I am getting error.Can someone help me figure out how to do it.

myModel.identification.forEach(identificationObj => {
issuedEntity: {
province = identificationObj.issuedEntity.province,
country = identificationObj.issuedEntity.country,
}
}
);

Body:
I think problem here, we are using = instead of : colon when assigning value to object.

    myModel.identification.forEach(identificationObj => {
    issuedEntity: {
        province **=** identificationObj.issuedEntity.province,
        country **=** identificationObj.issuedEntity.country,
    }
});

It should be like this

myModel.identification.forEach(identificationObj => {
    issuedEntity: {
        province: identificationObj.issuedEntity.province,
        country: identificationObj.issuedEntity.country,
    }
});


问:
scanf and getchar together to read string
I have this code:

```<code>Hotel new_h = (Hotel*)malloc(sizeof(Hotel));
printf("\nInsert name -> ");
scanf("%[^\n]s", new_h->name);
getchar();
</code>```

First of all, how it works %[^\n]s

Why there isn't just %s inside scanf?

And why there is getchar too?

答:
The getchar() function in this case would only be necessary if you were to do a following input after the hotel name, in wich case I would recommend you to just add a space before %s, something like this scanf(" %[^\n]s", new_h->name);.

Regarding that malloc() how's your definition of hotel because it has to be declared as a pointer, so you're able to allocate memory to it casting it to type pointer isn't enough and it will leed to a segfault you should declare it as

```<code>Hotel *new_h = malloc(sizeof(Hotel));
</code>```

This is considering that you are defining hotel as something like this

```<code>typedef struct{
    //Some vars
}Hotel;
</code>```

Body:
I have this code:

Hotel new_h = (Hotel*)malloc(sizeof(Hotel));
printf("\nInsert name -> ");
scanf("%[^\n]s", new_h->name);
getchar();

First of all, how it works %[^\n]s

Why there isn't just %s inside scanf?

And why there is getchar too?

Body:
The getchar() function in this case would only be necessary if you were to do a following input after the hotel name, in wich case I would recommend you to just add a space before %s, something like this scanf(" %[^\n]s", new_h->name);.

Regarding that malloc() how's your definition of hotel because it has to be declared as a pointer, so you're able to allocate memory to it casting it to type pointer isn't enough and it will leed to a segfault you should declare it as

Hotel *new_h = malloc(sizeof(Hotel));

This is considering that you are defining hotel as something like this

typedef struct{
    //Some vars
}Hotel;


问:
openGL texture mapping
Hey,
 I am creating a game using openGL in c++
when I try and map a texture to an object it changes the colour of everything else I have drawn
eg everything goes a transparent red or green..

```<code>glEnable (GL_TEXTURE_2D);
    Bitmap image;
    image.loadBMP ("Texture.bmp");

    glGenTextures(1, &m_TextureID);
    glBindTexture ( GL_TEXTURE_2D, m_TextureID);

    glTexEnvf ( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE , GL_MODULATE);
    glTexParameterf ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);

    glTexParameterf ( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameterf ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    gluBuild2DMipmaps ( GL_TEXTURE_2D, 3, image.width, image.height, GL_RGB,    GL_UNSIGNED_BYTE, image.data);
    glEnd();
</code>```

this is my texture code and here is how i am mapping the texture

```<code>glBegin(GL_QUADS);
glEnable (GL_TEXTURE_2D);
//glColor3d(1, 0, 0);
glTexCoord2f (0.0f,0.0f);
glVertex3f(0, 0, 0); // bottom left
glTexCoord2f (1.0f,0.0f);
glVertex3f(10, 0, 0); // bottom right
glTexCoord2f (1.0f,1.0f);
glVertex3f(10, 0.6, 0);// top right
glTexCoord2f (0.0f,1.0f);
glVertex3f(0, 0.6, 0); // top left
glEnd();
</code>```

etc...

all my non textured objects are drawn like this

```<code>glBegin(GL_QUADS);//BACK
glColor3d(1,0,0);
glVertex3f(10, 0, 0);
glVertex3f(10, 0, -5.6);
glVertex3f(10, 0.6, -5.6);
glVertex3f(10, 0.6, 0);
glEnd();
</code>```

etc...
am i missing something really obvious ?
thanks

答:
You switched these two :

```<code>glBegin(GL_QUADS);
glEnable (GL_TEXTURE_2D);
</code>```

glEnable should not be called between glBegin() and glEnd()

Other then that, use glGetError and see which exactly call fails.

ContentLicense: CC BY-SA 3.0

Title: openGL texture mapping

Body:
Hey,
 I am creating a game using openGL in c++
when I try and map a texture to an object it changes the colour of everything else I have drawn
eg everything goes a transparent red or green..

glEnable (GL_TEXTURE_2D);
    Bitmap image;
    image.loadBMP ("Texture.bmp");

    glGenTextures(1, &m_TextureID);
    glBindTexture ( GL_TEXTURE_2D, m_TextureID);

    glTexEnvf ( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE , GL_MODULATE);
    glTexParameterf ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);

    glTexParameterf ( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameterf ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    gluBuild2DMipmaps ( GL_TEXTURE_2D, 3, image.width, image.height, GL_RGB,    GL_UNSIGNED_BYTE, image.data);
    glEnd();

this is my texture code and here is how i am mapping the texture

glBegin(GL_QUADS);
glEnable (GL_TEXTURE_2D);
//glColor3d(1, 0, 0);
glTexCoord2f (0.0f,0.0f);
glVertex3f(0, 0, 0); // bottom left
glTexCoord2f (1.0f,0.0f);
glVertex3f(10, 0, 0); // bottom right
glTexCoord2f (1.0f,1.0f);
glVertex3f(10, 0.6, 0);// top right
glTexCoord2f (0.0f,1.0f);
glVertex3f(0, 0.6, 0); // top left
glEnd();

etc...

all my non textured objects are drawn like this

glBegin(GL_QUADS);//BACK
glColor3d(1,0,0);
glVertex3f(10, 0, 0);
glVertex3f(10, 0, -5.6);
glVertex3f(10, 0.6, -5.6);
glVertex3f(10, 0.6, 0);
glEnd();

etc...
am i missing something really obvious ?
thanks

Body:
You switched these two :

glBegin(GL_QUADS);
glEnable (GL_TEXTURE_2D);

glEnable should not be called between glBegin() and glEnd()

Other then that, use glGetError and see which exactly call fails.


问:
What happens to columns with IMAGE datatype after SQL-Server 2019?
I have a table which contains a column with the IMAGE datatype. This datatype will be removed in future versions of MS SQL Server. What happens to this column and the data stored in it, if I don't change it to another datatype before updating the server?

Will it be removed or is it still accessible?

答:
Microsoft clearly indicated that ntext, text, and image data types will be removed from future SQL versions. You should try to change these datatypes to  nvarchar(max), varchar(max), and varbinary(max).

In one environment I faced problem while maintenance jobs were running and failed. If these columns are part of Indexes then we can not rebuild online. Only offline operation is supported.

https://learn.microsoft.com/en-us/sql/t-sql/data-types/ntext-text-and-image-transact-sql?view=sql-server-ver15


问:
How to merge 2 CSV files based on filename
I have 2 CSV files:

```<code>1234ABC.stats.csv
name,value1,value1

1234ABC.csv
value2,value2,value2
</code>```

Both of these files have only 1 line in them.

They both have no header, and are in the same directory with no other file types.

How can I add the content from the second file onto the end of the line from the first?

desired output:

```<code>name,value1,value1,value2,value2,value2
</code>```

答:
try this:

```<code>paste -d, 1234ABC.stats.csv 1234ABC.csv
</code>```

loop over multiple files in local directory

```<code>#!/bin/bash
for statsfile in *.stats.csv; do
   paste -d, "$statsfile" "${statsfile//.stats/}" > "new_${statsfile//.stats/}"
done
</code>```

Body:
I have 2 CSV files:

1234ABC.stats.csv
name,value1,value1

1234ABC.csv
value2,value2,value2

Both of these files have only 1 line in them.

They both have no header, and are in the same directory with no other file types.

How can I add the content from the second file onto the end of the line from the first?

desired output:

name,value1,value1,value2,value2,value2

Body:
try this:

paste -d, 1234ABC.stats.csv 1234ABC.csv

loop over multiple files in local directory

#!/bin/bash
for statsfile in *.stats.csv; do
   paste -d, "$statsfile" "${statsfile//.stats/}" > "new_${statsfile//.stats/}"
done


问:
Monitor Spring Boot Apps using Prometheus on Kubernetes , not setting end Points
I am Trying to monitor Spring Boot application using Prometheus on Kubernetes. Promethus was insatll using Helm and I am using Spring Boot Actuator for  Health checking, Auditing, Metrics gathering and Monitoring.

Actuator gives details about application. For example

http://**IP:Port**/actuator/health return below output

```<code>{"status":"UP"}.
</code>```

I use below configuration file to add the application end point in promethus.

```<code>apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: scp-service-creator
  namespace: sc678
  labels:
    app: scp-service-creator
    release: prometheus-operator
spec:
  selector:
    matchLabels:
      app: scp-service-creator
  endpoints:
  - port: api
    path: "/actuator/prometheus"
    scheme: http
    interval: 10s
    honorLabels: true
</code>```

So my problem is even service is added to prometheus , no endpoint is assigned.
So What would be wrong here. Really appreciate your help.

Thank You.

答:
From the Spring Boot Actuator documentation, to be more specific the Endpoints part. One can read that Endpoints are enabled be default except Shutdown which is disabled, but only health and info are exposed.

This can be checked here.

You need to expose the Endpoint you want manually.

The Endpoint you want to use which is Prometheus is Not Available for JMX and is disabled for Web.

To change which endpoints are exposed, use the following technology-specific  include  and  exclude  properties:

Property | Default

management.endpoints.jmx.exposure.exclude |

management.endpoints.jmx.exposure.include | *

management.endpoints.web.exposure.exclude |

management.endpoints.web.exposure.include | info, health

The  include  property lists the IDs of the endpoints that are exposed. The  exclude  property lists the IDs of the endpoints that should not be exposed. The  excludeproperty takes precedence over the  include  property. Both  include  and  exclude  properties can be configured with a list of endpoint IDs.

For example, to stop exposing all endpoints over JMX and only expose the  health  and  info  endpoints, use the following property:

management.endpoints.jmx.exposure.include=health,info

*  can be used to select all endpoints. For example, to expose everything over HTTP except the  env  and  beans  endpoints, use the following properties:

management.endpoints.web.exposure.include=*
  management.endpoints.web.exposure.exclude=env,beans

Body:
I am Trying to monitor Spring Boot application using Prometheus on Kubernetes. Promethus was insatll using Helm and I am using Spring Boot Actuator for  Health checking, Auditing, Metrics gathering and Monitoring.

Actuator gives details about application. For example

http://**IP:Port**/actuator/health return below output

{"status":"UP"}.

I use below configuration file to add the application end point in promethus.

apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: scp-service-creator
  namespace: sc678
  labels:
    app: scp-service-creator
    release: prometheus-operator
spec:
  selector:
    matchLabels:
      app: scp-service-creator
  endpoints:
  - port: api
    path: "/actuator/prometheus"
    scheme: http
    interval: 10s
    honorLabels: true

So my problem is even service is added to prometheus , no endpoint is assigned.
So What would be wrong here. Really appreciate your help.

Thank You.


问:
java bit manipulation
```<code>byte x = -1;
for(int i = 0; i < 8; i++)
{
    x = (byte) (x >>> 1);
    System.out.println("X: " + x);
}
</code>```

As I understand it, java stores data in two's-complement, meaning -1 = 11111111 (according to wikipedia).

Also, from the java docs:
"The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension. "

Which means that >>> would shift a 0 to the left most bit every time.  So I expect this code to be

iteration: bit representation of x

0: 11111111

1: 01111111

2: 00111111

3: 00011111

...so on

However, my output is always X: -1, meaning (I guess) that >>> is putting the sign bit in the left most position.  So I then try >>, and same result.

What's going on?  I would expect my output to be: X: -1, x: 127, x: 63, etc.

答:
I don't know why it doesn't work, but an easy way to clear the top bit is to & with (binary) 0111111:</p>

```<code>x = (byte) (x >>> 1) & 0x7F;
</code>```

OwnerDisplayName: jbu

Title: java bit manipulation

Body:
byte x = -1;
for(int i = 0; i < 8; i++)
{
    x = (byte) (x >>> 1);
    System.out.println("X: " + x);
}

As I understand it, java stores data in two's-complement, meaning -1 = 11111111 (according to wikipedia).

Also, from the java docs:
"The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension. "

Which means that >>> would shift a 0 to the left most bit every time.  So I expect this code to be

iteration: bit representation of x

0: 11111111

1: 01111111

2: 00111111

3: 00011111

...so on

However, my output is always X: -1, meaning (I guess) that >>> is putting the sign bit in the left most position.  So I then try >>, and same result.

What's going on?  I would expect my output to be: X: -1, x: 127, x: 63, etc.

Body:
I don't know why it doesn't work, but an easy way to clear the top bit is to & with (binary) 0111111:

x = (byte) (x >>> 1) & 0x7F;

OwnerDisplayName: Jacob

ContentLicense: CC BY-SA 2.5


问:
How to place a div under a textarea and be able to handle events on it?
I want to make something like Grammarly, exactly like this:

The text is in a textarea, and a div for highlighting is under it, when I click on the red line, the correction card appears, but with z-index of the div less than the textarea's one, I am losing the events on it !

How can I implement such thing ?

答:
If Element A has a lower z-index than (ie. is underneath) Element B but Element B has the following applied (either in the initial stylesheet or later, dynamically):

```<code>element-b {
pointer-events: none;
}
</code>```

then any user clicking on Element B will actually be clicking on Element A.

Essentially the click goes straight through the element which cannot take pointer-events and instead hits the element beneath.

Further Reading:

https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

Body:
If Element A has a lower z-index than (ie. is underneath) Element B but Element B has the following applied (either in the initial stylesheet or later, dynamically):

element-b {
pointer-events: none;
}

then any user clicking on Element B will actually be clicking on Element A.

Essentially the click goes straight through the element which cannot take pointer-events and instead hits the element beneath.

Further Reading:

https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events


问:
AttributeError: 'float' object has no attribute 'shape' when using seaborn
I created a random dataFrame simulating the dataset tips from seaborn:

```<code>import numpy as np
import pandas as pd

time = ['day','night']
sex = ['female','male']
smoker = ['yes','no']
for t in range(0,len(time)):
    for s in range(0,len(sex)):
        for sm in range(0,len(smoker)):
            randomarray = np.random.rand(10)*10
            if t == 0 and s == 0 and sm == 0:
                df = pd.DataFrame(index=np.arange(0,len(randomarray)),columns=["total_bill","time","sex","smoker"])
                L = 0
                for i in range(0,len(randomarray)):
                    df.loc[i] = [randomarray[i], time[t], sex[s], smoker[sm]]
                    L = L + 1
            else:
                for i in range(0,len(randomarray)):
                    df.loc[i+L] = [randomarray[i], time[t], sex[s], smoker[sm]]
                    L = L + 1
</code>```

My dataFrame df has, for each column, the same type of class as the dataFrame tips from seaborn's dataset:

```<code>tips = sns.load_dataset("tips")
type(tips["total_bill"][0])
type(tips["time"][0])
</code>```

numpy.float64

str

And so on for the other columns. Same as my dataFrame:

```<code>type(df["total_bill"][0])
type(tips["time"][0])
</code>```

numpy.float64

str

However, when I try to use seaborn's violinplot or factorplot following the documentation:

```<code>g = sns.factorplot(x="sex", y="total_bill", hue="smoker", col="time",  data=df, kind="violin", split=True, size=4, aspect=.7);
</code>```

I have no problems if I use the dataFrame tips, but when I use my dataFrame I get:

AttributeError: 'float' object has no attribute 'shape'

I Imagine this is an issue with the way I pass the array into the dataFrame, but I couldn't find what is the problem since every issue I found on the internet with the same AttributeError says it's because it's not the same type of class, and as shown above my dataFrame has the same type of class as the one in seaborn's documentation.

Any suggestions?

答: Convert the data type of your variable from object to say float/int.</p>

Body:
I created a random dataFrame simulating the dataset tips from seaborn:

import numpy as np
import pandas as pd

time = ['day','night']
sex = ['female','male']
smoker = ['yes','no']
for t in range(0,len(time)):
    for s in range(0,len(sex)):
        for sm in range(0,len(smoker)):
            randomarray = np.random.rand(10)*10
            if t == 0 and s == 0 and sm == 0:
                df = pd.DataFrame(index=np.arange(0,len(randomarray)),columns=["total_bill","time","sex","smoker"])
                L = 0
                for i in range(0,len(randomarray)):
                    df.loc[i] = [randomarray[i], time[t], sex[s], smoker[sm]]
                    L = L + 1
            else:
                for i in range(0,len(randomarray)):
                    df.loc[i+L] = [randomarray[i], time[t], sex[s], smoker[sm]]
                    L = L + 1

My dataFrame df has, for each column, the same type of class as the dataFrame tips from seaborn's dataset:

tips = sns.load_dataset("tips")
type(tips["total_bill"][0])
type(tips["time"][0])

numpy.float64

str

And so on for the other columns. Same as my dataFrame:

type(df["total_bill"][0])
type(tips["time"][0])

numpy.float64

str

However, when I try to use seaborn's violinplot or factorplot following the documentation:

g = sns.factorplot(x="sex", y="total_bill", hue="smoker", col="time",  data=df, kind="violin", split=True, size=4, aspect=.7);

I have no problems if I use the dataFrame tips, but when I use my dataFrame I get:

AttributeError: 'float' object has no attribute 'shape'

I Imagine this is an issue with the way I pass the array into the dataFrame, but I couldn't find what is the problem since every issue I found on the internet with the same AttributeError says it's because it's not the same type of class, and as shown above my dataFrame has the same type of class as the one in seaborn's documentation.

Any suggestions?


问:
Is there any way to use `jsdoc` with `.ts` files? Maybe transpile with babel then use jsdoc?
Is there anyway to use jsdoc with typescript file?
I tried using jsdoc-babel with this config

```<code>{
  "plugins": [
    "node_modules/jsdoc-babel"
  ],
  "babel": {
    "extensions": [
      "js",
      "es6",
      "jsx",
      "ts",
      "tsx"
    ]
  }
}
</code>```

But it doesn't work, maybe we can transpile ts files manually and then generate jsdocs?
I know of alternatives like typedoc but it lacks many important features.

So do you guys use jsdoc with typescript anyhow?

答:
Although as stated by @Remi TypeDoc is a better fit for TypeScript, I use JSDoc for better jsdoc to markdown conversion (as of this writing).

Method 1:

Compile TypeScript and use JSDoc with compiled code

> tsc && nodemon node_modules/.bin/jsdoc -c jsdoc.json dist/**/*

Method 2:

I'm using below method with jsdoc2markdown (which uses jsdoc). Using jsdoc-babel, @babel/cli, @babel/core, @babel/preset-env, @babel/preset-typescript with below jsdoc configuration:

```<code>{
  "source": {
    "includePattern": ".+\\.ts(doc|x)?$",
    "excludePattern": ".+\\.(test|spec).ts"
  },
  "plugins": [
    "plugins/markdown",
    "node_modules/jsdoc-babel"
  ],
  "babel": {
    "extensions": ["ts", "tsx"],
    "ignore": ["**/*.(test|spec).ts"],
    "babelrc": false,
    "presets": [["@babel/preset-env", { "targets": { "node": true } }], "@babel/preset-typescript"],
    "plugins": ["@babel/proposal-class-properties", "@babel/proposal-object-rest-spread"]
  }
}
</code>```

This configuration:

Excludes your-file.test.ts, your-file.spec.ts and your-file.js files from compilation and documentation.

Includes your-file.ts, your-file.tsdoc and your-file.tsx

Using @babel/preset-env, targets current node version for conversion. (You can change and test it according to your needs) => See the preset-env documentation

Using @babel/preset-typescript gives babel the capability to parse TypeScript

Tips & Tricks

JSDoc Comments Disappear

Babel and TypeScript removes some JSDoc comments during transpilation:

babel/babel#6898: transform-flow-strip-types removes all jsdoc comments

babel/babel#5512: Babel very strange move comments

There is a hacky fix for this by adding a STUB code as seen below:

```<code>let STUB = 1;

/**
 * Some description
 * @typedef {Object} Config
 * @property {string}  name  - Name of the config.
 * @property {string}  color - Color of choice.
 */
STUB = 1;

export type Config = {
  name: string;
  color: string;
};
</code>```

<s>I wrote a wiki page for using TypeScript with jsdoc2md using jsdoc-babel long ago.

It may help: https://github.com/jsdoc2md/jsdoc-to-markdown/wiki/How-to-document-TypeScript</s>

 Method 3 (TypeDoc)

This is not directly what is asked, but strongly related to it. Below workflow may be useful:

Using TypeDoc to generate HTML pages.

Using typedoc-plugin-markdown to generate multiple MarkDown pages.

Using concat-md to generate single MarkDown page from multiple MarkDown pages. (This is an npm package developed by me lately to solve my JSDoc/TypeScript single page MarkDown requirement.)

Example

```<code>$ typedoc --plugin typedoc-plugin-markdown --mode file --out docs
$ npx concat-md --decrease-title-levels --dir-name-as-title docs > README.md
</code>```

Body:
Is there anyway to use jsdoc with typescript file?
I tried using jsdoc-babel with this config

{
  "plugins": [
    "node_modules/jsdoc-babel"
  ],
  "babel": {
    "extensions": [
      "js",
      "es6",
      "jsx",
      "ts",
      "tsx"
    ]
  }
}

But it doesn't work, maybe we can transpile ts files manually and then generate jsdocs?
I know of alternatives like typedoc but it lacks many important features.

So do you guys use jsdoc with typescript anyhow?

Body:
Although as stated by @Remi TypeDoc is a better fit for TypeScript, I use JSDoc for better jsdoc to markdown conversion (as of this writing).

Method 1:

Compile TypeScript and use JSDoc with compiled code

> tsc && nodemon node_modules/.bin/jsdoc -c jsdoc.json dist/**/*

Method 2:

I'm using below method with jsdoc2markdown (which uses jsdoc). Using jsdoc-babel, @babel/cli, @babel/core, @babel/preset-env, @babel/preset-typescript with below jsdoc configuration:

{
  "source": {
    "includePattern": ".+\\.ts(doc|x)?$",
    "excludePattern": ".+\\.(test|spec).ts"
  },
  "plugins": [
    "plugins/markdown",
    "node_modules/jsdoc-babel"
  ],
  "babel": {
    "extensions": ["ts", "tsx"],
    "ignore": ["**/*.(test|spec).ts"],
    "babelrc": false,
    "presets": [["@babel/preset-env", { "targets": { "node": true } }], "@babel/preset-typescript"],
    "plugins": ["@babel/proposal-class-properties", "@babel/proposal-object-rest-spread"]
  }
}

This configuration:

Excludes your-file.test.ts, your-file.spec.ts and your-file.js files from compilation and documentation.

Includes your-file.ts, your-file.tsdoc and your-file.tsx

Using @babel/preset-env, targets current node version for conversion. (You can change and test it according to your needs) => See the preset-env documentation

Using @babel/preset-typescript gives babel the capability to parse TypeScript

Tips & Tricks

JSDoc Comments Disappear

Babel and TypeScript removes some JSDoc comments during transpilation:

babel/babel#6898: transform-flow-strip-types removes all jsdoc comments

babel/babel#5512: Babel very strange move comments

There is a hacky fix for this by adding a STUB code as seen below:

let STUB = 1;

/**
 * Some description
 * @typedef {Object} Config
 * @property {string}  name  - Name of the config.
 * @property {string}  color - Color of choice.
 */
STUB = 1;

export type Config = {
  name: string;
  color: string;
};

<s>I wrote a wiki page for using TypeScript with jsdoc2md using jsdoc-babel long ago.

It may help: https://github.com/jsdoc2md/jsdoc-to-markdown/wiki/How-to-document-TypeScript</s>

 Method 3 (TypeDoc)

This is not directly what is asked, but strongly related to it. Below workflow may be useful:

Using TypeDoc to generate HTML pages.

Using typedoc-plugin-markdown to generate multiple MarkDown pages.

Using concat-md to generate single MarkDown page from multiple MarkDown pages. (This is an npm package developed by me lately to solve my JSDoc/TypeScript single page MarkDown requirement.)

Example

$ typedoc --plugin typedoc-plugin-markdown --mode file --out docs
$ npx concat-md --decrease-title-levels --dir-name-as-title docs > README.md


问:
Method awaited and the program get out of the method before it ends
I am making this method to connect to thingsboard and getting a Token access, when the program starts it get out of the program before getting the token, I've already tried to lunch the program with just this method and nothing else after and it get the token, but if I put some code after calling this method, the program get out of the log method.

```<code>class Login
{
    public thingboardToken tbToken;
    public thingboardCredentials tbCredentials;
    public string thingsboardAPIUrl = "https://demo.thingsboard.io/api";

    public Login() {
        loginAsync();
    }

    public async System.Threading.Tasks.Task<string> loginAsync()
    {
        string requesturl = thingsboardAPIUrl + "/auth/login";

        HttpClient client = new HttpClient();

        tbCredentials = new thingboardCredentials();
        tbCredentials.username = "xxxxx";
        tbCredentials.password = "xxxxx";

        var myContent = JsonConvert.SerializeObject(tbCredentials);
        var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
        var byteContent = new ByteArrayContent(buffer);
        byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        var response = await client.PostAsync(requesturl, byteContent);

        var responseString = await response.Content.ReadAsStringAsync();
        tbToken = JsonConvert.DeserializeObject<thingboardToken>(responseString);

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

Expected getting a token.

答:
In your constructor, you are calling an async method without awaiting it. In your constructor, loginAsync task hasn't competed but the execution of the current method continues before the call is completed.

```<code> public Login() {
        loginAsync();
 }
</code>```

Don't put initialization code in your constructor, instead, do it like below:

```<code>public class Foo
{
   public Foo() {}
   public async Task LoginAsync() { ... }
}

var obj = new Foo();
await obj.LoginAsync();
</code>```

In this approach, it wouldn't block the thread and it's better.

Body:
I am making this method to connect to thingsboard and getting a Token access, when the program starts it get out of the program before getting the token, I've already tried to lunch the program with just this method and nothing else after and it get the token, but if I put some code after calling this method, the program get out of the log method.

class Login
{
    public thingboardToken tbToken;
    public thingboardCredentials tbCredentials;
    public string thingsboardAPIUrl = "https://demo.thingsboard.io/api";

    public Login() {
        loginAsync();
    }

    public async System.Threading.Tasks.Task<string> loginAsync()
    {
        string requesturl = thingsboardAPIUrl + "/auth/login";

        HttpClient client = new HttpClient();

        tbCredentials = new thingboardCredentials();
        tbCredentials.username = "xxxxx";
        tbCredentials.password = "xxxxx";

        var myContent = JsonConvert.SerializeObject(tbCredentials);
        var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
        var byteContent = new ByteArrayContent(buffer);
        byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        var response = await client.PostAsync(requesturl, byteContent);

        var responseString = await response.Content.ReadAsStringAsync();
        tbToken = JsonConvert.DeserializeObject<thingboardToken>(responseString);

        return responseString;
    }
}

Expected getting a token.

Body:
In your constructor, you are calling an async method without awaiting it. In your constructor, loginAsync task hasn't competed but the execution of the current method continues before the call is completed.

 public Login() {
        loginAsync();
 }

Don't put initialization code in your constructor, instead, do it like below:

public class Foo
{
   public Foo() {}
   public async Task LoginAsync() { ... }
}

var obj = new Foo();
await obj.LoginAsync();

In this approach, it wouldn't block the thread and it's better.


问:
Rate limiting in Istio using Redis Handler
I am trying to apply ISTIO rate limiting using Redis Handler using Redis Handler ISTIO

But mixer is not able to find the redis handler. Below from mixer log:

2019-05-27T11:59:23.910183Z   warn    Unable to find a handler for action. rule[action]='quota.rule.istio-system[0]', handler='redishandler.istio-system'

redisquota: could not create a connection to redis server: NOAUTH Authentication required.''.
Also, how to provide Redis credential for the template?

答:
redis quota does not support Authentication

    // test redis connection
    option := redis.Options{
        Addr: b.adapterConfig.RedisServerUrl,
    }

    if b.adapterConfig.ConnectionPoolSize > 0 {
        option.PoolSize = int(b.adapterConfig.ConnectionPoolSize)
    }

```

https://github.com/istio/istio/redisquota.go

Body:
redis quota does not support Authentication

    // test redis connection
    option := redis.Options{
        Addr: b.adapterConfig.RedisServerUrl,
    }

    if b.adapterConfig.ConnectionPoolSize > 0 {
        option.PoolSize = int(b.adapterConfig.ConnectionPoolSize)
    }

https://github.com/istio/istio/redisquota.go


问:
How to set default table storage engine in MySQL using Entity Framework Core?
I'm using Pomelo.EntityFrameworkCore.MySql and would like to set InnoDB as the default storage engine for all my databases instead of the default MyISAM, but have no idea to do so in EFC code-first.

答:
There is an opened issue in Pomelo.EntityFrameworkCore.MySql that an engine cannot be specified: link.

And on that page there is a workaround posted as: to use migrations instead of EnsureDatabaseCreated, and manually to set default_storage_engine variable to InnoDBduring migration db session: link to the workaround.


问:
Cannot read property 'location' of undefined
I try to use react-router-dom 4.0.0 library. But it send me this error

Uncaught TypeError: Cannot read property 'location' of undefined

It seems that problem in browserHistore. Before I used react-router 2.x.x and everything was alright.
This is my index.js

```<code>import 'babel-polyfill'
import React from 'react'
import { Router, hashHistory } from 'react-router-dom'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { configureStore } from './store'
import { routes } from './routes'

const store = configureStore()

render(
  <Provider store={store}>
    <Router history={hashHistory} routes={routes} />
  </Provider>,
  document.getElementById('root')
)
</code>```

This is my routes

```<code>import React from 'react'
import { IndexRoute, Route } from 'react-router-dom'
import App from './containers/App'
import Main from './containers/Main'
import First from './containers/First'

export const routes = (
  <Route path='/' component={Main}>
    <Route path='/path' component={First} />
    <IndexRoute component={App} />
  </Route>
  )
</code>```

And also for server side express I set this get configuration

```<code>app.get('*', function root(req, res) {
  res.sendFile(__dirname + '/index.html');
});
</code>```

答:
Install npm history package: npm i history

and then use it as follow in your index/routes file:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Switch, Route} from 'react-router-dom';
import createBrowserHistory from 'history/createBrowserHistory';
import App from './components/App';
import './index.css'

const history = createBrowserHistory();

ReactDOM.render(
    <Router history={history}>
        <Switch>
            <Route path='/' component={App}/>
        </Switch>
    </Router>,
     document.getElementById('root')
    );
</code>```

Body:
I try to use react-router-dom 4.0.0 library. But it send me this error

Uncaught TypeError: Cannot read property 'location' of undefined

It seems that problem in browserHistore. Before I used react-router 2.x.x and everything was alright.
This is my index.js

import 'babel-polyfill'
import React from 'react'
import { Router, hashHistory } from 'react-router-dom'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { configureStore } from './store'
import { routes } from './routes'

const store = configureStore()

render(
  <Provider store={store}>
    <Router history={hashHistory} routes={routes} />
  </Provider>,
  document.getElementById('root')
)

This is my routes

import React from 'react'
import { IndexRoute, Route } from 'react-router-dom'
import App from './containers/App'
import Main from './containers/Main'
import First from './containers/First'

export const routes = (
  <Route path='/' component={Main}>
    <Route path='/path' component={First} />
    <IndexRoute component={App} />
  </Route>
  )

And also for server side express I set this get configuration

app.get('*', function root(req, res) {
  res.sendFile(__dirname + '/index.html');
});

Body:
Install npm history package: npm i history

and then use it as follow in your index/routes file:

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Switch, Route} from 'react-router-dom';
import createBrowserHistory from 'history/createBrowserHistory';
import App from './components/App';
import './index.css'

const history = createBrowserHistory();

ReactDOM.render(
    <Router history={history}>
        <Switch>
            <Route path='/' component={App}/>
        </Switch>
    </Router>,
     document.getElementById('root')
    );


问:
Hide filenames for product images
Is there any way that I can hide the image filenames for all products on a website so that, even if someone chooses to view the page source or image properties, they can't?
I need a way to hide the filenames because in some cases they contain information that i dont want to display to the public.</p>

答:
Renaming the files and giving them some random name would the simplest way to go.

If that's not an option, using a PHP frontend as @SLaks shows is the second-simplest way to go. It's a bit resource consuming, but okay if you don't have a lot of traffic.

If you do have a lot of traffic and are a bit advanced with Apache, you could also consider using an RewriteMap. It makes Apache to look up URL substitutions from a text file, which is faster than passing the resource through PHP. It will require some fiddling to get it to work, though.

Title: Hide filenames for product images


问:
Getting "TypeError: get() got an unexpected keyword argument 'fields" using the Facebook Marketing API
I literally copied this code from Facebook's documentation.

But I get this error:

TypeError: get() got an unexpected keyword argument 'fields

the code I copied:

```<code>facebook_business.adobjects.adcreative import AdCreative
from facebook_business.api import FacebookAdsApi

access_token = '<ACCESS_TOKEN>'
app_secret = '<APP_SECRET>'
app_id = '<APP_ID>'
id = '<AD_CREATIVE_ID>'
FacebookAdsApi.init(access_token=access_token)

fields = [
  'name',
  'object_story_id',
]
params = {
}
print AdCreative(id).get(
  fields=fields,
  params=params,
)
</code>```

答: There's a mistake in Facebook's documentation. .get() does not exist. Use api_get() instead.</p>

Body:
I literally copied this code from Facebook's documentation.

But I get this error:

TypeError: get() got an unexpected keyword argument 'fields

the code I copied:

facebook_business.adobjects.adcreative import AdCreative
from facebook_business.api import FacebookAdsApi

access_token = '<ACCESS_TOKEN>'
app_secret = '<APP_SECRET>'
app_id = '<APP_ID>'
id = '<AD_CREATIVE_ID>'
FacebookAdsApi.init(access_token=access_token)

fields = [
  'name',
  'object_story_id',
]
params = {
}
print AdCreative(id).get(
  fields=fields,
  params=params,
)


问:
Best Practice of running postgres in Ubuntu?
I just installed postgresql in Ubuntu 18.04 and been going through the official guide. Things I understand:

The installation comes with the default postgres user

We should not create databases with this default user

Instead we should create a different user

The questions I have are:

Why is this so?

Should the new user name I create be same as my ubuntu user $(whoami) ? Or should it be different ?

Should this new user be a superuser ?

When I have to delete or create databases/tables, do I have to log in to this newly created user or the default postgres user?

答:
You should read the documentation, this is no substitute.

It is ok to use the user postgres to create databases.

Ideally there should be no remote connections with user postgres (block it in pg_hba.conf).

Never let an application connect as superuser.

You should create other database users that are not superusers to create objects and work with them.

The name of the database users has no connection to the name of your operating system users.

For maximum safety, create objects with one user and let your application connect with a different user that has the required permissions on the objects.


问:
How to fix Errors in a Java2Word Generated ms-word document
I am using the java2word library for generating a word document from IBM Notes Database data.

My problem is that the document I am getting is interpreted as containing errors by ms word and only recoverable by text.

When I click the "Go to" button on the Word Repair pop up window (once I opened my doc in recovery) nothing happens and from the dialog, I can't tell anything at all. (in German)

I have Successfully used 2 other libraries with my Agent Class so I am pretty sure it can't be the data Collection and parsing to my Document Writing class.
The following Code runs successfully.

DataRow Class used for temporarily storing data:

```<code>    public class DataRow {
    String Date;
    String VorgangDesc;
    String DayShort;
    double Hours;
    public DataRow(String Dayshort, String Vorgangdesc, double hours, String date1){
        Date=date1;
        VorgangDesc=Vorgangdesc;
        DayShort=Dayshort;
        Hours=hours;
        }
}
</code>```

BerichtsHeft Class used for implementing java2word:

```<code>import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import lotus.domino.Session;

import word.api.interfaces.IDocument;
import word.api.interfaces.IElement;
import word.utils.TestUtils;
import word.utils.Utils;
import word.w2004.Document2004;
import word.w2004.Document2004.Encoding;
import word.w2004.elements.BreakLine;
import word.w2004.elements.Table;
import word.w2004.elements.tableElements.TableEle;

public class BerichtsHeft {
        public String Name;
        public String startD;
        public Session CurrentS;
        public int TableCount=1;
        public String Abteilung;
        public int AusbildungsJahr;
        String[] ItemsLastRow = new String[] {"..." , "...", "..."};
        String[] ItemsFirstRow = new String[] {"Ausbildungsnachweis", "Nr." + TableCount, "Woche vom" + startD + "bis" + "e end"};
        PrintWriter writer = null;
        Table CurrentTable;
        IDocument myDoc;

        public BerichtsHeft(String strName, String startDate, Session CurrentSes, String abteilung){
            this.Name=strName;
            this.startD=startDate;
            this.CurrentS=CurrentSes;
            this.Abteilung=abteilung;
            this.myDoc = new Document2004();
            myDoc.encoding(Encoding.UTF_8);
        }
        public void Spacer(){
            myDoc.addEle(BreakLine.times(1).create());
        }
        public void createTable(ArrayList<DataRow> DataList){
            Table tbl = new Table();
            CurrentTable = tbl;
            String[] ItemsFlexible = new String[3];
            AddFirstRow(ItemsFirstRow);
            for(int ij2=0; ij2<DataList.size(); ij2++){
                ItemsFlexible[0]=DataList.get(ij2).DayShort.toString();
                ItemsFlexible[1]=DataList.get(ij2).VorgangDesc.toString();
                ItemsFlexible[2]=Double.toString(DataList.get(ij2).Hours);
                AddRow(ItemsFlexible);
            }
            AddLastRow(ItemsLastRow);
            myDoc.addEle(CurrentTable);
            TableCount++;
            Spacer();
        }

        public void AddFirstRow(String[] Items){
                CurrentTable.addTableEle(TableEle.TH, Items);
        }
        public void AddRow(String[] items){
                CurrentTable.addTableEle(TableEle.TD, items);
        }
        public void AddLastRow(String[] items){
                CurrentTable.addTableEle(TableEle.TD, items);
        }
        public void logNext(){

        }
        public void SaveDoc(){
            File fileObj = new File("C:\\temp\\test2.doc");
            PrintWriter writer = null;
            try {
                writer = new PrintWriter(fileObj);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            String myWord = myDoc.getContent();
            writer.println(myWord);
            writer.close();
        }
    }
</code>```

Pastebin link to the text formated word document
PasteBin link to text Word Doc

What is the best technique to find the origin of these errors?

答: I found the Error in the Text document, it was caused by a special character, because the encoding was UTF_8 and not ISO8859_1.

Body:
I am using the java2word library for generating a word document from IBM Notes Database data.

My problem is that the document I am getting is interpreted as containing errors by ms word and only recoverable by text.

When I click the "Go to" button on the Word Repair pop up window (once I opened my doc in recovery) nothing happens and from the dialog, I can't tell anything at all. (in German)

I have Successfully used 2 other libraries with my Agent Class so I am pretty sure it can't be the data Collection and parsing to my Document Writing class.
The following Code runs successfully.

DataRow Class used for temporarily storing data:

    public class DataRow {
    String Date;
    String VorgangDesc;
    String DayShort;
    double Hours;
    public DataRow(String Dayshort, String Vorgangdesc, double hours, String date1){
        Date=date1;
        VorgangDesc=Vorgangdesc;
        DayShort=Dayshort;
        Hours=hours;
        }
}

BerichtsHeft Class used for implementing java2word:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import lotus.domino.Session;

import word.api.interfaces.IDocument;
import word.api.interfaces.IElement;
import word.utils.TestUtils;
import word.utils.Utils;
import word.w2004.Document2004;
import word.w2004.Document2004.Encoding;
import word.w2004.elements.BreakLine;
import word.w2004.elements.Table;
import word.w2004.elements.tableElements.TableEle;

public class BerichtsHeft {
        public String Name;
        public String startD;
        public Session CurrentS;
        public int TableCount=1;
        public String Abteilung;
        public int AusbildungsJahr;
        String[] ItemsLastRow = new String[] {"..." , "...", "..."};
        String[] ItemsFirstRow = new String[] {"Ausbildungsnachweis", "Nr." + TableCount, "Woche vom" + startD + "bis" + "e end"};
        PrintWriter writer = null;
        Table CurrentTable;
        IDocument myDoc;

        public BerichtsHeft(String strName, String startDate, Session CurrentSes, String abteilung){
            this.Name=strName;
            this.startD=startDate;
            this.CurrentS=CurrentSes;
            this.Abteilung=abteilung;
            this.myDoc = new Document2004();
            myDoc.encoding(Encoding.UTF_8);
        }
        public void Spacer(){
            myDoc.addEle(BreakLine.times(1).create());
        }
        public void createTable(ArrayList<DataRow> DataList){
            Table tbl = new Table();
            CurrentTable = tbl;
            String[] ItemsFlexible = new String[3];
            AddFirstRow(ItemsFirstRow);
            for(int ij2=0; ij2<DataList.size(); ij2++){
                ItemsFlexible[0]=DataList.get(ij2).DayShort.toString();
                ItemsFlexible[1]=DataList.get(ij2).VorgangDesc.toString();
                ItemsFlexible[2]=Double.toString(DataList.get(ij2).Hours);
                AddRow(ItemsFlexible);
            }
            AddLastRow(ItemsLastRow);
            myDoc.addEle(CurrentTable);
            TableCount++;
            Spacer();
        }

        public void AddFirstRow(String[] Items){
                CurrentTable.addTableEle(TableEle.TH, Items);
        }
        public void AddRow(String[] items){
                CurrentTable.addTableEle(TableEle.TD, items);
        }
        public void AddLastRow(String[] items){
                CurrentTable.addTableEle(TableEle.TD, items);
        }
        public void logNext(){

        }
        public void SaveDoc(){
            File fileObj = new File("C:\\temp\\test2.doc");
            PrintWriter writer = null;
            try {
                writer = new PrintWriter(fileObj);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            String myWord = myDoc.getContent();
            writer.println(myWord);
            writer.close();
        }
    }

Pastebin link to the text formated word document
PasteBin link to text Word Doc

What is the best technique to find the origin of these errors?


问:
Is it possible to use conditions in pom.xml
I've a maven web project and I'm using profiles in pom.xml for creating .war files for different environments. See the sample below snippet from my pom.xml </p>

```<code>    ...
<profiles>
    <!-- DEVELOPMENT PROFILE -->
    <profile>
        <id>development</id>
        ...
        <build>
           ...
                <plugin>
                    <groupId>com.google.code.echo-maven-plugin</groupId>
                    <artifactId>echo-maven-plugin</artifactId>
                    ...
                    <configuration>
                        <message>Message 1</message>
                    </configuration>
                    ...
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                    <configuration>
                        <webXml>src/main/webapp/WEB-INF/web-development.xml</webXml>
                    </configuration>
                </plugin>
                 ...
        </build>
    </profile>
    <!-- PRODUCTION PROFILE -->
    <profile>
        <id>production</id>
        ...
       <build>
           ...
                <plugin>
                    <groupId>com.google.code.echo-maven-plugin</groupId>
                    <artifactId>echo-maven-plugin</artifactId>
                    ...
                    <configuration>
                        <message>Message 2</message>
                    </configuration>
                    ...
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                    <configuration>
                        <webXml>src/main/webapp/WEB-INF/web-production.xml</webXml>
                    </configuration>
                </plugin>
        </build>
    </profile>
</profiles>
</code>```

<p>However, this makes my pom.xml pretty large - I've 5 different profiles. All I wanted to do is to display a custom message and use a custom web.xml file based on the profile.
Is there a way I could add conditions in the pom.xml so that I can simplify it some like below: </p>

```<code>...
    <profiles>
        <profile>
            <id>development</id>
            ...
        </profile>
        <profile>
            <id>production</id>
            ...
        </profile>
    <profiles>
    <build>
       ...
            <plugin>
                <groupId>com.google.code.echo-maven-plugin</groupId>
                <artifactId>echo-maven-plugin</artifactId>
                <version>1.0.0</version>
                <inherited>false</inherited>
                <configuration>
                    <IF CONDITION TO CHECK IF development PROFILE>
                        <message>Message 1</message>
                    </IF CONDITION>
                    <ELSE CASE>
                        <message>Message 2</message>
                    <ELSE CASE>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>echo</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.2</version>
                <configuration>
                    <IF CONDITION TO CHECK IF development PROFILE>
                        <webXml>src/main/webapp/WEB-INF/web-development.xml</webXml>
                    </IF CONDITION>
                    <ELSE CASE>
                        <webXml>src/main/webapp/WEB-INF/web-production.xml</webXml>
                    <ELSE CASE>
                </configuration>
            </plugin>
                    ...
    </build>
</code>```

答:
No.

But you could experiment with defining properties in profiles, which might allow you to write things more concisely.

Body:
I've a maven web project and I'm using profiles in pom.xml for creating .war files for different environments. See the sample below snippet from my pom.xml

    ...
<profiles>

    <profile>
        <id>development</id>
        ...
        <build>
           ...
                <plugin>
                    <groupId>com.google.code.echo-maven-plugin</groupId>
                    <artifactId>echo-maven-plugin</artifactId>
                    ...
                    <configuration>
                        <message>Message 1</message>
                    </configuration>
                    ...
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                    <configuration>
                        <webXml>src/main/webapp/WEB-INF/web-development.xml</webXml>
                    </configuration>
                </plugin>
                 ...
        </build>
    </profile>

    <profile>
        <id>production</id>
        ...
       <build>
           ...
                <plugin>
                    <groupId>com.google.code.echo-maven-plugin</groupId>
                    <artifactId>echo-maven-plugin</artifactId>
                    ...
                    <configuration>
                        <message>Message 2</message>
                    </configuration>
                    ...
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                    <configuration>
                        <webXml>src/main/webapp/WEB-INF/web-production.xml</webXml>
                    </configuration>
                </plugin>
        </build>
    </profile>
</profiles>

However, this makes my pom.xml pretty large - I've 5 different profiles. All I wanted to do is to display a custom message and use a custom web.xml file based on the profile.
Is there a way I could add conditions in the pom.xml so that I can simplify it some like below:

...
    <profiles>
        <profile>
            <id>development</id>
            ...
        </profile>
        <profile>
            <id>production</id>
            ...
        </profile>
    <profiles>
    <build>
       ...
            <plugin>
                <groupId>com.google.code.echo-maven-plugin</groupId>
                <artifactId>echo-maven-plugin</artifactId>
                <version>1.0.0</version>
                <inherited>false</inherited>
                <configuration>
                    <IF CONDITION TO CHECK IF development PROFILE>
                        <message>Message 1</message>
                    </IF CONDITION>
                    <ELSE CASE>
                        <message>Message 2</message>
                    <ELSE CASE>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>echo</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.2</version>
                <configuration>
                    <IF CONDITION TO CHECK IF development PROFILE>
                        <webXml>src/main/webapp/WEB-INF/web-development.xml</webXml>
                    </IF CONDITION>
                    <ELSE CASE>
                        <webXml>src/main/webapp/WEB-INF/web-production.xml</webXml>
                    <ELSE CASE>
                </configuration>
            </plugin>
                    ...
    </build>