问:
Mockito mock method throwing exception
I'm trying to mock a class using mock() method; however, it is throwing an exception when I call it.

Here is my code for test class:

```<code>   @Test
   @DisplayName("Function should return when pass in null componentResource")
   public void passinNullResourceDoesNotChangeList() {
      FormHelper formMock = mock(FormHelper.class);
      boolean  persisChanges = false;
      List<Map<String, String>> listArg = new ArrayList<>();
      Map<String, String> filler = new HashMap<>();
      filler.put("Hello", "World");
      listArg.add(filler);
      List<Map<String, String>>  expected = new ArrayList<>(listArg);
      formMock.readMultiProperty(null, listArg, persisChanges);
      assertThat(listArg, is(expected));

   }
</code>```

Here is the FormHelper class:

```<code> private FormHelper() {
   }

   /**
    * Reads the values of the "multi" property of the given component resource and optionally attempts to save it in the new format if
    * needed.
    *
    * @param componentResource the components resource
    * @param items             the list of item data from the property
    * @param persistChanges    if true it will attempt to save the items in the new JSON format when they were in the old '~' separated
    *                          format
    */
   public static void readMultiProperty(final Resource componentResource,
                                        final List<Map<String, String>> items,
                                        final boolean persistChanges) {

      boolean allowModification = false;

      final ValueMap properties = getProperties(componentResource);
      if (properties == null) {
         return;
      } else if (properties instanceof ModifiableValueMap) {
         allowModification = true;
      }

      final String[] multi = properties.get("multi", String[].class);
      if (multi != null) {
         boolean needsConversion = false;

         for (final String item : multi) {
            final Map<String, String> itemData = new HashMap<>();

            try {
               final JSONObject object = new JSONObject(item);
               readFromJsonObject(object, itemData);
            } catch (JSONException ex) {
               needsConversion = true;
               readFromSeparatedValue(item, itemData);
            }

            items.add(itemData);
         }

         if (allowModification && persistChanges && needsConversion) {
            setJsonConvertedValues(componentResource, items);

            try {
               componentResource.getResourceResolver().commit();
            } catch (PersistenceException ex) {
               LOGGER.error(String.format(
                                            "Failed to save changes of the form component at %s", componentResource.getPath()), ex);
            }
         }
      }
   }
}
</code>```

Here is the exception it has thrown:

```<code>java.lang.ExceptionInInitializerError
    at org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter.<init>(ConditionalStackTraceFilter.java:17)
    at org.mockito.exceptions.base.MockitoException.filterStackTrace(MockitoException.java:30)
    at org.mockito.exceptions.base.MockitoException.<init>(MockitoException.java:19)
    at org.mockito.exceptions.misusing.MockitoConfigurationException.<init>(MockitoConfigurationException.java:18)
    at org.mockito.internal.configuration.ClassPathLoader.loadImplementations(ClassPathLoader.java:145)
    at org.mockito.internal.configuration.ClassPathLoader.findPluginImplementation(ClassPathLoader.java:110)
    at org.mockito.internal.configuration.ClassPathLoader.findPlatformMockMaker(ClassPathLoader.java:106)
    at org.mockito.internal.configuration.ClassPathLoader.<clinit>(ClassPathLoader.java:59)
    at org.mockito.internal.util.MockUtil.<clinit>(MockUtil.java:21)
    at org.mockito.internal.MockitoCore.<init>(MockitoCore.java:40)
    at org.mockito.Mockito.<clinit>(Mockito.java:932)
    at com.iggroup.onedomain.form.FormHelperTest.passinNullResourceDoesNotChangeList(FormHelperTest.java:38)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:675)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:125)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:132)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:124)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:74)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:104)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:62)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:43)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:35)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:202)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:198)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:69)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.util.ArrayList.forEach(ArrayList.java:1259)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.util.ArrayList.forEach(ArrayList.java:1259)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
    at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Caused by: java.lang.NullPointerException
    at org.mockito.internal.exceptions.stacktrace.StackTraceFilter.<clinit>(StackTraceFilter.java:21)
    ... 77 more
</code>```

The exception is definitely referring to the line where the mock() method is called, but I don't know why.

答:
FormHelper has a private constructor and readMultiProperty is a static method. You cannot use Mockito to mock the static method.

In order to mock the static method, you can use PowerMockito to mock it.

But I don't recommend you to do so. The best way is to avoid using PowerMockito, and design your code to be testable code.

For e.g. in your case, FormHelper can be a singleton service and let's design it to implement an interface.

Title: Mockito mock method throwing exception

Body:
I'm trying to mock a class using mock() method; however, it is throwing an exception when I call it.

Here is my code for test class:

   @Test
   @DisplayName("Function should return when pass in null componentResource")
   public void passinNullResourceDoesNotChangeList() {
      FormHelper formMock = mock(FormHelper.class);
      boolean  persisChanges = false;
      List<Map<String, String>> listArg = new ArrayList<>();
      Map<String, String> filler = new HashMap<>();
      filler.put("Hello", "World");
      listArg.add(filler);
      List<Map<String, String>>  expected = new ArrayList<>(listArg);
      formMock.readMultiProperty(null, listArg, persisChanges);
      assertThat(listArg, is(expected));

   }

Here is the FormHelper class:

 private FormHelper() {
   }

   /**
    * Reads the values of the "multi" property of the given component resource and optionally attempts to save it in the new format if
    * needed.
    *
    * @param componentResource the components resource
    * @param items             the list of item data from the property
    * @param persistChanges    if true it will attempt to save the items in the new JSON format when they were in the old '~' separated
    *                          format
    */
   public static void readMultiProperty(final Resource componentResource,
                                        final List<Map<String, String>> items,
                                        final boolean persistChanges) {

      boolean allowModification = false;

      final ValueMap properties = getProperties(componentResource);
      if (properties == null) {
         return;
      } else if (properties instanceof ModifiableValueMap) {
         allowModification = true;
      }

      final String[] multi = properties.get("multi", String[].class);
      if (multi != null) {
         boolean needsConversion = false;

         for (final String item : multi) {
            final Map<String, String> itemData = new HashMap<>();

            try {
               final JSONObject object = new JSONObject(item);
               readFromJsonObject(object, itemData);
            } catch (JSONException ex) {
               needsConversion = true;
               readFromSeparatedValue(item, itemData);
            }

            items.add(itemData);
         }

         if (allowModification && persistChanges && needsConversion) {
            setJsonConvertedValues(componentResource, items);

            try {
               componentResource.getResourceResolver().commit();
            } catch (PersistenceException ex) {
               LOGGER.error(String.format(
                                            "Failed to save changes of the form component at %s", componentResource.getPath()), ex);
            }
         }
      }
   }
}

Here is the exception it has thrown:

java.lang.ExceptionInInitializerError
    at org.mockito.internal.exceptions.stacktrace.ConditionalStackTraceFilter.<init>(ConditionalStackTraceFilter.java:17)
    at org.mockito.exceptions.base.MockitoException.filterStackTrace(MockitoException.java:30)
    at org.mockito.exceptions.base.MockitoException.<init>(MockitoException.java:19)
    at org.mockito.exceptions.misusing.MockitoConfigurationException.<init>(MockitoConfigurationException.java:18)
    at org.mockito.internal.configuration.ClassPathLoader.loadImplementations(ClassPathLoader.java:145)
    at org.mockito.internal.configuration.ClassPathLoader.findPluginImplementation(ClassPathLoader.java:110)
    at org.mockito.internal.configuration.ClassPathLoader.findPlatformMockMaker(ClassPathLoader.java:106)
    at org.mockito.internal.configuration.ClassPathLoader.<clinit>(ClassPathLoader.java:59)
    at org.mockito.internal.util.MockUtil.<clinit>(MockUtil.java:21)
    at org.mockito.internal.MockitoCore.<init>(MockitoCore.java:40)
    at org.mockito.Mockito.<clinit>(Mockito.java:932)
    at com.iggroup.onedomain.form.FormHelperTest.passinNullResourceDoesNotChangeList(FormHelperTest.java:38)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:675)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:125)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:132)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:124)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:74)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:104)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:62)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:43)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:35)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:202)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:198)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:69)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.util.ArrayList.forEach(ArrayList.java:1259)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.util.ArrayList.forEach(ArrayList.java:1259)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
    at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Caused by: java.lang.NullPointerException
    at org.mockito.internal.exceptions.stacktrace.StackTraceFilter.<clinit>(StackTraceFilter.java:21)
    ... 77 more

The exception is definitely referring to the line where the mock() method is called, but I don't know why.


来源: stackexchange

问:
typeorm inner join and where problem - BaseEntity model
I use typeorm (^0.2.41) and define two model which extends from my custom BaseModel:

BaseModel:

```<code>import { BaseEntity } from 'typeorm';

export class BaseModel extends BaseEntity {
}
</code>```

Category:

```<code>@Entity('Category', { schema: 'public' })
export class Category extends BaseModel {
  @PrimaryGeneratedColumn({ type: 'integer', name: 'id' })
  id: number;

  @OneToMany(() => AbilityCategory, (abilityCategory) => abilityCategory.category, { onDelete: 'CASCADE' })
  abilityCategories: AbilityCategory[];
}
</code>```

AbilityCategory:

