问:
Swipe trailing UITableView Cell by clicking on button
I need to achieve swipe functionality by clicking on the button, as seen in the picture.

I achieved this thing by using the following code

```<code>func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    //*********** DELETE (.destructive = red color) ***********
    let deleteAction = UIContextualAction(style: .destructive, title: "Delete") {
                (action, sourceView, completionHandler) in

        print("delete Tapped")
        completionHandler(true)
    } // end action Delete
    // *********** EDIT ***********
    let editAction = UIContextualAction(style: .normal, title: "Edit Name") {
        (action, sourceView, completionHandler) in
        // 1. Segue to Edit view MUST PASS INDEX PATH as Sender to the prepareSegue function
        print("Edit tapped")
        completionHandler(true)

    }
    editAction.backgroundColor = Colors.primary
    let switchAction = UIContextualAction(style: .normal, title: "Switch") {
        (action, sourceView, completionHandler) in
        // 1. Segue to Edit view MUST PASS INDEX PATH as Sender to the prepareSegue function
        print("switch tapped")
        completionHandler(true)

    }
    switchAction.backgroundColor = Colors.secondary
    // SWIPE TO LEFT CONFIGURATION
    let swipeConfiguration = UISwipeActionsConfiguration(actions: [editAction, switchAction, deleteAction])
    // Delete should not delete automatically
    swipeConfiguration.performsFirstActionWithFullSwipe = false
    return swipeConfiguration
}
</code>```

What I actually want is to get this swipe functionality by clicking on the more(3 dots) button as you can see in the picture above.

Body:
I need to achieve swipe functionality by clicking on the button, as seen in the picture.

I achieved this thing by using the following code

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    //*********** DELETE (.destructive = red color) ***********
    let deleteAction = UIContextualAction(style: .destructive, title: "Delete") {
                (action, sourceView, completionHandler) in

        print("delete Tapped")
        completionHandler(true)
    } // end action Delete
    // *********** EDIT ***********
    let editAction = UIContextualAction(style: .normal, title: "Edit Name") {
        (action, sourceView, completionHandler) in
        // 1. Segue to Edit view MUST PASS INDEX PATH as Sender to the prepareSegue function
        print("Edit tapped")
        completionHandler(true)

    }
    editAction.backgroundColor = Colors.primary
    let switchAction = UIContextualAction(style: .normal, title: "Switch") {
        (action, sourceView, completionHandler) in
        // 1. Segue to Edit view MUST PASS INDEX PATH as Sender to the prepareSegue function
        print("switch tapped")
        completionHandler(true)

    }
    switchAction.backgroundColor = Colors.secondary
    // SWIPE TO LEFT CONFIGURATION
    let swipeConfiguration = UISwipeActionsConfiguration(actions: [editAction, switchAction, deleteAction])
    // Delete should not delete automatically
    swipeConfiguration.performsFirstActionWithFullSwipe = false
    return swipeConfiguration
}

What I actually want is to get this swipe functionality by clicking on the more(3 dots) button as you can see in the picture above.


来源: stackexchange

问:
Vertical grid alignment between div header and content when content has a scroll bar
Please see this codepen: https://codepen.io/thummper/pen/MWXZdRJ or the snippet below

@charset "UTF-8";
.checkboxicon-unchecked:before {
  font-family: "FontAwesome" !important;
  font-weight: normal !important;
  content: "" !important;
  font-size: 18px !important;
  color: #336699 !important;
}

.fileGrid,
.fileExplorerItem {
  display: grid;
  grid-template-columns: 200px repeat(2, 70px) 1fr 105px;
}

.fileGrid .itemActions a::before {
  color: #ff7a33 !important;
}

.fileGrid div {
  display: flex;
  align-items: center;
}

.fileGrid .breadcrumb {
  grid-column: 1/2;
}

.fileGrid .progressWrapper {
  grid-column: 2/5;
  padding: 0 10px;
}

.fileGrid .progressWrapper .progress {
  margin: 0;
  width: 100%;
}

.fileGrid .itemActions {
  grid-column: 5/6;
}

.fileName::before,
.navigation::before,
.singleDownloadButton,
.singleDeleteButton,
.eye,
.eyeSlash {
  color: black;
  font-family: "FontAwesome";
  font-weight: normal;
  font-size: 18px;
}

.fileExplorerWrapper .name {
  overflow: clip;
  white-space: nowrap;
}

.fileExplorerWrapper .file .name {
  grid-column: 1/2;
}

.fileExplorerWrapper .file .ext {
  grid-column: 2/3;
}

.fileExplorerWrapper .file .size {
  grid-column: 3/4;
}

.fileExplorerWrapper .file .itemActions {
  grid-column: 5/6;
}

.fileExplorerWrapper .folder .name {
  grid-column: 1/2;
}

.fileExplorerWrapper .folder .itemActions {
  grid-column: 5/6;
}

.fileExplorerWrapper .fileExplorerItem {
  padding: 5px 0;
  padding-left: 10px;
}

.fileExplorerWrapper .itemActions {
  display: flex;
  align-content: center;
  margin-left: auto;
  margin-right: 10px;
}

.fileExplorerWrapper .itemActions a {
  margin-left: 8px;
}

.fileExplorerWrapper .progress {
  border-radius: 2px;
  background: #919ec7;
  box-shadow: rgba(17, 17, 26, 0.1) 0px 0px 16px;
  position: relative;
  flex: 1;
  margin: auto 12px;
}

