问:
py-cord: How do I delete the last n messages of a user?
I am writing an anti-spam bot in py-cord and I would like to delete a users last n messages automatically once they reach the pressure limit (= too much spam). My code for just deleting the messages so far is:

```<code>95 counter = 0
96 while counter < 10:
97    for channel in message.guild.channels:
98        for msg in channel.messages:
99            if msg.author.id == message.author.id and counter < 10:
100               await msg.delete()
101               counter += 1
</code>```

and the error that I get is

```<code>Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\Username\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\Username\OneDrive\Desktop\Dateien\Python\MessageCheck\messagecheck.py", line 98, in on_message
    for msg in channel.messages:
AttributeError: 'CategoryChannel' object has no attribute 'messages'
</code>```

I tried searching for similar questions on StackOverflow, but the closest I got was 50301090, which doesn't quite answer my question as I don't want to use a command for this and it seems like it could put some strain onto the cache if it's run for some time.

答:
Based upon the error, I'd say you are missing an indented block, making your first for loop do effectively nothing.

Try:

```<code>95 counter = 0
96 while counter < 10:
97    for channel in message.guild.channels:
98        for msg in channel.messages:
99            if msg.author.id == message.author.id and counter < 10:
100               await msg.delete()
101               counter += 1
</code>```

Or the Error is saying you are not scoping properly.

Body:
I am writing an anti-spam bot in py-cord and I would like to delete a users last n messages automatically once they reach the pressure limit (= too much spam). My code for just deleting the messages so far is:

95 counter = 0
96 while counter < 10:
97    for channel in message.guild.channels:
98        for msg in channel.messages:
99            if msg.author.id == message.author.id and counter < 10:
100               await msg.delete()
101               counter += 1

and the error that I get is

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\Username\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\Username\OneDrive\Desktop\Dateien\Python\MessageCheck\messagecheck.py", line 98, in on_message
    for msg in channel.messages:
AttributeError: 'CategoryChannel' object has no attribute 'messages'

I tried searching for similar questions on StackOverflow, but the closest I got was 50301090, which doesn't quite answer my question as I don't want to use a command for this and it seems like it could put some strain onto the cache if it's run for some time.

Body:
Based upon the error, I'd say you are missing an indented block, making your first for loop do effectively nothing.

Try:

95 counter = 0
96 while counter < 10:
97    for channel in message.guild.channels:
98        for msg in channel.messages:
99            if msg.author.id == message.author.id and counter < 10:
100               await msg.delete()
101               counter += 1

Or the Error is saying you are not scoping properly.


来源: stackexchange

问:
Is indexing into an array with a signal synthesizable in verilog?
Are there any problems with synthesizing the following?:

```<code> // Read entry
  assign entry[7:0] = my_array[read_address[10:0]][7:0];
</code>```

Where read_address is a signal being used to read my_array.

I'm used to AND-OR logic for reading an array but I was wondering if the above is 1) synthesizable and 2) what kind of logic it would create?

答:
Yes, you can use another variable or expression as an index into an array. The catch is you are only allowed to do this on the RHS of a continuous assignment. You would not be allowed to do the reverse

```<code>assign my_array[read_address[10:0]] = entry; // illegal
</code>```

Also, there is no need to select [7:0] if that is the entire range of the element or signals. In fact that causes problems with signed signals making them unsigned operands.

ContentLicense: CC BY-SA 4.0

Body:
Are there any problems with synthesizing the following?:

 // Read entry
  assign entry[7:0] = my_array[read_address[10:0]][7:0];

Where read_address is a signal being used to read my_array.

I'm used to AND-OR logic for reading an array but I was wondering if the above is 1) synthesizable and 2) what kind of logic it would create?

Body:
Yes, you can use another variable or expression as an index into an array. The catch is you are only allowed to do this on the RHS of a continuous assignment. You would not be allowed to do the reverse

assign my_array[read_address[10:0]] = entry; // illegal

Also, there is no need to select [7:0] if that is the entire range of the element or signals. In fact that causes problems with signed signals making them unsigned operands.


问:
Failed to resolve module specifier "three" - Working Three/Wordpress Integration Suddenly Failed
I manage a WordPress website which uses a Three.js animation on the homepage. I built this site months ago and everything had been working perfectly fine - I even showed it to someone a week ago and nothing was amiss. Yesterday, I check the site and find that Three is not loading, and that I have this in the console:

Uncaught TypeError: Failed to resolve module specifier "three". Relative references must start with either "/", "./", or "../".

I don't have a line or even file to reference, the error is logged coming from the first line of the root domain. I want to emphasize that I had changed absolutely nothing about the set-up. I hadn't even updated to WP 5.9 yet. This is how I had originally set things up. Sorry if it's not best practices, but I want to emphasize that it did in fact work fine.
Enqueuing animation javascript file and defining its type as "module":

```<code>function my_custom_scripts() {
    wp_enqueue_script( 'gsap', 'https://cdnjs.cloudflare.com/ajax/libs/gsap/3.7.0/gsap.min.js', array( 'jquery' ), '', true);
    wp_enqueue_script( 'scrolltrigger', 'https://cdnjs.cloudflare.com/ajax/libs/gsap/3.7.0/ScrollTrigger.min.js', array( 'gsap' ), '', true);
    wp_enqueue_script( 'custom-animations', get_stylesheet_directory_uri() . '/js/animations.js', array( 'gsap' ),'',true );

}
add_action( 'wp_enqueue_scripts', 'my_custom_scripts', 15);

add_filter('script_loader_tag','add_type_to_script', 10, 3);
function add_type_to_script($tag, $handle, $source){
    if ('custom-animations' === $handle) {
        $tag = '<script type="module" src="'. $source .'"></script>';
    }
    return $tag;
}
</code>```

First lines of "animations.js":

```<code>import * as THREE from 'https://cdn.skypack.dev/three@0.137.5/build/three.module.js';
import { GLTFLoader } from "https://threejs.org/examples/jsm/loaders/GLTFLoader.js";
import { DRACOLoader } from 'https://threejs.org/examples/jsm/loaders/DRACOLoader.js';
</code>```

If there is other relevant code to this problem, please let me know, but I've been pouring over this and tried A) downloading the module file and putting it on my own server and providing a relative path, the same console issue appears (though it did complain with a 404 if the link was invalid, suggesting it did follow it). B) downloading the three.min.js file and loading it before this one, removing the module call entirely and I still get the same console error (even though it's not even being imported as a module). This site has been hosted on Cloudflare, so I did disable that first. Clearing the cache changed nothing, and I have confirmed at every step that I have not been loading a cached version. In the Network tab of Chrome dev tools, the module/file gets loaded into the cache just fine. Somewhere along the way, some file (I wish the console would specify, maybe that is indicative of the problem) fails to attach "Three" as a module and I have no idea why. Any help would be massively appreciated!

答:
I had exact same problem. I uploaded my project on Github a month ago (https://kramzin.github.io/threejs-task/) and since then didn't change a one symbol, but about a week ago it started showing same strange error in console. I found following:
"Since r137 using ES6 modules like GLTFLoader in the browser requires an import map. Add the following section right below you canvas."

```<code><script type="importmap">
    {
        "imports": {
            "three": "../master/three.js-master/build/three.module.js"
        }
    }
</script>
</code>```

The three.js import statement in your scripts.js looks like so then:

```<code>import * as THREE from 'three'
</code>```

https://github.com/Kramzin/threejs-task - Here you can see updated and previous code, after these changes everything started working

Body:
I manage a WordPress website which uses a Three.js animation on the homepage. I built this site months ago and everything had been working perfectly fine - I even showed it to someone a week ago and nothing was amiss. Yesterday, I check the site and find that Three is not loading, and that I have this in the console:

Uncaught TypeError: Failed to resolve module specifier "three". Relative references must start with either "/", "./", or "../".

I don't have a line or even file to reference, the error is logged coming from the first line of the root domain. I want to emphasize that I had changed absolutely nothing about the set-up. I hadn't even updated to WP 5.9 yet. This is how I had originally set things up. Sorry if it's not best practices, but I want to emphasize that it did in fact work fine.
Enqueuing animation javascript file and defining its type as "module":

function my_custom_scripts() {
    wp_enqueue_script( 'gsap', 'https://cdnjs.cloudflare.com/ajax/libs/gsap/3.7.0/gsap.min.js', array( 'jquery' ), '', true);
    wp_enqueue_script( 'scrolltrigger', 'https://cdnjs.cloudflare.com/ajax/libs/gsap/3.7.0/ScrollTrigger.min.js', array( 'gsap' ), '', true);
    wp_enqueue_script( 'custom-animations', get_stylesheet_directory_uri() . '/js/animations.js', array( 'gsap' ),'',true );

}
add_action( 'wp_enqueue_scripts', 'my_custom_scripts', 15);

add_filter('script_loader_tag','add_type_to_script', 10, 3);
function add_type_to_script($tag, $handle, $source){
    if ('custom-animations' === $handle) {
        $tag = '';
    }
    return $tag;
}

First lines of "animations.js":

import * as THREE from 'https://cdn.skypack.dev/three@0.137.5/build/three.module.js';
import { GLTFLoader } from "https://threejs.org/examples/jsm/loaders/GLTFLoader.js";
import { DRACOLoader } from 'https://threejs.org/examples/jsm/loaders/DRACOLoader.js';

If there is other relevant code to this problem, please let me know, but I've been pouring over this and tried A) downloading the module file and putting it on my own server and providing a relative path, the same console issue appears (though it did complain with a 404 if the link was invalid, suggesting it did follow it). B) downloading the three.min.js file and loading it before this one, removing the module call entirely and I still get the same console error (even though it's not even being imported as a module). This site has been hosted on Cloudflare, so I did disable that first. Clearing the cache changed nothing, and I have confirmed at every step that I have not been loading a cached version. In the Network tab of Chrome dev tools, the module/file gets loaded into the cache just fine. Somewhere along the way, some file (I wish the console would specify, maybe that is indicative of the problem) fails to attach "Three" as a module and I have no idea why. Any help would be massively appreciated!