```<code>@Entity('_ability_category', { schema: 'public' })
export class AbilityCategory extends BaseModel {
  @PrimaryGeneratedColumn({ type: 'integer', name: 'id' })
  id: number;

  @ManyToOne(() => Category, (category) => category.abilityCategories)
  @JoinColumn([{ name: 'categoryId', referencedColumnName: 'id' }])
  category: Category;
}
</code>```

(I've removed unnecessary fields, before mention here)

and I write this query:

```<code>await Category.find({
  where: {
    type: 'JobCategory',
    'abilityCategories.id': 13
  },
  join: {
    alias: 'category',
    innerJoinAndSelect: { abilityCategories: 'category.abilityCategories' }
  },
  take: 5
}
);
</code>```

but in raw sql query, it passes null to abilityCategories.id:

```<code>SELECT DISTINCT "distinctAlias"."category_id" as "ids_category_id"
FROM (SELECT "category"."id" AS "category_id"
      FROM "public"."Category" "category"
               INNER JOIN "public"."_ability_category" "abilityCategories"
      ON "abilityCategories"."categoryId" = "category"."id"
      WHERE ("category"."type" = $1 AND "abilityCategories"."id" = $2)) "distinctAlias"
ORDER BY "category_id" ASC
LIMIT 5 -- PARAMETERS: ["JobCategory",null]
</code>```

is there anyone to help me find out the reason of null value for second parameter?

答:
it is related to this issue on GitHub

https://github.com/typeorm/typeorm/issues/3890

ContentLicense: CC BY-SA 4.0

Body:
I use typeorm (^0.2.41) and define two model which extends from my custom BaseModel:

BaseModel:

import { BaseEntity } from 'typeorm';

export class BaseModel extends BaseEntity {
}

Category:

@Entity('Category', { schema: 'public' })
export class Category extends BaseModel {
  @PrimaryGeneratedColumn({ type: 'integer', name: 'id' })
  id: number;

  @OneToMany(() => AbilityCategory, (abilityCategory) => abilityCategory.category, { onDelete: 'CASCADE' })
  abilityCategories: AbilityCategory[];
}

AbilityCategory:

@Entity('_ability_category', { schema: 'public' })
export class AbilityCategory extends BaseModel {
  @PrimaryGeneratedColumn({ type: 'integer', name: 'id' })
  id: number;

  @ManyToOne(() => Category, (category) => category.abilityCategories)
  @JoinColumn([{ name: 'categoryId', referencedColumnName: 'id' }])
  category: Category;
}

(I've removed unnecessary fields, before mention here)

and I write this query:

await Category.find({
  where: {
    type: 'JobCategory',
    'abilityCategories.id': 13
  },
  join: {
    alias: 'category',
    innerJoinAndSelect: { abilityCategories: 'category.abilityCategories' }
  },
  take: 5
}
);

but in raw sql query, it passes null to abilityCategories.id:

SELECT DISTINCT "distinctAlias"."category_id" as "ids_category_id"
FROM (SELECT "category"."id" AS "category_id"
      FROM "public"."Category" "category"
               INNER JOIN "public"."_ability_category" "abilityCategories"
      ON "abilityCategories"."categoryId" = "category"."id"
      WHERE ("category"."type" = $1 AND "abilityCategories"."id" = $2)) "distinctAlias"
ORDER BY "category_id" ASC
LIMIT 5 -- PARAMETERS: ["JobCategory",null]

is there anyone to help me find out the reason of null value for second parameter?


问:
Mockito in maven using JPMS cannot access a member of class with modifiers "private"
I am migrating a codebase to Java 11 and JPMS / Jigsaw and am having some trouble with mocking.

This is the test I am trying to run.

```<code>import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
public class DbTest {

    @Mock
    private Connection connection;

    @Mock
    private PreparedStatement preparedStatement;

    @Captor
    private ArgumentCaptor<Timestamp> dateCaptor;

    @Test
    public void setTimestamp_instant() throws SQLException {
        Instant inputTime = Instant.parse("2018-03-12T10:25:37.386Z");
        when(connection.prepareStatement(anyString())).thenReturn(preparedStatement);
        PreparedStatement preparedStatement = connection.prepareStatement("UPDATE fakeTable SET time = ? WHERE TRUE");
        RowPack rowPack = new RowPack(preparedStatement, DatabaseType.MYSQL);
        rowPack.setTimestamp(inputTime);
        verify(preparedStatement).setTimestamp(anyInt(), dateCaptor.capture(), Mockito.any(Calendar.class));
    }
}
</code>```

When running this test in Eclipse it passes but when I run it through maven it fails due to mockito being unable to find some resources using reflection.

```<code>org.mockito.exceptions.base.MockitoException: Problems setting field connection annotated with @org.mockito.Mock(name="", stubOnly=false, extraInterfaces={}, answer=RETURNS_DEFAULTS, serializable=false, lenient=false)
Caused by: java.lang.IllegalAccessException: class org.mockito.internal.util.reflection.ReflectionMemberAccessor cannot access a member of class foo.bar.DbTest (in module foo.bar) with modifiers "private"
</code>```

I am using Surefire 3.0.0-M5, junit 5.7.0 and mockito 3.5.10.

```<code>        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-junit-jupiter</artifactId>
            <scope>test</scope>
        </dependency>
</code>```

Needless to say this worked well in maven before switching to modularising with JPMS.

I have read Testing in the modular world and tried the junit-platform-maven-plugin as a replacement for surefire but ran into similar problems with mockito.

Help would be greatly appreciated.

答:
I had a similar problem. I am using Junit and Mockito on a Java 11 jpms project and wanted to run my tests using maven.

To build upon deduper's great answer, I added:

```<code><configuration>
    <argLine>--add-opens foo.bar/foo.bar=ALL-UNNAMED</argLine>
</configuration>
</code>```

on my surefire configuration.

Notice the 2 prefixed dashes --, without them add-opens was parsed as a class and throws an Error.

Body:
I am migrating a codebase to Java 11 and JPMS / Jigsaw and am having some trouble with mocking.

This is the test I am trying to run.

import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
public class DbTest {

    @Mock
    private Connection connection;

    @Mock
    private PreparedStatement preparedStatement;

    @Captor
    private ArgumentCaptor<Timestamp> dateCaptor;

    @Test
    public void setTimestamp_instant() throws SQLException {
        Instant inputTime = Instant.parse("2018-03-12T10:25:37.386Z");
        when(connection.prepareStatement(anyString())).thenReturn(preparedStatement);
        PreparedStatement preparedStatement = connection.prepareStatement("UPDATE fakeTable SET time = ? WHERE TRUE");
        RowPack rowPack = new RowPack(preparedStatement, DatabaseType.MYSQL);
        rowPack.setTimestamp(inputTime);
        verify(preparedStatement).setTimestamp(anyInt(), dateCaptor.capture(), Mockito.any(Calendar.class));
    }
}

When running this test in Eclipse it passes but when I run it through maven it fails due to mockito being unable to find some resources using reflection.

org.mockito.exceptions.base.MockitoException: Problems setting field connection annotated with @org.mockito.Mock(name="", stubOnly=false, extraInterfaces={}, answer=RETURNS_DEFAULTS, serializable=false, lenient=false)
Caused by: java.lang.IllegalAccessException: class org.mockito.internal.util.reflection.ReflectionMemberAccessor cannot access a member of class foo.bar.DbTest (in module foo.bar) with modifiers "private"

I am using Surefire 3.0.0-M5, junit 5.7.0 and mockito 3.5.10.

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-junit-jupiter</artifactId>
            <scope>test</scope>
        </dependency>

Needless to say this worked well in maven before switching to modularising with JPMS.

I have read Testing in the modular world and tried the junit-platform-maven-plugin as a replacement for surefire but ran into similar problems with mockito.

Help would be greatly appreciated.

Body:
I had a similar problem. I am using Junit and Mockito on a Java 11 jpms project and wanted to run my tests using maven.

To build upon deduper's great answer, I added:

<configuration>
    <argLine>--add-opens foo.bar/foo.bar=ALL-UNNAMED</argLine>
</configuration>

on my surefire configuration.

Notice the 2 prefixed dashes --, without them add-opens was parsed as a class and throws an Error.


问:
Can I change the theme name in WordPress?
How can I change the theme name in WordPress and where?

Can I also change the folder name theme1244 in public/wp-content/themes/theme1244 without having problems in the future?

答:
The answers above are good, but I wanted the full list and this is it
so go to: wp-content/themes/{your site name folder}/style.css
and change this values if they exist, if not you can add them

```<code>/* this should be at the top of your theme CSS file

 Theme Name:   Twenty Fifteen Child
 Theme URI:    http://example.com/twenty-fifteen-child/
 Description:  Twenty Fifteen Child Theme
 Author:       John Doe
 Author URI:   http://example.com
 Template:     twentyfifteen
 Version:      1.0.0
 License:      GNU General Public License v2 or later
 License URI:  http://www.gnu.org/licenses/gpl-2.0.html
 Tags:         light, dark, two-columns, right-sidebar, responsive-layout, accessibility-ready
 Text Domain:  twentyfifteenchild
*/
</code>```

See Source for more details

Body:
The answers above are good, but I wanted the full list and this is it
so go to: wp-content/themes/{your site name folder}/style.css
and change this values if they exist, if not you can add them

/* this should be at the top of your theme CSS file

 Theme Name:   Twenty Fifteen Child
 Theme URI:    http://example.com/twenty-fifteen-child/
 Description:  Twenty Fifteen Child Theme
 Author:       John Doe
 Author URI:   http://example.com
 Template:     twentyfifteen
 Version:      1.0.0
 License:      GNU General Public License v2 or later
 License URI:  http://www.gnu.org/licenses/gpl-2.0.html
 Tags:         light, dark, two-columns, right-sidebar, responsive-layout, accessibility-ready
 Text Domain:  twentyfifteenchild
*/

See Source for more details


问:
MySQL limits decimals in round() to fewer than expected
I have two different MySQL servers, when i run the following query on both, i get different results:

SELECT round(1/3,6) -- 0,333333 on Server1
SELECT round(1/3,6) -- 0,3333   on Server2
```
<p>The first one gives 6 decimals as expected, the second one gives only 4 decimals.</p>
<pre class="lang-sql prettyprint-override"><code>SELECT format(round(1/3,6),6) -- 0,333333 on Server1
SELECT format(round(1/3,6),6) -- 0,333300 on Server2

SELECT round(cast(1 as float)/3,6) -- 0,333333 (6 decimals) on both

SELECT 1/3 -- 0,3333 (4 decimals) on both as expected
</code>```

The MySQL Version is 8.0.18-9 on Server1 and 8.0.26-17 on Server2.
div_precision_increment = 4 on both servers.

UPDATE:

Its a mysql version issue - when updated to 8.0.26 both servers have the same issue. But i think its the behaviour of 8.0.26 thats buggy.

In 8.0.27 there is a bugfix description that might address this issue:

Type resolution for negation did not set the proper precision when converting the type from integer to decimal. This is fixed by assigning the same precision as the argument. (Bug #32863037)

But Percona does not offer that update for now, so ill try to downgrade and then wait for 8.0.27+

答:
UPDATE:

This is a error in the version, update the version of the 8.0.18 server to the same version

it is a server variable

```<code>SET div_precision_increment = 6;
</code>```

will change for the session the number of digits.
This variable indicates the number of digits by which to increase the scale of the result of division operations performed with the / operator. The default value is 4. The minimum and maximum values are 0 and 30, respectively. The following example illustrates the effect of increasing the default value.

more information

Body:
I have two different MySQL servers, when i run the following query on both, i get different results:

SELECT round(1/3,6) -- 0,333333 on Server1
SELECT round(1/3,6) -- 0,3333   on Server2

The first one gives 6 decimals as expected, the second one gives only 4 decimals.

SELECT format(round(1/3,6),6) -- 0,333333 on Server1
SELECT format(round(1/3,6),6) -- 0,333300 on Server2

SELECT round(cast(1 as float)/3,6) -- 0,333333 (6 decimals) on both

SELECT 1/3 -- 0,3333 (4 decimals) on both as expected

The MySQL Version is 8.0.18-9 on Server1 and 8.0.26-17 on Server2.
div_precision_increment = 4 on both servers.

UPDATE:

Its a mysql version issue - when updated to 8.0.26 both servers have the same issue. But i think its the behaviour of 8.0.26 thats buggy.

In 8.0.27 there is a bugfix description that might address this issue:

Type resolution for negation did not set the proper precision when converting the type from integer to decimal. This is fixed by assigning the same precision as the argument. (Bug #32863037)

But Percona does not offer that update for now, so ill try to downgrade and then wait for 8.0.27+

Body:
UPDATE:

This is a error in the version, update the version of the 8.0.18 server to the same version

it is a server variable

SET div_precision_increment = 6;

will change for the session the number of digits.
This variable indicates the number of digits by which to increase the scale of the result of division operations performed with the / operator. The default value is 4. The minimum and maximum values are 0 and 30, respectively. The following example illustrates the effect of increasing the default value.

more information


问:
Class parameter name for default type in spring-kafka listener
I'm attempting to change the default type value for kafka listener with property  "spring.json.value.default.type=" using my own annotation in spring-kafka. Currently, it's possible to overwrite it with following values:
properties="spring.json.value.default.type=com.package.class" which is canonical name of class.
I've made an annotation that sets the following value:

```<code>@MyAnnotation(topic = Topics.BUILD_CONFIG_CREATED, defaultType = ConstantsClass.TYPE_HEADER + "prz.student.finger.kafkaBSC.MyObjectDTO")
</code>```

Is there any way to avoid hard typing the class name?
I would like to implement the option to use the following code(just giving the class that was imported):

```<code>@MyAnnotation(topic = Topics.BUILD_CONFIG_CREATED, defaultType = MyObjectDTO.class)
</code>```

The closest to I've got is adding in my annotation:

```<code>@AliasFor(annotation = KafkaListener.class, attribute = "properties")
    String defaultType() default headerType()+dtoType().getCanonicalName().toString();
String headerType() default "spring.json.value.default.type=";
</code>```

Unfortunately, the constraints regarding the compilation time values for class in annotation blocks me from implementing it. Is there any way to inject the cannonical name without hard typing it, or any other way to implement this?

答:
The properties property can contain SpEL (see its Javadocs).

Something like #{@someBean.type.name}; where someBean is a bean with a method public Class<?> getType().

Body:
I'm attempting to change the default type value for kafka listener with property  "spring.json.value.default.type=" using my own annotation in spring-kafka. Currently, it's possible to overwrite it with following values:
properties="spring.json.value.default.type=com.package.class" which is canonical name of class.
I've made an annotation that sets the following value:

@MyAnnotation(topic = Topics.BUILD_CONFIG_CREATED, defaultType = ConstantsClass.TYPE_HEADER + "prz.student.finger.kafkaBSC.MyObjectDTO")

Is there any way to avoid hard typing the class name?
I would like to implement the option to use the following code(just giving the class that was imported):

@MyAnnotation(topic = Topics.BUILD_CONFIG_CREATED, defaultType = MyObjectDTO.class)

The closest to I've got is adding in my annotation:

@AliasFor(annotation = KafkaListener.class, attribute = "properties")
    String defaultType() default headerType()+dtoType().getCanonicalName().toString();
String headerType() default "spring.json.value.default.type=";

Unfortunately, the constraints regarding the compilation time values for class in annotation blocks me from implementing it. Is there any way to inject the cannonical name without hard typing it, or any other way to implement this?


问:
Control.Invoke() and Control.BeginInvoke() - Where are the past parameters stored? How is it disposed?
I have done a lot of reading about Control.Invoke and Control.BeginInvoke and understand that Invoke is like SendMessage() and BeginInvoke is like PostMessage(), but I do not understand where the parameter list passed via new object[] { arg, arg, arg, ...} is stored. During a conventional call, parameters are pushed to the stack and popped within the called function, then the call frame is recovered from the stack after exit, I assume releasing any references to any heap objects, allowing them to be collected. So, where is the pushed stack date for Invoke/BeginInvoke stored? How does it get disposed once the method called exits?

Also, I have successfully invoked a control method without loading a new object array with the pass parameters. Why would this work? Better yet, since it does work, why would all the examples I have ever seen show it with a new object array?

This is what I have always seen and used:

```<code>BeginInvoke(FormReceiveEvent, new object[] { Event, Arg1, Arg2, Arg3 });
</code>```

But this works too:

```<code>BeginInvoke(FormReceiveEvent, Event, Arg1, Arg2, Arg3);
</code>```

Any information and comments are always appreciated...

Thanks in advance.

答:
The object[] containing the parameters is stored internally by the BeginInvoke method while it asynchronously invokes the target delegate. The reference to the array is released once the asynchronous call completes, allowing the array and its contents (assuming they are not otherwise reachable) to be collected.

The BeginInvoke(FormReceiveEvent, Event, Arg1, Arg2, Arg3); form works because the second parameter to BeginInvoke is defined as params object[]. This means that if you don't explicitly create an array, the compiler will do it for you. Therefore, the two calls are identical in terms of runtime behaviour.

A note on terminology: in the context of .Net, to say that an object is "disposed" typically means that the object implements IDisposable and that its IDisposable.Dispose method got called. In the context of Control.BeginInvoke and Control.Invoke, that does not happen.

After the asynchronous call finishes, the reference to the object[] is released so it can be collected, but if any of its members implement IDisposable, the IDisposable.Dispose method is not called. The object's resources will not be released until it is collected (or someone else disposes it).

ContentLicense: CC BY-SA 3.0

Body:
I have done a lot of reading about Control.Invoke and Control.BeginInvoke and understand that Invoke is like SendMessage() and BeginInvoke is like PostMessage(), but I do not understand where the parameter list passed via new object[] { arg, arg, arg, ...} is stored. During a conventional call, parameters are pushed to the stack and popped within the called function, then the call frame is recovered from the stack after exit, I assume releasing any references to any heap objects, allowing them to be collected. So, where is the pushed stack date for Invoke/BeginInvoke stored? How does it get disposed once the method called exits?

Also, I have successfully invoked a control method without loading a new object array with the pass parameters. Why would this work? Better yet, since it does work, why would all the examples I have ever seen show it with a new object array?

This is what I have always seen and used:

BeginInvoke(FormReceiveEvent, new object[] { Event, Arg1, Arg2, Arg3 });

But this works too:

BeginInvoke(FormReceiveEvent, Event, Arg1, Arg2, Arg3);

Any information and comments are always appreciated...

Thanks in advance.


问:
Error: Provider configuration not present
Im trying to update terraform version from 0.12 to 0.13. While updating the terraform I came across on an issue during plan

```<code>Error: Provider configuration not present

To work with
aws_sns_topic_subscription.sns_s3_raw_parquet_sqs_user_cleansing_monet_service_subscription
its original provider configuration at provider["registry.terraform.io/-/aws"]
is required, but it has been removed. This occurs when a provider
configuration is removed while objects created by that provider still exist in
the state. Re-add the provider configuration to destroy
aws_sns_topic_subscription.sns_s3_raw_parquet_sqs_user_cleansing_monet_service_subscription,
after which you can remove the provider configuration again.
</code>```

Could someone please help?

答:
Most likely you have not proceeded with the migration to Terraform v.013 fully.

Make a backup of your current state with terraform state pull then try to execute the following:

```<code>terraform state replace-provider 'registry.terraform.io/-/aws' 'registry.terraform.io/hashicorp/aws'
</code>```

This should amend your state to the newer Terraform version.

Body:
Im trying to update terraform version from 0.12 to 0.13. While updating the terraform I came across on an issue during plan

Error: Provider configuration not present

To work with
aws_sns_topic_subscription.sns_s3_raw_parquet_sqs_user_cleansing_monet_service_subscription
its original provider configuration at provider["registry.terraform.io/-/aws"]
is required, but it has been removed. This occurs when a provider
configuration is removed while objects created by that provider still exist in
the state. Re-add the provider configuration to destroy
aws_sns_topic_subscription.sns_s3_raw_parquet_sqs_user_cleansing_monet_service_subscription,
after which you can remove the provider configuration again.

Could someone please help?

Body:
Most likely you have not proceeded with the migration to Terraform v.013 fully.

Make a backup of your current state with terraform state pull then try to execute the following:

terraform state replace-provider 'registry.terraform.io/-/aws' 'registry.terraform.io/hashicorp/aws'

This should amend your state to the newer Terraform version.


问:
Fancybox 3 - prevent moblie view swipe up or click overlay area close
I am trying to make a fancybox only can close by close button. I have looked the fancyBox3 documentation but still no idea. The fancybox default setting only can prevent mouse click outside close and mouse touch close. Even the touch setting set to false, swipe up or click overlay area close problem still happen on mobile view.

I have a sample script to show the fancybox.

HTML

```<code><div id="fancybox" style="display:none;">
  <img src="https://farm6.staticflickr.com/5519/9432166677_61aa7e7f90_m_d.jpg">
</div>
</code>```

JS

```<code>$(document).ready(function() {
    $.fancybox.open({
    src: "#fancybox",
    type: "inline",
    clickSlide : 'false',
    clickOutside : 'false',
    touch: false
  });
});
</code>```

JSFIDDLE

Any idea to prevent mobile swipe up close? Thanks!

答:
I had this problem, you need add options for mobile devices

    $.fancybox.open({
        src: '#order-popup-desktop',
        type: 'inline',
        mobile: {
            clickSlide: false,
            touch: false
        },
    });```

This code 100% work for fancy v.3.5.7

Body:
I am trying to make a fancybox only can close by close button. I have looked the fancyBox3 documentation but still no idea. The fancybox default setting only can prevent mouse click outside close and mouse touch close. Even the touch setting set to false, swipe up or click overlay area close problem still happen on mobile view.

I have a sample script to show the fancybox.

HTML

JS

$(document).ready(function() {
    $.fancybox.open({
    src: "#fancybox",
    type: "inline",
    clickSlide : 'false',
    clickOutside : 'false',
    touch: false
  });
});

JSFIDDLE

Any idea to prevent mobile swipe up close? Thanks!

Body:
I had this problem, you need add options for mobile devices

    $.fancybox.open({
        src: '#order-popup-desktop',
        type: 'inline',
        mobile: {
            clickSlide: false,
            touch: false
        },
    });

This code 100% work for fancy v.3.5.7


问:
How do you prevent a user from taking down your application by holding down the refresh key?
I had a recent outage on a Nginx/Rails application server. It turned out we were being bombarded by requests to a particular URL that takes a few seconds to load. It appears that a user was continually refreshing that page for a number of minutes - my guess is they accidentally put some object on their keyboard in such a way as to trigger a constant stream of browser refreshes.

Regardless of the cause, I need to put protection in place against this kind of problem, and note that this is not static content - it's dynamic, user-specific content sitting behind authentication.

I've looked into using Cache-Control but this appears to be a non-starter - on Chrome at least, refreshing a page within the same tab will trigger a request regardless of the Cache-Control header (cf iis - Is Chrome ignoring Cache-Control: max-age? - Stack Overflow)

I believe the answer may be rate limiting. If so, I wouldn't be able to do it based on IP because many of our customers share the same one. However I may be able to add a new header to identify a user and then apply rate limiting in Nginx based on this.

Does this sound like the way forward? This feels like it should be a fairly common problem!

答:
A colleague of mine suggested a solution that I think is the best fit for our situation. I'll explain why in case this proves useful to anyone else.

Note that we were receiving requests at a low rate - just 6 per second. The reason this was a problem was that the page in question was quite a slow loading report, only accessible to authenticated users.

Server-side caching is not a great solution for us because it needs to be implemented individually on each affected page and we have a complex app with lots of different controllers.

Rate-limiting via Nginx might be viable but tricky to optimise and also has issues with testability.

Anyway, my colleague's solution is as follows: we already have a table that logs details of each request, including the ID of the user that made it. To find out if a user is refreshing too often, we simply schedule a Sidekiq job once every, say, 30 seconds to check this table for users with a refresh rate above our threshold and then kill any active sessions.

How you kill a session depends how you are managing them - in our case, we could simply add a flag to the user that says "rate_limited" and have our Sidekiq job set it to true, and then check the value of this flag on each request. If it's true, the user will be redirected away from the slow page and on to the login screen which will happily deal with refreshing itself 6 times per second.

You could achieve something similar even without a request logging table, e.g. by keeping track of the request rate in a new column on the users table.

Note that this solution is a better UX than Nginx rate-limiting, as users are never actually locked out of the app.


问:
I wanted to remove particular pattern from a string in tcl
hreset_error_status_t2_reg1
htrans_flag_t1_reg2
hsize_flag_error_reg
check_hwdata_reg

I had to write a Tcl script using regex I have to remove error_status, flag, flag_error, and check in the following strings. It has to search the following keywords in the file and have to remove the mentioned keywords in a string.

答:
To remove all those patterns from a string, use regsub -all.   If you don't need to use the power of regular expressions, then string map works well too.

```<code>set my_str "hreset_error_status_t2_reg1 htrans_flag_t1_reg2 hsize_flag_error_reg check_hwdata_reg"
set my_regex {error_status_|flag_(error_)?|check_}
regsub -all $my_regex $my_str ""
  --> hreset_t2_reg1 htrans_t1_reg2 hsize_reg hwdata_reg
</code>```

or

```<code>set my_map {
   error_status_  ""
   flag_error_    ""
   flag_          ""
   check_         ""
}
string map $my_map $my_str
   --> hreset_t2_reg1 htrans_t1_reg2 hsize_reg hwdata_reg
</code>```

Note that I put flag_error_ before flag_ in $my_map so that only the flag_ characters in flag_error weren't removed.

Body:
To remove all those patterns from a string, use regsub -all.   If you don't need to use the power of regular expressions, then string map works well too.

set my_str "hreset_error_status_t2_reg1 htrans_flag_t1_reg2 hsize_flag_error_reg check_hwdata_reg"
set my_regex {error_status_|flag_(error_)?|check_}
regsub -all $my_regex $my_str ""
  --> hreset_t2_reg1 htrans_t1_reg2 hsize_reg hwdata_reg

or

set my_map {
   error_status_  ""
   flag_error_    ""
   flag_          ""
   check_         ""
}
string map $my_map $my_str
   --> hreset_t2_reg1 htrans_t1_reg2 hsize_reg hwdata_reg

Note that I put flag_error_ before flag_ in $my_map so that only the flag_ characters in flag_error weren't removed.


问:
Can you delete multiple branches in one command with Git?
I'd like to clean up my local repository, which has a ton of old branches: for example 3.2, 3.2.1, 3.2.2, etc.

I was hoping for a sneaky way to remove a lot of them at once. Since they mostly follow a dot release convention, I thought maybe there was a shortcut to say:

```<code>git branch -D 3.2.*
</code>```

and kill all 3.2.x branches.

I tried that command and it, of course, didn't work.

答:
My specific case was not addressed, so I'm making a new answer...

Scenario:

Freshly cloned repo

No local branches created

Many remote branches (over 100 in my case)

I want to delete all the feature branches, feature/myfeature , from the remote

This is the command that I got to work:

```<code>git branch  -a | cut -c3- | grep 'origin\/feature' | sed 's/remotes\/origin\///' | xargs git push origin --delete
</code>```

Thanks to @gwai for putting me on the right track.

Body:
I'd like to clean up my local repository, which has a ton of old branches: for example 3.2, 3.2.1, 3.2.2, etc.

I was hoping for a sneaky way to remove a lot of them at once. Since they mostly follow a dot release convention, I thought maybe there was a shortcut to say:

git branch -D 3.2.*

and kill all 3.2.x branches.

I tried that command and it, of course, didn't work.

Body:
My specific case was not addressed, so I'm making a new answer...

Scenario:

Freshly cloned repo

No local branches created

Many remote branches (over 100 in my case)

I want to delete all the feature branches, feature/myfeature , from the remote

This is the command that I got to work:

git branch  -a | cut -c3- | grep 'origin\/feature' | sed 's/remotes\/origin\///' | xargs git push origin --delete

Thanks to @gwai for putting me on the right track.


问:
Why can't I reassign variables in this function?
Here is the question:

You will be given an array of numbers. You have to sort the odd numbers in ascending order while leaving the even numbers at their original positions.

Here is my code:

```<code>def sort_array(source_array):
    odd_ints = []

    for i in source_array:
        if i % 2 == 1:
            odd_ints.append(i)
            odd_ints.sort()
        else:
            pass
    counter = 0
    for x in source_array:
        if x % 2 == 1:
            x = odd_ints[counter]
            counter += 1
            print(source_array)
        else:
            pass

    return source_array
</code>```

When I test it, it does this:

```<code>>>> sort_array([5, 3, 2, 8, 1, 4])
[5, 3, 2, 8, 1, 4]
[5, 3, 2, 8, 1, 4]
[5, 3, 2, 8, 1, 4]

[5, 3, 2, 8, 1, 4]
</code>```

For some reason, I can't re-assign the variable x in the function to odd_ints in ascending order. Would anyone know the problem in my code?

答:
You can do this:

Separate the odds with indexes into a dict;

Sort the odds and reset the indexes into odd slots;

Insert those odds into the original list.

Example:

```<code>def sort_the_odds(li):
    odds={idx:n for idx,n in enumerate(li) if n%2}

    for idx,val in zip([t[0] for t in sorted(odds.items())],
            [t[1] for t in sorted(odds.items(), key=lambda t: t[1])]):
        li[idx]=val

    return li

>>> sort_the_odds([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])
[10, 1, 8, 3, 6, 5, 4, 7, 2, 9]

>>> sort_the_odds([5, 3, 2, 8, 1, 4])
[1, 3, 2, 8, 5, 4]
</code>```

Body:
Here is the question:

You will be given an array of numbers. You have to sort the odd numbers in ascending order while leaving the even numbers at their original positions.

Here is my code:

def sort_array(source_array):
    odd_ints = []

    for i in source_array:
        if i % 2 == 1:
            odd_ints.append(i)
            odd_ints.sort()
        else:
            pass
    counter = 0
    for x in source_array:
        if x % 2 == 1:
            x = odd_ints[counter]
            counter += 1
            print(source_array)
        else:
            pass

    return source_array

When I test it, it does this:

>>> sort_array([5, 3, 2, 8, 1, 4])
[5, 3, 2, 8, 1, 4]
[5, 3, 2, 8, 1, 4]
[5, 3, 2, 8, 1, 4]

[5, 3, 2, 8, 1, 4]

For some reason, I can't re-assign the variable x in the function to odd_ints in ascending order. Would anyone know the problem in my code?

Body:
You can do this:

Separate the odds with indexes into a dict;

Sort the odds and reset the indexes into odd slots;

Insert those odds into the original list.

Example:

def sort_the_odds(li):
    odds={idx:n for idx,n in enumerate(li) if n%2}

    for idx,val in zip([t[0] for t in sorted(odds.items())],
            [t[1] for t in sorted(odds.items(), key=lambda t: t[1])]):
        li[idx]=val

    return li

>>> sort_the_odds([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])
[10, 1, 8, 3, 6, 5, 4, 7, 2, 9]

>>> sort_the_odds([5, 3, 2, 8, 1, 4])
[1, 3, 2, 8, 5, 4]


问:
Running ray serve in a docker container in foreground, not daemon mode
I'm running Ray Serve to host a HTTP API of a ray remote function. Is there a better way than below to run Ray Serve in foreground (i.e not daemon mode). Code is taken pretty straight from ray serve example:

import os
import time

import ray.serve

ray.serve.init(blocking=True, http_host="0.0.0.0", ray_init_kwargs={
    'webui_host': '0.0.0.0',
    'redis_password': os.getenv('RAY_REDIS_PASSWORD'),
})

ray.serve.create_endpoint("my_endpoint", "/echo")

def echo_v1(flask_request, response="hello from python!"):
    return "1"

ray.serve.create_backend(echo_v1, "echo:v1")

ray.serve.link("my_endpoint", "echo:v1")

# Make sure the Docker container doesn't exit
while True:
    time.sleep(2)
```

<p>Without the last part:</p>

<pre class="lang-py prettyprint-override"><code># Make sure the Docker container doesn't exit
while True:
    time.sleep(2)
</code>```

The Docker container will immediately exit.

答:
From the ray documentation as well (https://docs.ray.io/en/latest/serve/deployment.html), you can start a server beforehand with ray start --head and connect to the server with ray.init(address="auto"):

ray start --head
```
<pre class="lang-py prettyprint-override"><code>import ray
from ray import serve

# This will connect to the running Ray cluster.
ray.init(address="auto", namespace="serve")

@serve.deployment
def my_func(request):
  return "hello"

my_func.deploy()
</code>```

Body:
I'm running Ray Serve to host a HTTP API of a ray remote function. Is there a better way than below to run Ray Serve in foreground (i.e not daemon mode). Code is taken pretty straight from ray serve example:

import os
import time

import ray.serve

ray.serve.init(blocking=True, http_host="0.0.0.0", ray_init_kwargs={
    'webui_host': '0.0.0.0',
    'redis_password': os.getenv('RAY_REDIS_PASSWORD'),
})

ray.serve.create_endpoint("my_endpoint", "/echo")

def echo_v1(flask_request, response="hello from python!"):
    return "1"

ray.serve.create_backend(echo_v1, "echo:v1")

ray.serve.link("my_endpoint", "echo:v1")

# Make sure the Docker container doesn't exit
while True:
    time.sleep(2)

Without the last part:

# Make sure the Docker container doesn't exit
while True:
    time.sleep(2)

The Docker container will immediately exit.

Body:
From the ray documentation as well (https://docs.ray.io/en/latest/serve/deployment.html), you can start a server beforehand with ray start --head and connect to the server with ray.init(address="auto"):

ray start --head

import ray
from ray import serve

# This will connect to the running Ray cluster.
ray.init(address="auto", namespace="serve")

@serve.deployment
def my_func(request):
  return "hello"

my_func.deploy()


问:
Exchangelib read emails from a service account without personal login
I would like to read the inbox of a shared service account. The service account inbox is a shared inbox and does not have a password per-se. I can log in and read my personal inbox using this:

```<code>from exchangelib import DELEGATE, Account, Credentials
import pytz
from datetime import datetime, date, time
now = datetime.now() # current date and time
timestr = now.strftime("%m-%d-%Y, %H.%M.%S")

credentials = Credentials(
    username='me@company.org',
    password='Password1'
)
a = Account(
    primary_smtp_address='me@company.org',
    credentials=credentials,
    autodiscover=True,
    access_type=DELEGATE
)
print('im in')
key = 'Filter Word'
midnight = datetime.combine(datetime.today(), time.min, pytz.UTC)
for item in a.inbox.filter(datetime_received__gte=midnight, subject__icontains=key).order_by('-datetime_received')[
            :30]:
    print(item.subject)
</code>```

I think the answer to my question lies somewhere in the credentials portion. I have been able to read the shared inbox by using my personal credentials and inputting the inbox address in the primary_smtp_address field. Like this:

```<code>    credentials = Credentials(
    username='me@company.org',
    password='Password1'
)
a = Account(
    primary_smtp_address='sharedinbox@company.org',
    credentials=credentials,
    autodiscover=True,
    access_type=DELEGATE
)
</code>```

This works great, however, if (for some reason) my credentials no longer become valid at the company, I would like the script to still run. Is there a way to do this?

答:
If you don't want to access the shared account using a personal account, you should create a service account in Exchange and use that to login instead.

You cannot access the shared account without some sort of authentication.

Body:
I would like to read the inbox of a shared service account. The service account inbox is a shared inbox and does not have a password per-se. I can log in and read my personal inbox using this:

from exchangelib import DELEGATE, Account, Credentials
import pytz
from datetime import datetime, date, time
now = datetime.now() # current date and time
timestr = now.strftime("%m-%d-%Y, %H.%M.%S")

credentials = Credentials(
    username='me@company.org',
    password='Password1'
)
a = Account(
    primary_smtp_address='me@company.org',
    credentials=credentials,
    autodiscover=True,
    access_type=DELEGATE
)
print('im in')
key = 'Filter Word'
midnight = datetime.combine(datetime.today(), time.min, pytz.UTC)
for item in a.inbox.filter(datetime_received__gte=midnight, subject__icontains=key).order_by('-datetime_received')[
            :30]:
    print(item.subject)

I think the answer to my question lies somewhere in the credentials portion. I have been able to read the shared inbox by using my personal credentials and inputting the inbox address in the primary_smtp_address field. Like this:

    credentials = Credentials(
    username='me@company.org',
    password='Password1'
)
a = Account(
    primary_smtp_address='sharedinbox@company.org',
    credentials=credentials,
    autodiscover=True,
    access_type=DELEGATE
)

This works great, however, if (for some reason) my credentials no longer become valid at the company, I would like the script to still run. Is there a way to do this?


问:
How to automatically change label color depending on relative values (maximum/minimum)?
In order to make a dynamic visualization, for example in a dashboard, I want to display the label colors (percentages or totals) depending on their real values in black or white.

As you can see from my reprex below, I changed the color of the label with the highest percentage manually to black, in order gain a better visability.

Is there a was, to automatically implement the label color? The label with the highest percentage corresponding should always be black, if data is changing over time.

```<code>library(ggplot2)
library(dplyr)

set.seed(3)
reviews <- data.frame(review_star = as.character(sample.int(5,400, replace = TRUE)),
                      stars = 1)

df <- reviews %>%
  group_by(review_star) %>%
  count() %>%
  ungroup() %>%
  mutate(perc = `n` / sum(`n`)) %>%
  arrange(perc) %>%
  mutate(labels = scales::percent(perc))

ggplot(df, aes(x = "", y = perc, fill = review_star)) +
  geom_col(color = "black") +
  geom_label(aes(label = labels), color = c( "white", "white","white",1,"white"),
             position = position_stack(vjust = 0.5),
             show.legend = FALSE) +
  guides(fill = guide_legend(title = "Answer")) +
  scale_fill_viridis_d() +
  coord_polar(theta = "y") +
  theme_void()
</code>```

答:
you can set the colors using replace(rep('white', nrow(df)), which.max(df$perc), 'black').

```<code>ggplot(df, aes(x = "", y = perc, fill = review_star)) +
  geom_col(color = "black") +
  geom_label(aes(label = labels),
             color = replace(rep('white', nrow(df)), which.max(df$perc), 'black'),
             position = position_stack(vjust = 0.5),
             show.legend = FALSE) +
  guides(fill = guide_legend(title = "Answer")) +
  scale_fill_viridis_d() +
  coord_polar(theta = "y") +
  theme_void()
</code>```

Body:
In order to make a dynamic visualization, for example in a dashboard, I want to display the label colors (percentages or totals) depending on their real values in black or white.

As you can see from my reprex below, I changed the color of the label with the highest percentage manually to black, in order gain a better visability.

Is there a was, to automatically implement the label color? The label with the highest percentage corresponding should always be black, if data is changing over time.

library(ggplot2)
library(dplyr)

set.seed(3)
reviews <- data.frame(review_star = as.character(sample.int(5,400, replace = TRUE)),
                      stars = 1)

df <- reviews %>%
  group_by(review_star) %>%
  count() %>%
  ungroup() %>%
  mutate(perc = `n` / sum(`n`)) %>%
  arrange(perc) %>%
  mutate(labels = scales::percent(perc))

ggplot(df, aes(x = "", y = perc, fill = review_star)) +
  geom_col(color = "black") +
  geom_label(aes(label = labels), color = c( "white", "white","white",1,"white"),
             position = position_stack(vjust = 0.5),
             show.legend = FALSE) +
  guides(fill = guide_legend(title = "Answer")) +
  scale_fill_viridis_d() +
  coord_polar(theta = "y") +
  theme_void()

Body:
you can set the colors using replace(rep('white', nrow(df)), which.max(df$perc), 'black').

ggplot(df, aes(x = "", y = perc, fill = review_star)) +
  geom_col(color = "black") +
  geom_label(aes(label = labels),
             color = replace(rep('white', nrow(df)), which.max(df$perc), 'black'),
             position = position_stack(vjust = 0.5),
             show.legend = FALSE) +
  guides(fill = guide_legend(title = "Answer")) +
  scale_fill_viridis_d() +
  coord_polar(theta = "y") +
  theme_void()


问:
How to parse JSON in Java
I have the following JSON text. How can I parse it to get the values of pageName, pagePic, post_id, etc.?

{
  "pageInfo": {
    "pageName": "abc",
    "pagePic": "http://example.com/content.jpg"
  },
  "posts": [
    {
      "post_id": "123456789012_123456789012",
      "actor_id": "1234567890",
      "picOfPersonWhoPosted": "http://example.com/photo.jpg",
      "nameOfPersonWhoPosted": "Jane Doe",
      "message": "Sounds cool. Can't wait to see it!",
      "likesCount": "2",
      "comments": [],
      "timeOfPost": "1234567890"
    }
  ]
}
```

答:
If your data is simple and you don't want external dependencies, use some lines of code:

```<code>/**
 * A very simple JSON parser for one level, everything quoted.
 * @param json the json content.
 * @return a key => value map.
 */
public static Map<String, String> simpleParseJson(String json) {
    Map<String, String> map = new TreeMap<>();
    String qs[] = json.replace("\\\"", "\u0001").replace("\\\\", "\\").split("\"");
    for (int i = 1; i + 3 < qs.length; i += 4) {
        map.put(qs[i].replace('\u0001', '"'), qs[i + 2].replace('\u0001', '"'));
    }
    return map;
}
</code>```

So this data

```<code>{"name":"John", "age":"30", "car":"a \"quoted\" back\\slash car"}
</code>```

yields a map containing

```<code>{age=30, car=a "quoted" back\slash car, name=John}
</code>```

This can be upgraded to work with unquoted values too...

```<code>/**
 * A very simple JSON parser for one level, names are quoted.
 * @param json the json content.
 * @return a key => value map.
 */
public static Map<String, String> simpleParseJson(String json) {
    Map<String, String> map = new TreeMap<>();
    String qs[] = json.replace("\\\"", "\u0001").replace("\\\\",  "\\").split("\"");
    for (int i = 1; i + 1 < qs.length; i += 4) {
        if (qs[i + 1].trim().length() > 1) {
            String x = qs[i + 1].trim();
            map.put(qs[i].replace('\u0001', '"'), x.substring(1, x.length() - 1).trim().replace('\u0001', '"'));
            i -= 2;
        } else {
            map.put(qs[i].replace('\u0001', '"'), qs[i + 2].replace('\u0001', '"'));
        }
    }
    return map;
}
</code>```

And to solve complex structure, it gets ugly...
... SORRY!!! ... but I could not resist to code it^^
This parses the given JSON in question and way more. It yields nested maps and lists.

```<code>/**
 * A very simple JSON parser, names are quoted.
 *
 * @param json the json content.
 * @return a key => value map.
 */
public static Map<String, Object> simpleParseJson(String json) {
    Map<String, Object> map = new TreeMap<>();
    String qs[] = json.replace("\\\"", "\u0001").replace("\\\\", "\\").split("\"");
    int index[] = { 1 };
    recurse(index, map, qs);
    return map;
}

/**
 * Eierlegende Wollmilchsau.
 *
 * @param index index into array.
 * @param map   the current map to fill.
 * @param qs    the data.
 */
private static void recurse(int[] index, Map<String, Object> map, String[] qs) {
    int i = index[0];
    for (;; i += 4) {
        String end = qs[i - 1].trim(); // check for termination of an object
        if (end.startsWith("}")) {
            qs[i - 1] = end.substring(1).trim();
            i -= 4;
            break;
        }

        String key = qs[i].replace('\u0001', '"');
        String x = qs[i + 1].trim();
        if (x.endsWith("{")) {
            x = x.substring(0, x.length() - 1).trim();
            if (x.endsWith("[")) {
                List<Object> list = new ArrayList<>();
                index[0] = i + 2;
                for (;;) {
                    Map<String, Object> inner = new TreeMap<>();
                    list.add(inner);
                    recurse(index, inner, qs);
                    map.put(key, list);
                    i = index[0];

                    String y = qs[i + 3]; // check for termination of array
                    if (y.startsWith("]")) {
                        qs[i + 3] = y.substring(1).trim();
                        break;
                    }
                }
                continue;
            }

            Map<String, Object> inner = new TreeMap<>();
            index[0] = i + 2;
            recurse(index, inner, qs);
            map.put(key, inner);
            i = index[0];
            continue;
        }
        if (x.length() > 1) { // unquoted
            String value = x.substring(1, x.length() - 1).trim().replace('\u0001', '"');
            if ("[]".equals(value)) // handle empty array
                map.put(key, new ArrayList<>());
            else
                map.put(key, value);
            i -= 2;
        } else {
            map.put(key, qs[i + 2].replace('\u0001', '"'));
        }
    }
    index[0] = i;
}
</code>```

yields - if you print the map:

```<code>{pageInfo={pageName=abc, pagePic=http://example.com/content.jpg}, posts=[{actor_id=1234567890, comments=[], likesCount=2, message=Sounds cool. Can't wait to see it!, nameOfPersonWhoPosted=Jane Doe, picOfPersonWhoPosted=http://example.com/photo.jpg, post_id=123456789012_123456789012, timeOfPost=1234567890}]}
</code>```

Title: How to parse JSON in Java

Body:
If your data is simple and you don't want external dependencies, use some lines of code:

/**
 * A very simple JSON parser for one level, everything quoted.
 * @param json the json content.
 * @return a key => value map.
 */
public static Map<String, String> simpleParseJson(String json) {
    Map<String, String> map = new TreeMap<>();
    String qs[] = json.replace("\\\"", "\u0001").replace("\\\\", "\\").split("\"");
    for (int i = 1; i + 3 < qs.length; i += 4) {
        map.put(qs[i].replace('\u0001', '"'), qs[i + 2].replace('\u0001', '"'));
    }
    return map;
}

So this data

{"name":"John", "age":"30", "car":"a \"quoted\" back\\slash car"}

yields a map containing

{age=30, car=a "quoted" back\slash car, name=John}

This can be upgraded to work with unquoted values too...

/**
 * A very simple JSON parser for one level, names are quoted.
 * @param json the json content.
 * @return a key => value map.
 */
public static Map<String, String> simpleParseJson(String json) {
    Map<String, String> map = new TreeMap<>();
    String qs[] = json.replace("\\\"", "\u0001").replace("\\\\",  "\\").split("\"");
    for (int i = 1; i + 1 < qs.length; i += 4) {
        if (qs[i + 1].trim().length() > 1) {
            String x = qs[i + 1].trim();
            map.put(qs[i].replace('\u0001', '"'), x.substring(1, x.length() - 1).trim().replace('\u0001', '"'));
            i -= 2;
        } else {
            map.put(qs[i].replace('\u0001', '"'), qs[i + 2].replace('\u0001', '"'));
        }
    }
    return map;
}

And to solve complex structure, it gets ugly...
... SORRY!!! ... but I could not resist to code it^^
This parses the given JSON in question and way more. It yields nested maps and lists.

/**
 * A very simple JSON parser, names are quoted.
 *
 * @param json the json content.
 * @return a key => value map.
 */
public static Map<String, Object> simpleParseJson(String json) {
    Map<String, Object> map = new TreeMap<>();
    String qs[] = json.replace("\\\"", "\u0001").replace("\\\\", "\\").split("\"");
    int index[] = { 1 };
    recurse(index, map, qs);
    return map;
}

/**
 * Eierlegende Wollmilchsau.
 *
 * @param index index into array.
 * @param map   the current map to fill.
 * @param qs    the data.
 */
private static void recurse(int[] index, Map<String, Object> map, String[] qs) {
    int i = index[0];
    for (;; i += 4) {
        String end = qs[i - 1].trim(); // check for termination of an object
        if (end.startsWith("}")) {
            qs[i - 1] = end.substring(1).trim();
            i -= 4;
            break;
        }

        String key = qs[i].replace('\u0001', '"');
        String x = qs[i + 1].trim();
        if (x.endsWith("{")) {
            x = x.substring(0, x.length() - 1).trim();
            if (x.endsWith("[")) {
                List<Object> list = new ArrayList<>();
                index[0] = i + 2;
                for (;;) {
                    Map<String, Object> inner = new TreeMap<>();
                    list.add(inner);
                    recurse(index, inner, qs);
                    map.put(key, list);
                    i = index[0];

                    String y = qs[i + 3]; // check for termination of array
                    if (y.startsWith("]")) {
                        qs[i + 3] = y.substring(1).trim();
                        break;
                    }
                }
                continue;
            }

            Map<String, Object> inner = new TreeMap<>();
            index[0] = i + 2;
            recurse(index, inner, qs);
            map.put(key, inner);
            i = index[0];
            continue;
        }
        if (x.length() > 1) { // unquoted
            String value = x.substring(1, x.length() - 1).trim().replace('\u0001', '"');
            if ("[]".equals(value)) // handle empty array
                map.put(key, new ArrayList<>());
            else
                map.put(key, value);
            i -= 2;
        } else {
            map.put(key, qs[i + 2].replace('\u0001', '"'));
        }
    }
    index[0] = i;
}

yields - if you print the map:

{pageInfo={pageName=abc, pagePic=http://example.com/content.jpg}, posts=[{actor_id=1234567890, comments=[], likesCount=2, message=Sounds cool. Can't wait to see it!, nameOfPersonWhoPosted=Jane Doe, picOfPersonWhoPosted=http://example.com/photo.jpg, post_id=123456789012_123456789012, timeOfPost=1234567890}]}


问:
GENEXUS Instalation Erro Android SDK "Android SDK for Genexus Setup error"
I have error with Android SDK Installation for Genexus.

I have install all platforms and componentes of Genexus (NodJs, Visual Studio, SQL Server, Apache, Maven, Framework SDK, Java, etc.) also i download file "commandlinetools-win-6609375_latest.zip" on browser and the download was successfully. This file i was rename to "AndroidSDK.zip" and do not resolve problem

This problem is apparear with executable "androidsdk17.exe" and present this error message:

Android SDK for Genexus Setup error

Unable to download file:
https://dl.google.com/android/repository/commandlinetools-win-6609375_latest.zip

into
C:\Users\Administrador\AppData\Local\Temp\ART\AndroidSDK.zip
Please verify your Internet connection.

答:
The cause of the error is that the wizard for some reason cannot access the internet to download the file. Probably due to some security problem, proxies or something like that.

I think the best way to install Android requirements is by downloading "Android Studio" on your local machine, it would install all the requirements for you.

Another way is downloading manually the URL of the error.


问:
Python Outlook how to handle recall email
My project works on emails in Inbox. When process get a "Recall" email it crashes. Recall email does not have subject attribute. I want to write some error handling. I cannot find method to move email to another folder or delete such email from Outlook.

Currently my Code skip such items using method GetPrevious() but the email is still in Inbox
Do you have any ideas how to make 'recall' email disappear from Inbox folder?

```<code>    obj_emails = obj_inbox.Items
    obj_email = obj_emails.GetLast()

    if obj_email.MessageClass == 'IPM.Outlook.Recall':
        obj_email = obj_emails.GetPrevious()
</code>```

答:
The Outlook object model doesn't provide anything for handling or generating recall items. You may consider using a low-level API on which Outlook is based on - Extended MAPI. Also you may consider using thied-party components, i.e. wrappers around the low-level API such as Redemption.

Try to play with MFCMAPI to make sure recall items can be easily handled (moved or removed).

Body:
My project works on emails in Inbox. When process get a "Recall" email it crashes. Recall email does not have subject attribute. I want to write some error handling. I cannot find method to move email to another folder or delete such email from Outlook.

Currently my Code skip such items using method GetPrevious() but the email is still in Inbox
Do you have any ideas how to make 'recall' email disappear from Inbox folder?

    obj_emails = obj_inbox.Items
    obj_email = obj_emails.GetLast()

    if obj_email.MessageClass == 'IPM.Outlook.Recall':
        obj_email = obj_emails.GetPrevious()


问:
Scatterplot looks strange
my scatterplot that shows the relationship between my principal component and one of my questionnaire items looks strange.
The scatterplot between two of my principal components looks great (see second image).

The item is measured on a Likert scale from 1 to 5 (1 = strongly disagree, 5 = strongly agree). The histogram of this item also has many gaps between the bars, which is strange to me too.

Please let me know which specific output you still need to figure this out.

Thanks

答:
For reproducibility, it is best if you provide a piece of the database you are using to make these scatterplots. It would also be great if you include the axes titles inside the graph.

To be honest, I dont see anything wrong with the first figure. Variable y (the questionare item) is a discrete variable between 1 and 5. It make sense that one result from the PC1 is match with more than one of the values of the item questionare.

Title: Scatterplot looks strange


问:
How to add a second group legend in ggplot (R)?
As you can see from the graph below, ggplot automatically change the graphs color based on a second group division (literally group2).
Now, what I am not able to do is to print a legend for it. I would like under gender with their respective color to be added group2 legend with their respective color or maybe just to manually label them as such.

```<code>set.seed(34)
data <- data.frame(gender = rep(c("female", "male"), length.out=10),
    group2 = sample(letters[1:2], 10, replace = T),
    group = rep(letters[11:13], length.out=10),
    nums = as.integer(runif(10, min=10, max=500)))

xc <- data %>%
    group_by(group) %>%
    mutate(sum=sum(nums)) %>%
    group_by(gender, group2, group) %>%
    mutate(prop = nums/sum*100)

ggplot(xc, aes(x=group, fill = gender, color = group2, y = prop)) +
    geom_col(position="dodge", color = "white", alpha = 0.85) +
    scale_fill_manual(values = c("#466760","#845574")) +
    theme_minimal() +
    theme() +
    ggtitle("") +
    xlab("") +
    ylab("Percentage %")

</code>```

My plot:

答:
Hard to tell what you are trying to achieve, maybe this approach could be useful:

library(dplyr)
library(ggplot2)

ggplot(xc, aes(x = gender, y = prop, fill = group2)) +
  geom_col(position = position_dodge2(preserve = "single", padding = 0.01), alpha = 0.85) +
  scale_fill_manual(values = c("#466760", "#845574")) +
  facet_wrap(~group, nrow = 1)+
  theme_bw() +
  theme(panel.border = element_blank()) +
  ggtitle("") +
  xlab("") +
  ylab("Percentage %")
```

Created on 2022-02-07 by the reprex package (v2.0.1)

Body:
As you can see from the graph below, ggplot automatically change the graphs color based on a second group division (literally group2).
Now, what I am not able to do is to print a legend for it. I would like under gender with their respective color to be added group2 legend with their respective color or maybe just to manually label them as such.

set.seed(34)
data <- data.frame(gender = rep(c("female", "male"), length.out=10),
    group2 = sample(letters[1:2], 10, replace = T),
    group = rep(letters[11:13], length.out=10),
    nums = as.integer(runif(10, min=10, max=500)))

xc <- data %>%
    group_by(group) %>%
    mutate(sum=sum(nums)) %>%
    group_by(gender, group2, group) %>%
    mutate(prop = nums/sum*100)

ggplot(xc, aes(x=group, fill = gender, color = group2, y = prop)) +
    geom_col(position="dodge", color = "white", alpha = 0.85) +
    scale_fill_manual(values = c("#466760","#845574")) +
    theme_minimal() +
    theme() +
    ggtitle("") +
    xlab("") +
    ylab("Percentage %")

My plot:

Body:
Hard to tell what you are trying to achieve, maybe this approach could be useful:

library(dplyr)
library(ggplot2)

ggplot(xc, aes(x = gender, y = prop, fill = group2)) +
  geom_col(position = position_dodge2(preserve = "single", padding = 0.01), alpha = 0.85) +
  scale_fill_manual(values = c("#466760", "#845574")) +
  facet_wrap(~group, nrow = 1)+
  theme_bw() +
  theme(panel.border = element_blank()) +
  ggtitle("") +
  xlab("") +
  ylab("Percentage %")

Created on 2022-02-07 by the reprex package (v2.0.1)


问:
Business hours in different timezones
I am trying to display a users business hours in one timezone to another timezone.

A users business hours is stored as below object for each day of the week

```<code>Timezone = Asia/Kolakata
Day number = 3 (Wednesday)
Hour = 7:00 (12 hour system)
</code>```

the above is in IST

But now if i need to reteive this for a user in Australia, I can change the timezone and get the value. But this would be incorrect as a business hour available on Monday in one timezone might be valid for Tuesday in another. What is the best way to deal with this conversion?

The objects are being store and retrieved from Firestore.

Any help/guidance would be appreciated

thanks

答:
If you want to be able to query the business hours across all time zones in one go, you will have to store the hours in a single, normalized time zone (typically UTC) for all business.

So you'll Hour (and possibly Day number) field are the in UTC, and you'd use the Timezone field to indicate what timezone the store is in.

Then to query for the Australian user, you convert their local time zone to UTC too, and can query across all documents.

So in this approach, all times stored in the database are normalized, and you use a time zone only when converting the entered data to the database format, or when displaying the data from the database into a display value again.

Title: Business hours in different timezones

Body:
I am trying to display a users business hours in one timezone to another timezone.

A users business hours is stored as below object for each day of the week

Timezone = Asia/Kolakata
Day number = 3 (Wednesday)
Hour = 7:00 (12 hour system)

the above is in IST

But now if i need to reteive this for a user in Australia, I can change the timezone and get the value. But this would be incorrect as a business hour available on Monday in one timezone might be valid for Tuesday in another. What is the best way to deal with this conversion?

The objects are being store and retrieved from Firestore.

Any help/guidance would be appreciated

thanks


问:
Ping a site in Python?
How do I ping a website or IP address with Python?</p>

答:
On python 3 you can use ping3.</p>
```<code>from ping3 import ping, verbose_ping
ip-host = '8.8.8.8'
if not ping(ip-host):
    raise ValueError('{} is not available.'.format(ip-host))
</code>```

Title: Ping a site in Python?

LastEditorDisplayName: xan

Body:
On python 3 you can use ping3.

from ping3 import ping, verbose_ping
ip-host = '8.8.8.8'
if not ping(ip-host):
    raise ValueError('{} is not available.'.format(ip-host))


问:
How can i convert a file .png to a Bitmap? Nothing works for me. Error "'Failed to decode image. The provided image must be a Bitmap.'" Xamarin.forms
I'm working with Xamarin in the part of  Xamarin.Forms  i need to convert a file ("image.png") to a Bitmap because when project run its enter in "break mode" and show me this message "Java.Lang.IllegalArgumentException: 'Failed to decode image. The provided image must be a Bitmap.'". So i tried to convert the file in many ways like:

1_ Using methods from System.Drawing.Bitmap but it's show this exception "This operation is not supported in this platform"

2_ Cannot use Android.Graphics because i'm working in xamarin.forms not in xamarin.android.

3_ I tried to convert the "image.png" into a base64 or byte[] array and then into a bitmap but the problem is the same like in first problem because to convert from byte[] array or base64 to a Bitmap i have use methods from System.Drawing.Bitmap.

4_ I tried using the library SkiaSharp but i don't have success because i don't found so much information  about how to convert .png to SKBitmap and then convert SKBitmap to Bitmap (even i don't know if this is possible).

5_ Finally i converted "image.png" to a "image.bmp" with an app and use the file .bmp in my project but it doesn't work too.

the "image.png" i have to save in a string variable, well that's the idea.

If you have a solution with SkiaSharp o whatever i will glad

EDIT

here is a part of my code, i just save in a variable the image

```<code>Icon = "pin_blue.png";
//i can't use a path because in xamarin you have many size from the same
//image for the different size of the screen
</code>```

EDIT 2 This is my method to show the pins in google maps

```<code>private void ShowPins(List<PointsOfInterest> resultPointsOfInterest)
        {
            if (resultPointsOfInterest != null && resultPointsOfInterest.Any())
            {
                var location = Geolocation.GetLastKnownLocationAsync();
                PointsOfInterest position = new PointsOfInterest();
                if (location != null)
                {
                    position.ccsm0166latitud = location.Result.Latitude;
                   position.ccsm0166longitud = location.Result.Longitude;

            }
            else {
                position = resultPointsOfInterest.First();
            }
            //Distance = Distance.FromKilometers(new Random().Next(23,35));
            Distance = Distance.FromKilometers(3);
            Position = new Position(position.ccsm0166latitud, position.ccsm0166longitud);
            PinsFiltered= Pins = new List<PinCustom>(resultPointsOfInterest.Select(
                x => new PinCustom()
                {
                    Position =
                        new Position(x.ccsm0166latitud, x.ccsm0166longitud),
                    Address = x.ccsm0166direccion,
                    Label = x.ccsm0166nombre,
                    Type = PinType.Place,
                    TypePointOfInterest = x.ccsm0166tipositio,
                    IconBM = Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branch ?  PinCustom.ConvertToBitmap("pin_blue.png") :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branch ? "pin_blue.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branchWithExtendedHours ? "pin_black.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branchWithExtendedHours2 ? "pin_black.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branchWithExtendedHours3 ? "pin_black.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.selfServiceTerminal ? "pin_green.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.atmServBox ? "pin_yellow.png" : string.Empty
                }).ToList());
        }
        else
        {
            Pins = new List<PinCustom>();
        }
    }
</code>```

This is the class Pin where i save the image

```<code>public class PinCustom : Pin
    {
        public string TypePointOfInterest { get; set; }
        public string Icon { get; set; }
        public Bitmap { get; set; }
        //Here  i create this variable to save a bitmap but i don't know if i do the things well
    }
</code>```

this is the icon .png i want to show in googlemaps

Pin Blue Image

答:
Use ffmpeg
command for this: ffmpeg -i image.png image.bmp</p>

Body:
I'm working with Xamarin in the part of  Xamarin.Forms  i need to convert a file ("image.png") to a Bitmap because when project run its enter in "break mode" and show me this message "Java.Lang.IllegalArgumentException: 'Failed to decode image. The provided image must be a Bitmap.'". So i tried to convert the file in many ways like:

1_ Using methods from System.Drawing.Bitmap but it's show this exception "This operation is not supported in this platform"

2_ Cannot use Android.Graphics because i'm working in xamarin.forms not in xamarin.android.

3_ I tried to convert the "image.png" into a base64 or byte[] array and then into a bitmap but the problem is the same like in first problem because to convert from byte[] array or base64 to a Bitmap i have use methods from System.Drawing.Bitmap.

4_ I tried using the library SkiaSharp but i don't have success because i don't found so much information  about how to convert .png to SKBitmap and then convert SKBitmap to Bitmap (even i don't know if this is possible).

5_ Finally i converted "image.png" to a "image.bmp" with an app and use the file .bmp in my project but it doesn't work too.

the "image.png" i have to save in a string variable, well that's the idea.

If you have a solution with SkiaSharp o whatever i will glad

EDIT

here is a part of my code, i just save in a variable the image

Icon = "pin_blue.png";
//i can't use a path because in xamarin you have many size from the same
//image for the different size of the screen

EDIT 2 This is my method to show the pins in google maps

private void ShowPins(List<PointsOfInterest> resultPointsOfInterest)
        {
            if (resultPointsOfInterest != null && resultPointsOfInterest.Any())
            {
                var location = Geolocation.GetLastKnownLocationAsync();
                PointsOfInterest position = new PointsOfInterest();
                if (location != null)
                {
                    position.ccsm0166latitud = location.Result.Latitude;
                   position.ccsm0166longitud = location.Result.Longitude;

            }
            else {
                position = resultPointsOfInterest.First();
            }
            //Distance = Distance.FromKilometers(new Random().Next(23,35));
            Distance = Distance.FromKilometers(3);
            Position = new Position(position.ccsm0166latitud, position.ccsm0166longitud);
            PinsFiltered= Pins = new List<PinCustom>(resultPointsOfInterest.Select(
                x => new PinCustom()
                {
                    Position =
                        new Position(x.ccsm0166latitud, x.ccsm0166longitud),
                    Address = x.ccsm0166direccion,
                    Label = x.ccsm0166nombre,
                    Type = PinType.Place,
                    TypePointOfInterest = x.ccsm0166tipositio,
                    IconBM = Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branch ?  PinCustom.ConvertToBitmap("pin_blue.png") :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branch ? "pin_blue.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branchWithExtendedHours ? "pin_black.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branchWithExtendedHours2 ? "pin_black.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branchWithExtendedHours3 ? "pin_black.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.selfServiceTerminal ? "pin_green.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.atmServBox ? "pin_yellow.png" : string.Empty
                }).ToList());
        }
        else
        {
            Pins = new List<PinCustom>();
        }
    }

This is the class Pin where i save the image

public class PinCustom : Pin
    {
        public string TypePointOfInterest { get; set; }
        public string Icon { get; set; }
        public Bitmap { get; set; }
        //Here  i create this variable to save a bitmap but i don't know if i do the things well
    }

this is the icon .png i want to show in googlemaps

Pin Blue Image