.fileExplorerWrapper .progress .progressText {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.fileExplorerWrapper .progress .progress-bar {
  font-weight: bold;
  background: #283869;
}

.fileExplorerWrapper .headerRow {
  background-color: #566db5;
  padding: 10px 0;
  padding-left: 10px;
}

.fileExplorerWrapper .headerRow .fileBreadcrumb {
  font-size: 14px;
  padding: 10px;
  color: white;
}

.fileExplorerWrapper .folderName::before {
  content: "";
}

.fileExplorerWrapper .singleDeleteButton::before {
  content: "";
}

.fileExplorerWrapper .singleDownloadButton::before {
  content: "";
}

.fileExplorerWrapper .eye::before {
  content: "";
}

.fileExplorerWrapper .eyeSlash::before {
  content: "";
}

.directorylist {
  width: 100%;
  border: solid 1px #ddd;
  min-height: 500px;
  max-height: 500px;
  overflow-y: auto;
  list-style: none;
  padding: 0;
  margin: 0;
}

.name>a:before {
  margin-right: 20px;
}

.name>a.jpg:before,
.name>a.jpeg:before,
.name>a.png:before,
.name>a.ico:before,
.name>a.bmp:before,
.name>a.tiff:before,
.name>a.tif:before,
.name>a.gif:before,
.name>a.webp:before {
  content: "";
}

.noFilesSplash {
  width: 100%;
  height: 500px;
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
}

.noFilesSplash img {
  filter: opacity(0.2);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/4.5.3/css/bootstrap.min.css" />

<div id="content_file_explorer" class="fileExplorerWrapper">
  <div class="fileExplorer">
    <div class="headerRow fileGrid">
      <div class="fileBreadcrumb">
        \empdocs\6159
      </div>

      <div class="progressWrapper">
        <div class="progress">
          <div class="progress-bar" role="progressbar" style="width: 0%" aria-valuenow="60883" aria-valuemin="0" aria-valuemax="125"></div>
          <div class="progressText">
            <span> 0.06 MB / 125 MB</span>
          </div>
        </div>
      </div>

      <div class="itemActions">

      </div>
    </div>

    <div id="fileBrowser">

      <div class="noFilesSplash hidden" style="pointer-events: none">
        <img src="/Content/Images/LivePayBW.png">
      </div>

      <ul class="directorylist" id="explorerList">

        <li class="fileExplorerItem file">
          <div class="name">
            AddExpense.png
          </div>
          <div class="ext"></div>
          <div class="size"></div>

          <div class="itemActions">

          </div>

        </li>

        <li class="fileExplorerItem file">
          <div class="name">
            AddExpense.png
          </div>
          <div class="ext"></div>
          <div class="size"></div>

          <div class="itemActions">

          </div>

        </li>

        <li class="fileExplorerItem file">
          <div class="name">
            AddExpense.png
          </div>
          <div class="ext"></div>
          <div class="size"></div>

          <div class="itemActions">

          </div>

        </li>

        <li class="fileExplorerItem file">
          <div class="name">
            AddExpense.png
          </div>
          <div class="ext"></div>
          <div class="size"></div>

          <div class="itemActions">

          </div>

        </li>

        <li class="fileExplorerItem file">
          <div class="name">
            AddExpense.png
          </div>
          <div class="ext"></div>
          <div class="size"></div>

          <div class="itemActions">

          </div>

        </li>

        <li class="fileExplorerItem file">
          <div class="name">
            AddExpense.png
          </div>
          <div class="ext"></div>
          <div class="size"></div>

          <div class="itemActions">

          </div>

        </li>

        <li class="fileExplorerItem file">
          <div class="name">
            AddExpense.png
          </div>
          <div class="ext"></div>
          <div class="size"></div>

          <div class="itemActions">

          </div>

        </li>

        <li class="fileExplorerItem file">
          <div class="name">
            AddExpense.png
          </div>
          <div class="ext"></div>
          <div class="size"></div>

          <div class="itemActions">

          </div>

        </li>

        <li class="fileExplorerItem file">
          <div class="name">
            AddExpense.png
          </div>
          <div class="ext"></div>
          <div class="size"></div>

          <div class="itemActions">

          </div>

        </li>

        <li class="fileExplorerItem file">
          <div class="name">
            AddExpense.png
          </div>
          <div class="ext"></div>
          <div class="size"></div>

          <div class="itemActions">

          </div>

        </li>

        <li class="fileExplorerItem file">
          <div class="name">
            AddExpense.png
          </div>
          <div class="ext"></div>
          <div class="size"></div>

          <div class="itemActions">

          </div>

        </li>

        <li class="fileExplorerItem file">
          <div class="name">
            AddExpense.png
          </div>
          <div class="ext"></div>
          <div class="size"></div>

          <div class="itemActions">

          </div>

        </li>

        <li class="fileExplorerItem file">
          <div class="name">
            AddExpense.png
          </div>
          <div class="ext"></div>
          <div class="size"></div>

          <div class="itemActions">

          </div>

        </li>

        <li class="fileExplorerItem file">
          <div class="name">
            AddExpense.png
          </div>
          <div class="ext"></div>
          <div class="size"></div>

          <div class="itemActions">

          </div>

        </li>

        <li class="fileExplorerItem file">
          <div class="name">
            AddExpense.png
          </div>
          <div class="ext"></div>
          <div class="size"></div>

          <div class="itemActions">

          </div>

        </li>
      </ul>
    </div>
  </div>
</div></code>```

I am trying to get the #fileBulkCheck checkbox to vertically align with checkboxes in the .directorylist ul.

The header row and the li's in the directory list use the same grid layout, but become misaligned when the ul expands past 500px - the set max width.

When the scrollbar appears it pushes everything towards the left - but as far as I can tell there is no well supported way to change the behaviour of this scroll?

I can vertically align them by placing a useless scrollbar on my header, but I'm not sure if I can make it invisible // It would not respect the child content unless the scrollbar is always visible.

Any suggestions to achieve this please?

ContentLicense: CC BY-SA 4.0

Body:
Please see this codepen: https://codepen.io/thummper/pen/MWXZdRJ or the snippet below

@charset "UTF-8";
.checkboxicon-unchecked:before {
  font-family: "FontAwesome" !important;
  font-weight: normal !important;
  content: "" !important;
  font-size: 18px !important;
  color: #336699 !important;
}

.fileGrid,
.fileExplorerItem {
  display: grid;
  grid-template-columns: 200px repeat(2, 70px) 1fr 105px;
}

.fileGrid .itemActions a::before {
  color: #ff7a33 !important;
}

.fileGrid div {
  display: flex;
  align-items: center;
}

.fileGrid .breadcrumb {
  grid-column: 1/2;
}

.fileGrid .progressWrapper {
  grid-column: 2/5;
  padding: 0 10px;
}

.fileGrid .progressWrapper .progress {
  margin: 0;
  width: 100%;
}

.fileGrid .itemActions {
  grid-column: 5/6;
}

.fileName::before,
.navigation::before,
.singleDownloadButton,
.singleDeleteButton,
.eye,
.eyeSlash {
  color: black;
  font-family: "FontAwesome";
  font-weight: normal;
  font-size: 18px;
}

.fileExplorerWrapper .name {
  overflow: clip;
  white-space: nowrap;
}

.fileExplorerWrapper .file .name {
  grid-column: 1/2;
}

.fileExplorerWrapper .file .ext {
  grid-column: 2/3;
}

.fileExplorerWrapper .file .size {
  grid-column: 3/4;
}

.fileExplorerWrapper .file .itemActions {
  grid-column: 5/6;
}

.fileExplorerWrapper .folder .name {
  grid-column: 1/2;
}

.fileExplorerWrapper .folder .itemActions {
  grid-column: 5/6;
}

.fileExplorerWrapper .fileExplorerItem {
  padding: 5px 0;
  padding-left: 10px;
}

.fileExplorerWrapper .itemActions {
  display: flex;
  align-content: center;
  margin-left: auto;
  margin-right: 10px;
}

.fileExplorerWrapper .itemActions a {
  margin-left: 8px;
}

.fileExplorerWrapper .progress {
  border-radius: 2px;
  background: #919ec7;
  box-shadow: rgba(17, 17, 26, 0.1) 0px 0px 16px;
  position: relative;
  flex: 1;
  margin: auto 12px;
}

.fileExplorerWrapper .progress .progressText {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.fileExplorerWrapper .progress .progress-bar {
  font-weight: bold;
  background: #283869;
}

.fileExplorerWrapper .headerRow {
  background-color: #566db5;
  padding: 10px 0;
  padding-left: 10px;
}

.fileExplorerWrapper .headerRow .fileBreadcrumb {
  font-size: 14px;
  padding: 10px;
  color: white;
}

.fileExplorerWrapper .folderName::before {
  content: "";
}

.fileExplorerWrapper .singleDeleteButton::before {
  content: "";
}

.fileExplorerWrapper .singleDownloadButton::before {
  content: "";
}

.fileExplorerWrapper .eye::before {
  content: "";
}

.fileExplorerWrapper .eyeSlash::before {
  content: "";
}

.directorylist {
  width: 100%;
  border: solid 1px #ddd;
  min-height: 500px;
  max-height: 500px;
  overflow-y: auto;
  list-style: none;
  padding: 0;
  margin: 0;
}

.name>a:before {
  margin-right: 20px;
}

.name>a.jpg:before,
.name>a.jpeg:before,
.name>a.png:before,
.name>a.ico:before,
.name>a.bmp:before,
.name>a.tiff:before,
.name>a.tif:before,
.name>a.gif:before,
.name>a.webp:before {
  content: "";
}

.noFilesSplash {
  width: 100%;
  height: 500px;
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
}

.noFilesSplash img {
  filter: opacity(0.2);
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/4.5.3/css/bootstrap.min.css" />

        \empdocs\6159

             0.06 MB / 125 MB

            AddExpense.png

            AddExpense.png

            AddExpense.png

            AddExpense.png

            AddExpense.png

            AddExpense.png

            AddExpense.png

            AddExpense.png

            AddExpense.png

            AddExpense.png

            AddExpense.png

            AddExpense.png

            AddExpense.png

            AddExpense.png

            AddExpense.png

I am trying to get the #fileBulkCheck checkbox to vertically align with checkboxes in the .directorylist ul.

The header row and the li's in the directory list use the same grid layout, but become misaligned when the ul expands past 500px - the set max width.

When the scrollbar appears it pushes everything towards the left - but as far as I can tell there is no well supported way to change the behaviour of this scroll?

I can vertically align them by placing a useless scrollbar on my header, but I'm not sure if I can make it invisible // It would not respect the child content unless the scrollbar is always visible.

Any suggestions to achieve this please?


问:
How to get Runnable target from a thread
I need to get CPU time from the thread with a specific Runnable.
I have a thread pool with a specific group name and thread prefix and I can get a ThreadInfo from ThreadMXBean. My code that do it looks like the following:

```<code>final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
Arrays.stream(threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds()))
        .filter(threadInfo -> threadInfo != null && threadInfo.getThreadName().startsWith("my-thread-prefix"))
        .forEach(threadInfo -> {
            logger.info("Thread: {}", threadInfo.getThreadName());
            logger.info("CPU time: {}", threadMXBean.getThreadCpuTime(threadInfo.getThreadId()));
            Thread.getAllStackTraces().keySet().stream()
                    .filter(thread -> thread.getId() == threadInfo.getThreadId())
                    .forEach(thread -> {
                        for (StackTraceElement stackTraceElement : thread.getStackTrace()) {
                            String className = stackTraceElement.getClassName();
                            if (className.equals("MySpecificClass") {
                                logger.info(className);
                                logger.info("CPU {}", threadMXBean.getThreadCpuTime(threadInfo.getThreadId()));
                            }
                        }
                    });
        });
</code>```

However, this code doesn't work because I can't get that class instead I have gotten an AbstractClass.

```<code>public class MySpecificClass extends AbstractClass {
    public void doWork() {
        ...
    }
}

public abstract class AbstractClass {
    public void methodFromTheAbstractClass() {
        // this method has been called
        ...
    }
}
</code>```

And if this method was called and I'm getting stacktrace at this moment, I only get AbstractClass, but actually it must be instance of MySpecificClass.

How can I get MySpecificClass in the stacktrace or target runnable from the thread?

Body:
I need to get CPU time from the thread with a specific Runnable.
I have a thread pool with a specific group name and thread prefix and I can get a ThreadInfo from ThreadMXBean. My code that do it looks like the following:

final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
Arrays.stream(threadMXBean.getThreadInfo(threadMXBean.getAllThreadIds()))
        .filter(threadInfo -> threadInfo != null && threadInfo.getThreadName().startsWith("my-thread-prefix"))
        .forEach(threadInfo -> {
            logger.info("Thread: {}", threadInfo.getThreadName());
            logger.info("CPU time: {}", threadMXBean.getThreadCpuTime(threadInfo.getThreadId()));
            Thread.getAllStackTraces().keySet().stream()
                    .filter(thread -> thread.getId() == threadInfo.getThreadId())
                    .forEach(thread -> {
                        for (StackTraceElement stackTraceElement : thread.getStackTrace()) {
                            String className = stackTraceElement.getClassName();
                            if (className.equals("MySpecificClass") {
                                logger.info(className);
                                logger.info("CPU {}", threadMXBean.getThreadCpuTime(threadInfo.getThreadId()));
                            }
                        }
                    });
        });

However, this code doesn't work because I can't get that class instead I have gotten an AbstractClass.

public class MySpecificClass extends AbstractClass {
    public void doWork() {
        ...
    }
}

public abstract class AbstractClass {
    public void methodFromTheAbstractClass() {
        // this method has been called
        ...
    }
}

And if this method was called and I'm getting stacktrace at this moment, I only get AbstractClass, but actually it must be instance of MySpecificClass.

How can I get MySpecificClass in the stacktrace or target runnable from the thread?


问:
java.lang.ClassNotFoundException: org.glassfish.jersey.server.spi.internal.ValueParamProvider
I am trying to run my maven application but getting the following error:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/glassfish/jersey/server/spi/internal/ValueParamProvider
    at ru.vyarus.dropwizard.guice.module.installer.feature.jersey.provider.JerseyProviderInstaller.<clinit>(JerseyProviderInstaller.java:72)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
    at java.base/java.lang.reflect.ReflectAccess.newInstance(ReflectAccess.java:128)
    at java.base/jdk.internal.reflect.ReflectionFactory.newInstance(ReflectionFactory.java:347)
    at java.base/java.lang.Class.newInstance(Class.java:645)
    at ru.vyarus.dropwizard.guice.module.GuiceyInitializer.prepareInstallers(GuiceyInitializer.java:217)
    at ru.vyarus.dropwizard.guice.module.GuiceyInitializer.resolveInstallers(GuiceyInitializer.java:119)
    at ru.vyarus.dropwizard.guice.GuiceBundle.initialize(GuiceBundle.java:123)
    at io.dropwizard.setup.Bootstrap.addBundle(Bootstrap.java:150)
    at com.test.aae.aggregator.facade.App.initialize(App.java:164)
    at io.dropwizard.Application.run(Application.java:88)
    at com.test.aae.aggregator.facade.App.main(App.java:46)
Caused by: java.lang.ClassNotFoundException: org.glassfish.jersey.server.spi.internal.ValueParamProvider
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
</code>```

I am using the following dependency in my pom.xml:

```<code><dependency>
   <groupId>org.glassfish.jersey.bundles.repackaged</groupId>
   <artifactId>jersey-guava</artifactId>
   <version>${jersey-guava.version}</version>
</dependency>

<dependency>
   <groupId>org.glassfish.jersey.core</groupId>
   <artifactId>jersey-server</artifactId>
   <version>2.22.1</version>
</dependency>
</code>```

My app is running with java 17

Body:
I am trying to run my maven application but getting the following error:

Exception in thread "main" java.lang.NoClassDefFoundError: org/glassfish/jersey/server/spi/internal/ValueParamProvider
    at ru.vyarus.dropwizard.guice.module.installer.feature.jersey.provider.JerseyProviderInstaller.<clinit>(JerseyProviderInstaller.java:72)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
    at java.base/java.lang.reflect.ReflectAccess.newInstance(ReflectAccess.java:128)
    at java.base/jdk.internal.reflect.ReflectionFactory.newInstance(ReflectionFactory.java:347)
    at java.base/java.lang.Class.newInstance(Class.java:645)
    at ru.vyarus.dropwizard.guice.module.GuiceyInitializer.prepareInstallers(GuiceyInitializer.java:217)
    at ru.vyarus.dropwizard.guice.module.GuiceyInitializer.resolveInstallers(GuiceyInitializer.java:119)
    at ru.vyarus.dropwizard.guice.GuiceBundle.initialize(GuiceBundle.java:123)
    at io.dropwizard.setup.Bootstrap.addBundle(Bootstrap.java:150)
    at com.test.aae.aggregator.facade.App.initialize(App.java:164)
    at io.dropwizard.Application.run(Application.java:88)
    at com.test.aae.aggregator.facade.App.main(App.java:46)
Caused by: java.lang.ClassNotFoundException: org.glassfish.jersey.server.spi.internal.ValueParamProvider
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)

I am using the following dependency in my pom.xml:

<dependency>
   <groupId>org.glassfish.jersey.bundles.repackaged</groupId>
   <artifactId>jersey-guava</artifactId>
   <version>${jersey-guava.version}</version>
</dependency>

<dependency>
   <groupId>org.glassfish.jersey.core</groupId>
   <artifactId>jersey-server</artifactId>
   <version>2.22.1</version>
</dependency>

My app is running with java 17


问:
want to get all jpg from device storage using packages path provider and file manager
I want to get different files from device storage using different extensions. but the packages I want to use is file manager and path provider.</p>


问:
Storing Binary Combinations in an elegant way
For my problem I have 16 inputs, which can be switched on and off individually and an output that depends on the input combinations. I now want to store the output for each input combination in an one-dimensional-array. This is rather trivial to do if I store every possible input combination, since I can just use the binary coding. The combination 2x0000 0000 0000 1000 would be 10 as a decimal, so I store it as the tenth element of my array.

However, due to storage constraints, I just want to save the combinatons where at least one input is switched on, but also just up to a maximum of n inputs. As an example for a maximum of n=4 inputs, I would want to store
"0010 0100 0101 0000"
but not
"0110 1111 0111 1001"
if that makes sense.

So instead of storing all 2^16=65,536 combinations, I would only need to save 16c4=1,820 (Edit: This number is wrong I think, I can't use nCr here) combinations. But I can't use the binary coding anymore. For example my last entry would be 1111 0000 0000 0000, which is around 61,000 in decimal and not 1,820.

So how could I find this specific combination again?

Currently, I added a second column where I store the binary combination of inputs, but this yet again increases the storage demand. I also now have to search this column for the right combination, increasing computational load as well.
I wonder if there is a sytem to store these combinations and recall them using the same system.


问:
django : AttributeError: 'str' object has no attribute 'utcoffset'
```<code>template:
<h2>Summary Details</h2>
  <table class="center">
    <thead>
    <tr>
      <th>scrapper_id</th>
      <th>scrapper_jobs_log_id</th>
      <th>external_job_source_id</th>
    </tr>
    </thead>
    <tbody>
    {% for stud in scrappers %}
    {% csrf_token %}
      <tr>
        <td>{{stud.scrapper_id}}</td>
        <td>{{stud.scrapper_jobs_log_id}}</td>
        <td>{{stud.external_job_source_id}}</td>
      </tr>
    {% endfor %}

views.py
from django.db.models import Q
from django.utils import timezone
import pytz
import warnings
warnings.filterwarnings("ignore")
get_records_by_date = ""

def index(request):
    if request.method == "POST":
        from_date = request.POST.get("from_date")
        f_date = datetime.datetime.strptime(from_date,'%Y-%m-%d')
        print(f_date)
        to_date = request.POST.get("to_date")
        t_date = datetime.datetime.strptime(to_date, '%Y-%m-%d')
        print(t_date)
        new_records_check_box_status = request.POST.get("new_records", None)
        print(new_records_check_box_status)
        error_records_check_box_status = request.POST.get("error_records", None)
        print(error_records_check_box_status)
        drop_down_status = request.POST.get("field",None)
        print(drop_down_status)
        global get_records_by_date
        if new_records_check_box_status is None and error_records_check_box_status is None:
            get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date))
            get_records_by_date = check_drop_down_status(get_records_by_date,drop_down_status)
        elif new_records_check_box_status and error_records_check_box_status is None:
            get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)).filter(new_records__gt=0)
            get_records_by_date = check_drop_down_status(get_records_by_date, drop_down_status)
        elif error_records_check_box_status and new_records_check_box_status is None:
            get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)).filter(error_records__gt=0)
            get_records_by_date = check_drop_down_status(get_records_by_date, drop_down_status)
        else:
            get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)).filter(Q(new_records__gt=0)|Q(error_records__gt=0))
            get_records_by_date = check_drop_down_status(get_records_by_date, drop_down_status)
        # print(get_records_by_date)
    else:
        roles =  Scrapper.objects.all()
        return render(request, "home.html",{"scrappers": roles})

    return render(request, "home.html", {"scrappers": get_records_by_date})
</code>```

AttributeError: 'str' object has no attribute 'utcoffset'. It was running correctly when I run another project and change the url the error is showing. Is there any solution what is the reason for the error. Its showing error in view page and html page return render(request, "home.html",{"scrappers": roles}) . Kindly give a solution

Body:
template:

Summary Details

      scrapper_id
      scrapper_jobs_log_id
      external_job_source_id

    {% for stud in scrappers %}
    {% csrf_token %}

        {{stud.scrapper_id}}
        {{stud.scrapper_jobs_log_id}}
        {{stud.external_job_source_id}}

    {% endfor %}

views.py
from django.db.models import Q
from django.utils import timezone
import pytz
import warnings
warnings.filterwarnings("ignore")
get_records_by_date = ""

def index(request):
    if request.method == "POST":
        from_date = request.POST.get("from_date")
        f_date = datetime.datetime.strptime(from_date,'%Y-%m-%d')
        print(f_date)
        to_date = request.POST.get("to_date")
        t_date = datetime.datetime.strptime(to_date, '%Y-%m-%d')
        print(t_date)
        new_records_check_box_status = request.POST.get("new_records", None)
        print(new_records_check_box_status)
        error_records_check_box_status = request.POST.get("error_records", None)
        print(error_records_check_box_status)
        drop_down_status = request.POST.get("field",None)
        print(drop_down_status)
        global get_records_by_date
        if new_records_check_box_status is None and error_records_check_box_status is None:
            get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date))
            get_records_by_date = check_drop_down_status(get_records_by_date,drop_down_status)
        elif new_records_check_box_status and error_records_check_box_status is None:
            get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)).filter(new_records__gt=0)
            get_records_by_date = check_drop_down_status(get_records_by_date, drop_down_status)
        elif error_records_check_box_status and new_records_check_box_status is None:
            get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)).filter(error_records__gt=0)
            get_records_by_date = check_drop_down_status(get_records_by_date, drop_down_status)
        else:
            get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)).filter(Q(new_records__gt=0)|Q(error_records__gt=0))
            get_records_by_date = check_drop_down_status(get_records_by_date, drop_down_status)
        # print(get_records_by_date)
    else:
        roles =  Scrapper.objects.all()
        return render(request, "home.html",{"scrappers": roles})

    return render(request, "home.html", {"scrappers": get_records_by_date})