Body:
I had exact same problem. I uploaded my project on Github a month ago (https://kramzin.github.io/threejs-task/) and since then didn't change a one symbol, but about a week ago it started showing same strange error in console. I found following:
"Since r137 using ES6 modules like GLTFLoader in the browser requires an import map. Add the following section right below you canvas."

<script type="importmap">
    {
        "imports": {
            "three": "../master/three.js-master/build/three.module.js"
        }
    }
</script>

The three.js import statement in your scripts.js looks like so then:

import * as THREE from 'three'

https://github.com/Kramzin/threejs-task - Here you can see updated and previous code, after these changes everything started working


问:
Kotlin Data Class Parsing Mutiple member properties at once
Let say I have a data class called Class A

```<code>data class ClassA {
 val x0 = ""
 val x1 = "some string"
 val x2 = "some string"
 val x3 = "some string"
 val x4 = "some string"
 val x5 = ""
 val x6 = ""
 val y = ""
 val z = ""
}
</code>```

I can retrieve the value of these class member thru its class object

```<code>val obj = ClassA()
// if the properties has prefix x and not empty then concatenate to this x variable
val x = obj.x1 + obj.x2 + etc...
...
</code>```

Let say if this data class has 50+ x(n) in it and I want to retrieve any member that does not have an "empty string or null" and match the prefix then how do I do it dynamically (can be a for-loop), instead of type out statically every single properties that I want to retrieve, is there an alternative way to do it?

答:
I'm going to answer you question and provide a way of doing it, however, I highly recommend against doing it this way simply because while it works, it is seen as hacky and you'd be better off solving this by changing the multiple fields/properties into a collection of some sort instead.

You can use reflection to do it without having to type out all of the values manually.

To do it via reflection, you will have to do something like this.

```<code>fun getNonEmptyStrings(input: A): List<String> {
    val members = A::class.memberProperties

    return members
        .filter { it.name.startsWith("x") }
        .map { it.get(input) }
        .filterIsInstance<String>()
        .filter { it.isNotBlank() }
}
</code>```

There might be some other form of meta-programming that is better suited to this, but I'm not sure what that would be.

Body:
Let say I have a data class called Class A

data class ClassA {
 val x0 = ""
 val x1 = "some string"
 val x2 = "some string"
 val x3 = "some string"
 val x4 = "some string"
 val x5 = ""
 val x6 = ""
 val y = ""
 val z = ""
}

I can retrieve the value of these class member thru its class object

val obj = ClassA()
// if the properties has prefix x and not empty then concatenate to this x variable
val x = obj.x1 + obj.x2 + etc...
...

Let say if this data class has 50+ x(n) in it and I want to retrieve any member that does not have an "empty string or null" and match the prefix then how do I do it dynamically (can be a for-loop), instead of type out statically every single properties that I want to retrieve, is there an alternative way to do it?

Body:
I'm going to answer you question and provide a way of doing it, however, I highly recommend against doing it this way simply because while it works, it is seen as hacky and you'd be better off solving this by changing the multiple fields/properties into a collection of some sort instead.

You can use reflection to do it without having to type out all of the values manually.

To do it via reflection, you will have to do something like this.

fun getNonEmptyStrings(input: A): List<String> {
    val members = A::class.memberProperties

    return members
        .filter { it.name.startsWith("x") }
        .map { it.get(input) }
        .filterIsInstance<String>()
        .filter { it.isNotBlank() }
}

There might be some other form of meta-programming that is better suited to this, but I'm not sure what that would be.


问:
PYTHON: How to take a .txt file as input from user using raw_input in Python and then read that file row wise?
I want to take a .txt file as input from user through raw_input.

Once the input is taken, I want the txt file name given by user to be accessed and the contents from it written into another file (each in next row).

I am having a problem with how to connect a and b above or how to link raw input with reading of file. I need help...the code is as follows (but it is erroneous :S).

```<code>import sys,os,csv

x = raw_input("Enter name of file to be written row wise:")
ui = "x" + txt
for ui in x:
    data = open("ui").readlines()
    outfile = open("myfile.csv","w")
    out = csv.writer(outfile)
for row in data:
    row = row.strip().split(';')
    if row:
        for subrow in row:
            subrow = subrow.strip().split()
            if subrow:
                out.writerow(subrow)
outfile.close()
</code>```

I get the error:

cannot concatenate 'str' and 'list' objects

答:
corrected code below </p>

```<code>import sys,os,csv

x = raw_input("Enter name of file to be written row wise:")
input_filename = x + ".txt"
input_file = open(input_filename)
outfile = open("myfile.csv","wb")
out = csv.writer(outfile)
for row in input_file:
    row = row.strip().split(';')
    if row:
        for subrow in row:
            subrow = subrow.strip().split()
            if subrow:
                out.writerow(subrow)
input_file.close()
outfile.close()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to take a .txt file as input from user through raw_input.

Once the input is taken, I want the txt file name given by user to be accessed and the contents from it written into another file (each in next row).

I am having a problem with how to connect a and b above or how to link raw input with reading of file. I need help...the code is as follows (but it is erroneous :S).

import sys,os,csv

x = raw_input("Enter name of file to be written row wise:")
ui = "x" + txt
for ui in x:
    data = open("ui").readlines()
    outfile = open("myfile.csv","w")
    out = csv.writer(outfile)
for row in data:
    row = row.strip().split(';')
    if row:
        for subrow in row:
            subrow = subrow.strip().split()
            if subrow:
                out.writerow(subrow)
outfile.close()

I get the error:

cannot concatenate 'str' and 'list' objects

Body:
corrected code below

import sys,os,csv

x = raw_input("Enter name of file to be written row wise:")
input_filename = x + ".txt"
input_file = open(input_filename)
outfile = open("myfile.csv","wb")
out = csv.writer(outfile)
for row in input_file:
    row = row.strip().split(';')
    if row:
        for subrow in row:
            subrow = subrow.strip().split()
            if subrow:
                out.writerow(subrow)
input_file.close()
outfile.close()


问:
Making a scrictly increasing graph into a sinus rhythm sort of graph
Right now I have a graph of this sort:

But I want to make the above graph into something like this:

Can anyone guide me how to do this using Matplotlib?

答:
try plotting the first difference of your time series such as:

# sample data (this is your "before" data):
df = pd.DataFrame({'data you are plotting now': [1, 2, 3, 4]})

# new data to plot:
df['new data'] = df['data you are plotting now'] - df['data you are plotting now'].shift()
```

assuming data['data you are plotting now'] is your current time series

I should add that generally you should add your code and your input data as well as your expected output data and not images.

Body:
try plotting the first difference of your time series such as:

# sample data (this is your "before" data):
df = pd.DataFrame({'data you are plotting now': [1, 2, 3, 4]})

# new data to plot:
df['new data'] = df['data you are plotting now'] - df['data you are plotting now'].shift()

assuming data['data you are plotting now'] is your current time series

I should add that generally you should add your code and your input data as well as your expected output data and not images.


问:
Android Is it possible to define a map in an XML file?
I was trying to define a static hash table that makes use of resources, but I got stonewalled by the impossibility of accessing resources statically.

Then I realized that the best of all places to define a static map is in the resources files themselves.

How can I define a map in  XML?
I believe that if possible it should be similar to the Listpreference mechanism, with entries and entries-values.

答:
Android often works with DefaultsXmlParser.getDefaultsFromXml() which parse next syntax:

```<code><?xml version="1.0" encoding="utf-8"?>
<defaults>
    <entry>
        <key>api_url</key>
        <value>https://</value>
    </entry>
    <entry>
        <key>some_feature_flag</key>
        <value>true</value>
    </entry>
</defaults>
</code>```

And read map:

```<code>val map = DefaultsXmlParser.getDefaultsFromXml(this, R.xml.my_map)
</code>```

Body:
Android often works with DefaultsXmlParser.getDefaultsFromXml() which parse next syntax:

<?xml version="1.0" encoding="utf-8"?>
<defaults>
    <entry>
        <key>api_url</key>
        <value>https://</value>
    </entry>
    <entry>
        <key>some_feature_flag</key>
        <value>true</value>
    </entry>
</defaults>

And read map:

val map = DefaultsXmlParser.getDefaultsFromXml(this, R.xml.my_map)


问:
hashtable values reordered
I have a hashtable, which contains strings for example, when I use put method as below

```<code> hashtable.put("1","A");
 hashtable.put("1","B");
 hashtable.put("1","C");
 hashtable.put("1","D");
 hashtable.put("1","E");
</code>```

Then when I try to print it back it doesn't print in same order, Any one knows why would something like this happen?

```<code> Collection c = ht.values();
 Iterator itr = c.iterator();
 while(itr.hasNext())
 System.out.println(itr.next());
</code>```

Thanks
Max

答: you should use LinkedHashMap if you want to print items in order.</p>

Title: hashtable values reordered

Body:
I have a hashtable, which contains strings for example, when I use put method as below

 hashtable.put("1","A");
 hashtable.put("1","B");
 hashtable.put("1","C");
 hashtable.put("1","D");
 hashtable.put("1","E");

Then when I try to print it back it doesn't print in same order, Any one knows why would something like this happen?

 Collection c = ht.values();
 Iterator itr = c.iterator();
 while(itr.hasNext())
 System.out.println(itr.next());

Thanks
Max


问:
Button's background color turns grey when mouse hovering on it C# Winforms
I made a simple design for my WinForms app in Photoshop and I want to make some borderless buttons. In FlatAppearance properties, I changed border size to 0 and the FlatSyle is Flat but when the mouse is hovering on the button, its background color turns to grey, although I changed it to transparent. I'll attach some pics to get the problem better.

Can somebody help me, please?

How I want to look:

how it looks

答: In the same place that you changed the border size to zero, change the MouseOverBackColor to Transparent:


问:
GestureDetector does not work after Transform and Offset Animation (Flutter)
I want to create an spinning animation with a set of buttons - arranged in a circle - that rotate and extend from a clicked center button.

While animation and rotation work well, and the open button and close button work smoothly and respond to onTap() in spite of rotation, the outer buttons do not work in terms of "onTap"-GestureDetector.

Goal: I want to make the red container clickable (e.g. GestureDetector).
Problem: Red container does not react to onTap().

```<code>import "dart:developer" as dev;
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:sdg3/Widget/rotation_controller.dart';
import 'package:sdg3/Widget/rotation_menu_button.dart';
import 'package:vector_math/vector_math.dart' show radians, Vector3;

class RadialMenu extends StatefulWidget {
  final Widget open;
  final Widget? close;
  final int startAngle;
  final List<RotationMenuButton> rotationButtons;
  final RotationController? rotationController;

  const RadialMenu({
    Key? key,
    this.rotationController,
    required this.open,
    this.startAngle = 0,
    this.close,
    required this.rotationButtons,
  }) : super(key: key);

  @override
  createState() => _RadialMenuState();
}

class _RadialMenuState extends State<RadialMenu>
    with SingleTickerProviderStateMixin {
  late AnimationController controller;
  late double maxButtonRadius;

  @override
  void initState() {
    super.initState();
    //get "biggest" button
    maxButtonRadius = widget.rotationButtons.map((e) => e.size).reduce(max);

    controller = AnimationController(
        duration: const Duration(milliseconds: 1500), vsync: this)
      ..addListener(() => setState(() {}));
    translation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(
      CurvedAnimation(parent: controller, curve: Curves.easeInOutCirc),
    );
    scale = Tween<double>(
      begin: 1.5,
      end: 0.0,
    ).animate(
      CurvedAnimation(parent: controller, curve: Curves.fastOutSlowIn),
    );
    rotation = Tween<double>(
      begin: 0.0,
      end: 360.0,
    ).animate(
      CurvedAnimation(
        parent: controller,
        curve: const Interval(
          0.0,
          0.7,
          curve: Curves.easeInOutCirc,
        ),
      ),
    );
  }

 @override
  Widget build(BuildContext context) {
    Widget open = widget.open;
    Widget? close = widget.close;
    var buttonsMap = widget.rotationButtons.asMap();
    List<Widget> buttons = buttonsMap.entries.map((e) {
      RotationMenuButton button = e.value;
      double singleangle = 360.0 / buttonsMap.length;
      double angle = (e.key * singleangle + widget.startAngle) % 360;
      return LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
          double menuwidth = (min(constraints.maxWidth, constraints.maxHeight) -
                  maxButtonRadius) /
              2.0;
          //minimizie space between cicrles
          double dimensionsOfButton = 1 + button.size * (1 - scale.value / 1.5);

          double overlapRadiusOfButton =
              2.0 * sin(radians(singleangle / 2.0)) * menuwidth;
          if (dimensionsOfButton > overlapRadiusOfButton) {
            dimensionsOfButton = overlapRadiusOfButton - 5;
          }

          return Visibility(
            visible: scale.value < 1.0,
            child: Container(
              color: Colors.blue,
              child: Transform(
                transform: Matrix4.identity()
                  ..translate(
                      (translation.value * menuwidth) * cos(radians(angle)),
                      (translation.value * menuwidth) * sin(radians(angle))),
                child: ConstrainedBox(
                  constraints: BoxConstraints(
                      maxHeight: dimensionsOfButton,
                      maxWidth: dimensionsOfButton),
                  child: GestureDetector(
                      onTap: () => dev.log("I was pushed"),
                      child: Container(color: Colors.red)),
                ),
              ),
            ),
          );
        },
      );
    }).toList(growable: false);

    return AnimatedBuilder(
      animation: controller,
      builder: (context, widget) {
        return Transform.rotate(
          angle: radians(rotation.value),
          child: Stack(
            clipBehavior: Clip.none,
            alignment: Alignment.center,
            children: [
              if (close != null)
                Transform.scale(
                  scale: 1.5 - scale.value,
                  child: GestureDetector(
                    onTap: _close,
                    child: close,
                  ),
                ),
              Transform.scale(
                scale: scale.value,
                child: GestureDetector(
                  onTap: _open,
                  child: open,
                ),
              ),
              buttons.first
            ],
          ),
        );
      },
    );
  }

  late final Animation<double> rotation;
  late final Animation<double> translation;
  late final Animation<double> scale;

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  _open() {
    controller.forward();
  }

  _close() {
    controller.reverse();
  }

</code>```

The problem is the dev.log("I was pushed"). It never appears (also inkwell does not work neither does a GestureDetector.behaviour).

This is the output of the animation. The blue container ist just for visualisation where the Container is placed before Tranform, the red container is the correct "Button" after transform which does not respond to onTap():

When I remove the translation:

```<code>                  ..translate(
                      (translation.value * menuwidth) * cos(radians(angle)),
                      (translation.value * menuwidth) * sin(radians(angle))),
</code>```

it works, however that is not the desired output.

I have the impression that hit-Tests are not tranlated correctly. Do you have an idea? Thanks!

答:
I used a workaround using Positioned instead of translation. You´ll require a bit mathematics to repositioned it but it works with GestureDetector onTap() (here not shown, but its inside the button widget) including translation:

```<code>          return Visibility(
            visible: scale.value < 1.0,
            child: Stack(
              children: [
                Positioned(
                  left: constraints.maxWidth / 2 -
                      maxButtonRadius / 2 +
                      (translation.value * menuwidth) * cos(radians(angle)),
                  top: constraints.maxHeight / 2 -
                      maxButtonRadius / 2 +
                      (translation.value * menuwidth) * sin(radians(angle)),
                  child: SizedBox(
                    height: dimensionsOfButton,
                    width: dimensionsOfButton,
                    child: button,
                  ),
                ),
              ],
            ),
          );
</code>```

Body:
I want to create an spinning animation with a set of buttons - arranged in a circle - that rotate and extend from a clicked center button.

While animation and rotation work well, and the open button and close button work smoothly and respond to onTap() in spite of rotation, the outer buttons do not work in terms of "onTap"-GestureDetector.

Goal: I want to make the red container clickable (e.g. GestureDetector).
Problem: Red container does not react to onTap().

import "dart:developer" as dev;
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:sdg3/Widget/rotation_controller.dart';
import 'package:sdg3/Widget/rotation_menu_button.dart';
import 'package:vector_math/vector_math.dart' show radians, Vector3;

class RadialMenu extends StatefulWidget {
  final Widget open;
  final Widget? close;
  final int startAngle;
  final List<RotationMenuButton> rotationButtons;
  final RotationController? rotationController;

  const RadialMenu({
    Key? key,
    this.rotationController,
    required this.open,
    this.startAngle = 0,
    this.close,
    required this.rotationButtons,
  }) : super(key: key);

  @override
  createState() => _RadialMenuState();
}

class _RadialMenuState extends State<RadialMenu>
    with SingleTickerProviderStateMixin {
  late AnimationController controller;
  late double maxButtonRadius;

  @override
  void initState() {
    super.initState();
    //get "biggest" button
    maxButtonRadius = widget.rotationButtons.map((e) => e.size).reduce(max);

    controller = AnimationController(
        duration: const Duration(milliseconds: 1500), vsync: this)
      ..addListener(() => setState(() {}));
    translation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(
      CurvedAnimation(parent: controller, curve: Curves.easeInOutCirc),
    );
    scale = Tween<double>(
      begin: 1.5,
      end: 0.0,
    ).animate(
      CurvedAnimation(parent: controller, curve: Curves.fastOutSlowIn),
    );
    rotation = Tween<double>(
      begin: 0.0,
      end: 360.0,
    ).animate(
      CurvedAnimation(
        parent: controller,
        curve: const Interval(
          0.0,
          0.7,
          curve: Curves.easeInOutCirc,
        ),
      ),
    );
  }

 @override
  Widget build(BuildContext context) {
    Widget open = widget.open;
    Widget? close = widget.close;
    var buttonsMap = widget.rotationButtons.asMap();
    List<Widget> buttons = buttonsMap.entries.map((e) {
      RotationMenuButton button = e.value;
      double singleangle = 360.0 / buttonsMap.length;
      double angle = (e.key * singleangle + widget.startAngle) % 360;
      return LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
          double menuwidth = (min(constraints.maxWidth, constraints.maxHeight) -
                  maxButtonRadius) /
              2.0;
          //minimizie space between cicrles
          double dimensionsOfButton = 1 + button.size * (1 - scale.value / 1.5);

          double overlapRadiusOfButton =
              2.0 * sin(radians(singleangle / 2.0)) * menuwidth;
          if (dimensionsOfButton > overlapRadiusOfButton) {
            dimensionsOfButton = overlapRadiusOfButton - 5;
          }

          return Visibility(
            visible: scale.value < 1.0,
            child: Container(
              color: Colors.blue,
              child: Transform(
                transform: Matrix4.identity()
                  ..translate(
                      (translation.value * menuwidth) * cos(radians(angle)),
                      (translation.value * menuwidth) * sin(radians(angle))),
                child: ConstrainedBox(
                  constraints: BoxConstraints(
                      maxHeight: dimensionsOfButton,
                      maxWidth: dimensionsOfButton),
                  child: GestureDetector(
                      onTap: () => dev.log("I was pushed"),
                      child: Container(color: Colors.red)),
                ),
              ),
            ),
          );
        },
      );
    }).toList(growable: false);

    return AnimatedBuilder(
      animation: controller,
      builder: (context, widget) {
        return Transform.rotate(
          angle: radians(rotation.value),
          child: Stack(
            clipBehavior: Clip.none,
            alignment: Alignment.center,
            children: [
              if (close != null)
                Transform.scale(
                  scale: 1.5 - scale.value,
                  child: GestureDetector(
                    onTap: _close,
                    child: close,
                  ),
                ),
              Transform.scale(
                scale: scale.value,
                child: GestureDetector(
                  onTap: _open,
                  child: open,
                ),
              ),
              buttons.first
            ],
          ),
        );
      },
    );
  }

  late final Animation<double> rotation;
  late final Animation<double> translation;
  late final Animation<double> scale;

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  _open() {
    controller.forward();
  }

  _close() {
    controller.reverse();
  }

