问:
Neural network always predicts the same class
I am trying to create a CNN to classify text input into 4 bins and I am having the problem that the model will always predict the same class. I have used other simpler machine learning algorithms with the same preprocessing I am using with this CNN, and I achieve satisfactory results, so I am confident my preprocessing is fine.

My model is defined as follows:

```<code>model = keras.Sequential(
    [
        keras.layers.Input(shape=[vect_len], name="wide_input"),
        keras.layers.Embedding(vect_len, 100, input_length=vect_len),
        keras.layers.Conv1D(95, 4, activation='relu', kernel_regularizer=regularizers.l1_l2(l1=0.001, l2=0.01), bias_regularizer=regularizers.l2(0.04)),
        keras.layers.GlobalMaxPooling1D(data_format='channels_first'),
        keras.layers.Dense(4, activation='sigmoid')
    ]
)
</code>```

And trained as follows:

```<code>model.summary()
model.compile(optimizer=keras.optimizers.Adam(learning_rate=0.0006), loss='categorical_crossentropy', metrics=['accuracy'])
batch_size = 16
epochs = 50
history = model.fit(input_train, target_train, epochs=epochs, batch_size=batch_size, validation_split=0.2, shuffle=True)
</code>```

And after training my resulting confusion matrix is as follows.

Confusion Matrix