AttributeError: 'str' object has no attribute 'utcoffset'. It was running correctly when I run another project and change the url the error is showing. Is there any solution what is the reason for the error. Its showing error in view page and html page return render(request, "home.html",{"scrappers": roles}) . Kindly give a solution


问:
popup menu in iframe, in order not to edit all htmls menu, but only menu in iframe
Not an expert here. I have a question, how can i have the popup menu in an iframe? I have a site menu that has popup content. But when i try to have it in iframe, popup doesn' work. I want to have a  popup menu, so if you want to edit it, you can edit only the menu in iframe, and not all the htmls. But i cannot make it popup in parent html, only inside the iframe, so the popup is not visible.

Otherwise, is a better way to have a site menu that you can edit it in easy way, rather than have it in every html, something that means more edit?

I tried z-index, but couldn't make it work. I tried also changing the dimensions of the iframe, but also din't work.


问:
Could not resolve argument .. maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"?
I keep getting this error when adding controller to my symphony bundle:

Could not resolve argument $returnController of "verzeilberg\UploadImagesBundle\Controller\Crop\CropController::crop()", maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"?

This is the controller (src/Controller/Crop/CropController.php):

```<code>namespace verzeilberg\UploadImagesBundle\Controller\Crop;

class CropController
{

/** @var ImageService */
private $imageService;

public function __construct(ImageService $imageService)
{
    $this->imageService = $imageService;
}

public function crop($returnController,Request $request)
{....
</code>```