The problem is the dev.log("I was pushed"). It never appears (also inkwell does not work neither does a GestureDetector.behaviour).

This is the output of the animation. The blue container ist just for visualisation where the Container is placed before Tranform, the red container is the correct "Button" after transform which does not respond to onTap():

When I remove the translation:

                  ..translate(
                      (translation.value * menuwidth) * cos(radians(angle)),
                      (translation.value * menuwidth) * sin(radians(angle))),

it works, however that is not the desired output.

I have the impression that hit-Tests are not tranlated correctly. Do you have an idea? Thanks!

Body:
I used a workaround using Positioned instead of translation. You´ll require a bit mathematics to repositioned it but it works with GestureDetector onTap() (here not shown, but its inside the button widget) including translation:

          return Visibility(
            visible: scale.value < 1.0,
            child: Stack(
              children: [
                Positioned(
                  left: constraints.maxWidth / 2 -
                      maxButtonRadius / 2 +
                      (translation.value * menuwidth) * cos(radians(angle)),
                  top: constraints.maxHeight / 2 -
                      maxButtonRadius / 2 +
                      (translation.value * menuwidth) * sin(radians(angle)),
                  child: SizedBox(
                    height: dimensionsOfButton,
                    width: dimensionsOfButton,
                    child: button,
                  ),
                ),
              ],
            ),
          );