Following on the advice from this post (https://stackoverflow.com/a/41493375/6543460) I reduced my data set to simply all data of a class i to see if the model could predict that value when I tried this for each of the 4 classes.

I then went on to create a size 10 dataset with 5 instances of 2 distinct datapoints to see if the model could classify them into their correct classes, but it couldn't. I also tried 15 datapoints from 3 classes as follows,

```<code>target_train = np.array([
    [0., 0., 0., 1.],
    [0., 0., 0., 1.],
    [0., 0., 0., 1.],
    [0., 0., 0., 1.],
    [0., 0., 0., 1.],
    [1., 0., 0., 0.],
    [1., 0., 0., 0.],
    [1., 0., 0., 0.],
    [1., 0., 0., 0.],
    [1., 0., 0., 0.],
    [0., 0., 1., 0.],
    [0., 0., 1., 0.],
    [0., 0., 1., 0.],
    [0., 0., 1., 0.],
    [0., 0., 1., 0.]
])
target_train

input_train = np.array([
    np.copy(a),
    np.copy(a),
    np.copy(a),
    np.copy(a),
    np.copy(a),
    np.copy(b),
    np.copy(b),
    np.copy(b),
    np.copy(b),
    np.copy(b),
    np.copy(c),
    np.copy(c),
    np.copy(c),
    np.copy(c),
    np.copy(c)
])
</code>```

Confusion Matrix

which also didn't work. So, using this same size 15 dataset I tried simplifying my model until I could predict them accurately. Using just the dense layer I get what I need.

```<code>model = keras.Sequential(
    [
        keras.layers.Input(shape=[vect_len], name="wide_input"),
        # keras.layers.Embedding(vect_len, 100, input_length=vect_len),
        # keras.layers.Conv1D(95, 4, activation='relu', kernel_regularizer=regularizers.l1_l2(l1=0.001, l2=0.01), bias_regularizer=regularizers.l2(0.04)),
        # keras.layers.GlobalMaxPooling1D(data_format='channels_first'),
        keras.layers.Dense(4, activation='sigmoid')
    ]
)
</code>```

Confusion Matrix

But with just the embedding and the pooling layers (excluding the convolution layer) it doesn't work.

```<code>model = keras.Sequential(
    [
        keras.layers.Input(shape=[vect_len], name="wide_input"),
        keras.layers.Embedding(vect_len, 100, input_length=vect_len),
        # keras.layers.Conv1D(95, 4, activation='relu', kernel_regularizer=regularizers.l1_l2(l1=0.001, l2=0.01), bias_regularizer=regularizers.l2(0.04)),
        keras.layers.GlobalMaxPooling1D(data_format='channels_first'),
        keras.layers.Dense(4, activation='sigmoid')
    ]
)
</code>```

Confusion Matrix

I think there is some way in these steps I could be losing information, but I can't figure out what's happening specifically or how to fix it.

Body:
I am trying to create a CNN to classify text input into 4 bins and I am having the problem that the model will always predict the same class. I have used other simpler machine learning algorithms with the same preprocessing I am using with this CNN, and I achieve satisfactory results, so I am confident my preprocessing is fine.

My model is defined as follows:

model = keras.Sequential(
    [
        keras.layers.Input(shape=[vect_len], name="wide_input"),
        keras.layers.Embedding(vect_len, 100, input_length=vect_len),
        keras.layers.Conv1D(95, 4, activation='relu', kernel_regularizer=regularizers.l1_l2(l1=0.001, l2=0.01), bias_regularizer=regularizers.l2(0.04)),
        keras.layers.GlobalMaxPooling1D(data_format='channels_first'),
        keras.layers.Dense(4, activation='sigmoid')
    ]
)

And trained as follows:

model.summary()
model.compile(optimizer=keras.optimizers.Adam(learning_rate=0.0006), loss='categorical_crossentropy', metrics=['accuracy'])
batch_size = 16
epochs = 50
history = model.fit(input_train, target_train, epochs=epochs, batch_size=batch_size, validation_split=0.2, shuffle=True)

And after training my resulting confusion matrix is as follows.

Confusion Matrix

Following on the advice from this post (https://stackoverflow.com/a/41493375/6543460) I reduced my data set to simply all data of a class i to see if the model could predict that value when I tried this for each of the 4 classes.

I then went on to create a size 10 dataset with 5 instances of 2 distinct datapoints to see if the model could classify them into their correct classes, but it couldn't. I also tried 15 datapoints from 3 classes as follows,

target_train = np.array([
    [0., 0., 0., 1.],
    [0., 0., 0., 1.],
    [0., 0., 0., 1.],
    [0., 0., 0., 1.],
    [0., 0., 0., 1.],
    [1., 0., 0., 0.],
    [1., 0., 0., 0.],
    [1., 0., 0., 0.],
    [1., 0., 0., 0.],
    [1., 0., 0., 0.],
    [0., 0., 1., 0.],
    [0., 0., 1., 0.],
    [0., 0., 1., 0.],
    [0., 0., 1., 0.],
    [0., 0., 1., 0.]
])
target_train

input_train = np.array([
    np.copy(a),
    np.copy(a),
    np.copy(a),
    np.copy(a),
    np.copy(a),
    np.copy(b),
    np.copy(b),
    np.copy(b),
    np.copy(b),
    np.copy(b),
    np.copy(c),
    np.copy(c),
    np.copy(c),
    np.copy(c),
    np.copy(c)
])

Confusion Matrix

which also didn't work. So, using this same size 15 dataset I tried simplifying my model until I could predict them accurately. Using just the dense layer I get what I need.

model = keras.Sequential(
    [
        keras.layers.Input(shape=[vect_len], name="wide_input"),
        # keras.layers.Embedding(vect_len, 100, input_length=vect_len),
        # keras.layers.Conv1D(95, 4, activation='relu', kernel_regularizer=regularizers.l1_l2(l1=0.001, l2=0.01), bias_regularizer=regularizers.l2(0.04)),
        # keras.layers.GlobalMaxPooling1D(data_format='channels_first'),
        keras.layers.Dense(4, activation='sigmoid')
    ]
)

Confusion Matrix

But with just the embedding and the pooling layers (excluding the convolution layer) it doesn't work.

model = keras.Sequential(
    [
        keras.layers.Input(shape=[vect_len], name="wide_input"),
        keras.layers.Embedding(vect_len, 100, input_length=vect_len),
        # keras.layers.Conv1D(95, 4, activation='relu', kernel_regularizer=regularizers.l1_l2(l1=0.001, l2=0.01), bias_regularizer=regularizers.l2(0.04)),
        keras.layers.GlobalMaxPooling1D(data_format='channels_first'),
        keras.layers.Dense(4, activation='sigmoid')
    ]
)

Confusion Matrix

I think there is some way in these steps I could be losing information, but I can't figure out what's happening specifically or how to fix it.


来源: stackexchange

问:
Springboot and react fileupload: Required request part 'image' is not present
I dont understand whats wrong with my code.
This is the situation:

I have a frontend with react, where I can upload an image to springboot, which then puts it in a mysql database.

This works successfully, in both react and postman

Then I want to add new functionality. I want it so images can have tags (so you can for example search up images by writing tags). This is a many-to-many realtionship, in that each image can have several tags, and each tag can be with several images.

I proceed to change the code in springboot so that there is a new tag entity, and a many-to-many relationship between the tag entity and the image entity.

Aftermath:

I try to upload an image via postman to see if things still work. The uploads in postman are succsessfull.

I try to do a upload via the react frontend, but I get an error. I havent changed the code in the react frontend. The only thing ive done is adding a field to specify tags, but I dont actually send any axios requests with the tags.

So despite not sending any new requests and not changing the way an image is specified for uploading, I get an error.

In springboot, this is the error that appears when I try to upload a file from reactjs:
Required request part 'image' is not present

I hope you can help me with this. Ive sat with this for a long time. I wouldve thought everything would still work since it still works in postman. Why would uploading an image still work in postman, but suddenly not work in react, when the code for selecting a file and uploading it hasnt changed?

This is what it looks like when I upload an image via postman
upload via postman

here are some screenshots of the console in the browser when I try to make a post requesting with an image.
Browser console

In the first image Ive entered the page

In the second image Ive selected an image called "emo.png".

In the third image Ive pressed the "Upload" button, to send the post request. Something quickly appears in the console before the page is automatically rendered again.

The fourth image is after the page has rendered again.

The fifth image shows the log in the terminal, with the error message "Required request part 'image' is not present"

This is the code in my react frontend for file uploading:

```<code>const UploadFile = () => {

    var formData = new FormData()

    const [image, setImage] = useState([''])
    const [tags, setTags] = useState([])
    const [imageName, setImageName] = useState('')

    {/*TAGS*/}
    function updateTags(e) {
        var dict = {"tags": e.target.value.split(" ")}
        setTags(dict)
        console.log(tags)
        console.log(imageName)
    }

    {/*FILE*/}
    const handleFile = (e) => {
        formData.append("image", e.target.files[0])
        console.log(formData)
        setImageName(e.target.files[0].name)
    }

    const uploadFile = (e) => {
        const link = "http://localhost:8080/uploadimage"

        {/* UPLOADING FILE */}
        axios.post(link, formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
        .then(res => {
            console.log(res.data)
        })
        .catch(error => {
            console.log(error)
        })
    }

  return (
    <>

    <form>
        <label>Label</label>
        <input name="file" type="file"onChange={
            (e) => handleFile(e)}/>

        <br></br>
        <button onClick={(e) => uploadFile(e)}>Upload</button>
        <input onChange={(e) => updateTags(e)}></input>

    </form>
    </>
  )
}

export default UploadFile
</code>```

This is the controller in springboot, where the requests are handeled:

```<code>@RestController
public class FileController {

    @Autowired
    private StorageService service;

    @CrossOrigin(origins = "http://localhost:3000")
    @PostMapping("/uploadimage")
    public ResponseEntity<?> uploadImage(@RequestParam("image") MultipartFile file) throws IOException {
        String uploadImage = service.uploadImage(file);
        return ResponseEntity.status(HttpStatus.OK)
                .body(uploadImage);
    }

    @CrossOrigin(origins = "http://localhost:3000")
    @GetMapping("/getimage/{fileName}")
    public ResponseEntity<?> downloadImage(@PathVariable String fileName){

        byte[] imageData=service.downloadImage(fileName);
        return ResponseEntity.status(HttpStatus.OK)
                .contentType(MediaType.valueOf(service.getType(fileName)))
                .body(imageData);

    }

    @CrossOrigin(origins = "http://localhost:3000")
    @PostMapping("updatetags/{fileName}")
    public ImageData updateTags(@PathVariable String fileName, @RequestBody Map<String, List<String>> tags) {
        return service.updateTags(fileName, tags);
    }
}
</code>```

This is the code for the service, where the backend talks to the database

```<code>@Service
public class StorageService {

    @Autowired
    private StorageRepository repository;

    public String uploadImage(MultipartFile file) throws IOException {

        ImageData imageData = repository.save(ImageData.builder()
                .name(file.getOriginalFilename())
                .type(file.getContentType())
                .imageData(ImageUtils.compressImage(file.getBytes())).build());
        if (imageData != null) {
            return "file uploaded successfully : " + file.getOriginalFilename();
        }
        return null;
    }

    public byte[] downloadImage(String fileName){
        Optional<ImageData> dbImageData = repository.findByName(fileName);
        byte[] images=ImageUtils.decompressImage(dbImageData.get().getImageData());
        return images;
    }

    public String getType(String fileName) {
        String returnType = "";
        for (ImageData imageData : repository.findAll()) {
            if (Objects.equals(imageData.getName(), fileName)) {
                returnType = imageData.getType();
            }
        }

        return returnType;

    }

    public ImageData updateTags(String name, Map<String, List<String>> tags) {
        ImageData returnImage = new ImageData();
        System.out.println(tags);

        Set<Tag> tag_objects = new HashSet<>();
        for (String tag : tags.get("tags")) {
            Tag tagEntity = new Tag(null, tag);
            tag_objects.add(tagEntity);
        }
        for (ImageData image : repository.findAll()) {
            if (name.contains(image.getName())) {
                Set<Tag> image_tags = image.getTags();
                image_tags.addAll(tag_objects);
                image.setTags(image_tags);
                repository.save(image);
                break;
            }

        }

        return returnImage;

    }
}
</code>```

This is the code for the entities.
ImageData:

```<code>@Entity
@Table(name = "ImageData")
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class ImageData {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private String type;

    @Lob
    @Column(name = "imagedata",length = 1000)
    private byte[] imageData;

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name="file_has_tag",
            joinColumns = {@JoinColumn(name="image_data_id")},
            inverseJoinColumns = {@JoinColumn(name = "tag_id")})
    @JsonIgnoreProperties("image_data")
    private Set<Tag> tags;
}
</code>```

Tag;

```<code>@Entity
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class Tag {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long tagId;

    @Column(unique = true)
    private String tagName;
}
</code>```

Ive tried searching around for a solution. The problem is that the error I got can come from all kinds of errors.
So Im kind of baffeled.

ContentLicense: CC BY-SA 4.0

Body:
I dont understand whats wrong with my code.
This is the situation:

I have a frontend with react, where I can upload an image to springboot, which then puts it in a mysql database.

This works successfully, in both react and postman

Then I want to add new functionality. I want it so images can have tags (so you can for example search up images by writing tags). This is a many-to-many realtionship, in that each image can have several tags, and each tag can be with several images.

I proceed to change the code in springboot so that there is a new tag entity, and a many-to-many relationship between the tag entity and the image entity.

Aftermath:

I try to upload an image via postman to see if things still work. The uploads in postman are succsessfull.

I try to do a upload via the react frontend, but I get an error. I havent changed the code in the react frontend. The only thing ive done is adding a field to specify tags, but I dont actually send any axios requests with the tags.

So despite not sending any new requests and not changing the way an image is specified for uploading, I get an error.

In springboot, this is the error that appears when I try to upload a file from reactjs:
Required request part 'image' is not present

I hope you can help me with this. Ive sat with this for a long time. I wouldve thought everything would still work since it still works in postman. Why would uploading an image still work in postman, but suddenly not work in react, when the code for selecting a file and uploading it hasnt changed?

This is what it looks like when I upload an image via postman
upload via postman

here are some screenshots of the console in the browser when I try to make a post requesting with an image.
Browser console

In the first image Ive entered the page

In the second image Ive selected an image called "emo.png".

In the third image Ive pressed the "Upload" button, to send the post request. Something quickly appears in the console before the page is automatically rendered again.

The fourth image is after the page has rendered again.

The fifth image shows the log in the terminal, with the error message "Required request part 'image' is not present"

This is the code in my react frontend for file uploading:

const UploadFile = () => {

    var formData = new FormData()

    const [image, setImage] = useState([''])
    const [tags, setTags] = useState([])
    const [imageName, setImageName] = useState('')

    {/*TAGS*/}
    function updateTags(e) {
        var dict = {"tags": e.target.value.split(" ")}
        setTags(dict)
        console.log(tags)
        console.log(imageName)
    }

    {/*FILE*/}
    const handleFile = (e) => {
        formData.append("image", e.target.files[0])
        console.log(formData)
        setImageName(e.target.files[0].name)
    }

    const uploadFile = (e) => {
        const link = "http://localhost:8080/uploadimage"

        {/* UPLOADING FILE */}
        axios.post(link, formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
        .then(res => {
            console.log(res.data)
        })
        .catch(error => {
            console.log(error)
        })
    }

  return (
    <>

    <form>
        Label
        <input name="file" type="file"onChange={
            (e) => handleFile(e)}/>

        <button onClick={(e) => uploadFile(e)}>Upload</button>
        <input onChange={(e) => updateTags(e)}></input>

    </form>
    </>
  )
}

export default UploadFile

This is the controller in springboot, where the requests are handeled:

@RestController
public class FileController {

    @Autowired
    private StorageService service;

    @CrossOrigin(origins = "http://localhost:3000")
    @PostMapping("/uploadimage")
    public ResponseEntity<?> uploadImage(@RequestParam("image") MultipartFile file) throws IOException {
        String uploadImage = service.uploadImage(file);
        return ResponseEntity.status(HttpStatus.OK)
                .body(uploadImage);
    }

    @CrossOrigin(origins = "http://localhost:3000")
    @GetMapping("/getimage/{fileName}")
    public ResponseEntity<?> downloadImage(@PathVariable String fileName){

        byte[] imageData=service.downloadImage(fileName);
        return ResponseEntity.status(HttpStatus.OK)
                .contentType(MediaType.valueOf(service.getType(fileName)))
                .body(imageData);

    }

    @CrossOrigin(origins = "http://localhost:3000")
    @PostMapping("updatetags/{fileName}")
    public ImageData updateTags(@PathVariable String fileName, @RequestBody Map<String, List<String>> tags) {
        return service.updateTags(fileName, tags);
    }
}

This is the code for the service, where the backend talks to the database

@Service
public class StorageService {

    @Autowired
    private StorageRepository repository;

    public String uploadImage(MultipartFile file) throws IOException {

        ImageData imageData = repository.save(ImageData.builder()
                .name(file.getOriginalFilename())
                .type(file.getContentType())
                .imageData(ImageUtils.compressImage(file.getBytes())).build());
        if (imageData != null) {
            return "file uploaded successfully : " + file.getOriginalFilename();
        }
        return null;
    }

    public byte[] downloadImage(String fileName){
        Optional<ImageData> dbImageData = repository.findByName(fileName);
        byte[] images=ImageUtils.decompressImage(dbImageData.get().getImageData());
        return images;
    }

    public String getType(String fileName) {
        String returnType = "";
        for (ImageData imageData : repository.findAll()) {
            if (Objects.equals(imageData.getName(), fileName)) {
                returnType = imageData.getType();
            }
        }

        return returnType;

    }

    public ImageData updateTags(String name, Map<String, List<String>> tags) {
        ImageData returnImage = new ImageData();
        System.out.println(tags);

        Set<Tag> tag_objects = new HashSet<>();
        for (String tag : tags.get("tags")) {
            Tag tagEntity = new Tag(null, tag);
            tag_objects.add(tagEntity);
        }
        for (ImageData image : repository.findAll()) {
            if (name.contains(image.getName())) {
                Set<Tag> image_tags = image.getTags();
                image_tags.addAll(tag_objects);
                image.setTags(image_tags);
                repository.save(image);
                break;
            }

        }

        return returnImage;

    }
}

This is the code for the entities.
ImageData:

@Entity
@Table(name = "ImageData")
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class ImageData {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private String type;

    @Lob
    @Column(name = "imagedata",length = 1000)
    private byte[] imageData;

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name="file_has_tag",
            joinColumns = {@JoinColumn(name="image_data_id")},
            inverseJoinColumns = {@JoinColumn(name = "tag_id")})
    @JsonIgnoreProperties("image_data")
    private Set<Tag> tags;
}

Tag;

@Entity
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class Tag {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long tagId;

    @Column(unique = true)
    private String tagName;
}

Ive tried searching around for a solution. The problem is that the error I got can come from all kinds of errors.
So Im kind of baffeled.


问:
In flutter, Share a link using Share Plus then page moves to status bar and status become hide
I am using the Share package so that when I click on the icon I can share the link but the page moves to the status bar, this issue comes to android only.

Screenshots: (In the second screenshot, the title of the page moved in the status bar)

Before Share

After Share

class FeesPage extends StatelessWidget {
  const FeesPage({super.key});

  Future<void> share() async {
    await Share.share("Example share", subject: "Test subject");
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              ElevatedButton(
                child: Text('Share text and link'),
                onPressed: share,
              ),
              ElevatedButton(
                child: Text('Share local file'),
                onPressed: share,
              ),
            ],
          ),
        ),
      ),
    );
  }
}```


问:
How to cache event data in calendar
I am planning to show a calendar inside my webpage. The events displayed in the calendar can be in my side as well in some of the micro service(which i fetch using API passing the event's reference in my side). When the user navigates through my calendar, for each month i make request to get events from my side and then from the micro services to display the entire data. Also, the events are a shared resources and some user may/may not have access to certain events. Also the access permission is also a dynamic state and based on permission it varies. To put simply, a month data viewed by one user may/may not be same.

I have explored redis caching to cache the response from the micro service and invalidate them when an update is made on the event. I am unsure about the format to store the user based data in redis. Also, as my website scales and users increases, will this be a problem as there is limitation to redis storage limit.

P.S. Any other ideas or suggestion are welcomed. Just having a block and looking for a idea to explore more.

Title: How to cache event data in calendar


问:
How to restrict users from accessing product after it has expired?
I'm developing an e-learning app in which users can purchase courses that have an expiry date of up to two months from the time they purchase the course.

I'm aware of how to limit their access by comparing dates, but I was hoping you could advise me on how to easily restrict the users without manually going through every view and calling a function that returns Permission Denied if their course has expired.

I attempted to create a decorator that checks this but was unsuccessful. Should I use middleware to accomplish this? Could you point me in the right direction so I don't have to go through every view manually?


问:
How to continue loading after window.stop()? in chrome extension contentscript?
I'm trying to modify a content of a webpage, specifically I want to replace the links to the scripts on the page to something else. The way I do it is putting the following code on top of my contentscript.js of the extension:

```<code>window.stop();
var request = new XMLHttpRequest();