Service yaml file (src/Resources/config/services.yaml):

```<code>UploadImagesBundle\Controller\Crop:
resource: '../../src/Controller/Crop'
tags: ['controller.service_arguments']
</code>```

UploadImagesExtension file (src/DependencyInjection/UploadImagesExtension.php):

```<code>...
$loader = new YamlFileLoader($container, new
FileLocator(dirname(__DIR__).'/Resources'));
</code>```

Body:
I keep getting this error when adding controller to my symphony bundle:

Could not resolve argument $returnController of "verzeilberg\UploadImagesBundle\Controller\Crop\CropController::crop()", maybe you forgot to register the controller as a service or missed tagging it with the "controller.service_arguments"?

This is the controller (src/Controller/Crop/CropController.php):

namespace verzeilberg\UploadImagesBundle\Controller\Crop;

class CropController
{

/** @var ImageService */
private $imageService;

public function __construct(ImageService $imageService)
{
    $this->imageService = $imageService;
}

public function crop($returnController,Request $request)
{....

Service yaml file (src/Resources/config/services.yaml):

UploadImagesBundle\Controller\Crop:
resource: '../../src/Controller/Crop'
tags: ['controller.service_arguments']

UploadImagesExtension file (src/DependencyInjection/UploadImagesExtension.php):

...
$loader = new YamlFileLoader($container, new
FileLocator(dirname(__DIR__).'/Resources'));


问:
How to put more weight on one class during training in Pytorch
I try to train a neural network with 12 features in input and 3 possible outputs.

These 3 classes are not balanced, I tried to train my neural network with balanced weight based on the occurrence of each class. So I compute the number of occurrence of each class in my training set

```<code>w = torch.Tensor(df_train["type"].values)
Counter(w.numpy())
</code>```

This outputs me the following:

```<code>Counter({1.0: 20164, 0.0: 25828, 2.0: 13250})
</code>```

And so, the class weights will be computed as:

```<code>class_weights=compute_class_weight(class_weight='balanced',classes= np.unique(w),y=w.numpy())
class_weights=torch.tensor(class_weights,dtype=torch.float)
</code>```

which gives the following weights:

```<code>tensor([0.7646, 0.9793, 1.4904])
</code>```

to be able to input it into the criterion:

```<code>criterion = torch.nn.CrossEntropyLoss(weight=class_weights)
</code>```

The thing is that there is one class (class 1) that I really want to classify correctly. So I prefer the 2 other classes 0 and 2 to be mislabeled as class 1 than the opposite. Of course I don't want to classify everything as class 1 and have a precision of 0 for the 2 other classes.

Therefore what I tried is to give myself the different weights as:

```<code>class_weights=torch.tensor([1., 5., 1.])
</code>```

But I wonder if there is a better way to do such a thing ?
Thank you for your help.

Body:
I try to train a neural network with 12 features in input and 3 possible outputs.

These 3 classes are not balanced, I tried to train my neural network with balanced weight based on the occurrence of each class. So I compute the number of occurrence of each class in my training set

w = torch.Tensor(df_train["type"].values)
Counter(w.numpy())

This outputs me the following:

Counter({1.0: 20164, 0.0: 25828, 2.0: 13250})

And so, the class weights will be computed as:

class_weights=compute_class_weight(class_weight='balanced',classes= np.unique(w),y=w.numpy())
class_weights=torch.tensor(class_weights,dtype=torch.float)

which gives the following weights:

tensor([0.7646, 0.9793, 1.4904])

to be able to input it into the criterion:

criterion = torch.nn.CrossEntropyLoss(weight=class_weights)

The thing is that there is one class (class 1) that I really want to classify correctly. So I prefer the 2 other classes 0 and 2 to be mislabeled as class 1 than the opposite. Of course I don't want to classify everything as class 1 and have a precision of 0 for the 2 other classes.

Therefore what I tried is to give myself the different weights as:

class_weights=torch.tensor([1., 5., 1.])

But I wonder if there is a better way to do such a thing ?
Thank you for your help.


问:
Flutter: java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.name.name/com.name.name.name}: FLutter app keep stopping
Flutter logs:
E/AndroidRuntime(11852):FATAL EXCEPTION: main
E/AndroidRuntime(11852):java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.name.name/com.name.name.name}: java.lang.ClassNotFoundException: Didn't find class "com.name.name.name" on path: DexPathList[[zip file "/data/app/com.portal.name-nCBiBcVsHFUgEAoWt_8Nbw==/base.apk"],

app/gradle file
`

```<code>def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}

def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.google.gms.google-services'

android {
compileSdkVersion 33

sourceSets {
main.java.srcDirs += 'src/main/kotlin'
    }

lintOptions {
disable 'InvalidPackage'
    }

defaultConfig {
TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.name.name"
minSdkVersion 24
targetSdkVersion 30
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
multiDexEnabled true
manifestPlaceholders = [
appAuthRedirectScheme: 'com.name.name'
        ]
    }

    /*buildTypes {
release {
TODO: Add your own signing config for the release build.
Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
        }
    }*/

signingConfigs {
release {
keyAlias keystoreProperties['keyAlias']
keyPassword keystoreProperties['keyPassword']
storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
storePassword keystoreProperties['storePassword']
        }
    }
buildTypes {
release {
multiDexKeepProguard file('multidex-config.pro')
signingConfig signingConfigs.release
        }
    }
}

flutter {
source '../..'
}

dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
def multidex_version = "2.0.1"
implementation "androidx.multidex:multidex:$multidex_version"
implementation 'com.google.firebase:firebase-core:12.0.1'
}

</code>```

```<code>android/gradle

```
buildscript {
    ext.kotlin_version = '1.6.21'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:7.2.1'
        // classpath 'com.android.tools.build:gradle:4.0.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.10'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

```

</code>```

Body:
Flutter logs:
E/AndroidRuntime(11852):FATAL EXCEPTION: main
E/AndroidRuntime(11852):java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.name.name/com.name.name.name}: java.lang.ClassNotFoundException: Didn't find class "com.name.name.name" on path: DexPathList[[zip file "/data/app/com.portal.name-nCBiBcVsHFUgEAoWt_8Nbw==/base.apk"],

app/gradle file
`

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}

def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.google.gms.google-services'

android {
compileSdkVersion 33

sourceSets {
main.java.srcDirs += 'src/main/kotlin'
    }

lintOptions {
disable 'InvalidPackage'
    }

defaultConfig {
TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.name.name"
minSdkVersion 24
targetSdkVersion 30
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
multiDexEnabled true
manifestPlaceholders = [
appAuthRedirectScheme: 'com.name.name'
        ]
    }

    /*buildTypes {
release {
TODO: Add your own signing config for the release build.
Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
        }
    }*/

signingConfigs {
release {
keyAlias keystoreProperties['keyAlias']
keyPassword keystoreProperties['keyPassword']
storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
storePassword keystoreProperties['storePassword']
        }
    }
buildTypes {
release {
multiDexKeepProguard file('multidex-config.pro')
signingConfig signingConfigs.release
        }
    }
}

flutter {
source '../..'
}

dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
def multidex_version = "2.0.1"
implementation "androidx.multidex:multidex:$multidex_version"
implementation 'com.google.firebase:firebase-core:12.0.1'
}

android/gradle

```
buildscript {
    ext.kotlin_version = '1.6.21'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:7.2.1'
        // classpath 'com.android.tools.build:gradle:4.0.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.10'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

```


问:
Howto use a tokencache for an active directory interactive sql connection
I'm having a console application calling some web api's an connecting to the database. Our company policy requires MFA so we used MSAL to implement it for the API and specified the authentication method in the connection string.

```<code>Authentication=Active Directory Interactive;
</code>```

It all works, but the users have to authenticate after the execution of every command. Which is inconvenient. For the web api we were a able to use token caching.

```<code>var cacheHelper = await MsalCacheHelper.CreateAsync(storageProperties );
cacheHelper.RegisterCache(publicClientApplication.UserTokenCache);
</code>```

However, I did not found any solution for the database connection yet.

I tried to build a custom SqlAuthenticationProvider but wasn't succesfull with that.

Body:
I'm having a console application calling some web api's an connecting to the database. Our company policy requires MFA so we used MSAL to implement it for the API and specified the authentication method in the connection string.

Authentication=Active Directory Interactive;