问:
java format string printing unable to print
I'm unable to run the code, it says it cannot resolve println with the parameters.</p>
```<code>public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("%s : %d", this.getName(), i);
        }
    }
</code>```

答:
That is because there is no println() method that takes a format string and substitution parameters.

There is the format() method though (when using that, remember that you have to add the newline char in the line yourself).

Where: the real answer is ... in programming, every character matters. Meaning: you have to be really diligent about such things. Always read the javadoc carefully, and when you are taught: "there is no such method", then: look at the javadoc for the class you intend to use. Ensure that the method you want exists, and then ensure that the arguments you provide to it are matching the documented method signature.

Body:
I'm unable to run the code, it says it cannot resolve println with the parameters.

public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("%s : %d", this.getName(), i);
        }
    }


问:
Execute command with multiple layers of quoting via ssh
I want to execute a docker command on a remote server. The problem is I don't know to escape multiple quotes.

```<code>ret=$(ssh root@server "docker exec nginx bash -c 'cat /etc/nginx/nginx.conf | grep 'ServerName' | cut -d '|' -f1'")
</code>```

I get

```<code>bash:  -f1: command not found
</code>```

答:
Consider using here-document :

```<code>ret="$(ssh root@server << 'EOF'
docker exec nginx bash -c "grep 'ServerName' /etc/nginx/nginx.conf | cut -d '|' -f1"
EOF
)"
echo "$ret"
</code>```

Or, simpler as suggested by @MichaelVeksler :

```<code>ret="$(ssh root@server docker exec -i nginx bash << 'EOF'
grep 'ServerName' /etc/nginx/nginx.conf | cut -d '|' -f1
EOF
)"
echo "$ret"
</code>```

Body:
I want to execute a docker command on a remote server. The problem is I don't know to escape multiple quotes.

ret=$(ssh root@server "docker exec nginx bash -c 'cat /etc/nginx/nginx.conf | grep 'ServerName' | cut -d '|' -f1'")

I get

bash:  -f1: command not found

Body:
Consider using here-document :

ret="$(ssh root@server << 'EOF'
docker exec nginx bash -c "grep 'ServerName' /etc/nginx/nginx.conf | cut -d '|' -f1"
EOF
)"
echo "$ret"

Or, simpler as suggested by @MichaelVeksler :

ret="$(ssh root@server docker exec -i nginx bash << 'EOF'
grep 'ServerName' /etc/nginx/nginx.conf | cut -d '|' -f1
EOF
)"
echo "$ret"


问:
Block visitors from internet explorer or microsoft edge
I need a Javascript script to block internet explorer or microsoft edge visitors to prevent accessing my website on blogger
Edit*
Someone help me and answered the question across using user-agent</p>

答:
Every browser and app which access a website has something called a "User Agent". The UA is part of the header that is sent/received with each HTTP call.

Since accessing your website is nothing else than sending a GET-request, you can handle this by checking the user agent in the header and re-route users to a page where you can tell them that they should a different browser.
Or you could entirely block the access by not displaying any elements if the user agent is either Edge or IE.

Here is an example on how to get the user agent:

https://www.w3schools.com/jsref/prop_nav_useragent.asp

If you want a better example this could also help:

https://learn.microsoft.com/en-us/microsoft-edge/web-platform/user-agent-guidance

TL;DR: All you need to do is to check the user agent. You can either do this by pattern matching or simpler by searching if the string contains something that's only there in IE/Edge browsers and act accordingly, e.g. by re-routing or not showing/hiding all elements. (I'd avoid the 2nd suggestion, since it's not user friendly)


答:
There's little need to execute so much on the remote host. The file you want to search isn't likely that big: just pipe the entire thing down via ssh to a local awk process:

```<code>ret=$(ssh root@server "docker exec nginx cat /etc/nginx/nginx.conf" |
         awk -F'|' '/ServerName/ {print $1}')
</code>```

Title: Execute command with multiple layers of quoting via ssh

Body:
There's little need to execute so much on the remote host. The file you want to search isn't likely that big: just pipe the entire thing down via ssh to a local awk process:

ret=$(ssh root@server "docker exec nginx cat /etc/nginx/nginx.conf" |
         awk -F'|' '/ServerName/ {print $1}')


问:
Persistent warnings from earlier commands with RStudio
I'm struggling to create a reproducible example for this, but I suspect others will know what I mean.  Why does R sometimes seem to get stuck with a backlog of warnings/error messages that it repeats again after subsequent commands?  E.g. you get some warning message Bad whatever system choking after running some code, which repeats again after you enter an innocuous instruction like x <- 5. This sometimes happens after several entries of x <- 5, although it normally stops after one or two.

R has been like this for me for at least 5 years, across many versions on both Windows and Mac.  Am I alone?  Does anyone know if it has been identified as a bug?  I normally work with RStudio so I wonder if it's related to the IDE.

Edit. Pretty sure this is related to RStudio.

答:
Answer by zeehio.

This is an issue with the Diagnostics tool in RStudio (the tool that shows warnings and possible mistakes in your code). It was partially fixed at this commit in RStudio v1.1.103 or later by @kevin-ushey. That fix was partial, because the warnings still appeared (albeit with less frequency). This issue was reported with a reproducible example at https://github.com/rstudio/rstudio/issues/7372 and it was fixed on RStudio v1.4 pull request.

The warnings appear because the diagnostics tool in RStudio parses the source code to detect errors and when it performs the diagnostic checks it accesses columns in your tibble that are not initialized, giving the Warning we see. The warnings do not appear because you run unrelated things, they appear when the RStudio diagnostics are executed (when a file is saved, then modified, when you run something...).


问:
PyCharm node.js does not exists although it is installed in Path (Windows)
I have installed Node.js and it works fine when I run it from the command line on all paths. I ran npm version on the cmd and it worked fine.

But when I run the same npm version in PyCharm it says it doesn't exists although it is in the system's Path...

```<code>'npm' is not recognized as an internal or external command, operable program or batch file.
</code>```

The same things happens when I try to run Node.js cmd subproccess command...

```<code>'tr' is not recognized as an internal or external command,
</code>```

I think it comes from the same problem that Node.js doesn't exists on PyCharm.

答: What I ended up doing is to copy the Node.js files from C:\Porgram files\nodejs to the PyCharm's project's path and then restart the Ide

Body:
I have installed Node.js and it works fine when I run it from the command line on all paths. I ran npm version on the cmd and it worked fine.

But when I run the same npm version in PyCharm it says it doesn't exists although it is in the system's Path...

'npm' is not recognized as an internal or external command, operable program or batch file.

The same things happens when I try to run Node.js cmd subproccess command...

'tr' is not recognized as an internal or external command,

I think it comes from the same problem that Node.js doesn't exists on PyCharm.


问:
Sort array output python
```<code>array1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]

</code>```

I'm trying to write a code to sort the array

答:
Using list comprehension, you can do the following:

```<code>array1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
array2 = [ "c", "a","b"]

Z = [b for b in array1 if any(b in a for a in array2)]
print(Z)
</code>```

Output:

```<code>['a', 'b', 'c']
</code>```

Title: Sort array output python

Body:
array1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]

I'm trying to write a code to sort the array

Body:
Using list comprehension, you can do the following:

array1 = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
array2 = [ "c", "a","b"]

Z = [b for b in array1 if any(b in a for a in array2)]
print(Z)

Output:

['a', 'b', 'c']


问:
Convert text format to date in mySQL
I have a CSV file I imported into mySQL. One of the columns has dates in it but the data type for it in mySQL is 'text'.

How can I convert it to a date format?
Example dates in the column:

```<code>2/2/2012
7/23/2011
11/27/2011
</code>```

I've tried using

```<code>SELECT STR_TO_DATE(latest_launch,'%m,%d,%Y')
FROM cars;
</code>```

But the output gives me a blank column.
Thanks for the help.

答:
I suggest looking at the 'CAST()' function,

Your solution might look something like this:

```<code>    SELECT CAST(<text> AS date);
</code>```

Where  is the text you want to make into the date type.

If you want to change an entire column try something like this:

```<code>    SELECT CAST(<column_name> AS DATE)
    FROM Table
</code>```

Where <column_name> is the entire column you are trying to convert to the date type.

I hope this was helpful! Let me know if you have any questions!

Title: Convert text format to date in mySQL

Body:
I have a CSV file I imported into mySQL. One of the columns has dates in it but the data type for it in mySQL is 'text'.

How can I convert it to a date format?
Example dates in the column:

2/2/2012
7/23/2011
11/27/2011

I've tried using

SELECT STR_TO_DATE(latest_launch,'%m,%d,%Y')
FROM cars;

But the output gives me a blank column.
Thanks for the help.

Body:
I suggest looking at the 'CAST()' function,