request.open('GET', location.href);
request.onload = function(event) {
  var html = request.responseText
    .replace('old link' 'new link');

  console.log(html);

  document.open();
  document.write(html);
  document.close();
};

request.send(null);
</code>```

Even though I write the html into the document the execution just stops and the website doesn't finish loading. So what am I missing? What do I need to call to continue the execution?

Body:
I'm trying to modify a content of a webpage, specifically I want to replace the links to the scripts on the page to something else. The way I do it is putting the following code on top of my contentscript.js of the extension:

window.stop();
var request = new XMLHttpRequest();

request.open('GET', location.href);
request.onload = function(event) {
  var html = request.responseText
    .replace('old link' 'new link');

  console.log(html);

  document.open();
  document.write(html);
  document.close();
};

request.send(null);

Even though I write the html into the document the execution just stops and the website doesn't finish loading. So what am I missing? What do I need to call to continue the execution?


问:
can i read Token from code java when OTP is enabled?
this is my code for reading token in java :

```<code>Keycloak instance = Keycloak.getInstance(authServer, realm, username, password,resource,secrets);
    TokenManager tokenmanager = instance.tokenManager();
    String accessToken = tokenmanager.getAccessTokenString();
    demandeur.setToken(accessToken);
</code>```

it work for me when the user dont have OTP , but if the user have otp actived i have bad Request execption

Body:
this is my code for reading token in java :

Keycloak instance = Keycloak.getInstance(authServer, realm, username, password,resource,secrets);
    TokenManager tokenmanager = instance.tokenManager();
    String accessToken = tokenmanager.getAccessTokenString();
    demandeur.setToken(accessToken);

it work for me when the user dont have OTP , but if the user have otp actived i have bad Request execption


问:
Rodrigo54 minify_css causing problems with quotes
Trying to implement a the css minifier Rodrigo54 from github and this works pretty well** - except I notice that it's corrupting some of my grid-template-areas which need quotes around the area names.

I can see the problem seems to be around the following regex, which if I remove the highlighted portion seems to work - but the question is why is this part needed - and how do I fix it (considering removing this part breaks at least the HEX color code part)?

```<code>  '#(\/\*(?>.*?\*\/))|(?<!content\:)([\'"])([a-z_][a-z0-9\-_]*?)\2(?=[\s\{\}\];,])#si',
                                    ^^^^^^^
</code>```

A running version of this minify_css can be found on https://onlinephp.io/c/2f6ec

** I'm only using this for the css

Body:
Trying to implement a the css minifier Rodrigo54 from github and this works pretty well** - except I notice that it's corrupting some of my grid-template-areas which need quotes around the area names.

I can see the problem seems to be around the following regex, which if I remove the highlighted portion seems to work - but the question is why is this part needed - and how do I fix it (considering removing this part breaks at least the HEX color code part)?

  '#(\/\*(?>.*?\*\/))|(?<!content\:)([\'"])([a-z_][a-z0-9\-_]*?)\2(?=[\s\{\}\];,])#si',
                                    ^^^^^^^

A running version of this minify_css can be found on https://onlinephp.io/c/2f6ec

** I'm only using this for the css


问:
eslint/lint for not supported expressions and operators
How would u implement eslint config/rules to only detect JS not supported expressions and operators for a given Node.js version

Example

If the project is using Node.js v10 than should detect this types of errors

using optional chaining (?.)

using null coalescing operator

similar errors

Only js not supported expressions and operators should be detected.


问:
How to change kerberos user password in shell script
I want to figure out a way on how to change the kerberos password in shell script?

I understood that we can change the password of a principal by running below command as mentioned in below link,
kadmin: cpw david

https://web.mit.edu/kerberos/krb5-1.5/krb5-1.5.4/doc/krb5-admin/Changing-Passwords.html

But I am confused on how to pass the same password when confirm password prompts on the screen without manual intervention in shell script,

Any leads would be appreciated. Thanks in advance!


问:
How to open notepad when from application that starts as schedule task when user is not log on?
I have a gRPC service that is hosted in a ASP application.

I create a task scehdule that is starts no matter if the user log on or not. This user is user A.

I have test that the application works when the computer starts, because it has a method to say "hello" to check if it is running or not.

I have created another method in the gRPC service to open the notepad for testing.

When I log on with the user A, I try to open the notepad, but this doesn't work.

I have tried to run the ASP application manually, so I can see the log windows, and in this case the notepad is opened.

Also I have tried to run the application as scheduled task, in this case when user log on, and it work too. Really it is the same that if I run it manually, I see the log windows.

So I guess the problem is related when I start the application as scheduled task without the need the user has to log on.

The reason to use a scheduled task no matter if the user log on or not it is because I don't want to see the log windows of the ASP application, so it is running in the backgruound and it doesn't dusturb.

So my question is, how could I run the ASP application without showing the window and can open applications likes notepad?

Thanks.


问:
Proper way to pass variables through chain of components in Vue 3
I'm trying to improve my code style, so there is a question: what is right way to pass data through chain of parent-child components?
For example: i have a CategoryView component. It is receiving prop:

```<code>{
  "id": 1,
  "title": "Some title",
  "articles": [(array of article objects..)]
}
</code>```

Inside of CategoryView i have an ArticleEditDialog component. When i'm editing some article, clearly i need to pass there object of article, which will be a reference. But when i'm creating a new article, i need somehow push new article in array of articles. So, i need to pass in article edit dialog array of articles. But then, i'm facing that i need to know category id when creating new article, so now i need to pass to article edit dialog complete category object. When adding some sub-components, this chain of passing root object may be long. Is it right or there is a more proper way? Maybe you can advice some articles about it?

Body:
I'm trying to improve my code style, so there is a question: what is right way to pass data through chain of parent-child components?
For example: i have a CategoryView component. It is receiving prop:

{
  "id": 1,
  "title": "Some title",
  "articles": [(array of article objects..)]
}

Inside of CategoryView i have an ArticleEditDialog component. When i'm editing some article, clearly i need to pass there object of article, which will be a reference. But when i'm creating a new article, i need somehow push new article in array of articles. So, i need to pass in article edit dialog array of articles. But then, i'm facing that i need to know category id when creating new article, so now i need to pass to article edit dialog complete category object. When adding some sub-components, this chain of passing root object may be long. Is it right or there is a more proper way? Maybe you can advice some articles about it?


问:
Ubuntu 22.04 - kernel module can not get address of printk
I'm compiling a legacy kernel driver on Ubuntu 22.04, kernel 5.15.0-56-generic

The driver provides IOCTL where user process can set the address of kernel exported function using system.map file.

To this user process provided address, driver internally adds the address of printk to get the actual address of the kernel function. (as the addresses in system.map are relative to printk)

```<code>required_function_addr = (user_provided_addr + printk);
</code>```

Now we want to compile the driver for ubuntu 22.04 and get below error:

```<code>error: ‘printk’ undeclared (first use in this function); did you mean ‘_printk’?
</code>```

Is there a way to fix this?

Body:
I'm compiling a legacy kernel driver on Ubuntu 22.04, kernel 5.15.0-56-generic

The driver provides IOCTL where user process can set the address of kernel exported function using system.map file.

To this user process provided address, driver internally adds the address of printk to get the actual address of the kernel function. (as the addresses in system.map are relative to printk)

required_function_addr = (user_provided_addr + printk);

Now we want to compile the driver for ubuntu 22.04 and get below error:

error: ‘printk’ undeclared (first use in this function); did you mean ‘_printk’?

Is there a way to fix this?


问:
Why firebase persistence does not save?
I am trying to set persistence in my Angular project, but the data is not saving. Here admin can choose persistence mode in admindashboard.html

```<code> <div class="inline">
    <h3>Choose persistence mode:</h3>
    <select [(ngModel)]="selectedPersistence" (ngModelChange)="chosenPersistence()">
        <option>local</option>
        <option>session</option>
        <option>none</option>
    </select>
</div>
</code>```

Then function in admindashboard.ts file is called

```<code>chosenPersistence() {
this.auth.changePersistenceMode(this.selectedPersistence);}
</code>```

and finally function in auth.service is called

```<code>  persistenceSetting: string = 'local'; //variable to store persistence mode

  changePersistenceMode(mode: string): void{
    switch(mode){
      case "local":
        console.log(mode);
        this.afAuth.setPersistence(firebase.auth.Auth.Persistence.LOCAL)
        this.persistenceSetting = "local"
        break
      case "session":
        console.log(mode);
        this.afAuth.setPersistence(firebase.auth.Auth.Persistence.SESSION)
        this.persistenceSetting = "session"
        break
      case "none":
          console.log(mode);
          this.afAuth.setPersistence(firebase.auth.Auth.Persistence.NONE)
          this.persistenceSetting = "none"
          break
    }
  }