It all works, but the users have to authenticate after the execution of every command. Which is inconvenient. For the web api we were a able to use token caching.

var cacheHelper = await MsalCacheHelper.CreateAsync(storageProperties );
cacheHelper.RegisterCache(publicClientApplication.UserTokenCache);

However, I did not found any solution for the database connection yet.

I tried to build a custom SqlAuthenticationProvider but wasn't succesfull with that.


问:
SNS Heatmap, display one column label out of two
I am currently working on the dataset: Car_Price_Assignment (Kaggle).

When I display my correlation heatmap, with only the 'price' column (x-axis), it displays only one label out of two in y_axis (see below).

Here is my code:

```<code>sns.heatmap(dataset.corr()[['price']], cbar=True, annot=True, cmap='RdBu', fmt='.2f');

fig= plt.gcf()
fig.set_size_inches(4,10)
plt.show()
</code>```

Thank you in advance for your insights :) !!

Display each label in y_axis.

My current heatmap

Body:
I am currently working on the dataset: Car_Price_Assignment (Kaggle).

When I display my correlation heatmap, with only the 'price' column (x-axis), it displays only one label out of two in y_axis (see below).

Here is my code:

sns.heatmap(dataset.corr()[['price']], cbar=True, annot=True, cmap='RdBu', fmt='.2f');

fig= plt.gcf()
fig.set_size_inches(4,10)
plt.show()

Thank you in advance for your insights :) !!

Display each label in y_axis.

My current heatmap


问:
Android media3 exoplayer MediaController: Send fake messages to trigger Player.Listener
I need to trigger a fake event to process the current progress with a flow and update the UI.

I've got following function which belongs to ViewModel A:

```<code>val listener = object : Player.Listener {
    override fun onEvents(player: Player, events: Player.Events) {
            trySend(player.toPlayerState())
                .onFailure { Timber.w(it, "Error sending player state") }

        super.onEvents(player, events)
    }
}
</code>```

This listener gets called on every event from the player (mediaController). All right!

I've got a second ViewModel (ViewModel B) which reseaves a message from the UI progress bar:

```<code>binding.playerControlView.setProgressUpdateListener { position, _ ->
    viewModel.onUpdateProgress(position)
}
</code>```

If the onUpdateProgress function calls eg. the function to increase the sound, the event listener gets triggered. All right!

My goal is to trigger the event listener without changing anything (kind of fake trigger).

This is the code which should trigger the event listener:

```<code>fun onUpdateProgress(position: Long) {
    viewModelScope.launch {
        Timber.d("YYYYYY $position")
        val player = getMediaController()   // Returns  Deferred<MediaController>
        player.todo()  // Replace by correct function
    }
}
</code>```

Maybe there is also a better approach to update the progress UI in ViewModel A?

Body:
I need to trigger a fake event to process the current progress with a flow and update the UI.

I've got following function which belongs to ViewModel A:

val listener = object : Player.Listener {
    override fun onEvents(player: Player, events: Player.Events) {
            trySend(player.toPlayerState())
                .onFailure { Timber.w(it, "Error sending player state") }

        super.onEvents(player, events)
    }
}

This listener gets called on every event from the player (mediaController). All right!

I've got a second ViewModel (ViewModel B) which reseaves a message from the UI progress bar:

binding.playerControlView.setProgressUpdateListener { position, _ ->
    viewModel.onUpdateProgress(position)
}

If the onUpdateProgress function calls eg. the function to increase the sound, the event listener gets triggered. All right!

My goal is to trigger the event listener without changing anything (kind of fake trigger).

This is the code which should trigger the event listener:

fun onUpdateProgress(position: Long) {
    viewModelScope.launch {
        Timber.d("YYYYYY $position")
        val player = getMediaController()   // Returns  Deferred<MediaController>
        player.todo()  // Replace by correct function
    }
}

Maybe there is also a better approach to update the progress UI in ViewModel A?


问:
DJANGO - Unable to refresh my edit profile page
Good day,

I am making a Django application,

I want to call my data that the user signs up with and to display the information they submitted as:

Name
Email

Then I want to be able to change that data and then I want to save it, and reload back into the dashboard, but when I am updating my 'update_profile.html' the info is not updating, I can; add form data and change it

What am I doing wrong?

My code below:

```<code>    views.py
    from django.shortcuts import render, redirect, HttpResponse
    from django.contrib import messages, auth
    from django.contrib.auth.models import User
    from django.contrib.auth.decorators import login_required
    from contacts.models import Contact

    def register(request):
        if request.method == 'POST':
            # Get form values
            first_name = request.POST['first_name']
            last_name = request.POST['last_name']
            username = request.POST['username']
            email = request.POST['email']
            password = request.POST['password']
            password2 = request.POST['password2']

            # Check if passwords match
            if password == password2:
                # Check username
                if User.objects.filter(username=username).exists():
                    messages.error(request, 'That username is taken')
                    return redirect('register')
                else:
                    if User.objects.filter(email=email).exists():
                        messages.error(request, 'That email is being used')
                        return redirect('register')
                    else:
                        # Looks good
                        user = User.objects.create_user(
                            username=username, password=password, email=email, first_name=first_name, last_name=last_name)  # noqa
                        # Login after register
                        auth.login(request, user)
                        messages.success(request, 'You are now logged in')
                        return redirect('index')
                        # user.save()
                        # messages.success(
                        #     request, 'You are now registered and can log in')
                        # return redirect('login')
            else:
                messages.error(request, 'Passwords do not match')
                return redirect('register')
        else:
            return render(request, 'accounts/register.html')

    def login(request):
        if request.method == 'POST':
            username = request.POST['username']
            password = request.POST['password']

            user = auth.authenticate(username=username, password=password)

            if user is not None:
                auth.login(request, user)
                messages.success(request, 'You are now logged in')
                return redirect('dashboard')
            else:
                messages.error(request, 'Invalid credentials')
                return redirect('login')
        else:
            return render(request, 'accounts/login.html')

    def logout(request):
        if request.method == 'POST':
            auth.logout(request)
            messages.success(request, 'You are now logged out')
            return redirect('index')

    @login_required(login_url='login')
    def dashboard(request):
        user_contacts = Contact.objects.order_by(
            '-contact_date').filter(user_id=request.user.id)

        context = {
            'contacts': user_contacts
        }
        return render(request, 'accounts/dashboard.html', context)

    @login_required(login_url='login')
    def edit_profile(request, pk):

        user = User.objects.get(id=pk)

        if request.method == 'POST':
            ...
            user.name = request.GET['name']
            user.email_address = request.GET['email_address']

            user.save()
            return redirect('dashboard')

        context = {
            'user': user
            }

        return render(request, 'accounts/dashboard.html', context)

@login_required(login_url='login')
def delete_profile(request, pk):

    user = User.objects.get(id=pk)

    if request.method == 'POST':
        ...
        user.name = request.GET['name']
        user.email_address = request.GET['email_address']

        user.delete()
        return redirect('index')

    context = {
        'user': user
    }

    return render(request, 'index.html', context)
</code>```

Then my urls

```<code>urls.py
from django.urls import path

from . import views

urlpatterns = [
    path('register', views.register, name='register'),
    path('login', views.login, name='login'),
    path('logout', views.logout, name='logout'),
    path('dashboard', views.dashboard, name='dashboard'),
    path('edit_profile/<int:pk>/', views.edit_profile, name='edit_profile'),
]
</code>```

Lastly My edit_profile.html

```<code>{% extends 'base.html' %}

{% block title %} | Edit Profile {% endblock %}

{% block content %}
<section id="showcase-inner" class="py-5 text-white">
    <div class="container">
      <div class="row text-center">
        <div class="col-md-12">
          <h1 class="display-4">User Dashboard</h1>
          <p class="lead">Manage your BT Real Estate account</p>
        </div>
      </div>
    </div>
  </section>

  <!-- Breadcrumb -->
  <section id="bc" class="mt-3">
    <div class="container">
      <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
          <li class="breadcrumb-item">
            <a href="{% url 'index' %}">
              <i class="fas fa-home"></i> Home</a>
          </li>
          <li class="breadcrumb-item active"> Dashboard</li>
        </ol>
      </nav>
    </div>
  </section>

  {% comment %} Alerts {% endcomment %}
  {% include 'partials/__alerts.html' %}

  <section id="dashboard" class="py-4">
    <div class="container">
      <div class="row">
        <div class="col-md-12">
          <h2>Welcome {{ user.first_name }}
            <a class="btn btn-info" href="{% url 'dashboard' %}">
            Save Profile
            </a>
            <a class="btn btn-da nger" href="{% url 'dashboard' %}">
            Del;ete Profile
            </a>
          </h2>

          <h3>Account Details: </h3>
            <form action="{% url 'contact' %}" method="POST">
                    {% csrf_token %}
                    {% if user.is_authenticated %}
                        <input type="hidden" name="user_id" value="{{ user.id }}">
                    {% else %}
                        <input type="hidden" name="user_id" value="0">
                    {% endif %}
                    <input type="hidden" name="realtor_email" value="{{ listing.realtor.email }}">
                    <input type="hidden" name="listing_id" value="{{ listing.id }}">
                    <div class="form-group">
                        <label for="property_name" class="col-form-label">Property:</label>
                        <input type="text" name="listing" class="form-control" value="{{ listing.title }}" >
                    </div>
                    <div class="form-group">
                        <label for="name" class="col-form-label">Name:</label>
                        <input type="text" name="name" class="form-control" {% if user.is_authenticated %} value="{{ user.first_name }} {{ user.last_name }}" {% endif %} required>
                    </div>
                    <div class="form-group">
                        <label for="email" class="col-form-label">Email:</label>
                        <input type="email" name="email" class="form-control" {% if user.is_authenticated %} value="{{ user.email }}" {% endif %} required>
                    </div>
                    <div class="form-group">
                        <label for="phone" class="col-form-label">Phone:</label>
                        <input type="phone" name="phone" class="form-control" {% if user.is_authenticated %} value="{{ user.phone }}" {% endif %} >
                    </div>
                    <input type="submit" value="Send" class="btn btn-block btn-secondary">
                </form>
        </div>
      </div>
    </div>
  </section>
{% endblock %}
</code>```