Your solution might look something like this:

    SELECT CAST(<text> AS date);

Where  is the text you want to make into the date type.

If you want to change an entire column try something like this:

    SELECT CAST(<column_name> AS DATE)
    FROM Table

Where <column_name> is the entire column you are trying to convert to the date type.

I hope this was helpful! Let me know if you have any questions!


问:
POST ManytoMany relationship in Django Rest Framework
I have a ManytoMany relationship with Book model and Genres the below code works fine when i try to get data but when tried to post similar as the output but i keep getting this error

```<code>The `.create()` method does not support writable nested fields by default.
Write an explicit `.create()` method for serializer `pages.serializes.BookSerial`, or set `read_only=True` on nested serializer fields.

</code>```

models.py

```<code>class Book(models.Model):
    title =  models.CharField(max_length=100)
    description  =  models.TextField(max_length=4000)
    alternative_name = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    blacklist =  models.BooleanField(default=False)

class Genres(models.Model):
    name =  models.CharField(max_length=200)
    book = models.ManyToManyField(Book,related_name="bookgenres")
    def __str__(self):
        return self.name
</code>```

serialazer.py

```<code>class GenreSerial(serializers.ModelSerializer):
    class Meta:
        model =  Genres
        fields  = ['name']

class BookSerial(serializers.ModelSerializer):
    genre =  GenreSerial(source="bookgenres",many=True)

    class Meta:
        model =  Book
        fields = '__all__'

</code>```

views.py

```<code>class AllSerialed(generics.ListCreateAPIView):
    queryset = Book.objects.filter(blacklist=False).order_by("-date")
    serializer_class = BookSerial
</code>```

答:
You will have to extend the BookSerial and define a create method. And in create method first you save the book object as

```<code>bookobject= books.objects.create(passData),
</code>```

then create the Genres as

```<code>Genreobject = Genres.objects.creae(data)
</code>```

(this data should not contain book value), and then do something like -

```<code>Genreobject.book.add(bookobject)
</code>```

Body:
I have a ManytoMany relationship with Book model and Genres the below code works fine when i try to get data but when tried to post similar as the output but i keep getting this error

The `.create()` method does not support writable nested fields by default.
Write an explicit `.create()` method for serializer `pages.serializes.BookSerial`, or set `read_only=True` on nested serializer fields.

models.py

class Book(models.Model):
    title =  models.CharField(max_length=100)
    description  =  models.TextField(max_length=4000)
    alternative_name = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    blacklist =  models.BooleanField(default=False)

class Genres(models.Model):
    name =  models.CharField(max_length=200)
    book = models.ManyToManyField(Book,related_name="bookgenres")
    def __str__(self):
        return self.name

serialazer.py

class GenreSerial(serializers.ModelSerializer):
    class Meta:
        model =  Genres
        fields  = ['name']

class BookSerial(serializers.ModelSerializer):
    genre =  GenreSerial(source="bookgenres",many=True)

    class Meta:
        model =  Book
        fields = '__all__'

views.py

class AllSerialed(generics.ListCreateAPIView):
    queryset = Book.objects.filter(blacklist=False).order_by("-date")
    serializer_class = BookSerial

Body:
You will have to extend the BookSerial and define a create method. And in create method first you save the book object as

bookobject= books.objects.create(passData),

then create the Genres as

Genreobject = Genres.objects.creae(data)

(this data should not contain book value), and then do something like -

Genreobject.book.add(bookobject)


答: That is simply the property of a hash table -- it makes no guarantee about ordering. Do you want to use a LinkedHashMap instead?</p>

Title: hashtable values reordered


问:
How to access has_many through relationship possible in rails?
How can I access my related records?

```<code>class Post < ActiveRecord::Base
has_many :post_categories
has_many :categories, through: :post_categories

class Categories < ActiveRecord::Base
has_many :post_categories
has_many :post, through: :post_categories

class PostCategories < ActiveRecord::Base
belongs_to :post
belongs_to :category
</code>```

PostCategories table has id, posts_id, and categories_id columns.

```<code>id | posts_id | categories_id
1. | 2       | 3
2. | 2       | 4
</code>```

What I want is: to get posts related to a category. like: all Posts where in x category.

答:
Yep, this is an easy one.

one_or_more_categories = # Category.find... or Category.where...
posts = Post.joins(:categories).where(category: one_or_more_categories)
```
<p>Rails is clever enough to take either a model or a query that <em>would</em> find some data and turn that into an efficient appropriate query, that might be a subquery. Trying things out in the Rails console (<code>bundle exec rails c</code>) is a good way to see the generated SQL and better understand what's going on.</p>
<p>(EDIT: As another answer points out, if you've already retrieved a specific Category instance then you can just reference <code>category.posts</code> and work with that relationship directly, including chaining in <code>.order</code>, <code>.limit</code> and so-on).</p>
<p>Another way to write it 'lower level' would be:</p>
<pre class="lang-rb prettyprint-override"><code>Post.joins(:categories).where(category: {id: one_or_more_category_ids})
</code>```

...which is in essence what Rails will be doing under the hood when given an ActiveRecord model instance or an ActiveRecord::Relation. If you already knew the e.g. category "name", or some other indexed text column that you could search on, then you'd adjust the above accordingly:

Post.joins(:categories).where(category: {name: name_of_category})
```

The pattern of joins and where taking a Hash where the join table name is used as a key with values nested under there can be taken as deep as you like (e.g. if categories had-many subcategories) and you can find more about that in Rails Guides or appropriate web searches. The only gotcha is the tortuous singular/plural stuff, which Rails uses to try and make things more "English-y" but sometimes - as in this case - just creates an additional cognitive burden of needing to remember which parts should be singular and which plural.

Body:
How can I access my related records?

class Post < ActiveRecord::Base
has_many :post_categories
has_many :categories, through: :post_categories

class Categories < ActiveRecord::Base
has_many :post_categories
has_many :post, through: :post_categories

class PostCategories < ActiveRecord::Base
belongs_to :post
belongs_to :category

PostCategories table has id, posts_id, and categories_id columns.

id | posts_id | categories_id
1. | 2       | 3
2. | 2       | 4

What I want is: to get posts related to a category. like: all Posts where in x category.

Body:
Yep, this is an easy one.

one_or_more_categories = # Category.find... or Category.where...
posts = Post.joins(:categories).where(category: one_or_more_categories)

Rails is clever enough to take either a model or a query that would find some data and turn that into an efficient appropriate query, that might be a subquery. Trying things out in the Rails console (bundle exec rails c) is a good way to see the generated SQL and better understand what's going on.

(EDIT: As another answer points out, if you've already retrieved a specific Category instance then you can just reference category.posts and work with that relationship directly, including chaining in .order, .limit and so-on).

Another way to write it 'lower level' would be:

Post.joins(:categories).where(category: {id: one_or_more_category_ids})

...which is in essence what Rails will be doing under the hood when given an ActiveRecord model instance or an ActiveRecord::Relation. If you already knew the e.g. category "name", or some other indexed text column that you could search on, then you'd adjust the above accordingly:

Post.joins(:categories).where(category: {name: name_of_category})

The pattern of joins and where taking a Hash where the join table name is used as a key with values nested under there can be taken as deep as you like (e.g. if categories had-many subcategories) and you can find more about that in Rails Guides or appropriate web searches. The only gotcha is the tortuous singular/plural stuff, which Rails uses to try and make things more "English-y" but sometimes - as in this case - just creates an additional cognitive burden of needing to remember which parts should be singular and which plural.


问:
maven wildfly deploy could not resolve dependencies
I have a maven project with two modules : core and webapp.
The webapp module is a war file to be deployed to wildfly. It has a dependency to the core module.

I can run mvn clean package in the parent directory of my modules. I am able to deploy de war file manually to wildfly and it works. Unfortunately if I run mvn wildfly:deploy in the webapp directory I get :

```<code>Failed to execute goal on project webapp: Could not resolve dependencies for project gbt:webapp:war:1.0-SNAPSHOT: Could not find artifact gbt:core:jar:1.0-SNAPSHOT
</code>```

What shall I do to deploy the war file with the wildfly plugin ?

parent pom

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>gbt</groupId>
    <artifactId>unite_compte</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <version.server.bom>25.0.1.Final</version.server.bom>
        <version.microprofile.bom>25.0.1.Final</version.microprofile.bom>
        <jakartaee.version>8.0.0</jakartaee.version>
        <version.wildfly.maven.plugin>2.1.0.Final</version.wildfly.maven.plugin>
        <failOnMissingWebXml>false</failOnMissingWebXml>
    </properties>

    <dependencyManagement>
        <dependencies>
            <!-- importing the jakartaee8-with-tools BOM adds specs and other useful artifacts as managed dependencies -->
            <dependency>
                <groupId>org.wildfly.bom</groupId>
                <artifactId>wildfly-jakartaee8-with-tools</artifactId>
                <version>${version.server.bom}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>jakarta.platform</groupId>
            <artifactId>jakarta.jakartaee-api</artifactId>
            <version>${jakartaee.version}</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.wildfly.plugins</groupId>
                    <artifactId>wildfly-maven-plugin</artifactId>
                    <version>${version.wildfly.maven.plugin}</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

    <modules>
        <module>core</module>
        <module>webapp</module>
    </modules>
</project>
</code>```

webapp pom :

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>gbt</groupId>
        <artifactId>unite_compte</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <groupId>gbt</groupId>
    <artifactId>webapp</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>gbt</groupId>
            <artifactId>core</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
    <build>
        <!--finalName>${project.artifactId}</finalName-->
        <finalName>unite_compte</finalName>
        <plugins>
            <plugin>
                <groupId>org.wildfly.plugins</groupId>
                <artifactId>wildfly-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

core pom

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>gbt</groupId>
        <artifactId>unite_compte</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <groupId>gbt</groupId>
    <artifactId>core</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>

    </dependencies>
    <build>
        <finalName>${project.artifactId}</finalName>
    </build>