</code>```

Why is persistence mode not changing?

Title: Why firebase persistence does not save?

Body:
I am trying to set persistence in my Angular project, but the data is not saving. Here admin can choose persistence mode in admindashboard.html

Choose persistence mode:

    <select [(ngModel)]="selectedPersistence" (ngModelChange)="chosenPersistence()">
        <option>local</option>
        <option>session</option>
        <option>none</option>
    </select>

Then function in admindashboard.ts file is called

chosenPersistence() {
this.auth.changePersistenceMode(this.selectedPersistence);}

and finally function in auth.service is called

  persistenceSetting: string = 'local'; //variable to store persistence mode

  changePersistenceMode(mode: string): void{
    switch(mode){
      case "local":
        console.log(mode);
        this.afAuth.setPersistence(firebase.auth.Auth.Persistence.LOCAL)
        this.persistenceSetting = "local"
        break
      case "session":
        console.log(mode);
        this.afAuth.setPersistence(firebase.auth.Auth.Persistence.SESSION)
        this.persistenceSetting = "session"
        break
      case "none":
          console.log(mode);
          this.afAuth.setPersistence(firebase.auth.Auth.Persistence.NONE)
          this.persistenceSetting = "none"
          break
    }
  }

Why is persistence mode not changing?


问:
Element implicitly has an any type because expression of type '0'can't be used to index type 'Object' - angular error
Property '0' does not exist on type'Object'.ts(7053)
I am getting error where i have written data[0]. I was trying to retrieve data from php database</p>
```<code>import { Component,OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-adashboard',
  templateUrl: './adashboard.component.html',
  styleUrls: ['./adashboard.component.css']
})
export class AdashboardComponent {
  title = 'angulardatatables';
  dtOptions: DataTables.Settings = {};

  data = []  ;
  constructor(private http: HttpClient) {
    this.http.get('http://localhost/angular_admin/php/user.php').subscribe(data => {
    this.data = data[0];

    }, error => console.error(error));
  }

  ngOnInit() {
    this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 5,
      processing: true
    };
}

}

Can anyone help me here ?

</code>```

Body:
Property '0' does not exist on type'Object'.ts(7053)
I am getting error where i have written data[0]. I was trying to retrieve data from php database

import { Component,OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-adashboard',
  templateUrl: './adashboard.component.html',
  styleUrls: ['./adashboard.component.css']
})
export class AdashboardComponent {
  title = 'angulardatatables';
  dtOptions: DataTables.Settings = {};

  data = []  ;
  constructor(private http: HttpClient) {
    this.http.get('http://localhost/angular_admin/php/user.php').subscribe(data => {
    this.data = data[0];

    }, error => console.error(error));
  }

  ngOnInit() {
    this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 5,
      processing: true
    };
}

}

Can anyone help me here ?


问:
Is there a way to validate nodejs code before running it
I am looking for a way to sign (locally) and validate (on the server) the code for a nodejs app that i am gonna be deploying.

I am thinking about creating a custom docker container that will check for a signature file (that contains hashes for all files in the project) and run the code only if it passes the check.

Is there something like that already exists?


问:
pycharm module directory import error problem
I am using pycharm and use 2 windows10 64bit PCs (one is a laptop and the other is desktop) for studying python3.

Recently, I found module importing issues which is different between PC.
Both pycahrm version is same: PyCharm 2022.2.2 (Community Edition).
Python version is also same: 3.9.
But when I import modules from main.py, I found the below difference.

[directory]
After the below directory,
C:\Users\username\PycharmProjects\pythonProject\python_programming_demo_app-0.0.1
enter image description here

The main.py is in dir1. In the main.py, to import module A, I can write the below.

1, from dir1.dir2 import A

2, from dir2 import A

PC 1(laptop): The above 1 and 2 both work. But when you create main.exe by pyinstaller, only 1 can work well. (main.exe created with 2 said no module named dir2 after executing main.exe.)

PC 2(desktop): The above 2 only works and main.exe created by pyinstaller also works. But the one never works on pycharm with the error message of [ModuleNotFoundError: No module named 'dir1']

Does anyone encounter the similar situation??
Is this caused by setting of pycharm??


问:
How to display old values from pivot table in Laravel Livewire on update?
I'm trying to Crud in Laravel Livewire. My site is about nutritionist who can create Receipts. In every Recipe he can add the Regime's type. I used many to many relation. So i have a pivot table.
I have a solution for create and update all the informations. I show you here an extract of my form and the livewire controller. Then i will explain you what i need to.

My form

```<code>            @if($updateMode || $createMode)
            <form class="bg-white rounded-lg px-4 py-5 mt-2 shadow hover:shadow-xl">

                <div class="flex space-x-10 justify-center mb-5">
                    <!-- Regime -->
                    <div class="mb-3">
                        <x-jet-label class="underline font-semibold" for="regimes">Type de régimes </x-jet-label>
                        @foreach($regimes as $index => $regime)
                            <div class="flex space-x-2 space-y-2 items-center" wire:key="regime-field-{{$regime->id}}">
                                <div>
                                    <x-jet-input type="checkbox" wire:model.defer="state.regimes_id.{{ $index }}" value="{{ $regime->id }}"/>
                                </div>
                                <div>
                                    <x-jet-label>{{ $regime->type }}</x-jet-label>
                                </div>
                            </div>
                        @endforeach
                    </div>
                </div>

                <!-- Buttons -->
                <div class="mb-3 text-center">
                    <x-jet-danger-button type="reset" wire:click.prevent="cancel">Annuler</x-jet-danger-button>
                    @if ($updateMode)
                        <x-jet-button class="bg-blue-600" type="submit" wire:click.prevent="update">Mettre à jour</x-jet-button>
                    @else
                        <x-jet-button class="bg-green-600" type="submit" wire:click.prevent="store">Enregistrer</x-jet-button>
                    @endif
                </div>
            </form>
            @endif

        <h3 class="text-green-600 text-lg text-center mb-5"> {{ $recettes->count() }} Recette(s) en ligne</h3>

        <div class="mb-2 text-cyan-600">
            <button type=button wire:click="openForm" class="flex inline space-x-2">
                <p> Create new Recipe</p>
            </button>
        </div>

        <div class="border-b border-gray-200 shadow-lg hover:shadow-2xl hover:shadow-cyan-500/60 shadow-cyan-500/50">
            <table class="divide-y divide-gray-300">
                <thead class="bg-gray-200">
                    <tr class="px-6 py-2 text-xs text-gray-500 divide-x divide-gray-300">
                        <th class="px-4 py-4" scope="col">#</th>
                        <th class="px-4 py-4" scope="col">Type de régime</th>
                        <th class="px-4 py-4" scope="col"> -- </th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-300">
                    @foreach ($recettesWithPagination as $recette)
                        <tr class="whitespace-nowrap text-xs text-center text-gray-500 divide-x">
                            <th class="bg-gray-200"  scope="row">{{ $recette->id }}</th>
                            <td>
                                <ol>
                                @foreach($recette->regimes as $regime)
                                    <li>{{ $regime->type}}</li>
                                @endforeach
                                </ol>
                            </td>
                            <td class="px-6 py-4">
                                <button wire:click.prevent="edit({{ $recette->id }})" type="button" class="px-4 py-1 text-sm text-blue-600 bg-blue-200 rounded-full">Modifier</button>
                                <button wire:click.prevent="delete({{ $recette->id }})" type="button" class="px-4 py-1 text-sm text-red-400 bg-red-200 rounded-full">Supprimer</button>
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
            <div class="bg-white border-t px-4 py-2">
            {{ $recettesWithPagination->links() }}
            </div>
        </div>