PLEASE HELP!

Body:
Good day,

I am making a Django application,

I want to call my data that the user signs up with and to display the information they submitted as:

Name
Email

Then I want to be able to change that data and then I want to save it, and reload back into the dashboard, but when I am updating my 'update_profile.html' the info is not updating, I can; add form data and change it

What am I doing wrong?

My code below:

    views.py
    from django.shortcuts import render, redirect, HttpResponse
    from django.contrib import messages, auth
    from django.contrib.auth.models import User
    from django.contrib.auth.decorators import login_required
    from contacts.models import Contact

    def register(request):
        if request.method == 'POST':
            # Get form values
            first_name = request.POST['first_name']
            last_name = request.POST['last_name']
            username = request.POST['username']
            email = request.POST['email']
            password = request.POST['password']
            password2 = request.POST['password2']

            # Check if passwords match
            if password == password2:
                # Check username
                if User.objects.filter(username=username).exists():
                    messages.error(request, 'That username is taken')
                    return redirect('register')
                else:
                    if User.objects.filter(email=email).exists():
                        messages.error(request, 'That email is being used')
                        return redirect('register')
                    else:
                        # Looks good
                        user = User.objects.create_user(
                            username=username, password=password, email=email, first_name=first_name, last_name=last_name)  # noqa
                        # Login after register
                        auth.login(request, user)
                        messages.success(request, 'You are now logged in')
                        return redirect('index')
                        # user.save()
                        # messages.success(
                        #     request, 'You are now registered and can log in')
                        # return redirect('login')
            else:
                messages.error(request, 'Passwords do not match')
                return redirect('register')
        else:
            return render(request, 'accounts/register.html')

    def login(request):
        if request.method == 'POST':
            username = request.POST['username']
            password = request.POST['password']

            user = auth.authenticate(username=username, password=password)

            if user is not None:
                auth.login(request, user)
                messages.success(request, 'You are now logged in')
                return redirect('dashboard')
            else:
                messages.error(request, 'Invalid credentials')
                return redirect('login')
        else:
            return render(request, 'accounts/login.html')

    def logout(request):
        if request.method == 'POST':
            auth.logout(request)
            messages.success(request, 'You are now logged out')
            return redirect('index')

    @login_required(login_url='login')
    def dashboard(request):
        user_contacts = Contact.objects.order_by(
            '-contact_date').filter(user_id=request.user.id)

        context = {
            'contacts': user_contacts
        }
        return render(request, 'accounts/dashboard.html', context)

    @login_required(login_url='login')
    def edit_profile(request, pk):

        user = User.objects.get(id=pk)

        if request.method == 'POST':
            ...
            user.name = request.GET['name']
            user.email_address = request.GET['email_address']

            user.save()
            return redirect('dashboard')

        context = {
            'user': user
            }

        return render(request, 'accounts/dashboard.html', context)

@login_required(login_url='login')
def delete_profile(request, pk):

    user = User.objects.get(id=pk)

    if request.method == 'POST':
        ...
        user.name = request.GET['name']
        user.email_address = request.GET['email_address']

        user.delete()
        return redirect('index')

    context = {
        'user': user
    }

    return render(request, 'index.html', context)

Then my urls

urls.py
from django.urls import path

from . import views

urlpatterns = [
    path('register', views.register, name='register'),
    path('login', views.login, name='login'),
    path('logout', views.logout, name='logout'),
    path('dashboard', views.dashboard, name='dashboard'),
    path('edit_profile/<int:pk>/', views.edit_profile, name='edit_profile'),
]

Lastly My edit_profile.html

{% extends 'base.html' %}

{% block title %} | Edit Profile {% endblock %}

{% block content %}

User Dashboard

Manage your BT Real Estate account

               Home

 Dashboard

  {% comment %} Alerts {% endcomment %}
  {% include 'partials/__alerts.html' %}

Welcome {{ user.first_name }}

            Save Profile

            Del;ete Profile

Account Details:

            <form action="{% url 'contact' %}" method="POST">
                    {% csrf_token %}
                    {% if user.is_authenticated %}
                        <input type="hidden" name="user_id" value="{{ user.id }}">
                    {% else %}
                        <input type="hidden" name="user_id" value="0">
                    {% endif %}
                    <input type="hidden" name="realtor_email" value="{{ listing.realtor.email }}">
                    <input type="hidden" name="listing_id" value="{{ listing.id }}">

                        Property:
                        <input type="text" name="listing" class="form-control" value="{{ listing.title }}" >

                        Name:
                        <input type="text" name="name" class="form-control" {% if user.is_authenticated %} value="{{ user.first_name }} {{ user.last_name }}" {% endif %} required>

                        Email:
                        <input type="email" name="email" class="form-control" {% if user.is_authenticated %} value="{{ user.email }}" {% endif %} required>

                        Phone:
                        <input type="phone" name="phone" class="form-control" {% if user.is_authenticated %} value="{{ user.phone }}" {% endif %} >

                    <input type="submit" value="Send" class="btn btn-block btn-secondary">
                </form>

{% endblock %}

PLEASE HELP!


问:
Issue when importing dataset: Rows that contain more elements/columns than the previous row are divided between two rows
For a project I receive datasets in the form of text files. These text files are generated by the measuring software from a machine. The data in the files is seperated by spaces and has no header, example of a row:

Mo 27.06.2022 12:01:11  MP2 mv:(mean. 5s): 4,824 mg/mü org.C

When loading this data using
my_data <- read.table("File.txt", header = FALSE, sep = "", dec = ",", fill=TRUE, na.strings=c("","NA"))
I obtain 9 columns in the following format (example), as intended.

|Mo|27.06.2022|12:01:11|MP2|mv:(mean.| 5s):| 4,824| mg/mü| org.C|

However, sometimes the data set starts with a notification from the machine (example):

Mo 27.06.2022 11:42:04  {SE14} service requestend

When this happens, the 'regular' 9 column rows are seperated between two rows (example):

Row 1: Mo|27.06.2022|11:58:26|MP1|mv:(mean.| 5s):|
Row 2: 7,858| mg/mü |org.C

How do I tell R to not perform this seperation between two rows? As I understand, it does this because earlier in the text file, an input of only 6 columns is recognized.
This is a script that we will use for years to come, so help is greatly appreciated!

I've tried removing the fill function from the read.table function, I have tried removing the na.strings, and ofcourse looking for answers on stack overflow, but was not able to encounter this specific problem.


问:
Why is my Code not working? - Responsive Tabs CSS/JS
Im trying to create Tabs which are draggable / swipeable on mobile.

This is what ive got so far but the code does not work..

Even though its not working, i dont think that the code is too far off..

I assume it could be fixed without too much effort.

Any help is much appreciated

const btn = [].slice.call(document.getElementsByTagName('button'));
btn.forEach((item, index) => {
  item.addEventListener('click',function(){
    btn.forEach((item) => {item.classList.remove('active')})
    item.classList.add('active')
    document.getElementById('tab').setAttribute('data-tab', index)
  });
});

// detect touch events
if (document.ontouchstart !== null) {
  // register touch events
  document.addEventListener('touchstart', handleTouchStart, false);
  document.addEventListener('touchmove', handleTouchMove, false);
}

// handle touch start event
function handleTouchStart(event) {
  // get the touch event object
  const touch = event.touches[0];
  // store the starting position of the touch
  touchStartX = touch.pageX;
}