</project>
</code>```

答: You need to run mvn install, or the artifact for the core module is built but never installed into the local repository and cannot be resolved when building the webapp module.

Body:
I have a maven project with two modules : core and webapp.
The webapp module is a war file to be deployed to wildfly. It has a dependency to the core module.

I can run mvn clean package in the parent directory of my modules. I am able to deploy de war file manually to wildfly and it works. Unfortunately if I run mvn wildfly:deploy in the webapp directory I get :

Failed to execute goal on project webapp: Could not resolve dependencies for project gbt:webapp:war:1.0-SNAPSHOT: Could not find artifact gbt:core:jar:1.0-SNAPSHOT

What shall I do to deploy the war file with the wildfly plugin ?

parent pom

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>gbt</groupId>
    <artifactId>unite_compte</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <version.server.bom>25.0.1.Final</version.server.bom>
        <version.microprofile.bom>25.0.1.Final</version.microprofile.bom>
        <jakartaee.version>8.0.0</jakartaee.version>
        <version.wildfly.maven.plugin>2.1.0.Final</version.wildfly.maven.plugin>
        <failOnMissingWebXml>false</failOnMissingWebXml>
    </properties>

    <dependencyManagement>
        <dependencies>

            <dependency>
                <groupId>org.wildfly.bom</groupId>
                <artifactId>wildfly-jakartaee8-with-tools</artifactId>
                <version>${version.server.bom}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>jakarta.platform</groupId>
            <artifactId>jakarta.jakartaee-api</artifactId>
            <version>${jakartaee.version}</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.wildfly.plugins</groupId>
                    <artifactId>wildfly-maven-plugin</artifactId>
                    <version>${version.wildfly.maven.plugin}</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

    <modules>
        <module>core</module>
        <module>webapp</module>
    </modules>
</project>

webapp pom :

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>gbt</groupId>
        <artifactId>unite_compte</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <groupId>gbt</groupId>
    <artifactId>webapp</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>gbt</groupId>
            <artifactId>core</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
    <build>

        <finalName>unite_compte</finalName>
        <plugins>
            <plugin>
                <groupId>org.wildfly.plugins</groupId>
                <artifactId>wildfly-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

core pom

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>gbt</groupId>
        <artifactId>unite_compte</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <groupId>gbt</groupId>
    <artifactId>core</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>

    </dependencies>
    <build>
        <finalName>${project.artifactId}</finalName>
    </build>
</project>


问:
getting "error: redefinition of class" in cpp file even though I am not trying to redefine a class
I was coding something as a little practice and I kept getting this error:

error: redefinition of a "LabMouse::LabMouse(std::__cxx::string,int)

It's saying that it was already defined in my .h file, which it is. I'm just confused on why it's saying that I'm trying to redefine it within my .cpp file?

The .cpp file

```<code>#include <iostream>
#include "LabMouse.h"

LabMouse::LabMouse(const std::string aname, const int aage){

}

void LabMouse::speak(){
        std::cout << "Narf!" << std::endl;
}

LabMouse::~LabMouse(){
        std::cout << "LabMouse Destructor" << std::endl;
}

void LabMouse::setName(std::string name){
        name = "Pinky";
}

void LabMouse::sayHello(){
        std::cout << "LabMouse Name: " << aname << " ,age: " << aage << std::endl;
}
</code>```

The .h file

```<code>#ifndef LABMOUSE_H
#define LABMOUSE_H
#include <string>

class LabMouse{
private:
        std::string aname = "";
        int aage = 1;
public:
        LabMouse(const std::string aname, const int aage){

        }
        void speak();
        void setName(std::string aname);
        void sayHello();

        virtual ~LabMouse();
};

#endif
</code>```

答:
You are defining a body for LabMouse() in the .h file, and you are defining another body for LabMouse() in the .cpp file.  Hence the error.  You need to get rid of one of those bodies.

Also, your constructor is not initializing the aname and aage class members with the values of the input parameters.

Use this instead:

```<code>#include <iostream>
#include "LabMouse.h"

LabMouse::LabMouse(const std::string aname, const int aage)
    : name(aname), age(aage) {
}

void LabMouse::speak() const {
    std::cout << "Narf!" << std::endl;
}

LabMouse::~LabMouse() {
    std::cout << "LabMouse Destructor" << std::endl;
}

void LabMouse::setName(const std::string &aname) {
    name = aname;
}

void LabMouse::sayHello() const {
    std::cout << "LabMouse Name: " << name << ", age: " << age << std::endl;
}
</code>```
```<code>#ifndef LABMOUSE_H
#define LABMOUSE_H
#include <string>

class LabMouse{
private:
    std::string name;
    int age = 1;
public:
    LabMouse(const std::string aname, const int aage);
    virtual ~LabMouse();

    void speak() const;
    void setName(const std::string &aname);
    void sayHello() const;
};

#endif
</code>```

Or this:

```<code>#include <iostream>
#include "LabMouse.h"

void LabMouse::speak() const {
    std::cout << "Narf!" << std::endl;
}

LabMouse::~LabMouse() {
    std::cout << "LabMouse Destructor" << std::endl;
}

void LabMouse::setName(const std::string &aname) {
    name = aname;
}

void LabMouse::sayHello() const {
    std::cout << "LabMouse Name: " << name << ", age: " << age << std::endl;
}
</code>```
```<code>#ifndef LABMOUSE_H
#define LABMOUSE_H
#include <string>

class LabMouse{
private:
    std::string name;
    int age = 1;
public:
    LabMouse(const std::string aname, const int aage)
        : name(aname), age(aage)
    {
    }

    virtual ~LabMouse();

    void speak() const;
    void setName(const std::string &aname);
    void sayHello() const;
};