</code>```

My Livewire Controller

```<code>class Recettes extends Component
{
use WithPagination;

public $recettes, $photo, $allergenes, $allergenes_id, $regimes;

public $state = [];

public $updateMode = false;
public $createMode = false;

public function mount()
{
    $this->recettes = Recette::all();
    $this->regimes = Regime::all();
    $this->allergenes = Allergene::all();
}

private function resetInputFields()
{
    $this->reset('state');
}

protected $rules = [
    'allergenes_id.*' => 'nullable|boolean',
    'regimes_id.*' => 'nullable|boolean',
];

public function store()
{

    $validator = Validator::make($this->state, [
        here all my validation rules
       ]
    )->validate();

    $create = Recette::create([
        here my wire:models i need to store in db
    ]);

    /* PIVOT TABLE */

        if(isset($this->state['regimes_id'])){
            $create->regimes()->sync($this->state['regimes_id']);
        }
    /* /PIVOT TABLE */

    $this->reset('state');
    $this->createMode = false;
    $this->recettes = Recette::all();
}

public function edit($id)
{
    $this->updateMode = true;

    $recette = Recette::find($id);
    $this->state = [
        'id' => $recette->id,
        'title' => $recette->title,
        'description' => $recette->description,
        'preparation' => $recette->preparation,
        'rest' => $recette->rest,
        'cooking' => $recette->cooking,
        'ingredients' => $recette->ingredients,
        'steps' => $recette->steps,
        'patient_only' => $recette->patient_only,
    ];

}

public function openForm()
{
    $this->createMode = true;
}

public function cancel()
{
    if($this->updateMode) {
        $this->updateMode = false;
    }
    if($this->createMode) {
        $this->createMode = false;
    }

    $this->reset('state');
}

public function update()
{
    $validator = Validator::make($this->state, [
        --
       ] )->validate();

    if ($this->state['id']) {
        $recette = Recette::find($this->state['id']);

        /* DELETE PIVOT TABLE */
        $recette->regimes()->detach();

        $recette->update([
            'title' => $this->state['title'],
            'description' => $this->state['description'],
            'preparation' => $this->state['preparation'],
            'rest' => $this->state['rest'],
            'cooking' => $this->state['cooking'],
            'ingredients' => $this->state['ingredients'],
            'steps' => $this->state['steps'],
            'patient_only' => $this->state['patient_only'],
            'photo' => $name_file,
        ]);

        /* PIVOT TABLE */

        if(isset($this->state['regimes_id'])){
            $recette->regimes()->sync($this->state['regimes_id']);
        }
        /* END PIVOT TABLE */

        $this->updateMode = false;
        $this->reset('state');
        $this->recettes = Recette::all();
    }
}

public function render()
{
    return view('livewire.admin.recettes', ['recettesWithPagination' => Recette::paginate(5)]);
}
</code>```

}

As you can see my form is used for create and for update. What i want is click on "update" button, it open the form...until here all is good.
When the form is open all the fields ('title', 'description'...) take the old values (i precise that i delete this field in the form cause it was too long if i keep them) BUT i tried many way but i don't know how to fill the regime's checkboxes with the values of the table pivot.

The only way i could make it work is to detach the pivot and sync the new information. But if the admin don't want to change any of the regime's informations it's not pratical cause he need to add again this information.
Does it exist a way too display as "checked" the checkboxes that the admin already checked?

Body:
I'm trying to Crud in Laravel Livewire. My site is about nutritionist who can create Receipts. In every Recipe he can add the Regime's type. I used many to many relation. So i have a pivot table.
I have a solution for create and update all the informations. I show you here an extract of my form and the livewire controller. Then i will explain you what i need to.

My form

            @if($updateMode || $createMode)
            <form class="bg-white rounded-lg px-4 py-5 mt-2 shadow hover:shadow-xl">

                        <x-jet-label class="underline font-semibold" for="regimes">Type de régimes </x-jet-label>
                        @foreach($regimes as $index => $regime)

id}}">

                                    <x-jet-input type="checkbox" wire:model.defer="state.regimes_id.{{ $index }}" value="{{ $regime->id }}"/>

                                    <x-jet-label>{{ $regime->type }}</x-jet-label>

                        @endforeach

                    <x-jet-danger-button type="reset" wire:click.prevent="cancel">Annuler</x-jet-danger-button>
                    @if ($updateMode)
                        <x-jet-button class="bg-blue-600" type="submit" wire:click.prevent="update">Mettre à jour</x-jet-button>
                    @else
                        <x-jet-button class="bg-green-600" type="submit" wire:click.prevent="store">Enregistrer</x-jet-button>
                    @endif

            </form>
            @endif

 {{ $recettes->count() }} Recette(s) en ligne

            <button type=button wire:click="openForm" class="flex inline space-x-2">

 Create new Recipe

            </button>

                        #
                        Type de régime
                         --

                    @foreach ($recettesWithPagination as $recette)

                            {{ $recette->id }}

                                @foreach($recette->regimes as $regime)

{{ $regime->type}}

                                @endforeach

                                <button wire:click.prevent="edit({{ $recette->id }})" type="button" class="px-4 py-1 text-sm text-blue-600 bg-blue-200 rounded-full">Modifier</button>
                                <button wire:click.prevent="delete({{ $recette->id }})" type="button" class="px-4 py-1 text-sm text-red-400 bg-red-200 rounded-full">Supprimer</button>

                    @endforeach

            {{ $recettesWithPagination->links() }}

My Livewire Controller

class Recettes extends Component
{
use WithPagination;

public $recettes, $photo, $allergenes, $allergenes_id, $regimes;

public $state = [];

public $updateMode = false;
public $createMode = false;

public function mount()
{
    $this->recettes = Recette::all();
    $this->regimes = Regime::all();
    $this->allergenes = Allergene::all();
}

private function resetInputFields()
{
    $this->reset('state');
}

protected $rules = [
    'allergenes_id.*' => 'nullable|boolean',
    'regimes_id.*' => 'nullable|boolean',
];

public function store()
{

    $validator = Validator::make($this->state, [
        here all my validation rules
       ]
    )->validate();

    $create = Recette::create([
        here my wire:models i need to store in db
    ]);

    /* PIVOT TABLE */

        if(isset($this->state['regimes_id'])){
            $create->regimes()->sync($this->state['regimes_id']);
        }
    /* /PIVOT TABLE */

    $this->reset('state');
    $this->createMode = false;
    $this->recettes = Recette::all();
}

public function edit($id)
{
    $this->updateMode = true;

    $recette = Recette::find($id);
    $this->state = [
        'id' => $recette->id,
        'title' => $recette->title,
        'description' => $recette->description,
        'preparation' => $recette->preparation,
        'rest' => $recette->rest,
        'cooking' => $recette->cooking,
        'ingredients' => $recette->ingredients,
        'steps' => $recette->steps,
        'patient_only' => $recette->patient_only,
    ];

}

public function openForm()
{
    $this->createMode = true;
}

public function cancel()
{
    if($this->updateMode) {
        $this->updateMode = false;
    }
    if($this->createMode) {
        $this->createMode = false;
    }

    $this->reset('state');
}

public function update()
{
    $validator = Validator::make($this->state, [
        --
       ] )->validate();

    if ($this->state['id']) {
        $recette = Recette::find($this->state['id']);

        /* DELETE PIVOT TABLE */
        $recette->regimes()->detach();

        $recette->update([
            'title' => $this->state['title'],
            'description' => $this->state['description'],
            'preparation' => $this->state['preparation'],
            'rest' => $this->state['rest'],
            'cooking' => $this->state['cooking'],
            'ingredients' => $this->state['ingredients'],
            'steps' => $this->state['steps'],
            'patient_only' => $this->state['patient_only'],
            'photo' => $name_file,
        ]);

        /* PIVOT TABLE */

        if(isset($this->state['regimes_id'])){
            $recette->regimes()->sync($this->state['regimes_id']);
        }
        /* END PIVOT TABLE */

        $this->updateMode = false;
        $this->reset('state');
        $this->recettes = Recette::all();
    }
}

public function render()
{
    return view('livewire.admin.recettes', ['recettesWithPagination' => Recette::paginate(5)]);
}

}

As you can see my form is used for create and for update. What i want is click on "update" button, it open the form...until here all is good.
When the form is open all the fields ('title', 'description'...) take the old values (i precise that i delete this field in the form cause it was too long if i keep them) BUT i tried many way but i don't know how to fill the regime's checkboxes with the values of the table pivot.

The only way i could make it work is to detach the pivot and sync the new information. But if the admin don't want to change any of the regime's informations it's not pratical cause he need to add again this information.
Does it exist a way too display as "checked" the checkboxes that the admin already checked?


问:
How To Design a MFC Application That Will Work On All Resolutions
I'm currently working on the MFC application in Visual Studio 2017 which is having the dialogs designed for resolution 1920 x 1080, but now I want to modify it and make it scalable for all resolution.

What changes should I make to the application so that the application fits to all the screen size irrespective of resolution.


问:
Exntended Choice Parameter - does not see property file path from gitlab repository
I have created choice parameted using Extended Choice Parameter property files. When used locally jenkins sees file's path correctly and choices are visible, but when I use deployed version and try to get the property file from git repository it does not recognize the path.
I use pipeline script from SCM, pass credentials and connect with no problems. Jenkins file is read from git repository correctly.
Can the Extended Choice Paramters use git files? What is it's working directory? I don't know where the extension is looking for for this files.</p>


问:
impala replacing in-clause with inner join
overflow members!

I have a query like this running in impala:

```<code>SELECT
    COUNT(*) AS value
FROM
    myTable
WHERE
  mycolumn IN ('value1', 'value2',..... 'value_n')
</code>```

it seems than where n is in the thousands it makes this query to be quite slow.. I am trying
now to replace the in clause with an inner join something like this:

```<code>SELECT
        COUNT(*) AS value
    FROM
        myTable
        INNER JOIN (SELECT UNNEST(['value1', 'value2', .. 'value_n']) AS myColumnName)
        ON myColumn=myColumnName
</code>```

Impala complains about the use there of UNNEST;

[13:09] rdm (Guest)
Query: SELECT UNNEST([1, 2, 3]) AS myColumnName
Query submitted at: 2022-12-29 12:08:08 (Coordinator: http://rpkgh21dev147:25000)
ERROR: ParseException: Syntax error in line 1:
SELECT UNNEST([1, 2, 3]) AS myColumnName
       ^
Encountered: A reserved word cannot be used as an identifier: UNNEST
Expected: ALL, CASE, CAST, DEFAULT, DISTINCT, EXISTS, FALSE, IF, INTERVAL, LEFT, NOT, NULL, REPLACE, RIGHT, STRAIGHT_JOIN, TRUNCATE, TRUE, IDENTIFIER

I am not able to figure out how to make this.. what is the correct syntax in impala to make this? (be aware the n-values doesnt came from another table so I can not replace the literal array with another select).

Thank you very much in advance.

Roberto

Body:
overflow members!

I have a query like this running in impala:

SELECT
    COUNT(*) AS value
FROM
    myTable
WHERE
  mycolumn IN ('value1', 'value2',..... 'value_n')

it seems than where n is in the thousands it makes this query to be quite slow.. I am trying
now to replace the in clause with an inner join something like this:

SELECT
        COUNT(*) AS value
    FROM
        myTable
        INNER JOIN (SELECT UNNEST(['value1', 'value2', .. 'value_n']) AS myColumnName)
        ON myColumn=myColumnName

Impala complains about the use there of UNNEST;

[13:09] rdm (Guest)
Query: SELECT UNNEST([1, 2, 3]) AS myColumnName
Query submitted at: 2022-12-29 12:08:08 (Coordinator: http://rpkgh21dev147:25000)
ERROR: ParseException: Syntax error in line 1:
SELECT UNNEST([1, 2, 3]) AS myColumnName
       ^
Encountered: A reserved word cannot be used as an identifier: UNNEST
Expected: ALL, CASE, CAST, DEFAULT, DISTINCT, EXISTS, FALSE, IF, INTERVAL, LEFT, NOT, NULL, REPLACE, RIGHT, STRAIGHT_JOIN, TRUNCATE, TRUE, IDENTIFIER

I am not able to figure out how to make this.. what is the correct syntax in impala to make this? (be aware the n-values doesnt came from another table so I can not replace the literal array with another select).

Thank you very much in advance.

Roberto


问:
How can I work with OLE2 objects in Python?
I am working on a python project where I need to read an xlsx, edit a row on a specific worksheet and then save it to run a bigger program in Anylogic (the xlsx file is an input for this program). The thing is that I can not modify the Anylogic program (it's an exported program) and I get the following error:

```<code>Your InputStream was neither an OLE2 stream, nor an OOXML stream
</code>```

I tried using Pandas to modify the xlsx and then I tried to use openpyxl which is the library that Pandas uses to work with xlsx and xls files.

Here's the code I used with openpyxl

def open_workbook(source_file: str, worksheet_name: str):

    workbook = openpyxl.load_workbook(source_file)
    worksheet = workbook.worksheets[WORKSHEETS_NAME[worksheet_name]]

    return workbook, worksheet

def write_extreme(workbook, worksheet_name: str, j: int):

    worksheet = workbook.worksheets[WORKSHEETS_NAME[worksheet_name]]

    for i in range(worksheet.max_row - 1):
        if i == j:
            print("hola")
            worksheet.cell(i + 1, CA_COLUMNS_INDEX["nAmbulance"], 1771)
            print(1771 - worksheet.max_row + 2)
        else:
            print("hola2")
            worksheet.cell(i + 1, CA_COLUMNS_INDEX["nAmbulance"], 1)

    workbook.save(SOURCE_PATH + "Hospitales_Ambulancias_CM_3.xlsx")
```

Body:
I am working on a python project where I need to read an xlsx, edit a row on a specific worksheet and then save it to run a bigger program in Anylogic (the xlsx file is an input for this program). The thing is that I can not modify the Anylogic program (it's an exported program) and I get the following error:

Your InputStream was neither an OLE2 stream, nor an OOXML stream

I tried using Pandas to modify the xlsx and then I tried to use openpyxl which is the library that Pandas uses to work with xlsx and xls files.

Here's the code I used with openpyxl

def open_workbook(source_file: str, worksheet_name: str):

    workbook = openpyxl.load_workbook(source_file)
    worksheet = workbook.worksheets[WORKSHEETS_NAME[worksheet_name]]

    return workbook, worksheet

def write_extreme(workbook, worksheet_name: str, j: int):

    worksheet = workbook.worksheets[WORKSHEETS_NAME[worksheet_name]]

    for i in range(worksheet.max_row - 1):
        if i == j:
            print("hola")
            worksheet.cell(i + 1, CA_COLUMNS_INDEX["nAmbulance"], 1771)
            print(1771 - worksheet.max_row + 2)
        else:
            print("hola2")
            worksheet.cell(i + 1, CA_COLUMNS_INDEX["nAmbulance"], 1)

    workbook.save(SOURCE_PATH + "Hospitales_Ambulancias_CM_3.xlsx")


问:
How to replace sitemap.xml in SAP Hybris
Client has provided two .xml files namely a_20221229.xml and b_20221229.xml for two sites i.e, site a and site b. And they wanted to replace content of urls https://a.local:9002/sitemap.xml with a_20221229.xml and https://b.local:9002/sitemap.xml with b_20221229.xml.

I have created CatalogUnawareMedia for a_20221229.xml and associated it with site map for the given site.

Can anyone please confirm, is it correct way of doing or have to do some other way?

Replacing sitemap.xml under storefront url https://b.local:9002/sitemap.xml


问:
Can't send a document via Telegram API on Swift; using Vapor

Code

```<code>        let handler16 = TGMessageHandler(filters: .regexp(pattern: "^11$")) {update, bot in
            if let id = update.message?.chat.id {
                let chatId: TGChatId = .chat(id)
            //    let file = File(data: "hello", filename: "МЭСК.docx")
                let params: TGSendDocumentParams = .init(chatId: chatId, document: .url("http://www.ncbi.nlm.nih.gov/geo/download/?acc=GSE46130&format=file"))
                try bot.sendDocument(params: params)
            }
        }
</code>```

Error

Type: server Description: Response marked as not Ok, it seems something wrong with request
Code: 400
Bad Request: failed to get HTTP URL contentReason:

How can i save my particular document and send it (if it is big) via Telegram Bot ?

After that I'm running on linux server, i don't know how to do it correct...

If the file is already stored somewhere on the Telegram servers, you don't need to reupload it: each file object has a file_id field, simply pass this FileInfo.fileId("file_id") as a parameter instead of uploading. There are no limits for files sent this way.

Body:
Code

        let handler16 = TGMessageHandler(filters: .regexp(pattern: "^11$")) {update, bot in
            if let id = update.message?.chat.id {
                let chatId: TGChatId = .chat(id)
            //    let file = File(data: "hello", filename: "МЭСК.docx")
                let params: TGSendDocumentParams = .init(chatId: chatId, document: .url("http://www.ncbi.nlm.nih.gov/geo/download/?acc=GSE46130&format=file"))
                try bot.sendDocument(params: params)
            }
        }

Error

Type: server Description: Response marked as not Ok, it seems something wrong with request
Code: 400
Bad Request: failed to get HTTP URL contentReason:

How can i save my particular document and send it (if it is big) via Telegram Bot ?

After that I'm running on linux server, i don't know how to do it correct...

If the file is already stored somewhere on the Telegram servers, you don't need to reupload it: each file object has a file_id field, simply pass this FileInfo.fileId("file_id") as a parameter instead of uploading. There are no limits for files sent this way.


问:
Is there array.splice() for Formik FieldArray?
I am creating a multistep form / wizard with react and Formik.
My initial values is an empty array, which I populate with answers from the form. I have this structure, because the data structure must be very specific (not of my choosing).
The form is displayed one question at a time, so the user cannot see upcoming questions, only previous answers.

Previous answers should be editable, but in such a way that if an answer is edited, all following answers are reset and the user must start over with the form from the point where the form was edited.
Hence, I need to get the index of the question where the value is being updated and remove all following values. Basically, I need to do:

```<code>const newArray = array.splice(index, array.length)
</code>```

...but in Formik. Is this possible?

I have looked at enableReinitialize  but I only need to reset part of my form, at a given index.

All I can find in the docs are ways of removing or inserting values, but not to reset.

I have also tried versions of setFieldValues('answers', []) but haven't gotten it to work.

All suggestions are much appreciated.

Here is my form component:

```<code>// lib
import { Formik, Form, Field, FieldArray } from 'formik';
import { motion, AnimatePresence, useScroll } from "framer-motion";

// components
import Question from './Question'
import ProgressBar from './ProgressBar'

// utils
import * as constants from '../Utils/constants';

const WizardBase = (props) => {

    const ref = React.useRef(null);

    const questionsToShow = 1;
    const [next, setNext] = useState(questionsToShow - 1);
    const [questions, setQuestions] = useState([]);
    const [question, setQuestion] = useState([]);

    const handleMoreQuestions = (index) => {
        setNext(next + questionsToShow);
    };

    useEffect(() => {
        props.loadQuestions();
    }, []);

    const questionGroups = props.wizardData.questions;

    useEffect(() => {
        if (questionGroups) {
            questionGroups.map((sections, i) => {

                sections.questions.map((question, index) => {
                    setQuestions(questions => [...questions, question]);
                })
            })
        }

    }, [questionGroups])

    useEffect(() => {
        if (questions.length > 0) {
            questions.map((question, i) => {
                setQuestion(question => [...questions, question])
            })
        }
    }, [questions])

    return (
        <div className="pension-wizard-block">Pension insurance

            <nav className="top-nav">
                <ProgressBar total={questions.length} />
            </nav>

            <Formik initialValues={constants.initialValues}
                onSubmit={(values) => { console.log(values) }}>

                <Form>

                     <div className='pension-wizard-block__question'
                           ref={ref}
                        >Välkommen
                            <button onClick={handleMoreQuestions}>Börja</button>
                     </div>

                    <FieldArray name="Answers">
                        {({ insert, remove, push }) => (

                            question && question.length > 0 && question.slice(0, next).map((q, index) => (
                                <Question
                                    key={q.id}
                                    index={index}
                                    legend={`Fråga ${index + 1}`}
                                    question={q.questionText}
                                    type='radio'
                                    labels={q.options}
                                    options={q.options}
                                    id={`Answers.${index}.QuestionId`}
                                    questionId={q.id}
                                    name={`Answers.${index}.Answer`}
                                    handleMoreQuestions={handleMoreQuestions}
                                    total={questions.length}
                                    />
                                ))

                       )}
                    </FieldArray>

                            <button type="submit">Submit</button>
                        </Form>
                </Formik>

        </div>
     )
}

</code>```

This is my question component:

```<code>
// lib
import { motion, useViewportScroll } from 'framer-motion';
import { throttle } from 'lodash';

// components
import QuestionInput from './QuestionInput'

const Question = ({
    type,
    name,
    legend,
    checked,
    options,
    question,
    id,
    questionId,
    handleMoreQuestions,
    index,
    total
}) => {

    const [answered, setAnswered] = useState(null);
    const [scrollingUp, setScrollingUp] = useState(false)

    // check scroll direction
    let { scrollY } = useViewportScroll();

    const update = useMemo(() => throttle((latest) => {
        if (latest < 0) return;

        let isScrollingDown = scrollY.getPrevious() - latest < 0;
        let scrollDirection = isScrollingDown ? "down" : "up";
        setScrollingUp(isScrollingDown)

    }, 100), [scrollY]);

    useEffect(() => {
        scrollY.onChange(update);
    }, [update]);

    // scroll effect on answer
    const refs = useRef([]);

    useEffect(() => {
        if (total) {
            if (refs.current[index] && total >= index + 1) {
                refs.current[index].scrollIntoView({ behavior: "smooth" });
            } else {
                console.log("end");
            }
        }
    }, [index]);

    // height animation on answer
    const variant = {
        open: {
            height: '80vh',
        },
        closed: {
            height: '100%',
        }
    }

    return (
        <motion.div
            animate={answered ? "closed" : "open"}
            variants={ variant }
            className={`pension-wizard-block__question ${answered !== null ? "answered" : ""}`}
            ref={(element) => (refs.current[index] = element)}
        >
            <fieldset className="pension-wizard-block__question__inner">
                <legend>{legend}</legend>

                <p>{question}</p>
                {options && options.length > 0 && options.map((option, index) => (
                    <QuestionInput
                        key={index}
                        handleMoreQuestions={handleMoreQuestions}
                        index={index}
                        questionId={questionId}
                        id={id}
                        type={type}
                        name={name}
                        label={option.text}
                        handleAnswered={setAnswered}
                        total={total}
                    />
                ))}
            </fieldset>
        </motion.div>
        )
}

export default Question;

</code>```

Body:
I am creating a multistep form / wizard with react and Formik.
My initial values is an empty array, which I populate with answers from the form. I have this structure, because the data structure must be very specific (not of my choosing).
The form is displayed one question at a time, so the user cannot see upcoming questions, only previous answers.

Previous answers should be editable, but in such a way that if an answer is edited, all following answers are reset and the user must start over with the form from the point where the form was edited.
Hence, I need to get the index of the question where the value is being updated and remove all following values. Basically, I need to do:

const newArray = array.splice(index, array.length)

...but in Formik. Is this possible?

I have looked at enableReinitialize  but I only need to reset part of my form, at a given index.

All I can find in the docs are ways of removing or inserting values, but not to reset.

I have also tried versions of setFieldValues('answers', []) but haven't gotten it to work.

All suggestions are much appreciated.

Here is my form component:

// lib
import { Formik, Form, Field, FieldArray } from 'formik';
import { motion, AnimatePresence, useScroll } from "framer-motion";

// components
import Question from './Question'
import ProgressBar from './ProgressBar'

// utils
import * as constants from '../Utils/constants';

const WizardBase = (props) => {

    const ref = React.useRef(null);

    const questionsToShow = 1;
    const [next, setNext] = useState(questionsToShow - 1);
    const [questions, setQuestions] = useState([]);
    const [question, setQuestion] = useState([]);

    const handleMoreQuestions = (index) => {
        setNext(next + questionsToShow);
    };

    useEffect(() => {
        props.loadQuestions();
    }, []);

    const questionGroups = props.wizardData.questions;

    useEffect(() => {
        if (questionGroups) {
            questionGroups.map((sections, i) => {

                sections.questions.map((question, index) => {
                    setQuestions(questions => [...questions, question]);
                })
            })
        }

    }, [questionGroups])

    useEffect(() => {
        if (questions.length > 0) {
            questions.map((question, i) => {
                setQuestion(question => [...questions, question])
            })
        }
    }, [questions])

    return (

Pension insurance

                <ProgressBar total={questions.length} />

            <Formik initialValues={constants.initialValues}
                onSubmit={(values) => { console.log(values) }}>

                <Form>

Välkommen
                            <button onClick={handleMoreQuestions}>Börja</button>

                    <FieldArray name="Answers">
                        {({ insert, remove, push }) => (

                            question && question.length > 0 && question.slice(0, next).map((q, index) => (
                                <Question
                                    key={q.id}
                                    index={index}
                                    legend={`Fråga ${index + 1}`}
                                    question={q.questionText}
                                    type='radio'
                                    labels={q.options}
                                    options={q.options}
                                    id={`Answers.${index}.QuestionId`}
                                    questionId={q.id}
                                    name={`Answers.${index}.Answer`}
                                    handleMoreQuestions={handleMoreQuestions}
                                    total={questions.length}
                                    />
                                ))

                       )}
                    </FieldArray>

                            <button type="submit">Submit</button>
                        </Form>
                </Formik>

     )
}

This is my question component:

// lib
import { motion, useViewportScroll } from 'framer-motion';
import { throttle } from 'lodash';

// components
import QuestionInput from './QuestionInput'

const Question = ({
    type,
    name,
    legend,
    checked,
    options,
    question,
    id,
    questionId,
    handleMoreQuestions,
    index,
    total
}) => {

    const [answered, setAnswered] = useState(null);
    const [scrollingUp, setScrollingUp] = useState(false)

    // check scroll direction
    let { scrollY } = useViewportScroll();

    const update = useMemo(() => throttle((latest) => {
        if (latest < 0) return;

        let isScrollingDown = scrollY.getPrevious() - latest < 0;
        let scrollDirection = isScrollingDown ? "down" : "up";
        setScrollingUp(isScrollingDown)

    }, 100), [scrollY]);

    useEffect(() => {
        scrollY.onChange(update);
    }, [update]);

    // scroll effect on answer
    const refs = useRef([]);

    useEffect(() => {
        if (total) {
            if (refs.current[index] && total >= index + 1) {
                refs.current[index].scrollIntoView({ behavior: "smooth" });
            } else {
                console.log("end");
            }
        }
    }, [index]);

    // height animation on answer
    const variant = {
        open: {
            height: '80vh',
        },
        closed: {
            height: '100%',
        }
    }

    return (
        <motion.div
            animate={answered ? "closed" : "open"}
            variants={ variant }
            className={`pension-wizard-block__question ${answered !== null ? "answered" : ""}`}
            ref={(element) => (refs.current[index] = element)}
        >
            <fieldset className="pension-wizard-block__question__inner">
                <legend>{legend}</legend>

{question}

                {options && options.length > 0 && options.map((option, index) => (
                    <QuestionInput
                        key={index}
                        handleMoreQuestions={handleMoreQuestions}
                        index={index}
                        questionId={questionId}
                        id={id}
                        type={type}
                        name={name}
                        label={option.text}
                        handleAnswered={setAnswered}
                        total={total}
                    />
                ))}
            </fieldset>
        </motion.div>
        )
}

export default Question;


问:
Custom WebView / WebViewX like iFrame flutter mobile or WebView in a rectangle
I am trying to create a mobile app in flutter where I can display the content from a webView but i need it in a rectangular form and inside a widget in the center of the app.</p>


问:
Mongoose deleteMany() timing out
I am using mongoose and my internet connection is slow. Most of the time when running the code I'm getting the following error:

```<code>MongooseError: Operation `users.deleteMany()` buffering timed out after 10000ms
</code>```

The line is:

```<code>await User.deleteMany({})
</code>```

Please note that the same code is working sometimes but when the internet isn't great it's not so I think that it simply needs more time but I cannot figure out how to change the timeout for deleteMany()

I tried the following:

```<code>await User.deleteMany({}).maxTimeMS(50000)
</code>```

but I'm still getting the same error.

Thank you.

Title: Mongoose deleteMany() timing out

Body:
I am using mongoose and my internet connection is slow. Most of the time when running the code I'm getting the following error:

MongooseError: Operation `users.deleteMany()` buffering timed out after 10000ms

The line is:

await User.deleteMany({})

Please note that the same code is working sometimes but when the internet isn't great it's not so I think that it simply needs more time but I cannot figure out how to change the timeout for deleteMany()

I tried the following:

await User.deleteMany({}).maxTimeMS(50000)

but I'm still getting the same error.

Thank you.


问:
How to solve great expectations "MetricResolutionError: Cannot compile Column object until its 'name' is assigned." Error?
I am trying to use great expectations,  The function i want to use is "expect_compound_columns_to_be_unique".
This is the code (main code - template);

```<code>import datetime

import pandas as pd

import great_expectations as ge
import great_expectations.jupyter_ux
from great_expectations.core.batch import BatchRequest
from great_expectations.checkpoint import SimpleCheckpoint
from great_expectations.exceptions import DataContextError

context = ge.data_context.DataContext()

# Note that if you modify this batch request, you may save the new version as a .json file
#  to pass in later via the --batch-request option
batch_request = {'datasource_name': 'impala_okh', 'data_connector_name': 'default_inferred_data_connector_name', 'data_asset_name': 'okh.okh_forecast_prod', 'limit': 1000}

# Feel free to change the name of your suite here. Renaming this will not remove the other one.
expectation_suite_name = "okh_forecast_prod"
try:
    suite = context.get_expectation_suite(expectation_suite_name=expectation_suite_name)
    print(f'Loaded ExpectationSuite "{suite.expectation_suite_name}" containing {len(suite.expectations)} expectations.')
except DataContextError:
    suite = context.create_expectation_suite(expectation_suite_name=expectation_suite_name)
    print(f'Created ExpectationSuite "{suite.expectation_suite_name}".')

validator = context.get_validator(
    batch_request=BatchRequest(**batch_request),
    expectation_suite_name=expectation_suite_name
)
column_names = [f'"{column_name}"' for column_name in validator.columns()]
print(f"Columns: {', '.join(column_names)}.")
validator.head(n_rows=5, fetch_all=False)
</code>```

the function (error in here);

```<code>validator.expect_compound_columns_to_be_unique(['column1', 'column2'])
</code>```

Then i am getting following error;

MetricResolutionError: Cannot compile Column object until its 'name' is assigned.

How can i solve this problem?

Body:
I am trying to use great expectations,  The function i want to use is "expect_compound_columns_to_be_unique".
This is the code (main code - template);

import datetime

import pandas as pd

import great_expectations as ge
import great_expectations.jupyter_ux
from great_expectations.core.batch import BatchRequest
from great_expectations.checkpoint import SimpleCheckpoint
from great_expectations.exceptions import DataContextError

context = ge.data_context.DataContext()

# Note that if you modify this batch request, you may save the new version as a .json file
#  to pass in later via the --batch-request option
batch_request = {'datasource_name': 'impala_okh', 'data_connector_name': 'default_inferred_data_connector_name', 'data_asset_name': 'okh.okh_forecast_prod', 'limit': 1000}

# Feel free to change the name of your suite here. Renaming this will not remove the other one.
expectation_suite_name = "okh_forecast_prod"
try:
    suite = context.get_expectation_suite(expectation_suite_name=expectation_suite_name)
    print(f'Loaded ExpectationSuite "{suite.expectation_suite_name}" containing {len(suite.expectations)} expectations.')
except DataContextError:
    suite = context.create_expectation_suite(expectation_suite_name=expectation_suite_name)
    print(f'Created ExpectationSuite "{suite.expectation_suite_name}".')

validator = context.get_validator(
    batch_request=BatchRequest(**batch_request),
    expectation_suite_name=expectation_suite_name
)
column_names = [f'"{column_name}"' for column_name in validator.columns()]
print(f"Columns: {', '.join(column_names)}.")
validator.head(n_rows=5, fetch_all=False)

the function (error in here);

validator.expect_compound_columns_to_be_unique(['column1', 'column2'])

Then i am getting following error;

MetricResolutionError: Cannot compile Column object until its 'name' is assigned.

How can i solve this problem?


问:
Spring Boot @PreAuthorize at class level
I have a Spring Boot controller. My controller is derived from a base class. If I annotate a method in the base class or the base class itself with:

@RequestMapping(value = "/page", method = RequestMethod.POST)
@PreAuthorize("hasRole('BACKOFFICE')")
public ResponseEntity<?> page(@RequestBody ObjectNode json, Pageable pageable,  Authentication authentication) throws ApplicationException{
   ...
}
```
<pre class="lang-java prettyprint-override"><code>@RestController
@PreAuthorize("hasRole('BACKOFFICE')")
public abstract class TableController {
   ...
}
</code>```

it works and roles are checked. I need to annotate the derived class but there @PreAuthorized annotation is ignored.

@RestController
@PreAuthorize("hasRole('BACKOFFICE')")
public class UtentiController extends TableController{
  ...
}
```
<p>Is there a different annotation or a cofinguration required?</p>
<p>My security configuration is</p>
<pre class="lang-java prettyprint-override"><code>@Configuration
@EnableWebSecurity
@EnableTransactionManagement
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailServiceImpl userService;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
        auth.userDetailsService(userService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
            .authorizeRequests()
                .antMatchers( "/css/**",  "/libs/**","/js/**", "/api/**", "/assets/**", "/register", "/public/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .logoutSuccessUrl("/login?logout")
                .permitAll()
                .and()
            .csrf().disable();
    }
}
</code>```

Body:
I have a Spring Boot controller. My controller is derived from a base class. If I annotate a method in the base class or the base class itself with:

@RequestMapping(value = "/page", method = RequestMethod.POST)
@PreAuthorize("hasRole('BACKOFFICE')")
public ResponseEntity<?> page(@RequestBody ObjectNode json, Pageable pageable,  Authentication authentication) throws ApplicationException{
   ...
}

@RestController
@PreAuthorize("hasRole('BACKOFFICE')")
public abstract class TableController {
   ...
}

it works and roles are checked. I need to annotate the derived class but there @PreAuthorized annotation is ignored.

@RestController
@PreAuthorize("hasRole('BACKOFFICE')")
public class UtentiController extends TableController{
  ...
}

Is there a different annotation or a cofinguration required?

My security configuration is

@Configuration
@EnableWebSecurity
@EnableTransactionManagement
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailServiceImpl userService;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
        auth.userDetailsService(userService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
            .authorizeRequests()
                .antMatchers( "/css/**",  "/libs/**","/js/**", "/api/**", "/assets/**", "/register", "/public/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .logoutSuccessUrl("/login?logout")
                .permitAll()
                .and()
            .csrf().disable();
    }
}


问:
Since React and Angular follow different approaches to route multiple pages, how does it affect the rendering speed?
New to learning React, i am curious about this difference.

I read that Angular has static routing and React has dynamic. What i could make of this is the routes could be changed even while the app is being rendered until the router piece is itself called making changes very convenient, but i am curious as to how it affects the speed with which the web app loads.


问:
How to make keycloak load users group membership changes from LDAP with each authorization in the application?
I have configured periodic full synchronization with ldap in user federation. I use group-ldap-mapper, it works fine. When the admin adds a user to a new group in LDAP (ACtive Directory), these changes will appear in keycloac only after the next synchronization. How to make it so that when the user logs into the application, the user's group membership changes from LDAP to keycloak are always loaded?

I'm interested in the following scenario:

The user has already been imported into the Keycloak database from LDAP and successfully logs into the application

The LDAP administrator includes the user in a new group

Keylock changes will appear only after full synchronization with LDAP.

How can I make the synchronization of user groups work the next time the user logs into the application?


问:
Anaconda installation
I've installed anaconda on ubuntu, and after that I am unable to install packages it has with pip for every other project in which I use pyCharm. cmd says that when I want to import one of its packages:
Requirement already satisfied: pandas in /home/michal/anaconda3/lib/python3.7/site-packages (0.23.4)
Requirement already satisfied: python-dateutil>=2.5.0 in /home/michal/anaconda3/lib/python3.7/site-packages (from pandas) (2.7.3)
Requirement already satisfied: pytz>=2011k in /home/michal/anaconda3/lib/python3.7/site-packages (from pandas) (2018.5)
Requirement already satisfied: numpy>=1.9.0 in /home/michal/anaconda3/lib/python3.7/site-packages (from pandas) (1.15.1)
Requirement already satisfied: six>=1.5 in /home/michal/anaconda3/lib/python3.7/site-packages (from python-dateutil>=2.5.0->pandas) (1.11.0)

I am a new linux user, just started learning. Did I install anaconda wrong or do I have to somehow use pip only within venv for each particular package install?

I've tried to find answer online, I want to be able to use pip for packages again.

Title: Anaconda installation


问:
How to connect WordPress media to another host?
I have uploaded about 1000 PDF files in the media section of the WordPress site, how can I transfer the files to another host and change the links of the files in the content of the site?

the second question, is there a plugin or a method that only files with a specific format, for example, PDF, can be uploaded to another host when uploaded in WordPress, and the images remain on the main host?


问:
Prisma: Finding users in the same chat room
```<code>model Chatroom {
  room_id     Int           @id @default(autoincrement())
  Participant Participant[]
  Message     Message[]
}

model Participant {
  participant_id Int @id @default(autoincrement())

  roomId          Chatroom @relation(fields: [chatroomRoom_id], references: [room_id])
  chatroomRoom_id Int

  user_id User @relation(fields: [userId], references: [id])
  userId  Int
}
</code>```

Is there a way to find if two target participants have a chatroom together in the Prisma client?

I've tried querying both users rooms and filtering it where I can find the room the two users are in exist but I want to know if there's a way to do this in prisma findFirst.

Body:
model Chatroom {
  room_id     Int           @id @default(autoincrement())
  Participant Participant[]
  Message     Message[]
}

model Participant {
  participant_id Int @id @default(autoincrement())

  roomId          Chatroom @relation(fields: [chatroomRoom_id], references: [room_id])
  chatroomRoom_id Int

  user_id User @relation(fields: [userId], references: [id])
  userId  Int
}

Is there a way to find if two target participants have a chatroom together in the Prisma client?

I've tried querying both users rooms and filtering it where I can find the room the two users are in exist but I want to know if there's a way to do this in prisma findFirst.


问:
Docker Compose - give access to docker.sock before running (Telegraf)
UPDATE:

I've tried implementing the accepted answer from here Telegraf can not connect to Docker sock like this in my docker compose file:

```<code>telegraf3:
  image: telegraf
  user: telegraf:$$(stat -c '%g' /var/run/docker.sock)
  volumes:
    - ./telegraf/telegraf3.conf:/etc/telegraf/telegraf.conf
    - /var/run/docker.sock:/var/run/docker.sock
</code>```

I am getting this error:

```<code>Error response from daemon: unable to find group $(stat -c '%g' /var/run/docker.sock): no matching entries in group file
</code>```

How can i fix this issue? :)

Background:

I'm trying to run Telegraf (https://github.com/influxdata/telegraf) with the docker input. I'm running Telegraf via Docker Compose, and i've configured it roughly like this:

```<code>telegraf3:
  image: telegraf
  volumes:
    - ./telegraf/telegraf3.conf:/etc/telegraf/telegraf.conf
    - /var/run/docker.sock:/var/run/docker.sock:rw
  env_file:
    - ./telegraf/telegraf.env
  depends_on:
    - influxdb
</code>```

The telegraf configuration uses a docker input plugin to interact with the docker.sock. It doesn't work, i get a permission related error:

```<code>test-grafana-telegraf3-1  | 2022-12-29T12:09:10Z E! [inputs.docker] Error in plugin: Got permission denied while trying to connect to the Docker daemon socket at unix:///docker.sock: Get "http://%2Fdocker.sock/v1.24/info": dial unix /docker.sock: connect: permission denied
</code>```

Basically, the entrypoint.sh script runs telegraf (the application) with the telegraf user, which can't access the docker.sock

There's a fix for this issue described here: Telegraf can not connect to Docker sock

Issue

As i am using docker compose, i would like this fix to be defined in the compose file, and not be dependent on me starting the container with docker run.

I've tried this:

```<code>telegraf3:
  image: telegraf
  volumes:
    - ./telegraf/telegraf3.conf:/etc/telegraf/telegraf.conf
    - /var/run/docker.sock:/var/run/docker.sock:rw
  env_file:
    - ./telegraf/telegraf.env
  depends_on:
    - influxdb
  command: ["bash -c -u telegraf $$(stat -c '%g' /var/run/docker.sock)", "/entrypoint.sh"]
</code>```

But then i get this error:

```<code>test-grafana-telegraf3-1  | setpriv: failed to execute bash -c -u telegraf $(stat -c '%g' /var/run/docker.sock): No such file or directory
</code>```

test-grafana-telegraf3-1 exited with code 127

Body:
UPDATE:

I've tried implementing the accepted answer from here Telegraf can not connect to Docker sock like this in my docker compose file:

telegraf3:
  image: telegraf
  user: telegraf:$$(stat -c '%g' /var/run/docker.sock)
  volumes:
    - ./telegraf/telegraf3.conf:/etc/telegraf/telegraf.conf
    - /var/run/docker.sock:/var/run/docker.sock

I am getting this error:

Error response from daemon: unable to find group $(stat -c '%g' /var/run/docker.sock): no matching entries in group file

How can i fix this issue? :)