// handle touch move event
function handleTouchMove(event) {
  // get the touch event object
  const touch = event.touches[0];
  // store the current position of the touch
  touchEndX = touch.pageX;

  // calculate the difference between the starting and current positions of the touch
  const diffX = touchStartX - touchEndX;

  // if the touch moved more than 50 pixels to the left,
  // set the data-tab attribute to the next tab
  if (diffX > 50) {
    const currentTab = document.getElementById('tab').getAttribute('data-tab');
    const nextTab = parseInt(currentTab) + 1;
    document.getElementById('tab').setAttribute('data-tab', nextTab);
  }

  // if the touch moved more than 50 pixels to the right,
  // set the data-tab attribute to the previous tab
  if (diffX < -50) {
    const currentTab = document.getElementById('tab').getAttribute('data-tab');
    const nextTab = parseInt(currentTab) - 1;
    document.getElementById('tab').setAttribute('data-tab', nextTab);
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.wrapper {
    overflow: hidden;
}

.tabs {
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
  -webkit-transition: all .9s ease-in-out;
  -moz-transition: all .9s ease-in-out;
  -ms-transition: all .9s ease-in-out;
  -o-transition: all .9s ease-in-out;
  transition: all .9s ease-in-out;
}

.tabs> * {
    width: 100%;
    height: 100%;
    position: absolute
}

.tabs[data-tab='1'] {
    left: 0%;
}

.tabs[data-tab='2'] {
    left: -100%
}

.tabs[data-tab='3'] {
    left: -200%
}

.tabs[data-tab='4'] {
    left: -300%
}

.inliner {
    white-space: nowrap;
}

.inliner > * {
    display: inline-block;
    *display: inline;
}</code>```

      <button> Tab 1</button>
      <button> Tab 2</button>
      <button> Tab 3</button>

Content 1

Content 2

Content 3

```

I tried around with a lot of CSS,

without success unfortunately

Body:
Im trying to create Tabs which are draggable / swipeable on mobile.

This is what ive got so far but the code does not work..

Even though its not working, i dont think that the code is too far off..

I assume it could be fixed without too much effort.

Any help is much appreciated

const btn = [].slice.call(document.getElementsByTagName('button'));
btn.forEach((item, index) => {
  item.addEventListener('click',function(){
    btn.forEach((item) => {item.classList.remove('active')})
    item.classList.add('active')
    document.getElementById('tab').setAttribute('data-tab', index)
  });
});

// detect touch events
if (document.ontouchstart !== null) {
  // register touch events
  document.addEventListener('touchstart', handleTouchStart, false);
  document.addEventListener('touchmove', handleTouchMove, false);
}

// handle touch start event
function handleTouchStart(event) {
  // get the touch event object
  const touch = event.touches[0];
  // store the starting position of the touch
  touchStartX = touch.pageX;
}

// handle touch move event
function handleTouchMove(event) {
  // get the touch event object
  const touch = event.touches[0];
  // store the current position of the touch
  touchEndX = touch.pageX;

  // calculate the difference between the starting and current positions of the touch
  const diffX = touchStartX - touchEndX;

  // if the touch moved more than 50 pixels to the left,
  // set the data-tab attribute to the next tab
  if (diffX > 50) {
    const currentTab = document.getElementById('tab').getAttribute('data-tab');
    const nextTab = parseInt(currentTab) + 1;
    document.getElementById('tab').setAttribute('data-tab', nextTab);
  }

  // if the touch moved more than 50 pixels to the right,
  // set the data-tab attribute to the previous tab
  if (diffX < -50) {
    const currentTab = document.getElementById('tab').getAttribute('data-tab');
    const nextTab = parseInt(currentTab) - 1;
    document.getElementById('tab').setAttribute('data-tab', nextTab);
  }
}

.wrapper {
    overflow: hidden;
}

.tabs {
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
  -webkit-transition: all .9s ease-in-out;
  -moz-transition: all .9s ease-in-out;
  -ms-transition: all .9s ease-in-out;
  -o-transition: all .9s ease-in-out;
  transition: all .9s ease-in-out;
}

.tabs> * {
    width: 100%;
    height: 100%;
    position: absolute
}

.tabs[data-tab='1'] {
    left: 0%;
}

.tabs[data-tab='2'] {
    left: -100%
}

.tabs[data-tab='3'] {
    left: -200%
}

.tabs[data-tab='4'] {
    left: -300%
}

.inliner {
    white-space: nowrap;
}

.inliner > * {
    display: inline-block;
    *display: inline;
}

      <button> Tab 1</button>
      <button> Tab 2</button>
      <button> Tab 3</button>

Content 1

Content 2

Content 3

I tried around with a lot of CSS,

without success unfortunately


问:
Conditional text formatting in Dash DataTable with a callback (edited)
I am using Dash to display a DataTable. In certain column, each cell contains a string (a long  string of comma-separated values). I am looking for a way to format a color (e.g. change it to red) of just some values in the cells based on matching with elements in the list "l". So if there is a value in the list, I would like to have it red in the Dash DataTable but a rest of the string in the cell I need in default color. I guess, there will be a way through a regex expression like in this example: DataTable - Color only substring in a cell
I also tried to use "style_data_conditional" with "filter_query" which colored all the string in cell. This is my testing copy for string "a":

```<code> style_data_conditional = [
                            {'if': {'filter_query': '{col1} contains "a"',
                                    'column_id':'col1'},
                                    'color': 'tomato',
                                    'fontWeight': 'bold',
                             },
</code>```

Can you guys help me on this?
Edited: another challenge is to implement a callback and return this "new style", too.
Thanks.

```<code>import pandas as pd
import numpy as np
import dash
from dash import Dash, html, dcc, dash_table
from dash.dash_table.Format import Format, Sign
from dash.dependencies import Input, Output, State
from dash import dash_table

df = pd.DataFrame({
        "col1":["a, b, c, d", "a, b, d", "a, b, z, x, y", "a, y","y, z, b"],
        "col2":[0, 1, 0, 1, 2]})

l = ["a", "b", "c"]

result_table = dash_table.DataTable(
                id = 'df',
                data = df.to_dict('records'),
                columns = [{'name': str(i), 'id': str(i)} for i in df.columns]
                )

external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"]
app = Dash(__name__, external_stylesheets = external_stylesheets)

app.layout = html.Div([
    html.Div([result_table]),
])

if __name__ == '__main__':
    app.run_server(debug = True, port = 8010)
</code>```

Update:
I think it could be possible to color certain sub-string using (like in the example linked above)

```<code>substituted = pattern.sub(
            f"<span style='color: {color};'>{found.group()}</span>", value)
</code>```

However, I am not quite sure how to "get the styling to the Dash app. through its @app.callback". Would that be possible to update the DataTable with "colored data" using standard data.to_dict('records')?
Thank you.

Body:
I am using Dash to display a DataTable. In certain column, each cell contains a string (a long  string of comma-separated values). I am looking for a way to format a color (e.g. change it to red) of just some values in the cells based on matching with elements in the list "l". So if there is a value in the list, I would like to have it red in the Dash DataTable but a rest of the string in the cell I need in default color. I guess, there will be a way through a regex expression like in this example: DataTable - Color only substring in a cell
I also tried to use "style_data_conditional" with "filter_query" which colored all the string in cell. This is my testing copy for string "a":

 style_data_conditional = [
                            {'if': {'filter_query': '{col1} contains "a"',
                                    'column_id':'col1'},
                                    'color': 'tomato',
                                    'fontWeight': 'bold',
                             },

Can you guys help me on this?
Edited: another challenge is to implement a callback and return this "new style", too.
Thanks.

import pandas as pd
import numpy as np
import dash
from dash import Dash, html, dcc, dash_table
from dash.dash_table.Format import Format, Sign
from dash.dependencies import Input, Output, State
from dash import dash_table

df = pd.DataFrame({
        "col1":["a, b, c, d", "a, b, d", "a, b, z, x, y", "a, y","y, z, b"],
        "col2":[0, 1, 0, 1, 2]})

l = ["a", "b", "c"]

result_table = dash_table.DataTable(
                id = 'df',
                data = df.to_dict('records'),
                columns = [{'name': str(i), 'id': str(i)} for i in df.columns]
                )

external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"]
app = Dash(__name__, external_stylesheets = external_stylesheets)

app.layout = html.Div([
    html.Div([result_table]),
])

if __name__ == '__main__':
    app.run_server(debug = True, port = 8010)

Update:
I think it could be possible to color certain sub-string using (like in the example linked above)

substituted = pattern.sub(
            f"{found.group()}", value)

However, I am not quite sure how to "get the styling to the Dash app. through its @app.callback". Would that be possible to update the DataTable with "colored data" using standard data.to_dict('records')?
Thank you.


问:
spring reuse test context and avoiding circular dependencies
I can‘t seem to figure this out. Project A (which is the core Project where the @SpringBootApplication resides) has a dependency in its pom to project B. Project A imports the configuration of Project B to register the beans  of project B with the @Import Annotation. Project B contains the Configuration that gets imported by A and the Beans that are referenced in that Configuration, thats it. A lot of Unit Tests that I write just @Autowired a Bean that I wanna test and check the behaviour. So there exists an abstract class that every unit test inherits.

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { FooConfig.class, FooTestConfig.class})
public abstract TestContext {}
</code>```
```<code>@Configuration
@Import(BarConfig.class)
public class FooConfig {

}
</code>```
```<code>@Configuration
public class BarConfig {

    public BarBean BarBean () {}
}
</code>```

Now I could just write the test to the Beans of Project B in Project A (that works!) But I want the tests for the Beans in Project B to reside in Project B and not A. When I add a dependency to Project A (test-jar)in the pom.xml of B, I could in theory just inherit the abstract "TestContext" that would work but maven tells me:

Annotation processing is not supported for module cycles.

And rightfully so because Project A depends on B and vice versa. If I write the Unit Test to the Beans in Project B then it works but I want the test to the Beans to reside in Project B.

This is what I want:

```<code>Project A
├── _main/java/packageName
│   ├── FooConfig.java
├── test/java/packageName
│   ├── FooTestConfig.java
│   ├── TestContext.java

Project B
├── main/java/packageName
│   ├── BarBean.java
│   ├── BarConfig.java
├── test/java/packageName
│   ├── BarBeanTest.java
</code>```

This is not what I want but this works:

```<code>Project A
├── _main/java/packageName
│   ├── FooConfig.java
├── test/java/packageName
│   ├── FooTestConfig.java
│   ├── TestContext.java
│   ├── BarBeanTest.java

Project B
├── main/java/packageName
│   ├── BarConfig.java
│   ├── BarBean.java
├── test/java/packageName
│
</code>```

The test would look sth like this, if there wasn't a circular dependency:

```<code>public class BarBeanTest extends TestContext {

   @Autowired
   BarBean barBean;
}
</code>```

I know that one solution would be to create a third Project C to resolve the cyclic dependency but I haven't figured out yet how to provide the TestContext of Project A to other projects.

Body:
I can‘t seem to figure this out. Project A (which is the core Project where the @SpringBootApplication resides) has a dependency in its pom to project B. Project A imports the configuration of Project B to register the beans  of project B with the @Import Annotation. Project B contains the Configuration that gets imported by A and the Beans that are referenced in that Configuration, thats it. A lot of Unit Tests that I write just @Autowired a Bean that I wanna test and check the behaviour. So there exists an abstract class that every unit test inherits.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { FooConfig.class, FooTestConfig.class})
public abstract TestContext {}

@Configuration
@Import(BarConfig.class)
public class FooConfig {

}

@Configuration
public class BarConfig {

    public BarBean BarBean () {}
}

Now I could just write the test to the Beans of Project B in Project A (that works!) But I want the tests for the Beans in Project B to reside in Project B and not A. When I add a dependency to Project A (test-jar)in the pom.xml of B, I could in theory just inherit the abstract "TestContext" that would work but maven tells me:

Annotation processing is not supported for module cycles.

And rightfully so because Project A depends on B and vice versa. If I write the Unit Test to the Beans in Project B then it works but I want the test to the Beans to reside in Project B.

This is what I want:

Project A
├── _main/java/packageName
│   ├── FooConfig.java
├── test/java/packageName
│   ├── FooTestConfig.java
│   ├── TestContext.java

Project B
├── main/java/packageName
│   ├── BarBean.java
│   ├── BarConfig.java
├── test/java/packageName
│   ├── BarBeanTest.java

This is not what I want but this works:

Project A
├── _main/java/packageName
│   ├── FooConfig.java
├── test/java/packageName
│   ├── FooTestConfig.java
│   ├── TestContext.java
│   ├── BarBeanTest.java

Project B
├── main/java/packageName
│   ├── BarConfig.java
│   ├── BarBean.java
├── test/java/packageName
│

The test would look sth like this, if there wasn't a circular dependency:

public class BarBeanTest extends TestContext {

   @Autowired
   BarBean barBean;
}

I know that one solution would be to create a third Project C to resolve the cyclic dependency but I haven't figured out yet how to provide the TestContext of Project A to other projects.


问:
Vite not watching React source code to trigger HMR
hi all i have a windows machine, created a new vite project using npm init vite client HMR was working like a charm but as the app got bigger HMR doesn't work anymore ive added server: { watch: { usePolling: true } } and still this does nothing vite only reloads or notices when changes have been made to vite.config.js can anyone offer any assistance??

this what my vite.config.js looks like:

```<code>import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  server: {
    port: 3000,
    hmr: {
      port: 3000
    },
    watch: {
      persistent: true,
      usePolling: true
    }
  },
  plugins: [react()]
})
</code>```

Body:
hi all i have a windows machine, created a new vite project using npm init vite client HMR was working like a charm but as the app got bigger HMR doesn't work anymore ive added server: { watch: { usePolling: true } } and still this does nothing vite only reloads or notices when changes have been made to vite.config.js can anyone offer any assistance??

this what my vite.config.js looks like:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  server: {
    port: 3000,
    hmr: {
      port: 3000
    },
    watch: {
      persistent: true,
      usePolling: true
    }
  },
  plugins: [react()]
})


问:
Trying to manually connect to AMQP in healthcheck controller
I'm trying to check if my rabbitmq instantiation still runs and put the result in my health-check endpoint, but unfortunatelly i got an error:

Cannot autowire argument $connection of "App\UI\Controller\HealthCheckController::healthCheck()": it references class "Symfony\Component\Messenger\Bridge\Amqp\Transport\Connection" but no such service exists.

Previously I've been checking if the RabbitMQ is working by sending a message through transport and see if everything works.

```<code>use Symfony\Component\Messenger\Bridge\Amqp\Transport\Connection;