#endif
</code>```

Body:
I was coding something as a little practice and I kept getting this error:

error: redefinition of a "LabMouse::LabMouse(std::__cxx::string,int)

It's saying that it was already defined in my .h file, which it is. I'm just confused on why it's saying that I'm trying to redefine it within my .cpp file?

The .cpp file

#include <iostream>
#include "LabMouse.h"

LabMouse::LabMouse(const std::string aname, const int aage){

}

void LabMouse::speak(){
        std::cout << "Narf!" << std::endl;
}

LabMouse::~LabMouse(){
        std::cout << "LabMouse Destructor" << std::endl;
}

void LabMouse::setName(std::string name){
        name = "Pinky";
}

void LabMouse::sayHello(){
        std::cout << "LabMouse Name: " << aname << " ,age: " << aage << std::endl;
}

The .h file

#ifndef LABMOUSE_H
#define LABMOUSE_H
#include <string>

class LabMouse{
private:
        std::string aname = "";
        int aage = 1;
public:
        LabMouse(const std::string aname, const int aage){

        }
        void speak();
        void setName(std::string aname);
        void sayHello();

        virtual ~LabMouse();
};

#endif

Body:
You are defining a body for LabMouse() in the .h file, and you are defining another body for LabMouse() in the .cpp file.  Hence the error.  You need to get rid of one of those bodies.

Also, your constructor is not initializing the aname and aage class members with the values of the input parameters.

Use this instead:

#include <iostream>
#include "LabMouse.h"

LabMouse::LabMouse(const std::string aname, const int aage)
    : name(aname), age(aage) {
}

void LabMouse::speak() const {
    std::cout << "Narf!" << std::endl;
}

LabMouse::~LabMouse() {
    std::cout << "LabMouse Destructor" << std::endl;
}

void LabMouse::setName(const std::string &aname) {
    name = aname;
}

void LabMouse::sayHello() const {
    std::cout << "LabMouse Name: " << name << ", age: " << age << std::endl;
}

#ifndef LABMOUSE_H
#define LABMOUSE_H
#include <string>

class LabMouse{
private:
    std::string name;
    int age = 1;
public:
    LabMouse(const std::string aname, const int aage);
    virtual ~LabMouse();

    void speak() const;
    void setName(const std::string &aname);
    void sayHello() const;
};

#endif

Or this:

#include <iostream>
#include "LabMouse.h"

void LabMouse::speak() const {
    std::cout << "Narf!" << std::endl;
}

LabMouse::~LabMouse() {
    std::cout << "LabMouse Destructor" << std::endl;
}

void LabMouse::setName(const std::string &aname) {
    name = aname;
}

void LabMouse::sayHello() const {
    std::cout << "LabMouse Name: " << name << ", age: " << age << std::endl;
}

#ifndef LABMOUSE_H
#define LABMOUSE_H
#include <string>

class LabMouse{
private:
    std::string name;
    int age = 1;
public:
    LabMouse(const std::string aname, const int aage)
        : name(aname), age(aage)
    {
    }

    virtual ~LabMouse();

    void speak() const;
    void setName(const std::string &aname);
    void sayHello() const;
};

#endif


问:
How to split one string into multiple strings separated by at least one space in bash shell?
I have a string containing many words with at least one space between each two. How can I split the string into individual words so I can loop through them?

The string is passed as an argument. E.g. ${2} == "cat cat  file". How can I loop through it?

Also, how can I check if a string contains spaces?

答:
$ echo foo bar baz | sed 's/ /\n/g'

```<code>foo
bar
baz
</code>```

Body:
$ echo foo bar baz | sed 's/ /\n/g'

foo
bar
baz


答:
First of all, I don't recommend using that on your website. if there is some functionality that doesn't support this browser you can show a notification or popup telling the user to switch his browser to get a better experiment.

but if you see that is the better solution you can check this code example from here to check the user browser:

```<code> let userAgent = navigator.userAgent;
 let browserName;

 if(userAgent.match(/chrome|chromium|crios/i)){
     browserName = "chrome";
   }else if(userAgent.match(/firefox|fxios/i)){
     browserName = "firefox";
   }  else if(userAgent.match(/safari/i)){
     browserName = "safari";
   }else if(userAgent.match(/opr\//i)){
     browserName = "opera";
   } else if(userAgent.match(/edg/i)){
     browserName = "edge";
   }else{
     browserName="No browser detection";
   }

  document.querySelector("h1").innerText="You are using "+ browserName +" browser";
</code>```

And this for redirect to another page:

```<code>window.location.replace("http://www.EXAMPLE.com");
</code>```

Title: Block visitors from internet explorer or microsoft edge

Body:
I need a Javascript script to block internet explorer or microsoft edge visitors to prevent accessing my website on blogger
Edit*
Someone help me and answered the question across using user-agent

Body:
First of all, I don't recommend using that on your website. if there is some functionality that doesn't support this browser you can show a notification or popup telling the user to switch his browser to get a better experiment.

but if you see that is the better solution you can check this code example from here to check the user browser:

 let userAgent = navigator.userAgent;
 let browserName;

 if(userAgent.match(/chrome|chromium|crios/i)){
     browserName = "chrome";
   }else if(userAgent.match(/firefox|fxios/i)){
     browserName = "firefox";
   }  else if(userAgent.match(/safari/i)){
     browserName = "safari";
   }else if(userAgent.match(/opr\//i)){
     browserName = "opera";
   } else if(userAgent.match(/edg/i)){
     browserName = "edge";
   }else{
     browserName="No browser detection";
   }

  document.querySelector("h1").innerText="You are using "+ browserName +" browser";

And this for redirect to another page:

window.location.replace("http://www.EXAMPLE.com");


问:
Getting Unexpected Java class loaded under Java version 11 (maximum supported version is 8): java.lang.AssertionError while querying SAP HANA database
I am trying to make a JDBC call to a SAP HANA database. My Java code version is Java 11. I am using ngdbc 2.11.14 HANA jdbc driver. I am getting below error.

Unexpected Java class loaded under Java version 11 (maximum supported version is 8): java.lang.AssertionError
java.lang.AssertionError: Unexpected Java class loaded under Java version 11 (maximum supported version is 8)
    at com.sap.db.jdbc.DriverSapDB._checkJavaVersion(DriverSapDB.java:2179)
    at com.sap.db.jdbc.DriverSapDB.checkJavaVersionMaximum8(DriverSapDB.java:2154)
```
<p>Also I can see in decompiler, below code in Driver.java file, which checks for maximum Java version 8. Does this mean SAP HANA JDBC driver does not support Java 11?</p>
```public class Driver extends DriverSapDB {
  static {
    checkJavaVersionMaximum8();
  }
```

答:
The SAP HANA JDBC driver is a multi-release JAR. From my basic understanding, this means that it carries separate class files for Java <= 8 and for Java > 8.

Short answer to your question: Yes, the SAP HANA JDBC driver does support Java 11 (and above)!

It seems your code (or framework) fetches the incorrect class files for Java 8 internally. I've had an issue in the past which resulted in the same error message that you see. For me, this has happened in the context of using OSGi and due to a bug with multi-release JARs in Apache Felix.

You can read the details about my issue (..which may or may not be different from yours) in this thread.

Body:
I am trying to make a JDBC call to a SAP HANA database. My Java code version is Java 11. I am using ngdbc 2.11.14 HANA jdbc driver. I am getting below error.

Unexpected Java class loaded under Java version 11 (maximum supported version is 8): java.lang.AssertionError
java.lang.AssertionError: Unexpected Java class loaded under Java version 11 (maximum supported version is 8)
    at com.sap.db.jdbc.DriverSapDB._checkJavaVersion(DriverSapDB.java:2179)
    at com.sap.db.jdbc.DriverSapDB.checkJavaVersionMaximum8(DriverSapDB.java:2154)

Also I can see in decompiler, below code in Driver.java file, which checks for maximum Java version 8. Does this mean SAP HANA JDBC driver does not support Java 11?

public class Driver extends DriverSapDB {
  static {
    checkJavaVersionMaximum8();
  }


答:
In the header file remove the braces (thereby turning your definition into a declaration), otherwise you are providing an implementation

```<code>LabMouse(const std::string aname, const int aage){
}
</code>```

should just be

```<code>LabMouse(const std::string aname, const int aage);
</code>```

because you have an implementation already in the cpp file.

Title: getting "error: redefinition of class" in cpp file even though I am not trying to redefine a class

Body:
In the header file remove the braces (thereby turning your definition into a declaration), otherwise you are providing an implementation

LabMouse(const std::string aname, const int aage){
}

should just be

LabMouse(const std::string aname, const int aage);

because you have an implementation already in the cpp file.


问:
Hibernate mapping: Get collection on runtime with nullSafeGet overrided method
To make the mapping between hibernate and my database work, I have this mapping :

```<code><property name="userRolesV2" column="user_roles_v2">
  <type name="io.markethero.repository.CommaSeparatedGenericEnumType">
    <param name="enumClassName">io.markethero.model.UserLoginRoleV2</param>
    <param name="collectionClassName">java.util.Set</param>
  </type>
</property>
</code>```

The idea is to directly get the Collection in my field class instead of doing the mapping each time.

For example, the field in the class could be a Set, a List, or a Queue.
In the database, the value is like "enumValue1,enumValue2,enumValue3".

To do that, my class CommaSeparatedGenericEnumType is like this:

```<code>public class CommaSeparatedGenericEnumType implements UserType, ParameterizedType {

  private Class enumClass = null;
  private Class targetCollection = null;

  public void setParameterValues(Properties params) {
    String enumClassName = params.getProperty("enumClassName");
    String collectionClassName = params.getProperty("collectionClassName");
    if (enumClassName == null) {
      throw new MappingException("enumClassName parameter not specified");
    }
    if (collectionClassName == null) {
      throw new MappingException("collectionClassName parameter not specified");
    }

    try {
      this.enumClass = Class.forName(enumClassName);
    } catch (ClassNotFoundException e) {
      throw new MappingException("enumClass " + enumClassName + " not found", e);
    }
    try {
      this.targetCollection = Class.forName(collectionClassName);
    } catch (ClassNotFoundException e) {
      throw new MappingException("targetCollection " + collectionClassName + " not found", e);
    }
  }

  @Override
  public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
    String commaSeparatedValues = rs.getString(names[0]);
    List<Object> result = new ArrayList<>();
    if (!rs.wasNull()) {
      String[] enums = commaSeparatedValues.split(",");
      for (String string : enums) {
        result.add(Enum.valueOf(enumClass, string));
      }
    }
    return result;
  }

  @Override
  @SuppressWarnings("unchecked")
  public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
    if (null == value) {
      st.setNull(index, Types.VARCHAR);
    } else {
      List<Object> enums = (List) value;

      StringBuilder sb = new StringBuilder("");
      for (Object each : enums) {
        sb.append(each.toString()).append(",");
      }

      if (sb.toString().isEmpty()) {
        st.setNull(index, Types.VARCHAR);
      } else {
        String commaSeparatedIds = sb.toString().substring(0, sb.toString().length() - 1);
        st.setString(index, commaSeparatedIds);
      }
    }
  }
}
</code>```

I would like to be able to parametrize which collection nullSafeGet and nullSafeSet are going to use, because for now, it's only working with a list.

Thank you!

答:
Maybe my question was asked was oddly, but here what I did:

For the getter, I used the factory pattern already implemented by Spring : CollectionFactory.

  @Override
  public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
    String commaSeparatedValues = rs.getString(names[0]);
    Collection<Object> result = CollectionFactory.createCollection(this.targetCollection, 50);
    if (!rs.wasNull()) {
      String[] enums = commaSeparatedValues.split(",");
      for (String string : enums) {
        try {
          result.add(Enum.valueOf(enumClass, string));
        } catch (IllegalArgumentException e) {
          throw new MappingException("[CommaSeparatedGenericEnumType::nullSafeGet] No such enum value"+ string +"for enum : " + enumClass, e);
        }
      }
    }
    return result;
  }
```
<ul>
<li>For the setter, I used the reflection API.</li>
</ul>
<pre class="lang-java prettyprint-override"><code>  public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
    if (value == null) {
      st.setNull(index, Types.VARCHAR);
    } else {
      if (value instanceof Collection) {
        try {
          StringBuilder sb = new StringBuilder("");

          Constructor<?> c = value.getClass().getConstructor(Collection.class);

          Collection<Object> enums = (Collection<Object>) c.newInstance((Collection<Object>) value);

          for (Object each : enums) {
            sb.append(each.toString()).append(",");
          }
          String commaSeparatedIds = sb.substring(0, sb.toString().length() - 1);

          if (sb.length() > 0) {
            st.setString(index, commaSeparatedIds);
          } else {
            st.setNull(index, Types.VARCHAR);
          }
        } catch (NoSuchMethodException e) {
          throw new MappingException("[CommaSeparatedGenericEnumType::nullSafeSet] No such constructor found for class : " + value.getClass(), e);
        } catch (InstantiationException e) {
          throw new MappingException("[CommaSeparatedGenericEnumType::nullSafeSet] Class : " + value.getClass() + " cannot be instantiate ", e);
        } catch (IllegalAccessException e) {
          throw new MappingException("[CommaSeparatedGenericEnumType::nullSafeSet] You cannot access to constructor of class : " + value.getClass(), e);
        } catch (InvocationTargetException e) {
          throw new MappingException("[CommaSeparatedGenericEnumType::nullSafeSet] InvocationTargetException for class : " + value.getClass(), e);
        }
      } else {
        st.setNull(index, Types.VARCHAR);
        throw new IllegalArgumentException();
      }
    }
  }
</code>```

Body:
To make the mapping between hibernate and my database work, I have this mapping :

<property name="userRolesV2" column="user_roles_v2">
  <type name="io.markethero.repository.CommaSeparatedGenericEnumType">
    <param name="enumClassName">io.markethero.model.UserLoginRoleV2</param>
    <param name="collectionClassName">java.util.Set</param>
  </type>
</property>

The idea is to directly get the Collection in my field class instead of doing the mapping each time.

For example, the field in the class could be a Set, a List, or a Queue.
In the database, the value is like "enumValue1,enumValue2,enumValue3".

To do that, my class CommaSeparatedGenericEnumType is like this:

public class CommaSeparatedGenericEnumType implements UserType, ParameterizedType {

  private Class enumClass = null;
  private Class targetCollection = null;

  public void setParameterValues(Properties params) {
    String enumClassName = params.getProperty("enumClassName");
    String collectionClassName = params.getProperty("collectionClassName");
    if (enumClassName == null) {
      throw new MappingException("enumClassName parameter not specified");
    }
    if (collectionClassName == null) {
      throw new MappingException("collectionClassName parameter not specified");
    }

    try {
      this.enumClass = Class.forName(enumClassName);
    } catch (ClassNotFoundException e) {
      throw new MappingException("enumClass " + enumClassName + " not found", e);
    }
    try {
      this.targetCollection = Class.forName(collectionClassName);
    } catch (ClassNotFoundException e) {
      throw new MappingException("targetCollection " + collectionClassName + " not found", e);
    }
  }

  @Override
  public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
    String commaSeparatedValues = rs.getString(names[0]);
    List<Object> result = new ArrayList<>();
    if (!rs.wasNull()) {
      String[] enums = commaSeparatedValues.split(",");
      for (String string : enums) {
        result.add(Enum.valueOf(enumClass, string));
      }
    }
    return result;
  }

  @Override
  @SuppressWarnings("unchecked")
  public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
    if (null == value) {
      st.setNull(index, Types.VARCHAR);
    } else {
      List<Object> enums = (List) value;

      StringBuilder sb = new StringBuilder("");
      for (Object each : enums) {
        sb.append(each.toString()).append(",");
      }

      if (sb.toString().isEmpty()) {
        st.setNull(index, Types.VARCHAR);
      } else {
        String commaSeparatedIds = sb.toString().substring(0, sb.toString().length() - 1);
        st.setString(index, commaSeparatedIds);
      }
    }
  }
}