Background:

I'm trying to run Telegraf (https://github.com/influxdata/telegraf) with the docker input. I'm running Telegraf via Docker Compose, and i've configured it roughly like this:

telegraf3:
  image: telegraf
  volumes:
    - ./telegraf/telegraf3.conf:/etc/telegraf/telegraf.conf
    - /var/run/docker.sock:/var/run/docker.sock:rw
  env_file:
    - ./telegraf/telegraf.env
  depends_on:
    - influxdb

The telegraf configuration uses a docker input plugin to interact with the docker.sock. It doesn't work, i get a permission related error:

test-grafana-telegraf3-1  | 2022-12-29T12:09:10Z E! [inputs.docker] Error in plugin: Got permission denied while trying to connect to the Docker daemon socket at unix:///docker.sock: Get "http://%2Fdocker.sock/v1.24/info": dial unix /docker.sock: connect: permission denied

Basically, the entrypoint.sh script runs telegraf (the application) with the telegraf user, which can't access the docker.sock

There's a fix for this issue described here: Telegraf can not connect to Docker sock

Issue

As i am using docker compose, i would like this fix to be defined in the compose file, and not be dependent on me starting the container with docker run.

I've tried this:

telegraf3:
  image: telegraf
  volumes:
    - ./telegraf/telegraf3.conf:/etc/telegraf/telegraf.conf
    - /var/run/docker.sock:/var/run/docker.sock:rw
  env_file:
    - ./telegraf/telegraf.env
  depends_on:
    - influxdb
  command: ["bash -c -u telegraf $$(stat -c '%g' /var/run/docker.sock)", "/entrypoint.sh"]

But then i get this error:

test-grafana-telegraf3-1  | setpriv: failed to execute bash -c -u telegraf $(stat -c '%g' /var/run/docker.sock): No such file or directory

test-grafana-telegraf3-1 exited with code 127