class HealthCheckController extends AbstractController
{
    public function __construct(
        private readonly Connection $connection,
    ) {
    }

    #[Route('/health', methods: ['GET'])]
    public function healthCheck(): JsonResponse
    {

        $connection->channel()->isConnected();

        return new JsonResponse([
            'status' => 'ok',
            'rabbitmq' => 'ok',
        ], Response::HTTP_OK);
    }
}
</code>```

Body:
I'm trying to check if my rabbitmq instantiation still runs and put the result in my health-check endpoint, but unfortunatelly i got an error:

Cannot autowire argument $connection of "App\UI\Controller\HealthCheckController::healthCheck()": it references class "Symfony\Component\Messenger\Bridge\Amqp\Transport\Connection" but no such service exists.

Previously I've been checking if the RabbitMQ is working by sending a message through transport and see if everything works.

use Symfony\Component\Messenger\Bridge\Amqp\Transport\Connection;

class HealthCheckController extends AbstractController
{
    public function __construct(
        private readonly Connection $connection,
    ) {
    }

    #[Route('/health', methods: ['GET'])]
    public function healthCheck(): JsonResponse
    {

        $connection->channel()->isConnected();

        return new JsonResponse([
            'status' => 'ok',
            'rabbitmq' => 'ok',
        ], Response::HTTP_OK);
    }
}


问:
how to implement grid over Osmdroid openstreet map in android java
I am creating an offline map application using osmdroid openstreet map I done maximum work but I am stuck on one task i.e. I want to show grid over on my map and that grid size should change when I zoom the map grid size should increases and when I zoom out the map grid size should decreases and also I want latitude longitude of specific grid.
if any one have any idea about how to achieve what I am asking please let me now it will be a big help for me from senior I am looking forward for my solution

thanks in advance to android developer and other who might now the solution.


问:
Image containing errors after upload in php
I am working on Reactjs and Php and sending image data using multiplart form data and trying to upload image using base64 ,

Image is uploading to server but whenever i try to open that image then getting
message "it apperar that we dont support this file format"

Every image is uploding "jpg" format i want image should be same as user upload (dynamic extension instead of static)

I tried with following code, Where i am wrong ?

```<code>$data = json_decode(file_get_contents("php://input"), TRUE);
$files=file_get_contents($_FILES["file"]["tmp_name"]);
$image2 = base64_decode($files);
image = base64_decode(explode( ',', $files)[1]);
$image_name = md5(uniqid(rand(), true));
$path = base_url().'admin_panel/assets/images/';

file_put_contents(
  "uploads/".$image_name.".jpg",
  base64_decode(
    str_replace('data:image/jpeg;base64,', '', $image)
  )
);
</code>```

And i am getting following array after ...( Print_R($_FILES));

```<code> [file] => Array
        (
            [name] => news.png
            [type] => image/png
            [tmp_name] => /tmp/phpAC8FrQ
            [error] => 0
            [size] => 736493
        )
</code>```

Body:
I am working on Reactjs and Php and sending image data using multiplart form data and trying to upload image using base64 ,

Image is uploading to server but whenever i try to open that image then getting
message "it apperar that we dont support this file format"

Every image is uploding "jpg" format i want image should be same as user upload (dynamic extension instead of static)

I tried with following code, Where i am wrong ?

$data = json_decode(file_get_contents("php://input"), TRUE);
$files=file_get_contents($_FILES["file"]["tmp_name"]);
$image2 = base64_decode($files);
image = base64_decode(explode( ',', $files)[1]);
$image_name = md5(uniqid(rand(), true));
$path = base_url().'admin_panel/assets/images/';

file_put_contents(
  "uploads/".$image_name.".jpg",
  base64_decode(
    str_replace('data:image/jpeg;base64,', '', $image)
  )
);

And i am getting following array after ...( Print_R($_FILES));

 [file] => Array
        (
            [name] => news.png
            [type] => image/png
            [tmp_name] => /tmp/phpAC8FrQ
            [error] => 0
            [size] => 736493
        )


问:
Why draggable object jump on the random position jQuery?
I work with draggable and dropablle object, and I have issues with jumping objects on random place.

I have few dropablle areas, and dragable objects, for this I use script:

```<code> $('.draggable-box').draggable();
</code>```

For droping I use this script:

```<code>$('.draggable').draggable({
        stop(e, ui) {

        },
    });

    $('.grid-item').droppable({
        accept: '.draggable',
        drop(e, ui) {
            ui.draggable.appendTo(this);
        },
    });
</code>```

As you can see on attachment it is jumping to random place in the page.

One solution I found:

```<code> $('.draggable').draggable({
        stop(e, ui) {
            $(this).css({
                left: 0,
                top: 0,
            });
        },
    });

    $('.grid-item').droppable({
        accept: '.draggable',
        drop(e, ui) {
            ui.draggable.appendTo(this);
        },
    });
</code>```

But on this case it's stuck on one place, I try to change css values top left, it's no working. As I understood it's taking left and top from first storing box, and for this I get width of the box

```<code>var width = $(".box-legend").width();
var currentWithd = ui.position.left;
</code>```

And try to minus from final position like this:

```<code> $('.draggable').draggable({
            stop(e, ui) {
                $(this).css({ left: currentWithd - width})
            },
        });
</code>```

But every time when I drag element it's jumping randomly, for now i tried and I have no idea how to fix :(

So end result should be dragging element to the storage box, and this element stay on position not jumping.

Body:
I work with draggable and dropablle object, and I have issues with jumping objects on random place.

I have few dropablle areas, and dragable objects, for this I use script:

 $('.draggable-box').draggable();

For droping I use this script:

$('.draggable').draggable({
        stop(e, ui) {

        },
    });

    $('.grid-item').droppable({
        accept: '.draggable',
        drop(e, ui) {
            ui.draggable.appendTo(this);
        },
    });

As you can see on attachment it is jumping to random place in the page.

One solution I found:

 $('.draggable').draggable({
        stop(e, ui) {
            $(this).css({
                left: 0,
                top: 0,
            });
        },
    });

    $('.grid-item').droppable({
        accept: '.draggable',
        drop(e, ui) {
            ui.draggable.appendTo(this);
        },
    });

But on this case it's stuck on one place, I try to change css values top left, it's no working. As I understood it's taking left and top from first storing box, and for this I get width of the box

var width = $(".box-legend").width();
var currentWithd = ui.position.left;

And try to minus from final position like this:

 $('.draggable').draggable({
            stop(e, ui) {
                $(this).css({ left: currentWithd - width})
            },
        });

But every time when I drag element it's jumping randomly, for now i tried and I have no idea how to fix :(

So end result should be dragging element to the storage box, and this element stay on position not jumping.