I would like to be able to parametrize which collection nullSafeGet and nullSafeSet are going to use, because for now, it's only working with a list.

Thank you!

Body:
Maybe my question was asked was oddly, but here what I did:

For the getter, I used the factory pattern already implemented by Spring : CollectionFactory.

  @Override
  public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws HibernateException, SQLException {
    String commaSeparatedValues = rs.getString(names[0]);
    Collection<Object> result = CollectionFactory.createCollection(this.targetCollection, 50);
    if (!rs.wasNull()) {
      String[] enums = commaSeparatedValues.split(",");
      for (String string : enums) {
        try {
          result.add(Enum.valueOf(enumClass, string));
        } catch (IllegalArgumentException e) {
          throw new MappingException("[CommaSeparatedGenericEnumType::nullSafeGet] No such enum value"+ string +"for enum : " + enumClass, e);
        }
      }
    }
    return result;
  }

For the setter, I used the reflection API.

  public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws HibernateException, SQLException {
    if (value == null) {
      st.setNull(index, Types.VARCHAR);
    } else {
      if (value instanceof Collection) {
        try {
          StringBuilder sb = new StringBuilder("");

          Constructor<?> c = value.getClass().getConstructor(Collection.class);

          Collection<Object> enums = (Collection<Object>) c.newInstance((Collection<Object>) value);

          for (Object each : enums) {
            sb.append(each.toString()).append(",");
          }
          String commaSeparatedIds = sb.substring(0, sb.toString().length() - 1);

          if (sb.length() > 0) {
            st.setString(index, commaSeparatedIds);
          } else {
            st.setNull(index, Types.VARCHAR);
          }
        } catch (NoSuchMethodException e) {
          throw new MappingException("[CommaSeparatedGenericEnumType::nullSafeSet] No such constructor found for class : " + value.getClass(), e);
        } catch (InstantiationException e) {
          throw new MappingException("[CommaSeparatedGenericEnumType::nullSafeSet] Class : " + value.getClass() + " cannot be instantiate ", e);
        } catch (IllegalAccessException e) {
          throw new MappingException("[CommaSeparatedGenericEnumType::nullSafeSet] You cannot access to constructor of class : " + value.getClass(), e);
        } catch (InvocationTargetException e) {
          throw new MappingException("[CommaSeparatedGenericEnumType::nullSafeSet] InvocationTargetException for class : " + value.getClass(), e);
        }
      } else {
        st.setNull(index, Types.VARCHAR);
        throw new IllegalArgumentException();
      }
    }
  }


问:
Can I use Javascript to change div class when div class is not unique?
Is there a way through javascript to change the class below assigned to these three different divs. As you can see the class is the same on all but the styling is different and I want to be able to control styling by class:

```<code><div class="pending-task-value" style="background-color: rgb(232, 188, 13);"> 0 <!----></div>

<div class="pending-task-value" style="background-color: rgb(47, 145, 211);"> 0 <!----></div>

<div class="pending-task-value" style="background-color: rgb(19, 152, 126);"> 0 <!----></div>
</code>```

Effectively I want the outcome to be:

```<code><div class="pending-task-value-total";> 0 <!---></div>
<div class="pending-task-value-phone";> 0 <!---></div>
<div class="pending-task-value-sms";> 0 <!---></div>
</code>```

Edit, here is the HTML in place today... I can't directly edit the HTML so I need a way to change the colors of the background colors.

```<code><div class="card-body">
  <div class="row" style="text-align: center;">
    <div class="col-4 pending-task-value-col">
      <div class="pending-task-value" style="background-color: rgb(232, 188, 13);"> 0
        <!---->
      </div>
      <div><i class="fas fa-tasks"></i></div>
      <div>Total Pending</div>
    </div>
    <div class="col-4 pending-task-value-col">
      <div class="pending-task-value" style="background-color: rgb(47, 145, 211);"> 0
        <!---->
      </div>
      <div><i class="fas fa-phone"></i></div>
      <div>Phone</div>
    </div>
    <div class="col-4 pending-task-value-col">
      <div class="pending-task-value" style="background-color: rgb(19, 152, 126);"> 0
        <!---->
      </div>
      <div><i class="fas fa-sms"></i></div>
      <div>SMS</div>
    </div>
  </div>
</code>```

The only thing that is making each "pending-task-value" unique is the "background-color" style element. I want to change the background-color so that it would be the following below but I need javascript to do it and can't figure out how to make the update:

```<code><div class="card-body">
  <div class="row" style="text-align: center;">
    <div class="col-4 pending-task-value-col">
      <div class="pending-task-value" style="background-color: #2B32B2;"> 0
        <!---->
      </div>
      <div><i class="fas fa-tasks"></i></div>
      <div>Total Pending</div>
    </div>
    <div class="col-4 pending-task-value-col">
      <div class="pending-task-value" style="background-color: #1488CC;"> 0
        <!---->
      </div>
      <div><i class="fas fa-phone"></i></div>
      <div>Phone</div>
    </div>
    <div class="col-4 pending-task-value-col">
      <div class="pending-task-value" style="background-color: #d63384;"> 0
        <!---->
      </div>
      <div><i class="fas fa-sms"></i></div>
      <div>SMS</div>
    </div>
  </div>
</code>```

Or if there is a way to change/add a style to each "pending-task-value" to make them unique so I can then apply css to them would work for me too.

Body:
Is there a way through javascript to change the class below assigned to these three different divs. As you can see the class is the same on all but the styling is different and I want to be able to control styling by class:

 0

 0

 0

Effectively I want the outcome to be:

 0

 0

Total Pending

 0

Phone

 0

SMS

The only thing that is making each "pending-task-value" unique is the "background-color" style element. I want to change the background-color so that it would be the following below but I need javascript to do it and can't figure out how to make the update:

 0

Total Pending

 0

Phone

 0

SMS

Or if there is a way to change/add a style to each "pending-task-value" to make them unique so I can then apply css to them would work for me too.

Body:
You probably shouldn't do this - the proper way would be to actually edit the underlying HTML or even the CSS to accomplish this. Leveraging this method can amount to loads of extra maintenance work in the future, whereas centralizing your styles in a proper CSS file and decoupling styling from your JavaScript application logic would be much cleaner and easier to maintain.

However, what you can do is insert an arbitrary <style> block to document.body that implements CSS rules using the :nth-child() CSS pseudo-class to accomplish what you seem to be looking for (assuming that the contents within .card-body .row appear in the same order each time:

var styleElement = document.createElement('style');
styleElement.innerText = `
.card-body .row .pending-task-value-col:nth-child(1) .pending-task-value {
  background-color: #2B32B2 !important;
}

.card-body .row .pending-task-value-col:nth-child(2) .pending-task-value {
  background-color: #1488CC !important;
}

.card-body .row .pending-task-value-col:nth-child(3) .pending-task-value {
  background-color: #d63384 !important;
}`;
document.body.appendChild(styleElement);

<div class="card-body">
  <div class="row" style="text-align: center;">
    <div class="col-4 pending-task-value-col">
      <div class="pending-task-value" style="background-color: rgb(232, 188, 13);"> 0
        <!---->
      </div>
      <div><i class="fas fa-tasks"></i></div>
      <div>Total Pending</div>
    </div>
    <div class="col-4 pending-task-value-col">
      <div class="pending-task-value" style="background-color: rgb(47, 145, 211);"> 0
        <!---->
      </div>
      <div><i class="fas fa-phone"></i></div>
      <div>Phone</div>
    </div>
    <div class="col-4 pending-task-value-col">
      <div class="pending-task-value" style="background-color: rgb(19, 152, 126);"> 0
        <!---->
      </div>
      <div><i class="fas fa-sms"></i></div>
      <div>SMS</div>
    </div>
  </div>
</div>
<hr />
<div class="card-body">
  <div class="row" style="text-align: center;">
    <div class="col-4 pending-task-value-col">
      <div class="pending-task-value" style="background-color: rgb(232, 188, 13);"> 0
        <!---->
      </div>
      <div><i class="fas fa-tasks"></i></div>
      <div>Total Pending</div>
    </div>
    <div class="col-4 pending-task-value-col">
      <div class="pending-task-value" style="background-color: rgb(47, 145, 211);"> 0
        <!---->
      </div>
      <div><i class="fas fa-phone"></i></div>
      <div>Phone</div>
    </div>
    <div class="col-4 pending-task-value-col">
      <div class="pending-task-value" style="background-color: rgb(19, 152, 126);"> 0
        <!---->
      </div>
      <div><i class="fas fa-sms"></i></div>
      <div>SMS</div>
    </div>
  </div>
</div>